sqlite3.c 7.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624161625161626161627161628161629161630161631161632161633161634161635161636161637161638161639161640161641161642161643161644161645161646161647161648161649161650161651161652161653161654161655161656161657161658161659161660161661161662161663161664161665161666161667161668161669161670161671161672161673161674161675161676161677161678161679161680161681161682161683161684161685161686161687161688161689161690161691161692161693161694161695161696161697161698161699161700161701161702161703161704161705161706161707161708161709161710161711161712161713161714161715161716161717161718161719161720161721161722161723161724161725161726161727161728161729161730161731161732161733161734161735161736161737161738161739161740161741161742161743161744161745161746161747161748161749161750161751161752161753161754161755161756161757161758161759161760161761161762161763161764161765161766161767161768161769161770161771161772161773161774161775161776161777161778161779161780161781161782161783161784161785161786161787161788161789161790161791161792161793161794161795161796161797161798161799161800161801161802161803161804161805161806161807161808161809161810161811161812161813161814161815161816161817161818161819161820161821161822161823161824161825161826161827161828161829161830161831161832161833161834161835161836161837161838161839161840161841161842161843161844161845161846161847161848161849161850161851161852161853161854161855161856161857161858161859161860161861161862161863161864161865161866161867161868161869161870161871161872161873161874161875161876161877161878161879161880161881161882161883161884161885161886161887161888161889161890161891161892161893161894161895161896161897161898161899161900161901161902161903161904161905161906161907161908161909161910161911161912161913161914161915161916161917161918161919161920161921161922161923161924161925161926161927161928161929161930161931161932161933161934161935161936161937161938161939161940161941161942161943161944161945161946161947161948161949161950161951161952161953161954161955161956161957161958161959161960161961161962161963161964161965161966161967161968161969161970161971161972161973161974161975161976161977161978161979161980161981161982161983161984161985161986161987161988161989161990161991161992161993161994161995161996161997161998161999162000162001162002162003162004162005162006162007162008162009162010162011162012162013162014162015162016162017162018162019162020162021162022162023162024162025162026162027162028162029162030162031162032162033162034162035162036162037162038162039162040162041162042162043162044162045162046162047162048162049162050162051162052162053162054162055162056162057162058162059162060162061162062162063162064162065162066162067162068162069162070162071162072162073162074162075162076162077162078162079162080162081162082162083162084162085162086162087162088162089162090162091162092162093162094162095162096162097162098162099162100162101162102162103162104162105162106162107162108162109162110162111162112162113162114162115162116162117162118162119162120162121162122162123162124162125162126162127162128162129162130162131162132162133162134162135162136162137162138162139162140162141162142162143162144162145162146162147162148162149162150162151162152162153162154162155162156162157162158162159162160162161162162162163162164162165162166162167162168162169162170162171162172162173162174162175162176162177162178162179162180162181162182162183162184162185162186162187162188162189162190162191162192162193162194162195162196162197162198162199162200162201162202162203162204162205162206162207162208162209162210162211162212162213162214162215162216162217162218162219162220162221162222162223162224162225162226162227162228162229162230162231162232162233162234162235162236162237162238162239162240162241162242162243162244162245162246162247162248162249162250162251162252162253162254162255162256162257162258162259162260162261162262162263162264162265162266162267162268162269162270162271162272162273162274162275162276162277162278162279162280162281162282162283162284162285162286162287162288162289162290162291162292162293162294162295162296162297162298162299162300162301162302162303162304162305162306162307162308162309162310162311162312162313162314162315162316162317162318162319162320162321162322162323162324162325162326162327162328162329162330162331162332162333162334162335162336162337162338162339162340162341162342162343162344162345162346162347162348162349162350162351162352162353162354162355162356162357162358162359162360162361162362162363162364162365162366162367162368162369162370162371162372162373162374162375162376162377162378162379162380162381162382162383162384162385162386162387162388162389162390162391162392162393162394162395162396162397162398162399162400162401162402162403162404162405162406162407162408162409162410162411162412162413162414162415162416162417162418162419162420162421162422162423162424162425162426162427162428162429162430162431162432162433162434162435162436162437162438162439162440162441162442162443162444162445162446162447162448162449162450162451162452162453162454162455162456162457162458162459162460162461162462162463162464162465162466162467162468162469162470162471162472162473162474162475162476162477162478162479162480162481162482162483162484162485162486162487162488162489162490162491162492162493162494162495162496162497162498162499162500162501162502162503162504162505162506162507162508162509162510162511162512162513162514162515162516162517162518162519162520162521162522162523162524162525162526162527162528162529162530162531162532162533162534162535162536162537162538162539162540162541162542162543162544162545162546162547162548162549162550162551162552162553162554162555162556162557162558162559162560162561162562162563162564162565162566162567162568162569162570162571162572162573162574162575162576162577162578162579162580162581162582162583162584162585162586162587162588162589162590162591162592162593162594162595162596162597162598162599162600162601162602162603162604162605162606162607162608162609162610162611162612162613162614162615162616162617162618162619162620162621162622162623162624162625162626162627162628162629162630162631162632162633162634162635162636162637162638162639162640162641162642162643162644162645162646162647162648162649162650162651162652162653162654162655162656162657162658162659162660162661162662162663162664162665162666162667162668162669162670162671162672162673162674162675162676162677162678162679162680162681162682162683162684162685162686162687162688162689162690162691162692162693162694162695162696162697162698162699162700162701162702162703162704162705162706162707162708162709162710162711162712162713162714162715162716162717162718162719162720162721162722162723162724162725162726162727162728162729162730162731162732162733162734162735162736162737162738162739162740162741162742162743162744162745162746162747162748162749162750162751162752162753162754162755162756162757162758162759162760162761162762162763162764162765162766162767162768162769162770162771162772162773162774162775162776162777162778162779162780162781162782162783162784162785162786162787162788162789162790162791162792162793162794162795162796162797162798162799162800162801162802162803162804162805162806162807162808162809162810162811162812162813162814162815162816162817162818162819162820162821162822162823162824162825162826162827162828162829162830162831162832162833162834162835162836162837162838162839162840162841162842162843162844162845162846162847162848162849162850162851162852162853162854162855162856162857162858162859162860162861162862162863162864162865162866162867162868162869162870162871162872162873162874162875162876162877162878162879162880162881162882162883162884162885162886162887162888162889162890162891162892162893162894162895162896162897162898162899162900162901162902162903162904162905162906162907162908162909162910162911162912162913162914162915162916162917162918162919162920162921162922162923162924162925162926162927162928162929162930162931162932162933162934162935162936162937162938162939162940162941162942162943162944162945162946162947162948162949162950162951162952162953162954162955162956162957162958162959162960162961162962162963162964162965162966162967162968162969162970162971162972162973162974162975162976162977162978162979162980162981162982162983162984162985162986162987162988162989162990162991162992162993162994162995162996162997162998162999163000163001163002163003163004163005163006163007163008163009163010163011163012163013163014163015163016163017163018163019163020163021163022163023163024163025163026163027163028163029163030163031163032163033163034163035163036163037163038163039163040163041163042163043163044163045163046163047163048163049163050163051163052163053163054163055163056163057163058163059163060163061163062163063163064163065163066163067163068163069163070163071163072163073163074163075163076163077163078163079163080163081163082163083163084163085163086163087163088163089163090163091163092163093163094163095163096163097163098163099163100163101163102163103163104163105163106163107163108163109163110163111163112163113163114163115163116163117163118163119163120163121163122163123163124163125163126163127163128163129163130163131163132163133163134163135163136163137163138163139163140163141163142163143163144163145163146163147163148163149163150163151163152163153163154163155163156163157163158163159163160163161163162163163163164163165163166163167163168163169163170163171163172163173163174163175163176163177163178163179163180163181163182163183163184163185163186163187163188163189163190163191163192163193163194163195163196163197163198163199163200163201163202163203163204163205163206163207163208163209163210163211163212163213163214163215163216163217163218163219163220163221163222163223163224163225163226163227163228163229163230163231163232163233163234163235163236163237163238163239163240163241163242163243163244163245163246163247163248163249163250163251163252163253163254163255163256163257163258163259163260163261163262163263163264163265163266163267163268163269163270163271163272163273163274163275163276163277163278163279163280163281163282163283163284163285163286163287163288163289163290163291163292163293163294163295163296163297163298163299163300163301163302163303163304163305163306163307163308163309163310163311163312163313163314163315163316163317163318163319163320163321163322163323163324163325163326163327163328163329163330163331163332163333163334163335163336163337163338163339163340163341163342163343163344163345163346163347163348163349163350163351163352163353163354163355163356163357163358163359163360163361163362163363163364163365163366163367163368163369163370163371163372163373163374163375163376163377163378163379163380163381163382163383163384163385163386163387163388163389163390163391163392163393163394163395163396163397163398163399163400163401163402163403163404163405163406163407163408163409163410163411163412163413163414163415163416163417163418163419163420163421163422163423163424163425163426163427163428163429163430163431163432163433163434163435163436163437163438163439163440163441163442163443163444163445163446163447163448163449163450163451163452163453163454163455163456163457163458163459163460163461163462163463163464163465163466163467163468163469163470163471163472163473163474163475163476163477163478163479163480163481163482163483163484163485163486163487163488163489163490163491163492163493163494163495163496163497163498163499163500163501163502163503163504163505163506163507163508163509163510163511163512163513163514163515163516163517163518163519163520163521163522163523163524163525163526163527163528163529163530163531163532163533163534163535163536163537163538163539163540163541163542163543163544163545163546163547163548163549163550163551163552163553163554163555163556163557163558163559163560163561163562163563163564163565163566163567163568163569163570163571163572163573163574163575163576163577163578163579163580163581163582163583163584163585163586163587163588163589163590163591163592163593163594163595163596163597163598163599163600163601163602163603163604163605163606163607163608163609163610163611163612163613163614163615163616163617163618163619163620163621163622163623163624163625163626163627163628163629163630163631163632163633163634163635163636163637163638163639163640163641163642163643163644163645163646163647163648163649163650163651163652163653163654163655163656163657163658163659163660163661163662163663163664163665163666163667163668163669163670163671163672163673163674163675163676163677163678163679163680163681163682163683163684163685163686163687163688163689163690163691163692163693163694163695163696163697163698163699163700163701163702163703163704163705163706163707163708163709163710163711163712163713163714163715163716163717163718163719163720163721163722163723163724163725163726163727163728163729163730163731163732163733163734163735163736163737163738163739163740163741163742163743163744163745163746163747163748163749163750163751163752163753163754163755163756163757163758163759163760163761163762163763163764163765163766163767163768163769163770163771163772163773163774163775163776163777163778163779163780163781163782163783163784163785163786163787163788163789163790163791163792163793163794163795163796163797163798163799163800163801163802163803163804163805163806163807163808163809163810163811163812163813163814163815163816163817163818163819163820163821163822163823163824163825163826163827163828163829163830163831163832163833163834163835163836163837163838163839163840163841163842163843163844163845163846163847163848163849163850163851163852163853163854163855163856163857163858163859163860163861163862163863163864163865163866163867163868163869163870163871163872163873163874163875163876163877163878163879163880163881163882163883163884163885163886163887163888163889163890163891163892163893163894163895163896163897163898163899163900163901163902163903163904163905163906163907163908163909163910163911163912163913163914163915163916163917163918163919163920163921163922163923163924163925163926163927163928163929163930163931163932163933163934163935163936163937163938163939163940163941163942163943163944163945163946163947163948163949163950163951163952163953163954163955163956163957163958163959163960163961163962163963163964163965163966163967163968163969163970163971163972163973163974163975163976163977163978163979163980163981163982163983163984163985163986163987163988163989163990163991163992163993163994163995163996163997163998163999164000164001164002164003164004164005164006164007164008164009164010164011164012164013164014164015164016164017164018164019164020164021164022164023164024164025164026164027164028164029164030164031164032164033164034164035164036164037164038164039164040164041164042164043164044164045164046164047164048164049164050164051164052164053164054164055164056164057164058164059164060164061164062164063164064164065164066164067164068164069164070164071164072164073164074164075164076164077164078164079164080164081164082164083164084164085164086164087164088164089164090164091164092164093164094164095164096164097164098164099164100164101164102164103164104164105164106164107164108164109164110164111164112164113164114164115164116164117164118164119164120164121164122164123164124164125164126164127164128164129164130164131164132164133164134164135164136164137164138164139164140164141164142164143164144164145164146164147164148164149164150164151164152164153164154164155164156164157164158164159164160164161164162164163164164164165164166164167164168164169164170164171164172164173164174164175164176164177164178164179164180164181164182164183164184164185164186164187164188164189164190164191164192164193164194164195164196164197164198164199164200164201164202164203164204164205164206164207164208164209164210164211164212164213164214164215164216164217164218164219164220164221164222164223164224164225164226164227164228164229164230164231164232164233164234164235164236164237164238164239164240164241164242164243164244164245164246164247164248164249164250164251164252164253164254164255164256164257164258164259164260164261164262164263164264164265164266164267164268164269164270164271164272164273164274164275164276164277164278164279164280164281164282164283164284164285164286164287164288164289164290164291164292164293164294164295164296164297164298164299164300164301164302164303164304164305164306164307164308164309164310164311164312164313164314164315164316164317164318164319164320164321164322164323164324164325164326164327164328164329164330164331164332164333164334164335164336164337164338164339164340164341164342164343164344164345164346164347164348164349164350164351164352164353164354164355164356164357164358164359164360164361164362164363164364164365164366164367164368164369164370164371164372164373164374164375164376164377164378164379164380164381164382164383164384164385164386164387164388164389164390164391164392164393164394164395164396164397164398164399164400164401164402164403164404164405164406164407164408164409164410164411164412164413164414164415164416164417164418164419164420164421164422164423164424164425164426164427164428164429164430164431164432164433164434164435164436164437164438164439164440164441164442164443164444164445164446164447164448164449164450164451164452164453164454164455164456164457164458164459164460164461164462164463164464164465164466164467164468164469164470164471164472164473164474164475164476164477164478164479164480164481164482164483164484164485164486164487164488164489164490164491164492164493164494164495164496164497164498164499164500164501164502164503164504164505164506164507164508164509164510164511164512164513164514164515164516164517164518164519164520164521164522164523164524164525164526164527164528164529164530164531164532164533164534164535164536164537164538164539164540164541164542164543164544164545164546164547164548164549164550164551164552164553164554164555164556164557164558164559164560164561164562164563164564164565164566164567164568164569164570164571164572164573164574164575164576164577164578164579164580164581164582164583164584164585164586164587164588164589164590164591164592164593164594164595164596164597164598164599164600164601164602164603164604164605164606164607164608164609164610164611164612164613164614164615164616164617164618164619164620164621164622164623164624164625164626164627164628164629164630164631164632164633164634164635164636164637164638164639164640164641164642164643164644164645164646164647164648164649164650164651164652164653164654164655164656164657164658164659164660164661164662164663164664164665164666164667164668164669164670164671164672164673164674164675164676164677164678164679164680164681164682164683164684164685164686164687164688164689164690164691164692164693164694164695164696164697164698164699164700164701164702164703164704164705164706164707164708164709164710164711164712164713164714164715164716164717164718164719164720164721164722164723164724164725164726164727164728164729164730164731164732164733164734164735164736164737164738164739164740164741164742164743164744164745164746164747164748164749164750164751164752164753164754164755164756164757164758164759164760164761164762164763164764164765164766164767164768164769164770164771164772164773164774164775164776164777164778164779164780164781164782164783164784164785164786164787164788164789164790164791164792164793164794164795164796164797164798164799164800164801164802164803164804164805164806164807164808164809164810164811164812164813164814164815164816164817164818164819164820164821164822164823164824164825164826164827164828164829164830164831164832164833164834164835164836164837164838164839164840164841164842164843164844164845164846164847164848164849164850164851164852164853164854164855164856164857164858164859164860164861164862164863164864164865164866164867164868164869164870164871164872164873164874164875164876164877164878164879164880164881164882164883164884164885164886164887164888164889164890164891164892164893164894164895164896164897164898164899164900164901164902164903164904164905164906164907164908164909164910164911164912164913164914164915164916164917164918164919164920164921164922164923164924164925164926164927164928164929164930164931164932164933164934164935164936164937164938164939164940164941164942164943164944164945164946164947164948164949164950164951164952164953164954164955164956164957164958164959164960164961164962164963164964164965164966164967164968164969164970164971164972164973164974164975164976164977164978164979164980164981164982164983164984164985164986164987164988164989164990164991164992164993164994164995164996164997164998164999165000165001165002165003165004165005165006165007165008165009165010165011165012165013165014165015165016165017165018165019165020165021165022165023165024165025165026165027165028165029165030165031165032165033165034165035165036165037165038165039165040165041165042165043165044165045165046165047165048165049165050165051165052165053165054165055165056165057165058165059165060165061165062165063165064165065165066165067165068165069165070165071165072165073165074165075165076165077165078165079165080165081165082165083165084165085165086165087165088165089165090165091165092165093165094165095165096165097165098165099165100165101165102165103165104165105165106165107165108165109165110165111165112165113165114165115165116165117165118165119165120165121165122165123165124165125165126165127165128165129165130165131165132165133165134165135165136165137165138165139165140165141165142165143165144165145165146165147165148165149165150165151165152165153165154165155165156165157165158165159165160165161165162165163165164165165165166165167165168165169165170165171165172165173165174165175165176165177165178165179165180165181165182165183165184165185165186165187165188165189165190165191165192165193165194165195165196165197165198165199165200165201165202165203165204165205165206165207165208165209165210165211165212165213165214165215165216165217165218165219165220165221165222165223165224165225165226165227165228165229165230165231165232165233165234165235165236165237165238165239165240165241165242165243165244165245165246165247165248165249165250165251165252165253165254165255165256165257165258165259165260165261165262165263165264165265165266165267165268165269165270165271165272165273165274165275165276165277165278165279165280165281165282165283165284165285165286165287165288165289165290165291165292165293165294165295165296165297165298165299165300165301165302165303165304165305165306165307165308165309165310165311165312165313165314165315165316165317165318165319165320165321165322165323165324165325165326165327165328165329165330165331165332165333165334165335165336165337165338165339165340165341165342165343165344165345165346165347165348165349165350165351165352165353165354165355165356165357165358165359165360165361165362165363165364165365165366165367165368165369165370165371165372165373165374165375165376165377165378165379165380165381165382165383165384165385165386165387165388165389165390165391165392165393165394165395165396165397165398165399165400165401165402165403165404165405165406165407165408165409165410165411165412165413165414165415165416165417165418165419165420165421165422165423165424165425165426165427165428165429165430165431165432165433165434165435165436165437165438165439165440165441165442165443165444165445165446165447165448165449165450165451165452165453165454165455165456165457165458165459165460165461165462165463165464165465165466165467165468165469165470165471165472165473165474165475165476165477165478165479165480165481165482165483165484165485165486165487165488165489165490165491165492165493165494165495165496165497165498165499165500165501165502165503165504165505165506165507165508165509165510165511165512165513165514165515165516165517165518165519165520165521165522165523165524165525165526165527165528165529165530165531165532165533165534165535165536165537165538165539165540165541165542165543165544165545165546165547165548165549165550165551165552165553165554165555165556165557165558165559165560165561165562165563165564165565165566165567165568165569165570165571165572165573165574165575165576165577165578165579165580165581165582165583165584165585165586165587165588165589165590165591165592165593165594165595165596165597165598165599165600165601165602165603165604165605165606165607165608165609165610165611165612165613165614165615165616165617165618165619165620165621165622165623165624165625165626165627165628165629165630165631165632165633165634165635165636165637165638165639165640165641165642165643165644165645165646165647165648165649165650165651165652165653165654165655165656165657165658165659165660165661165662165663165664165665165666165667165668165669165670165671165672165673165674165675165676165677165678165679165680165681165682165683165684165685165686165687165688165689165690165691165692165693165694165695165696165697165698165699165700165701165702165703165704165705165706165707165708165709165710165711165712165713165714165715165716165717165718165719165720165721165722165723165724165725165726165727165728165729165730165731165732165733165734165735165736165737165738165739165740165741165742165743165744165745165746165747165748165749165750165751165752165753165754165755165756165757165758165759165760165761165762165763165764165765165766165767165768165769165770165771165772165773165774165775165776165777165778165779165780165781165782165783165784165785165786165787165788165789165790165791165792165793165794165795165796165797165798165799165800165801165802165803165804165805165806165807165808165809165810165811165812165813165814165815165816165817165818165819165820165821165822165823165824165825165826165827165828165829165830165831165832165833165834165835165836165837165838165839165840165841165842165843165844165845165846165847165848165849165850165851165852165853165854165855165856165857165858165859165860165861165862165863165864165865165866165867165868165869165870165871165872165873165874165875165876165877165878165879165880165881165882165883165884165885165886165887165888165889165890165891165892165893165894165895165896165897165898165899165900165901165902165903165904165905165906165907165908165909165910165911165912165913165914165915165916165917165918165919165920165921165922165923165924165925165926165927165928165929165930165931165932165933165934165935165936165937165938165939165940165941165942165943165944165945165946165947165948165949165950165951165952165953165954165955165956165957165958165959165960165961165962165963165964165965165966165967165968165969165970165971165972165973165974165975165976165977165978165979165980165981165982165983165984165985165986165987165988165989165990165991165992165993165994165995165996165997165998165999166000166001166002166003166004166005166006166007166008166009166010166011166012166013166014166015166016166017166018166019166020166021166022166023166024166025166026166027166028166029166030166031166032166033166034166035166036166037166038166039166040166041166042166043166044166045166046166047166048166049166050166051166052166053166054166055166056166057166058166059166060166061166062166063166064166065166066166067166068166069166070166071166072166073166074166075166076166077166078166079166080166081166082166083166084166085166086166087166088166089166090166091166092166093166094166095166096166097166098166099166100166101166102166103166104166105166106166107166108166109166110166111166112166113166114166115166116166117166118166119166120166121166122166123166124166125166126166127166128166129166130166131166132166133166134166135166136166137166138166139166140166141166142166143166144166145166146166147166148166149166150166151166152166153166154166155166156166157166158166159166160166161166162166163166164166165166166166167166168166169166170166171166172166173166174166175166176166177166178166179166180166181166182166183166184166185166186166187166188166189166190166191166192166193166194166195166196166197166198166199166200166201166202166203166204166205166206166207166208166209166210166211166212166213166214166215166216166217166218166219166220166221166222166223166224166225166226166227166228166229166230166231166232166233166234166235166236166237166238166239166240166241166242166243166244166245166246166247166248166249166250166251166252166253166254166255166256166257166258166259166260166261166262166263166264166265166266166267166268166269166270166271166272166273166274166275166276166277166278166279166280166281166282166283166284166285166286166287166288166289166290166291166292166293166294166295166296166297166298166299166300166301166302166303166304166305166306166307166308166309166310166311166312166313166314166315166316166317166318166319166320166321166322166323166324166325166326166327166328166329166330166331166332166333166334166335166336166337166338166339166340166341166342166343166344166345166346166347166348166349166350166351166352166353166354166355166356166357166358166359166360166361166362166363166364166365166366166367166368166369166370166371166372166373166374166375166376166377166378166379166380166381166382166383166384166385166386166387166388166389166390166391166392166393166394166395166396166397166398166399166400166401166402166403166404166405166406166407166408166409166410166411166412166413166414166415166416166417166418166419166420166421166422166423166424166425166426166427166428166429166430166431166432166433166434166435166436166437166438166439166440166441166442166443166444166445166446166447166448166449166450166451166452166453166454166455166456166457166458166459166460166461166462166463166464166465166466166467166468166469166470166471166472166473166474166475166476166477166478166479166480166481166482166483166484166485166486166487166488166489166490166491166492166493166494166495166496166497166498166499166500166501166502166503166504166505166506166507166508166509166510166511166512166513166514166515166516166517166518166519166520166521166522166523166524166525166526166527166528166529166530166531166532166533166534166535166536166537166538166539166540166541166542166543166544166545166546166547166548166549166550166551166552166553166554166555166556166557166558166559166560166561166562166563166564166565166566166567166568166569166570166571166572166573166574166575166576166577166578166579166580166581166582166583166584166585166586166587166588166589166590166591166592166593166594166595166596166597166598166599166600166601166602166603166604166605166606166607166608166609166610166611166612166613166614166615166616166617166618166619166620166621166622166623166624166625166626166627166628166629166630166631166632166633166634166635166636166637166638166639166640166641166642166643166644166645166646166647166648166649166650166651166652166653166654166655166656166657166658166659166660166661166662166663166664166665166666166667166668166669166670166671166672166673166674166675166676166677166678166679166680166681166682166683166684166685166686166687166688166689166690166691166692166693166694166695166696166697166698166699166700166701166702166703166704166705166706166707166708166709166710166711166712166713166714166715166716166717166718166719166720166721166722166723166724166725166726166727166728166729166730166731166732166733166734166735166736166737166738166739166740166741166742166743166744166745166746166747166748166749166750166751166752166753166754166755166756166757166758166759166760166761166762166763166764166765166766166767166768166769166770166771166772166773166774166775166776166777166778166779166780166781166782166783166784166785166786166787166788166789166790166791166792166793166794166795166796166797166798166799166800166801166802166803166804166805166806166807166808166809166810166811166812166813166814166815166816166817166818166819166820166821166822166823166824166825166826166827166828166829166830166831166832166833166834166835166836166837166838166839166840166841166842166843166844166845166846166847166848166849166850166851166852166853166854166855166856166857166858166859166860166861166862166863166864166865166866166867166868166869166870166871166872166873166874166875166876166877166878166879166880166881166882166883166884166885166886166887166888166889166890166891166892166893166894166895166896166897166898166899166900166901166902166903166904166905166906166907166908166909166910166911166912166913166914166915166916166917166918166919166920166921166922166923166924166925166926166927166928166929166930166931166932166933166934166935166936166937166938166939166940166941166942166943166944166945166946166947166948166949166950166951166952166953166954166955166956166957166958166959166960166961166962166963166964166965166966166967166968166969166970166971166972166973166974166975166976166977166978166979166980166981166982166983166984166985166986166987166988166989166990166991166992166993166994166995166996166997166998166999167000167001167002167003167004167005167006167007167008167009167010167011167012167013167014167015167016167017167018167019167020167021167022167023167024167025167026167027167028167029167030167031167032167033167034167035167036167037167038167039167040167041167042167043167044167045167046167047167048167049167050167051167052167053167054167055167056167057167058167059167060167061167062167063167064167065167066167067167068167069167070167071167072167073167074167075167076167077167078167079167080167081167082167083167084167085167086167087167088167089167090167091167092167093167094167095167096167097167098167099167100167101167102167103167104167105167106167107167108167109167110167111167112167113167114167115167116167117167118167119167120167121167122167123167124167125167126167127167128167129167130167131167132167133167134167135167136167137167138167139167140167141167142167143167144167145167146167147167148167149167150167151167152167153167154167155167156167157167158167159167160167161167162167163167164167165167166167167167168167169167170167171167172167173167174167175167176167177167178167179167180167181167182167183167184167185167186167187167188167189167190167191167192167193167194167195167196167197167198167199167200167201167202167203167204167205167206167207167208167209167210167211167212167213167214167215167216167217167218167219167220167221167222167223167224167225167226167227167228167229167230167231167232167233167234167235167236167237167238167239167240167241167242167243167244167245167246167247167248167249167250167251167252167253167254167255167256167257167258167259167260167261167262167263167264167265167266167267167268167269167270167271167272167273167274167275167276167277167278167279167280167281167282167283167284167285167286167287167288167289167290167291167292167293167294167295167296167297167298167299167300167301167302167303167304167305167306167307167308167309167310167311167312167313167314167315167316167317167318167319167320167321167322167323167324167325167326167327167328167329167330167331167332167333167334167335167336167337167338167339167340167341167342167343167344167345167346167347167348167349167350167351167352167353167354167355167356167357167358167359167360167361167362167363167364167365167366167367167368167369167370167371167372167373167374167375167376167377167378167379167380167381167382167383167384167385167386167387167388167389167390167391167392167393167394167395167396167397167398167399167400167401167402167403167404167405167406167407167408167409167410167411167412167413167414167415167416167417167418167419167420167421167422167423167424167425167426167427167428167429167430167431167432167433167434167435167436167437167438167439167440167441167442167443167444167445167446167447167448167449167450167451167452167453167454167455167456167457167458167459167460167461167462167463167464167465167466167467167468167469167470167471167472167473167474167475167476167477167478167479167480167481167482167483167484167485167486167487167488167489167490167491167492167493167494167495167496167497167498167499167500167501167502167503167504167505167506167507167508167509167510167511167512167513167514167515167516167517167518167519167520167521167522167523167524167525167526167527167528167529167530167531167532167533167534167535167536167537167538167539167540167541167542167543167544167545167546167547167548167549167550167551167552167553167554167555167556167557167558167559167560167561167562167563167564167565167566167567167568167569167570167571167572167573167574167575167576167577167578167579167580167581167582167583167584167585167586167587167588167589167590167591167592167593167594167595167596167597167598167599167600167601167602167603167604167605167606167607167608167609167610167611167612167613167614167615167616167617167618167619167620167621167622167623167624167625167626167627167628167629167630167631167632167633167634167635167636167637167638167639167640167641167642167643167644167645167646167647167648167649167650167651167652167653167654167655167656167657167658167659167660167661167662167663167664167665167666167667167668167669167670167671167672167673167674167675167676167677167678167679167680167681167682167683167684167685167686167687167688167689167690167691167692167693167694167695167696167697167698167699167700167701167702167703167704167705167706167707167708167709167710167711167712167713167714167715167716167717167718167719167720167721167722167723167724167725167726167727167728167729167730167731167732167733167734167735167736167737167738167739167740167741167742167743167744167745167746167747167748167749167750167751167752167753167754167755167756167757167758167759167760167761167762167763167764167765167766167767167768167769167770167771167772167773167774167775167776167777167778167779167780167781167782167783167784167785167786167787167788167789167790167791167792167793167794167795167796167797167798167799167800167801167802167803167804167805167806167807167808167809167810167811167812167813167814167815167816167817167818167819167820167821167822167823167824167825167826167827167828167829167830167831167832167833167834167835167836167837167838167839167840167841167842167843167844167845167846167847167848167849167850167851167852167853167854167855167856167857167858167859167860167861167862167863167864167865167866167867167868167869167870167871167872167873167874167875167876167877167878167879167880167881167882167883167884167885167886167887167888167889167890167891167892167893167894167895167896167897167898167899167900167901167902167903167904167905167906167907167908167909167910167911167912167913167914167915167916167917167918167919167920167921167922167923167924167925167926167927167928167929167930167931167932167933167934167935167936167937167938167939167940167941167942167943167944167945167946167947167948167949167950167951167952167953167954167955167956167957167958167959167960167961167962167963167964167965167966167967167968167969167970167971167972167973167974167975167976167977167978167979167980167981167982167983167984167985167986167987167988167989167990167991167992167993167994167995167996167997167998167999168000168001168002168003168004168005168006168007168008168009168010168011168012168013168014168015168016168017168018168019168020168021168022168023168024168025168026168027168028168029168030168031168032168033168034168035168036168037168038168039168040168041168042168043168044168045168046168047168048168049168050168051168052168053168054168055168056168057168058168059168060168061168062168063168064168065168066168067168068168069168070168071168072168073168074168075168076168077168078168079168080168081168082168083168084168085168086168087168088168089168090168091168092168093168094168095168096168097168098168099168100168101168102168103168104168105168106168107168108168109168110168111168112168113168114168115168116168117168118168119168120168121168122168123168124168125168126168127168128168129168130168131168132168133168134168135168136168137168138168139168140168141168142168143168144168145168146168147168148168149168150168151168152168153168154168155168156168157168158168159168160168161168162168163168164168165168166168167168168168169168170168171168172168173168174168175168176168177168178168179168180168181168182168183168184168185168186168187168188168189168190168191168192168193168194168195168196168197168198168199168200168201168202168203168204168205168206168207168208168209168210168211168212168213168214168215168216168217168218168219168220168221168222168223168224168225168226168227168228168229168230168231168232168233168234168235168236168237168238168239168240168241168242168243168244168245168246168247168248168249168250168251168252168253168254168255168256168257168258168259168260168261168262168263168264168265168266168267168268168269168270168271168272168273168274168275168276168277168278168279168280168281168282168283168284168285168286168287168288168289168290168291168292168293168294168295168296168297168298168299168300168301168302168303168304168305168306168307168308168309168310168311168312168313168314168315168316168317168318168319168320168321168322168323168324168325168326168327168328168329168330168331168332168333168334168335168336168337168338168339168340168341168342168343168344168345168346168347168348168349168350168351168352168353168354168355168356168357168358168359168360168361168362168363168364168365168366168367168368168369168370168371168372168373168374168375168376168377168378168379168380168381168382168383168384168385168386168387168388168389168390168391168392168393168394168395168396168397168398168399168400168401168402168403168404168405168406168407168408168409168410168411168412168413168414168415168416168417168418168419168420168421168422168423168424168425168426168427168428168429168430168431168432168433168434168435168436168437168438168439168440168441168442168443168444168445168446168447168448168449168450168451168452168453168454168455168456168457168458168459168460168461168462168463168464168465168466168467168468168469168470168471168472168473168474168475168476168477168478168479168480168481168482168483168484168485168486168487168488168489168490168491168492168493168494168495168496168497168498168499168500168501168502168503168504168505168506168507168508168509168510168511168512168513168514168515168516168517168518168519168520168521168522168523168524168525168526168527168528168529168530168531168532168533168534168535168536168537168538168539168540168541168542168543168544168545168546168547168548168549168550168551168552168553168554168555168556168557168558168559168560168561168562168563168564168565168566168567168568168569168570168571168572168573168574168575168576168577168578168579168580168581168582168583168584168585168586168587168588168589168590168591168592168593168594168595168596168597168598168599168600168601168602168603168604168605168606168607168608168609168610168611168612168613168614168615168616168617168618168619168620168621168622168623168624168625168626168627168628168629168630168631168632168633168634168635168636168637168638168639168640168641168642168643168644168645168646168647168648168649168650168651168652168653168654168655168656168657168658168659168660168661168662168663168664168665168666168667168668168669168670168671168672168673168674168675168676168677168678168679168680168681168682168683168684168685168686168687168688168689168690168691168692168693168694168695168696168697168698168699168700168701168702168703168704168705168706168707168708168709168710168711168712168713168714168715168716168717168718168719168720168721168722168723168724168725168726168727168728168729168730168731168732168733168734168735168736168737168738168739168740168741168742168743168744168745168746168747168748168749168750168751168752168753168754168755168756168757168758168759168760168761168762168763168764168765168766168767168768168769168770168771168772168773168774168775168776168777168778168779168780168781168782168783168784168785168786168787168788168789168790168791168792168793168794168795168796168797168798168799168800168801168802168803168804168805168806168807168808168809168810168811168812168813168814168815168816168817168818168819168820168821168822168823168824168825168826168827168828168829168830168831168832168833168834168835168836168837168838168839168840168841168842168843168844168845168846168847168848168849168850168851168852168853168854168855168856168857168858168859168860168861168862168863168864168865168866168867168868168869168870168871168872168873168874168875168876168877168878168879168880168881168882168883168884168885168886168887168888168889168890168891168892168893168894168895168896168897168898168899168900168901168902168903168904168905168906168907168908168909168910168911168912168913168914168915168916168917168918168919168920168921168922168923168924168925168926168927168928168929168930168931168932168933168934168935168936168937168938168939168940168941168942168943168944168945168946168947168948168949168950168951168952168953168954168955168956168957168958168959168960168961168962168963168964168965168966168967168968168969168970168971168972168973168974168975168976168977168978168979168980168981168982168983168984168985168986168987168988168989168990168991168992168993168994168995168996168997168998168999169000169001169002169003169004169005169006169007169008169009169010169011169012169013169014169015169016169017169018169019169020169021169022169023169024169025169026169027169028169029169030169031169032169033169034169035169036169037169038169039169040169041169042169043169044169045169046169047169048169049169050169051169052169053169054169055169056169057169058169059169060169061169062169063169064169065169066169067169068169069169070169071169072169073169074169075169076169077169078169079169080169081169082169083169084169085169086169087169088169089169090169091169092169093169094169095169096169097169098169099169100169101169102169103169104169105169106169107169108169109169110169111169112169113169114169115169116169117169118169119169120169121169122169123169124169125169126169127169128169129169130169131169132169133169134169135169136169137169138169139169140169141169142169143169144169145169146169147169148169149169150169151169152169153169154169155169156169157169158169159169160169161169162169163169164169165169166169167169168169169169170169171169172169173169174169175169176169177169178169179169180169181169182169183169184169185169186169187169188169189169190169191169192169193169194169195169196169197169198169199169200169201169202169203169204169205169206169207169208169209169210169211169212169213169214169215169216169217169218169219169220169221169222169223169224169225169226169227169228169229169230169231169232169233169234169235169236169237169238169239169240169241169242169243169244169245169246169247169248169249169250169251169252169253169254169255169256169257169258169259169260169261169262169263169264169265169266169267169268169269169270169271169272169273169274169275169276169277169278169279169280169281169282169283169284169285169286169287169288169289169290169291169292169293169294169295169296169297169298169299169300169301169302169303169304169305169306169307169308169309169310169311169312169313169314169315169316169317169318169319169320169321169322169323169324169325169326169327169328169329169330169331169332169333169334169335169336169337169338169339169340169341169342169343169344169345169346169347169348169349169350169351169352169353169354169355169356169357169358169359169360169361169362169363169364169365169366169367169368169369169370169371169372169373169374169375169376169377169378169379169380169381169382169383169384169385169386169387169388169389169390169391169392169393169394169395169396169397169398169399169400169401169402169403169404169405169406169407169408169409169410169411169412169413169414169415169416169417169418169419169420169421169422169423169424169425169426169427169428169429169430169431169432169433169434169435169436169437169438169439169440169441169442169443169444169445169446169447169448169449169450169451169452169453169454169455169456169457169458169459169460169461169462169463169464169465169466169467169468169469169470169471169472169473169474169475169476169477169478169479169480169481169482169483169484169485169486169487169488169489169490169491169492169493169494169495169496169497169498169499169500169501169502169503169504169505169506169507169508169509169510169511169512169513169514169515169516169517169518169519169520169521169522169523169524169525169526169527169528169529169530169531169532169533169534169535169536169537169538169539169540169541169542169543169544169545169546169547169548169549169550169551169552169553169554169555169556169557169558169559169560169561169562169563169564169565169566169567169568169569169570169571169572169573169574169575169576169577169578169579169580169581169582169583169584169585169586169587169588169589169590169591169592169593169594169595169596169597169598169599169600169601169602169603169604169605169606169607169608169609169610169611169612169613169614169615169616169617169618169619169620169621169622169623169624169625169626169627169628169629169630169631169632169633169634169635169636169637169638169639169640169641169642169643169644169645169646169647169648169649169650169651169652169653169654169655169656169657169658169659169660169661169662169663169664169665169666169667169668169669169670169671169672169673169674169675169676169677169678169679169680169681169682169683169684169685169686169687169688169689169690169691169692169693169694169695169696169697169698169699169700169701169702169703169704169705169706169707169708169709169710169711169712169713169714169715169716169717169718169719169720169721169722169723169724169725169726169727169728169729169730169731169732169733169734169735169736169737169738169739169740169741169742169743169744169745169746169747169748169749169750169751169752169753169754169755169756169757169758169759169760169761169762169763169764169765169766169767169768169769169770169771169772169773169774169775169776169777169778169779169780169781169782169783169784169785169786169787169788169789169790169791169792169793169794169795169796169797169798169799169800169801169802169803169804169805169806169807169808169809169810169811169812169813169814169815169816169817169818169819169820169821169822169823169824169825169826169827169828169829169830169831169832169833169834169835169836169837169838169839169840169841169842169843169844169845169846169847169848169849169850169851169852169853169854169855169856169857169858169859169860169861169862169863169864169865169866169867169868169869169870169871169872169873169874169875169876169877169878169879169880169881169882169883169884169885169886169887169888169889169890169891169892169893169894169895169896169897169898169899169900169901169902169903169904169905169906169907169908169909169910169911169912169913169914169915169916169917169918169919169920169921169922169923169924169925169926169927169928169929169930169931169932169933169934169935169936169937169938169939169940169941169942169943169944169945169946169947169948169949169950169951169952169953169954169955169956169957169958169959169960169961169962169963169964169965169966169967169968169969169970169971169972169973169974169975169976169977169978169979169980169981169982169983169984169985169986169987169988169989169990169991169992169993169994169995169996169997169998169999170000170001170002170003170004170005170006170007170008170009170010170011170012170013170014170015170016170017170018170019170020170021170022170023170024170025170026170027170028170029170030170031170032170033170034170035170036170037170038170039170040170041170042170043170044170045170046170047170048170049170050170051170052170053170054170055170056170057170058170059170060170061170062170063170064170065170066170067170068170069170070170071170072170073170074170075170076170077170078170079170080170081170082170083170084170085170086170087170088170089170090170091170092170093170094170095170096170097170098170099170100170101170102170103170104170105170106170107170108170109170110170111170112170113170114170115170116170117170118170119170120170121170122170123170124170125170126170127170128170129170130170131170132170133170134170135170136170137170138170139170140170141170142170143170144170145170146170147170148170149170150170151170152170153170154170155170156170157170158170159170160170161170162170163170164170165170166170167170168170169170170170171170172170173170174170175170176170177170178170179170180170181170182170183170184170185170186170187170188170189170190170191170192170193170194170195170196170197170198170199170200170201170202170203170204170205170206170207170208170209170210170211170212170213170214170215170216170217170218170219170220170221170222170223170224170225170226170227170228170229170230170231170232170233170234170235170236170237170238170239170240170241170242170243170244170245170246170247170248170249170250170251170252170253170254170255170256170257170258170259170260170261170262170263170264170265170266170267170268170269170270170271170272170273170274170275170276170277170278170279170280170281170282170283170284170285170286170287170288170289170290170291170292170293170294170295170296170297170298170299170300170301170302170303170304170305170306170307170308170309170310170311170312170313170314170315170316170317170318170319170320170321170322170323170324170325170326170327170328170329170330170331170332170333170334170335170336170337170338170339170340170341170342170343170344170345170346170347170348170349170350170351170352170353170354170355170356170357170358170359170360170361170362170363170364170365170366170367170368170369170370170371170372170373170374170375170376170377170378170379170380170381170382170383170384170385170386170387170388170389170390170391170392170393170394170395170396170397170398170399170400170401170402170403170404170405170406170407170408170409170410170411170412170413170414170415170416170417170418170419170420170421170422170423170424170425170426170427170428170429170430170431170432170433170434170435170436170437170438170439170440170441170442170443170444170445170446170447170448170449170450170451170452170453170454170455170456170457170458170459170460170461170462170463170464170465170466170467170468170469170470170471170472170473170474170475170476170477170478170479170480170481170482170483170484170485170486170487170488170489170490170491170492170493170494170495170496170497170498170499170500170501170502170503170504170505170506170507170508170509170510170511170512170513170514170515170516170517170518170519170520170521170522170523170524170525170526170527170528170529170530170531170532170533170534170535170536170537170538170539170540170541170542170543170544170545170546170547170548170549170550170551170552170553170554170555170556170557170558170559170560170561170562170563170564170565170566170567170568170569170570170571170572170573170574170575170576170577170578170579170580170581170582170583170584170585170586170587170588170589170590170591170592170593170594170595170596170597170598170599170600170601170602170603170604170605170606170607170608170609170610170611170612170613170614170615170616170617170618170619170620170621170622170623170624170625170626170627170628170629170630170631170632170633170634170635170636170637170638170639170640170641170642170643170644170645170646170647170648170649170650170651170652170653170654170655170656170657170658170659170660170661170662170663170664170665170666170667170668170669170670170671170672170673170674170675170676170677170678170679170680170681170682170683170684170685170686170687170688170689170690170691170692170693170694170695170696170697170698170699170700170701170702170703170704170705170706170707170708170709170710170711170712170713170714170715170716170717170718170719170720170721170722170723170724170725170726170727170728170729170730170731170732170733170734170735170736170737170738170739170740170741170742170743170744170745170746170747170748170749170750170751170752170753170754170755170756170757170758170759170760170761170762170763170764170765170766170767170768170769170770170771170772170773170774170775170776170777170778170779170780170781170782170783170784170785170786170787170788170789170790170791170792170793170794170795170796170797170798170799170800170801170802170803170804170805170806170807170808170809170810170811170812170813170814170815170816170817170818170819170820170821170822170823170824170825170826170827170828170829170830170831170832170833170834170835170836170837170838170839170840170841170842170843170844170845170846170847170848170849170850170851170852170853170854170855170856170857170858170859170860170861170862170863170864170865170866170867170868170869170870170871170872170873170874170875170876170877170878170879170880170881170882170883170884170885170886170887170888170889170890170891170892170893170894170895170896170897170898170899170900170901170902170903170904170905170906170907170908170909170910170911170912170913170914170915170916170917170918170919170920170921170922170923170924170925170926170927170928170929170930170931170932170933170934170935170936170937170938170939170940170941170942170943170944170945170946170947170948170949170950170951170952170953170954170955170956170957170958170959170960170961170962170963170964170965170966170967170968170969170970170971170972170973170974170975170976170977170978170979170980170981170982170983170984170985170986170987170988170989170990170991170992170993170994170995170996170997170998170999171000171001171002171003171004171005171006171007171008171009171010171011171012171013171014171015171016171017171018171019171020171021171022171023171024171025171026171027171028171029171030171031171032171033171034171035171036171037171038171039171040171041171042171043171044171045171046171047171048171049171050171051171052171053171054171055171056171057171058171059171060171061171062171063171064171065171066171067171068171069171070171071171072171073171074171075171076171077171078171079171080171081171082171083171084171085171086171087171088171089171090171091171092171093171094171095171096171097171098171099171100171101171102171103171104171105171106171107171108171109171110171111171112171113171114171115171116171117171118171119171120171121171122171123171124171125171126171127171128171129171130171131171132171133171134171135171136171137171138171139171140171141171142171143171144171145171146171147171148171149171150171151171152171153171154171155171156171157171158171159171160171161171162171163171164171165171166171167171168171169171170171171171172171173171174171175171176171177171178171179171180171181171182171183171184171185171186171187171188171189171190171191171192171193171194171195171196171197171198171199171200171201171202171203171204171205171206171207171208171209171210171211171212171213171214171215171216171217171218171219171220171221171222171223171224171225171226171227171228171229171230171231171232171233171234171235171236171237171238171239171240171241171242171243171244171245171246171247171248171249171250171251171252171253171254171255171256171257171258171259171260171261171262171263171264171265171266171267171268171269171270171271171272171273171274171275171276171277171278171279171280171281171282171283171284171285171286171287171288171289171290171291171292171293171294171295171296171297171298171299171300171301171302171303171304171305171306171307171308171309171310171311171312171313171314171315171316171317171318171319171320171321171322171323171324171325171326171327171328171329171330171331171332171333171334171335171336171337171338171339171340171341171342171343171344171345171346171347171348171349171350171351171352171353171354171355171356171357171358171359171360171361171362171363171364171365171366171367171368171369171370171371171372171373171374171375171376171377171378171379171380171381171382171383171384171385171386171387171388171389171390171391171392171393171394171395171396171397171398171399171400171401171402171403171404171405171406171407171408171409171410171411171412171413171414171415171416171417171418171419171420171421171422171423171424171425171426171427171428171429171430171431171432171433171434171435171436171437171438171439171440171441171442171443171444171445171446171447171448171449171450171451171452171453171454171455171456171457171458171459171460171461171462171463171464171465171466171467171468171469171470171471171472171473171474171475171476171477171478171479171480171481171482171483171484171485171486171487171488171489171490171491171492171493171494171495171496171497171498171499171500171501171502171503171504171505171506171507171508171509171510171511171512171513171514171515171516171517171518171519171520171521171522171523171524171525171526171527171528171529171530171531171532171533171534171535171536171537171538171539171540171541171542171543171544171545171546171547171548171549171550171551171552171553171554171555171556171557171558171559171560171561171562171563171564171565171566171567171568171569171570171571171572171573171574171575171576171577171578171579171580171581171582171583171584171585171586171587171588171589171590171591171592171593171594171595171596171597171598171599171600171601171602171603171604171605171606171607171608171609171610171611171612171613171614171615171616171617171618171619171620171621171622171623171624171625171626171627171628171629171630171631171632171633171634171635171636171637171638171639171640171641171642171643171644171645171646171647171648171649171650171651171652171653171654171655171656171657171658171659171660171661171662171663171664171665171666171667171668171669171670171671171672171673171674171675171676171677171678171679171680171681171682171683171684171685171686171687171688171689171690171691171692171693171694171695171696171697171698171699171700171701171702171703171704171705171706171707171708171709171710171711171712171713171714171715171716171717171718171719171720171721171722171723171724171725171726171727171728171729171730171731171732171733171734171735171736171737171738171739171740171741171742171743171744171745171746171747171748171749171750171751171752171753171754171755171756171757171758171759171760171761171762171763171764171765171766171767171768171769171770171771171772171773171774171775171776171777171778171779171780171781171782171783171784171785171786171787171788171789171790171791171792171793171794171795171796171797171798171799171800171801171802171803171804171805171806171807171808171809171810171811171812171813171814171815171816171817171818171819171820171821171822171823171824171825171826171827171828171829171830171831171832171833171834171835171836171837171838171839171840171841171842171843171844171845171846171847171848171849171850171851171852171853171854171855171856171857171858171859171860171861171862171863171864171865171866171867171868171869171870171871171872171873171874171875171876171877171878171879171880171881171882171883171884171885171886171887171888171889171890171891171892171893171894171895171896171897171898171899171900171901171902171903171904171905171906171907171908171909171910171911171912171913171914171915171916171917171918171919171920171921171922171923171924171925171926171927171928171929171930171931171932171933171934171935171936171937171938171939171940171941171942171943171944171945171946171947171948171949171950171951171952171953171954171955171956171957171958171959171960171961171962171963171964171965171966171967171968171969171970171971171972171973171974171975171976171977171978171979171980171981171982171983171984171985171986171987171988171989171990171991171992171993171994171995171996171997171998171999172000172001172002172003172004172005172006172007172008172009172010172011172012172013172014172015172016172017172018172019172020172021172022172023172024172025172026172027172028172029172030172031172032172033172034172035172036172037172038172039172040172041172042172043172044172045172046172047172048172049172050172051172052172053172054172055172056172057172058172059172060172061172062172063172064172065172066172067172068172069172070172071172072172073172074172075172076172077172078172079172080172081172082172083172084172085172086172087172088172089172090172091172092172093172094172095172096172097172098172099172100172101172102172103172104172105172106172107172108172109172110172111172112172113172114172115172116172117172118172119172120172121172122172123172124172125172126172127172128172129172130172131172132172133172134172135172136172137172138172139172140172141172142172143172144172145172146172147172148172149172150172151172152172153172154172155172156172157172158172159172160172161172162172163172164172165172166172167172168172169172170172171172172172173172174172175172176172177172178172179172180172181172182172183172184172185172186172187172188172189172190172191172192172193172194172195172196172197172198172199172200172201172202172203172204172205172206172207172208172209172210172211172212172213172214172215172216172217172218172219172220172221172222172223172224172225172226172227172228172229172230172231172232172233172234172235172236172237172238172239172240172241172242172243172244172245172246172247172248172249172250172251172252172253172254172255172256172257172258172259172260172261172262172263172264172265172266172267172268172269172270172271172272172273172274172275172276172277172278172279172280172281172282172283172284172285172286172287172288172289172290172291172292172293172294172295172296172297172298172299172300172301172302172303172304172305172306172307172308172309172310172311172312172313172314172315172316172317172318172319172320172321172322172323172324172325172326172327172328172329172330172331172332172333172334172335172336172337172338172339172340172341172342172343172344172345172346172347172348172349172350172351172352172353172354172355172356172357172358172359172360172361172362172363172364172365172366172367172368172369172370172371172372172373172374172375172376172377172378172379172380172381172382172383172384172385172386172387172388172389172390172391172392172393172394172395172396172397172398172399172400172401172402172403172404172405172406172407172408172409172410172411172412172413172414172415172416172417172418172419172420172421172422172423172424172425172426172427172428172429172430172431172432172433172434172435172436172437172438172439172440172441172442172443172444172445172446172447172448172449172450172451172452172453172454172455172456172457172458172459172460172461172462172463172464172465172466172467172468172469172470172471172472172473172474172475172476172477172478172479172480172481172482172483172484172485172486172487172488172489172490172491172492172493172494172495172496172497172498172499172500172501172502172503172504172505172506172507172508172509172510172511172512172513172514172515172516172517172518172519172520172521172522172523172524172525172526172527172528172529172530172531172532172533172534172535172536172537172538172539172540172541172542172543172544172545172546172547172548172549172550172551172552172553172554172555172556172557172558172559172560172561172562172563172564172565172566172567172568172569172570172571172572172573172574172575172576172577172578172579172580172581172582172583172584172585172586172587172588172589172590172591172592172593172594172595172596172597172598172599172600172601172602172603172604172605172606172607172608172609172610172611172612172613172614172615172616172617172618172619172620172621172622172623172624172625172626172627172628172629172630172631172632172633172634172635172636172637172638172639172640172641172642172643172644172645172646172647172648172649172650172651172652172653172654172655172656172657172658172659172660172661172662172663172664172665172666172667172668172669172670172671172672172673172674172675172676172677172678172679172680172681172682172683172684172685172686172687172688172689172690172691172692172693172694172695172696172697172698172699172700172701172702172703172704172705172706172707172708172709172710172711172712172713172714172715172716172717172718172719172720172721172722172723172724172725172726172727172728172729172730172731172732172733172734172735172736172737172738172739172740172741172742172743172744172745172746172747172748172749172750172751172752172753172754172755172756172757172758172759172760172761172762172763172764172765172766172767172768172769172770172771172772172773172774172775172776172777172778172779172780172781172782172783172784172785172786172787172788172789172790172791172792172793172794172795172796172797172798172799172800172801172802172803172804172805172806172807172808172809172810172811172812172813172814172815172816172817172818172819172820172821172822172823172824172825172826172827172828172829172830172831172832172833172834172835172836172837172838172839172840172841172842172843172844172845172846172847172848172849172850172851172852172853172854172855172856172857172858172859172860172861172862172863172864172865172866172867172868172869172870172871172872172873172874172875172876172877172878172879172880172881172882172883172884172885172886172887172888172889172890172891172892172893172894172895172896172897172898172899172900172901172902172903172904172905172906172907172908172909172910172911172912172913172914172915172916172917172918172919172920172921172922172923172924172925172926172927172928172929172930172931172932172933172934172935172936172937172938172939172940172941172942172943172944172945172946172947172948172949172950172951172952172953172954172955172956172957172958172959172960172961172962172963172964172965172966172967172968172969172970172971172972172973172974172975172976172977172978172979172980172981172982172983172984172985172986172987172988172989172990172991172992172993172994172995172996172997172998172999173000173001173002173003173004173005173006173007173008173009173010173011173012173013173014173015173016173017173018173019173020173021173022173023173024173025173026173027173028173029173030173031173032173033173034173035173036173037173038173039173040173041173042173043173044173045173046173047173048173049173050173051173052173053173054173055173056173057173058173059173060173061173062173063173064173065173066173067173068173069173070173071173072173073173074173075173076173077173078173079173080173081173082173083173084173085173086173087173088173089173090173091173092173093173094173095173096173097173098173099173100173101173102173103173104173105173106173107173108173109173110173111173112173113173114173115173116173117173118173119173120173121173122173123173124173125173126173127173128173129173130173131173132173133173134173135173136173137173138173139173140173141173142173143173144173145173146173147173148173149173150173151173152173153173154173155173156173157173158173159173160173161173162173163173164173165173166173167173168173169173170173171173172173173173174173175173176173177173178173179173180173181173182173183173184173185173186173187173188173189173190173191173192173193173194173195173196173197173198173199173200173201173202173203173204173205173206173207173208173209173210173211173212173213173214173215173216173217173218173219173220173221173222173223173224173225173226173227173228173229173230173231173232173233173234173235173236173237173238173239173240173241173242173243173244173245173246173247173248173249173250173251173252173253173254173255173256173257173258173259173260173261173262173263173264173265173266173267173268173269173270173271173272173273173274173275173276173277173278173279173280173281173282173283173284173285173286173287173288173289173290173291173292173293173294173295173296173297173298173299173300173301173302173303173304173305173306173307173308173309173310173311173312173313173314173315173316173317173318173319173320173321173322173323173324173325173326173327173328173329173330173331173332173333173334173335173336173337173338173339173340173341173342173343173344173345173346173347173348173349173350173351173352173353173354173355173356173357173358173359173360173361173362173363173364173365173366173367173368173369173370173371173372173373173374173375173376173377173378173379173380173381173382173383173384173385173386173387173388173389173390173391173392173393173394173395173396173397173398173399173400173401173402173403173404173405173406173407173408173409173410173411173412173413173414173415173416173417173418173419173420173421173422173423173424173425173426173427173428173429173430173431173432173433173434173435173436173437173438173439173440173441173442173443173444173445173446173447173448173449173450173451173452173453173454173455173456173457173458173459173460173461173462173463173464173465173466173467173468173469173470173471173472173473173474173475173476173477173478173479173480173481173482173483173484173485173486173487173488173489173490173491173492173493173494173495173496173497173498173499173500173501173502173503173504173505173506173507173508173509173510173511173512173513173514173515173516173517173518173519173520173521173522173523173524173525173526173527173528173529173530173531173532173533173534173535173536173537173538173539173540173541173542173543173544173545173546173547173548173549173550173551173552173553173554173555173556173557173558173559173560173561173562173563173564173565173566173567173568173569173570173571173572173573173574173575173576173577173578173579173580173581173582173583173584173585173586173587173588173589173590173591173592173593173594173595173596173597173598173599173600173601173602173603173604173605173606173607173608173609173610173611173612173613173614173615173616173617173618173619173620173621173622173623173624173625173626173627173628173629173630173631173632173633173634173635173636173637173638173639173640173641173642173643173644173645173646173647173648173649173650173651173652173653173654173655173656173657173658173659173660173661173662173663173664173665173666173667173668173669173670173671173672173673173674173675173676173677173678173679173680173681173682173683173684173685173686173687173688173689173690173691173692173693173694173695173696173697173698173699173700173701173702173703173704173705173706173707173708173709173710173711173712173713173714173715173716173717173718173719173720173721173722173723173724173725173726173727173728173729173730173731173732173733173734173735173736173737173738173739173740173741173742173743173744173745173746173747173748173749173750173751173752173753173754173755173756173757173758173759173760173761173762173763173764173765173766173767173768173769173770173771173772173773173774173775173776173777173778173779173780173781173782173783173784173785173786173787173788173789173790173791173792173793173794173795173796173797173798173799173800173801173802173803173804173805173806173807173808173809173810173811173812173813173814173815173816173817173818173819173820173821173822173823173824173825173826173827173828173829173830173831173832173833173834173835173836173837173838173839173840173841173842173843173844173845173846173847173848173849173850173851173852173853173854173855173856173857173858173859173860173861173862173863173864173865173866173867173868173869173870173871173872173873173874173875173876173877173878173879173880173881173882173883173884173885173886173887173888173889173890173891173892173893173894173895173896173897173898173899173900173901173902173903173904173905173906173907173908173909173910173911173912173913173914173915173916173917173918173919173920173921173922173923173924173925173926173927173928173929173930173931173932173933173934173935173936173937173938173939173940173941173942173943173944173945173946173947173948173949173950173951173952173953173954173955173956173957173958173959173960173961173962173963173964173965173966173967173968173969173970173971173972173973173974173975173976173977173978173979173980173981173982173983173984173985173986173987173988173989173990173991173992173993173994173995173996173997173998173999174000174001174002174003174004174005174006174007174008174009174010174011174012174013174014174015174016174017174018174019174020174021174022174023174024174025174026174027174028174029174030174031174032174033174034174035174036174037174038174039174040174041174042174043174044174045174046174047174048174049174050174051174052174053174054174055174056174057174058174059174060174061174062174063174064174065174066174067174068174069174070174071174072174073174074174075174076174077174078174079174080174081174082174083174084174085174086174087174088174089174090174091174092174093174094174095174096174097174098174099174100174101174102174103174104174105174106174107174108174109174110174111174112174113174114174115174116174117174118174119174120174121174122174123174124174125174126174127174128174129174130174131174132174133174134174135174136174137174138174139174140174141174142174143174144174145174146174147174148174149174150174151174152174153174154174155174156174157174158174159174160174161174162174163174164174165174166174167174168174169174170174171174172174173174174174175174176174177174178174179174180174181174182174183174184174185174186174187174188174189174190174191174192174193174194174195174196174197174198174199174200174201174202174203174204174205174206174207174208174209174210174211174212174213174214174215174216174217174218174219174220174221174222174223174224174225174226174227174228174229174230174231174232174233174234174235174236174237174238174239174240174241174242174243174244174245174246174247174248174249174250174251174252174253174254174255174256174257174258174259174260174261174262174263174264174265174266174267174268174269174270174271174272174273174274174275174276174277174278174279174280174281174282174283174284174285174286174287174288174289174290174291174292174293174294174295174296174297174298174299174300174301174302174303174304174305174306174307174308174309174310174311174312174313174314174315174316174317174318174319174320174321174322174323174324174325174326174327174328174329174330174331174332174333174334174335174336174337174338174339174340174341174342174343174344174345174346174347174348174349174350174351174352174353174354174355174356174357174358174359174360174361174362174363174364174365174366174367174368174369174370174371174372174373174374174375174376174377174378174379174380174381174382174383174384174385174386174387174388174389174390174391174392174393174394174395174396174397174398174399174400174401174402174403174404174405174406174407174408174409174410174411174412174413174414174415174416174417174418174419174420174421174422174423174424174425174426174427174428174429174430174431174432174433174434174435174436174437174438174439174440174441174442174443174444174445174446174447174448174449174450174451174452174453174454174455174456174457174458174459174460174461174462174463174464174465174466174467174468174469174470174471174472174473174474174475174476174477174478174479174480174481174482174483174484174485174486174487174488174489174490174491174492174493174494174495174496174497174498174499174500174501174502174503174504174505174506174507174508174509174510174511174512174513174514174515174516174517174518174519174520174521174522174523174524174525174526174527174528174529174530174531174532174533174534174535174536174537174538174539174540174541174542174543174544174545174546174547174548174549174550174551174552174553174554174555174556174557174558174559174560174561174562174563174564174565174566174567174568174569174570174571174572174573174574174575174576174577174578174579174580174581174582174583174584174585174586174587174588174589174590174591174592174593174594174595174596174597174598174599174600174601174602174603174604174605174606174607174608174609174610174611174612174613174614174615174616174617174618174619174620174621174622174623174624174625174626174627174628174629174630174631174632174633174634174635174636174637174638174639174640174641174642174643174644174645174646174647174648174649174650174651174652174653174654174655174656174657174658174659174660174661174662174663174664174665174666174667174668174669174670174671174672174673174674174675174676174677174678174679174680174681174682174683174684174685174686174687174688174689174690174691174692174693174694174695174696174697174698174699174700174701174702174703174704174705174706174707174708174709174710174711174712174713174714174715174716174717174718174719174720174721174722174723174724174725174726174727174728174729174730174731174732174733174734174735174736174737174738174739174740174741174742174743174744174745174746174747174748174749174750174751174752174753174754174755174756174757174758174759174760174761174762174763174764174765174766174767174768174769174770174771174772174773174774174775174776174777174778174779174780174781174782174783174784174785174786174787174788174789174790174791174792174793174794174795174796174797174798174799174800174801174802174803174804174805174806174807174808174809174810174811174812174813174814174815174816174817174818174819174820174821174822174823174824174825174826174827174828174829174830174831174832174833174834174835174836174837174838174839174840174841174842174843174844174845174846174847174848174849174850174851174852174853174854174855174856174857174858174859174860174861174862174863174864174865174866174867174868174869174870174871174872174873174874174875174876174877174878174879174880174881174882174883174884174885174886174887174888174889174890174891174892174893174894174895174896174897174898174899174900174901174902174903174904174905174906174907174908174909174910174911174912174913174914174915174916174917174918174919174920174921174922174923174924174925174926174927174928174929174930174931174932174933174934174935174936174937174938174939174940174941174942174943174944174945174946174947174948174949174950174951174952174953174954174955174956174957174958174959174960174961174962174963174964174965174966174967174968174969174970174971174972174973174974174975174976174977174978174979174980174981174982174983174984174985174986174987174988174989174990174991174992174993174994174995174996174997174998174999175000175001175002175003175004175005175006175007175008175009175010175011175012175013175014175015175016175017175018175019175020175021175022175023175024175025175026175027175028175029175030175031175032175033175034175035175036175037175038175039175040175041175042175043175044175045175046175047175048175049175050175051175052175053175054175055175056175057175058175059175060175061175062175063175064175065175066175067175068175069175070175071175072175073175074175075175076175077175078175079175080175081175082175083175084175085175086175087175088175089175090175091175092175093175094175095175096175097175098175099175100175101175102175103175104175105175106175107175108175109175110175111175112175113175114175115175116175117175118175119175120175121175122175123175124175125175126175127175128175129175130175131175132175133175134175135175136175137175138175139175140175141175142175143175144175145175146175147175148175149175150175151175152175153175154175155175156175157175158175159175160175161175162175163175164175165175166175167175168175169175170175171175172175173175174175175175176175177175178175179175180175181175182175183175184175185175186175187175188175189175190175191175192175193175194175195175196175197175198175199175200175201175202175203175204175205175206175207175208175209175210175211175212175213175214175215175216175217175218175219175220175221175222175223175224175225175226175227175228175229175230175231175232175233175234175235175236175237175238175239175240175241175242175243175244175245175246175247175248175249175250175251175252175253175254175255175256175257175258175259175260175261175262175263175264175265175266175267175268175269175270175271175272175273175274175275175276175277175278175279175280175281175282175283175284175285175286175287175288175289175290175291175292175293175294175295175296175297175298175299175300175301175302175303175304175305175306175307175308175309175310175311175312175313175314175315175316175317175318175319175320175321175322175323175324175325175326175327175328175329175330175331175332175333175334175335175336175337175338175339175340175341175342175343175344175345175346175347175348175349175350175351175352175353175354175355175356175357175358175359175360175361175362175363175364175365175366175367175368175369175370175371175372175373175374175375175376175377175378175379175380175381175382175383175384175385175386175387175388175389175390175391175392175393175394175395175396175397175398175399175400175401175402175403175404175405175406175407175408175409175410175411175412175413175414175415175416175417175418175419175420175421175422175423175424175425175426175427175428175429175430175431175432175433175434175435175436175437175438175439175440175441175442175443175444175445175446175447175448175449175450175451175452175453175454175455175456175457175458175459175460175461175462175463175464175465175466175467175468175469175470175471175472175473175474175475175476175477175478175479175480175481175482175483175484175485175486175487175488175489175490175491175492175493175494175495175496175497175498175499175500175501175502175503175504175505175506175507175508175509175510175511175512175513175514175515175516175517175518175519175520175521175522175523175524175525175526175527175528175529175530175531175532175533175534175535175536175537175538175539175540175541175542175543175544175545175546175547175548175549175550175551175552175553175554175555175556175557175558175559175560175561175562175563175564175565175566175567175568175569175570175571175572175573175574175575175576175577175578175579175580175581175582175583175584175585175586175587175588175589175590175591175592175593175594175595175596175597175598175599175600175601175602175603175604175605175606175607175608175609175610175611175612175613175614175615175616175617175618175619175620175621175622175623175624175625175626175627175628175629175630175631175632175633175634175635175636175637175638175639175640175641175642175643175644175645175646175647175648175649175650175651175652175653175654175655175656175657175658175659175660175661175662175663175664175665175666175667175668175669175670175671175672175673175674175675175676175677175678175679175680175681175682175683175684175685175686175687175688175689175690175691175692175693175694175695175696175697175698175699175700175701175702175703175704175705175706175707175708175709175710175711175712175713175714175715175716175717175718175719175720175721175722175723175724175725175726175727175728175729175730175731175732175733175734175735175736175737175738175739175740175741175742175743175744175745175746175747175748175749175750175751175752175753175754175755175756175757175758175759175760175761175762175763175764175765175766175767175768175769175770175771175772175773175774175775175776175777175778175779175780175781175782175783175784175785175786175787175788175789175790175791175792175793175794175795175796175797175798175799175800175801175802175803175804175805175806175807175808175809175810175811175812175813175814175815175816175817175818175819175820175821175822175823175824175825175826175827175828175829175830175831175832175833175834175835175836175837175838175839175840175841175842175843175844175845175846175847175848175849175850175851175852175853175854175855175856175857175858175859175860175861175862175863175864175865175866175867175868175869175870175871175872175873175874175875175876175877175878175879175880175881175882175883175884175885175886175887175888175889175890175891175892175893175894175895175896175897175898175899175900175901175902175903175904175905175906175907175908175909175910175911175912175913175914175915175916175917175918175919175920175921175922175923175924175925175926175927175928175929175930175931175932175933175934175935175936175937175938175939175940175941175942175943175944175945175946175947175948175949175950175951175952175953175954175955175956175957175958175959175960175961175962175963175964175965175966175967175968175969175970175971175972175973175974175975175976175977175978175979175980175981175982175983175984175985175986175987175988175989175990175991175992175993175994175995175996175997175998175999176000176001176002176003176004176005176006176007176008176009176010176011176012176013176014176015176016176017176018176019176020176021176022176023176024176025176026176027176028176029176030176031176032176033176034176035176036176037176038176039176040176041176042176043176044176045176046176047176048176049176050176051176052176053176054176055176056176057176058176059176060176061176062176063176064176065176066176067176068176069176070176071176072176073176074176075176076176077176078176079176080176081176082176083176084176085176086176087176088176089176090176091176092176093176094176095176096176097176098176099176100176101176102176103176104176105176106176107176108176109176110176111176112176113176114176115176116176117176118176119176120176121176122176123176124176125176126176127176128176129176130176131176132176133176134176135176136176137176138176139176140176141176142176143176144176145176146176147176148176149176150176151176152176153176154176155176156176157176158176159176160176161176162176163176164176165176166176167176168176169176170176171176172176173176174176175176176176177176178176179176180176181176182176183176184176185176186176187176188176189176190176191176192176193176194176195176196176197176198176199176200176201176202176203176204176205176206176207176208176209176210176211176212176213176214176215176216176217176218176219176220176221176222176223176224176225176226176227176228176229176230176231176232176233176234176235176236176237176238176239176240176241176242176243176244176245176246176247176248176249176250176251176252176253176254176255176256176257176258176259176260176261176262176263176264176265176266176267176268176269176270176271176272176273176274176275176276176277176278176279176280176281176282176283176284176285176286176287176288176289176290176291176292176293176294176295176296176297176298176299176300176301176302176303176304176305176306176307176308176309176310176311176312176313176314176315176316176317176318176319176320176321176322176323176324176325176326176327176328176329176330176331176332176333176334176335176336176337176338176339176340176341176342176343176344176345176346176347176348176349176350176351176352176353176354176355176356176357176358176359176360176361176362176363176364176365176366176367176368176369176370176371176372176373176374176375176376176377176378176379176380176381176382176383176384176385176386176387176388176389176390176391176392176393176394176395176396176397176398176399176400176401176402176403176404176405176406176407176408176409176410176411176412176413176414176415176416176417176418176419176420176421176422176423176424176425176426176427176428176429176430176431176432176433176434176435176436176437176438176439176440176441176442176443176444176445176446176447176448176449176450176451176452176453176454176455176456176457176458176459176460176461176462176463176464176465176466176467176468176469176470176471176472176473176474176475176476176477176478176479176480176481176482176483176484176485176486176487176488176489176490176491176492176493176494176495176496176497176498176499176500176501176502176503176504176505176506176507176508176509176510176511176512176513176514176515176516176517176518176519176520176521176522176523176524176525176526176527176528176529176530176531176532176533176534176535176536176537176538176539176540176541176542176543176544176545176546176547176548176549176550176551176552176553176554176555176556176557176558176559176560176561176562176563176564176565176566176567176568176569176570176571176572176573176574176575176576176577176578176579176580176581176582176583176584176585176586176587176588176589176590176591176592176593176594176595176596176597176598176599176600176601176602176603176604176605176606176607176608176609176610176611176612176613176614176615176616176617176618176619176620176621176622176623176624176625176626176627176628176629176630176631176632176633176634176635176636176637176638176639176640176641176642176643176644176645176646176647176648176649176650176651176652176653176654176655176656176657176658176659176660176661176662176663176664176665176666176667176668176669176670176671176672176673176674176675176676176677176678176679176680176681176682176683176684176685176686176687176688176689176690176691176692176693176694176695176696176697176698176699176700176701176702176703176704176705176706176707176708176709176710176711176712176713176714176715176716176717176718176719176720176721176722176723176724176725176726176727176728176729176730176731176732176733176734176735176736176737176738176739176740176741176742176743176744176745176746176747176748176749176750176751176752176753176754176755176756176757176758176759176760176761176762176763176764176765176766176767176768176769176770176771176772176773176774176775176776176777176778176779176780176781176782176783176784176785176786176787176788176789176790176791176792176793176794176795176796176797176798176799176800176801176802176803176804176805176806176807176808176809176810176811176812176813176814176815176816176817176818176819176820176821176822176823176824176825176826176827176828176829176830176831176832176833176834176835176836176837176838176839176840176841176842176843176844176845176846176847176848176849176850176851176852176853176854176855176856176857176858176859176860176861176862176863176864176865176866176867176868176869176870176871176872176873176874176875176876176877176878176879176880176881176882176883176884176885176886176887176888176889176890176891176892176893176894176895176896176897176898176899176900176901176902176903176904176905176906176907176908176909176910176911176912176913176914176915176916176917176918176919176920176921176922176923176924176925176926176927176928176929176930176931176932176933176934176935176936176937176938176939176940176941176942176943176944176945176946176947176948176949176950176951176952176953176954176955176956176957176958176959176960176961176962176963176964176965176966176967176968176969176970176971176972176973176974176975176976176977176978176979176980176981176982176983176984176985176986176987176988176989176990176991176992176993176994176995176996176997176998176999177000177001177002177003177004177005177006177007177008177009177010177011177012177013177014177015177016177017177018177019177020177021177022177023177024177025177026177027177028177029177030177031177032177033177034177035177036177037177038177039177040177041177042177043177044177045177046177047177048177049177050177051177052177053177054177055177056177057177058177059177060177061177062177063177064177065177066177067177068177069177070177071177072177073177074177075177076177077177078177079177080177081177082177083177084177085177086177087177088177089177090177091177092177093177094177095177096177097177098177099177100177101177102177103177104177105177106177107177108177109177110177111177112177113177114177115177116177117177118177119177120177121177122177123177124177125177126177127177128177129177130177131177132177133177134177135177136177137177138177139177140177141177142177143177144177145177146177147177148177149177150177151177152177153177154177155177156177157177158177159177160177161177162177163177164177165177166177167177168177169177170177171177172177173177174177175177176177177177178177179177180177181177182177183177184177185177186177187177188177189177190177191177192177193177194177195177196177197177198177199177200177201177202177203177204177205177206177207177208177209177210177211177212177213177214177215177216177217177218177219177220177221177222177223177224177225177226177227177228177229177230177231177232177233177234177235177236177237177238177239177240177241177242177243177244177245177246177247177248177249177250177251177252177253177254177255177256177257177258177259177260177261177262177263177264177265177266177267177268177269177270177271177272177273177274177275177276177277177278177279177280177281177282177283177284177285177286177287177288177289177290177291177292177293177294177295177296177297177298177299177300177301177302177303177304177305177306177307177308177309177310177311177312177313177314177315177316177317177318177319177320177321177322177323177324177325177326177327177328177329177330177331177332177333177334177335177336177337177338177339177340177341177342177343177344177345177346177347177348177349177350177351177352177353177354177355177356177357177358177359177360177361177362177363177364177365177366177367177368177369177370177371177372177373177374177375177376177377177378177379177380177381177382177383177384177385177386177387177388177389177390177391177392177393177394177395177396177397177398177399177400177401177402177403177404177405177406177407177408177409177410177411177412177413177414177415177416177417177418177419177420177421177422177423177424177425177426177427177428177429177430177431177432177433177434177435177436177437177438177439177440177441177442177443177444177445177446177447177448177449177450177451177452177453177454177455177456177457177458177459177460177461177462177463177464177465177466177467177468177469177470177471177472177473177474177475177476177477177478177479177480177481177482177483177484177485177486177487177488177489177490177491177492177493177494177495177496177497177498177499177500177501177502177503177504177505177506177507177508177509177510177511177512177513177514177515177516177517177518177519177520177521177522177523177524177525177526177527177528177529177530177531177532177533177534177535177536177537177538177539177540177541177542177543177544177545177546177547177548177549177550177551177552177553177554177555177556177557177558177559177560177561177562177563177564177565177566177567177568177569177570177571177572177573177574177575177576177577177578177579177580177581177582177583177584177585177586177587177588177589177590177591177592177593177594177595177596177597177598177599177600177601177602177603177604177605177606177607177608177609177610177611177612177613177614177615177616177617177618177619177620177621177622177623177624177625177626177627177628177629177630177631177632177633177634177635177636177637177638177639177640177641177642177643177644177645177646177647177648177649177650177651177652177653177654177655177656177657177658177659177660177661177662177663177664177665177666177667177668177669177670177671177672177673177674177675177676177677177678177679177680177681177682177683177684177685177686177687177688177689177690177691177692177693177694177695177696177697177698177699177700177701177702177703177704177705177706177707177708177709177710177711177712177713177714177715177716177717177718177719177720177721177722177723177724177725177726177727177728177729177730177731177732177733177734177735177736177737177738177739177740177741177742177743177744177745177746177747177748177749177750177751177752177753177754177755177756177757177758177759177760177761177762177763177764177765177766177767177768177769177770177771177772177773177774177775177776177777177778177779177780177781177782177783177784177785177786177787177788177789177790177791177792177793177794177795177796177797177798177799177800177801177802177803177804177805177806177807177808177809177810177811177812177813177814177815177816177817177818177819177820177821177822177823177824177825177826177827177828177829177830177831177832177833177834177835177836177837177838177839177840177841177842177843177844177845177846177847177848177849177850177851177852177853177854177855177856177857177858177859177860177861177862177863177864177865177866177867177868177869177870177871177872177873177874177875177876177877177878177879177880177881177882177883177884177885177886177887177888177889177890177891177892177893177894177895177896177897177898177899177900177901177902177903177904177905177906177907177908177909177910177911177912177913177914177915177916177917177918177919177920177921177922177923177924177925177926177927177928177929177930177931177932177933177934177935177936177937177938177939177940177941177942177943177944177945177946177947177948177949177950177951177952177953177954177955177956177957177958177959177960177961177962177963177964177965177966177967177968177969177970177971177972177973177974177975177976177977177978177979177980177981177982177983177984177985177986177987177988177989177990177991177992177993177994177995177996177997177998177999178000178001178002178003178004178005178006178007178008178009178010178011178012178013178014178015178016178017178018178019178020178021178022178023178024178025178026178027178028178029178030178031178032178033178034178035178036178037178038178039178040178041178042178043178044178045178046178047178048178049178050178051178052178053178054178055178056178057178058178059178060178061178062178063178064178065178066178067178068178069178070178071178072178073178074178075178076178077178078178079178080178081178082178083178084178085178086178087178088178089178090178091178092178093178094178095178096178097178098178099178100178101178102178103178104178105178106178107178108178109178110178111178112178113178114178115178116178117178118178119178120178121178122178123178124178125178126178127178128178129178130178131178132178133178134178135178136178137178138178139178140178141178142178143178144178145178146178147178148178149178150178151178152178153178154178155178156178157178158178159178160178161178162178163178164178165178166178167178168178169178170178171178172178173178174178175178176178177178178178179178180178181178182178183178184178185178186178187178188178189178190178191178192178193178194178195178196178197178198178199178200178201178202178203178204178205178206178207178208178209178210178211178212178213178214178215178216178217178218178219178220178221178222178223178224178225178226178227178228178229178230178231178232178233178234178235178236178237178238178239178240178241178242178243178244178245178246178247178248178249178250178251178252178253178254178255178256178257178258178259178260178261178262178263178264178265178266178267178268178269178270178271178272178273178274178275178276178277178278178279178280178281178282178283178284178285178286178287178288178289178290178291178292178293178294178295178296178297178298178299178300178301178302178303178304178305178306178307178308178309178310178311178312178313178314178315178316178317178318178319178320178321178322178323178324178325178326178327178328178329178330178331178332178333178334178335178336178337178338178339178340178341178342178343178344178345178346178347178348178349178350178351178352178353178354178355178356178357178358178359178360178361178362178363178364178365178366178367178368178369178370178371178372178373178374178375178376178377178378178379178380178381178382178383178384178385178386178387178388178389178390178391178392178393178394178395178396178397178398178399178400178401178402178403178404178405178406178407178408178409178410178411178412178413178414178415178416178417178418178419178420178421178422178423178424178425178426178427178428178429178430178431178432178433178434178435178436178437178438178439178440178441178442178443178444178445178446178447178448178449178450178451178452178453178454178455178456178457178458178459178460178461178462178463178464178465178466178467178468178469178470178471178472178473178474178475178476178477178478178479178480178481178482178483178484178485178486178487178488178489178490178491178492178493178494178495178496178497178498178499178500178501178502178503178504178505178506178507178508178509178510178511178512178513178514178515178516178517178518178519178520178521178522178523178524178525178526178527178528178529178530178531178532178533178534178535178536178537178538178539178540178541178542178543178544178545178546178547178548178549178550178551178552178553178554178555178556178557178558178559178560178561178562178563178564178565178566178567178568178569178570178571178572178573178574178575178576178577178578178579178580178581178582178583178584178585178586178587178588178589178590178591178592178593178594178595178596178597178598178599178600178601178602178603178604178605178606178607178608178609178610178611178612178613178614178615178616178617178618178619178620178621178622178623178624178625178626178627178628178629178630178631178632178633178634178635178636178637178638178639178640178641178642178643178644178645178646178647178648178649178650178651178652178653178654178655178656178657178658178659178660178661178662178663178664178665178666178667178668178669178670178671178672178673178674178675178676178677178678178679178680178681178682178683178684178685178686178687178688178689178690178691178692178693178694178695178696178697178698178699178700178701178702178703178704178705178706178707178708178709178710178711178712178713178714178715178716178717178718178719178720178721178722178723178724178725178726178727178728178729178730178731178732178733178734178735178736178737178738178739178740178741178742178743178744178745178746178747178748178749178750178751178752178753178754178755178756178757178758178759178760178761178762178763178764178765178766178767178768178769178770178771178772178773178774178775178776178777178778178779178780178781178782178783178784178785178786178787178788178789178790178791178792178793178794178795178796178797178798178799178800178801178802178803178804178805178806178807178808178809178810178811178812178813178814178815178816178817178818178819178820178821178822178823178824178825178826178827178828178829178830178831178832178833178834178835178836178837178838178839178840178841178842178843178844178845178846178847178848178849178850178851178852178853178854178855178856178857178858178859178860178861178862178863178864178865178866178867178868178869178870178871178872178873178874178875178876178877178878178879178880178881178882178883178884178885178886178887178888178889178890178891178892178893178894178895178896178897178898178899178900178901178902178903178904178905178906178907178908178909178910178911178912178913178914178915178916178917178918178919178920178921178922178923178924178925178926178927178928178929178930178931178932178933178934178935178936178937178938178939178940178941178942178943178944178945178946178947178948178949178950178951178952178953178954178955178956178957178958178959178960178961178962178963178964178965178966178967178968178969178970178971178972178973178974178975178976178977178978178979178980178981178982178983178984178985178986178987178988178989178990178991178992178993178994178995178996178997178998178999179000179001179002179003179004179005179006179007179008179009179010179011179012179013179014179015179016179017179018179019179020179021179022179023179024179025179026179027179028179029179030179031179032179033179034179035179036179037179038179039179040179041179042179043179044179045179046179047179048179049179050179051179052179053179054179055179056179057179058179059179060179061179062179063179064179065179066179067179068179069179070179071179072179073179074179075179076179077179078179079179080179081179082179083179084179085179086179087179088179089179090179091179092179093179094179095179096179097179098179099179100179101179102179103179104179105179106179107179108179109179110179111179112179113179114179115179116179117179118179119179120179121179122179123179124179125179126179127179128179129179130179131179132179133179134179135179136179137179138179139179140179141179142179143179144179145179146179147179148179149179150179151179152179153179154179155179156179157179158179159179160179161179162179163179164179165179166179167179168179169179170179171179172179173179174179175179176179177179178179179179180179181179182179183179184179185179186179187179188179189179190179191179192179193179194179195179196179197179198179199179200179201179202179203179204179205179206179207179208179209179210179211179212179213179214179215179216179217179218179219179220179221179222179223179224179225179226179227179228179229179230179231179232179233179234179235179236179237179238179239179240179241179242179243179244179245179246179247179248179249179250179251179252179253179254179255179256179257179258179259179260179261179262179263179264179265179266179267179268179269179270179271179272179273179274179275179276179277179278179279179280179281179282179283179284179285179286179287179288179289179290179291179292179293179294179295179296179297179298179299179300179301179302179303179304179305179306179307179308179309179310179311179312179313179314179315179316179317179318179319179320179321179322179323179324179325179326179327179328179329179330179331179332179333179334179335179336179337179338179339179340179341179342179343179344179345179346179347179348179349179350179351179352179353179354179355179356179357179358179359179360179361179362179363179364179365179366179367179368179369179370179371179372179373179374179375179376179377179378179379179380179381179382179383179384179385179386179387179388179389179390179391179392179393179394179395179396179397179398179399179400179401179402179403179404179405179406179407179408179409179410179411179412179413179414179415179416179417179418179419179420179421179422179423179424179425179426179427179428179429179430179431179432179433179434179435179436179437179438179439179440179441179442179443179444179445179446179447179448179449179450179451179452179453179454179455179456179457179458179459179460179461179462179463179464179465179466179467179468179469179470179471179472179473179474179475179476179477179478179479179480179481179482179483179484179485179486179487179488179489179490179491179492179493179494179495179496179497179498179499179500179501179502179503179504179505179506179507179508179509179510179511179512179513179514179515179516179517179518179519179520179521179522179523179524179525179526179527179528179529179530179531179532179533179534179535179536179537179538179539179540179541179542179543179544179545179546179547179548179549179550179551179552179553179554179555179556179557179558179559179560179561179562179563179564179565179566179567179568179569179570179571179572179573179574179575179576179577179578179579179580179581179582179583179584179585179586179587179588179589179590179591179592179593179594179595179596179597179598179599179600179601179602179603179604179605179606179607179608179609179610179611179612179613179614179615179616179617179618179619179620179621179622179623179624179625179626179627179628179629179630179631179632179633179634179635179636179637179638179639179640179641179642179643179644179645179646179647179648179649179650179651179652179653179654179655179656179657179658179659179660179661179662179663179664179665179666179667179668179669179670179671179672179673179674179675179676179677179678179679179680179681179682179683179684179685179686179687179688179689179690179691179692179693179694179695179696179697179698179699179700179701179702179703179704179705179706179707179708179709179710179711179712179713179714179715179716179717179718179719179720179721179722179723179724179725179726179727179728179729179730179731179732179733179734179735179736179737179738179739179740179741179742179743179744179745179746179747179748179749179750179751179752179753179754179755179756179757179758179759179760179761179762179763179764179765179766179767179768179769179770179771179772179773179774179775179776179777179778179779179780179781179782179783179784179785179786179787179788179789179790179791179792179793179794179795179796179797179798179799179800179801179802179803179804179805179806179807179808179809179810179811179812179813179814179815179816179817179818179819179820179821179822179823179824179825179826179827179828179829179830179831179832179833179834179835179836179837179838179839179840179841179842179843179844179845179846179847179848179849179850179851179852179853179854179855179856179857179858179859179860179861179862179863179864179865179866179867179868179869179870179871179872179873179874179875179876179877179878179879179880179881179882179883179884179885179886179887179888179889179890179891179892179893179894179895179896179897179898179899179900179901179902179903179904179905179906179907179908179909179910179911179912179913179914179915179916179917179918179919179920179921179922179923179924179925179926179927179928179929179930179931179932179933179934179935179936179937179938179939179940179941179942179943179944179945179946179947179948179949179950179951179952179953179954179955179956179957179958179959179960179961179962179963179964179965179966179967179968179969179970179971179972179973179974179975179976179977179978179979179980179981179982179983179984179985179986179987179988179989179990179991179992179993179994179995179996179997179998179999180000180001180002180003180004180005180006180007180008180009180010180011180012180013180014180015180016180017180018180019180020180021180022180023180024180025180026180027180028180029180030180031180032180033180034180035180036180037180038180039180040180041180042180043180044180045180046180047180048180049180050180051180052180053180054180055180056180057180058180059180060180061180062180063180064180065180066180067180068180069180070180071180072180073180074180075180076180077180078180079180080180081180082180083180084180085180086180087180088180089180090180091180092180093180094180095180096180097180098180099180100180101180102180103180104180105180106180107180108180109180110180111180112180113180114180115180116180117180118180119180120180121180122180123180124180125180126180127180128180129180130180131180132180133180134180135180136180137180138180139180140180141180142180143180144180145180146180147180148180149180150180151180152180153180154180155180156180157180158180159180160180161180162180163180164180165180166180167180168180169180170180171180172180173180174180175180176180177180178180179180180180181180182180183180184180185180186180187180188180189180190180191180192180193180194180195180196180197180198180199180200180201180202180203180204180205180206180207180208180209180210180211180212180213180214180215180216180217180218180219180220180221180222180223180224180225180226180227180228180229180230180231180232180233180234180235180236180237180238180239180240180241180242180243180244180245180246180247180248180249180250180251180252180253180254180255180256180257180258180259180260180261180262180263180264180265180266180267180268180269180270180271180272180273180274180275180276180277180278180279180280180281180282180283180284180285180286180287180288180289180290180291180292180293180294180295180296180297180298180299180300180301180302180303180304180305180306180307180308180309180310180311180312180313180314180315180316180317180318180319180320180321180322180323180324180325180326180327180328180329180330180331180332180333180334180335180336180337180338180339180340180341180342180343180344180345180346180347180348180349180350180351180352180353180354180355180356180357180358180359180360180361180362180363180364180365180366180367180368180369180370180371180372180373180374180375180376180377180378180379180380180381180382180383180384180385180386180387180388180389180390180391180392180393180394180395180396180397180398180399180400180401180402180403180404180405180406180407180408180409180410180411180412180413180414180415180416180417180418180419180420180421180422180423180424180425180426180427180428180429180430180431180432180433180434180435180436180437180438180439180440180441180442180443180444180445180446180447180448180449180450180451180452180453180454180455180456180457180458180459180460180461180462180463180464180465180466180467180468180469180470180471180472180473180474180475180476180477180478180479180480180481180482180483180484180485180486180487180488180489180490180491180492180493180494180495180496180497180498180499180500180501180502180503180504180505180506180507180508180509180510180511180512180513180514180515180516180517180518180519180520180521180522180523180524180525180526180527180528180529180530180531180532180533180534180535180536180537180538180539180540180541180542180543180544180545180546180547180548180549180550180551180552180553180554180555180556180557180558180559180560180561180562180563180564180565180566180567180568180569180570180571180572180573180574180575180576180577180578180579180580180581180582180583180584180585180586180587180588180589180590180591180592180593180594180595180596180597180598180599180600180601180602180603180604180605180606180607180608180609180610180611180612180613180614180615180616180617180618180619180620180621180622180623180624180625180626180627180628180629180630180631180632180633180634180635180636180637180638180639180640180641180642180643180644180645180646180647180648180649180650180651180652180653180654180655180656180657180658180659180660180661180662180663180664180665180666180667180668180669180670180671180672180673180674180675180676180677180678180679180680180681180682180683180684180685180686180687180688180689180690180691180692180693180694180695180696180697180698180699180700180701180702180703180704180705180706180707180708180709180710180711180712180713180714180715180716180717180718180719180720180721180722180723180724180725180726180727180728180729180730180731180732180733180734180735180736180737180738180739180740180741180742180743180744180745180746180747180748180749180750180751180752180753180754180755180756180757180758180759180760180761180762180763180764180765180766180767180768180769180770180771180772180773180774180775180776180777180778180779180780180781180782180783180784180785180786180787180788180789180790180791180792180793180794180795180796180797180798180799180800180801180802180803180804180805180806180807180808180809180810180811180812180813180814180815180816180817180818180819180820180821180822180823180824180825180826180827180828180829180830180831180832180833180834180835180836180837180838180839180840180841180842180843180844180845180846180847180848180849180850180851180852180853180854180855180856180857180858180859180860180861180862180863180864180865180866180867180868180869180870180871180872180873180874180875180876180877180878180879180880180881180882180883180884180885180886180887180888180889180890180891180892180893180894180895180896180897180898180899180900180901180902180903180904180905180906180907180908180909180910180911180912180913180914180915180916180917180918180919180920180921180922180923180924180925180926180927180928180929180930180931180932180933180934180935180936180937180938180939180940180941180942180943180944180945180946180947180948180949180950180951180952180953180954180955180956180957180958180959180960180961180962180963180964180965180966180967180968180969180970180971180972180973180974180975180976180977180978180979180980180981180982180983180984180985180986180987180988180989180990180991180992180993180994180995180996180997180998180999181000181001181002181003181004181005181006181007181008181009181010181011181012181013181014181015181016181017181018181019181020181021181022181023181024181025181026181027181028181029181030181031181032181033181034181035181036181037181038181039181040181041181042181043181044181045181046181047181048181049181050181051181052181053181054181055181056181057181058181059181060181061181062181063181064181065181066181067181068181069181070181071181072181073181074181075181076181077181078181079181080181081181082181083181084181085181086181087181088181089181090181091181092181093181094181095181096181097181098181099181100181101181102181103181104181105181106181107181108181109181110181111181112181113181114181115181116181117181118181119181120181121181122181123181124181125181126181127181128181129181130181131181132181133181134181135181136181137181138181139181140181141181142181143181144181145181146181147181148181149181150181151181152181153181154181155181156181157181158181159181160181161181162181163181164181165181166181167181168181169181170181171181172181173181174181175181176181177181178181179181180181181181182181183181184181185181186181187181188181189181190181191181192181193181194181195181196181197181198181199181200181201181202181203181204181205181206181207181208181209181210181211181212181213181214181215181216181217181218181219181220181221181222181223181224181225181226181227181228181229181230181231181232181233181234181235181236181237181238181239181240181241181242181243181244181245181246181247181248181249181250181251181252181253181254181255181256181257181258181259181260181261181262181263181264181265181266181267181268181269181270181271181272181273181274181275181276181277181278181279181280181281181282181283181284181285181286181287181288181289181290181291181292181293181294181295181296181297181298181299181300181301181302181303181304181305181306181307181308181309181310181311181312181313181314181315181316181317181318181319181320181321181322181323181324181325181326181327181328181329181330181331181332181333181334181335181336181337181338181339181340181341181342181343181344181345181346181347181348181349181350181351181352181353181354181355181356181357181358181359181360181361181362181363181364181365181366181367181368181369181370181371181372181373181374181375181376181377181378181379181380181381181382181383181384181385181386181387181388181389181390181391181392181393181394181395181396181397181398181399181400181401181402181403181404181405181406181407181408181409181410181411181412181413181414181415181416181417181418181419181420181421181422181423181424181425181426181427181428181429181430181431181432181433181434181435181436181437181438181439181440181441181442181443181444181445181446181447181448181449181450181451181452181453181454181455181456181457181458181459181460181461181462181463181464181465181466181467181468181469181470181471181472181473181474181475181476181477181478181479181480181481181482181483181484181485181486181487181488181489181490181491181492181493181494181495181496181497181498181499181500181501181502181503181504181505181506181507181508181509181510181511181512181513181514181515181516181517181518181519181520181521181522181523181524181525181526181527181528181529181530181531181532181533181534181535181536181537181538181539181540181541181542181543181544181545181546181547181548181549181550181551181552181553181554181555181556181557181558181559181560181561181562181563181564181565181566181567181568181569181570181571181572181573181574181575181576181577181578181579181580181581181582181583181584181585181586181587181588181589181590181591181592181593181594181595181596181597181598181599181600181601181602181603181604181605181606181607181608181609181610181611181612181613181614181615181616181617181618181619181620181621181622181623181624181625181626181627181628181629181630181631181632181633181634181635181636181637181638181639181640181641181642181643181644181645181646181647181648181649181650181651181652181653181654181655181656181657181658181659181660181661181662181663181664181665181666181667181668181669181670181671181672181673181674181675181676181677181678181679181680181681181682181683181684181685181686181687181688181689181690181691181692181693181694181695181696181697181698181699181700181701181702181703181704181705181706181707181708181709181710181711181712181713181714181715181716181717181718181719181720181721181722181723181724181725181726181727181728181729181730181731181732181733181734181735181736181737181738181739181740181741181742181743181744181745181746181747181748181749181750181751181752181753181754181755181756181757181758181759181760181761181762181763181764181765181766181767181768181769181770181771181772181773181774181775181776181777181778181779181780181781181782181783181784181785181786181787181788181789181790181791181792181793181794181795181796181797181798181799181800181801181802181803181804181805181806181807181808181809181810181811181812181813181814181815181816181817181818181819181820181821181822181823181824181825181826181827181828181829181830181831181832181833181834181835181836181837181838181839181840181841181842181843181844181845181846181847181848181849181850181851181852181853181854181855181856181857181858181859181860181861181862181863181864181865181866181867181868181869181870181871181872181873181874181875181876181877181878181879181880181881181882181883181884181885181886181887181888181889181890181891181892181893181894181895181896181897181898181899181900181901181902181903181904181905181906181907181908181909181910181911181912181913181914181915181916181917181918181919181920181921181922181923181924181925181926181927181928181929181930181931181932181933181934181935181936181937181938181939181940181941181942181943181944181945181946181947181948181949181950181951181952181953181954181955181956181957181958181959181960181961181962181963181964181965181966181967181968181969181970181971181972181973181974181975181976181977181978181979181980181981181982181983181984181985181986181987181988181989181990181991181992181993181994181995181996181997181998181999182000182001182002182003182004182005182006182007182008182009182010182011182012182013182014182015182016182017182018182019182020182021182022182023182024182025182026182027182028182029182030182031182032182033182034182035182036182037182038182039182040182041182042182043182044182045182046182047182048182049182050182051182052182053182054182055182056182057182058182059182060182061182062182063182064182065182066182067182068182069182070182071182072182073182074182075182076182077182078182079182080182081182082182083182084182085182086182087182088182089182090182091182092182093182094182095182096182097182098182099182100182101182102182103182104182105182106182107182108182109182110182111182112182113182114182115182116182117182118182119182120182121182122182123182124182125182126182127182128182129182130182131182132182133182134182135182136182137182138182139182140182141182142182143182144182145182146182147182148182149182150182151182152182153182154182155182156182157182158182159182160182161182162182163182164182165182166182167182168182169182170182171182172182173182174182175182176182177182178182179182180182181182182182183182184182185182186182187182188182189182190182191182192182193182194182195182196182197182198182199182200182201182202182203182204182205182206182207182208182209182210182211182212182213182214182215182216182217182218182219182220182221182222182223182224182225182226182227182228182229182230182231182232182233182234182235182236182237182238182239182240182241182242182243182244182245182246182247182248182249182250182251182252182253182254182255182256182257182258182259182260182261182262182263182264182265182266182267182268182269182270182271182272182273182274182275182276182277182278182279182280182281182282182283182284182285182286182287182288182289182290182291182292182293182294182295182296182297182298182299182300182301182302182303182304182305182306182307182308182309182310182311182312182313182314182315182316182317182318182319182320182321182322182323182324182325182326182327182328182329182330182331182332182333182334182335182336182337182338182339182340182341182342182343182344182345182346182347182348182349182350182351182352182353182354182355182356182357182358182359182360182361182362182363182364182365182366182367182368182369182370182371182372182373182374182375182376182377182378182379182380182381182382182383182384182385182386182387182388182389182390182391182392182393182394182395182396182397182398182399182400182401182402182403182404182405182406182407182408182409182410182411182412182413182414182415182416182417182418182419182420182421182422182423182424182425182426182427182428182429182430182431182432182433182434182435182436182437182438182439182440182441182442182443182444182445182446182447182448182449182450182451182452182453182454182455182456182457182458182459182460182461182462182463182464182465182466182467182468182469182470182471182472182473182474182475182476182477182478182479182480182481182482182483182484182485182486182487182488182489182490182491182492182493182494182495182496182497182498182499182500182501182502182503182504182505182506182507182508182509182510182511182512182513182514182515182516182517182518182519182520182521182522182523182524182525182526182527182528182529182530182531182532182533182534182535182536182537182538182539182540182541182542182543182544182545182546182547182548182549182550182551182552182553182554182555182556182557182558182559182560182561182562182563182564182565182566182567182568182569182570182571182572182573182574182575182576182577182578182579182580182581182582182583182584182585182586182587182588182589182590182591182592182593182594182595182596182597182598182599182600182601182602182603182604182605182606182607182608182609182610182611182612182613182614182615182616182617182618182619182620182621182622182623182624182625182626182627182628182629182630182631182632182633182634182635182636182637182638182639182640182641182642182643182644182645182646182647182648182649182650182651182652182653182654182655182656182657182658182659182660182661182662182663182664182665182666182667182668182669182670182671182672182673182674182675182676182677182678182679182680182681182682182683182684182685182686182687182688182689182690182691182692182693182694182695182696182697182698182699182700182701182702182703182704182705182706182707182708182709182710182711182712182713182714182715182716182717182718182719182720182721182722182723182724182725182726182727182728182729182730182731182732182733182734182735182736182737182738182739182740182741182742182743182744182745182746182747182748182749182750182751182752182753182754182755182756182757182758182759182760182761182762182763182764182765182766182767182768182769182770182771182772182773182774182775182776182777182778182779182780182781182782182783182784182785182786182787182788182789182790182791182792182793182794182795182796182797182798182799182800182801182802182803182804182805182806182807182808182809182810182811182812182813182814182815182816182817182818182819182820182821182822182823182824182825182826182827182828182829182830182831182832182833182834182835182836182837182838182839182840182841182842182843182844182845182846182847182848182849182850182851182852182853182854182855182856182857182858182859182860182861182862182863182864182865182866182867182868182869182870182871182872182873182874182875182876182877182878182879182880182881182882182883182884182885182886182887182888182889182890182891182892182893182894182895182896182897182898182899182900182901182902182903182904182905182906182907182908182909182910182911182912182913182914182915182916182917182918182919182920182921182922182923182924182925182926182927182928182929182930182931182932182933182934182935182936182937182938182939182940182941182942182943182944182945182946182947182948182949182950182951182952182953182954182955182956182957182958182959182960182961182962182963182964182965182966182967182968182969182970182971182972182973182974182975182976182977182978182979182980182981182982182983182984182985182986182987182988182989182990182991182992182993182994182995182996182997182998182999183000183001183002183003183004183005183006183007183008183009183010183011183012183013183014183015183016183017183018183019183020183021183022183023183024183025183026183027183028183029183030183031183032183033183034183035183036183037183038183039183040183041183042183043183044183045183046183047183048183049183050183051183052183053183054183055183056183057183058183059183060183061183062183063183064183065183066183067183068183069183070183071183072183073183074183075183076183077183078183079183080183081183082183083183084183085183086183087183088183089183090183091183092183093183094183095183096183097183098183099183100183101183102183103183104183105183106183107183108183109183110183111183112183113183114183115183116183117183118183119183120183121183122183123183124183125183126183127183128183129183130183131183132183133183134183135183136183137183138183139183140183141183142183143183144183145183146183147183148183149183150183151183152183153183154183155183156183157183158183159183160183161183162183163183164183165183166183167183168183169183170183171183172183173183174183175183176183177183178183179183180183181183182183183183184183185183186183187183188183189183190183191183192183193183194183195183196183197183198183199183200183201183202183203183204183205183206183207183208183209183210183211183212183213183214183215183216183217183218183219183220183221183222183223183224183225183226183227183228183229183230183231183232183233183234183235183236183237183238183239183240183241183242183243183244183245183246183247183248183249183250183251183252183253183254183255183256183257183258183259183260183261183262183263183264183265183266183267183268183269183270183271183272183273183274183275183276183277183278183279183280183281183282183283183284183285183286183287183288183289183290183291183292183293183294183295183296183297183298183299183300183301183302183303183304183305183306183307183308183309183310183311183312183313183314183315183316183317183318183319183320183321183322183323183324183325183326183327183328183329183330183331183332183333183334183335183336183337183338183339183340183341183342183343183344183345183346183347183348183349183350183351183352183353183354183355183356183357183358183359183360183361183362183363183364183365183366183367183368183369183370183371183372183373183374183375183376183377183378183379183380183381183382183383183384183385183386183387183388183389183390183391183392183393183394183395183396183397183398183399183400183401183402183403183404183405183406183407183408183409183410183411183412183413183414183415183416183417183418183419183420183421183422183423183424183425183426183427183428183429183430183431183432183433183434183435183436183437183438183439183440183441183442183443183444183445183446183447183448183449183450183451183452183453183454183455183456183457183458183459183460183461183462183463183464183465183466183467183468183469183470183471183472183473183474183475183476183477183478183479183480183481183482183483183484183485183486183487183488183489183490183491183492183493183494183495183496183497183498183499183500183501183502183503183504183505183506183507183508183509183510183511183512183513183514183515183516183517183518183519183520183521183522183523183524183525183526183527183528183529183530183531183532183533183534183535183536183537183538183539183540183541183542183543183544183545183546183547183548183549183550183551183552183553183554183555183556183557183558183559183560183561183562183563183564183565183566183567183568183569183570183571183572183573183574183575183576183577183578183579183580183581183582183583183584183585183586183587183588183589183590183591183592183593183594183595183596183597183598183599183600183601183602183603183604183605183606183607183608183609183610183611183612183613183614183615183616183617183618183619183620183621183622183623183624183625183626183627183628183629183630183631183632183633183634183635183636183637183638183639183640183641183642183643183644183645183646183647183648183649183650183651183652183653183654183655183656183657183658183659183660183661183662183663183664183665183666183667183668183669183670183671183672183673183674183675183676183677183678183679183680183681183682183683183684183685183686183687183688183689183690183691183692183693183694183695183696183697183698183699183700183701183702183703183704183705183706183707183708183709183710183711183712183713183714183715183716183717183718183719183720183721183722183723183724183725183726183727183728183729183730183731183732183733183734183735183736183737183738183739183740183741183742183743183744183745183746183747183748183749183750183751183752183753183754183755183756183757183758183759183760183761183762183763183764183765183766183767183768183769183770183771183772183773183774183775183776183777183778183779183780183781183782183783183784183785183786183787183788183789183790183791183792183793183794183795183796183797183798183799183800183801183802183803183804183805183806183807183808183809183810183811183812183813183814183815183816183817183818183819183820183821183822183823183824183825183826183827183828183829183830183831183832183833183834183835183836183837183838183839183840183841183842183843183844183845183846183847183848183849183850183851183852183853183854183855183856183857183858183859183860183861183862183863183864183865183866183867183868183869183870183871183872183873183874183875183876183877183878183879183880183881183882183883183884183885183886183887183888183889183890183891183892183893183894183895183896183897183898183899183900183901183902183903183904183905183906183907183908183909183910183911183912183913183914183915183916183917183918183919183920183921183922183923183924183925183926183927183928183929183930183931183932183933183934183935183936183937183938183939183940183941183942183943183944183945183946183947183948183949183950183951183952183953183954183955183956183957183958183959183960183961183962183963183964183965183966183967183968183969183970183971183972183973183974183975183976183977183978183979183980183981183982183983183984183985183986183987183988183989183990183991183992183993183994183995183996183997183998183999184000184001184002184003184004184005184006184007184008184009184010184011184012184013184014184015184016184017184018184019184020184021184022184023184024184025184026184027184028184029184030184031184032184033184034184035184036184037184038184039184040184041184042184043184044184045184046184047184048184049184050184051184052184053184054184055184056184057184058184059184060184061184062184063184064184065184066184067184068184069184070184071184072184073184074184075184076184077184078184079184080184081184082184083184084184085184086184087184088184089184090184091184092184093184094184095184096184097184098184099184100184101184102184103184104184105184106184107184108184109184110184111184112184113184114184115184116184117184118184119184120184121184122184123184124184125184126184127184128184129184130184131184132184133184134184135184136184137184138184139184140184141184142184143184144184145184146184147184148184149184150184151184152184153184154184155184156184157184158184159184160184161184162184163184164184165184166184167184168184169184170184171184172184173184174184175184176184177184178184179184180184181184182184183184184184185184186184187184188184189184190184191184192184193184194184195184196184197184198184199184200184201184202184203184204184205184206184207184208184209184210184211184212184213184214184215184216184217184218184219184220184221184222184223184224184225184226184227184228184229184230184231184232184233184234184235184236184237184238184239184240184241184242184243184244184245184246184247184248184249184250184251184252184253184254184255184256184257184258184259184260184261184262184263184264184265184266184267184268184269184270184271184272184273184274184275184276184277184278184279184280184281184282184283184284184285184286184287184288184289184290184291184292184293184294184295184296184297184298184299184300184301184302184303184304184305184306184307184308184309184310184311184312184313184314184315184316184317184318184319184320184321184322184323184324184325184326184327184328184329184330184331184332184333184334184335184336184337184338184339184340184341184342184343184344184345184346184347184348184349184350184351184352184353184354184355184356184357184358184359184360184361184362184363184364184365184366184367184368184369184370184371184372184373184374184375184376184377184378184379184380184381184382184383184384184385184386184387184388184389184390184391184392184393184394184395184396184397184398184399184400184401184402184403184404184405184406184407184408184409184410184411184412184413184414184415184416184417184418184419184420184421184422184423184424184425184426184427184428184429184430184431184432184433184434184435184436184437184438184439184440184441184442184443184444184445184446184447184448184449184450184451184452184453184454184455184456184457184458184459184460184461184462184463184464184465184466184467184468184469184470184471184472184473184474184475184476184477184478184479184480184481184482184483184484184485184486184487184488184489184490184491184492184493184494184495184496184497184498184499184500184501184502184503184504184505184506184507184508184509184510184511184512184513184514184515184516184517184518184519184520184521184522184523184524184525184526184527184528184529184530184531184532184533184534184535184536184537184538184539184540184541184542184543184544184545184546184547184548184549184550184551184552184553184554184555184556184557184558184559184560184561184562184563184564184565184566184567184568184569184570184571184572184573184574184575184576184577184578184579184580184581184582184583184584184585184586184587184588184589184590184591184592184593184594184595184596184597184598184599184600184601184602184603184604184605184606184607184608184609184610184611184612184613184614184615184616184617184618184619184620184621184622184623184624184625184626184627184628184629184630184631184632184633184634184635184636184637184638184639184640184641184642184643184644184645184646184647184648184649184650184651184652184653184654184655184656184657184658184659184660184661184662184663184664184665184666184667184668184669184670184671184672184673184674184675184676184677184678184679184680184681184682184683184684184685184686184687184688184689184690184691184692184693184694184695184696184697184698184699184700184701184702184703184704184705184706184707184708184709184710184711184712184713184714184715184716184717184718184719184720184721184722184723184724184725184726184727184728184729184730184731184732184733184734184735184736184737184738184739184740184741184742184743184744184745184746184747184748184749184750184751184752184753184754184755184756184757184758184759184760184761184762184763184764184765184766184767184768184769184770184771184772184773184774184775184776184777184778184779184780184781184782184783184784184785184786184787184788184789184790184791184792184793184794184795184796184797184798184799184800184801184802184803184804184805184806184807184808184809184810184811184812184813184814184815184816184817184818184819184820184821184822184823184824184825184826184827184828184829184830184831184832184833184834184835184836184837184838184839184840184841184842184843184844184845184846184847184848184849184850184851184852184853184854184855184856184857184858184859184860184861184862184863184864184865184866184867184868184869184870184871184872184873184874184875184876184877184878184879184880184881184882184883184884184885184886184887184888184889184890184891184892184893184894184895184896184897184898184899184900184901184902184903184904184905184906184907184908184909184910184911184912184913184914184915184916184917184918184919184920184921184922184923184924184925184926184927184928184929184930184931184932184933184934184935184936184937184938184939184940184941184942184943184944184945184946184947184948184949184950184951184952184953184954184955184956184957184958184959184960184961184962184963184964184965184966184967184968184969184970184971184972184973184974184975184976184977184978184979184980184981184982184983184984184985184986184987184988184989184990184991184992184993184994184995184996184997184998184999185000185001185002185003185004185005185006185007185008185009185010185011185012185013185014185015185016185017185018185019185020185021185022185023185024185025185026185027185028185029185030185031185032185033185034185035185036185037185038185039185040185041185042185043185044185045185046185047185048185049185050185051185052185053185054185055185056185057185058185059185060185061185062185063185064185065185066185067185068185069185070185071185072185073185074185075185076185077185078185079185080185081185082185083185084185085185086185087185088185089185090185091185092185093185094185095185096185097185098185099185100185101185102185103185104185105185106185107185108185109185110185111185112185113185114185115185116185117185118185119185120185121185122185123185124185125185126185127185128185129185130185131185132185133185134185135185136185137185138185139185140185141185142185143185144185145185146185147185148185149185150185151185152185153185154185155185156185157185158185159185160185161185162185163185164185165185166185167185168185169185170185171185172185173185174185175185176185177185178185179185180185181185182185183185184185185185186185187185188185189185190185191185192185193185194185195185196185197185198185199185200185201185202185203185204185205185206185207185208185209185210185211185212185213185214185215185216185217185218185219185220185221185222185223185224185225185226185227185228185229185230185231185232185233185234185235185236185237185238185239185240185241185242185243185244185245185246185247185248185249185250185251185252185253185254185255185256185257185258185259185260185261185262185263185264185265185266185267185268185269185270185271185272185273185274185275185276185277185278185279185280185281185282185283185284185285185286185287185288185289185290185291185292185293185294185295185296185297185298185299185300185301185302185303185304185305185306185307185308185309185310185311185312185313185314185315185316185317185318185319185320185321185322185323185324185325185326185327185328185329185330185331185332185333185334185335185336185337185338185339185340185341185342185343185344185345185346185347185348185349185350185351185352185353185354185355185356185357185358185359185360185361185362185363185364185365185366185367185368185369185370185371185372185373185374185375185376185377185378185379185380185381185382185383185384185385185386185387185388185389185390185391185392185393185394185395185396185397185398185399185400185401185402185403185404185405185406185407185408185409185410185411185412185413185414185415185416185417185418185419185420185421185422185423185424185425185426185427185428185429185430185431185432185433185434185435185436185437185438185439185440185441185442185443185444185445185446185447185448185449185450185451185452185453185454185455185456185457185458185459185460185461185462185463185464185465185466185467185468185469185470185471185472185473185474185475185476185477185478185479185480185481185482185483185484185485185486185487185488185489185490185491185492185493185494185495185496185497185498185499185500185501185502185503185504185505185506185507185508185509185510185511185512185513185514185515185516185517185518185519185520185521185522185523185524185525185526185527185528185529185530185531185532185533185534185535185536185537185538185539185540185541185542185543185544185545185546185547185548185549185550185551185552185553185554185555185556185557185558185559185560185561185562185563185564185565185566185567185568185569185570185571185572185573185574185575185576185577185578185579185580185581185582185583185584185585185586185587185588185589185590185591185592185593185594185595185596185597185598185599185600185601185602185603185604185605185606185607185608185609185610185611185612185613185614185615185616185617185618185619185620185621185622185623185624185625185626185627185628185629185630185631185632185633185634185635185636185637185638185639185640185641185642185643185644185645185646185647185648185649185650185651185652185653185654185655185656185657185658185659185660185661185662185663185664185665185666185667185668185669185670185671185672185673185674185675185676185677185678185679185680185681185682185683185684185685185686185687185688185689185690185691185692185693185694185695185696185697185698185699185700185701185702185703185704185705185706185707185708185709185710185711185712185713185714185715185716185717185718185719185720185721185722185723185724185725185726185727185728185729185730185731185732185733185734185735185736185737185738185739185740185741185742185743185744185745185746185747185748185749185750185751185752185753185754185755185756185757185758185759185760185761185762185763185764185765185766185767185768185769185770185771185772185773185774185775185776185777185778185779185780185781185782185783185784185785185786185787185788185789185790185791185792185793185794185795185796185797185798185799185800185801185802185803185804185805185806185807185808185809185810185811185812185813185814185815185816185817185818185819185820185821185822185823185824185825185826185827185828185829185830185831185832185833185834185835185836185837185838185839185840185841185842185843185844185845185846185847185848185849185850185851185852185853185854185855185856185857185858185859185860185861185862185863185864185865185866185867185868185869185870185871185872185873185874185875185876185877185878185879185880185881185882185883185884185885185886185887185888185889185890185891185892185893185894185895185896185897185898185899185900185901185902185903185904185905185906185907185908185909185910185911185912185913185914185915185916185917185918185919185920185921185922185923185924185925185926185927185928185929185930185931185932185933185934185935185936185937185938185939185940185941185942185943185944185945185946185947185948185949185950185951185952185953185954185955185956185957185958185959185960185961185962185963185964185965185966185967185968185969185970185971185972185973185974185975185976185977185978185979185980185981185982185983185984185985185986185987185988185989185990185991185992185993185994185995185996185997185998185999186000186001186002186003186004186005186006186007186008186009186010186011186012186013186014186015186016186017186018186019186020186021186022186023186024186025186026186027186028186029186030186031186032186033186034186035186036186037186038186039186040186041186042186043186044186045186046186047186048186049186050186051186052186053186054186055186056186057186058186059186060186061186062186063186064186065186066186067186068186069186070186071186072186073186074186075186076186077186078186079186080186081186082186083186084186085186086186087186088186089186090186091186092186093186094186095186096186097186098186099186100186101186102186103186104186105186106186107186108186109186110186111186112186113186114186115186116186117186118186119186120186121186122186123186124186125186126186127186128186129186130186131186132186133186134186135186136186137186138186139186140186141186142186143186144186145186146186147186148186149186150186151186152186153186154186155186156186157186158186159186160186161186162186163186164186165186166186167186168186169186170186171186172186173186174186175186176186177186178186179186180186181186182186183186184186185186186186187186188186189186190186191186192186193186194186195186196186197186198186199186200186201186202186203186204186205186206186207186208186209186210186211186212186213186214186215186216186217186218186219186220186221186222186223186224186225186226186227186228186229186230186231186232186233186234186235186236186237186238186239186240186241186242186243186244186245186246186247186248186249186250186251186252186253186254186255186256186257186258186259186260186261186262186263186264186265186266186267186268186269186270186271186272186273186274186275186276186277186278186279186280186281186282186283186284186285186286186287186288186289186290186291186292186293186294186295186296186297186298186299186300186301186302186303186304186305186306186307186308186309186310186311186312186313186314186315186316186317186318186319186320186321186322186323186324186325186326186327186328186329186330186331186332186333186334186335186336186337186338186339186340186341186342186343186344186345186346186347186348186349186350186351186352186353186354186355186356186357186358186359186360186361186362186363186364186365186366186367186368186369186370186371186372186373186374186375186376186377186378186379186380186381186382186383186384186385186386186387186388186389186390186391186392186393186394186395186396186397186398186399186400186401186402186403186404186405186406186407186408186409186410186411186412186413186414186415186416186417186418186419186420186421186422186423186424186425186426186427186428186429186430186431186432186433186434186435186436186437186438186439186440186441186442186443186444186445186446186447186448186449186450186451186452186453186454186455186456186457186458186459186460186461186462186463186464186465186466186467186468186469186470186471186472186473186474186475186476186477186478186479186480186481186482186483186484186485186486186487186488186489186490186491186492186493186494186495186496186497186498186499186500186501186502186503186504186505186506186507186508186509186510186511186512186513186514186515186516186517186518186519186520186521186522186523186524186525186526186527186528186529186530186531186532186533186534186535186536186537186538186539186540186541186542186543186544186545186546186547186548186549186550186551186552186553186554186555186556186557186558186559186560186561186562186563186564186565186566186567186568186569186570186571186572186573186574186575186576186577186578186579186580186581186582186583186584186585186586186587186588186589186590186591186592186593186594186595186596186597186598186599186600186601186602186603186604186605186606186607186608186609186610186611186612186613186614186615186616186617186618186619186620186621186622186623186624186625186626186627186628186629186630186631186632186633186634186635186636186637186638186639186640186641186642186643186644186645186646186647186648186649186650186651186652186653186654186655186656186657186658186659186660186661186662186663186664186665186666186667186668186669186670186671186672186673186674186675186676186677186678186679186680186681186682186683186684186685186686186687186688186689186690186691186692186693186694186695186696186697186698186699186700186701186702186703186704186705186706186707186708186709186710186711186712186713186714186715186716186717186718186719186720186721186722186723186724186725186726186727186728186729186730186731186732186733186734186735186736186737186738186739186740186741186742186743186744186745186746186747186748186749186750186751186752186753186754186755186756186757186758186759186760186761186762186763186764186765186766186767186768186769186770186771186772186773186774186775186776186777186778186779186780186781186782186783186784186785186786186787186788186789186790186791186792186793186794186795186796186797186798186799186800186801186802186803186804186805186806186807186808186809186810186811186812186813186814186815186816186817186818186819186820186821186822186823186824186825186826186827186828186829186830186831186832186833186834186835186836186837186838186839186840186841186842186843186844186845186846186847186848186849186850186851186852186853186854186855186856186857186858186859186860186861186862186863186864186865186866186867186868186869186870186871186872186873186874186875186876186877186878186879186880186881186882186883186884186885186886186887186888186889186890186891186892186893186894186895186896186897186898186899186900186901186902186903186904186905186906186907186908186909186910186911186912186913186914186915186916186917186918186919186920186921186922186923186924186925186926186927186928186929186930186931186932186933186934186935186936186937186938186939186940186941186942186943186944186945186946186947186948186949186950186951186952186953186954186955186956186957186958186959186960186961186962186963186964186965186966186967186968186969186970186971186972186973186974186975186976186977186978186979186980186981186982186983186984186985186986186987186988186989186990186991186992186993186994186995186996186997186998186999187000187001187002187003187004187005187006187007187008187009187010187011187012187013187014187015187016187017187018187019187020187021187022187023187024187025187026187027187028187029187030187031187032187033187034187035187036187037187038187039187040187041187042187043187044187045187046187047187048187049187050187051187052187053187054187055187056187057187058187059187060187061187062187063187064187065187066187067187068187069187070187071187072187073187074187075187076187077187078187079187080187081187082187083187084187085187086187087187088187089187090187091187092187093187094187095187096187097187098187099187100187101187102187103187104187105187106187107187108187109187110187111187112187113187114187115187116187117187118187119187120187121187122187123187124187125187126187127187128187129187130187131187132187133187134187135187136187137187138187139187140187141187142187143187144187145187146187147187148187149187150187151187152187153187154187155187156187157187158187159187160187161187162187163187164187165187166187167187168187169187170187171187172187173187174187175187176187177187178187179187180187181187182187183187184187185187186187187187188187189187190187191187192187193187194187195187196187197187198187199187200187201187202187203187204187205187206187207187208187209187210187211187212187213187214187215187216187217187218187219187220187221187222187223187224187225187226187227187228187229187230187231187232187233187234187235187236187237187238187239187240187241187242187243187244187245187246187247187248187249187250187251187252187253187254187255187256187257187258187259187260187261187262187263187264187265187266187267187268187269187270187271187272187273187274187275187276187277187278187279187280187281187282187283187284187285187286187287187288187289187290187291187292187293187294187295187296187297187298187299187300187301187302187303187304187305187306187307187308187309187310187311187312187313187314187315187316187317187318187319187320187321187322187323187324187325187326187327187328187329187330187331187332187333187334187335187336187337187338187339187340187341187342187343187344187345187346187347187348187349187350187351187352187353187354187355187356187357187358187359187360187361187362187363187364187365187366187367187368187369187370187371187372187373187374187375187376187377187378187379187380187381187382187383187384187385187386187387187388187389187390187391187392187393187394187395187396187397187398187399187400187401187402187403187404187405187406187407187408187409187410187411187412187413187414187415187416187417187418187419187420187421187422187423187424187425187426187427187428187429187430187431187432187433187434187435187436187437187438187439187440187441187442187443187444187445187446187447187448187449187450187451187452187453187454187455187456187457187458187459187460187461187462187463187464187465187466187467187468187469187470187471187472187473187474187475187476187477187478187479187480187481187482187483187484187485187486187487187488187489187490187491187492187493187494187495187496187497187498187499187500187501187502187503187504187505187506187507187508187509187510187511187512187513187514187515187516187517187518187519187520187521187522187523187524187525187526187527187528187529187530187531187532187533187534187535187536187537187538187539187540187541187542187543187544187545187546187547187548187549187550187551187552187553187554187555187556187557187558187559187560187561187562187563187564187565187566187567187568187569187570187571187572187573187574187575187576187577187578187579187580187581187582187583187584187585187586187587187588187589187590187591187592187593187594187595187596187597187598187599187600187601187602187603187604187605187606187607187608187609187610187611187612187613187614187615187616187617187618187619187620187621187622187623187624187625187626187627187628187629187630187631187632187633187634187635187636187637187638187639187640187641187642187643187644187645187646187647187648187649187650187651187652187653187654187655187656187657187658187659187660187661187662187663187664187665187666187667187668187669187670187671187672187673187674187675187676187677187678187679187680187681187682187683187684187685187686187687187688187689187690187691187692187693187694187695187696187697187698187699187700187701187702187703187704187705187706187707187708187709187710187711187712187713187714187715187716187717187718187719187720187721187722187723187724187725187726187727187728187729187730187731187732187733187734187735187736187737187738187739187740187741187742187743187744187745187746187747187748187749187750187751187752187753187754187755187756187757187758187759187760187761187762187763187764187765187766187767187768187769187770187771187772187773187774187775187776187777187778187779187780187781187782187783187784187785187786187787187788187789187790187791187792187793187794187795187796187797187798187799187800187801187802187803187804187805187806187807187808187809187810187811187812187813187814187815187816187817187818187819187820187821187822187823187824187825187826187827187828187829187830187831187832187833187834187835187836187837187838187839187840187841187842187843187844187845187846187847187848187849187850187851187852187853187854187855187856187857187858187859187860187861187862187863187864187865187866187867187868187869187870187871187872187873187874187875187876187877187878187879187880187881187882187883187884187885187886187887187888187889187890187891187892187893187894187895187896187897187898187899187900187901187902187903187904187905187906187907187908187909187910187911187912187913187914187915187916187917187918187919187920187921187922187923187924187925187926187927187928187929187930187931187932187933187934187935187936187937187938187939187940187941187942187943187944187945187946187947187948187949187950187951187952187953187954187955187956187957187958187959187960187961187962187963187964187965187966187967187968187969187970187971187972187973187974187975187976187977187978187979187980187981187982187983187984187985187986187987187988187989187990187991187992187993187994187995187996187997187998187999188000188001188002188003188004188005188006188007188008188009188010188011188012188013188014188015188016188017188018188019188020188021188022188023188024188025188026188027188028188029188030188031188032188033188034188035188036188037188038188039188040188041188042188043188044188045188046188047188048188049188050188051188052188053188054188055188056188057188058188059188060188061188062188063188064188065188066188067188068188069188070188071188072188073188074188075188076188077188078188079188080188081188082188083188084188085188086188087188088188089188090188091188092188093188094188095188096188097188098188099188100188101188102188103188104188105188106188107188108188109188110188111188112188113188114188115188116188117188118188119188120188121188122188123188124188125188126188127188128188129188130188131188132188133188134188135188136188137188138188139188140188141188142188143188144188145188146188147188148188149188150188151188152188153188154188155188156188157188158188159188160188161188162188163188164188165188166188167188168188169188170188171188172188173188174188175188176188177188178188179188180188181188182188183188184188185188186188187188188188189188190188191188192188193188194188195188196188197188198188199188200188201188202188203188204188205188206188207188208188209188210188211188212188213188214188215188216188217188218188219188220188221188222188223188224188225188226188227188228188229188230188231188232188233188234188235188236188237188238188239188240188241188242188243188244188245188246188247188248188249188250188251188252188253188254188255188256188257188258188259188260188261188262188263188264188265188266188267188268188269188270188271188272188273188274188275188276188277188278188279188280188281188282188283188284188285188286188287188288188289188290188291188292188293188294188295188296188297188298188299188300188301188302188303188304188305188306188307188308188309188310188311188312188313188314188315188316188317188318188319188320188321188322188323188324188325188326188327188328188329188330188331188332188333188334188335188336188337188338188339188340188341188342188343188344188345188346188347188348188349188350188351188352188353188354188355188356188357188358188359188360188361188362188363188364188365188366188367188368188369188370188371188372188373188374188375188376188377188378188379188380188381188382188383188384188385188386188387188388188389188390188391188392188393188394188395188396188397188398188399188400188401188402188403188404188405188406188407188408188409188410188411188412188413188414188415188416188417188418188419188420188421188422188423188424188425188426188427188428188429188430188431188432188433188434188435188436188437188438188439188440188441188442188443188444188445188446188447188448188449188450188451188452188453188454188455188456188457188458188459188460188461188462188463188464188465188466188467188468188469188470188471188472188473188474188475188476188477188478188479188480188481188482188483188484188485188486188487188488188489188490188491188492188493188494188495188496188497188498188499188500188501188502188503188504188505188506188507188508188509188510188511188512188513188514188515188516188517188518188519188520188521188522188523188524188525188526188527188528188529188530188531188532188533188534188535188536188537188538188539188540188541188542188543188544188545188546188547188548188549188550188551188552188553188554188555188556188557188558188559188560188561188562188563188564188565188566188567188568188569188570188571188572188573188574188575188576188577188578188579188580188581188582188583188584188585188586188587188588188589188590188591188592188593188594188595188596188597188598188599188600188601188602188603188604188605188606188607188608188609188610188611188612188613188614188615188616188617188618188619188620188621188622188623188624188625188626188627188628188629188630188631188632188633188634188635188636188637188638188639188640188641188642188643188644188645188646188647188648188649188650188651188652188653188654188655188656188657188658188659188660188661188662188663188664188665188666188667188668188669188670188671188672188673188674188675188676188677188678188679188680188681188682188683188684188685188686188687188688188689188690188691188692188693188694188695188696188697188698188699188700188701188702188703188704188705188706188707188708188709188710188711188712188713188714188715188716188717188718188719188720188721188722188723188724188725188726188727188728188729188730188731188732188733188734188735188736188737188738188739188740188741188742188743188744188745188746188747188748188749188750188751188752188753188754188755188756188757188758188759188760188761188762188763188764188765188766188767188768188769188770188771188772188773188774188775188776188777188778188779188780188781188782188783188784188785188786188787188788188789188790188791188792188793188794188795188796188797188798188799188800188801188802188803188804188805188806188807188808188809188810188811188812188813188814188815188816188817188818188819188820188821188822188823188824188825188826188827188828188829188830188831188832188833188834188835188836188837188838188839188840188841188842188843188844188845188846188847188848188849188850188851188852188853188854188855188856188857188858188859188860188861188862188863188864188865188866188867188868188869188870188871188872188873188874188875188876188877188878188879188880188881188882188883188884188885188886188887188888188889188890188891188892188893188894188895188896188897188898188899188900188901188902188903188904188905188906188907188908188909188910188911188912188913188914188915188916188917188918188919188920188921188922188923188924188925188926188927188928188929188930188931188932188933188934188935188936188937188938188939188940188941188942188943188944188945188946188947188948188949188950188951188952188953188954188955188956188957188958188959188960188961188962188963188964188965188966188967188968188969188970188971188972188973188974188975188976188977188978188979188980188981188982188983188984188985188986188987188988188989188990188991188992188993188994188995188996188997188998188999189000189001189002189003189004189005189006189007189008189009189010189011189012189013189014189015189016189017189018189019189020189021189022189023189024189025189026189027189028189029189030189031189032189033189034189035189036189037189038189039189040189041189042189043189044189045189046189047189048189049189050189051189052189053189054189055189056189057189058189059189060189061189062189063189064189065189066189067189068189069189070189071189072189073189074189075189076189077189078189079189080189081189082189083189084189085189086189087189088189089189090189091189092189093189094189095189096189097189098189099189100189101189102189103189104189105189106189107189108189109189110189111189112189113189114189115189116189117189118189119189120189121189122189123189124189125189126189127189128189129189130189131189132189133189134189135189136189137189138189139189140189141189142189143189144189145189146189147189148189149189150189151189152189153189154189155189156189157189158189159189160189161189162189163189164189165189166189167189168189169189170189171189172189173189174189175189176189177189178189179189180189181189182189183189184189185189186189187189188189189189190189191189192189193189194189195189196189197189198189199189200189201189202189203189204189205189206189207189208189209189210189211189212189213189214189215189216189217189218189219189220189221189222189223189224189225189226189227189228189229189230189231189232189233189234189235189236189237189238189239189240189241189242189243189244189245189246189247189248189249189250189251189252189253189254189255189256189257189258189259189260189261189262189263189264189265189266189267189268189269189270189271189272189273189274189275189276189277189278189279189280189281189282189283189284189285189286189287189288189289189290189291189292189293189294189295189296189297189298189299189300189301189302189303189304189305189306189307189308189309189310189311189312189313189314189315189316189317189318189319189320189321189322189323189324189325189326189327189328189329189330189331189332189333189334189335189336189337189338189339189340189341189342189343189344189345189346189347189348189349189350189351189352189353189354189355189356189357189358189359189360189361189362189363189364189365189366189367189368189369189370189371189372189373189374189375189376189377189378189379189380189381189382189383189384189385189386189387189388189389189390189391189392189393189394189395189396189397189398189399189400189401189402189403189404189405189406189407189408189409189410189411189412189413189414189415189416189417189418189419189420189421189422189423189424189425189426189427189428189429189430189431189432189433189434189435189436189437189438189439189440189441189442189443189444189445189446189447189448189449189450189451189452189453189454189455189456189457189458189459189460189461189462189463189464189465189466189467189468189469189470189471189472189473189474189475189476189477189478189479189480189481189482189483189484189485189486189487189488189489189490189491189492189493189494189495189496189497189498189499189500189501189502189503189504189505189506189507189508189509189510189511189512189513189514189515189516189517189518189519189520189521189522189523189524189525189526189527189528189529189530189531189532189533189534189535189536189537189538189539189540189541189542189543189544189545189546189547189548189549189550189551189552189553189554189555189556189557189558189559189560189561189562189563189564189565189566189567189568189569189570189571189572189573189574189575189576189577189578189579189580189581189582189583189584189585189586189587189588189589189590189591189592189593189594189595189596189597189598189599189600189601189602189603189604189605189606189607189608189609189610189611189612189613189614189615189616189617189618189619189620189621189622189623189624189625189626189627189628189629189630189631189632189633189634189635189636189637189638189639189640189641189642189643189644189645189646189647189648189649189650189651189652189653189654189655189656189657189658189659189660189661189662189663189664189665189666189667189668189669189670189671189672189673189674189675189676189677189678189679189680189681189682189683189684189685189686189687189688189689189690189691189692189693189694189695189696189697189698189699189700189701189702189703189704189705189706189707189708189709189710189711189712189713189714189715189716189717189718189719189720189721189722189723189724189725189726189727189728189729189730189731189732189733189734189735189736189737189738189739189740189741189742189743189744189745189746189747189748189749189750189751189752189753189754189755189756189757189758189759189760189761189762189763189764189765189766189767189768189769189770189771189772189773189774189775189776189777189778189779189780189781189782189783189784189785189786189787189788189789189790189791189792189793189794189795189796189797189798189799189800189801189802189803189804189805189806189807189808189809189810189811189812189813189814189815189816189817189818189819189820189821189822189823189824189825189826189827189828189829189830189831189832189833189834189835189836189837189838189839189840189841189842189843189844189845189846189847189848189849189850189851189852189853189854189855189856189857189858189859189860189861189862189863189864189865189866189867189868189869189870189871189872189873189874189875189876189877189878189879189880189881189882189883189884189885189886189887189888189889189890189891189892189893189894189895189896189897189898189899189900189901189902189903189904189905189906189907189908189909189910189911189912189913189914189915189916189917189918189919189920189921189922189923189924189925189926189927189928189929189930189931189932189933189934189935189936189937189938189939189940189941189942189943189944189945189946189947189948189949189950189951189952189953189954189955189956189957189958189959189960189961189962189963189964189965189966189967189968189969189970189971189972189973189974189975189976189977189978189979189980189981189982189983189984189985189986189987189988189989189990189991189992189993189994189995189996189997189998189999190000190001190002190003190004190005190006190007190008190009190010190011190012190013190014190015190016190017190018190019190020190021190022190023190024190025190026190027190028190029190030190031190032190033190034190035190036190037190038190039190040190041190042190043190044190045190046190047190048190049190050190051190052190053190054190055190056190057190058190059190060190061190062190063190064190065190066190067190068190069190070190071190072190073190074190075190076190077190078190079190080190081190082190083190084190085190086190087190088190089190090190091190092190093190094190095190096190097190098190099190100190101190102190103190104190105190106190107190108190109190110190111190112190113190114190115190116190117190118190119190120190121190122190123190124190125190126190127190128190129190130190131190132190133190134190135190136190137190138190139190140190141190142190143190144190145190146190147190148190149190150190151190152190153190154190155190156190157190158190159190160190161190162190163190164190165190166190167190168190169190170190171190172190173190174190175190176190177190178190179190180190181190182190183190184190185190186190187190188190189190190190191190192190193190194190195190196190197190198190199190200190201190202190203190204190205190206190207190208190209190210190211190212190213190214190215190216190217190218190219190220190221190222190223190224190225190226190227190228190229190230190231190232190233190234190235190236190237190238190239190240190241190242190243190244190245190246190247190248190249190250190251190252190253190254190255190256190257190258190259190260190261190262190263190264190265190266190267190268190269190270190271190272190273190274190275190276190277190278190279190280190281190282190283190284190285190286190287190288190289190290190291190292190293190294190295190296190297190298190299190300190301190302190303190304190305190306190307190308190309190310190311190312190313190314190315190316190317190318190319190320190321190322190323190324190325190326190327190328190329190330190331190332190333190334190335190336190337190338190339190340190341190342190343190344190345190346190347190348190349190350190351190352190353190354190355190356190357190358190359190360190361190362190363190364190365190366190367190368190369190370190371190372190373190374190375190376190377190378190379190380190381190382190383190384190385190386190387190388190389190390190391190392190393190394190395190396190397190398190399190400190401190402190403190404190405190406190407190408190409190410190411190412190413190414190415190416190417190418190419190420190421190422190423190424190425190426190427190428190429190430190431190432190433190434190435190436190437190438190439190440190441190442190443190444190445190446190447190448190449190450190451190452190453190454190455190456190457190458190459190460190461190462190463190464190465190466190467190468190469190470190471190472190473190474190475190476190477190478190479190480190481190482190483190484190485190486190487190488190489190490190491190492190493190494190495190496190497190498190499190500190501190502190503190504190505190506190507190508190509190510190511190512190513190514190515190516190517190518190519190520190521190522190523190524190525190526190527190528190529190530190531190532190533190534190535190536190537190538190539190540190541190542190543190544190545190546190547190548190549190550190551190552190553190554190555190556190557190558190559190560190561190562190563190564190565190566190567190568190569190570190571190572190573190574190575190576190577190578190579190580190581190582190583190584190585190586190587190588190589190590190591190592190593190594190595190596190597190598190599190600190601190602190603190604190605190606190607190608190609190610190611190612190613190614190615190616190617190618190619190620190621190622190623190624190625190626190627190628190629190630190631190632190633190634190635190636190637190638190639190640190641190642190643190644190645190646190647190648190649190650190651190652190653190654190655190656190657190658190659190660190661190662190663190664190665190666190667190668190669190670190671190672190673190674190675190676190677190678190679190680190681190682190683190684190685190686190687190688190689190690190691190692190693190694190695190696190697190698190699190700190701190702190703190704190705190706190707190708190709190710190711190712190713190714190715190716190717190718190719190720190721190722190723190724190725190726190727190728190729190730190731190732190733190734190735190736190737190738190739190740190741190742190743190744190745190746190747190748190749190750190751190752190753190754190755190756190757190758190759190760190761190762190763190764190765190766190767190768190769190770190771190772190773190774190775190776190777190778190779190780190781190782190783190784190785190786190787190788190789190790190791190792190793190794190795190796190797190798190799190800190801190802190803190804190805190806190807190808190809190810190811190812190813190814190815190816190817190818190819190820190821190822190823190824190825190826190827190828190829190830190831190832190833190834190835190836190837190838190839190840190841190842190843190844190845190846190847190848190849190850190851190852190853190854190855190856190857190858190859190860190861190862190863190864190865190866190867190868190869190870190871190872190873190874190875190876190877190878190879190880190881190882190883190884190885190886190887190888190889190890190891190892190893190894190895190896190897190898190899190900190901190902190903190904190905190906190907190908190909190910190911190912190913190914190915190916190917190918190919190920190921190922190923190924190925190926190927190928190929190930190931190932190933190934190935190936190937190938190939190940190941190942190943190944190945190946190947190948190949190950190951190952190953190954190955190956190957190958190959190960190961190962190963190964190965190966190967190968190969190970190971190972190973190974190975190976190977190978190979190980190981190982190983190984190985190986190987190988190989190990190991190992190993190994190995190996190997190998190999191000191001191002191003191004191005191006191007191008191009191010191011191012191013191014191015191016191017191018191019191020191021191022191023191024191025191026191027191028191029191030191031191032191033191034191035191036191037191038191039191040191041191042191043191044191045191046191047191048191049191050191051191052191053191054191055191056191057191058191059191060191061191062191063191064191065191066191067191068191069191070191071191072191073191074191075191076191077191078191079191080191081191082191083191084191085191086191087191088191089191090191091191092191093191094191095191096191097191098191099191100191101191102191103191104191105191106191107191108191109191110191111191112191113191114191115191116191117191118191119191120191121191122191123191124191125191126191127191128191129191130191131191132191133191134191135191136191137191138191139191140191141191142191143191144191145191146191147191148191149191150191151191152191153191154191155191156191157191158191159191160191161191162191163191164191165191166191167191168191169191170191171191172191173191174191175191176191177191178191179191180191181191182191183191184191185191186191187191188191189191190191191191192191193191194191195191196191197191198191199191200191201191202191203191204191205191206191207191208191209191210191211191212191213191214191215191216191217191218191219191220191221191222191223191224191225191226191227191228191229191230191231191232191233191234191235191236191237191238191239191240191241191242191243191244191245191246191247191248191249191250191251191252191253191254191255191256191257191258191259191260191261191262191263191264191265191266191267191268191269191270191271191272191273191274191275191276191277191278191279191280191281191282191283191284191285191286191287191288191289191290191291191292191293191294191295191296191297191298191299191300191301191302191303191304191305191306191307191308191309191310191311191312191313191314191315191316191317191318191319191320191321191322191323191324191325191326191327191328191329191330191331191332191333191334191335191336191337191338191339191340191341191342191343191344191345191346191347191348191349191350191351191352191353191354191355191356191357191358191359191360191361191362191363191364191365191366191367191368191369191370191371191372191373191374191375191376191377191378191379191380191381191382191383191384191385191386191387191388191389191390191391191392191393191394191395191396191397191398191399191400191401191402191403191404191405191406191407191408191409191410191411191412191413191414191415191416191417191418191419191420191421191422191423191424191425191426191427191428191429191430191431191432191433191434191435191436191437191438191439191440191441191442191443191444191445191446191447191448191449191450191451191452191453191454191455191456191457191458191459191460191461191462191463191464191465191466191467191468191469191470191471191472191473191474191475191476191477191478191479191480191481191482191483191484191485191486191487191488191489191490191491191492191493191494191495191496191497191498191499191500191501191502191503191504191505191506191507191508191509191510191511191512191513191514191515191516191517191518191519191520191521191522191523191524191525191526191527191528191529191530191531191532191533191534191535191536191537191538191539191540191541191542191543191544191545191546191547191548191549191550191551191552191553191554191555191556191557191558191559191560191561191562191563191564191565191566191567191568191569191570191571191572191573191574191575191576191577191578191579191580191581191582191583191584191585191586191587191588191589191590191591191592191593191594191595191596191597191598191599191600191601191602191603191604191605191606191607191608191609191610191611191612191613191614191615191616191617191618191619191620191621191622191623191624191625191626191627191628191629191630191631191632191633191634191635191636191637191638191639191640191641191642191643191644191645191646191647191648191649191650191651191652191653191654191655191656191657191658191659191660191661191662191663191664191665191666191667191668191669191670191671191672191673191674191675191676191677191678191679191680191681191682191683191684191685191686191687191688191689191690191691191692191693191694191695191696191697191698191699191700191701191702191703191704191705191706191707191708191709191710191711191712191713191714191715191716191717191718191719191720191721191722191723191724191725191726191727191728191729191730191731191732191733191734191735191736191737191738191739191740191741191742191743191744191745191746191747191748191749191750191751191752191753191754191755191756191757191758191759191760191761191762191763191764191765191766191767191768191769191770191771191772191773191774191775191776191777191778191779191780191781191782191783191784191785191786191787191788191789191790191791191792191793191794191795191796191797191798191799191800191801191802191803191804191805191806191807191808191809191810191811191812191813191814191815191816191817191818191819191820191821191822191823191824191825191826191827191828191829191830191831191832191833191834191835191836191837191838191839191840191841191842191843191844191845191846191847191848191849191850191851191852191853191854191855191856191857191858191859191860191861191862191863191864191865191866191867191868191869191870191871191872191873191874191875191876191877191878191879191880191881191882191883191884191885191886191887191888191889191890191891191892191893191894191895191896191897191898191899191900191901191902191903191904191905191906191907191908191909191910191911191912191913191914191915191916191917191918191919191920191921191922191923191924191925191926191927191928191929191930191931191932191933191934191935191936191937191938191939191940191941191942191943191944191945191946191947191948191949191950191951191952191953191954191955191956191957191958191959191960191961191962191963191964191965191966191967191968191969191970191971191972191973191974191975191976191977191978191979191980191981191982191983191984191985191986191987191988191989191990191991191992191993191994191995191996191997191998191999192000192001192002192003192004192005192006192007192008192009192010192011192012192013192014192015192016192017192018192019192020192021192022192023192024192025192026192027192028192029192030192031192032192033192034192035192036192037192038192039192040192041192042192043192044192045192046192047192048192049192050192051192052192053192054192055192056192057192058192059192060192061192062192063192064192065192066192067192068192069192070192071192072192073192074192075192076192077192078192079192080192081192082192083192084192085192086192087192088192089192090192091192092192093192094192095192096192097192098192099192100192101192102192103192104192105192106192107192108192109192110192111192112192113192114192115192116192117192118192119192120192121192122192123192124192125192126192127192128192129192130192131192132192133192134192135192136192137192138192139192140192141192142192143192144192145192146192147192148192149192150192151192152192153192154192155192156192157192158192159192160192161192162192163192164192165192166192167192168192169192170192171192172192173192174192175192176192177192178192179192180192181192182192183192184192185192186192187192188192189192190192191192192192193192194192195192196192197192198192199192200192201192202192203192204192205192206192207192208192209192210192211192212192213192214192215192216192217192218192219192220192221192222192223192224192225192226192227192228192229192230192231192232192233192234192235192236192237192238192239192240192241192242192243192244192245192246192247192248192249192250192251192252192253192254192255192256192257192258192259192260192261192262192263192264192265192266192267192268192269192270192271192272192273192274192275192276192277192278192279192280192281192282192283192284192285192286192287192288192289192290192291192292192293192294192295192296192297192298192299192300192301192302192303192304192305192306192307192308192309192310192311192312192313192314192315192316192317192318192319192320192321192322192323192324192325192326192327192328192329192330192331192332192333192334192335192336192337192338192339192340192341192342192343192344192345192346192347192348192349192350192351192352192353192354192355192356192357192358192359192360192361192362192363192364192365192366192367192368192369192370192371192372192373192374192375192376192377192378192379192380192381192382192383192384192385192386192387192388192389192390192391192392192393192394192395192396192397192398192399192400192401192402192403192404192405192406192407192408192409192410192411192412192413192414192415192416192417192418192419192420192421192422192423192424192425192426192427192428192429192430192431192432192433192434192435192436192437192438192439192440192441192442192443192444192445192446192447192448192449192450192451192452192453192454192455192456192457192458192459192460192461192462192463192464192465192466192467192468192469192470192471192472192473192474192475192476192477192478192479192480192481192482192483192484192485192486192487192488192489192490192491192492192493192494192495192496192497192498192499192500192501192502192503192504192505192506192507192508192509192510192511192512192513192514192515192516192517192518192519192520192521192522192523192524192525192526192527192528192529192530192531192532192533192534192535192536192537192538192539192540192541192542192543192544192545192546192547192548192549192550192551192552192553192554192555192556192557192558192559192560192561192562192563192564192565192566192567192568192569192570192571192572192573192574192575192576192577192578192579192580192581192582192583192584192585192586192587192588192589192590192591192592192593192594192595192596192597192598192599192600192601192602192603192604192605192606192607192608192609192610192611192612192613192614192615192616192617192618192619192620192621192622192623192624192625192626192627192628192629192630192631192632192633192634192635192636192637192638192639192640192641192642192643192644192645192646192647192648192649192650192651192652192653192654192655192656192657192658192659192660192661192662192663192664192665192666192667192668192669192670192671192672192673192674192675192676192677192678192679192680192681192682192683192684192685192686192687192688192689192690192691192692192693192694192695192696192697192698192699192700192701192702192703192704192705192706192707192708192709192710192711192712192713192714192715192716192717192718192719192720192721192722192723192724192725192726192727192728192729192730192731192732192733192734192735192736192737192738192739192740192741192742192743192744192745192746192747192748192749192750192751192752192753192754192755192756192757192758192759192760192761192762192763192764192765192766192767192768192769192770192771192772192773192774192775192776192777192778192779192780192781192782192783192784192785192786192787192788192789192790192791192792192793192794192795192796192797192798192799192800192801192802192803192804192805192806192807192808192809192810192811192812192813192814192815192816192817192818192819192820192821192822192823192824192825192826192827192828192829192830192831192832192833192834192835192836192837192838192839192840192841192842192843192844192845192846192847192848192849192850192851192852192853192854192855192856192857192858192859192860192861192862192863192864192865192866192867192868192869192870192871192872192873192874192875192876192877192878192879192880192881192882192883192884192885192886192887192888192889192890192891192892192893192894192895192896192897192898192899192900192901192902192903192904192905192906192907192908192909192910192911192912192913192914192915192916192917192918192919192920192921192922192923192924192925192926192927192928192929192930192931192932192933192934192935192936192937192938192939192940192941192942192943192944192945192946192947192948192949192950192951192952192953192954192955192956192957192958192959192960192961192962192963192964192965192966192967192968192969192970192971192972192973192974192975192976192977192978192979192980192981192982192983192984192985192986192987192988192989192990192991192992192993192994192995192996192997192998192999193000193001193002193003193004193005193006193007193008193009193010193011193012193013193014193015193016193017193018193019193020193021193022193023193024193025193026193027193028193029193030193031193032193033193034193035193036193037193038193039193040193041193042193043193044193045193046193047193048193049193050193051193052193053193054193055193056193057193058193059193060193061193062193063193064193065193066193067193068193069193070193071193072193073193074193075193076193077193078193079193080193081193082193083193084193085193086193087193088193089193090193091193092193093193094193095193096193097193098193099193100193101193102193103193104193105193106193107193108193109193110193111193112193113193114193115193116193117193118193119193120193121193122193123193124193125193126193127193128193129193130193131193132193133193134193135193136193137193138193139193140193141193142193143193144193145193146193147193148193149193150193151193152193153193154193155193156193157193158193159193160193161193162193163193164193165193166193167193168193169193170193171193172193173193174193175193176193177193178193179193180193181193182193183193184193185193186193187193188193189193190193191193192193193193194193195193196193197193198193199193200193201193202193203193204193205193206193207193208193209193210193211193212193213193214193215193216193217193218193219193220193221193222193223193224193225193226193227193228193229193230193231193232193233193234193235193236193237193238193239193240193241193242193243193244193245193246193247193248193249193250193251193252193253193254193255193256193257193258193259193260193261193262193263193264193265193266193267193268193269193270193271193272193273193274193275193276193277193278193279193280193281193282193283193284193285193286193287193288193289193290193291193292193293193294193295193296193297193298193299193300193301193302193303193304193305193306193307193308193309193310193311193312193313193314193315193316193317193318193319193320193321193322193323193324193325193326193327193328193329193330193331193332193333193334193335193336193337193338193339193340193341193342193343193344193345193346193347193348193349193350193351193352193353193354193355193356193357193358193359193360193361193362193363193364193365193366193367193368193369193370193371193372193373193374193375193376193377193378193379193380193381193382193383193384193385193386193387193388193389193390193391193392193393193394193395193396193397193398193399193400193401193402193403193404193405193406193407193408193409193410193411193412193413193414193415193416193417193418193419193420193421193422193423193424193425193426193427193428193429193430193431193432193433193434193435193436193437193438193439193440193441193442193443193444193445193446193447193448193449193450193451193452193453193454193455193456193457193458193459193460193461193462193463193464193465193466193467193468193469193470193471193472193473193474193475193476193477193478193479193480193481193482193483193484193485193486193487193488193489193490193491193492193493193494193495193496193497193498193499193500193501193502193503193504193505193506193507193508193509193510193511193512193513193514193515193516193517193518193519193520193521193522193523193524193525193526193527193528193529193530193531193532193533193534193535193536193537193538193539193540193541193542193543193544193545193546193547193548193549193550193551193552193553193554193555193556193557193558193559193560193561193562193563193564193565193566193567193568193569193570193571193572193573193574193575193576193577193578193579193580193581193582193583193584193585193586193587193588193589193590193591193592193593193594193595193596193597193598193599193600193601193602193603193604193605193606193607193608193609193610193611193612193613193614193615193616193617193618193619193620193621193622193623193624193625193626193627193628193629193630193631193632193633193634193635193636193637193638193639193640193641193642193643193644193645193646193647193648193649193650193651193652193653193654193655193656193657193658193659193660193661193662193663193664193665193666193667193668193669193670193671193672193673193674193675193676193677193678193679193680193681193682193683193684193685193686193687193688193689193690193691193692193693193694193695193696193697193698193699193700193701193702193703193704193705193706193707193708193709193710193711193712193713193714193715193716193717193718193719193720193721193722193723193724193725193726193727193728193729193730193731193732193733193734193735193736193737193738193739193740193741193742193743193744193745193746193747193748193749193750193751193752193753193754193755193756193757193758193759193760193761193762193763193764193765193766193767193768193769193770193771193772193773193774193775193776193777193778193779193780193781193782193783193784193785193786193787193788193789193790193791193792193793193794193795193796193797193798193799193800193801193802193803193804193805193806193807193808193809193810193811193812193813193814193815193816193817193818193819193820193821193822193823193824193825193826193827193828193829193830193831193832193833193834193835193836193837193838193839193840193841193842193843193844193845193846193847193848193849193850193851193852193853193854193855193856193857193858193859193860193861193862193863193864193865193866193867193868193869193870193871193872193873193874193875193876193877193878193879193880193881193882193883193884193885193886193887193888193889193890193891193892193893193894193895193896193897193898193899193900193901193902193903193904193905193906193907193908193909193910193911193912193913193914193915193916193917193918193919193920193921193922193923193924193925193926193927193928193929193930193931193932193933193934193935193936193937193938193939193940193941193942193943193944193945193946193947193948193949193950193951193952193953193954193955193956193957193958193959193960193961193962193963193964193965193966193967193968193969193970193971193972193973193974193975193976193977193978193979193980193981193982193983193984193985193986193987193988193989193990193991193992193993193994193995193996193997193998193999194000194001194002194003194004194005194006194007194008194009194010194011194012194013194014194015194016194017194018194019194020194021194022194023194024194025194026194027194028194029194030194031194032194033194034194035194036194037194038194039194040194041194042194043194044194045194046194047194048194049194050194051194052194053194054194055194056194057194058194059194060194061194062194063194064194065194066194067194068194069194070194071194072194073194074194075194076194077194078194079194080194081194082194083194084194085194086194087194088194089194090194091194092194093194094194095194096194097194098194099194100194101194102194103194104194105194106194107194108194109194110194111194112194113194114194115194116194117194118194119194120194121194122194123194124194125194126194127194128194129194130194131194132194133194134194135194136194137194138194139194140194141194142194143194144194145194146194147194148194149194150194151194152194153194154194155194156194157194158194159194160194161194162194163194164194165194166194167194168194169194170194171194172194173194174194175194176194177194178194179194180194181194182194183194184194185194186194187194188194189194190194191194192194193194194194195194196194197194198194199194200194201194202194203194204194205194206194207194208194209194210194211194212194213194214194215194216194217194218194219194220194221194222194223194224194225194226194227194228194229194230194231194232194233194234194235194236194237194238194239194240194241194242194243194244194245194246194247194248194249194250194251194252194253194254194255194256194257194258194259194260194261194262194263194264194265194266194267194268194269194270194271194272194273194274194275194276194277194278194279194280194281194282194283194284194285194286194287194288194289194290194291194292194293194294194295194296194297194298194299194300194301194302194303194304194305194306194307194308194309194310194311194312194313194314194315194316194317194318194319194320194321194322194323194324194325194326194327194328194329194330194331194332194333194334194335194336194337194338194339194340194341194342194343194344194345194346194347194348194349194350194351194352194353194354194355194356194357194358194359194360194361194362194363194364194365194366194367194368194369194370194371194372194373194374194375194376194377194378194379194380194381194382194383194384194385194386194387194388194389194390194391194392194393194394194395194396194397194398194399194400194401194402194403194404194405194406194407194408194409194410194411194412194413194414194415194416194417194418194419194420194421194422194423194424194425194426194427194428194429194430194431194432194433194434194435194436194437194438194439194440194441194442194443194444194445194446194447194448194449194450194451194452194453194454194455194456194457194458194459194460194461194462194463194464194465194466194467194468194469194470194471194472194473194474194475194476194477194478194479194480194481194482194483194484194485194486194487194488194489194490194491194492194493194494194495194496194497194498194499194500194501194502194503194504194505194506194507194508194509194510194511194512194513194514194515194516194517194518194519194520194521194522194523194524194525194526194527194528194529194530194531194532194533194534194535194536194537194538194539194540194541194542194543194544194545194546194547194548194549194550194551194552194553194554194555194556194557194558194559194560194561194562194563194564194565194566194567194568194569194570194571194572194573194574194575194576194577194578194579194580194581194582194583194584194585194586194587194588194589194590194591194592194593194594194595194596194597194598194599194600194601194602194603194604194605194606194607194608194609194610194611194612194613194614194615194616194617194618194619194620194621194622194623194624194625194626194627194628194629194630194631194632194633194634194635194636194637194638194639194640194641194642194643194644194645194646194647194648194649194650194651194652194653194654194655194656194657194658194659194660194661194662194663194664194665194666194667194668194669194670194671194672194673194674194675194676194677194678194679194680194681194682194683194684194685194686194687194688194689194690194691194692194693194694194695194696194697194698194699194700194701194702194703194704194705194706194707194708194709194710194711194712194713194714194715194716194717194718194719194720194721194722194723194724194725194726194727194728194729194730194731194732194733194734194735194736194737194738194739194740194741194742194743194744194745194746194747194748194749194750194751194752194753194754194755194756194757194758194759194760194761194762194763194764194765194766194767194768194769194770194771194772194773194774194775194776194777194778194779194780194781194782194783194784194785194786194787194788194789194790194791194792194793194794194795194796194797194798194799194800194801194802194803194804194805194806194807194808194809194810194811194812194813194814194815194816194817194818194819194820194821194822194823194824194825194826194827194828194829194830194831194832194833194834194835194836194837194838194839194840194841194842194843194844194845194846194847194848194849194850194851194852194853194854194855194856194857194858194859194860194861194862194863194864194865194866194867194868194869194870194871194872194873194874194875194876194877194878194879194880194881194882194883194884194885194886194887194888194889194890194891194892194893194894194895194896194897194898194899194900194901194902194903194904194905194906194907194908194909194910194911194912194913194914194915194916194917194918194919194920194921194922194923194924194925194926194927194928194929194930194931194932194933194934194935194936194937194938194939194940194941194942194943194944194945194946194947194948194949194950194951194952194953194954194955194956194957194958194959194960194961194962194963194964194965194966194967194968194969194970194971194972194973194974194975194976194977194978194979194980194981194982194983194984194985194986194987194988194989194990194991194992194993194994194995194996194997194998194999195000195001195002195003195004195005195006195007195008195009195010195011195012195013195014195015195016195017195018195019195020195021195022195023195024195025195026195027195028195029195030195031195032195033195034195035195036195037195038195039195040195041195042195043195044195045195046195047195048195049195050195051195052195053195054195055195056195057195058195059195060195061195062195063195064195065195066195067195068195069195070195071195072195073195074195075195076195077195078195079195080195081195082195083195084195085195086195087195088195089195090195091195092195093195094195095195096195097195098195099195100195101195102195103195104195105195106195107195108195109195110195111195112195113195114195115195116195117195118195119195120195121195122195123195124195125195126195127195128195129195130195131195132195133195134195135195136195137195138195139195140195141195142195143195144195145195146195147195148195149195150195151195152195153195154195155195156195157195158195159195160195161195162195163195164195165195166195167195168195169195170195171195172195173195174195175195176195177195178195179195180195181195182195183195184195185195186195187195188195189195190195191195192195193195194195195195196195197195198195199195200195201195202195203195204195205195206195207195208195209195210195211195212195213195214195215195216195217195218195219195220195221195222195223195224195225195226195227195228195229195230195231195232195233195234195235195236195237195238195239195240195241195242195243195244195245195246195247195248195249195250195251195252195253195254195255195256195257195258195259195260195261195262195263195264195265195266195267195268195269195270195271195272195273195274195275195276195277195278195279195280195281195282195283195284195285195286195287195288195289195290195291195292195293195294195295195296195297195298195299195300195301195302195303195304195305195306195307195308195309195310195311195312195313195314195315195316195317195318195319195320195321195322195323195324195325195326195327195328195329195330195331195332195333195334195335195336195337195338195339195340195341195342195343195344195345195346195347195348195349195350195351195352195353195354195355195356195357195358195359195360195361195362195363195364195365195366195367195368195369195370195371195372195373195374195375195376195377195378195379195380195381195382195383195384195385195386195387195388195389195390195391195392195393195394195395195396195397195398195399195400195401195402195403195404195405195406195407195408195409195410195411195412195413195414195415195416195417195418195419195420195421195422195423195424195425195426195427195428195429195430195431195432195433195434195435195436195437195438195439195440195441195442195443195444195445195446195447195448195449195450195451195452195453195454195455195456195457195458195459195460195461195462195463195464195465195466195467195468195469195470195471195472195473195474195475195476195477195478195479195480195481195482195483195484195485195486195487195488195489195490195491195492195493195494195495195496195497195498195499195500195501195502195503195504195505195506195507195508195509195510195511195512195513195514195515195516195517195518195519195520195521195522195523195524195525195526195527195528195529195530195531195532195533195534195535195536195537195538195539195540195541195542195543195544195545195546195547195548195549195550195551195552195553195554195555195556195557195558195559195560195561195562195563195564195565195566195567195568195569195570195571195572195573195574195575195576195577195578195579195580195581195582195583195584195585195586195587195588195589195590195591195592195593195594195595195596195597195598195599195600195601195602195603195604195605195606195607195608195609195610195611195612195613195614195615195616195617195618195619195620195621195622195623195624195625195626195627195628195629195630195631195632195633195634195635195636195637195638195639195640195641195642195643195644195645195646195647195648195649195650195651195652195653195654195655195656195657195658195659195660195661195662195663195664195665195666195667195668195669195670195671195672195673195674195675195676195677195678195679195680195681195682195683195684195685195686195687195688195689195690195691195692195693195694195695195696195697195698195699195700195701195702195703195704195705195706195707195708195709195710195711195712195713195714195715195716195717195718195719195720195721195722195723195724195725195726195727195728195729195730195731195732195733195734195735195736195737195738195739195740195741195742195743195744195745195746195747195748195749195750195751195752195753195754195755195756195757195758195759195760195761195762195763195764195765195766195767195768195769195770195771195772195773195774195775195776195777195778195779195780195781195782195783195784195785195786195787195788195789195790195791195792195793195794195795195796195797195798195799195800195801195802195803195804195805195806195807195808195809195810195811195812195813195814195815195816195817195818195819195820195821195822195823195824195825195826195827195828195829195830195831195832195833195834195835195836195837195838195839195840195841195842195843195844195845195846195847195848195849195850195851195852195853195854195855195856195857195858195859195860195861195862195863195864195865195866195867195868195869195870195871195872195873195874195875195876195877195878195879195880195881195882195883195884195885195886195887195888195889195890195891195892195893195894195895195896195897195898195899195900195901195902195903195904195905195906195907195908195909195910195911195912195913195914195915195916195917195918195919195920195921195922195923195924195925195926195927195928195929195930195931195932195933195934195935195936195937195938195939195940195941195942195943195944195945195946195947195948195949195950195951195952195953195954195955195956195957195958195959195960195961195962195963195964195965195966195967195968195969195970195971195972195973195974195975195976195977195978195979195980195981195982195983195984195985195986195987195988195989195990195991195992195993195994195995195996195997195998195999196000196001196002196003196004196005196006196007196008196009196010196011196012196013196014196015196016196017196018196019196020196021196022196023196024196025196026196027196028196029196030196031196032196033196034196035196036196037196038196039196040196041196042196043196044196045196046196047196048196049196050196051196052196053196054196055196056196057196058196059196060196061196062196063196064196065196066196067196068196069196070196071196072196073196074196075196076196077196078196079196080196081196082196083196084196085196086196087196088196089196090196091196092196093196094196095196096196097196098196099196100196101196102196103196104196105196106196107196108196109196110196111196112196113196114196115196116196117196118196119196120196121196122196123196124196125196126196127196128196129196130196131196132196133196134196135196136196137196138196139196140196141196142196143196144196145196146196147196148196149196150196151196152196153196154196155196156196157196158196159196160196161196162196163196164196165196166196167196168196169196170196171196172196173196174196175196176196177196178196179196180196181196182196183196184196185196186196187196188196189196190196191196192196193196194196195196196196197196198196199196200196201196202196203196204196205196206196207196208196209196210196211196212196213196214196215196216196217196218196219196220196221196222196223196224196225196226196227196228196229196230196231196232196233196234196235196236196237196238196239196240196241196242196243196244196245196246196247196248196249196250196251196252196253196254196255196256196257196258196259196260196261196262196263196264196265196266196267196268196269196270196271196272196273196274196275196276196277196278196279196280196281196282196283196284196285196286196287196288196289196290196291196292196293196294196295196296196297196298196299196300196301196302196303196304196305196306196307196308196309196310196311196312196313196314196315196316196317196318196319196320196321196322196323196324196325196326196327196328196329196330196331196332196333196334196335196336196337196338196339196340196341196342196343196344196345196346196347196348196349196350196351196352196353196354196355196356196357196358196359196360196361196362196363196364196365196366196367196368196369196370196371196372196373196374196375196376196377196378196379196380196381196382196383196384196385196386196387196388196389196390196391196392196393196394196395196396196397196398196399196400196401196402196403196404196405196406196407196408196409196410196411196412196413196414196415196416196417196418196419196420196421196422196423196424196425196426196427196428196429196430196431196432196433196434196435196436196437196438196439196440196441196442196443196444196445196446196447196448196449196450196451196452196453196454196455196456196457196458196459196460196461196462196463196464196465196466196467196468196469196470196471196472196473196474196475196476196477196478196479196480196481196482196483196484196485196486196487196488196489196490196491196492196493196494196495196496196497196498196499196500196501196502196503196504196505196506196507196508196509196510196511196512196513196514196515196516196517196518196519196520196521196522196523196524196525196526196527196528196529196530196531196532196533196534196535196536196537196538196539196540196541196542196543196544196545196546196547196548196549196550196551196552196553196554196555196556196557196558196559196560196561196562196563196564196565196566196567196568196569196570196571196572196573196574196575196576196577196578196579196580196581196582196583196584196585196586196587196588196589196590196591196592196593196594196595196596196597196598196599196600196601196602196603196604196605196606196607196608196609196610196611196612196613196614196615196616196617196618196619196620196621196622196623196624196625196626196627196628196629196630196631196632196633196634196635196636196637196638196639196640196641196642196643196644196645196646196647196648196649196650196651196652196653196654196655196656196657196658196659196660196661196662196663196664196665196666196667196668196669196670196671196672196673196674196675196676196677196678196679196680196681196682196683196684196685196686196687196688196689196690196691196692196693196694196695196696196697196698196699196700196701196702196703196704196705196706196707196708196709196710196711196712196713196714196715196716196717196718196719196720196721196722196723196724196725196726196727196728196729196730196731196732196733196734196735196736196737196738196739196740196741196742196743196744196745196746196747196748196749196750196751196752196753196754196755196756196757196758196759196760196761196762196763196764196765196766196767196768196769196770196771196772196773196774196775196776196777196778196779196780196781196782196783196784196785196786196787196788196789196790196791196792196793196794196795196796196797196798196799196800196801196802196803196804196805196806196807196808196809196810196811196812196813196814196815196816196817196818196819196820196821196822196823196824196825196826196827196828196829196830196831196832196833196834196835196836196837196838196839196840196841196842196843196844196845196846196847196848196849196850196851196852196853196854196855196856196857196858196859196860196861196862196863196864196865196866196867196868196869196870196871196872196873196874196875196876196877196878196879196880196881196882196883196884196885196886196887196888196889196890196891196892196893196894196895196896196897196898196899196900196901196902196903196904196905196906196907196908196909196910196911196912196913196914196915196916196917196918196919196920196921196922196923196924196925196926196927196928196929196930196931196932196933196934196935196936196937196938196939196940196941196942196943196944196945196946196947196948196949196950196951196952196953196954196955196956196957196958196959196960196961196962196963196964196965196966196967196968196969196970196971196972196973196974196975196976196977196978196979196980196981196982196983196984196985196986196987196988196989196990196991196992196993196994196995196996196997196998196999197000197001197002197003197004197005197006197007197008197009197010197011197012197013197014197015197016197017197018197019197020197021197022197023197024197025197026197027197028197029197030197031197032197033197034197035197036197037197038197039197040197041197042197043197044197045197046197047197048197049197050197051197052197053197054197055197056197057197058197059197060197061197062197063197064197065197066197067197068197069197070197071197072197073197074197075197076197077197078197079197080197081197082197083197084197085197086197087197088197089197090197091197092197093197094197095197096197097197098197099197100197101197102197103197104197105197106197107197108197109197110197111197112197113197114197115197116197117197118197119197120197121197122197123197124197125197126197127197128197129197130197131197132197133197134197135197136197137197138197139197140197141197142197143197144197145197146197147197148197149197150197151197152197153197154197155197156197157197158197159197160197161197162197163197164197165197166197167197168197169197170197171197172197173197174197175197176197177197178197179197180197181197182197183197184197185197186197187197188197189197190197191197192197193197194197195197196197197197198197199197200197201197202197203197204197205197206197207197208197209197210197211197212197213197214197215197216197217197218197219197220197221197222197223197224197225197226197227197228197229197230197231197232197233197234197235197236197237197238197239197240197241197242197243197244197245197246197247197248197249197250197251197252197253197254197255197256197257197258197259197260197261197262197263197264197265197266197267197268197269197270197271197272197273197274197275197276197277197278197279197280197281197282197283197284197285197286197287197288197289197290197291197292197293197294197295197296197297197298197299197300197301197302197303197304197305197306197307197308197309197310197311197312197313197314197315197316197317197318197319197320197321197322197323197324197325197326197327197328197329197330197331197332197333197334197335197336197337197338197339197340197341197342197343197344197345197346197347197348197349197350197351197352197353197354197355197356197357197358197359197360197361197362197363197364197365197366197367197368197369197370197371197372197373197374197375197376197377197378197379197380197381197382197383197384197385197386197387197388197389197390197391197392197393197394197395197396197397197398197399197400197401197402197403197404197405197406197407197408197409197410197411197412197413197414197415197416197417197418197419197420197421197422197423197424197425197426197427197428197429197430197431197432197433197434197435197436197437197438197439197440197441197442197443197444197445197446197447197448197449197450197451197452197453197454197455197456197457197458197459197460197461197462197463197464197465197466197467197468197469197470197471197472197473197474197475197476197477197478197479197480197481197482197483197484197485197486197487197488197489197490197491197492197493197494197495197496197497197498197499197500197501197502197503197504197505197506197507197508197509197510197511197512197513197514197515197516197517197518197519197520197521197522197523197524197525197526197527197528197529197530197531197532197533197534197535197536197537197538197539197540197541197542197543197544197545197546197547197548197549197550197551197552197553197554197555197556197557197558197559197560197561197562197563197564197565197566197567197568197569197570197571197572197573197574197575197576197577197578197579197580197581197582197583197584197585197586197587197588197589197590197591197592197593197594197595197596197597197598197599197600197601197602197603197604197605197606197607197608197609197610197611197612197613197614197615197616197617197618197619197620197621197622197623197624197625197626197627197628197629197630197631197632197633197634197635197636197637197638197639197640197641197642197643197644197645197646197647197648197649197650197651197652197653197654197655197656197657197658197659197660197661197662197663197664197665197666197667197668197669197670197671197672197673197674197675197676197677197678197679197680197681197682197683197684197685197686197687197688197689197690197691197692197693197694197695197696197697197698197699197700197701197702197703197704197705197706197707197708197709197710197711197712197713197714197715197716197717197718197719197720197721197722197723197724197725197726197727197728197729197730197731197732197733197734197735197736197737197738197739197740197741197742197743197744197745197746197747197748197749197750197751197752197753197754197755197756197757197758197759197760197761197762197763197764197765197766197767197768197769197770197771197772197773197774197775197776197777197778197779197780197781197782197783197784197785197786197787197788197789197790197791197792197793197794197795197796197797197798197799197800197801197802197803197804197805197806197807197808197809197810197811197812197813197814197815197816197817197818197819197820197821197822197823197824197825197826197827197828197829197830197831197832197833197834197835197836197837197838197839197840197841197842197843197844197845197846197847197848197849197850197851197852197853197854197855197856197857197858197859197860197861197862197863197864197865197866197867197868197869197870197871197872197873197874197875197876197877197878197879197880197881197882197883197884197885197886197887197888197889197890197891197892197893197894197895197896197897197898197899197900197901197902197903197904197905197906197907197908197909197910197911197912197913197914197915197916197917197918197919197920197921197922197923197924197925197926197927197928197929197930197931197932197933197934197935197936197937197938197939197940197941197942197943197944197945197946197947197948197949197950197951197952197953197954197955197956197957197958197959197960197961197962197963197964197965197966197967197968197969197970197971197972197973197974197975197976197977197978197979197980197981197982197983197984197985197986197987197988197989197990197991197992197993197994197995197996197997197998197999198000198001198002198003198004198005198006198007198008198009198010198011198012198013198014198015198016198017198018198019198020198021198022198023198024198025198026198027198028198029198030198031198032198033198034198035198036198037198038198039198040198041198042198043198044198045198046198047198048198049198050198051198052198053198054198055198056198057198058198059198060198061198062198063198064198065198066198067198068198069198070198071198072198073198074198075198076198077198078198079198080198081198082198083198084198085198086198087198088198089198090198091198092198093198094198095198096198097198098198099198100198101198102198103198104198105198106198107198108198109198110198111198112198113198114198115198116198117198118198119198120198121198122198123198124198125198126198127198128198129198130198131198132198133198134198135198136198137198138198139198140198141198142198143198144198145198146198147198148198149198150198151198152198153198154198155198156198157198158198159198160198161198162198163198164198165198166198167198168198169198170198171198172198173198174198175198176198177198178198179198180198181198182198183198184198185198186198187198188198189198190198191198192198193198194198195198196198197198198198199198200198201198202198203198204198205198206198207198208198209198210198211198212198213198214198215198216198217198218198219198220198221198222198223198224198225198226198227198228198229198230198231198232198233198234198235198236198237198238198239198240198241198242198243198244198245198246198247198248198249198250198251198252198253198254198255198256198257198258198259198260198261198262198263198264198265198266198267198268198269198270198271198272198273198274198275198276198277198278198279198280198281198282198283198284198285198286198287198288198289198290198291198292198293198294198295198296198297198298198299198300198301198302198303198304198305198306198307198308198309198310198311198312198313198314198315198316198317198318198319198320198321198322198323198324198325198326198327198328198329198330198331198332198333198334198335198336198337198338198339198340198341198342198343198344198345198346198347198348198349198350198351198352198353198354198355198356198357198358198359198360198361198362198363198364198365198366198367198368198369198370198371198372198373198374198375198376198377198378198379198380198381198382198383198384198385198386198387198388198389198390198391198392198393198394198395198396198397198398198399198400198401198402198403198404198405198406198407198408198409198410198411198412198413198414198415198416198417198418198419198420198421198422198423198424198425198426198427198428198429198430198431198432198433198434198435198436198437198438198439198440198441198442198443198444198445198446198447198448198449198450198451198452198453198454198455198456198457198458198459198460198461198462198463198464198465198466198467198468198469198470198471198472198473198474198475198476198477198478198479198480198481198482198483198484198485198486198487198488198489198490198491198492198493198494198495198496198497198498198499198500198501198502198503198504198505198506198507198508198509198510198511198512198513198514198515198516198517198518198519198520198521198522198523198524198525198526198527198528198529198530198531198532198533198534198535198536198537198538198539198540198541198542198543198544198545198546198547198548198549198550198551198552198553198554198555198556198557198558198559198560198561198562198563198564198565198566198567198568198569198570198571198572198573198574198575198576198577198578198579198580198581198582198583198584198585198586198587198588198589198590198591198592198593198594198595198596198597198598198599198600198601198602198603198604198605198606198607198608198609198610198611198612198613198614198615198616198617198618198619198620198621198622198623198624198625198626198627198628198629198630198631198632198633198634198635198636198637198638198639198640198641198642198643198644198645198646198647198648198649198650198651198652198653198654198655198656198657198658198659198660198661198662198663198664198665198666198667198668198669198670198671198672198673198674198675198676198677198678198679198680198681198682198683198684198685198686198687198688198689198690198691198692198693198694198695198696198697198698198699198700198701198702198703198704198705198706198707198708198709198710198711198712198713198714198715198716198717198718198719198720198721198722198723198724198725198726198727198728198729198730198731198732198733198734198735198736198737198738198739198740198741198742198743198744198745198746198747198748198749198750198751198752198753198754198755198756198757198758198759198760198761198762198763198764198765198766198767198768198769198770198771198772198773198774198775198776198777198778198779198780198781198782198783198784198785198786198787198788198789198790198791198792198793198794198795198796198797198798198799198800198801198802198803198804198805198806198807198808198809198810198811198812198813198814198815198816198817198818198819198820198821198822198823198824198825198826198827198828198829198830198831198832198833198834198835198836198837198838198839198840198841198842198843198844198845198846198847198848198849198850198851198852198853198854198855198856198857198858198859198860198861198862198863198864198865198866198867198868198869198870198871198872198873198874198875198876198877198878198879198880198881198882198883198884198885198886198887198888198889198890198891198892198893198894198895198896198897198898198899198900198901198902198903198904198905198906198907198908198909198910198911198912198913198914198915198916198917198918198919198920198921198922198923198924198925198926198927198928198929198930198931198932198933198934198935198936198937198938198939198940198941198942198943198944198945198946198947198948198949198950198951198952198953198954198955198956198957198958198959198960198961198962198963198964198965198966198967198968198969198970198971198972198973198974198975198976198977198978198979198980198981198982198983198984198985198986198987198988198989198990198991198992198993198994198995198996198997198998198999199000199001199002199003199004199005199006199007199008199009199010199011199012199013199014199015199016199017199018199019199020199021199022199023199024199025199026199027199028199029199030199031199032199033199034199035199036199037199038199039199040199041199042199043199044199045199046199047199048199049199050199051199052199053199054199055199056199057199058199059199060199061199062199063199064199065199066199067199068199069199070199071199072199073199074199075199076199077199078199079199080199081199082199083199084199085199086199087199088199089199090199091199092199093199094199095199096199097199098199099199100199101199102199103199104199105199106199107199108199109199110199111199112199113199114199115199116199117199118199119199120199121199122199123199124199125199126199127199128199129199130199131199132199133199134199135199136199137199138199139199140199141199142199143199144199145199146199147199148199149199150199151199152199153199154199155199156199157199158199159199160199161199162199163199164199165199166199167199168199169199170199171199172199173199174199175199176199177199178199179199180199181199182199183199184199185199186199187199188199189199190199191199192199193199194199195199196199197199198199199199200199201199202199203199204199205199206199207199208199209199210199211199212199213199214199215199216199217199218199219199220199221199222199223199224199225199226199227199228199229199230199231199232199233199234199235199236199237199238199239199240199241199242199243199244199245199246199247199248199249199250199251199252199253199254199255199256199257199258199259199260199261199262199263199264199265199266199267199268199269199270199271199272199273199274199275199276199277199278199279199280199281199282199283199284199285199286199287199288199289199290199291199292199293199294199295199296199297199298199299199300199301199302199303199304199305199306199307199308199309199310199311199312199313199314199315199316199317199318199319199320199321199322199323199324199325199326199327199328199329199330199331199332199333199334199335199336199337199338199339199340199341199342199343199344199345199346199347199348199349199350199351199352199353199354199355199356199357199358199359199360199361199362199363199364199365199366199367199368199369199370199371199372199373199374199375199376199377199378199379199380199381199382199383199384199385199386199387199388199389199390199391199392199393199394199395199396199397199398199399199400199401199402199403199404199405199406199407199408199409199410199411199412199413199414199415199416199417199418199419199420199421199422199423199424199425199426199427199428199429199430199431199432199433199434199435199436199437199438199439199440199441199442199443199444199445199446199447199448199449199450199451199452199453199454199455199456199457199458199459199460199461199462199463199464199465199466199467199468199469199470199471199472199473199474199475199476199477199478199479199480199481199482199483199484199485199486199487199488199489199490199491199492199493199494199495199496199497199498199499199500199501199502199503199504199505199506199507199508199509199510199511199512199513199514199515199516199517199518199519199520199521199522199523199524199525199526199527199528199529199530199531199532199533199534199535199536199537199538199539199540199541199542199543199544199545199546199547199548199549199550199551199552199553199554199555199556199557199558199559199560199561199562199563199564199565199566199567199568199569199570199571199572199573199574199575199576199577199578199579199580199581199582199583199584199585199586199587199588199589199590199591199592199593199594199595199596199597199598199599199600199601199602199603199604199605199606199607199608199609199610199611199612199613199614199615199616199617199618199619199620199621199622199623199624199625199626199627199628199629199630199631199632199633199634199635199636199637199638199639199640199641199642199643199644199645199646199647199648199649199650199651199652199653199654199655199656199657199658199659199660199661199662199663199664199665199666199667199668199669199670199671199672199673199674199675199676199677199678199679199680199681199682199683199684199685199686199687199688199689199690199691199692199693199694199695199696199697199698199699199700199701199702199703199704199705199706199707199708199709199710199711199712199713199714199715199716199717199718199719199720199721199722199723199724199725199726199727199728199729199730199731199732199733199734199735199736199737199738199739199740199741199742199743199744199745199746199747199748199749199750199751199752199753199754199755199756199757199758199759199760199761199762199763199764199765199766199767199768199769199770199771199772199773199774199775199776199777199778199779199780199781199782199783199784199785199786199787199788199789199790199791199792199793199794199795199796199797199798199799199800199801199802199803199804199805199806199807199808199809199810199811199812199813199814199815199816199817199818199819199820199821199822199823199824199825199826199827199828199829199830199831199832199833199834199835199836199837199838199839199840199841199842199843199844199845199846199847199848199849199850199851199852199853199854199855199856199857199858199859199860199861199862199863199864199865199866199867199868199869199870199871199872199873199874199875199876199877199878199879199880199881199882199883199884199885199886199887199888199889199890199891199892199893199894199895199896199897199898199899199900199901199902199903199904199905199906199907199908199909199910199911199912199913199914199915199916199917199918199919199920199921199922199923199924199925199926199927199928199929199930199931199932199933199934199935199936199937199938199939199940199941199942199943199944199945199946199947199948199949199950199951199952199953199954199955199956199957199958199959199960199961199962199963199964199965199966199967199968199969199970199971199972199973199974199975199976199977199978199979199980199981199982199983199984199985199986199987199988199989199990199991199992199993199994199995199996199997199998199999200000200001200002200003200004200005200006200007200008200009200010200011200012200013200014200015200016200017200018200019200020200021200022200023200024200025200026200027200028200029200030200031200032200033200034200035200036200037200038200039200040200041200042200043200044200045200046200047200048200049200050200051200052200053200054200055200056200057200058200059200060200061200062200063200064200065200066200067200068200069200070200071200072200073200074200075200076200077200078200079200080200081200082200083200084200085200086200087200088200089200090200091200092200093200094200095200096200097200098200099200100200101200102200103200104200105200106200107200108200109200110200111200112200113200114200115200116200117200118200119200120200121200122200123200124200125200126200127200128200129200130200131200132200133200134200135200136200137200138200139200140200141200142200143200144200145200146200147200148200149200150200151200152200153200154200155200156200157200158200159200160200161200162200163200164200165200166200167200168200169200170200171200172200173200174200175200176200177200178200179200180200181200182200183200184200185200186200187200188200189200190200191200192200193200194200195200196200197200198200199200200200201200202200203200204200205200206200207200208200209200210200211200212200213200214200215200216200217200218200219200220200221200222200223200224200225200226200227200228200229200230200231200232200233200234200235200236200237200238200239200240200241200242200243200244200245200246200247200248200249200250200251200252200253200254200255200256200257200258200259200260200261200262200263200264200265200266200267200268200269200270200271200272200273200274200275200276200277200278200279200280200281200282200283200284200285200286200287200288200289200290200291200292200293200294200295200296200297200298200299200300200301200302200303200304200305200306200307200308200309200310200311200312200313200314200315200316200317200318200319200320200321200322200323200324200325200326200327200328200329200330200331200332200333200334200335200336200337200338200339200340200341200342200343200344200345200346200347200348200349200350200351200352200353200354200355200356200357200358200359200360200361200362200363200364200365200366200367200368200369200370200371200372200373200374200375200376200377200378200379200380200381200382200383200384200385200386200387200388200389200390200391200392200393200394200395200396200397200398200399200400200401200402200403200404200405200406200407200408200409200410200411200412200413200414200415200416200417200418200419200420200421200422200423200424200425200426200427200428200429200430200431200432200433200434200435200436200437200438200439200440200441200442200443200444200445200446200447200448200449200450200451200452200453200454200455200456200457200458200459200460200461200462200463200464200465200466200467200468200469200470200471200472200473200474200475200476200477200478200479200480200481200482200483200484200485200486200487200488200489200490200491200492200493200494200495200496200497200498200499200500200501200502200503200504200505200506200507200508200509200510200511200512200513200514200515200516200517200518200519200520200521200522200523200524200525200526200527200528200529200530200531200532200533200534200535200536200537200538200539200540200541200542200543200544200545200546200547200548200549200550200551200552200553200554200555200556200557200558200559200560200561200562200563200564200565200566200567200568200569200570200571200572200573200574200575200576200577200578200579200580200581200582200583200584200585200586200587200588200589200590200591200592200593200594200595200596200597200598200599200600200601200602200603200604200605200606200607200608200609200610200611200612200613200614200615200616200617200618200619200620200621200622200623200624200625200626200627200628200629200630200631200632200633200634200635200636200637200638200639200640200641200642200643200644200645200646200647200648200649200650200651200652200653200654200655200656200657200658200659200660200661200662200663200664200665200666200667200668200669200670200671200672200673200674200675200676200677200678200679200680200681200682200683200684200685200686200687200688200689200690200691200692200693200694200695200696200697200698200699200700200701200702200703200704200705200706200707200708200709200710200711200712200713200714200715200716200717200718200719200720200721200722200723200724200725200726200727200728200729200730200731200732200733200734200735200736200737200738200739200740200741200742200743200744200745200746200747200748200749200750200751200752200753200754200755200756200757200758200759200760200761200762200763200764200765200766200767200768200769200770200771200772200773200774200775200776200777200778200779200780200781200782200783200784200785200786200787200788200789200790200791200792200793200794200795200796200797200798200799200800200801200802200803200804200805200806200807200808200809200810200811200812200813200814200815200816200817200818200819200820200821200822200823200824200825200826200827200828200829200830200831200832200833200834200835200836200837200838200839200840200841200842200843200844200845200846200847200848200849200850200851200852200853200854200855200856200857200858200859200860200861200862200863200864200865200866200867200868200869200870200871200872200873200874200875200876200877200878200879200880200881200882200883200884200885200886200887200888200889200890200891200892200893200894200895200896200897200898200899200900200901200902200903200904200905200906200907200908200909200910200911200912200913200914200915200916200917200918200919200920200921200922200923200924200925200926200927200928200929200930200931200932200933200934200935200936200937200938200939200940200941200942200943200944200945200946200947200948200949200950200951200952200953200954200955200956200957200958200959200960200961200962200963200964200965200966200967200968200969200970200971200972200973200974200975200976200977200978200979200980200981200982200983200984200985200986200987200988200989200990200991200992200993200994200995200996200997200998200999201000201001201002201003201004201005201006201007201008201009201010201011201012201013201014201015201016201017201018201019201020201021201022201023201024201025201026201027201028201029201030201031201032201033201034201035201036201037201038201039201040201041201042201043201044201045201046201047201048201049201050201051201052201053201054201055201056201057201058201059201060201061201062201063201064201065201066201067201068201069201070201071201072201073201074201075201076201077201078201079201080201081201082201083201084201085201086201087201088201089201090201091201092201093201094201095201096201097201098201099201100201101201102201103201104201105201106201107201108201109201110201111201112201113201114201115201116201117201118201119201120201121201122201123201124201125201126201127201128201129201130201131201132201133201134201135201136201137201138201139201140201141201142201143201144201145201146201147201148201149201150201151201152201153201154201155201156201157201158201159201160201161201162201163201164201165201166201167201168201169201170201171201172201173201174201175201176201177201178201179201180201181201182201183201184201185201186201187201188201189201190201191201192201193201194201195201196201197201198201199201200201201201202201203201204201205201206201207201208201209201210201211201212201213201214201215201216201217201218201219201220201221201222201223201224201225201226201227201228201229201230201231201232201233201234201235201236201237201238201239201240201241201242201243201244201245201246201247201248201249201250201251201252201253201254201255201256201257201258201259201260201261201262201263201264201265201266201267201268201269201270201271201272201273201274201275201276201277201278201279201280201281201282201283201284201285201286201287201288201289201290201291201292201293201294201295201296201297201298201299201300201301201302201303201304201305201306201307201308201309201310201311201312201313201314201315201316201317201318201319201320201321201322201323201324201325201326201327201328201329201330201331201332201333201334201335201336201337201338201339201340201341201342201343201344201345201346201347201348201349201350201351201352201353201354201355201356201357201358201359201360201361201362201363201364201365201366201367201368201369201370201371201372201373201374201375201376201377201378201379201380201381201382201383201384201385201386201387201388201389201390201391201392201393201394201395201396201397201398201399201400201401201402201403201404201405201406201407201408201409201410201411201412201413201414201415201416201417201418201419201420201421201422201423201424201425201426201427201428201429201430201431201432201433201434201435201436201437201438201439201440201441201442201443201444201445201446201447201448201449201450201451201452201453201454201455201456201457201458201459201460201461201462201463201464201465201466201467201468201469201470201471201472201473201474201475201476201477201478201479201480201481201482201483201484201485201486201487201488201489201490201491201492201493201494201495201496201497201498201499201500201501201502201503201504201505201506201507201508201509201510201511201512201513201514201515201516201517201518201519201520201521201522201523201524201525201526201527201528201529201530201531201532201533201534201535201536201537201538201539201540201541201542201543201544201545201546201547201548201549201550201551201552201553201554201555201556201557201558201559201560201561201562201563201564201565201566201567201568201569201570201571201572201573201574201575201576201577201578201579201580201581201582201583201584201585201586201587201588201589201590201591201592201593201594201595201596201597201598201599201600201601201602201603201604201605201606201607201608201609201610201611201612201613201614201615201616201617201618201619201620201621201622201623201624201625201626201627201628201629201630201631201632201633201634201635201636201637201638201639201640201641201642201643201644201645201646201647201648201649201650201651201652201653201654201655201656201657201658201659201660201661201662201663201664201665201666201667201668201669201670201671201672201673201674201675201676201677201678201679201680201681201682201683201684201685201686201687201688201689201690201691201692201693201694201695201696201697201698201699201700201701201702201703201704201705201706201707201708201709201710201711201712201713201714201715201716201717201718201719201720201721201722201723201724201725201726201727201728201729201730201731201732201733201734201735201736201737201738201739201740201741201742201743201744201745201746201747201748201749201750201751201752201753201754201755201756201757201758201759201760201761201762201763201764201765201766201767201768201769201770201771201772201773201774201775201776201777201778201779201780201781201782201783201784201785201786201787201788201789201790201791201792201793201794201795201796201797201798201799201800201801201802201803201804201805201806201807201808201809201810201811201812201813201814201815201816201817201818201819201820201821201822201823201824201825201826201827201828201829201830201831201832201833201834201835201836201837201838201839201840201841201842201843201844201845201846201847201848201849201850201851201852201853201854201855201856201857201858201859201860201861201862201863201864201865201866201867201868201869201870201871201872201873201874201875201876201877201878201879201880201881201882201883201884201885201886201887201888201889201890201891201892201893201894201895201896201897201898201899201900201901201902201903201904201905201906201907201908201909201910201911201912201913201914201915201916201917201918201919201920201921201922201923201924201925201926201927201928201929201930201931201932201933201934201935201936201937201938201939201940201941201942201943201944201945201946201947201948201949201950201951201952201953201954201955201956201957201958201959201960201961201962201963201964201965201966201967201968201969201970201971201972201973201974201975201976201977201978201979201980201981201982201983201984201985201986201987201988201989201990201991201992201993201994201995201996201997201998201999202000202001202002202003202004202005202006202007202008202009202010202011202012202013202014202015202016202017202018202019202020202021202022202023202024202025202026202027202028202029202030202031202032202033202034202035202036202037202038202039202040202041202042202043202044202045202046202047202048202049202050202051202052202053202054202055202056202057202058202059202060202061202062202063202064202065202066202067202068202069202070202071202072202073202074202075202076202077202078202079202080202081202082202083202084202085202086202087202088202089202090202091202092202093202094202095202096202097202098202099202100202101202102202103202104202105202106202107202108202109202110202111202112202113202114202115202116202117202118202119202120202121202122202123202124202125202126202127202128202129202130202131202132202133202134202135202136202137202138202139202140202141202142202143202144202145202146202147202148202149202150202151202152202153202154202155202156202157202158202159202160202161202162202163202164202165202166202167202168202169202170202171202172202173202174202175202176202177202178202179202180202181202182202183202184202185202186202187202188202189202190202191202192202193202194202195202196202197202198202199202200202201202202202203202204202205202206202207202208202209202210202211202212202213202214202215202216202217202218202219202220202221202222202223202224202225202226202227202228202229202230202231202232202233202234202235202236202237202238202239202240202241202242202243202244202245202246202247202248202249202250202251202252202253202254202255202256202257202258202259202260202261202262202263202264202265202266202267202268202269202270202271202272202273202274202275202276202277202278202279202280202281202282202283202284202285202286202287202288202289202290202291202292202293202294202295202296202297202298202299202300202301202302202303202304202305202306202307202308202309202310202311202312202313202314202315202316202317202318202319202320202321202322202323202324202325202326202327202328202329202330202331202332202333202334202335202336202337202338202339202340202341202342202343202344202345202346202347202348202349202350202351202352202353202354202355202356202357202358202359202360202361202362202363202364202365202366202367202368202369202370202371202372202373202374202375202376202377202378202379202380202381202382202383202384202385202386202387202388202389202390202391202392202393202394202395202396202397202398202399202400202401202402202403202404202405202406202407202408202409202410202411202412202413202414202415202416202417202418202419202420202421202422202423202424202425202426202427202428202429202430202431202432202433202434202435202436202437202438202439202440202441202442202443202444202445202446202447202448202449202450202451202452202453202454202455202456202457202458202459202460202461202462202463202464202465202466202467202468202469202470202471202472202473202474202475202476202477202478202479202480202481202482202483202484202485202486202487202488202489202490202491202492202493202494202495202496202497202498202499202500202501202502202503202504202505202506202507202508202509202510202511202512202513202514202515202516202517202518202519202520202521202522202523202524202525202526202527202528202529202530202531202532202533202534202535202536202537202538202539202540202541202542202543202544202545202546202547202548202549202550202551202552202553202554202555202556202557202558202559202560202561202562202563202564202565202566202567202568202569202570202571202572202573202574202575202576202577202578202579202580202581202582202583202584202585202586202587202588202589202590202591202592202593202594202595202596202597202598202599202600202601202602202603202604202605202606202607202608202609202610202611202612202613202614202615202616202617202618202619202620202621202622202623202624202625202626202627202628202629202630202631202632202633202634202635202636202637202638202639202640202641202642202643202644202645202646202647202648202649202650202651202652202653202654202655202656202657202658202659202660202661202662202663202664202665202666202667202668202669202670202671202672202673202674202675202676202677202678202679202680202681202682202683202684202685202686202687202688202689202690202691202692202693202694202695202696202697202698202699202700202701202702202703202704202705202706202707202708202709202710202711202712202713202714202715202716202717202718202719202720202721202722202723202724202725202726202727202728202729202730202731202732202733202734202735202736202737202738202739202740202741202742202743202744202745202746202747202748202749202750202751202752202753202754202755202756202757202758202759202760202761202762202763202764202765202766202767202768202769202770202771202772202773202774202775202776202777202778202779202780202781202782202783202784202785202786202787202788202789202790202791202792202793202794202795202796202797202798202799202800202801202802202803202804202805202806202807202808202809202810202811202812202813202814202815202816202817202818202819202820202821202822202823202824202825202826202827202828202829202830202831202832202833202834202835202836202837202838202839202840202841202842202843202844202845202846202847202848202849202850202851202852202853202854202855202856202857202858202859202860202861202862202863202864202865202866202867202868202869202870202871202872202873202874202875202876202877202878202879202880202881202882202883202884202885202886202887202888202889202890202891202892202893202894202895202896202897202898202899202900202901202902202903202904202905202906202907202908202909202910202911202912202913202914202915202916202917202918202919202920202921202922202923202924202925202926202927202928202929202930202931202932202933202934202935202936202937202938202939202940202941202942202943202944202945202946202947202948202949202950202951202952202953202954202955202956202957202958202959202960202961202962202963202964202965202966202967202968202969202970202971202972202973202974202975202976202977202978202979202980202981202982202983202984202985202986202987202988202989202990202991202992202993202994202995202996202997202998202999203000203001203002203003203004203005203006203007203008203009203010203011203012203013203014203015203016203017203018203019203020203021203022203023203024203025203026203027203028203029203030203031203032203033203034203035203036203037203038203039203040203041203042203043203044203045203046203047203048203049203050203051203052203053203054203055203056203057203058203059203060203061203062203063203064203065203066203067203068203069203070203071203072203073203074203075203076203077203078203079203080203081203082203083203084203085203086203087203088203089203090203091203092203093203094203095203096203097203098203099203100203101203102203103203104203105203106203107203108203109203110203111203112203113203114203115203116203117203118203119203120203121203122203123203124203125203126203127203128203129203130203131203132203133203134203135203136203137203138203139203140203141203142203143203144203145203146203147203148203149203150203151203152203153203154203155203156203157203158203159203160203161203162203163203164203165203166203167203168203169203170203171203172203173203174203175203176203177203178203179203180203181203182203183203184203185203186203187203188203189203190203191203192203193203194203195203196203197203198203199203200203201203202203203203204203205203206203207203208203209203210203211203212203213203214203215203216203217203218203219203220203221203222203223203224203225203226203227203228203229203230203231203232203233203234203235203236203237203238203239203240203241203242203243203244203245203246203247203248203249203250203251203252203253203254203255203256203257203258203259203260203261203262203263203264203265203266203267203268203269203270203271203272203273203274203275203276203277203278203279203280203281203282203283203284203285203286203287203288203289203290203291203292203293203294203295203296203297203298203299203300203301203302203303203304203305203306203307203308203309203310203311203312203313203314203315203316203317203318203319203320203321203322203323203324203325203326203327203328203329203330203331203332203333203334203335203336203337203338203339203340203341203342203343203344203345203346203347203348203349203350203351203352203353203354203355203356203357203358203359203360203361203362203363203364203365203366203367203368203369203370203371203372203373203374203375203376203377203378203379203380203381203382203383203384203385203386203387203388203389203390203391203392203393203394203395203396203397203398203399203400203401203402203403203404203405203406203407203408203409203410203411203412203413203414203415203416203417203418203419203420203421203422203423203424203425203426203427203428203429203430203431203432203433203434203435203436203437203438203439203440203441203442203443203444203445203446203447203448203449203450203451203452203453203454203455203456203457203458203459203460203461203462203463203464203465203466203467203468203469203470203471203472203473203474203475203476203477203478203479203480203481203482203483203484203485203486203487203488203489203490203491203492203493203494203495203496203497203498203499203500203501203502203503203504203505203506203507203508203509203510203511203512203513203514203515203516203517203518203519203520203521203522203523203524203525203526203527203528203529203530203531203532203533203534203535203536203537203538203539203540203541203542203543203544203545203546203547203548203549203550203551203552203553203554203555203556203557203558203559203560203561203562203563203564203565203566203567203568203569203570203571203572203573203574203575203576203577203578203579203580203581203582203583203584203585203586203587203588203589203590203591203592203593203594203595203596203597203598203599203600203601203602203603203604203605203606203607203608203609203610203611203612203613203614203615203616203617203618203619203620203621203622203623203624203625203626203627203628203629203630203631203632203633203634203635203636203637203638203639203640203641203642203643203644203645203646203647203648203649203650203651203652203653203654203655203656203657203658203659203660203661203662203663203664203665203666203667203668203669203670203671203672203673203674203675203676203677203678203679203680203681203682203683203684203685203686203687203688203689203690203691203692203693203694203695203696203697203698203699203700203701203702203703203704203705203706203707203708203709203710203711203712203713203714203715203716203717203718203719203720203721203722203723203724203725203726203727203728203729203730203731203732203733203734203735203736203737203738203739203740203741203742203743203744203745203746203747203748203749203750203751203752203753203754203755203756203757203758203759203760203761203762203763203764203765203766203767203768203769203770203771203772203773203774203775203776203777203778203779203780203781203782203783203784203785203786203787203788203789203790203791203792203793203794203795203796203797203798203799203800203801203802203803203804203805203806203807203808203809203810203811203812203813203814203815203816203817203818203819203820203821203822203823203824203825203826203827203828203829203830203831203832203833203834203835203836203837203838203839203840203841203842203843203844203845203846203847203848203849203850203851203852203853203854203855203856203857203858203859203860203861203862203863203864203865203866203867203868203869203870203871203872203873203874203875203876203877203878203879203880203881203882203883203884203885203886203887203888203889203890203891203892203893203894203895203896203897203898203899203900203901203902203903203904203905203906203907203908203909203910203911203912203913203914203915203916203917203918203919203920203921203922203923203924203925203926203927203928203929203930203931203932203933203934203935203936203937203938203939203940203941203942203943203944203945203946203947203948203949203950203951203952203953203954203955203956203957203958203959203960203961203962203963203964203965203966203967203968203969203970203971203972203973203974203975203976203977203978203979203980203981203982203983203984203985203986203987203988203989203990203991203992203993203994203995203996203997203998203999204000204001204002204003204004204005204006204007204008204009204010204011204012204013204014204015204016204017204018204019204020204021204022204023204024204025204026204027204028204029204030204031204032204033204034204035204036204037204038204039204040204041204042204043204044204045204046204047204048204049204050204051204052204053204054204055204056204057204058204059204060204061204062204063204064204065204066204067204068204069204070204071204072204073204074204075204076204077204078204079204080204081204082204083204084204085204086204087204088204089204090204091204092204093204094204095204096204097204098204099204100204101204102204103204104204105204106204107204108204109204110204111204112204113204114204115204116204117204118204119204120204121204122204123204124204125204126204127204128204129204130204131204132204133204134204135204136204137204138204139204140204141204142204143204144204145204146204147204148204149204150204151204152204153204154204155204156204157204158204159204160204161204162204163204164204165204166204167204168204169204170204171204172204173204174204175204176204177204178204179204180204181204182204183204184204185204186204187204188204189204190204191204192204193204194204195204196204197204198204199204200204201204202204203204204204205204206204207204208204209204210204211204212204213204214204215204216204217204218204219204220204221204222204223204224204225204226204227204228204229204230204231204232204233204234204235204236204237204238204239204240204241204242204243204244204245204246204247204248204249204250204251204252204253204254204255204256204257204258204259204260204261204262204263204264204265204266204267204268204269204270204271204272204273204274204275204276204277204278204279204280204281204282204283204284204285204286204287204288204289204290204291204292204293204294204295204296204297204298204299204300204301204302204303204304204305204306204307204308204309204310204311204312204313204314204315204316204317204318204319204320204321204322204323204324204325204326204327204328204329204330204331204332204333204334204335204336204337204338204339204340204341204342204343204344204345204346204347204348204349204350204351204352204353204354204355204356204357204358204359204360204361204362204363204364204365204366204367204368204369204370204371204372204373204374204375204376204377204378204379204380204381204382204383204384204385204386204387204388204389204390204391204392204393204394204395204396204397204398204399204400204401204402204403204404204405204406204407204408204409204410204411204412204413204414204415204416204417204418204419204420204421204422204423204424204425204426204427204428204429204430204431204432204433204434204435204436204437204438204439204440204441204442204443204444204445204446204447204448204449204450204451204452204453204454204455204456204457204458204459204460204461204462204463204464204465204466204467204468204469204470204471204472204473204474204475204476204477204478204479204480204481204482204483204484204485204486204487204488204489204490204491204492204493204494204495204496204497204498204499204500204501204502204503204504204505204506204507204508204509204510204511204512204513204514204515204516204517204518204519204520204521204522204523204524204525204526204527204528204529204530204531204532204533204534204535204536204537204538204539204540204541204542204543204544204545204546204547204548204549204550204551204552204553204554204555204556204557204558204559204560204561204562204563204564204565204566204567204568204569204570204571204572204573204574204575204576204577204578204579204580204581204582204583204584204585204586204587204588204589204590204591204592204593204594204595204596204597204598204599204600204601204602204603204604204605204606204607204608204609204610204611204612204613204614204615204616204617204618204619204620204621204622204623204624204625204626204627204628204629204630204631204632204633204634204635204636204637204638204639204640204641204642204643204644204645204646204647204648204649204650204651204652204653204654204655204656204657204658204659204660204661204662204663204664204665204666204667204668204669204670204671204672204673204674204675204676204677204678204679204680204681204682204683204684204685204686204687204688204689204690204691204692204693204694204695204696204697204698204699204700204701204702204703204704204705204706204707204708204709204710204711204712204713204714204715204716204717204718204719204720204721204722204723204724204725204726204727204728204729204730204731204732204733204734204735204736204737204738204739204740204741204742204743204744204745204746204747204748204749204750204751204752204753204754204755204756204757204758204759204760204761204762204763204764204765204766204767204768204769204770204771204772204773204774204775204776204777204778204779204780204781204782204783204784204785204786204787204788204789204790204791204792204793204794204795204796204797204798204799204800204801204802204803204804204805204806204807204808204809204810204811204812204813204814204815204816204817204818204819204820204821204822204823204824204825204826204827204828204829204830204831204832204833204834204835204836204837204838204839204840204841204842204843204844204845204846204847204848204849204850204851204852204853204854204855204856204857204858204859204860204861204862204863204864204865204866204867204868204869204870204871204872204873204874204875204876204877204878204879204880204881204882204883204884204885204886204887204888204889204890204891204892204893204894204895204896204897204898204899204900204901204902204903204904204905204906204907204908204909204910204911204912204913204914204915204916204917204918204919204920204921204922204923204924204925204926204927204928204929204930204931204932204933204934204935204936204937204938204939204940204941204942204943204944204945204946204947204948204949204950204951204952204953204954204955204956204957204958204959204960204961204962204963204964204965204966204967204968204969204970204971204972204973204974204975204976204977204978204979204980204981204982204983204984204985204986204987204988204989204990204991204992204993204994204995204996204997204998204999205000205001205002205003205004205005205006205007205008205009205010205011205012205013205014205015205016205017205018205019205020205021205022205023205024205025205026205027205028205029205030205031205032205033205034205035205036205037205038205039205040205041205042205043205044205045205046205047205048205049205050205051205052205053205054205055205056205057205058205059205060205061205062205063205064205065205066205067205068205069205070205071205072205073205074205075205076205077205078205079205080205081205082205083205084205085205086205087205088205089205090205091205092205093205094205095205096205097205098205099205100205101205102205103205104205105205106205107205108205109205110205111205112205113205114205115205116205117205118205119205120205121205122205123205124205125205126205127205128205129205130205131205132205133205134205135205136205137205138205139205140205141205142205143205144205145205146205147205148205149205150205151205152205153205154205155205156205157205158205159205160205161205162205163205164205165205166205167205168205169205170205171205172205173205174205175205176205177205178205179205180205181205182205183205184205185205186205187205188205189205190205191205192205193205194205195205196205197205198205199205200205201205202205203205204205205205206205207205208205209205210205211205212205213205214205215205216205217205218205219205220205221205222205223205224205225205226205227205228205229205230205231205232205233205234205235205236205237205238205239205240205241205242205243205244205245205246205247205248205249205250205251205252205253205254205255205256205257205258205259205260205261205262205263205264205265205266205267205268205269205270205271205272205273205274205275205276205277205278205279205280205281205282205283205284205285205286205287205288205289205290205291205292205293205294205295205296205297205298205299205300205301205302205303205304205305205306205307205308205309205310205311205312205313205314205315205316205317205318205319205320205321205322205323205324205325205326205327205328205329205330205331205332205333205334205335205336205337205338205339205340205341205342205343205344205345205346205347205348205349205350205351205352205353205354205355205356205357205358205359205360205361205362205363205364205365205366205367205368205369205370205371205372205373205374205375205376205377205378205379205380205381205382205383205384205385205386205387205388205389205390205391205392205393205394205395205396205397205398205399205400205401205402205403205404205405205406205407205408205409205410205411205412205413205414205415205416205417205418205419205420205421205422205423205424205425205426205427205428205429205430205431205432205433205434205435205436205437205438205439205440205441205442205443205444205445205446205447205448205449205450205451205452205453205454205455205456205457205458205459205460205461205462205463205464205465205466205467205468205469205470205471205472205473205474205475205476205477205478205479205480205481205482205483205484205485205486205487205488205489205490205491205492205493205494205495205496205497205498205499205500205501205502205503205504205505205506205507205508205509205510205511205512205513205514205515205516205517205518205519205520205521205522205523205524205525205526205527205528205529205530205531205532205533205534205535205536205537205538205539205540205541205542205543205544205545205546205547205548205549205550205551205552205553205554205555205556205557205558205559205560205561205562205563205564205565205566205567205568205569205570205571205572205573205574205575205576205577205578205579205580205581205582205583205584205585205586205587205588205589205590205591205592205593205594205595205596205597205598205599205600205601205602205603205604205605205606205607205608205609205610205611205612205613205614205615205616205617205618205619205620205621205622205623205624205625205626205627205628205629205630205631205632205633205634205635205636205637205638205639205640205641205642205643205644205645205646205647205648205649205650205651205652205653205654205655205656205657205658205659205660205661205662205663205664205665205666205667205668205669205670205671205672205673205674205675205676205677205678205679205680205681205682205683205684205685205686205687205688205689205690205691205692205693205694205695205696205697205698205699205700205701205702205703205704205705205706205707205708205709205710205711205712205713205714205715205716205717205718205719205720205721205722205723205724205725205726205727205728205729205730205731205732205733205734205735205736205737205738205739205740205741205742205743205744205745205746205747205748205749205750205751205752205753205754205755205756205757205758205759205760205761205762205763205764205765205766205767205768205769205770205771205772205773205774205775205776205777205778205779205780205781205782205783205784205785205786205787205788205789205790205791205792205793205794205795205796205797205798205799205800205801205802205803205804205805205806205807205808205809205810205811205812205813205814205815205816205817205818205819205820205821205822205823205824205825205826205827205828205829205830205831205832205833205834205835205836205837205838205839205840205841205842205843205844205845205846205847205848205849205850205851205852205853205854205855205856205857205858205859205860205861205862205863205864205865205866205867205868205869205870205871205872205873205874205875205876205877205878205879205880205881205882205883205884205885205886205887205888205889205890205891205892205893205894205895205896205897205898205899205900205901205902205903205904205905205906205907205908205909205910205911205912205913205914205915205916205917205918205919205920205921205922205923205924205925205926205927205928205929205930205931205932205933205934205935205936205937205938205939205940205941205942205943205944205945205946205947205948205949205950205951205952205953205954205955205956205957205958205959205960205961205962205963205964205965205966205967205968205969205970205971205972205973205974205975205976205977205978205979205980205981205982205983205984205985205986205987205988205989205990205991205992205993205994205995205996205997205998205999206000206001206002206003206004206005206006206007206008206009206010206011206012206013206014206015206016206017206018206019206020206021206022206023206024206025206026206027206028206029206030206031206032206033206034206035206036206037206038206039206040206041206042206043206044206045206046206047206048206049206050206051206052206053206054206055206056206057206058206059206060206061206062206063206064206065206066206067206068206069206070206071206072206073206074206075206076206077206078206079206080206081206082206083206084206085206086206087206088206089206090206091206092206093206094206095206096206097206098206099206100206101206102206103206104206105206106206107206108206109206110206111206112206113206114206115206116206117206118206119206120206121206122206123206124206125206126206127206128206129206130206131206132206133206134206135206136206137206138206139206140206141206142206143206144206145206146206147206148206149206150206151206152206153206154206155206156206157206158206159206160206161206162206163206164206165206166206167206168206169206170206171206172206173206174206175206176206177206178206179206180206181206182206183206184206185206186206187206188206189206190206191206192206193206194206195206196206197206198206199206200206201206202206203206204206205206206206207206208206209206210206211206212206213206214206215206216206217206218206219206220206221206222206223206224206225206226206227206228206229206230206231206232206233206234206235206236206237206238206239206240206241206242206243206244206245206246206247206248206249206250206251206252206253206254206255206256206257206258206259206260206261206262206263206264206265206266206267206268206269206270206271206272206273206274206275206276206277206278206279206280206281206282206283206284206285206286206287206288206289206290206291206292206293206294206295206296206297206298206299206300206301206302206303206304206305206306206307206308206309206310206311206312206313206314206315206316206317206318206319206320206321206322206323206324206325206326206327206328206329206330206331206332206333206334206335206336206337206338206339206340206341206342206343206344206345206346206347206348206349206350206351206352206353206354206355206356206357206358206359206360206361206362206363206364206365206366206367206368206369206370206371206372206373206374206375206376206377206378206379206380206381206382206383206384206385206386206387206388206389206390206391206392206393206394206395206396206397206398206399206400206401206402206403206404206405206406206407206408206409206410206411206412206413206414206415206416206417206418206419206420206421206422206423206424206425206426206427206428206429206430206431206432206433206434206435206436206437206438206439206440206441206442206443206444206445206446206447206448206449206450206451206452206453206454206455206456206457206458206459206460206461206462206463206464206465206466206467206468206469206470206471206472206473206474206475206476206477206478206479206480206481206482206483206484206485206486206487206488206489206490206491206492206493206494206495206496206497206498206499206500206501206502206503206504206505206506206507206508206509206510206511206512206513206514206515206516206517206518206519206520206521206522206523206524206525206526206527206528206529206530206531206532206533206534206535206536206537206538206539206540206541206542206543206544206545206546206547206548206549206550206551206552206553206554206555206556206557206558206559206560206561206562206563206564206565206566206567206568206569206570206571206572206573206574206575206576206577206578206579206580206581206582206583206584206585206586206587206588206589206590206591206592206593206594206595206596206597206598206599206600206601206602206603206604206605206606206607206608206609206610206611206612206613206614206615206616206617206618206619206620206621206622206623206624206625206626206627206628206629206630206631206632206633206634206635206636206637206638206639206640206641206642206643206644206645206646206647206648206649206650206651206652206653206654206655206656206657206658206659206660206661206662206663206664206665206666206667206668206669206670206671206672206673206674206675206676206677206678206679206680206681206682206683206684206685206686206687206688206689206690206691206692206693206694206695206696206697206698206699206700206701206702206703206704206705206706206707206708206709206710206711206712206713206714206715206716206717206718206719206720206721206722206723206724206725206726206727206728206729206730206731206732206733206734206735206736206737206738206739206740206741206742206743206744206745206746206747206748206749206750206751206752206753206754206755206756206757206758206759206760206761206762206763206764206765206766206767206768206769206770206771206772206773206774206775206776206777206778206779206780206781206782206783206784206785206786206787206788206789206790206791206792206793206794206795206796206797206798206799206800206801206802206803206804206805206806206807206808206809206810206811206812206813206814206815206816206817206818206819206820206821206822206823206824206825206826206827206828206829206830206831206832206833206834206835206836206837206838206839206840206841206842206843206844206845206846206847206848206849206850206851206852206853206854206855206856206857206858206859206860206861206862206863206864206865206866206867206868206869206870206871206872206873206874206875206876206877206878206879206880206881206882206883206884206885206886206887206888206889206890206891206892206893206894206895206896206897206898206899206900206901206902206903206904206905206906206907206908206909206910206911206912206913206914206915206916206917206918206919206920206921206922206923206924206925206926206927206928206929206930206931206932206933206934206935206936206937206938206939206940206941206942206943206944206945206946206947206948206949206950206951206952206953206954206955206956206957206958206959206960206961206962206963206964206965206966206967206968206969206970206971206972206973206974206975206976206977206978206979206980206981206982206983206984206985206986206987206988206989206990206991206992206993206994206995206996206997206998206999207000207001207002207003207004207005207006207007207008207009207010207011207012207013207014207015207016207017207018207019207020207021207022207023207024207025207026207027207028207029207030207031207032207033207034207035207036207037207038207039207040207041207042207043207044207045207046207047207048207049207050207051207052207053207054207055207056207057207058207059207060207061207062207063207064207065207066207067207068207069207070207071207072207073207074207075207076207077207078207079207080207081207082207083207084207085207086207087207088207089207090207091207092207093207094207095207096207097207098207099207100207101207102207103207104207105207106207107207108207109207110207111207112207113207114207115207116207117207118207119207120207121207122207123207124207125207126207127207128207129207130207131207132207133207134207135207136207137207138207139207140207141207142207143207144207145207146207147207148207149207150207151207152207153207154207155207156207157207158207159207160207161207162207163207164207165207166207167207168207169207170207171207172207173207174207175207176207177207178207179207180207181207182207183207184207185207186207187207188207189207190207191207192207193207194207195207196207197207198207199207200207201207202207203207204207205207206207207207208207209207210207211207212207213207214207215207216207217207218207219207220207221207222207223207224207225207226207227207228207229207230207231207232207233207234207235207236207237207238207239207240207241207242207243207244207245207246207247207248207249207250207251207252207253207254207255207256207257207258207259207260207261207262207263207264207265207266207267207268207269207270207271207272207273207274207275207276207277207278207279207280207281207282207283207284207285207286207287207288207289207290207291207292207293207294207295207296207297207298207299207300207301207302207303207304207305207306207307207308207309207310207311207312207313207314207315207316207317207318207319207320207321207322207323207324207325207326207327207328207329207330207331207332207333207334207335207336207337207338207339207340207341207342207343207344207345207346207347207348207349207350207351207352207353207354207355207356207357207358207359207360207361207362207363207364207365207366207367207368207369207370207371207372207373207374207375207376207377207378207379207380207381207382207383207384207385207386207387207388207389207390207391207392207393207394207395207396207397207398207399207400207401207402207403207404207405207406207407207408207409207410207411207412207413207414207415207416207417207418207419207420207421207422207423207424207425207426207427207428207429207430207431207432207433207434207435207436207437207438207439207440207441207442207443207444207445207446207447207448207449207450207451207452207453207454207455207456207457207458207459207460207461207462207463207464207465207466207467207468207469207470207471207472207473207474207475207476207477207478207479207480207481207482207483207484207485207486207487207488207489207490207491207492207493207494207495207496207497207498207499207500207501207502207503207504207505207506207507207508207509207510207511207512207513207514207515207516207517207518207519207520207521207522207523207524207525207526207527207528207529207530207531207532207533207534207535207536207537207538207539207540207541207542207543207544207545207546207547207548207549207550207551207552207553207554207555207556207557207558207559207560207561207562207563207564207565207566207567207568207569207570207571207572207573207574207575207576207577207578207579207580207581207582207583207584207585207586207587207588207589207590207591207592207593207594207595207596207597207598207599207600207601207602207603207604207605207606207607207608207609207610207611207612207613207614207615207616207617207618207619207620207621207622207623207624207625207626207627207628207629207630207631207632207633207634207635207636207637207638207639207640207641207642207643207644207645207646207647207648207649207650207651207652207653207654207655207656207657207658207659207660207661207662207663207664207665207666207667207668207669207670207671207672207673207674207675207676207677207678207679207680207681207682207683207684207685207686207687207688207689207690207691207692207693207694207695207696207697207698207699207700207701207702207703207704207705207706207707207708207709207710207711207712207713207714207715207716207717207718207719207720207721207722207723207724207725207726207727207728207729207730207731207732207733207734207735207736207737207738207739207740207741207742207743207744207745207746207747207748207749207750207751207752207753207754207755207756207757207758207759207760207761207762207763207764207765207766207767207768207769207770207771207772207773207774207775207776207777207778207779207780207781207782207783207784207785207786207787207788207789207790207791207792207793207794207795207796207797207798207799207800207801207802207803207804207805207806207807207808207809207810207811207812207813207814207815207816207817207818207819207820207821207822207823207824207825207826207827207828207829207830207831207832207833207834207835207836207837207838207839207840207841207842207843207844207845207846207847207848207849207850207851207852207853207854207855207856207857207858207859207860207861207862207863207864207865207866207867207868207869207870207871207872207873207874207875207876207877207878207879207880207881207882207883207884207885207886207887207888207889207890207891207892207893207894207895207896207897207898207899207900207901207902207903207904207905207906207907207908207909207910207911207912207913207914207915207916207917207918207919207920207921207922207923207924207925207926207927207928207929207930207931207932207933207934207935207936207937207938207939207940207941207942207943207944207945207946207947207948207949207950207951207952207953207954207955207956207957207958207959207960207961207962207963207964207965207966207967207968207969207970207971207972207973207974207975207976207977207978207979207980207981207982207983207984207985207986207987207988207989207990207991207992207993207994207995207996207997207998207999208000208001208002208003208004208005208006208007208008208009208010208011208012208013208014208015208016208017208018208019208020208021208022208023208024208025208026208027208028208029208030208031208032208033208034208035208036208037208038208039208040208041208042208043208044208045208046208047208048208049208050208051208052208053208054208055208056208057208058208059208060208061208062208063208064208065208066208067208068208069208070208071208072208073208074208075208076208077208078208079208080208081208082208083208084208085208086208087208088208089208090208091208092208093208094208095208096208097208098208099208100208101208102208103208104208105208106208107208108208109208110208111208112208113208114208115208116208117208118208119208120208121208122208123208124208125208126208127208128208129208130208131208132208133208134208135208136208137208138208139208140208141208142208143208144208145208146208147208148208149208150208151208152208153208154208155208156208157208158208159208160208161208162208163208164208165208166208167208168208169208170208171208172208173208174208175208176208177208178208179208180208181208182208183208184208185208186208187208188208189208190208191208192208193208194208195208196208197208198208199208200208201208202208203208204208205208206208207208208208209208210208211208212208213208214208215208216208217208218208219208220208221208222208223208224208225208226208227208228208229208230208231208232208233208234208235208236208237208238208239208240208241208242208243208244208245208246208247208248208249208250208251208252208253208254208255208256208257208258208259208260208261208262208263208264208265208266208267208268208269208270208271208272208273208274208275208276208277208278208279208280208281208282208283208284208285208286208287208288208289208290208291208292208293208294208295208296208297208298208299208300208301208302208303208304208305208306208307208308208309208310208311208312208313208314208315208316208317208318208319208320208321208322208323208324208325208326208327208328208329208330208331208332208333208334208335208336208337208338208339208340208341208342208343208344208345208346208347208348208349208350208351208352208353208354208355208356208357208358208359208360208361208362208363208364208365208366208367208368208369208370208371208372208373208374208375208376208377208378208379208380208381208382208383208384208385208386208387208388208389208390208391208392208393208394208395208396208397208398208399208400208401208402208403208404208405208406208407208408208409208410208411208412208413208414208415208416208417208418208419208420208421208422208423208424208425208426208427208428208429208430208431208432208433208434208435208436208437208438208439208440208441208442208443208444208445208446208447208448208449208450208451208452208453208454208455208456208457208458208459208460208461208462208463208464208465208466208467208468208469208470208471208472208473208474208475208476208477208478208479208480208481208482208483208484208485208486208487208488208489208490208491208492208493208494208495208496208497208498208499208500208501208502208503208504208505208506208507208508208509208510208511208512208513208514208515208516208517208518208519208520208521208522208523208524208525208526208527208528208529208530208531208532208533208534208535208536208537208538208539208540208541208542208543208544208545208546208547208548208549208550208551208552208553208554208555208556208557208558208559208560208561208562208563208564208565208566208567208568208569208570208571208572208573208574208575208576208577208578208579208580208581208582208583208584208585208586208587208588208589208590208591208592208593208594208595208596208597208598208599208600208601208602208603208604208605208606208607208608208609208610208611208612208613208614208615208616208617208618208619208620208621208622208623208624208625208626208627208628208629208630208631208632208633208634208635208636208637208638208639208640208641208642208643208644208645208646208647208648208649208650208651208652208653208654208655208656208657208658208659208660208661208662208663208664208665208666208667208668208669208670208671208672208673208674208675208676208677208678208679208680208681208682208683208684208685208686208687208688208689208690208691208692208693208694208695208696208697208698208699208700208701208702208703208704208705208706208707208708208709208710208711208712208713208714208715208716208717208718208719208720208721208722208723208724208725208726208727208728208729208730208731208732208733208734208735208736208737208738208739208740208741208742208743208744208745208746208747208748208749208750208751208752208753208754208755208756208757208758208759208760208761208762208763208764208765208766208767208768208769208770208771208772208773208774208775208776208777208778208779208780208781208782208783208784208785208786208787208788208789208790208791208792208793208794208795208796208797208798208799208800208801208802208803208804208805208806208807208808208809208810208811208812208813208814208815208816208817208818208819208820208821208822208823208824208825208826208827208828208829208830208831208832208833208834208835208836208837208838208839208840208841208842208843208844208845208846208847208848208849208850208851208852208853208854208855208856208857208858208859208860208861208862208863208864208865208866208867208868208869208870208871208872208873208874208875208876208877208878208879208880208881208882208883208884208885208886208887208888208889208890208891208892208893208894208895208896208897208898208899208900208901208902208903208904208905208906208907208908208909208910208911208912208913208914208915208916208917208918208919208920208921208922208923208924208925208926208927208928208929208930208931208932208933208934208935208936208937208938208939208940208941208942208943208944208945208946208947208948208949208950208951208952208953208954208955208956208957208958208959208960208961208962208963208964208965208966208967208968208969208970208971208972208973208974208975208976208977208978208979208980208981208982208983208984208985208986208987208988208989208990208991208992208993208994208995208996208997208998208999209000209001209002209003209004209005209006209007209008209009209010209011209012209013209014209015209016209017209018209019209020209021209022209023209024209025209026209027209028209029209030209031209032209033209034209035209036209037209038209039209040209041209042209043209044209045209046209047209048209049209050209051209052209053209054209055209056209057209058209059209060209061209062209063209064209065209066209067209068209069209070209071209072209073209074209075209076209077209078209079209080209081209082209083209084209085209086209087209088209089209090209091209092209093209094209095209096209097209098209099209100209101209102209103209104209105209106209107209108209109209110209111209112209113209114209115209116209117209118209119209120209121209122209123209124209125209126209127209128209129209130209131209132209133209134209135209136209137209138209139209140209141209142209143209144209145209146209147209148209149209150209151209152209153209154209155209156209157209158209159209160209161209162209163209164209165209166209167209168209169209170209171209172209173209174209175209176209177209178209179209180209181209182209183209184209185209186209187209188209189209190209191209192209193209194209195209196209197209198209199209200209201209202209203209204209205209206209207209208209209209210209211209212209213209214209215209216209217209218209219209220209221209222209223209224209225209226209227209228209229209230209231209232209233209234209235209236209237209238209239209240209241209242209243209244209245209246209247209248209249209250209251209252209253209254209255209256209257209258209259209260209261209262209263209264209265209266209267209268209269209270209271209272209273209274209275209276209277209278209279209280209281209282209283209284209285209286209287209288209289209290209291209292209293209294209295209296209297209298209299209300209301209302209303209304209305209306209307209308209309209310209311209312209313209314209315209316209317209318209319209320209321209322209323209324209325209326209327209328209329209330209331209332209333209334209335209336209337209338209339209340209341209342209343209344209345209346209347209348209349209350209351209352209353209354209355209356209357209358209359209360209361209362209363209364209365209366209367209368209369209370209371209372209373209374209375209376209377209378209379209380209381209382209383209384209385209386209387209388209389209390209391209392209393209394209395209396209397209398209399209400209401209402209403209404209405209406209407209408209409209410209411209412209413209414209415209416209417209418209419209420209421209422209423209424209425209426209427209428209429209430209431209432209433209434209435209436209437209438209439209440209441209442209443209444209445209446209447209448209449209450209451209452209453209454209455209456209457209458209459209460209461209462209463209464209465209466209467209468209469209470209471209472209473209474209475209476209477209478209479209480209481209482209483209484209485209486209487209488209489209490209491209492209493209494209495209496209497209498209499209500209501209502209503209504209505209506209507209508209509209510209511209512209513209514209515209516209517209518209519209520209521209522209523209524209525209526209527209528209529209530209531209532209533209534209535209536209537209538209539209540209541209542209543209544209545209546209547209548209549209550209551209552209553209554209555209556209557209558209559209560209561209562209563209564209565209566209567209568209569209570209571209572209573209574209575209576209577209578209579209580209581209582209583209584209585209586209587209588209589209590209591209592209593209594209595209596209597209598209599209600209601209602209603209604209605209606209607209608209609209610209611209612209613209614209615209616209617209618209619209620209621209622209623209624209625209626209627209628209629209630209631209632209633209634209635209636209637209638209639209640209641209642209643209644209645209646209647209648209649209650209651209652209653209654209655209656209657209658209659209660209661209662209663209664209665209666209667209668209669209670209671209672209673209674209675209676209677209678209679209680209681209682209683209684209685209686209687209688209689209690209691209692209693209694209695209696209697209698209699209700209701209702209703209704209705209706209707209708209709209710209711209712209713209714209715209716209717209718209719209720209721209722209723209724209725209726209727209728209729209730209731209732209733209734209735209736209737209738209739209740209741209742209743209744209745209746209747209748209749209750209751209752209753209754209755209756209757209758209759209760209761209762209763209764209765209766209767209768209769209770209771209772209773209774209775209776209777209778209779209780209781209782209783209784209785209786209787209788209789209790209791209792209793209794209795209796209797209798209799209800209801209802209803209804209805209806209807209808209809209810209811209812209813209814209815209816209817209818209819209820209821209822209823209824209825209826209827209828209829209830209831209832209833209834209835209836209837209838209839209840209841209842209843209844209845209846209847209848209849209850209851209852209853209854209855209856209857209858209859209860209861209862209863209864209865209866209867209868209869209870209871209872209873209874209875209876209877209878209879209880209881209882209883209884209885209886209887209888209889209890209891209892209893209894209895209896209897209898209899209900209901209902209903209904209905209906209907209908209909209910209911209912209913209914209915209916209917209918209919209920209921209922209923209924209925209926209927209928209929209930209931209932209933209934209935209936209937209938209939209940209941209942209943209944209945209946209947209948209949209950209951209952209953209954209955209956209957209958209959209960209961209962209963209964209965209966209967209968209969209970209971209972209973209974209975209976209977209978209979209980209981209982209983209984209985209986209987209988209989209990209991209992209993209994209995209996209997209998209999210000210001210002210003210004210005210006210007210008210009210010210011210012210013210014210015210016210017210018210019210020210021210022210023210024210025210026210027210028210029210030210031210032210033210034210035210036210037210038210039210040210041210042210043210044210045210046210047210048210049210050210051210052210053210054210055210056210057210058210059210060210061210062210063210064210065210066210067210068210069210070210071210072210073210074210075210076210077210078210079210080210081210082210083210084210085210086210087210088210089210090210091210092210093210094210095210096210097210098210099210100210101210102210103210104210105210106210107210108210109210110210111210112210113210114210115210116210117210118210119210120210121210122210123210124210125210126210127210128210129210130210131210132210133210134210135210136210137210138210139210140210141210142210143210144210145210146210147210148210149210150210151210152210153210154210155210156210157210158210159210160210161210162210163210164210165210166210167210168210169210170210171210172210173210174210175210176210177210178210179210180210181210182210183210184210185210186210187210188210189210190210191210192210193210194210195210196210197210198210199210200210201210202210203210204210205210206210207210208210209210210210211210212210213210214210215210216210217210218210219210220210221210222210223210224210225210226210227210228210229210230210231210232210233210234210235210236210237210238210239210240210241210242210243210244210245210246210247210248210249210250210251210252210253210254210255210256210257210258210259210260210261210262210263210264210265210266210267210268210269210270210271210272210273210274210275210276210277210278210279210280210281210282210283210284210285210286210287210288210289210290210291210292210293210294210295210296210297210298210299210300210301210302210303210304210305210306210307210308210309210310210311210312210313210314210315210316210317210318210319210320210321210322210323210324210325210326210327210328210329210330210331210332210333210334210335210336210337210338210339210340210341210342210343210344210345210346210347210348210349210350210351210352210353210354210355210356210357210358210359210360210361210362210363210364210365210366210367210368210369210370210371210372210373210374210375210376210377210378210379210380210381210382210383210384210385210386210387210388210389210390210391210392210393210394210395210396210397210398210399210400210401210402210403210404210405210406210407210408210409210410210411210412210413210414210415210416210417210418210419210420210421210422210423210424210425210426210427210428210429210430210431210432210433210434210435210436210437210438210439210440210441210442210443210444210445210446210447210448210449210450210451210452210453210454210455210456210457210458210459210460210461210462210463210464210465210466210467210468210469210470210471210472210473210474210475210476210477210478210479210480210481210482210483210484210485210486210487210488210489210490210491210492210493210494210495210496210497210498210499210500210501210502210503210504210505210506210507210508210509210510210511210512210513210514210515210516210517210518210519210520210521210522210523210524210525210526210527210528210529210530210531210532210533210534210535210536210537210538210539210540210541210542210543210544210545210546210547210548210549210550210551210552210553210554210555210556210557210558210559210560210561210562210563210564210565210566210567210568210569210570210571210572210573210574210575210576210577210578210579210580210581210582210583210584210585210586210587210588210589210590210591210592210593210594210595210596210597210598210599210600210601210602210603210604210605210606210607210608210609210610210611210612210613210614210615210616210617210618210619210620210621210622210623210624210625210626210627210628210629210630210631210632210633210634210635210636210637210638210639210640210641210642210643210644210645210646210647210648210649210650210651210652210653210654210655210656210657210658210659210660210661210662210663210664210665210666210667210668210669210670210671210672210673210674210675210676210677210678210679210680210681210682210683210684210685210686210687210688210689210690210691210692210693210694210695210696210697210698210699210700210701210702210703210704210705210706210707210708210709210710210711210712210713210714210715210716210717210718210719210720210721210722210723210724210725210726210727210728210729210730210731210732210733210734210735210736210737210738210739210740210741210742210743210744210745210746210747210748210749210750210751210752210753210754210755210756210757210758210759210760210761210762210763210764210765210766210767210768210769210770210771210772210773210774210775210776210777210778210779210780210781210782210783210784210785210786210787210788210789210790210791210792210793210794210795210796210797210798210799210800210801210802210803210804210805210806210807210808210809210810210811210812210813210814210815210816210817210818210819210820210821210822210823210824210825210826210827210828210829210830210831210832210833210834210835210836210837210838210839210840210841210842210843210844210845210846210847210848210849210850210851210852210853210854210855210856210857210858210859210860210861210862210863210864210865210866210867210868210869210870210871210872210873210874210875210876210877210878210879210880210881210882210883210884210885210886210887210888210889210890210891210892210893210894210895210896210897210898210899210900210901210902210903210904210905210906210907210908210909210910210911210912210913210914210915210916210917210918210919210920210921210922210923210924210925210926210927210928210929210930210931210932210933210934210935210936210937210938210939210940210941210942210943210944210945210946210947210948210949210950210951210952210953210954210955210956210957210958210959210960210961210962210963210964210965210966210967210968210969210970210971210972210973210974210975210976210977210978210979210980210981210982210983210984210985210986210987210988210989210990210991210992210993210994210995210996210997210998210999211000211001211002211003211004211005211006211007211008211009211010211011211012211013211014211015211016211017211018211019211020211021211022211023211024211025211026211027211028211029211030211031211032211033211034211035211036211037211038211039211040211041211042211043211044211045211046211047211048211049211050211051211052211053211054211055211056211057211058211059211060211061211062211063211064211065211066211067211068211069211070211071211072211073211074211075211076211077211078211079211080211081211082211083211084211085211086211087211088211089211090211091211092211093211094211095211096211097211098211099211100211101211102211103211104211105211106211107211108211109211110211111211112211113211114211115211116211117211118211119211120211121211122211123211124211125211126211127211128211129211130211131211132211133211134211135211136211137211138211139211140211141211142211143211144211145211146211147211148211149211150211151211152211153211154211155211156211157211158211159211160211161211162211163211164211165211166211167211168211169211170211171211172211173211174211175211176211177211178211179211180211181211182211183211184211185211186211187211188211189211190211191211192211193211194211195211196211197211198211199211200211201211202211203211204211205211206211207211208211209211210211211211212211213211214211215211216211217211218211219211220211221211222211223211224211225211226211227211228211229211230211231211232211233211234211235211236211237211238211239211240211241211242211243211244211245211246211247211248211249211250211251211252211253211254211255211256211257211258211259211260211261211262211263211264211265211266211267211268211269211270211271211272211273211274211275211276211277211278211279211280211281211282211283211284211285211286211287211288211289211290211291211292211293211294211295211296211297211298211299211300211301211302211303211304211305211306211307211308211309211310211311211312211313211314211315211316211317211318211319211320211321211322211323211324211325211326211327211328211329211330211331211332211333211334211335211336211337211338211339211340211341211342211343211344211345211346211347211348211349211350211351211352211353211354211355211356211357211358211359211360211361211362211363211364211365211366211367211368211369211370211371211372211373211374211375211376211377211378211379211380211381211382211383211384211385211386211387211388211389211390211391211392211393211394211395211396211397211398211399211400211401211402211403211404211405211406211407211408211409211410211411211412211413211414211415211416211417211418211419211420211421211422211423211424211425211426211427211428211429211430211431211432211433211434211435211436211437211438211439211440211441211442211443211444211445211446211447211448211449211450211451211452211453211454211455211456211457211458211459211460211461211462211463211464211465211466211467211468211469211470211471211472211473211474211475211476211477211478211479211480211481211482211483211484211485211486211487211488211489211490211491211492211493211494211495211496211497211498211499211500211501211502211503211504211505211506211507211508211509211510211511211512211513211514211515211516211517211518211519211520211521211522211523211524211525211526211527211528211529211530211531211532211533211534211535211536211537211538211539211540211541211542211543211544211545211546211547211548211549211550211551211552211553211554211555211556211557211558211559211560211561211562211563211564211565211566211567211568211569211570211571211572211573211574211575211576211577211578211579211580211581211582211583211584211585211586211587211588211589211590211591211592211593211594211595211596211597211598211599211600211601211602211603211604211605211606211607211608211609211610211611211612211613211614211615211616211617211618211619211620211621211622211623211624211625211626211627211628211629211630211631211632211633211634211635211636211637211638211639211640211641211642211643211644211645211646211647211648211649211650211651211652211653211654211655211656211657211658211659211660211661211662211663211664211665211666211667211668211669211670211671211672211673211674211675211676211677211678211679211680211681211682211683211684211685211686211687211688211689211690211691211692211693211694211695211696211697211698211699211700211701211702211703211704211705211706211707211708211709211710211711211712211713211714211715211716211717211718211719211720211721211722211723211724211725211726211727211728211729211730211731211732211733211734211735211736211737211738211739211740211741211742211743211744211745211746211747211748211749211750211751211752211753211754211755211756211757211758211759211760211761211762211763211764211765211766211767211768211769211770211771211772211773211774211775211776211777211778211779211780211781211782211783211784211785211786211787211788211789211790211791211792211793211794211795211796211797211798211799211800211801211802211803211804211805211806211807211808211809211810211811211812211813211814211815211816211817211818211819211820211821211822211823211824211825211826211827211828211829211830211831211832211833211834211835211836211837211838211839211840211841211842211843211844211845211846211847211848211849211850211851211852211853211854211855211856211857211858211859211860211861211862211863211864211865211866211867211868211869211870211871211872211873211874211875211876211877211878211879211880211881211882211883211884211885211886211887211888211889211890211891211892211893211894211895211896211897211898211899211900211901211902211903211904211905211906211907211908211909211910211911211912211913211914211915211916211917211918211919211920211921211922211923211924211925211926211927211928211929211930211931211932211933211934211935211936211937211938211939211940211941211942211943211944211945211946211947211948211949211950211951211952211953211954211955211956211957211958211959211960211961211962211963211964211965211966211967211968211969211970211971211972211973211974211975211976211977211978211979211980211981211982211983211984211985211986211987211988211989211990211991211992211993211994211995211996211997211998211999212000212001212002212003212004212005212006212007212008212009212010212011212012212013212014212015212016212017212018212019212020212021212022212023212024212025212026212027212028212029212030212031212032212033212034212035212036212037212038212039212040212041212042212043212044212045212046212047212048212049212050212051212052212053212054212055212056212057212058212059212060212061212062212063212064212065212066212067212068212069212070212071212072212073212074212075212076212077212078212079212080212081212082212083212084212085212086212087212088212089212090212091212092212093212094212095212096212097212098212099212100212101212102212103212104212105212106212107212108212109212110212111212112212113212114212115212116212117212118212119212120212121212122212123212124212125212126212127212128212129212130212131212132212133212134212135212136212137212138212139212140212141212142212143212144212145212146212147212148212149212150212151212152212153212154212155212156212157212158212159212160212161212162212163212164212165212166212167212168212169212170212171212172212173212174212175212176212177212178212179212180212181212182212183212184212185212186212187212188212189212190212191212192212193212194212195212196212197212198212199212200212201212202212203212204212205212206212207212208212209212210212211212212212213212214212215212216212217212218212219212220212221212222212223212224212225212226212227212228212229212230212231212232212233212234212235212236212237212238212239212240212241212242212243212244212245212246212247212248212249212250212251212252212253212254212255212256212257212258212259212260212261212262212263212264212265212266212267212268212269212270212271212272212273212274212275212276212277212278212279212280212281212282212283212284212285212286212287212288212289212290212291212292212293212294212295212296212297212298212299212300212301212302212303212304212305212306212307212308212309212310212311212312212313212314212315212316212317212318212319212320212321212322212323212324212325212326212327212328212329212330212331212332212333212334212335212336212337212338212339212340212341212342212343212344212345212346212347212348212349212350212351212352212353212354212355212356212357212358212359212360212361212362212363212364212365212366212367212368212369212370212371212372212373212374212375212376212377212378212379212380212381212382212383212384212385212386212387212388212389212390212391212392212393212394212395212396212397212398212399212400212401212402212403212404212405212406212407212408212409212410212411212412212413212414212415212416212417212418212419212420212421212422212423212424212425212426212427212428212429212430212431212432212433212434212435212436212437212438212439212440212441212442212443212444212445212446212447212448212449212450212451212452212453212454212455212456212457212458212459212460212461212462212463212464212465212466212467212468212469212470212471212472212473212474212475212476212477212478212479212480212481212482212483212484212485212486212487212488212489212490212491212492212493212494212495212496212497212498212499212500212501212502212503212504212505212506212507212508212509212510212511212512212513212514212515212516212517212518212519212520212521212522212523212524212525212526212527212528212529212530212531212532212533212534212535212536212537212538212539212540212541212542212543212544212545212546212547212548212549212550212551212552212553212554212555212556212557212558212559212560212561212562212563212564212565212566212567212568212569212570212571212572212573212574212575212576212577212578212579212580212581212582212583212584212585212586212587212588212589212590212591212592212593212594212595212596212597212598212599212600212601212602212603212604212605212606212607212608212609212610212611212612212613212614212615212616212617212618212619212620212621212622212623212624212625212626212627212628212629212630212631212632212633212634212635212636212637212638212639212640212641212642212643212644212645212646212647212648212649212650212651212652212653212654212655212656212657212658212659212660212661212662212663212664212665212666212667212668212669212670212671212672212673212674212675212676212677212678212679212680212681212682212683212684212685212686212687212688212689212690212691212692212693212694212695212696212697212698212699212700212701212702212703212704212705212706212707212708212709212710212711212712212713212714212715212716212717212718212719212720212721212722212723212724212725212726212727212728212729212730212731212732212733212734212735212736212737212738212739212740212741212742212743212744212745212746212747212748212749212750212751212752212753212754212755212756212757212758212759212760212761212762212763212764212765212766212767212768212769212770212771212772212773212774212775212776212777212778212779212780212781212782212783212784212785212786212787212788212789212790212791212792212793212794212795212796212797212798212799212800212801212802212803212804212805212806212807212808212809212810212811212812212813212814212815212816212817212818212819212820212821212822212823212824212825212826212827212828212829212830212831212832212833212834212835212836212837212838212839212840212841212842212843212844212845212846212847212848212849212850212851212852212853212854212855212856212857212858212859212860212861212862212863212864212865212866212867212868212869212870212871212872212873212874212875212876212877212878212879212880212881212882212883212884212885212886212887212888212889212890212891212892212893212894212895212896212897212898212899212900212901212902212903212904212905212906212907212908212909212910212911212912212913212914212915212916212917212918212919212920212921212922212923212924212925212926212927212928212929212930212931212932212933212934212935212936212937212938212939212940212941212942212943212944212945212946212947212948212949212950212951212952212953212954212955212956212957212958212959212960212961212962212963212964212965212966212967212968212969212970212971212972212973212974212975212976212977212978212979212980212981212982212983212984212985212986212987212988212989212990212991212992212993212994212995212996212997212998212999213000213001213002213003213004213005213006213007213008213009213010213011213012213013213014213015213016213017213018213019213020213021213022213023213024213025213026213027213028213029213030213031213032213033213034213035213036213037213038213039213040213041213042213043213044213045213046213047213048213049213050213051213052213053213054213055213056213057213058213059213060213061213062213063213064213065213066213067213068213069213070213071213072213073213074213075213076213077213078213079213080213081213082213083213084213085213086213087213088213089213090213091213092213093213094213095213096213097213098213099213100213101213102213103213104213105213106213107213108213109213110213111213112213113213114213115213116213117213118213119213120213121213122213123213124213125213126213127213128213129213130213131213132213133213134213135213136213137213138213139213140213141213142213143213144213145213146213147213148213149213150213151213152213153213154213155213156213157213158213159213160213161213162213163213164213165213166213167213168213169213170213171213172213173213174213175213176213177213178213179213180213181213182213183213184213185213186213187213188213189213190213191213192213193213194213195213196213197213198213199213200213201213202213203213204213205213206213207213208213209213210213211213212213213213214213215213216213217213218213219213220213221213222213223213224213225213226213227213228213229213230213231213232213233213234213235213236213237213238213239213240213241213242213243213244213245213246213247213248213249213250213251213252213253213254213255213256213257213258213259213260213261213262213263213264213265213266213267213268213269213270213271213272213273213274213275213276213277213278213279213280213281213282213283213284213285213286213287213288213289213290213291213292213293213294213295213296213297213298213299213300213301213302213303213304213305213306213307213308213309213310213311213312213313213314213315213316213317213318213319213320213321213322213323213324213325213326213327213328213329213330213331213332213333213334213335213336213337213338213339213340213341213342213343213344213345213346213347213348213349213350213351213352213353213354213355213356213357213358213359213360213361213362213363213364213365213366213367213368213369213370213371213372213373213374213375213376213377213378213379213380213381213382213383213384213385213386213387213388213389213390213391213392213393213394213395213396213397213398213399213400213401213402213403213404213405213406213407213408213409213410213411213412213413213414213415213416213417213418213419213420213421213422213423213424213425213426213427213428213429213430213431213432213433213434213435213436213437213438213439213440213441213442213443213444213445213446213447213448213449213450213451213452213453213454213455213456213457213458213459213460213461213462213463213464213465213466213467213468213469213470213471213472213473213474213475213476213477213478213479213480213481213482213483213484213485213486213487213488213489213490213491213492213493213494213495213496213497213498213499213500213501213502213503213504213505213506213507213508213509213510213511213512213513213514213515213516213517213518213519213520213521213522213523213524213525213526213527213528213529213530213531213532213533213534213535213536213537213538213539213540213541213542213543213544213545213546213547213548213549213550213551213552213553213554213555213556213557213558213559213560213561213562213563213564213565213566213567213568213569213570213571213572213573213574213575213576213577213578213579213580213581213582213583213584213585213586213587213588213589213590213591213592213593213594213595213596213597213598213599213600213601213602213603213604213605213606213607213608213609213610213611213612213613213614213615213616213617213618213619213620213621213622213623213624213625213626213627213628213629213630213631213632213633213634213635213636213637213638213639213640213641213642213643213644213645213646213647213648213649213650213651213652213653213654213655213656213657213658213659213660213661213662213663213664213665213666213667213668213669213670213671213672213673213674213675213676213677213678213679213680213681213682213683213684213685213686213687213688213689213690213691213692213693213694213695213696213697213698213699213700213701213702213703213704213705213706213707213708213709213710213711213712213713213714213715213716213717213718213719213720213721213722213723213724213725213726213727213728213729213730213731213732213733213734213735213736213737213738213739213740213741213742213743213744213745213746213747213748213749213750213751213752213753213754213755213756213757213758213759213760213761213762213763213764213765213766213767213768213769213770213771213772213773213774213775213776213777213778213779213780213781213782213783213784213785213786213787213788213789213790213791213792213793213794213795213796213797213798213799213800213801213802213803213804213805213806213807213808213809213810213811213812213813213814213815213816213817213818213819213820213821213822213823213824213825213826213827213828213829213830213831213832213833213834213835213836213837213838213839213840213841213842213843213844213845213846213847213848213849213850213851213852213853213854213855213856213857213858213859213860213861213862213863213864213865213866213867213868213869213870213871213872213873213874213875213876213877213878213879213880213881213882213883213884213885213886213887213888213889213890213891213892213893213894213895213896213897213898213899213900213901213902213903213904213905213906213907213908213909213910213911213912213913213914213915213916213917213918213919213920213921213922213923213924213925213926213927213928213929213930213931213932213933213934213935213936213937213938213939213940213941213942213943213944213945213946213947213948213949213950213951213952213953213954213955213956213957213958213959213960213961213962213963213964213965213966213967213968213969213970213971213972213973213974213975213976213977213978213979213980213981213982213983213984213985213986213987213988213989213990213991213992213993213994213995213996213997213998213999214000214001214002214003214004214005214006214007214008214009214010214011214012214013214014214015214016214017214018214019214020214021214022214023214024214025214026214027214028214029214030214031214032214033214034214035214036214037214038214039214040214041214042214043214044214045214046214047214048214049214050214051214052214053214054214055214056214057214058214059214060214061214062214063214064214065214066214067214068214069214070214071214072214073214074214075214076214077214078214079214080214081214082214083214084214085214086214087214088214089214090214091214092214093214094214095214096214097214098214099214100214101214102214103214104214105214106214107214108214109214110214111214112214113214114214115214116214117214118214119214120214121214122214123214124214125214126214127214128214129214130214131214132214133214134214135214136214137214138214139214140214141214142214143214144214145214146214147214148214149214150214151214152214153214154214155214156214157214158214159214160214161214162214163214164214165214166214167214168214169214170214171214172214173214174214175214176214177214178214179214180214181214182214183214184214185214186214187214188214189214190214191214192214193214194214195214196214197214198214199214200214201214202214203214204214205214206214207214208214209214210214211214212214213214214214215214216214217214218214219214220214221214222214223214224214225214226214227214228214229214230214231214232214233214234214235214236214237214238214239214240214241214242214243214244214245214246214247214248214249214250214251214252214253214254214255214256214257214258214259214260214261214262214263214264214265214266214267214268214269214270214271214272214273214274214275214276214277214278214279214280214281214282214283214284214285214286214287214288214289214290214291214292214293214294214295214296214297214298214299214300214301214302214303214304214305214306214307214308214309214310214311214312214313214314214315214316214317214318214319214320214321214322214323214324214325214326214327214328214329214330214331214332214333214334214335214336214337214338214339214340214341214342214343214344214345214346214347214348214349214350214351214352214353214354214355214356214357214358214359214360214361214362214363214364214365214366214367214368214369214370214371214372214373214374214375214376214377214378214379214380214381214382214383214384214385214386214387214388214389214390214391214392214393214394214395214396214397214398214399214400214401214402214403214404214405214406214407214408214409214410214411214412214413214414214415214416214417214418214419214420214421214422214423214424214425214426214427214428214429214430214431214432214433214434214435214436214437214438214439214440214441214442214443214444214445214446214447214448214449214450214451214452214453214454214455214456214457214458214459214460214461214462214463214464214465214466214467214468214469214470214471214472214473214474214475214476214477214478214479214480214481214482214483214484214485214486214487214488214489214490214491214492214493214494214495214496214497214498214499214500214501214502214503214504214505214506214507214508214509214510214511214512214513214514214515214516214517214518214519214520214521214522214523214524214525214526214527214528214529214530214531214532214533214534214535214536214537214538214539214540214541214542214543214544214545214546214547214548214549214550214551214552214553214554214555214556214557214558214559214560214561214562214563214564214565214566214567214568214569214570214571214572214573214574214575214576214577214578214579214580214581214582214583214584214585214586214587214588214589214590214591214592214593214594214595214596214597214598214599214600214601214602214603214604214605214606214607214608214609214610214611214612214613214614214615214616214617214618214619214620214621214622214623214624214625214626214627214628214629214630214631214632214633214634214635214636214637214638214639214640214641214642214643214644214645214646214647214648214649214650214651214652214653214654214655214656214657214658214659214660214661214662214663214664214665214666214667214668214669214670214671214672214673214674214675214676214677214678214679214680214681214682214683214684214685214686214687214688214689214690214691214692214693214694214695214696214697214698214699214700214701214702214703214704214705214706214707214708214709214710214711214712214713214714214715214716214717214718214719214720214721214722214723214724214725214726214727214728214729214730214731214732214733214734214735214736214737214738214739214740214741214742214743214744214745214746214747214748214749214750214751214752214753214754214755214756214757214758214759214760214761214762214763214764214765214766214767214768214769214770214771214772214773214774214775214776214777214778214779214780214781214782214783214784214785214786214787214788214789214790214791214792214793214794214795214796214797214798214799214800214801214802214803214804214805214806214807214808214809214810214811214812214813214814214815214816214817214818214819214820214821214822214823214824214825214826214827214828214829214830214831214832214833214834214835214836214837214838214839214840214841214842214843214844214845214846214847214848214849214850214851214852214853214854214855214856214857214858214859214860214861214862214863214864214865214866214867214868214869214870214871214872214873214874214875214876214877214878214879214880214881214882214883214884214885214886214887214888214889214890214891214892214893214894214895214896214897214898214899214900214901214902214903214904214905214906214907214908214909214910214911214912214913214914214915214916214917214918214919214920214921214922214923214924214925214926214927214928214929214930214931214932214933214934214935214936214937214938214939214940214941214942214943214944214945214946214947214948214949214950214951214952214953214954214955214956214957214958214959214960214961214962214963214964214965214966214967214968214969214970214971214972214973214974214975214976214977214978214979214980214981214982214983214984214985214986214987214988214989214990214991214992214993214994214995214996214997214998214999215000215001215002215003215004215005215006215007215008215009215010215011215012215013215014215015215016215017215018215019215020215021215022215023215024215025215026215027215028215029215030215031215032215033215034215035215036215037215038215039215040215041215042215043215044215045215046215047215048215049215050215051215052215053215054215055215056215057215058215059215060215061215062215063215064215065215066215067215068215069215070215071215072215073215074215075215076215077215078215079215080215081215082215083215084215085215086215087215088215089215090215091215092215093215094215095215096215097215098215099215100215101215102215103215104215105215106215107215108215109215110215111215112215113215114215115215116215117215118215119215120215121215122215123215124215125215126215127215128215129215130215131215132215133215134215135215136215137215138215139215140215141215142215143215144215145215146215147215148215149215150215151215152215153215154215155215156215157215158215159215160215161215162215163215164215165215166215167215168215169215170215171215172215173215174215175215176215177215178215179215180215181215182215183215184215185215186215187215188215189215190215191215192215193215194215195215196215197215198215199215200215201215202215203215204215205215206215207215208215209215210215211215212215213215214215215215216215217215218215219215220215221215222215223215224215225215226215227215228215229215230215231215232215233215234215235215236215237215238215239215240215241215242215243215244215245215246215247215248215249215250215251215252215253215254215255215256215257215258215259215260215261215262215263215264215265215266215267215268215269215270215271215272215273215274215275215276215277215278215279215280215281215282215283215284215285215286215287215288215289215290215291215292215293215294215295215296215297215298215299215300215301215302215303215304215305215306215307215308215309215310215311215312215313215314215315215316215317215318215319215320215321215322215323215324215325215326215327215328215329215330215331215332215333215334215335215336215337215338215339215340215341215342215343215344215345215346215347215348215349215350215351215352215353215354215355215356215357215358215359215360215361215362215363215364215365215366215367215368215369215370215371215372215373215374215375215376215377215378215379215380215381215382215383215384215385215386215387215388215389215390215391215392215393215394215395215396215397215398215399215400215401215402215403215404215405215406215407215408215409215410215411215412215413215414215415215416215417215418215419215420215421215422215423215424215425215426215427215428215429215430215431215432215433215434215435215436215437215438215439215440215441215442215443215444215445215446215447215448215449215450215451215452215453215454215455215456215457215458215459215460215461215462215463215464215465215466215467215468215469215470215471215472215473215474215475215476215477215478215479215480215481215482215483215484215485215486215487215488215489215490215491215492215493215494215495215496215497215498215499215500215501215502215503215504215505215506215507215508215509215510215511215512215513215514215515215516215517215518215519215520215521215522215523215524215525215526215527215528215529215530215531215532215533215534215535215536215537215538215539215540215541215542215543215544215545215546215547215548215549215550215551215552215553215554215555215556215557215558215559215560215561215562215563215564215565215566215567215568215569215570215571215572215573215574215575215576215577215578215579215580215581215582215583215584215585215586215587215588215589215590215591215592215593215594215595215596215597215598215599215600215601215602215603215604215605215606215607215608215609215610215611215612215613215614215615215616215617215618215619215620215621215622215623215624215625215626215627215628215629215630215631215632215633215634215635215636215637215638215639215640215641215642215643215644215645215646215647215648215649215650215651215652215653215654215655215656215657215658215659215660215661215662215663215664215665215666215667215668215669215670215671215672215673215674215675215676215677215678215679215680215681215682215683215684215685215686215687215688215689215690215691215692215693215694215695215696215697215698215699215700215701215702215703215704215705215706215707215708215709215710215711215712215713215714215715215716215717215718215719215720215721215722215723215724215725215726215727215728215729215730215731215732215733215734215735215736215737215738215739215740215741215742215743215744215745215746215747215748215749215750215751215752215753215754215755215756215757215758215759215760215761215762215763215764215765215766215767215768215769215770215771215772215773215774215775215776215777215778215779215780215781215782215783215784215785215786215787215788215789215790215791215792215793215794215795215796215797215798215799215800215801215802215803215804215805215806215807215808215809215810215811215812215813215814215815215816215817215818215819215820215821215822215823215824215825215826215827215828215829215830215831215832215833215834215835215836215837215838215839215840215841215842215843215844215845215846215847215848215849215850215851215852215853215854215855215856215857215858215859215860215861215862215863215864215865215866215867215868215869215870215871215872215873215874215875215876215877215878215879215880215881215882215883215884215885215886215887215888215889215890215891215892215893215894215895215896215897215898215899215900215901215902215903215904215905215906215907215908215909215910215911215912215913215914215915215916215917215918215919215920215921215922215923215924215925215926215927215928215929215930215931215932215933215934215935215936215937215938215939215940215941215942215943215944215945215946215947215948215949215950215951215952215953215954215955215956215957215958215959215960215961215962215963215964215965215966215967215968215969215970215971215972215973215974215975215976215977215978215979215980215981215982215983215984215985215986215987215988215989215990215991215992215993215994215995215996215997215998215999216000216001216002216003216004216005216006216007216008216009216010216011216012216013216014216015216016216017216018216019216020216021216022216023216024216025216026216027216028216029216030216031216032216033216034216035216036216037216038216039216040216041216042216043216044216045216046216047216048216049216050216051216052216053216054216055216056216057216058216059216060216061216062216063216064216065216066216067216068216069216070216071216072216073216074216075216076216077216078216079216080216081216082216083216084216085216086216087216088216089216090216091216092216093216094216095216096216097216098216099216100216101216102216103216104216105216106216107216108216109216110216111216112216113216114216115216116216117216118216119216120216121216122216123216124216125216126216127216128216129216130216131216132216133216134216135216136216137216138216139216140216141216142216143216144216145216146216147216148216149216150216151216152216153216154216155216156216157216158216159216160216161216162216163216164216165216166216167216168216169216170216171216172216173216174216175216176216177216178216179216180216181216182216183216184216185216186216187216188216189216190216191216192216193216194216195216196216197216198216199216200216201216202216203216204216205216206216207216208216209216210216211216212216213216214216215216216216217216218216219216220216221216222216223216224216225216226216227216228216229216230216231216232216233216234216235216236216237216238216239216240216241216242216243216244216245216246216247216248216249216250216251216252216253216254216255216256216257216258216259216260216261216262216263216264216265216266216267216268216269216270216271216272216273216274216275216276216277216278216279216280216281216282216283216284216285216286216287216288216289216290216291216292216293216294216295216296216297216298216299216300216301216302216303216304216305216306216307216308216309216310216311216312216313216314216315216316216317216318216319216320216321216322216323216324216325216326216327216328216329216330216331216332216333216334216335216336216337216338216339216340216341216342216343216344216345216346216347216348216349216350216351216352216353216354216355216356216357216358216359216360216361216362216363216364216365216366216367216368216369216370216371216372216373216374216375216376216377216378216379216380216381216382216383216384216385216386216387216388216389216390216391216392216393216394216395216396216397216398216399216400216401216402216403216404216405216406216407216408216409216410216411216412216413216414216415216416216417216418216419216420216421216422216423216424216425216426216427216428216429216430216431216432216433216434216435216436216437216438216439216440216441216442216443216444216445216446216447216448216449216450216451216452216453216454216455216456216457216458216459216460216461216462216463216464216465216466216467216468216469216470216471216472216473216474216475216476216477216478216479216480216481216482216483216484216485216486216487216488216489216490216491216492216493216494216495216496216497216498216499216500216501216502216503216504216505216506216507216508216509216510216511216512216513216514216515216516216517216518216519216520216521216522216523216524216525216526216527216528216529216530216531216532216533216534216535216536216537216538216539216540216541216542216543216544216545216546216547216548216549216550216551216552216553216554216555216556216557216558216559216560216561216562216563216564216565216566216567216568216569216570216571216572216573216574216575216576216577216578216579216580216581216582216583216584216585216586216587216588216589216590216591216592216593216594216595216596216597216598216599216600216601216602216603216604216605216606216607216608216609216610216611216612216613216614216615216616216617216618216619216620216621216622216623216624216625216626216627216628216629216630216631216632216633216634216635216636216637216638216639216640216641216642216643216644216645216646216647216648216649216650216651216652216653216654216655216656216657216658216659216660216661216662216663216664216665216666216667216668216669216670216671216672216673216674216675216676216677216678216679216680216681216682216683216684216685216686216687216688216689216690216691216692216693216694216695216696216697216698216699216700216701216702216703216704216705216706216707216708216709216710216711216712216713216714216715216716216717216718216719216720216721216722216723216724216725216726216727216728216729216730216731216732216733216734216735216736216737216738216739216740216741216742216743216744216745216746216747216748216749216750216751216752216753216754216755216756216757216758216759216760216761216762216763216764216765216766216767216768216769216770216771216772216773216774216775216776216777216778216779216780216781216782216783216784216785216786216787216788216789216790216791216792216793216794216795216796216797216798216799216800216801216802216803216804216805216806216807216808216809216810216811216812216813216814216815216816216817216818216819216820216821216822216823216824216825216826216827216828216829216830216831216832216833216834216835216836216837216838216839216840216841216842216843216844216845216846216847216848216849216850216851216852216853216854216855216856216857216858216859216860216861216862216863216864216865216866216867216868216869216870216871216872216873216874216875216876216877216878216879216880216881216882216883216884216885216886216887216888216889216890216891216892216893216894216895216896216897216898216899216900216901216902216903216904216905216906216907216908216909216910216911216912216913216914216915216916216917216918216919216920216921216922216923216924216925216926216927216928216929216930216931216932216933216934216935216936216937216938216939216940216941216942216943216944216945216946216947216948216949216950216951216952216953216954216955216956216957216958216959216960216961216962216963216964216965216966216967216968216969216970216971216972216973216974216975216976216977216978216979216980216981216982216983216984216985216986216987216988216989216990216991216992216993216994216995216996216997216998216999217000217001217002217003217004217005217006217007217008217009217010217011217012217013217014217015217016217017217018217019217020217021217022217023217024217025217026217027217028217029217030217031217032217033217034217035217036217037217038217039217040217041217042217043217044217045217046217047217048217049217050217051217052217053217054217055217056217057217058217059217060217061217062217063217064217065217066217067217068217069217070217071217072217073217074217075217076217077217078217079217080217081217082217083217084217085217086217087217088217089217090217091217092217093217094217095217096217097217098217099217100217101217102217103217104217105217106217107217108217109217110217111217112217113217114217115217116217117217118217119217120217121217122217123217124217125217126217127217128217129217130217131217132217133217134217135217136217137217138217139217140217141217142217143217144217145217146217147217148217149217150217151217152217153217154217155217156217157217158217159217160217161217162217163217164217165217166217167217168217169217170217171217172217173217174217175217176217177217178217179217180217181217182217183217184217185217186217187217188217189217190217191217192217193217194217195217196217197217198217199217200217201217202217203217204217205217206217207217208217209217210217211217212217213217214217215217216217217217218217219217220217221217222217223217224217225217226217227217228217229217230217231217232217233217234217235217236217237217238217239217240217241217242217243217244217245217246217247217248217249217250217251217252217253217254217255217256217257217258217259217260217261217262217263217264217265217266217267217268217269217270217271217272217273217274217275217276217277217278217279217280217281217282217283217284217285217286217287217288217289217290217291217292217293217294217295217296217297217298217299217300217301217302217303217304217305217306217307217308217309217310217311217312217313217314217315217316217317217318217319217320217321217322217323217324217325217326217327217328217329217330217331217332217333217334217335217336217337217338217339217340217341217342217343217344217345217346217347217348217349217350217351217352217353217354217355217356217357217358217359217360217361217362217363217364217365217366217367217368217369217370217371217372217373217374217375217376217377217378217379217380217381217382217383217384217385217386217387217388217389217390217391217392217393217394217395217396217397217398217399217400217401217402217403217404217405217406217407217408217409217410217411217412217413217414217415217416217417217418217419217420217421217422217423217424217425217426217427217428217429217430217431217432217433217434217435217436217437217438217439217440217441217442217443217444217445217446217447217448217449217450217451217452217453217454217455217456217457217458217459217460217461217462217463217464217465217466217467217468217469217470217471217472217473217474217475217476217477217478217479217480217481217482217483217484217485217486217487217488217489217490217491217492217493217494217495217496217497217498217499217500217501217502217503217504217505217506217507217508217509217510217511217512217513217514217515217516217517217518217519217520217521217522217523217524217525217526217527217528217529217530217531217532217533217534217535217536217537217538217539217540217541217542217543217544217545217546217547217548217549217550217551217552217553217554217555217556217557217558217559217560217561217562217563217564217565217566217567217568217569217570217571217572217573217574217575217576217577217578217579217580217581217582217583217584217585217586217587217588217589217590217591217592217593217594217595217596217597217598217599217600217601217602217603217604217605217606217607217608217609217610217611217612217613217614217615217616217617217618217619217620217621217622217623217624217625217626217627217628217629217630217631217632217633217634217635217636217637217638217639217640217641217642217643217644217645217646217647217648217649217650217651217652217653217654217655217656217657217658217659217660217661217662217663217664217665217666217667217668217669217670217671217672217673217674217675217676217677217678217679217680217681217682217683217684217685217686217687217688217689217690217691217692217693217694217695217696217697217698217699217700217701217702217703217704217705217706217707217708217709217710217711217712217713217714217715217716217717217718217719217720217721217722217723217724217725217726217727217728217729217730217731217732217733217734217735217736217737217738217739217740217741217742217743217744217745217746217747217748217749217750217751217752217753217754217755217756217757217758217759217760217761217762217763217764217765217766217767217768217769217770217771217772217773217774217775217776217777217778217779217780217781217782217783217784217785217786217787217788217789217790217791217792217793217794217795217796217797217798217799217800217801217802217803217804217805217806217807217808217809217810217811217812217813217814217815217816217817217818217819217820217821217822217823217824217825217826217827217828217829217830217831217832217833217834217835217836217837217838217839217840217841217842217843217844217845217846217847217848217849217850217851217852217853217854217855217856217857217858217859217860217861217862217863217864217865217866217867217868217869217870217871217872217873217874217875217876217877217878217879217880217881217882217883217884217885217886217887217888217889217890217891217892217893217894217895217896217897217898217899217900217901217902217903217904217905217906217907217908217909217910217911217912217913217914217915217916217917217918217919217920217921217922217923217924217925217926217927217928217929217930217931217932217933217934217935217936217937217938217939217940217941217942217943217944217945217946217947217948217949217950217951217952217953217954217955217956217957217958217959217960217961217962217963217964217965217966217967217968217969217970217971217972217973217974217975217976217977217978217979217980217981217982217983217984217985217986217987217988217989217990217991217992217993217994217995217996217997217998217999218000218001218002218003218004218005218006218007218008218009218010218011218012218013218014218015218016218017218018218019218020218021218022218023218024218025218026218027218028218029218030218031218032218033218034218035218036218037218038218039218040218041218042218043218044218045218046218047218048218049218050218051218052218053218054218055218056218057218058218059218060218061218062218063218064218065218066218067218068218069218070218071218072218073218074218075218076218077218078218079218080218081218082218083218084218085218086218087218088218089218090218091218092218093218094218095218096218097218098218099218100218101218102218103218104218105218106218107218108218109218110218111218112218113218114218115218116218117218118218119218120218121218122218123218124218125218126218127218128218129218130218131218132218133218134218135218136218137218138218139218140218141218142218143218144218145218146218147218148218149218150218151218152218153218154218155218156218157218158218159218160218161218162218163218164218165218166218167218168218169218170218171218172218173218174218175218176218177218178218179218180218181218182218183218184218185218186218187218188218189218190218191218192218193218194218195218196218197218198218199218200218201218202218203218204218205218206218207218208218209218210218211218212218213218214218215218216218217218218218219218220218221218222218223218224218225218226218227218228218229218230218231218232218233218234218235218236218237218238218239218240218241218242218243218244218245218246218247218248218249218250218251218252218253218254218255218256218257218258218259218260218261218262218263218264218265218266218267218268218269218270218271218272218273218274218275218276218277218278218279218280218281218282218283218284218285218286218287218288218289218290218291218292218293218294218295218296218297218298218299218300218301218302218303218304218305218306218307218308218309218310218311218312218313218314218315218316218317218318218319218320218321218322218323218324218325218326218327218328218329218330218331218332218333218334218335218336218337218338218339218340218341218342218343218344218345218346218347218348218349218350218351218352218353218354218355218356218357218358218359218360218361218362218363218364218365218366218367218368218369218370218371218372218373218374218375218376218377218378218379218380218381218382218383218384218385218386218387218388218389218390218391218392218393218394218395218396218397218398218399218400218401218402218403218404218405218406218407218408218409218410218411218412218413218414218415218416218417218418218419218420218421218422218423218424218425218426218427218428218429218430218431218432218433218434218435218436218437218438218439218440218441218442218443218444218445218446218447218448218449218450218451218452218453218454218455218456218457218458218459218460218461218462218463218464218465218466218467218468218469218470218471218472218473218474218475218476218477218478218479218480218481218482218483218484218485218486218487218488218489218490218491218492218493218494218495218496218497218498218499218500218501218502218503218504218505218506218507218508218509218510218511218512218513218514218515218516218517218518218519218520218521218522218523218524218525218526218527218528218529218530218531218532218533218534218535218536218537218538218539218540218541218542218543218544218545218546218547218548218549218550218551218552218553218554218555218556218557218558218559218560218561218562218563218564218565218566218567218568218569218570218571218572218573218574218575218576218577218578218579218580218581218582218583218584218585218586218587218588218589218590218591218592218593218594218595218596218597218598218599218600218601218602218603218604218605218606218607218608218609218610218611218612218613218614218615218616218617218618218619218620218621218622218623218624218625218626218627218628218629218630218631218632218633218634218635218636218637218638218639218640218641218642218643218644218645218646218647218648218649218650218651218652218653218654218655218656218657218658218659218660218661218662218663218664218665218666218667218668218669218670218671218672218673218674218675218676218677218678218679218680218681218682218683218684218685218686218687218688218689218690218691218692218693218694218695218696218697218698218699218700218701218702218703218704218705218706218707218708218709218710218711218712218713218714218715218716218717218718218719218720218721218722218723218724218725218726218727218728218729218730218731218732218733218734218735218736218737218738218739218740218741218742218743218744218745218746218747218748218749218750218751218752218753218754218755218756218757218758218759218760218761218762218763218764218765218766218767218768218769218770218771218772218773218774218775218776218777218778218779218780218781218782218783218784218785218786218787218788218789218790218791218792218793218794218795218796218797218798218799218800218801218802218803218804218805218806218807218808218809218810218811218812218813218814218815218816218817218818218819218820218821218822218823218824218825218826218827218828218829218830218831218832218833218834218835218836218837218838218839218840218841218842218843218844218845218846218847218848218849218850218851218852218853218854218855218856218857218858218859218860218861218862218863218864218865218866218867218868218869218870218871218872218873218874218875218876218877218878218879218880218881218882218883218884218885218886218887218888218889218890218891218892218893218894218895218896218897218898218899218900218901218902218903218904218905218906218907218908218909218910218911218912218913218914218915218916218917218918218919218920218921218922218923218924218925218926218927218928218929218930218931218932218933218934218935218936218937218938218939218940218941218942218943218944218945218946218947218948218949218950218951218952218953218954218955218956218957218958218959218960218961218962218963218964218965218966218967218968218969218970218971218972218973218974218975218976218977218978218979218980218981218982218983218984218985218986218987218988218989218990218991218992218993218994218995218996218997218998218999219000219001219002219003219004219005219006219007219008219009219010219011219012219013219014219015219016219017219018219019219020219021219022219023219024219025219026219027219028219029219030219031219032219033219034219035219036219037219038219039219040219041219042219043219044219045219046219047219048219049219050219051219052219053219054219055219056219057219058219059219060219061219062219063219064219065219066219067219068219069219070219071219072219073219074219075219076219077219078219079219080219081219082219083219084219085219086219087219088219089219090219091219092219093219094219095219096219097219098219099219100219101219102219103219104219105219106219107219108219109219110219111219112219113219114219115219116219117219118219119219120219121219122219123219124219125219126219127219128219129219130219131219132219133219134219135219136219137219138219139219140219141219142219143219144219145219146219147219148219149219150219151219152219153219154219155219156219157219158219159219160219161219162219163219164219165219166219167219168219169219170219171219172219173219174219175219176219177219178219179219180219181219182219183219184219185219186219187219188219189219190219191219192219193219194219195219196219197219198219199219200219201219202219203219204219205219206219207219208219209219210219211219212219213219214219215219216219217219218219219219220219221219222219223219224219225219226219227219228219229219230219231219232219233219234219235219236219237219238219239219240219241219242219243219244219245219246219247219248219249219250219251219252219253219254219255219256219257219258219259219260219261219262219263219264219265219266219267219268219269219270219271219272219273219274219275219276219277219278219279219280219281219282219283219284219285219286219287219288219289219290219291219292219293219294219295219296219297219298219299219300219301219302219303219304219305219306219307219308219309219310219311219312219313219314219315219316219317219318219319219320219321219322219323219324219325219326219327219328219329219330219331219332219333219334219335219336219337219338219339219340219341219342219343219344219345219346219347219348219349219350219351219352219353219354219355219356219357219358219359219360219361219362219363219364219365219366219367219368219369219370219371219372219373219374219375219376219377219378219379219380219381219382219383219384219385219386219387219388219389219390219391219392219393219394219395219396219397219398219399219400219401219402219403219404219405219406219407219408219409219410219411219412219413219414219415219416219417219418219419219420219421219422219423219424219425219426219427219428219429219430219431219432219433219434219435219436219437219438219439219440219441219442219443219444219445219446219447219448219449219450219451219452219453219454219455219456219457219458219459219460219461219462219463219464219465219466219467219468219469219470219471219472219473219474219475219476219477219478219479219480219481219482219483219484219485219486219487219488219489219490219491219492219493219494219495219496219497219498219499219500219501219502219503219504219505219506219507219508219509219510219511219512219513219514219515219516219517219518219519219520219521219522219523219524219525219526219527219528219529219530219531219532219533219534219535219536219537219538219539219540219541219542219543219544219545219546219547219548219549219550219551219552219553219554219555219556219557219558219559219560219561219562219563219564219565219566219567219568219569219570219571219572219573219574219575219576219577219578219579219580219581219582219583219584219585219586219587219588219589219590219591219592219593219594219595219596219597219598219599219600219601219602219603219604219605219606219607219608219609219610219611219612219613219614219615219616219617219618219619219620219621219622219623219624219625219626219627219628219629219630219631219632219633219634219635219636219637219638219639219640219641219642219643219644219645219646219647219648219649219650219651219652219653219654219655219656219657219658219659219660219661219662219663219664219665219666219667219668219669219670219671219672219673219674219675219676219677219678219679219680219681219682219683219684219685219686219687219688219689219690219691219692219693219694219695219696219697219698219699219700219701219702219703219704219705219706219707219708219709219710219711219712219713219714219715219716219717219718219719219720219721219722219723219724219725219726219727219728219729219730219731219732219733219734219735219736219737219738219739219740219741219742219743219744219745219746219747219748219749219750219751219752219753219754219755219756219757219758219759219760219761219762219763219764219765219766219767219768219769219770219771219772219773219774219775219776219777219778219779219780219781219782219783219784219785219786219787219788219789219790219791219792219793219794219795219796219797219798219799219800219801219802219803219804219805219806219807219808219809219810219811219812219813219814219815219816219817219818219819219820219821219822219823219824219825219826219827219828219829219830219831219832219833219834219835219836219837219838219839219840219841219842219843219844219845219846219847219848219849219850219851219852219853219854219855219856219857219858219859219860219861219862219863219864219865219866219867219868219869219870219871219872219873219874219875219876219877219878219879219880219881219882219883219884219885219886219887219888219889219890219891219892219893219894219895219896219897219898219899219900219901219902219903219904219905219906219907219908219909219910219911219912219913219914219915219916219917219918219919219920219921219922219923219924219925219926219927219928219929219930219931219932219933219934219935219936219937219938219939219940219941219942219943219944219945219946219947219948219949219950219951219952219953219954219955219956219957219958219959219960219961219962219963219964219965219966219967219968219969219970219971219972219973219974219975219976219977219978219979219980219981219982219983219984219985219986219987219988219989219990219991219992219993219994219995219996219997219998219999220000220001220002220003220004220005220006220007220008220009220010220011220012220013220014220015220016220017220018220019220020220021220022220023220024220025220026220027220028220029220030220031220032220033220034220035220036220037220038220039220040220041220042220043220044220045220046220047220048220049220050220051220052220053220054220055220056220057220058220059220060220061220062220063220064220065220066220067220068220069220070220071220072220073220074220075220076220077220078220079220080220081220082220083220084220085220086220087220088220089220090220091220092220093220094220095220096220097220098220099220100220101220102220103220104220105220106220107220108220109220110220111220112220113220114220115220116220117220118220119220120220121220122220123220124220125220126220127220128220129220130220131220132220133220134220135220136220137220138220139220140220141220142220143220144220145220146220147220148220149220150220151220152220153220154220155220156220157220158220159220160220161220162220163220164220165220166220167220168220169220170220171220172220173220174220175220176220177220178220179220180220181220182220183220184220185220186220187220188220189220190220191220192220193220194220195220196220197220198220199220200220201220202220203220204220205220206220207220208220209220210220211220212220213220214220215220216220217220218220219220220220221220222220223220224220225220226220227220228220229220230220231220232220233220234220235220236220237220238220239220240220241220242220243220244220245220246220247220248220249220250220251220252220253220254220255220256220257220258220259220260220261220262220263220264220265220266220267220268220269220270220271220272220273220274220275220276220277220278220279220280220281220282220283220284220285220286220287220288220289220290220291220292220293220294220295220296220297220298220299220300220301220302220303220304220305220306220307220308220309220310220311220312220313220314220315220316220317220318220319220320220321220322220323220324220325220326220327220328220329220330220331220332220333220334220335220336220337220338220339220340220341220342220343220344220345220346220347220348220349220350220351220352220353220354220355220356220357220358220359220360220361220362220363220364220365220366220367220368220369220370220371220372220373220374220375220376220377220378220379220380220381220382220383220384220385220386220387220388220389220390220391220392220393220394220395220396220397220398220399220400220401220402220403220404220405220406220407220408220409220410220411220412220413220414220415220416220417220418220419220420220421220422220423220424220425220426220427220428220429220430220431220432220433220434220435220436220437220438220439220440220441220442220443220444220445220446220447220448220449220450220451220452220453220454220455220456220457220458220459220460220461220462220463220464220465220466220467220468220469220470220471220472220473220474220475220476220477220478220479220480220481220482220483220484220485220486220487220488220489220490220491220492220493220494220495220496220497220498220499220500220501220502220503220504220505220506220507220508220509220510220511220512220513220514220515220516220517220518220519220520220521220522220523220524220525220526220527220528220529220530220531220532220533220534
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.26.0. 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. /* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This
  55. ** option requires a separate macro because legal values contain a single
  56. ** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
  57. #define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt2
  58. #define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)
  59. /*
  60. ** An array of names of all compile-time options. This array should
  61. ** be sorted A-Z.
  62. **
  63. ** This array looks large, but in a typical installation actually uses
  64. ** only a handful of compile-time options, so most times this array is usually
  65. ** rather short and uses little memory space.
  66. */
  67. static const char * const sqlite3azCompileOpt[] = {
  68. /*
  69. ** BEGIN CODE GENERATED BY tool/mkctime.tcl
  70. */
  71. #if SQLITE_32BIT_ROWID
  72. "32BIT_ROWID",
  73. #endif
  74. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  75. "4_BYTE_ALIGNED_MALLOC",
  76. #endif
  77. #if SQLITE_64BIT_STATS
  78. "64BIT_STATS",
  79. #endif
  80. #if SQLITE_ALLOW_COVERING_INDEX_SCAN
  81. "ALLOW_COVERING_INDEX_SCAN",
  82. #endif
  83. #if SQLITE_ALLOW_URI_AUTHORITY
  84. "ALLOW_URI_AUTHORITY",
  85. #endif
  86. #ifdef SQLITE_BITMASK_TYPE
  87. "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
  88. #endif
  89. #if SQLITE_BUG_COMPATIBLE_20160819
  90. "BUG_COMPATIBLE_20160819",
  91. #endif
  92. #if SQLITE_CASE_SENSITIVE_LIKE
  93. "CASE_SENSITIVE_LIKE",
  94. #endif
  95. #if SQLITE_CHECK_PAGES
  96. "CHECK_PAGES",
  97. #endif
  98. #if defined(__clang__) && defined(__clang_major__)
  99. "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
  100. CTIMEOPT_VAL(__clang_minor__) "."
  101. CTIMEOPT_VAL(__clang_patchlevel__),
  102. #elif defined(_MSC_VER)
  103. "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
  104. #elif defined(__GNUC__) && defined(__VERSION__)
  105. "COMPILER=gcc-" __VERSION__,
  106. #endif
  107. #if SQLITE_COVERAGE_TEST
  108. "COVERAGE_TEST",
  109. #endif
  110. #if SQLITE_DEBUG
  111. "DEBUG",
  112. #endif
  113. #if SQLITE_DEFAULT_AUTOMATIC_INDEX
  114. "DEFAULT_AUTOMATIC_INDEX",
  115. #endif
  116. #if SQLITE_DEFAULT_AUTOVACUUM
  117. "DEFAULT_AUTOVACUUM",
  118. #endif
  119. #ifdef SQLITE_DEFAULT_CACHE_SIZE
  120. "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
  121. #endif
  122. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  123. "DEFAULT_CKPTFULLFSYNC",
  124. #endif
  125. #ifdef SQLITE_DEFAULT_FILE_FORMAT
  126. "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
  127. #endif
  128. #ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
  129. "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
  130. #endif
  131. #if SQLITE_DEFAULT_FOREIGN_KEYS
  132. "DEFAULT_FOREIGN_KEYS",
  133. #endif
  134. #ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  135. "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
  136. #endif
  137. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  138. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  139. #endif
  140. #ifdef SQLITE_DEFAULT_LOOKASIDE
  141. "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),
  142. #endif
  143. #if SQLITE_DEFAULT_MEMSTATUS
  144. "DEFAULT_MEMSTATUS",
  145. #endif
  146. #ifdef SQLITE_DEFAULT_MMAP_SIZE
  147. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  148. #endif
  149. #ifdef SQLITE_DEFAULT_PAGE_SIZE
  150. "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
  151. #endif
  152. #ifdef SQLITE_DEFAULT_PCACHE_INITSZ
  153. "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
  154. #endif
  155. #ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  156. "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
  157. #endif
  158. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  159. "DEFAULT_RECURSIVE_TRIGGERS",
  160. #endif
  161. #ifdef SQLITE_DEFAULT_ROWEST
  162. "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
  163. #endif
  164. #ifdef SQLITE_DEFAULT_SECTOR_SIZE
  165. "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
  166. #endif
  167. #ifdef SQLITE_DEFAULT_SYNCHRONOUS
  168. "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
  169. #endif
  170. #ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  171. "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
  172. #endif
  173. #ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  174. "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
  175. #endif
  176. #ifdef SQLITE_DEFAULT_WORKER_THREADS
  177. "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
  178. #endif
  179. #if SQLITE_DIRECT_OVERFLOW_READ
  180. "DIRECT_OVERFLOW_READ",
  181. #endif
  182. #if SQLITE_DISABLE_DIRSYNC
  183. "DISABLE_DIRSYNC",
  184. #endif
  185. #if SQLITE_DISABLE_FTS3_UNICODE
  186. "DISABLE_FTS3_UNICODE",
  187. #endif
  188. #if SQLITE_DISABLE_FTS4_DEFERRED
  189. "DISABLE_FTS4_DEFERRED",
  190. #endif
  191. #if SQLITE_DISABLE_INTRINSIC
  192. "DISABLE_INTRINSIC",
  193. #endif
  194. #if SQLITE_DISABLE_LFS
  195. "DISABLE_LFS",
  196. #endif
  197. #if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  198. "DISABLE_PAGECACHE_OVERFLOW_STATS",
  199. #endif
  200. #if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  201. "DISABLE_SKIPAHEAD_DISTINCT",
  202. #endif
  203. #ifdef SQLITE_ENABLE_8_3_NAMES
  204. "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
  205. #endif
  206. #if SQLITE_ENABLE_API_ARMOR
  207. "ENABLE_API_ARMOR",
  208. #endif
  209. #if SQLITE_ENABLE_ATOMIC_WRITE
  210. "ENABLE_ATOMIC_WRITE",
  211. #endif
  212. #if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  213. "ENABLE_BATCH_ATOMIC_WRITE",
  214. #endif
  215. #if SQLITE_ENABLE_CEROD
  216. "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
  217. #endif
  218. #if SQLITE_ENABLE_COLUMN_METADATA
  219. "ENABLE_COLUMN_METADATA",
  220. #endif
  221. #if SQLITE_ENABLE_COLUMN_USED_MASK
  222. "ENABLE_COLUMN_USED_MASK",
  223. #endif
  224. #if SQLITE_ENABLE_COSTMULT
  225. "ENABLE_COSTMULT",
  226. #endif
  227. #if SQLITE_ENABLE_CURSOR_HINTS
  228. "ENABLE_CURSOR_HINTS",
  229. #endif
  230. #if SQLITE_ENABLE_DBSTAT_VTAB
  231. "ENABLE_DBSTAT_VTAB",
  232. #endif
  233. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  234. "ENABLE_EXPENSIVE_ASSERT",
  235. #endif
  236. #if SQLITE_ENABLE_FTS1
  237. "ENABLE_FTS1",
  238. #endif
  239. #if SQLITE_ENABLE_FTS2
  240. "ENABLE_FTS2",
  241. #endif
  242. #if SQLITE_ENABLE_FTS3
  243. "ENABLE_FTS3",
  244. #endif
  245. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  246. "ENABLE_FTS3_PARENTHESIS",
  247. #endif
  248. #if SQLITE_ENABLE_FTS3_TOKENIZER
  249. "ENABLE_FTS3_TOKENIZER",
  250. #endif
  251. #if SQLITE_ENABLE_FTS4
  252. "ENABLE_FTS4",
  253. #endif
  254. #if SQLITE_ENABLE_FTS5
  255. "ENABLE_FTS5",
  256. #endif
  257. #if SQLITE_ENABLE_GEOPOLY
  258. "ENABLE_GEOPOLY",
  259. #endif
  260. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  261. "ENABLE_HIDDEN_COLUMNS",
  262. #endif
  263. #if SQLITE_ENABLE_ICU
  264. "ENABLE_ICU",
  265. #endif
  266. #if SQLITE_ENABLE_IOTRACE
  267. "ENABLE_IOTRACE",
  268. #endif
  269. #if SQLITE_ENABLE_JSON1
  270. "ENABLE_JSON1",
  271. #endif
  272. #if SQLITE_ENABLE_LOAD_EXTENSION
  273. "ENABLE_LOAD_EXTENSION",
  274. #endif
  275. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  276. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  277. #endif
  278. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  279. "ENABLE_MEMORY_MANAGEMENT",
  280. #endif
  281. #if SQLITE_ENABLE_MEMSYS3
  282. "ENABLE_MEMSYS3",
  283. #endif
  284. #if SQLITE_ENABLE_MEMSYS5
  285. "ENABLE_MEMSYS5",
  286. #endif
  287. #if SQLITE_ENABLE_MULTIPLEX
  288. "ENABLE_MULTIPLEX",
  289. #endif
  290. #if SQLITE_ENABLE_NORMALIZE
  291. "ENABLE_NORMALIZE",
  292. #endif
  293. #if SQLITE_ENABLE_NULL_TRIM
  294. "ENABLE_NULL_TRIM",
  295. #endif
  296. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  297. "ENABLE_OVERSIZE_CELL_CHECK",
  298. #endif
  299. #if SQLITE_ENABLE_PREUPDATE_HOOK
  300. "ENABLE_PREUPDATE_HOOK",
  301. #endif
  302. #if SQLITE_ENABLE_QPSG
  303. "ENABLE_QPSG",
  304. #endif
  305. #if SQLITE_ENABLE_RBU
  306. "ENABLE_RBU",
  307. #endif
  308. #if SQLITE_ENABLE_RTREE
  309. "ENABLE_RTREE",
  310. #endif
  311. #if SQLITE_ENABLE_SELECTTRACE
  312. "ENABLE_SELECTTRACE",
  313. #endif
  314. #if SQLITE_ENABLE_SESSION
  315. "ENABLE_SESSION",
  316. #endif
  317. #if SQLITE_ENABLE_SNAPSHOT
  318. "ENABLE_SNAPSHOT",
  319. #endif
  320. #if SQLITE_ENABLE_SORTER_REFERENCES
  321. "ENABLE_SORTER_REFERENCES",
  322. #endif
  323. #if SQLITE_ENABLE_SQLLOG
  324. "ENABLE_SQLLOG",
  325. #endif
  326. #if defined(SQLITE_ENABLE_STAT4)
  327. "ENABLE_STAT4",
  328. #elif defined(SQLITE_ENABLE_STAT3)
  329. "ENABLE_STAT3",
  330. #endif
  331. #if SQLITE_ENABLE_STMTVTAB
  332. "ENABLE_STMTVTAB",
  333. #endif
  334. #if SQLITE_ENABLE_STMT_SCANSTATUS
  335. "ENABLE_STMT_SCANSTATUS",
  336. #endif
  337. #if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  338. "ENABLE_UNKNOWN_SQL_FUNCTION",
  339. #endif
  340. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  341. "ENABLE_UNLOCK_NOTIFY",
  342. #endif
  343. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  344. "ENABLE_UPDATE_DELETE_LIMIT",
  345. #endif
  346. #if SQLITE_ENABLE_URI_00_ERROR
  347. "ENABLE_URI_00_ERROR",
  348. #endif
  349. #if SQLITE_ENABLE_VFSTRACE
  350. "ENABLE_VFSTRACE",
  351. #endif
  352. #if SQLITE_ENABLE_WHERETRACE
  353. "ENABLE_WHERETRACE",
  354. #endif
  355. #if SQLITE_ENABLE_ZIPVFS
  356. "ENABLE_ZIPVFS",
  357. #endif
  358. #if SQLITE_EXPLAIN_ESTIMATED_ROWS
  359. "EXPLAIN_ESTIMATED_ROWS",
  360. #endif
  361. #if SQLITE_EXTRA_IFNULLROW
  362. "EXTRA_IFNULLROW",
  363. #endif
  364. #ifdef SQLITE_EXTRA_INIT
  365. "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
  366. #endif
  367. #ifdef SQLITE_EXTRA_SHUTDOWN
  368. "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
  369. #endif
  370. #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
  371. "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
  372. #endif
  373. #if SQLITE_FTS5_ENABLE_TEST_MI
  374. "FTS5_ENABLE_TEST_MI",
  375. #endif
  376. #if SQLITE_FTS5_NO_WITHOUT_ROWID
  377. "FTS5_NO_WITHOUT_ROWID",
  378. #endif
  379. #if SQLITE_HAS_CODEC
  380. "HAS_CODEC",
  381. #endif
  382. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  383. "HAVE_ISNAN",
  384. #endif
  385. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  386. "HOMEGROWN_RECURSIVE_MUTEX",
  387. #endif
  388. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  389. "IGNORE_AFP_LOCK_ERRORS",
  390. #endif
  391. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  392. "IGNORE_FLOCK_LOCK_ERRORS",
  393. #endif
  394. #if SQLITE_INLINE_MEMCPY
  395. "INLINE_MEMCPY",
  396. #endif
  397. #if SQLITE_INT64_TYPE
  398. "INT64_TYPE",
  399. #endif
  400. #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  401. "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
  402. #endif
  403. #if SQLITE_LIKE_DOESNT_MATCH_BLOBS
  404. "LIKE_DOESNT_MATCH_BLOBS",
  405. #endif
  406. #if SQLITE_LOCK_TRACE
  407. "LOCK_TRACE",
  408. #endif
  409. #if SQLITE_LOG_CACHE_SPILL
  410. "LOG_CACHE_SPILL",
  411. #endif
  412. #ifdef SQLITE_MALLOC_SOFT_LIMIT
  413. "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
  414. #endif
  415. #ifdef SQLITE_MAX_ATTACHED
  416. "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
  417. #endif
  418. #ifdef SQLITE_MAX_COLUMN
  419. "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
  420. #endif
  421. #ifdef SQLITE_MAX_COMPOUND_SELECT
  422. "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
  423. #endif
  424. #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
  425. "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
  426. #endif
  427. #ifdef SQLITE_MAX_EXPR_DEPTH
  428. "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
  429. #endif
  430. #ifdef SQLITE_MAX_FUNCTION_ARG
  431. "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
  432. #endif
  433. #ifdef SQLITE_MAX_LENGTH
  434. "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
  435. #endif
  436. #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
  437. "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
  438. #endif
  439. #ifdef SQLITE_MAX_MEMORY
  440. "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
  441. #endif
  442. #ifdef SQLITE_MAX_MMAP_SIZE
  443. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  444. #endif
  445. #ifdef SQLITE_MAX_MMAP_SIZE_
  446. "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
  447. #endif
  448. #ifdef SQLITE_MAX_PAGE_COUNT
  449. "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
  450. #endif
  451. #ifdef SQLITE_MAX_PAGE_SIZE
  452. "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
  453. #endif
  454. #ifdef SQLITE_MAX_SCHEMA_RETRY
  455. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  456. #endif
  457. #ifdef SQLITE_MAX_SQL_LENGTH
  458. "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
  459. #endif
  460. #ifdef SQLITE_MAX_TRIGGER_DEPTH
  461. "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
  462. #endif
  463. #ifdef SQLITE_MAX_VARIABLE_NUMBER
  464. "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
  465. #endif
  466. #ifdef SQLITE_MAX_VDBE_OP
  467. "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
  468. #endif
  469. #ifdef SQLITE_MAX_WORKER_THREADS
  470. "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
  471. #endif
  472. #if SQLITE_MEMDEBUG
  473. "MEMDEBUG",
  474. #endif
  475. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  476. "MIXED_ENDIAN_64BIT_FLOAT",
  477. #endif
  478. #if SQLITE_MMAP_READWRITE
  479. "MMAP_READWRITE",
  480. #endif
  481. #if SQLITE_MUTEX_NOOP
  482. "MUTEX_NOOP",
  483. #endif
  484. #if SQLITE_MUTEX_NREF
  485. "MUTEX_NREF",
  486. #endif
  487. #if SQLITE_MUTEX_OMIT
  488. "MUTEX_OMIT",
  489. #endif
  490. #if SQLITE_MUTEX_PTHREADS
  491. "MUTEX_PTHREADS",
  492. #endif
  493. #if SQLITE_MUTEX_W32
  494. "MUTEX_W32",
  495. #endif
  496. #if SQLITE_NEED_ERR_NAME
  497. "NEED_ERR_NAME",
  498. #endif
  499. #if SQLITE_NOINLINE
  500. "NOINLINE",
  501. #endif
  502. #if SQLITE_NO_SYNC
  503. "NO_SYNC",
  504. #endif
  505. #if SQLITE_OMIT_ALTERTABLE
  506. "OMIT_ALTERTABLE",
  507. #endif
  508. #if SQLITE_OMIT_ANALYZE
  509. "OMIT_ANALYZE",
  510. #endif
  511. #if SQLITE_OMIT_ATTACH
  512. "OMIT_ATTACH",
  513. #endif
  514. #if SQLITE_OMIT_AUTHORIZATION
  515. "OMIT_AUTHORIZATION",
  516. #endif
  517. #if SQLITE_OMIT_AUTOINCREMENT
  518. "OMIT_AUTOINCREMENT",
  519. #endif
  520. #if SQLITE_OMIT_AUTOINIT
  521. "OMIT_AUTOINIT",
  522. #endif
  523. #if SQLITE_OMIT_AUTOMATIC_INDEX
  524. "OMIT_AUTOMATIC_INDEX",
  525. #endif
  526. #if SQLITE_OMIT_AUTORESET
  527. "OMIT_AUTORESET",
  528. #endif
  529. #if SQLITE_OMIT_AUTOVACUUM
  530. "OMIT_AUTOVACUUM",
  531. #endif
  532. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  533. "OMIT_BETWEEN_OPTIMIZATION",
  534. #endif
  535. #if SQLITE_OMIT_BLOB_LITERAL
  536. "OMIT_BLOB_LITERAL",
  537. #endif
  538. #if SQLITE_OMIT_BTREECOUNT
  539. "OMIT_BTREECOUNT",
  540. #endif
  541. #if SQLITE_OMIT_CAST
  542. "OMIT_CAST",
  543. #endif
  544. #if SQLITE_OMIT_CHECK
  545. "OMIT_CHECK",
  546. #endif
  547. #if SQLITE_OMIT_COMPLETE
  548. "OMIT_COMPLETE",
  549. #endif
  550. #if SQLITE_OMIT_COMPOUND_SELECT
  551. "OMIT_COMPOUND_SELECT",
  552. #endif
  553. #if SQLITE_OMIT_CONFLICT_CLAUSE
  554. "OMIT_CONFLICT_CLAUSE",
  555. #endif
  556. #if SQLITE_OMIT_CTE
  557. "OMIT_CTE",
  558. #endif
  559. #if SQLITE_OMIT_DATETIME_FUNCS
  560. "OMIT_DATETIME_FUNCS",
  561. #endif
  562. #if SQLITE_OMIT_DECLTYPE
  563. "OMIT_DECLTYPE",
  564. #endif
  565. #if SQLITE_OMIT_DEPRECATED
  566. "OMIT_DEPRECATED",
  567. #endif
  568. #if SQLITE_OMIT_DISKIO
  569. "OMIT_DISKIO",
  570. #endif
  571. #if SQLITE_OMIT_EXPLAIN
  572. "OMIT_EXPLAIN",
  573. #endif
  574. #if SQLITE_OMIT_FLAG_PRAGMAS
  575. "OMIT_FLAG_PRAGMAS",
  576. #endif
  577. #if SQLITE_OMIT_FLOATING_POINT
  578. "OMIT_FLOATING_POINT",
  579. #endif
  580. #if SQLITE_OMIT_FOREIGN_KEY
  581. "OMIT_FOREIGN_KEY",
  582. #endif
  583. #if SQLITE_OMIT_GET_TABLE
  584. "OMIT_GET_TABLE",
  585. #endif
  586. #if SQLITE_OMIT_HEX_INTEGER
  587. "OMIT_HEX_INTEGER",
  588. #endif
  589. #if SQLITE_OMIT_INCRBLOB
  590. "OMIT_INCRBLOB",
  591. #endif
  592. #if SQLITE_OMIT_INTEGRITY_CHECK
  593. "OMIT_INTEGRITY_CHECK",
  594. #endif
  595. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  596. "OMIT_LIKE_OPTIMIZATION",
  597. #endif
  598. #if SQLITE_OMIT_LOAD_EXTENSION
  599. "OMIT_LOAD_EXTENSION",
  600. #endif
  601. #if SQLITE_OMIT_LOCALTIME
  602. "OMIT_LOCALTIME",
  603. #endif
  604. #if SQLITE_OMIT_LOOKASIDE
  605. "OMIT_LOOKASIDE",
  606. #endif
  607. #if SQLITE_OMIT_MEMORYDB
  608. "OMIT_MEMORYDB",
  609. #endif
  610. #if SQLITE_OMIT_OR_OPTIMIZATION
  611. "OMIT_OR_OPTIMIZATION",
  612. #endif
  613. #if SQLITE_OMIT_PAGER_PRAGMAS
  614. "OMIT_PAGER_PRAGMAS",
  615. #endif
  616. #if SQLITE_OMIT_PARSER_TRACE
  617. "OMIT_PARSER_TRACE",
  618. #endif
  619. #if SQLITE_OMIT_POPEN
  620. "OMIT_POPEN",
  621. #endif
  622. #if SQLITE_OMIT_PRAGMA
  623. "OMIT_PRAGMA",
  624. #endif
  625. #if SQLITE_OMIT_PROGRESS_CALLBACK
  626. "OMIT_PROGRESS_CALLBACK",
  627. #endif
  628. #if SQLITE_OMIT_QUICKBALANCE
  629. "OMIT_QUICKBALANCE",
  630. #endif
  631. #if SQLITE_OMIT_REINDEX
  632. "OMIT_REINDEX",
  633. #endif
  634. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  635. "OMIT_SCHEMA_PRAGMAS",
  636. #endif
  637. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  638. "OMIT_SCHEMA_VERSION_PRAGMAS",
  639. #endif
  640. #if SQLITE_OMIT_SHARED_CACHE
  641. "OMIT_SHARED_CACHE",
  642. #endif
  643. #if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  644. "OMIT_SHUTDOWN_DIRECTORIES",
  645. #endif
  646. #if SQLITE_OMIT_SUBQUERY
  647. "OMIT_SUBQUERY",
  648. #endif
  649. #if SQLITE_OMIT_TCL_VARIABLE
  650. "OMIT_TCL_VARIABLE",
  651. #endif
  652. #if SQLITE_OMIT_TEMPDB
  653. "OMIT_TEMPDB",
  654. #endif
  655. #if SQLITE_OMIT_TEST_CONTROL
  656. "OMIT_TEST_CONTROL",
  657. #endif
  658. #if SQLITE_OMIT_TRACE
  659. "OMIT_TRACE",
  660. #endif
  661. #if SQLITE_OMIT_TRIGGER
  662. "OMIT_TRIGGER",
  663. #endif
  664. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  665. "OMIT_TRUNCATE_OPTIMIZATION",
  666. #endif
  667. #if SQLITE_OMIT_UTF16
  668. "OMIT_UTF16",
  669. #endif
  670. #if SQLITE_OMIT_VACUUM
  671. "OMIT_VACUUM",
  672. #endif
  673. #if SQLITE_OMIT_VIEW
  674. "OMIT_VIEW",
  675. #endif
  676. #if SQLITE_OMIT_VIRTUALTABLE
  677. "OMIT_VIRTUALTABLE",
  678. #endif
  679. #if SQLITE_OMIT_WAL
  680. "OMIT_WAL",
  681. #endif
  682. #if SQLITE_OMIT_WSD
  683. "OMIT_WSD",
  684. #endif
  685. #if SQLITE_OMIT_XFER_OPT
  686. "OMIT_XFER_OPT",
  687. #endif
  688. #if SQLITE_PCACHE_SEPARATE_HEADER
  689. "PCACHE_SEPARATE_HEADER",
  690. #endif
  691. #if SQLITE_PERFORMANCE_TRACE
  692. "PERFORMANCE_TRACE",
  693. #endif
  694. #if SQLITE_POWERSAFE_OVERWRITE
  695. "POWERSAFE_OVERWRITE",
  696. #endif
  697. #if SQLITE_PREFER_PROXY_LOCKING
  698. "PREFER_PROXY_LOCKING",
  699. #endif
  700. #if SQLITE_PROXY_DEBUG
  701. "PROXY_DEBUG",
  702. #endif
  703. #if SQLITE_REVERSE_UNORDERED_SELECTS
  704. "REVERSE_UNORDERED_SELECTS",
  705. #endif
  706. #if SQLITE_RTREE_INT_ONLY
  707. "RTREE_INT_ONLY",
  708. #endif
  709. #if SQLITE_SECURE_DELETE
  710. "SECURE_DELETE",
  711. #endif
  712. #if SQLITE_SMALL_STACK
  713. "SMALL_STACK",
  714. #endif
  715. #ifdef SQLITE_SORTER_PMASZ
  716. "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
  717. #endif
  718. #if SQLITE_SOUNDEX
  719. "SOUNDEX",
  720. #endif
  721. #ifdef SQLITE_STAT4_SAMPLES
  722. "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
  723. #endif
  724. #ifdef SQLITE_STMTJRNL_SPILL
  725. "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
  726. #endif
  727. #if SQLITE_SUBSTR_COMPATIBILITY
  728. "SUBSTR_COMPATIBILITY",
  729. #endif
  730. #if SQLITE_SYSTEM_MALLOC
  731. "SYSTEM_MALLOC",
  732. #endif
  733. #if SQLITE_TCL
  734. "TCL",
  735. #endif
  736. #ifdef SQLITE_TEMP_STORE
  737. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  738. #endif
  739. #if SQLITE_TEST
  740. "TEST",
  741. #endif
  742. #if defined(SQLITE_THREADSAFE)
  743. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  744. #elif defined(THREADSAFE)
  745. "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
  746. #else
  747. "THREADSAFE=1",
  748. #endif
  749. #if SQLITE_UNLINK_AFTER_CLOSE
  750. "UNLINK_AFTER_CLOSE",
  751. #endif
  752. #if SQLITE_UNTESTABLE
  753. "UNTESTABLE",
  754. #endif
  755. #if SQLITE_USER_AUTHENTICATION
  756. "USER_AUTHENTICATION",
  757. #endif
  758. #if SQLITE_USE_ALLOCA
  759. "USE_ALLOCA",
  760. #endif
  761. #if SQLITE_USE_FCNTL_TRACE
  762. "USE_FCNTL_TRACE",
  763. #endif
  764. #if SQLITE_USE_URI
  765. "USE_URI",
  766. #endif
  767. #if SQLITE_VDBE_COVERAGE
  768. "VDBE_COVERAGE",
  769. #endif
  770. #if SQLITE_WIN32_MALLOC
  771. "WIN32_MALLOC",
  772. #endif
  773. #if SQLITE_ZERO_MALLOC
  774. "ZERO_MALLOC",
  775. #endif
  776. /*
  777. ** END CODE GENERATED BY tool/mkctime.tcl
  778. */
  779. };
  780. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
  781. *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
  782. return (const char**)sqlite3azCompileOpt;
  783. }
  784. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  785. /************** End of ctime.c ***********************************************/
  786. /************** Begin file sqliteInt.h ***************************************/
  787. /*
  788. ** 2001 September 15
  789. **
  790. ** The author disclaims copyright to this source code. In place of
  791. ** a legal notice, here is a blessing:
  792. **
  793. ** May you do good and not evil.
  794. ** May you find forgiveness for yourself and forgive others.
  795. ** May you share freely, never taking more than you give.
  796. **
  797. *************************************************************************
  798. ** Internal interface definitions for SQLite.
  799. **
  800. */
  801. #ifndef SQLITEINT_H
  802. #define SQLITEINT_H
  803. /* Special Comments:
  804. **
  805. ** Some comments have special meaning to the tools that measure test
  806. ** coverage:
  807. **
  808. ** NO_TEST - The branches on this line are not
  809. ** measured by branch coverage. This is
  810. ** used on lines of code that actually
  811. ** implement parts of coverage testing.
  812. **
  813. ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
  814. ** and the correct answer is still obtained,
  815. ** though perhaps more slowly.
  816. **
  817. ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
  818. ** and the correct answer is still obtained,
  819. ** though perhaps more slowly.
  820. **
  821. ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
  822. ** that would be harmless and undetectable
  823. ** if it did occur.
  824. **
  825. ** In all cases, the special comment must be enclosed in the usual
  826. ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
  827. ** asterisks and the comment text.
  828. */
  829. /*
  830. ** Make sure the Tcl calling convention macro is defined. This macro is
  831. ** only used by test code and Tcl integration code.
  832. */
  833. #ifndef SQLITE_TCLAPI
  834. # define SQLITE_TCLAPI
  835. #endif
  836. /*
  837. ** Include the header file used to customize the compiler options for MSVC.
  838. ** This should be done first so that it can successfully prevent spurious
  839. ** compiler warnings due to subsequent content in this file and other files
  840. ** that are included by this file.
  841. */
  842. /************** Include msvc.h in the middle of sqliteInt.h ******************/
  843. /************** Begin file msvc.h ********************************************/
  844. /*
  845. ** 2015 January 12
  846. **
  847. ** The author disclaims copyright to this source code. In place of
  848. ** a legal notice, here is a blessing:
  849. **
  850. ** May you do good and not evil.
  851. ** May you find forgiveness for yourself and forgive others.
  852. ** May you share freely, never taking more than you give.
  853. **
  854. ******************************************************************************
  855. **
  856. ** This file contains code that is specific to MSVC.
  857. */
  858. #ifndef SQLITE_MSVC_H
  859. #define SQLITE_MSVC_H
  860. #if defined(_MSC_VER)
  861. #pragma warning(disable : 4054)
  862. #pragma warning(disable : 4055)
  863. #pragma warning(disable : 4100)
  864. #pragma warning(disable : 4127)
  865. #pragma warning(disable : 4130)
  866. #pragma warning(disable : 4152)
  867. #pragma warning(disable : 4189)
  868. #pragma warning(disable : 4206)
  869. #pragma warning(disable : 4210)
  870. #pragma warning(disable : 4232)
  871. #pragma warning(disable : 4244)
  872. #pragma warning(disable : 4305)
  873. #pragma warning(disable : 4306)
  874. #pragma warning(disable : 4702)
  875. #pragma warning(disable : 4706)
  876. #endif /* defined(_MSC_VER) */
  877. #endif /* SQLITE_MSVC_H */
  878. /************** End of msvc.h ************************************************/
  879. /************** Continuing where we left off in sqliteInt.h ******************/
  880. /*
  881. ** Special setup for VxWorks
  882. */
  883. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  884. /************** Begin file vxworks.h *****************************************/
  885. /*
  886. ** 2015-03-02
  887. **
  888. ** The author disclaims copyright to this source code. In place of
  889. ** a legal notice, here is a blessing:
  890. **
  891. ** May you do good and not evil.
  892. ** May you find forgiveness for yourself and forgive others.
  893. ** May you share freely, never taking more than you give.
  894. **
  895. ******************************************************************************
  896. **
  897. ** This file contains code that is specific to Wind River's VxWorks
  898. */
  899. #if defined(__RTP__) || defined(_WRS_KERNEL)
  900. /* This is VxWorks. Set up things specially for that OS
  901. */
  902. #include <vxWorks.h>
  903. #include <pthread.h> /* amalgamator: dontcache */
  904. #define OS_VXWORKS 1
  905. #define SQLITE_OS_OTHER 0
  906. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  907. #define SQLITE_OMIT_LOAD_EXTENSION 1
  908. #define SQLITE_ENABLE_LOCKING_STYLE 0
  909. #define HAVE_UTIME 1
  910. #else
  911. /* This is not VxWorks. */
  912. #define OS_VXWORKS 0
  913. #define HAVE_FCHOWN 1
  914. #define HAVE_READLINK 1
  915. #define HAVE_LSTAT 1
  916. #endif /* defined(_WRS_KERNEL) */
  917. /************** End of vxworks.h *********************************************/
  918. /************** Continuing where we left off in sqliteInt.h ******************/
  919. /*
  920. ** These #defines should enable >2GB file support on POSIX if the
  921. ** underlying operating system supports it. If the OS lacks
  922. ** large file support, or if the OS is windows, these should be no-ops.
  923. **
  924. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  925. ** system #includes. Hence, this block of code must be the very first
  926. ** code in all source files.
  927. **
  928. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  929. ** on the compiler command line. This is necessary if you are compiling
  930. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  931. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  932. ** without this option, LFS is enable. But LFS does not exist in the kernel
  933. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  934. ** portability you should omit LFS.
  935. **
  936. ** The previous paragraph was written in 2005. (This paragraph is written
  937. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  938. ** you should probably leave LFS enabled. But some embedded platforms might
  939. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  940. **
  941. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  942. */
  943. #ifndef SQLITE_DISABLE_LFS
  944. # define _LARGE_FILE 1
  945. # ifndef _FILE_OFFSET_BITS
  946. # define _FILE_OFFSET_BITS 64
  947. # endif
  948. # define _LARGEFILE_SOURCE 1
  949. #endif
  950. /* The GCC_VERSION and MSVC_VERSION macros are used to
  951. ** conditionally include optimizations for each of these compilers. A
  952. ** value of 0 means that compiler is not being used. The
  953. ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
  954. ** optimizations, and hence set all compiler macros to 0
  955. **
  956. ** There was once also a CLANG_VERSION macro. However, we learn that the
  957. ** version numbers in clang are for "marketing" only and are inconsistent
  958. ** and unreliable. Fortunately, all versions of clang also recognize the
  959. ** gcc version numbers and have reasonable settings for gcc version numbers,
  960. ** so the GCC_VERSION macro will be set to a correct non-zero value even
  961. ** when compiling with clang.
  962. */
  963. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  964. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  965. #else
  966. # define GCC_VERSION 0
  967. #endif
  968. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  969. # define MSVC_VERSION _MSC_VER
  970. #else
  971. # define MSVC_VERSION 0
  972. #endif
  973. /* Needed for various definitions... */
  974. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  975. # define _GNU_SOURCE
  976. #endif
  977. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  978. # define _BSD_SOURCE
  979. #endif
  980. /*
  981. ** For MinGW, check to see if we can include the header file containing its
  982. ** version information, among other things. Normally, this internal MinGW
  983. ** header file would [only] be included automatically by other MinGW header
  984. ** files; however, the contained version information is now required by this
  985. ** header file to work around binary compatibility issues (see below) and
  986. ** this is the only known way to reliably obtain it. This entire #if block
  987. ** would be completely unnecessary if there was any other way of detecting
  988. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  989. ** some MinGW-specific macros). When compiling for MinGW, either the
  990. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  991. ** defined; otherwise, detection of conditions specific to MinGW will be
  992. ** disabled.
  993. */
  994. #if defined(_HAVE_MINGW_H)
  995. # include "mingw.h"
  996. #elif defined(_HAVE__MINGW_H)
  997. # include "_mingw.h"
  998. #endif
  999. /*
  1000. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  1001. ** define is required to maintain binary compatibility with the MSVC runtime
  1002. ** library in use (e.g. for Windows XP).
  1003. */
  1004. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  1005. defined(_WIN32) && !defined(_WIN64) && \
  1006. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  1007. defined(__MSVCRT__)
  1008. # define _USE_32BIT_TIME_T
  1009. #endif
  1010. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  1011. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  1012. ** MinGW.
  1013. */
  1014. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  1015. /************** Begin file sqlite3.h *****************************************/
  1016. /*
  1017. ** 2001-09-15
  1018. **
  1019. ** The author disclaims copyright to this source code. In place of
  1020. ** a legal notice, here is a blessing:
  1021. **
  1022. ** May you do good and not evil.
  1023. ** May you find forgiveness for yourself and forgive others.
  1024. ** May you share freely, never taking more than you give.
  1025. **
  1026. *************************************************************************
  1027. ** This header file defines the interface that the SQLite library
  1028. ** presents to client programs. If a C-function, structure, datatype,
  1029. ** or constant definition does not appear in this file, then it is
  1030. ** not a published API of SQLite, is subject to change without
  1031. ** notice, and should not be referenced by programs that use SQLite.
  1032. **
  1033. ** Some of the definitions that are in this file are marked as
  1034. ** "experimental". Experimental interfaces are normally new
  1035. ** features recently added to SQLite. We do not anticipate changes
  1036. ** to experimental interfaces but reserve the right to make minor changes
  1037. ** if experience from use "in the wild" suggest such changes are prudent.
  1038. **
  1039. ** The official C-language API documentation for SQLite is derived
  1040. ** from comments in this file. This file is the authoritative source
  1041. ** on how SQLite interfaces are supposed to operate.
  1042. **
  1043. ** The name of this file under configuration management is "sqlite.h.in".
  1044. ** The makefile makes some minor changes to this file (such as inserting
  1045. ** the version number) and changes its name to "sqlite3.h" as
  1046. ** part of the build process.
  1047. */
  1048. #ifndef SQLITE3_H
  1049. #define SQLITE3_H
  1050. #include <stdarg.h> /* Needed for the definition of va_list */
  1051. /*
  1052. ** Make sure we can call this stuff from C++.
  1053. */
  1054. #if 0
  1055. extern "C" {
  1056. #endif
  1057. /*
  1058. ** Provide the ability to override linkage features of the interface.
  1059. */
  1060. #ifndef SQLITE_EXTERN
  1061. # define SQLITE_EXTERN extern
  1062. #endif
  1063. #ifndef SQLITE_API
  1064. # define SQLITE_API
  1065. #endif
  1066. #ifndef SQLITE_CDECL
  1067. # define SQLITE_CDECL
  1068. #endif
  1069. #ifndef SQLITE_APICALL
  1070. # define SQLITE_APICALL
  1071. #endif
  1072. #ifndef SQLITE_STDCALL
  1073. # define SQLITE_STDCALL SQLITE_APICALL
  1074. #endif
  1075. #ifndef SQLITE_CALLBACK
  1076. # define SQLITE_CALLBACK
  1077. #endif
  1078. #ifndef SQLITE_SYSAPI
  1079. # define SQLITE_SYSAPI
  1080. #endif
  1081. /*
  1082. ** These no-op macros are used in front of interfaces to mark those
  1083. ** interfaces as either deprecated or experimental. New applications
  1084. ** should not use deprecated interfaces - they are supported for backwards
  1085. ** compatibility only. Application writers should be aware that
  1086. ** experimental interfaces are subject to change in point releases.
  1087. **
  1088. ** These macros used to resolve to various kinds of compiler magic that
  1089. ** would generate warning messages when they were used. But that
  1090. ** compiler magic ended up generating such a flurry of bug reports
  1091. ** that we have taken it all out and gone back to using simple
  1092. ** noop macros.
  1093. */
  1094. #define SQLITE_DEPRECATED
  1095. #define SQLITE_EXPERIMENTAL
  1096. /*
  1097. ** Ensure these symbols were not defined by some previous header file.
  1098. */
  1099. #ifdef SQLITE_VERSION
  1100. # undef SQLITE_VERSION
  1101. #endif
  1102. #ifdef SQLITE_VERSION_NUMBER
  1103. # undef SQLITE_VERSION_NUMBER
  1104. #endif
  1105. /*
  1106. ** CAPI3REF: Compile-Time Library Version Numbers
  1107. **
  1108. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  1109. ** evaluates to a string literal that is the SQLite version in the
  1110. ** format "X.Y.Z" where X is the major version number (always 3 for
  1111. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  1112. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  1113. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  1114. ** numbers used in [SQLITE_VERSION].)^
  1115. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  1116. ** be larger than the release from which it is derived. Either Y will
  1117. ** be held constant and Z will be incremented or else Y will be incremented
  1118. ** and Z will be reset to zero.
  1119. **
  1120. ** Since [version 3.6.18] ([dateof:3.6.18]),
  1121. ** SQLite source code has been stored in the
  1122. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  1123. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  1124. ** a string which identifies a particular check-in of SQLite
  1125. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  1126. ** string contains the date and time of the check-in (UTC) and a SHA1
  1127. ** or SHA3-256 hash of the entire source tree. If the source code has
  1128. ** been edited in any way since it was last checked in, then the last
  1129. ** four hexadecimal digits of the hash may be modified.
  1130. **
  1131. ** See also: [sqlite3_libversion()],
  1132. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  1133. ** [sqlite_version()] and [sqlite_source_id()].
  1134. */
  1135. #define SQLITE_VERSION "3.26.0"
  1136. #define SQLITE_VERSION_NUMBER 3026000
  1137. #define SQLITE_SOURCE_ID "2018-12-01 12:34:55 bf8c1b2b7a5960c282e543b9c293686dccff272512d08865f4600fb58238b4f9"
  1138. /*
  1139. ** CAPI3REF: Run-Time Library Version Numbers
  1140. ** KEYWORDS: sqlite3_version sqlite3_sourceid
  1141. **
  1142. ** These interfaces provide the same information as the [SQLITE_VERSION],
  1143. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  1144. ** but are associated with the library instead of the header file. ^(Cautious
  1145. ** programmers might include assert() statements in their application to
  1146. ** verify that values returned by these interfaces match the macros in
  1147. ** the header, and thus ensure that the application is
  1148. ** compiled with matching library and header files.
  1149. **
  1150. ** <blockquote><pre>
  1151. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  1152. ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
  1153. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  1154. ** </pre></blockquote>)^
  1155. **
  1156. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  1157. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  1158. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  1159. ** function is provided for use in DLLs since DLL users usually do not have
  1160. ** direct access to string constants within the DLL. ^The
  1161. ** sqlite3_libversion_number() function returns an integer equal to
  1162. ** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
  1163. ** a pointer to a string constant whose value is the same as the
  1164. ** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
  1165. ** using an edited copy of [the amalgamation], then the last four characters
  1166. ** of the hash might be different from [SQLITE_SOURCE_ID].)^
  1167. **
  1168. ** See also: [sqlite_version()] and [sqlite_source_id()].
  1169. */
  1170. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  1171. SQLITE_API const char *sqlite3_libversion(void);
  1172. SQLITE_API const char *sqlite3_sourceid(void);
  1173. SQLITE_API int sqlite3_libversion_number(void);
  1174. /*
  1175. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  1176. **
  1177. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  1178. ** indicating whether the specified option was defined at
  1179. ** compile time. ^The SQLITE_ prefix may be omitted from the
  1180. ** option name passed to sqlite3_compileoption_used().
  1181. **
  1182. ** ^The sqlite3_compileoption_get() function allows iterating
  1183. ** over the list of options that were defined at compile time by
  1184. ** returning the N-th compile time option string. ^If N is out of range,
  1185. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  1186. ** prefix is omitted from any strings returned by
  1187. ** sqlite3_compileoption_get().
  1188. **
  1189. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  1190. ** and sqlite3_compileoption_get() may be omitted by specifying the
  1191. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  1192. **
  1193. ** See also: SQL functions [sqlite_compileoption_used()] and
  1194. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  1195. */
  1196. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  1197. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  1198. SQLITE_API const char *sqlite3_compileoption_get(int N);
  1199. #endif
  1200. /*
  1201. ** CAPI3REF: Test To See If The Library Is Threadsafe
  1202. **
  1203. ** ^The sqlite3_threadsafe() function returns zero if and only if
  1204. ** SQLite was compiled with mutexing code omitted due to the
  1205. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  1206. **
  1207. ** SQLite can be compiled with or without mutexes. When
  1208. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  1209. ** are enabled and SQLite is threadsafe. When the
  1210. ** [SQLITE_THREADSAFE] macro is 0,
  1211. ** the mutexes are omitted. Without the mutexes, it is not safe
  1212. ** to use SQLite concurrently from more than one thread.
  1213. **
  1214. ** Enabling mutexes incurs a measurable performance penalty.
  1215. ** So if speed is of utmost importance, it makes sense to disable
  1216. ** the mutexes. But for maximum safety, mutexes should be enabled.
  1217. ** ^The default behavior is for mutexes to be enabled.
  1218. **
  1219. ** This interface can be used by an application to make sure that the
  1220. ** version of SQLite that it is linking against was compiled with
  1221. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  1222. **
  1223. ** This interface only reports on the compile-time mutex setting
  1224. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  1225. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  1226. ** can be fully or partially disabled using a call to [sqlite3_config()]
  1227. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  1228. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  1229. ** sqlite3_threadsafe() function shows only the compile-time setting of
  1230. ** thread safety, not any run-time changes to that setting made by
  1231. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  1232. ** is unchanged by calls to sqlite3_config().)^
  1233. **
  1234. ** See the [threading mode] documentation for additional information.
  1235. */
  1236. SQLITE_API int sqlite3_threadsafe(void);
  1237. /*
  1238. ** CAPI3REF: Database Connection Handle
  1239. ** KEYWORDS: {database connection} {database connections}
  1240. **
  1241. ** Each open SQLite database is represented by a pointer to an instance of
  1242. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  1243. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  1244. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  1245. ** and [sqlite3_close_v2()] are its destructors. There are many other
  1246. ** interfaces (such as
  1247. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  1248. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  1249. ** sqlite3 object.
  1250. */
  1251. typedef struct sqlite3 sqlite3;
  1252. /*
  1253. ** CAPI3REF: 64-Bit Integer Types
  1254. ** KEYWORDS: sqlite_int64 sqlite_uint64
  1255. **
  1256. ** Because there is no cross-platform way to specify 64-bit integer types
  1257. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  1258. **
  1259. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  1260. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  1261. ** compatibility only.
  1262. **
  1263. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  1264. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  1265. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  1266. ** between 0 and +18446744073709551615 inclusive.
  1267. */
  1268. #ifdef SQLITE_INT64_TYPE
  1269. typedef SQLITE_INT64_TYPE sqlite_int64;
  1270. # ifdef SQLITE_UINT64_TYPE
  1271. typedef SQLITE_UINT64_TYPE sqlite_uint64;
  1272. # else
  1273. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  1274. # endif
  1275. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  1276. typedef __int64 sqlite_int64;
  1277. typedef unsigned __int64 sqlite_uint64;
  1278. #else
  1279. typedef long long int sqlite_int64;
  1280. typedef unsigned long long int sqlite_uint64;
  1281. #endif
  1282. typedef sqlite_int64 sqlite3_int64;
  1283. typedef sqlite_uint64 sqlite3_uint64;
  1284. /*
  1285. ** If compiling for a processor that lacks floating point support,
  1286. ** substitute integer for floating-point.
  1287. */
  1288. #ifdef SQLITE_OMIT_FLOATING_POINT
  1289. # define double sqlite3_int64
  1290. #endif
  1291. /*
  1292. ** CAPI3REF: Closing A Database Connection
  1293. ** DESTRUCTOR: sqlite3
  1294. **
  1295. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  1296. ** for the [sqlite3] object.
  1297. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  1298. ** the [sqlite3] object is successfully destroyed and all associated
  1299. ** resources are deallocated.
  1300. **
  1301. ** ^If the database connection is associated with unfinalized prepared
  1302. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  1303. ** will leave the database connection open and return [SQLITE_BUSY].
  1304. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  1305. ** and/or unfinished sqlite3_backups, then the database connection becomes
  1306. ** an unusable "zombie" which will automatically be deallocated when the
  1307. ** last prepared statement is finalized or the last sqlite3_backup is
  1308. ** finished. The sqlite3_close_v2() interface is intended for use with
  1309. ** host languages that are garbage collected, and where the order in which
  1310. ** destructors are called is arbitrary.
  1311. **
  1312. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  1313. ** [sqlite3_blob_close | close] all [BLOB handles], and
  1314. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  1315. ** with the [sqlite3] object prior to attempting to close the object. ^If
  1316. ** sqlite3_close_v2() is called on a [database connection] that still has
  1317. ** outstanding [prepared statements], [BLOB handles], and/or
  1318. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  1319. ** of resources is deferred until all [prepared statements], [BLOB handles],
  1320. ** and [sqlite3_backup] objects are also destroyed.
  1321. **
  1322. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  1323. ** the transaction is automatically rolled back.
  1324. **
  1325. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  1326. ** must be either a NULL
  1327. ** pointer or an [sqlite3] object pointer obtained
  1328. ** from [sqlite3_open()], [sqlite3_open16()], or
  1329. ** [sqlite3_open_v2()], and not previously closed.
  1330. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  1331. ** argument is a harmless no-op.
  1332. */
  1333. SQLITE_API int sqlite3_close(sqlite3*);
  1334. SQLITE_API int sqlite3_close_v2(sqlite3*);
  1335. /*
  1336. ** The type for a callback function.
  1337. ** This is legacy and deprecated. It is included for historical
  1338. ** compatibility and is not documented.
  1339. */
  1340. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  1341. /*
  1342. ** CAPI3REF: One-Step Query Execution Interface
  1343. ** METHOD: sqlite3
  1344. **
  1345. ** The sqlite3_exec() interface is a convenience wrapper around
  1346. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  1347. ** that allows an application to run multiple statements of SQL
  1348. ** without having to use a lot of C code.
  1349. **
  1350. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  1351. ** semicolon-separate SQL statements passed into its 2nd argument,
  1352. ** in the context of the [database connection] passed in as its 1st
  1353. ** argument. ^If the callback function of the 3rd argument to
  1354. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  1355. ** coming out of the evaluated SQL statements. ^The 4th argument to
  1356. ** sqlite3_exec() is relayed through to the 1st argument of each
  1357. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  1358. ** is NULL, then no callback is ever invoked and result rows are
  1359. ** ignored.
  1360. **
  1361. ** ^If an error occurs while evaluating the SQL statements passed into
  1362. ** sqlite3_exec(), then execution of the current statement stops and
  1363. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  1364. ** is not NULL then any error message is written into memory obtained
  1365. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  1366. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  1367. ** on error message strings returned through the 5th parameter of
  1368. ** sqlite3_exec() after the error message string is no longer needed.
  1369. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  1370. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  1371. ** NULL before returning.
  1372. **
  1373. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  1374. ** routine returns SQLITE_ABORT without invoking the callback again and
  1375. ** without running any subsequent SQL statements.
  1376. **
  1377. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  1378. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  1379. ** callback is an array of pointers to strings obtained as if from
  1380. ** [sqlite3_column_text()], one for each column. ^If an element of a
  1381. ** result row is NULL then the corresponding string pointer for the
  1382. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  1383. ** sqlite3_exec() callback is an array of pointers to strings where each
  1384. ** entry represents the name of corresponding result column as obtained
  1385. ** from [sqlite3_column_name()].
  1386. **
  1387. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  1388. ** to an empty string, or a pointer that contains only whitespace and/or
  1389. ** SQL comments, then no SQL statements are evaluated and the database
  1390. ** is not changed.
  1391. **
  1392. ** Restrictions:
  1393. **
  1394. ** <ul>
  1395. ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  1396. ** is a valid and open [database connection].
  1397. ** <li> The application must not close the [database connection] specified by
  1398. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  1399. ** <li> The application must not modify the SQL statement text passed into
  1400. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  1401. ** </ul>
  1402. */
  1403. SQLITE_API int sqlite3_exec(
  1404. sqlite3*, /* An open database */
  1405. const char *sql, /* SQL to be evaluated */
  1406. int (*callback)(void*,int,char**,char**), /* Callback function */
  1407. void *, /* 1st argument to callback */
  1408. char **errmsg /* Error msg written here */
  1409. );
  1410. /*
  1411. ** CAPI3REF: Result Codes
  1412. ** KEYWORDS: {result code definitions}
  1413. **
  1414. ** Many SQLite functions return an integer result code from the set shown
  1415. ** here in order to indicate success or failure.
  1416. **
  1417. ** New error codes may be added in future versions of SQLite.
  1418. **
  1419. ** See also: [extended result code definitions]
  1420. */
  1421. #define SQLITE_OK 0 /* Successful result */
  1422. /* beginning-of-error-codes */
  1423. #define SQLITE_ERROR 1 /* Generic error */
  1424. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  1425. #define SQLITE_PERM 3 /* Access permission denied */
  1426. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  1427. #define SQLITE_BUSY 5 /* The database file is locked */
  1428. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  1429. #define SQLITE_NOMEM 7 /* A malloc() failed */
  1430. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  1431. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  1432. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  1433. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  1434. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  1435. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  1436. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  1437. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  1438. #define SQLITE_EMPTY 16 /* Internal use only */
  1439. #define SQLITE_SCHEMA 17 /* The database schema changed */
  1440. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  1441. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  1442. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  1443. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  1444. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  1445. #define SQLITE_AUTH 23 /* Authorization denied */
  1446. #define SQLITE_FORMAT 24 /* Not used */
  1447. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  1448. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  1449. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  1450. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  1451. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  1452. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  1453. /* end-of-error-codes */
  1454. /*
  1455. ** CAPI3REF: Extended Result Codes
  1456. ** KEYWORDS: {extended result code definitions}
  1457. **
  1458. ** In its default configuration, SQLite API routines return one of 30 integer
  1459. ** [result codes]. However, experience has shown that many of
  1460. ** these result codes are too coarse-grained. They do not provide as
  1461. ** much information about problems as programmers might like. In an effort to
  1462. ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
  1463. ** and later) include
  1464. ** support for additional result codes that provide more detailed information
  1465. ** about errors. These [extended result codes] are enabled or disabled
  1466. ** on a per database connection basis using the
  1467. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  1468. ** the most recent error can be obtained using
  1469. ** [sqlite3_extended_errcode()].
  1470. */
  1471. #define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
  1472. #define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
  1473. #define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))
  1474. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  1475. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  1476. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  1477. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  1478. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  1479. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  1480. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  1481. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  1482. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  1483. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  1484. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  1485. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  1486. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  1487. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  1488. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  1489. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  1490. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  1491. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  1492. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  1493. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  1494. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  1495. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  1496. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  1497. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  1498. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  1499. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  1500. #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
  1501. #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
  1502. #define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
  1503. #define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
  1504. #define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
  1505. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  1506. #define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))
  1507. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  1508. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  1509. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  1510. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  1511. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  1512. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  1513. #define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
  1514. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  1515. #define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8))
  1516. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  1517. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  1518. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  1519. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  1520. #define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
  1521. #define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
  1522. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  1523. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  1524. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  1525. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  1526. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  1527. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  1528. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  1529. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  1530. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  1531. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  1532. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  1533. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  1534. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  1535. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  1536. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  1537. #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
  1538. /*
  1539. ** CAPI3REF: Flags For File Open Operations
  1540. **
  1541. ** These bit values are intended for use in the
  1542. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  1543. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  1544. */
  1545. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  1546. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  1547. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  1548. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  1549. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  1550. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  1551. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  1552. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  1553. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  1554. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  1555. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  1556. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  1557. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  1558. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  1559. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  1560. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  1561. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  1562. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  1563. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  1564. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  1565. /* Reserved: 0x00F00000 */
  1566. /*
  1567. ** CAPI3REF: Device Characteristics
  1568. **
  1569. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  1570. ** object returns an integer which is a vector of these
  1571. ** bit values expressing I/O characteristics of the mass storage
  1572. ** device that holds the file that the [sqlite3_io_methods]
  1573. ** refers to.
  1574. **
  1575. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1576. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1577. ** mean that writes of blocks that are nnn bytes in size and
  1578. ** are aligned to an address which is an integer multiple of
  1579. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1580. ** that when data is appended to a file, the data is appended
  1581. ** first then the size of the file is extended, never the other
  1582. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1583. ** information is written to disk in the same order as calls
  1584. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  1585. ** after reboot following a crash or power loss, the only bytes in a
  1586. ** file that were written at the application level might have changed
  1587. ** and that adjacent bytes, even bytes within the same sector are
  1588. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  1589. ** flag indicates that a file cannot be deleted when open. The
  1590. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  1591. ** read-only media and cannot be changed even by processes with
  1592. ** elevated privileges.
  1593. **
  1594. ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
  1595. ** filesystem supports doing multiple write operations atomically when those
  1596. ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
  1597. ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
  1598. */
  1599. #define SQLITE_IOCAP_ATOMIC 0x00000001
  1600. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  1601. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  1602. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  1603. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  1604. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  1605. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  1606. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  1607. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  1608. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  1609. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  1610. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  1611. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  1612. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  1613. #define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
  1614. /*
  1615. ** CAPI3REF: File Locking Levels
  1616. **
  1617. ** SQLite uses one of these integer values as the second
  1618. ** argument to calls it makes to the xLock() and xUnlock() methods
  1619. ** of an [sqlite3_io_methods] object.
  1620. */
  1621. #define SQLITE_LOCK_NONE 0
  1622. #define SQLITE_LOCK_SHARED 1
  1623. #define SQLITE_LOCK_RESERVED 2
  1624. #define SQLITE_LOCK_PENDING 3
  1625. #define SQLITE_LOCK_EXCLUSIVE 4
  1626. /*
  1627. ** CAPI3REF: Synchronization Type Flags
  1628. **
  1629. ** When SQLite invokes the xSync() method of an
  1630. ** [sqlite3_io_methods] object it uses a combination of
  1631. ** these integer values as the second argument.
  1632. **
  1633. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1634. ** sync operation only needs to flush data to mass storage. Inode
  1635. ** information need not be flushed. If the lower four bits of the flag
  1636. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1637. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1638. ** to use Mac OS X style fullsync instead of fsync().
  1639. **
  1640. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1641. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1642. ** settings. The [synchronous pragma] determines when calls to the
  1643. ** xSync VFS method occur and applies uniformly across all platforms.
  1644. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1645. ** energetic or rigorous or forceful the sync operations are and
  1646. ** only make a difference on Mac OSX for the default SQLite code.
  1647. ** (Third-party VFS implementations might also make the distinction
  1648. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1649. ** operating systems natively supported by SQLite, only Mac OSX
  1650. ** cares about the difference.)
  1651. */
  1652. #define SQLITE_SYNC_NORMAL 0x00002
  1653. #define SQLITE_SYNC_FULL 0x00003
  1654. #define SQLITE_SYNC_DATAONLY 0x00010
  1655. /*
  1656. ** CAPI3REF: OS Interface Open File Handle
  1657. **
  1658. ** An [sqlite3_file] object represents an open file in the
  1659. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  1660. ** implementations will
  1661. ** want to subclass this object by appending additional fields
  1662. ** for their own use. The pMethods entry is a pointer to an
  1663. ** [sqlite3_io_methods] object that defines methods for performing
  1664. ** I/O operations on the open file.
  1665. */
  1666. typedef struct sqlite3_file sqlite3_file;
  1667. struct sqlite3_file {
  1668. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1669. };
  1670. /*
  1671. ** CAPI3REF: OS Interface File Virtual Methods Object
  1672. **
  1673. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1674. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1675. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1676. ** This object defines the methods used to perform various operations
  1677. ** against the open file represented by the [sqlite3_file] object.
  1678. **
  1679. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  1680. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1681. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  1682. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1683. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1684. ** to NULL.
  1685. **
  1686. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1687. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1688. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1689. ** flag may be ORed in to indicate that only the data of the file
  1690. ** and not its inode needs to be synced.
  1691. **
  1692. ** The integer values to xLock() and xUnlock() are one of
  1693. ** <ul>
  1694. ** <li> [SQLITE_LOCK_NONE],
  1695. ** <li> [SQLITE_LOCK_SHARED],
  1696. ** <li> [SQLITE_LOCK_RESERVED],
  1697. ** <li> [SQLITE_LOCK_PENDING], or
  1698. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1699. ** </ul>
  1700. ** xLock() increases the lock. xUnlock() decreases the lock.
  1701. ** The xCheckReservedLock() method checks whether any database connection,
  1702. ** either in this process or in some other process, is holding a RESERVED,
  1703. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1704. ** if such a lock exists and false otherwise.
  1705. **
  1706. ** The xFileControl() method is a generic interface that allows custom
  1707. ** VFS implementations to directly control an open file using the
  1708. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1709. ** integer opcode. The third argument is a generic pointer intended to
  1710. ** point to a structure that may contain arguments or space in which to
  1711. ** write return values. Potential uses for xFileControl() might be
  1712. ** functions to enable blocking locks with timeouts, to change the
  1713. ** locking strategy (for example to use dot-file locks), to inquire
  1714. ** about the status of a lock, or to break stale locks. The SQLite
  1715. ** core reserves all opcodes less than 100 for its own use.
  1716. ** A [file control opcodes | list of opcodes] less than 100 is available.
  1717. ** Applications that define a custom xFileControl method should use opcodes
  1718. ** greater than 100 to avoid conflicts. VFS implementations should
  1719. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1720. ** recognize.
  1721. **
  1722. ** The xSectorSize() method returns the sector size of the
  1723. ** device that underlies the file. The sector size is the
  1724. ** minimum write that can be performed without disturbing
  1725. ** other bytes in the file. The xDeviceCharacteristics()
  1726. ** method returns a bit vector describing behaviors of the
  1727. ** underlying device:
  1728. **
  1729. ** <ul>
  1730. ** <li> [SQLITE_IOCAP_ATOMIC]
  1731. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1732. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1733. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1734. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1735. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1736. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1737. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1738. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1739. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1740. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1741. ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
  1742. ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
  1743. ** <li> [SQLITE_IOCAP_IMMUTABLE]
  1744. ** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
  1745. ** </ul>
  1746. **
  1747. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1748. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1749. ** mean that writes of blocks that are nnn bytes in size and
  1750. ** are aligned to an address which is an integer multiple of
  1751. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1752. ** that when data is appended to a file, the data is appended
  1753. ** first then the size of the file is extended, never the other
  1754. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1755. ** information is written to disk in the same order as calls
  1756. ** to xWrite().
  1757. **
  1758. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1759. ** in the unread portions of the buffer with zeros. A VFS that
  1760. ** fails to zero-fill short reads might seem to work. However,
  1761. ** failure to zero-fill short reads will eventually lead to
  1762. ** database corruption.
  1763. */
  1764. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1765. struct sqlite3_io_methods {
  1766. int iVersion;
  1767. int (*xClose)(sqlite3_file*);
  1768. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1769. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1770. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1771. int (*xSync)(sqlite3_file*, int flags);
  1772. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1773. int (*xLock)(sqlite3_file*, int);
  1774. int (*xUnlock)(sqlite3_file*, int);
  1775. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1776. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1777. int (*xSectorSize)(sqlite3_file*);
  1778. int (*xDeviceCharacteristics)(sqlite3_file*);
  1779. /* Methods above are valid for version 1 */
  1780. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1781. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1782. void (*xShmBarrier)(sqlite3_file*);
  1783. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1784. /* Methods above are valid for version 2 */
  1785. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1786. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1787. /* Methods above are valid for version 3 */
  1788. /* Additional methods may be added in future releases */
  1789. };
  1790. /*
  1791. ** CAPI3REF: Standard File Control Opcodes
  1792. ** KEYWORDS: {file control opcodes} {file control opcode}
  1793. **
  1794. ** These integer constants are opcodes for the xFileControl method
  1795. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1796. ** interface.
  1797. **
  1798. ** <ul>
  1799. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  1800. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1801. ** opcode causes the xFileControl method to write the current state of
  1802. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1803. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1804. ** into an integer that the pArg argument points to. This capability
  1805. ** is used during testing and is only available when the SQLITE_TEST
  1806. ** compile-time option is used.
  1807. **
  1808. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1809. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1810. ** layer a hint of how large the database file will grow to be during the
  1811. ** current transaction. This hint is not guaranteed to be accurate but it
  1812. ** is often close. The underlying VFS might choose to preallocate database
  1813. ** file space based on this hint in order to help writes to the database
  1814. ** file run faster.
  1815. **
  1816. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1817. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1818. ** extends and truncates the database file in chunks of a size specified
  1819. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1820. ** point to an integer (type int) containing the new chunk-size to use
  1821. ** for the nominated database. Allocating database file space in large
  1822. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1823. ** improve performance on some systems.
  1824. **
  1825. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1826. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1827. ** to the [sqlite3_file] object associated with a particular database
  1828. ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
  1829. **
  1830. ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  1831. ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  1832. ** to the [sqlite3_file] object associated with the journal file (either
  1833. ** the [rollback journal] or the [write-ahead log]) for a particular database
  1834. ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
  1835. **
  1836. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1837. ** No longer in use.
  1838. **
  1839. ** <li>[[SQLITE_FCNTL_SYNC]]
  1840. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  1841. ** sent to the VFS immediately before the xSync method is invoked on a
  1842. ** database file descriptor. Or, if the xSync method is not invoked
  1843. ** because the user has configured SQLite with
  1844. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  1845. ** of the xSync method. In most cases, the pointer argument passed with
  1846. ** this file-control is NULL. However, if the database file is being synced
  1847. ** as part of a multi-database commit, the argument points to a nul-terminated
  1848. ** string containing the transactions master-journal file name. VFSes that
  1849. ** do not need this signal should silently ignore this opcode. Applications
  1850. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  1851. ** disrupt the operation of the specialized VFSes that do require it.
  1852. **
  1853. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1854. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1855. ** and sent to the VFS after a transaction has been committed immediately
  1856. ** but before the database is unlocked. VFSes that do not need this signal
  1857. ** should silently ignore this opcode. Applications should not call
  1858. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  1859. ** operation of the specialized VFSes that do require it.
  1860. **
  1861. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1862. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1863. ** retry counts and intervals for certain disk I/O operations for the
  1864. ** windows [VFS] in order to provide robustness in the presence of
  1865. ** anti-virus programs. By default, the windows VFS will retry file read,
  1866. ** file write, and file delete operations up to 10 times, with a delay
  1867. ** of 25 milliseconds before the first retry and with the delay increasing
  1868. ** by an additional 25 milliseconds with each subsequent retry. This
  1869. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1870. ** to be adjusted. The values are changed for all database connections
  1871. ** within the same process. The argument is a pointer to an array of two
  1872. ** integers where the first integer is the new retry count and the second
  1873. ** integer is the delay. If either integer is negative, then the setting
  1874. ** is not changed but instead the prior value of that setting is written
  1875. ** into the array entry, allowing the current retry settings to be
  1876. ** interrogated. The zDbName parameter is ignored.
  1877. **
  1878. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1879. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1880. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1881. ** write ahead log ([WAL file]) and shared memory
  1882. ** files used for transaction control
  1883. ** are automatically deleted when the latest connection to the database
  1884. ** closes. Setting persistent WAL mode causes those files to persist after
  1885. ** close. Persisting the files is useful when other processes that do not
  1886. ** have write permission on the directory containing the database file want
  1887. ** to read the database file, as the WAL and shared memory files must exist
  1888. ** in order for the database to be readable. The fourth parameter to
  1889. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1890. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1891. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1892. ** WAL persistence setting.
  1893. **
  1894. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1895. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1896. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1897. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1898. ** xDeviceCharacteristics methods. The fourth parameter to
  1899. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1900. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1901. ** mode. If the integer is -1, then it is overwritten with the current
  1902. ** zero-damage mode setting.
  1903. **
  1904. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1905. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1906. ** a write transaction to indicate that, unless it is rolled back for some
  1907. ** reason, the entire database file will be overwritten by the current
  1908. ** transaction. This is used by VACUUM operations.
  1909. **
  1910. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1911. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1912. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1913. ** final bottom-level VFS are written into memory obtained from
  1914. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1915. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1916. ** The caller is responsible for freeing the memory when done. As with
  1917. ** all file-control actions, there is no guarantee that this will actually
  1918. ** do anything. Callers should initialize the char* variable to a NULL
  1919. ** pointer in case this file-control is not implemented. This file-control
  1920. ** is intended for diagnostic use only.
  1921. **
  1922. ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1923. ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1924. ** [VFSes] currently in use. ^(The argument X in
  1925. ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1926. ** of type "[sqlite3_vfs] **". This opcodes will set *X
  1927. ** to a pointer to the top-level VFS.)^
  1928. ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1929. ** upper-most shim only.
  1930. **
  1931. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1932. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1933. ** file control is sent to the open [sqlite3_file] object corresponding
  1934. ** to the database file to which the pragma statement refers. ^The argument
  1935. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1936. ** pointers to strings (char**) in which the second element of the array
  1937. ** is the name of the pragma and the third element is the argument to the
  1938. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1939. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1940. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1941. ** or the equivalent and that string will become the result of the pragma or
  1942. ** the error message if the pragma fails. ^If the
  1943. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1944. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1945. ** file control returns [SQLITE_OK], then the parser assumes that the
  1946. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1947. ** prepared statement if result string is NULL, or that returns a copy
  1948. ** of the result string if the string is non-NULL.
  1949. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1950. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1951. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1952. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1953. ** file control occurs at the beginning of pragma statement analysis and so
  1954. ** it is able to override built-in [PRAGMA] statements.
  1955. **
  1956. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1957. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1958. ** file-control may be invoked by SQLite on the database file handle
  1959. ** shortly after it is opened in order to provide a custom VFS with access
  1960. ** to the connections busy-handler callback. The argument is of type (void **)
  1961. ** - an array of two (void *) values. The first (void *) actually points
  1962. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1963. ** busy-handler, this function should be invoked with the second (void *) in
  1964. ** the array as the only argument. If it returns non-zero, then the operation
  1965. ** should be retried. If it returns zero, the custom VFS should abandon the
  1966. ** current operation.
  1967. **
  1968. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1969. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1970. ** to have SQLite generate a
  1971. ** temporary filename using the same algorithm that is followed to generate
  1972. ** temporary filenames for TEMP tables and other internal uses. The
  1973. ** argument should be a char** which will be filled with the filename
  1974. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1975. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1976. **
  1977. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1978. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1979. ** maximum number of bytes that will be used for memory-mapped I/O.
  1980. ** The argument is a pointer to a value of type sqlite3_int64 that
  1981. ** is an advisory maximum number of bytes in the file to memory map. The
  1982. ** pointer is overwritten with the old value. The limit is not changed if
  1983. ** the value originally pointed to is negative, and so the current limit
  1984. ** can be queried by passing in a pointer to a negative number. This
  1985. ** file-control is used internally to implement [PRAGMA mmap_size].
  1986. **
  1987. ** <li>[[SQLITE_FCNTL_TRACE]]
  1988. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1989. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1990. ** This file control is used by some VFS activity tracing [shims].
  1991. ** The argument is a zero-terminated string. Higher layers in the
  1992. ** SQLite stack may generate instances of this file control if
  1993. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1994. **
  1995. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1996. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1997. ** pointer to an integer and it writes a boolean into that integer depending
  1998. ** on whether or not the file has been renamed, moved, or deleted since it
  1999. ** was first opened.
  2000. **
  2001. ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
  2002. ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
  2003. ** underlying native file handle associated with a file handle. This file
  2004. ** control interprets its argument as a pointer to a native file handle and
  2005. ** writes the resulting value there.
  2006. **
  2007. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  2008. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  2009. ** opcode causes the xFileControl method to swap the file handle with the one
  2010. ** pointed to by the pArg argument. This capability is used during testing
  2011. ** and only needs to be supported when SQLITE_TEST is defined.
  2012. **
  2013. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  2014. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  2015. ** be advantageous to block on the next WAL lock if the lock is not immediately
  2016. ** available. The WAL subsystem issues this signal during rare
  2017. ** circumstances in order to fix a problem with priority inversion.
  2018. ** Applications should <em>not</em> use this file-control.
  2019. **
  2020. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  2021. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  2022. ** VFS should return SQLITE_NOTFOUND for this opcode.
  2023. **
  2024. ** <li>[[SQLITE_FCNTL_RBU]]
  2025. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  2026. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  2027. ** this opcode.
  2028. **
  2029. ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
  2030. ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
  2031. ** the file descriptor is placed in "batch write mode", which
  2032. ** means all subsequent write operations will be deferred and done
  2033. ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
  2034. ** that do not support batch atomic writes will return SQLITE_NOTFOUND.
  2035. ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
  2036. ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
  2037. ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
  2038. ** no VFS interface calls on the same [sqlite3_file] file descriptor
  2039. ** except for calls to the xWrite method and the xFileControl method
  2040. ** with [SQLITE_FCNTL_SIZE_HINT].
  2041. **
  2042. ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
  2043. ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
  2044. ** operations since the previous successful call to
  2045. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
  2046. ** This file control returns [SQLITE_OK] if and only if the writes were
  2047. ** all performed successfully and have been committed to persistent storage.
  2048. ** ^Regardless of whether or not it is successful, this file control takes
  2049. ** the file descriptor out of batch write mode so that all subsequent
  2050. ** write operations are independent.
  2051. ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
  2052. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2053. **
  2054. ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
  2055. ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
  2056. ** operations since the previous successful call to
  2057. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
  2058. ** ^This file control takes the file descriptor out of batch write mode
  2059. ** so that all subsequent write operations are independent.
  2060. ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
  2061. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2062. **
  2063. ** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
  2064. ** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode causes attempts to obtain
  2065. ** a file lock using the xLock or xShmLock methods of the VFS to wait
  2066. ** for up to M milliseconds before failing, where M is the single
  2067. ** unsigned integer parameter.
  2068. **
  2069. ** <li>[[SQLITE_FCNTL_DATA_VERSION]]
  2070. ** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
  2071. ** a database file. The argument is a pointer to a 32-bit unsigned integer.
  2072. ** The "data version" for the pager is written into the pointer. The
  2073. ** "data version" changes whenever any change occurs to the corresponding
  2074. ** database file, either through SQL statements on the same database
  2075. ** connection or through transactions committed by separate database
  2076. ** connections possibly in other processes. The [sqlite3_total_changes()]
  2077. ** interface can be used to find if any database on the connection has changed,
  2078. ** but that interface responds to changes on TEMP as well as MAIN and does
  2079. ** not provide a mechanism to detect changes to MAIN only. Also, the
  2080. ** [sqlite3_total_changes()] interface responds to internal changes only and
  2081. ** omits changes made by other database connections. The
  2082. ** [PRAGMA data_version] command provide a mechanism to detect changes to
  2083. ** a single attached database that occur due to other database connections,
  2084. ** but omits changes implemented by the database connection on which it is
  2085. ** called. This file control is the only mechanism to detect changes that
  2086. ** happen either internally or externally and that are associated with
  2087. ** a particular attached database.
  2088. ** </ul>
  2089. */
  2090. #define SQLITE_FCNTL_LOCKSTATE 1
  2091. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  2092. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  2093. #define SQLITE_FCNTL_LAST_ERRNO 4
  2094. #define SQLITE_FCNTL_SIZE_HINT 5
  2095. #define SQLITE_FCNTL_CHUNK_SIZE 6
  2096. #define SQLITE_FCNTL_FILE_POINTER 7
  2097. #define SQLITE_FCNTL_SYNC_OMITTED 8
  2098. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  2099. #define SQLITE_FCNTL_PERSIST_WAL 10
  2100. #define SQLITE_FCNTL_OVERWRITE 11
  2101. #define SQLITE_FCNTL_VFSNAME 12
  2102. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  2103. #define SQLITE_FCNTL_PRAGMA 14
  2104. #define SQLITE_FCNTL_BUSYHANDLER 15
  2105. #define SQLITE_FCNTL_TEMPFILENAME 16
  2106. #define SQLITE_FCNTL_MMAP_SIZE 18
  2107. #define SQLITE_FCNTL_TRACE 19
  2108. #define SQLITE_FCNTL_HAS_MOVED 20
  2109. #define SQLITE_FCNTL_SYNC 21
  2110. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  2111. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  2112. #define SQLITE_FCNTL_WAL_BLOCK 24
  2113. #define SQLITE_FCNTL_ZIPVFS 25
  2114. #define SQLITE_FCNTL_RBU 26
  2115. #define SQLITE_FCNTL_VFS_POINTER 27
  2116. #define SQLITE_FCNTL_JOURNAL_POINTER 28
  2117. #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
  2118. #define SQLITE_FCNTL_PDB 30
  2119. #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
  2120. #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
  2121. #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
  2122. #define SQLITE_FCNTL_LOCK_TIMEOUT 34
  2123. #define SQLITE_FCNTL_DATA_VERSION 35
  2124. /* deprecated names */
  2125. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  2126. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  2127. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  2128. /*
  2129. ** CAPI3REF: Mutex Handle
  2130. **
  2131. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  2132. ** abstract type for a mutex object. The SQLite core never looks
  2133. ** at the internal representation of an [sqlite3_mutex]. It only
  2134. ** deals with pointers to the [sqlite3_mutex] object.
  2135. **
  2136. ** Mutexes are created using [sqlite3_mutex_alloc()].
  2137. */
  2138. typedef struct sqlite3_mutex sqlite3_mutex;
  2139. /*
  2140. ** CAPI3REF: Loadable Extension Thunk
  2141. **
  2142. ** A pointer to the opaque sqlite3_api_routines structure is passed as
  2143. ** the third parameter to entry points of [loadable extensions]. This
  2144. ** structure must be typedefed in order to work around compiler warnings
  2145. ** on some platforms.
  2146. */
  2147. typedef struct sqlite3_api_routines sqlite3_api_routines;
  2148. /*
  2149. ** CAPI3REF: OS Interface Object
  2150. **
  2151. ** An instance of the sqlite3_vfs object defines the interface between
  2152. ** the SQLite core and the underlying operating system. The "vfs"
  2153. ** in the name of the object stands for "virtual file system". See
  2154. ** the [VFS | VFS documentation] for further information.
  2155. **
  2156. ** The VFS interface is sometimes extended by adding new methods onto
  2157. ** the end. Each time such an extension occurs, the iVersion field
  2158. ** is incremented. The iVersion value started out as 1 in
  2159. ** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
  2160. ** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
  2161. ** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields
  2162. ** may be appended to the sqlite3_vfs object and the iVersion value
  2163. ** may increase again in future versions of SQLite.
  2164. ** Note that the structure
  2165. ** of the sqlite3_vfs object changes in the transition from
  2166. ** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
  2167. ** and yet the iVersion field was not modified.
  2168. **
  2169. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  2170. ** structure used by this VFS. mxPathname is the maximum length of
  2171. ** a pathname in this VFS.
  2172. **
  2173. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  2174. ** the pNext pointer. The [sqlite3_vfs_register()]
  2175. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  2176. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  2177. ** searches the list. Neither the application code nor the VFS
  2178. ** implementation should use the pNext pointer.
  2179. **
  2180. ** The pNext field is the only field in the sqlite3_vfs
  2181. ** structure that SQLite will ever modify. SQLite will only access
  2182. ** or modify this field while holding a particular static mutex.
  2183. ** The application should never modify anything within the sqlite3_vfs
  2184. ** object once the object has been registered.
  2185. **
  2186. ** The zName field holds the name of the VFS module. The name must
  2187. ** be unique across all VFS modules.
  2188. **
  2189. ** [[sqlite3_vfs.xOpen]]
  2190. ** ^SQLite guarantees that the zFilename parameter to xOpen
  2191. ** is either a NULL pointer or string obtained
  2192. ** from xFullPathname() with an optional suffix added.
  2193. ** ^If a suffix is added to the zFilename parameter, it will
  2194. ** consist of a single "-" character followed by no more than
  2195. ** 11 alphanumeric and/or "-" characters.
  2196. ** ^SQLite further guarantees that
  2197. ** the string will be valid and unchanged until xClose() is
  2198. ** called. Because of the previous sentence,
  2199. ** the [sqlite3_file] can safely store a pointer to the
  2200. ** filename if it needs to remember the filename for some reason.
  2201. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  2202. ** must invent its own temporary name for the file. ^Whenever the
  2203. ** xFilename parameter is NULL it will also be the case that the
  2204. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  2205. **
  2206. ** The flags argument to xOpen() includes all bits set in
  2207. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  2208. ** or [sqlite3_open16()] is used, then flags includes at least
  2209. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  2210. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  2211. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  2212. **
  2213. ** ^(SQLite will also add one of the following flags to the xOpen()
  2214. ** call, depending on the object being opened:
  2215. **
  2216. ** <ul>
  2217. ** <li> [SQLITE_OPEN_MAIN_DB]
  2218. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  2219. ** <li> [SQLITE_OPEN_TEMP_DB]
  2220. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  2221. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  2222. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  2223. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  2224. ** <li> [SQLITE_OPEN_WAL]
  2225. ** </ul>)^
  2226. **
  2227. ** The file I/O implementation can use the object type flags to
  2228. ** change the way it deals with files. For example, an application
  2229. ** that does not care about crash recovery or rollback might make
  2230. ** the open of a journal file a no-op. Writes to this journal would
  2231. ** also be no-ops, and any attempt to read the journal would return
  2232. ** SQLITE_IOERR. Or the implementation might recognize that a database
  2233. ** file will be doing page-aligned sector reads and writes in a random
  2234. ** order and set up its I/O subsystem accordingly.
  2235. **
  2236. ** SQLite might also add one of the following flags to the xOpen method:
  2237. **
  2238. ** <ul>
  2239. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  2240. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  2241. ** </ul>
  2242. **
  2243. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  2244. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  2245. ** will be set for TEMP databases and their journals, transient
  2246. ** databases, and subjournals.
  2247. **
  2248. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  2249. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  2250. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  2251. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  2252. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  2253. ** be created, and that it is an error if it already exists.
  2254. ** It is <i>not</i> used to indicate the file should be opened
  2255. ** for exclusive access.
  2256. **
  2257. ** ^At least szOsFile bytes of memory are allocated by SQLite
  2258. ** to hold the [sqlite3_file] structure passed as the third
  2259. ** argument to xOpen. The xOpen method does not have to
  2260. ** allocate the structure; it should just fill it in. Note that
  2261. ** the xOpen method must set the sqlite3_file.pMethods to either
  2262. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  2263. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  2264. ** element will be valid after xOpen returns regardless of the success
  2265. ** or failure of the xOpen call.
  2266. **
  2267. ** [[sqlite3_vfs.xAccess]]
  2268. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  2269. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  2270. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  2271. ** to test whether a file is at least readable. The file can be a
  2272. ** directory.
  2273. **
  2274. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  2275. ** output buffer xFullPathname. The exact size of the output buffer
  2276. ** is also passed as a parameter to both methods. If the output buffer
  2277. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  2278. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  2279. ** to prevent this by setting mxPathname to a sufficiently large value.
  2280. **
  2281. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  2282. ** interfaces are not strictly a part of the filesystem, but they are
  2283. ** included in the VFS structure for completeness.
  2284. ** The xRandomness() function attempts to return nBytes bytes
  2285. ** of good-quality randomness into zOut. The return value is
  2286. ** the actual number of bytes of randomness obtained.
  2287. ** The xSleep() method causes the calling thread to sleep for at
  2288. ** least the number of microseconds given. ^The xCurrentTime()
  2289. ** method returns a Julian Day Number for the current date and time as
  2290. ** a floating point value.
  2291. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  2292. ** Day Number multiplied by 86400000 (the number of milliseconds in
  2293. ** a 24-hour day).
  2294. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  2295. ** date and time if that method is available (if iVersion is 2 or
  2296. ** greater and the function pointer is not NULL) and will fall back
  2297. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  2298. **
  2299. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  2300. ** are not used by the SQLite core. These optional interfaces are provided
  2301. ** by some VFSes to facilitate testing of the VFS code. By overriding
  2302. ** system calls with functions under its control, a test program can
  2303. ** simulate faults and error conditions that would otherwise be difficult
  2304. ** or impossible to induce. The set of system calls that can be overridden
  2305. ** varies from one VFS to another, and from one version of the same VFS to the
  2306. ** next. Applications that use these interfaces must be prepared for any
  2307. ** or all of these interfaces to be NULL or for their behavior to change
  2308. ** from one release to the next. Applications must not attempt to access
  2309. ** any of these methods if the iVersion of the VFS is less than 3.
  2310. */
  2311. typedef struct sqlite3_vfs sqlite3_vfs;
  2312. typedef void (*sqlite3_syscall_ptr)(void);
  2313. struct sqlite3_vfs {
  2314. int iVersion; /* Structure version number (currently 3) */
  2315. int szOsFile; /* Size of subclassed sqlite3_file */
  2316. int mxPathname; /* Maximum file pathname length */
  2317. sqlite3_vfs *pNext; /* Next registered VFS */
  2318. const char *zName; /* Name of this virtual file system */
  2319. void *pAppData; /* Pointer to application-specific data */
  2320. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  2321. int flags, int *pOutFlags);
  2322. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  2323. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  2324. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  2325. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  2326. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  2327. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  2328. void (*xDlClose)(sqlite3_vfs*, void*);
  2329. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  2330. int (*xSleep)(sqlite3_vfs*, int microseconds);
  2331. int (*xCurrentTime)(sqlite3_vfs*, double*);
  2332. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  2333. /*
  2334. ** The methods above are in version 1 of the sqlite_vfs object
  2335. ** definition. Those that follow are added in version 2 or later
  2336. */
  2337. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  2338. /*
  2339. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  2340. ** Those below are for version 3 and greater.
  2341. */
  2342. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  2343. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  2344. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  2345. /*
  2346. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  2347. ** New fields may be appended in future versions. The iVersion
  2348. ** value will increment whenever this happens.
  2349. */
  2350. };
  2351. /*
  2352. ** CAPI3REF: Flags for the xAccess VFS method
  2353. **
  2354. ** These integer constants can be used as the third parameter to
  2355. ** the xAccess method of an [sqlite3_vfs] object. They determine
  2356. ** what kind of permissions the xAccess method is looking for.
  2357. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  2358. ** simply checks whether the file exists.
  2359. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  2360. ** checks whether the named directory is both readable and writable
  2361. ** (in other words, if files can be added, removed, and renamed within
  2362. ** the directory).
  2363. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  2364. ** [temp_store_directory pragma], though this could change in a future
  2365. ** release of SQLite.
  2366. ** With SQLITE_ACCESS_READ, the xAccess method
  2367. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  2368. ** currently unused, though it might be used in a future release of
  2369. ** SQLite.
  2370. */
  2371. #define SQLITE_ACCESS_EXISTS 0
  2372. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  2373. #define SQLITE_ACCESS_READ 2 /* Unused */
  2374. /*
  2375. ** CAPI3REF: Flags for the xShmLock VFS method
  2376. **
  2377. ** These integer constants define the various locking operations
  2378. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  2379. ** following are the only legal combinations of flags to the
  2380. ** xShmLock method:
  2381. **
  2382. ** <ul>
  2383. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  2384. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  2385. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  2386. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  2387. ** </ul>
  2388. **
  2389. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  2390. ** was given on the corresponding lock.
  2391. **
  2392. ** The xShmLock method can transition between unlocked and SHARED or
  2393. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  2394. ** and EXCLUSIVE.
  2395. */
  2396. #define SQLITE_SHM_UNLOCK 1
  2397. #define SQLITE_SHM_LOCK 2
  2398. #define SQLITE_SHM_SHARED 4
  2399. #define SQLITE_SHM_EXCLUSIVE 8
  2400. /*
  2401. ** CAPI3REF: Maximum xShmLock index
  2402. **
  2403. ** The xShmLock method on [sqlite3_io_methods] may use values
  2404. ** between 0 and this upper bound as its "offset" argument.
  2405. ** The SQLite core will never attempt to acquire or release a
  2406. ** lock outside of this range
  2407. */
  2408. #define SQLITE_SHM_NLOCK 8
  2409. /*
  2410. ** CAPI3REF: Initialize The SQLite Library
  2411. **
  2412. ** ^The sqlite3_initialize() routine initializes the
  2413. ** SQLite library. ^The sqlite3_shutdown() routine
  2414. ** deallocates any resources that were allocated by sqlite3_initialize().
  2415. ** These routines are designed to aid in process initialization and
  2416. ** shutdown on embedded systems. Workstation applications using
  2417. ** SQLite normally do not need to invoke either of these routines.
  2418. **
  2419. ** A call to sqlite3_initialize() is an "effective" call if it is
  2420. ** the first time sqlite3_initialize() is invoked during the lifetime of
  2421. ** the process, or if it is the first time sqlite3_initialize() is invoked
  2422. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  2423. ** of sqlite3_initialize() does any initialization. All other calls
  2424. ** are harmless no-ops.)^
  2425. **
  2426. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  2427. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  2428. ** an effective call to sqlite3_shutdown() does any deinitialization.
  2429. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  2430. **
  2431. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  2432. ** is not. The sqlite3_shutdown() interface must only be called from a
  2433. ** single thread. All open [database connections] must be closed and all
  2434. ** other SQLite resources must be deallocated prior to invoking
  2435. ** sqlite3_shutdown().
  2436. **
  2437. ** Among other things, ^sqlite3_initialize() will invoke
  2438. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  2439. ** will invoke sqlite3_os_end().
  2440. **
  2441. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  2442. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  2443. ** the library (perhaps it is unable to allocate a needed resource such
  2444. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  2445. **
  2446. ** ^The sqlite3_initialize() routine is called internally by many other
  2447. ** SQLite interfaces so that an application usually does not need to
  2448. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  2449. ** calls sqlite3_initialize() so the SQLite library will be automatically
  2450. ** initialized when [sqlite3_open()] is called if it has not be initialized
  2451. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  2452. ** compile-time option, then the automatic calls to sqlite3_initialize()
  2453. ** are omitted and the application must call sqlite3_initialize() directly
  2454. ** prior to using any other SQLite interface. For maximum portability,
  2455. ** it is recommended that applications always invoke sqlite3_initialize()
  2456. ** directly prior to using any other SQLite interface. Future releases
  2457. ** of SQLite may require this. In other words, the behavior exhibited
  2458. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  2459. ** default behavior in some future release of SQLite.
  2460. **
  2461. ** The sqlite3_os_init() routine does operating-system specific
  2462. ** initialization of the SQLite library. The sqlite3_os_end()
  2463. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  2464. ** performed by these routines include allocation or deallocation
  2465. ** of static resources, initialization of global variables,
  2466. ** setting up a default [sqlite3_vfs] module, or setting up
  2467. ** a default configuration using [sqlite3_config()].
  2468. **
  2469. ** The application should never invoke either sqlite3_os_init()
  2470. ** or sqlite3_os_end() directly. The application should only invoke
  2471. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  2472. ** interface is called automatically by sqlite3_initialize() and
  2473. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  2474. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  2475. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  2476. ** When [custom builds | built for other platforms]
  2477. ** (using the [SQLITE_OS_OTHER=1] compile-time
  2478. ** option) the application must supply a suitable implementation for
  2479. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  2480. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  2481. ** must return [SQLITE_OK] on success and some other [error code] upon
  2482. ** failure.
  2483. */
  2484. SQLITE_API int sqlite3_initialize(void);
  2485. SQLITE_API int sqlite3_shutdown(void);
  2486. SQLITE_API int sqlite3_os_init(void);
  2487. SQLITE_API int sqlite3_os_end(void);
  2488. /*
  2489. ** CAPI3REF: Configuring The SQLite Library
  2490. **
  2491. ** The sqlite3_config() interface is used to make global configuration
  2492. ** changes to SQLite in order to tune SQLite to the specific needs of
  2493. ** the application. The default configuration is recommended for most
  2494. ** applications and so this routine is usually not necessary. It is
  2495. ** provided to support rare applications with unusual needs.
  2496. **
  2497. ** <b>The sqlite3_config() interface is not threadsafe. The application
  2498. ** must ensure that no other SQLite interfaces are invoked by other
  2499. ** threads while sqlite3_config() is running.</b>
  2500. **
  2501. ** The sqlite3_config() interface
  2502. ** may only be invoked prior to library initialization using
  2503. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  2504. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  2505. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  2506. ** Note, however, that ^sqlite3_config() can be called as part of the
  2507. ** implementation of an application-defined [sqlite3_os_init()].
  2508. **
  2509. ** The first argument to sqlite3_config() is an integer
  2510. ** [configuration option] that determines
  2511. ** what property of SQLite is to be configured. Subsequent arguments
  2512. ** vary depending on the [configuration option]
  2513. ** in the first argument.
  2514. **
  2515. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  2516. ** ^If the option is unknown or SQLite is unable to set the option
  2517. ** then this routine returns a non-zero [error code].
  2518. */
  2519. SQLITE_API int sqlite3_config(int, ...);
  2520. /*
  2521. ** CAPI3REF: Configure database connections
  2522. ** METHOD: sqlite3
  2523. **
  2524. ** The sqlite3_db_config() interface is used to make configuration
  2525. ** changes to a [database connection]. The interface is similar to
  2526. ** [sqlite3_config()] except that the changes apply to a single
  2527. ** [database connection] (specified in the first argument).
  2528. **
  2529. ** The second argument to sqlite3_db_config(D,V,...) is the
  2530. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  2531. ** that indicates what aspect of the [database connection] is being configured.
  2532. ** Subsequent arguments vary depending on the configuration verb.
  2533. **
  2534. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  2535. ** the call is considered successful.
  2536. */
  2537. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  2538. /*
  2539. ** CAPI3REF: Memory Allocation Routines
  2540. **
  2541. ** An instance of this object defines the interface between SQLite
  2542. ** and low-level memory allocation routines.
  2543. **
  2544. ** This object is used in only one place in the SQLite interface.
  2545. ** A pointer to an instance of this object is the argument to
  2546. ** [sqlite3_config()] when the configuration option is
  2547. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  2548. ** By creating an instance of this object
  2549. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  2550. ** during configuration, an application can specify an alternative
  2551. ** memory allocation subsystem for SQLite to use for all of its
  2552. ** dynamic memory needs.
  2553. **
  2554. ** Note that SQLite comes with several [built-in memory allocators]
  2555. ** that are perfectly adequate for the overwhelming majority of applications
  2556. ** and that this object is only useful to a tiny minority of applications
  2557. ** with specialized memory allocation requirements. This object is
  2558. ** also used during testing of SQLite in order to specify an alternative
  2559. ** memory allocator that simulates memory out-of-memory conditions in
  2560. ** order to verify that SQLite recovers gracefully from such
  2561. ** conditions.
  2562. **
  2563. ** The xMalloc, xRealloc, and xFree methods must work like the
  2564. ** malloc(), realloc() and free() functions from the standard C library.
  2565. ** ^SQLite guarantees that the second argument to
  2566. ** xRealloc is always a value returned by a prior call to xRoundup.
  2567. **
  2568. ** xSize should return the allocated size of a memory allocation
  2569. ** previously obtained from xMalloc or xRealloc. The allocated size
  2570. ** is always at least as big as the requested size but may be larger.
  2571. **
  2572. ** The xRoundup method returns what would be the allocated size of
  2573. ** a memory allocation given a particular requested size. Most memory
  2574. ** allocators round up memory allocations at least to the next multiple
  2575. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  2576. ** Every memory allocation request coming in through [sqlite3_malloc()]
  2577. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  2578. ** that causes the corresponding memory allocation to fail.
  2579. **
  2580. ** The xInit method initializes the memory allocator. For example,
  2581. ** it might allocate any require mutexes or initialize internal data
  2582. ** structures. The xShutdown method is invoked (indirectly) by
  2583. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  2584. ** by xInit. The pAppData pointer is used as the only parameter to
  2585. ** xInit and xShutdown.
  2586. **
  2587. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  2588. ** the xInit method, so the xInit method need not be threadsafe. The
  2589. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  2590. ** not need to be threadsafe either. For all other methods, SQLite
  2591. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  2592. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  2593. ** it is by default) and so the methods are automatically serialized.
  2594. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  2595. ** methods must be threadsafe or else make their own arrangements for
  2596. ** serialization.
  2597. **
  2598. ** SQLite will never invoke xInit() more than once without an intervening
  2599. ** call to xShutdown().
  2600. */
  2601. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  2602. struct sqlite3_mem_methods {
  2603. void *(*xMalloc)(int); /* Memory allocation function */
  2604. void (*xFree)(void*); /* Free a prior allocation */
  2605. void *(*xRealloc)(void*,int); /* Resize an allocation */
  2606. int (*xSize)(void*); /* Return the size of an allocation */
  2607. int (*xRoundup)(int); /* Round up request size to allocation size */
  2608. int (*xInit)(void*); /* Initialize the memory allocator */
  2609. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  2610. void *pAppData; /* Argument to xInit() and xShutdown() */
  2611. };
  2612. /*
  2613. ** CAPI3REF: Configuration Options
  2614. ** KEYWORDS: {configuration option}
  2615. **
  2616. ** These constants are the available integer configuration options that
  2617. ** can be passed as the first argument to the [sqlite3_config()] interface.
  2618. **
  2619. ** New configuration options may be added in future releases of SQLite.
  2620. ** Existing configuration options might be discontinued. Applications
  2621. ** should check the return code from [sqlite3_config()] to make sure that
  2622. ** the call worked. The [sqlite3_config()] interface will return a
  2623. ** non-zero [error code] if a discontinued or unsupported configuration option
  2624. ** is invoked.
  2625. **
  2626. ** <dl>
  2627. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  2628. ** <dd>There are no arguments to this option. ^This option sets the
  2629. ** [threading mode] to Single-thread. In other words, it disables
  2630. ** all mutexing and puts SQLite into a mode where it can only be used
  2631. ** by a single thread. ^If SQLite is compiled with
  2632. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2633. ** it is not possible to change the [threading mode] from its default
  2634. ** value of Single-thread and so [sqlite3_config()] will return
  2635. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  2636. ** configuration option.</dd>
  2637. **
  2638. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  2639. ** <dd>There are no arguments to this option. ^This option sets the
  2640. ** [threading mode] to Multi-thread. In other words, it disables
  2641. ** mutexing on [database connection] and [prepared statement] objects.
  2642. ** The application is responsible for serializing access to
  2643. ** [database connections] and [prepared statements]. But other mutexes
  2644. ** are enabled so that SQLite will be safe to use in a multi-threaded
  2645. ** environment as long as no two threads attempt to use the same
  2646. ** [database connection] at the same time. ^If SQLite is compiled with
  2647. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2648. ** it is not possible to set the Multi-thread [threading mode] and
  2649. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2650. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  2651. **
  2652. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  2653. ** <dd>There are no arguments to this option. ^This option sets the
  2654. ** [threading mode] to Serialized. In other words, this option enables
  2655. ** all mutexes including the recursive
  2656. ** mutexes on [database connection] and [prepared statement] objects.
  2657. ** In this mode (which is the default when SQLite is compiled with
  2658. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  2659. ** to [database connections] and [prepared statements] so that the
  2660. ** application is free to use the same [database connection] or the
  2661. ** same [prepared statement] in different threads at the same time.
  2662. ** ^If SQLite is compiled with
  2663. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2664. ** it is not possible to set the Serialized [threading mode] and
  2665. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2666. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  2667. **
  2668. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  2669. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  2670. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  2671. ** The argument specifies
  2672. ** alternative low-level memory allocation routines to be used in place of
  2673. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  2674. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  2675. ** before the [sqlite3_config()] call returns.</dd>
  2676. **
  2677. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  2678. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  2679. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  2680. ** The [sqlite3_mem_methods]
  2681. ** structure is filled with the currently defined memory allocation routines.)^
  2682. ** This option can be used to overload the default memory allocation
  2683. ** routines with a wrapper that simulations memory allocation failure or
  2684. ** tracks memory usage, for example. </dd>
  2685. **
  2686. ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
  2687. ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
  2688. ** type int, interpreted as a boolean, which if true provides a hint to
  2689. ** SQLite that it should avoid large memory allocations if possible.
  2690. ** SQLite will run faster if it is free to make large memory allocations,
  2691. ** but some application might prefer to run slower in exchange for
  2692. ** guarantees about memory fragmentation that are possible if large
  2693. ** allocations are avoided. This hint is normally off.
  2694. ** </dd>
  2695. **
  2696. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  2697. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  2698. ** interpreted as a boolean, which enables or disables the collection of
  2699. ** memory allocation statistics. ^(When memory allocation statistics are
  2700. ** disabled, the following SQLite interfaces become non-operational:
  2701. ** <ul>
  2702. ** <li> [sqlite3_memory_used()]
  2703. ** <li> [sqlite3_memory_highwater()]
  2704. ** <li> [sqlite3_soft_heap_limit64()]
  2705. ** <li> [sqlite3_status64()]
  2706. ** </ul>)^
  2707. ** ^Memory allocation statistics are enabled by default unless SQLite is
  2708. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  2709. ** allocation statistics are disabled by default.
  2710. ** </dd>
  2711. **
  2712. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  2713. ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
  2714. ** </dd>
  2715. **
  2716. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  2717. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  2718. ** that SQLite can use for the database page cache with the default page
  2719. ** cache implementation.
  2720. ** This configuration option is a no-op if an application-define page
  2721. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  2722. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  2723. ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  2724. ** and the number of cache lines (N).
  2725. ** The sz argument should be the size of the largest database page
  2726. ** (a power of two between 512 and 65536) plus some extra bytes for each
  2727. ** page header. ^The number of extra bytes needed by the page header
  2728. ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  2729. ** ^It is harmless, apart from the wasted memory,
  2730. ** for the sz parameter to be larger than necessary. The pMem
  2731. ** argument must be either a NULL pointer or a pointer to an 8-byte
  2732. ** aligned block of memory of at least sz*N bytes, otherwise
  2733. ** subsequent behavior is undefined.
  2734. ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  2735. ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  2736. ** a page cache line is larger than sz bytes or if all of the pMem buffer
  2737. ** is exhausted.
  2738. ** ^If pMem is NULL and N is non-zero, then each database connection
  2739. ** does an initial bulk allocation for page cache memory
  2740. ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  2741. ** of -1024*N bytes if N is negative, . ^If additional
  2742. ** page cache memory is needed beyond what is provided by the initial
  2743. ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  2744. ** additional cache line. </dd>
  2745. **
  2746. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  2747. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  2748. ** that SQLite will use for all of its dynamic memory allocation needs
  2749. ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
  2750. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  2751. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  2752. ** [SQLITE_ERROR] if invoked otherwise.
  2753. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  2754. ** An 8-byte aligned pointer to the memory,
  2755. ** the number of bytes in the memory buffer, and the minimum allocation size.
  2756. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  2757. ** to using its default memory allocator (the system malloc() implementation),
  2758. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  2759. ** memory pointer is not NULL then the alternative memory
  2760. ** allocator is engaged to handle all of SQLites memory allocation needs.
  2761. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  2762. ** boundary or subsequent behavior of SQLite will be undefined.
  2763. ** The minimum allocation size is capped at 2**12. Reasonable values
  2764. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  2765. **
  2766. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  2767. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  2768. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  2769. ** The argument specifies alternative low-level mutex routines to be used
  2770. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  2771. ** the content of the [sqlite3_mutex_methods] structure before the call to
  2772. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  2773. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2774. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2775. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  2776. ** return [SQLITE_ERROR].</dd>
  2777. **
  2778. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  2779. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  2780. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  2781. ** [sqlite3_mutex_methods]
  2782. ** structure is filled with the currently defined mutex routines.)^
  2783. ** This option can be used to overload the default mutex allocation
  2784. ** routines with a wrapper used to track mutex usage for performance
  2785. ** profiling or testing, for example. ^If SQLite is compiled with
  2786. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2787. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2788. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  2789. ** return [SQLITE_ERROR].</dd>
  2790. **
  2791. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  2792. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  2793. ** the default size of lookaside memory on each [database connection].
  2794. ** The first argument is the
  2795. ** size of each lookaside buffer slot and the second is the number of
  2796. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  2797. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  2798. ** option to [sqlite3_db_config()] can be used to change the lookaside
  2799. ** configuration on individual connections.)^ </dd>
  2800. **
  2801. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  2802. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  2803. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  2804. ** the interface to a custom page cache implementation.)^
  2805. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  2806. **
  2807. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  2808. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  2809. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  2810. ** the current page cache implementation into that object.)^ </dd>
  2811. **
  2812. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  2813. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  2814. ** global [error log].
  2815. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  2816. ** function with a call signature of void(*)(void*,int,const char*),
  2817. ** and a pointer to void. ^If the function pointer is not NULL, it is
  2818. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  2819. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  2820. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  2821. ** passed through as the first parameter to the application-defined logger
  2822. ** function whenever that function is invoked. ^The second parameter to
  2823. ** the logger function is a copy of the first parameter to the corresponding
  2824. ** [sqlite3_log()] call and is intended to be a [result code] or an
  2825. ** [extended result code]. ^The third parameter passed to the logger is
  2826. ** log message after formatting via [sqlite3_snprintf()].
  2827. ** The SQLite logging interface is not reentrant; the logger function
  2828. ** supplied by the application must not invoke any SQLite interface.
  2829. ** In a multi-threaded application, the application-defined logger
  2830. ** function must be threadsafe. </dd>
  2831. **
  2832. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2833. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  2834. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  2835. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  2836. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  2837. ** [sqlite3_open16()] or
  2838. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2839. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2840. ** connection is opened. ^If it is globally disabled, filenames are
  2841. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2842. ** database connection is opened. ^(By default, URI handling is globally
  2843. ** disabled. The default value may be changed by compiling with the
  2844. ** [SQLITE_USE_URI] symbol defined.)^
  2845. **
  2846. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2847. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  2848. ** argument which is interpreted as a boolean in order to enable or disable
  2849. ** the use of covering indices for full table scans in the query optimizer.
  2850. ** ^The default setting is determined
  2851. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2852. ** if that compile-time option is omitted.
  2853. ** The ability to disable the use of covering indices for full table scans
  2854. ** is because some incorrectly coded legacy applications might malfunction
  2855. ** when the optimization is enabled. Providing the ability to
  2856. ** disable the optimization allows the older, buggy application code to work
  2857. ** without change even with newer versions of SQLite.
  2858. **
  2859. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2860. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2861. ** <dd> These options are obsolete and should not be used by new code.
  2862. ** They are retained for backwards compatibility but are now no-ops.
  2863. ** </dd>
  2864. **
  2865. ** [[SQLITE_CONFIG_SQLLOG]]
  2866. ** <dt>SQLITE_CONFIG_SQLLOG
  2867. ** <dd>This option is only available if sqlite is compiled with the
  2868. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2869. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2870. ** The second should be of type (void*). The callback is invoked by the library
  2871. ** in three separate circumstances, identified by the value passed as the
  2872. ** fourth parameter. If the fourth parameter is 0, then the database connection
  2873. ** passed as the second argument has just been opened. The third argument
  2874. ** points to a buffer containing the name of the main database file. If the
  2875. ** fourth parameter is 1, then the SQL statement that the third parameter
  2876. ** points to has just been executed. Or, if the fourth parameter is 2, then
  2877. ** the connection being passed as the second parameter is being closed. The
  2878. ** third parameter is passed NULL In this case. An example of using this
  2879. ** configuration option can be seen in the "test_sqllog.c" source file in
  2880. ** the canonical SQLite source tree.</dd>
  2881. **
  2882. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2883. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2884. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2885. ** that are the default mmap size limit (the default setting for
  2886. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2887. ** ^The default setting can be overridden by each database connection using
  2888. ** either the [PRAGMA mmap_size] command, or by using the
  2889. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  2890. ** will be silently truncated if necessary so that it does not exceed the
  2891. ** compile-time maximum mmap size set by the
  2892. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  2893. ** ^If either argument to this option is negative, then that argument is
  2894. ** changed to its compile-time default.
  2895. **
  2896. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  2897. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  2898. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  2899. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  2900. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  2901. ** that specifies the maximum size of the created heap.
  2902. **
  2903. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  2904. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  2905. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  2906. ** is a pointer to an integer and writes into that integer the number of extra
  2907. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  2908. ** The amount of extra space required can change depending on the compiler,
  2909. ** target platform, and SQLite version.
  2910. **
  2911. ** [[SQLITE_CONFIG_PMASZ]]
  2912. ** <dt>SQLITE_CONFIG_PMASZ
  2913. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  2914. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  2915. ** sorter to that integer. The default minimum PMA Size is set by the
  2916. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  2917. ** to help with sort operations when multithreaded sorting
  2918. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  2919. ** to be sorted exceeds the page size times the minimum of the
  2920. ** [PRAGMA cache_size] setting and this value.
  2921. **
  2922. ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  2923. ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  2924. ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  2925. ** becomes the [statement journal] spill-to-disk threshold.
  2926. ** [Statement journals] are held in memory until their size (in bytes)
  2927. ** exceeds this threshold, at which point they are written to disk.
  2928. ** Or if the threshold is -1, statement journals are always held
  2929. ** exclusively in memory.
  2930. ** Since many statement journals never become large, setting the spill
  2931. ** threshold to a value such as 64KiB can greatly reduce the amount of
  2932. ** I/O required to support statement rollback.
  2933. ** The default value for this setting is controlled by the
  2934. ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2935. **
  2936. ** [[SQLITE_CONFIG_SORTERREF_SIZE]]
  2937. ** <dt>SQLITE_CONFIG_SORTERREF_SIZE
  2938. ** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
  2939. ** of type (int) - the new value of the sorter-reference size threshold.
  2940. ** Usually, when SQLite uses an external sort to order records according
  2941. ** to an ORDER BY clause, all fields required by the caller are present in the
  2942. ** sorted records. However, if SQLite determines based on the declared type
  2943. ** of a table column that its values are likely to be very large - larger
  2944. ** than the configured sorter-reference size threshold - then a reference
  2945. ** is stored in each sorted record and the required column values loaded
  2946. ** from the database as records are returned in sorted order. The default
  2947. ** value for this option is to never use this optimization. Specifying a
  2948. ** negative value for this option restores the default behaviour.
  2949. ** This option is only available if SQLite is compiled with the
  2950. ** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
  2951. ** </dl>
  2952. */
  2953. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  2954. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  2955. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  2956. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  2957. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  2958. #define SQLITE_CONFIG_SCRATCH 6 /* No longer used */
  2959. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  2960. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  2961. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  2962. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  2963. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2964. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2965. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2966. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2967. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2968. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2969. #define SQLITE_CONFIG_URI 17 /* int */
  2970. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2971. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2972. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  2973. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  2974. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  2975. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  2976. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  2977. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  2978. #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
  2979. #define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
  2980. #define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */
  2981. /*
  2982. ** CAPI3REF: Database Connection Configuration Options
  2983. **
  2984. ** These constants are the available integer configuration options that
  2985. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2986. **
  2987. ** New configuration options may be added in future releases of SQLite.
  2988. ** Existing configuration options might be discontinued. Applications
  2989. ** should check the return code from [sqlite3_db_config()] to make sure that
  2990. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2991. ** non-zero [error code] if a discontinued or unsupported configuration option
  2992. ** is invoked.
  2993. **
  2994. ** <dl>
  2995. ** [[SQLITE_DBCONFIG_LOOKASIDE]]
  2996. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2997. ** <dd> ^This option takes three additional arguments that determine the
  2998. ** [lookaside memory allocator] configuration for the [database connection].
  2999. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  3000. ** pointer to a memory buffer to use for lookaside memory.
  3001. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  3002. ** may be NULL in which case SQLite will allocate the
  3003. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  3004. ** size of each lookaside buffer slot. ^The third argument is the number of
  3005. ** slots. The size of the buffer in the first argument must be greater than
  3006. ** or equal to the product of the second and third arguments. The buffer
  3007. ** must be aligned to an 8-byte boundary. ^If the second argument to
  3008. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  3009. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  3010. ** configuration for a database connection can only be changed when that
  3011. ** connection is not currently using lookaside memory, or in other words
  3012. ** when the "current value" returned by
  3013. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  3014. ** Any attempt to change the lookaside memory configuration when lookaside
  3015. ** memory is in use leaves the configuration unchanged and returns
  3016. ** [SQLITE_BUSY].)^</dd>
  3017. **
  3018. ** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
  3019. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  3020. ** <dd> ^This option is used to enable or disable the enforcement of
  3021. ** [foreign key constraints]. There should be two additional arguments.
  3022. ** The first argument is an integer which is 0 to disable FK enforcement,
  3023. ** positive to enable FK enforcement or negative to leave FK enforcement
  3024. ** unchanged. The second parameter is a pointer to an integer into which
  3025. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  3026. ** following this call. The second parameter may be a NULL pointer, in
  3027. ** which case the FK enforcement setting is not reported back. </dd>
  3028. **
  3029. ** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]
  3030. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  3031. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  3032. ** There should be two additional arguments.
  3033. ** The first argument is an integer which is 0 to disable triggers,
  3034. ** positive to enable triggers or negative to leave the setting unchanged.
  3035. ** The second parameter is a pointer to an integer into which
  3036. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  3037. ** following this call. The second parameter may be a NULL pointer, in
  3038. ** which case the trigger setting is not reported back. </dd>
  3039. **
  3040. ** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
  3041. ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  3042. ** <dd> ^This option is used to enable or disable the two-argument
  3043. ** version of the [fts3_tokenizer()] function which is part of the
  3044. ** [FTS3] full-text search engine extension.
  3045. ** There should be two additional arguments.
  3046. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  3047. ** positive to enable fts3_tokenizer() or negative to leave the setting
  3048. ** unchanged.
  3049. ** The second parameter is a pointer to an integer into which
  3050. ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  3051. ** following this call. The second parameter may be a NULL pointer, in
  3052. ** which case the new setting is not reported back. </dd>
  3053. **
  3054. ** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
  3055. ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  3056. ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  3057. ** interface independently of the [load_extension()] SQL function.
  3058. ** The [sqlite3_enable_load_extension()] API enables or disables both the
  3059. ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  3060. ** There should be two additional arguments.
  3061. ** When the first argument to this interface is 1, then only the C-API is
  3062. ** enabled and the SQL function remains disabled. If the first argument to
  3063. ** this interface is 0, then both the C-API and the SQL function are disabled.
  3064. ** If the first argument is -1, then no changes are made to state of either the
  3065. ** C-API or the SQL function.
  3066. ** The second parameter is a pointer to an integer into which
  3067. ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  3068. ** is disabled or enabled following this call. The second parameter may
  3069. ** be a NULL pointer, in which case the new setting is not reported back.
  3070. ** </dd>
  3071. **
  3072. ** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  3073. ** <dd> ^This option is used to change the name of the "main" database
  3074. ** schema. ^The sole argument is a pointer to a constant UTF8 string
  3075. ** which will become the new schema name in place of "main". ^SQLite
  3076. ** does not make a copy of the new main schema name string, so the application
  3077. ** must ensure that the argument passed into this DBCONFIG option is unchanged
  3078. ** until after the database connection closes.
  3079. ** </dd>
  3080. **
  3081. ** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
  3082. ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  3083. ** <dd> Usually, when a database in wal mode is closed or detached from a
  3084. ** database handle, SQLite checks if this will mean that there are now no
  3085. ** connections at all to the database. If so, it performs a checkpoint
  3086. ** operation before closing the connection. This option may be used to
  3087. ** override this behaviour. The first parameter passed to this operation
  3088. ** is an integer - positive to disable checkpoints-on-close, or zero (the
  3089. ** default) to enable them, and negative to leave the setting unchanged.
  3090. ** The second parameter is a pointer to an integer
  3091. ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  3092. ** have been disabled - 0 if they are not disabled, 1 if they are.
  3093. ** </dd>
  3094. **
  3095. ** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
  3096. ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
  3097. ** the [query planner stability guarantee] (QPSG). When the QPSG is active,
  3098. ** a single SQL query statement will always use the same algorithm regardless
  3099. ** of values of [bound parameters].)^ The QPSG disables some query optimizations
  3100. ** that look at the values of bound parameters, which can make some queries
  3101. ** slower. But the QPSG has the advantage of more predictable behavior. With
  3102. ** the QPSG active, SQLite will always use the same query plan in the field as
  3103. ** was used during testing in the lab.
  3104. ** The first argument to this setting is an integer which is 0 to disable
  3105. ** the QPSG, positive to enable QPSG, or negative to leave the setting
  3106. ** unchanged. The second parameter is a pointer to an integer into which
  3107. ** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
  3108. ** following this call.
  3109. ** </dd>
  3110. **
  3111. ** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
  3112. ** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
  3113. ** include output for any operations performed by trigger programs. This
  3114. ** option is used to set or clear (the default) a flag that governs this
  3115. ** behavior. The first parameter passed to this operation is an integer -
  3116. ** positive to enable output for trigger programs, or zero to disable it,
  3117. ** or negative to leave the setting unchanged.
  3118. ** The second parameter is a pointer to an integer into which is written
  3119. ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
  3120. ** it is not disabled, 1 if it is.
  3121. ** </dd>
  3122. **
  3123. ** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
  3124. ** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
  3125. ** [VACUUM] in order to reset a database back to an empty database
  3126. ** with no schema and no content. The following process works even for
  3127. ** a badly corrupted database file:
  3128. ** <ol>
  3129. ** <li> If the database connection is newly opened, make sure it has read the
  3130. ** database schema by preparing then discarding some query against the
  3131. ** database, or calling sqlite3_table_column_metadata(), ignoring any
  3132. ** errors. This step is only necessary if the application desires to keep
  3133. ** the database in WAL mode after the reset if it was in WAL mode before
  3134. ** the reset.
  3135. ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
  3136. ** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
  3137. ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
  3138. ** </ol>
  3139. ** Because resetting a database is destructive and irreversible, the
  3140. ** process requires the use of this obscure API and multiple steps to help
  3141. ** ensure that it does not happen by accident.
  3142. **
  3143. ** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
  3144. ** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
  3145. ** "defensive" flag for a database connection. When the defensive
  3146. ** flag is enabled, language features that allow ordinary SQL to
  3147. ** deliberately corrupt the database file are disabled. The disabled
  3148. ** features include but are not limited to the following:
  3149. ** <ul>
  3150. ** <li> The [PRAGMA writable_schema=ON] statement.
  3151. ** <li> Writes to the [sqlite_dbpage] virtual table.
  3152. ** <li> Direct writes to [shadow tables].
  3153. ** </ul>
  3154. ** </dd>
  3155. ** </dl>
  3156. */
  3157. #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
  3158. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  3159. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  3160. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  3161. #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  3162. #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  3163. #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
  3164. #define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
  3165. #define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */
  3166. #define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */
  3167. #define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */
  3168. #define SQLITE_DBCONFIG_MAX 1010 /* Largest DBCONFIG */
  3169. /*
  3170. ** CAPI3REF: Enable Or Disable Extended Result Codes
  3171. ** METHOD: sqlite3
  3172. **
  3173. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  3174. ** [extended result codes] feature of SQLite. ^The extended result
  3175. ** codes are disabled by default for historical compatibility.
  3176. */
  3177. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  3178. /*
  3179. ** CAPI3REF: Last Insert Rowid
  3180. ** METHOD: sqlite3
  3181. **
  3182. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  3183. ** has a unique 64-bit signed
  3184. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  3185. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  3186. ** names are not also used by explicitly declared columns. ^If
  3187. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  3188. ** is another alias for the rowid.
  3189. **
  3190. ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
  3191. ** the most recent successful [INSERT] into a rowid table or [virtual table]
  3192. ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
  3193. ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
  3194. ** on the database connection D, then sqlite3_last_insert_rowid(D) returns
  3195. ** zero.
  3196. **
  3197. ** As well as being set automatically as rows are inserted into database
  3198. ** tables, the value returned by this function may be set explicitly by
  3199. ** [sqlite3_set_last_insert_rowid()]
  3200. **
  3201. ** Some virtual table implementations may INSERT rows into rowid tables as
  3202. ** part of committing a transaction (e.g. to flush data accumulated in memory
  3203. ** to disk). In this case subsequent calls to this function return the rowid
  3204. ** associated with these internal INSERT operations, which leads to
  3205. ** unintuitive results. Virtual table implementations that do write to rowid
  3206. ** tables in this way can avoid this problem by restoring the original
  3207. ** rowid value using [sqlite3_set_last_insert_rowid()] before returning
  3208. ** control to the user.
  3209. **
  3210. ** ^(If an [INSERT] occurs within a trigger then this routine will
  3211. ** return the [rowid] of the inserted row as long as the trigger is
  3212. ** running. Once the trigger program ends, the value returned
  3213. ** by this routine reverts to what it was before the trigger was fired.)^
  3214. **
  3215. ** ^An [INSERT] that fails due to a constraint violation is not a
  3216. ** successful [INSERT] and does not change the value returned by this
  3217. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  3218. ** and INSERT OR ABORT make no changes to the return value of this
  3219. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  3220. ** encounters a constraint violation, it does not fail. The
  3221. ** INSERT continues to completion after deleting rows that caused
  3222. ** the constraint problem so INSERT OR REPLACE will always change
  3223. ** the return value of this interface.)^
  3224. **
  3225. ** ^For the purposes of this routine, an [INSERT] is considered to
  3226. ** be successful even if it is subsequently rolled back.
  3227. **
  3228. ** This function is accessible to SQL statements via the
  3229. ** [last_insert_rowid() SQL function].
  3230. **
  3231. ** If a separate thread performs a new [INSERT] on the same
  3232. ** database connection while the [sqlite3_last_insert_rowid()]
  3233. ** function is running and thus changes the last insert [rowid],
  3234. ** then the value returned by [sqlite3_last_insert_rowid()] is
  3235. ** unpredictable and might not equal either the old or the new
  3236. ** last insert [rowid].
  3237. */
  3238. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  3239. /*
  3240. ** CAPI3REF: Set the Last Insert Rowid value.
  3241. ** METHOD: sqlite3
  3242. **
  3243. ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
  3244. ** set the value returned by calling sqlite3_last_insert_rowid(D) to R
  3245. ** without inserting a row into the database.
  3246. */
  3247. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
  3248. /*
  3249. ** CAPI3REF: Count The Number Of Rows Modified
  3250. ** METHOD: sqlite3
  3251. **
  3252. ** ^This function returns the number of rows modified, inserted or
  3253. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  3254. ** statement on the database connection specified by the only parameter.
  3255. ** ^Executing any other type of SQL statement does not modify the value
  3256. ** returned by this function.
  3257. **
  3258. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  3259. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  3260. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  3261. **
  3262. ** Changes to a view that are intercepted by
  3263. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  3264. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  3265. ** DELETE statement run on a view is always zero. Only changes made to real
  3266. ** tables are counted.
  3267. **
  3268. ** Things are more complicated if the sqlite3_changes() function is
  3269. ** executed while a trigger program is running. This may happen if the
  3270. ** program uses the [changes() SQL function], or if some other callback
  3271. ** function invokes sqlite3_changes() directly. Essentially:
  3272. **
  3273. ** <ul>
  3274. ** <li> ^(Before entering a trigger program the value returned by
  3275. ** sqlite3_changes() function is saved. After the trigger program
  3276. ** has finished, the original value is restored.)^
  3277. **
  3278. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  3279. ** statement sets the value returned by sqlite3_changes()
  3280. ** upon completion as normal. Of course, this value will not include
  3281. ** any changes performed by sub-triggers, as the sqlite3_changes()
  3282. ** value will be saved and restored after each sub-trigger has run.)^
  3283. ** </ul>
  3284. **
  3285. ** ^This means that if the changes() SQL function (or similar) is used
  3286. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  3287. ** returns the value as set when the calling statement began executing.
  3288. ** ^If it is used by the second or subsequent such statement within a trigger
  3289. ** program, the value returned reflects the number of rows modified by the
  3290. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  3291. **
  3292. ** If a separate thread makes changes on the same database connection
  3293. ** while [sqlite3_changes()] is running then the value returned
  3294. ** is unpredictable and not meaningful.
  3295. **
  3296. ** See also:
  3297. ** <ul>
  3298. ** <li> the [sqlite3_total_changes()] interface
  3299. ** <li> the [count_changes pragma]
  3300. ** <li> the [changes() SQL function]
  3301. ** <li> the [data_version pragma]
  3302. ** </ul>
  3303. */
  3304. SQLITE_API int sqlite3_changes(sqlite3*);
  3305. /*
  3306. ** CAPI3REF: Total Number Of Rows Modified
  3307. ** METHOD: sqlite3
  3308. **
  3309. ** ^This function returns the total number of rows inserted, modified or
  3310. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  3311. ** since the database connection was opened, including those executed as
  3312. ** part of trigger programs. ^Executing any other type of SQL statement
  3313. ** does not affect the value returned by sqlite3_total_changes().
  3314. **
  3315. ** ^Changes made as part of [foreign key actions] are included in the
  3316. ** count, but those made as part of REPLACE constraint resolution are
  3317. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  3318. ** are not counted.
  3319. **
  3320. ** This the [sqlite3_total_changes(D)] interface only reports the number
  3321. ** of rows that changed due to SQL statement run against database
  3322. ** connection D. Any changes by other database connections are ignored.
  3323. ** To detect changes against a database file from other database
  3324. ** connections use the [PRAGMA data_version] command or the
  3325. ** [SQLITE_FCNTL_DATA_VERSION] [file control].
  3326. **
  3327. ** If a separate thread makes changes on the same database connection
  3328. ** while [sqlite3_total_changes()] is running then the value
  3329. ** returned is unpredictable and not meaningful.
  3330. **
  3331. ** See also:
  3332. ** <ul>
  3333. ** <li> the [sqlite3_changes()] interface
  3334. ** <li> the [count_changes pragma]
  3335. ** <li> the [changes() SQL function]
  3336. ** <li> the [data_version pragma]
  3337. ** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]
  3338. ** </ul>
  3339. */
  3340. SQLITE_API int sqlite3_total_changes(sqlite3*);
  3341. /*
  3342. ** CAPI3REF: Interrupt A Long-Running Query
  3343. ** METHOD: sqlite3
  3344. **
  3345. ** ^This function causes any pending database operation to abort and
  3346. ** return at its earliest opportunity. This routine is typically
  3347. ** called in response to a user action such as pressing "Cancel"
  3348. ** or Ctrl-C where the user wants a long query operation to halt
  3349. ** immediately.
  3350. **
  3351. ** ^It is safe to call this routine from a thread different from the
  3352. ** thread that is currently running the database operation. But it
  3353. ** is not safe to call this routine with a [database connection] that
  3354. ** is closed or might close before sqlite3_interrupt() returns.
  3355. **
  3356. ** ^If an SQL operation is very nearly finished at the time when
  3357. ** sqlite3_interrupt() is called, then it might not have an opportunity
  3358. ** to be interrupted and might continue to completion.
  3359. **
  3360. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  3361. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  3362. ** that is inside an explicit transaction, then the entire transaction
  3363. ** will be rolled back automatically.
  3364. **
  3365. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  3366. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  3367. ** that are started after the sqlite3_interrupt() call and before the
  3368. ** running statements reaches zero are interrupted as if they had been
  3369. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  3370. ** that are started after the running statement count reaches zero are
  3371. ** not effected by the sqlite3_interrupt().
  3372. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  3373. ** SQL statements is a no-op and has no effect on SQL statements
  3374. ** that are started after the sqlite3_interrupt() call returns.
  3375. */
  3376. SQLITE_API void sqlite3_interrupt(sqlite3*);
  3377. /*
  3378. ** CAPI3REF: Determine If An SQL Statement Is Complete
  3379. **
  3380. ** These routines are useful during command-line input to determine if the
  3381. ** currently entered text seems to form a complete SQL statement or
  3382. ** if additional input is needed before sending the text into
  3383. ** SQLite for parsing. ^These routines return 1 if the input string
  3384. ** appears to be a complete SQL statement. ^A statement is judged to be
  3385. ** complete if it ends with a semicolon token and is not a prefix of a
  3386. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  3387. ** string literals or quoted identifier names or comments are not
  3388. ** independent tokens (they are part of the token in which they are
  3389. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  3390. ** and comments that follow the final semicolon are ignored.
  3391. **
  3392. ** ^These routines return 0 if the statement is incomplete. ^If a
  3393. ** memory allocation fails, then SQLITE_NOMEM is returned.
  3394. **
  3395. ** ^These routines do not parse the SQL statements thus
  3396. ** will not detect syntactically incorrect SQL.
  3397. **
  3398. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  3399. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  3400. ** automatically by sqlite3_complete16(). If that initialization fails,
  3401. ** then the return value from sqlite3_complete16() will be non-zero
  3402. ** regardless of whether or not the input SQL is complete.)^
  3403. **
  3404. ** The input to [sqlite3_complete()] must be a zero-terminated
  3405. ** UTF-8 string.
  3406. **
  3407. ** The input to [sqlite3_complete16()] must be a zero-terminated
  3408. ** UTF-16 string in native byte order.
  3409. */
  3410. SQLITE_API int sqlite3_complete(const char *sql);
  3411. SQLITE_API int sqlite3_complete16(const void *sql);
  3412. /*
  3413. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  3414. ** KEYWORDS: {busy-handler callback} {busy handler}
  3415. ** METHOD: sqlite3
  3416. **
  3417. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  3418. ** that might be invoked with argument P whenever
  3419. ** an attempt is made to access a database table associated with
  3420. ** [database connection] D when another thread
  3421. ** or process has the table locked.
  3422. ** The sqlite3_busy_handler() interface is used to implement
  3423. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  3424. **
  3425. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  3426. ** is returned immediately upon encountering the lock. ^If the busy callback
  3427. ** is not NULL, then the callback might be invoked with two arguments.
  3428. **
  3429. ** ^The first argument to the busy handler is a copy of the void* pointer which
  3430. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  3431. ** the busy handler callback is the number of times that the busy handler has
  3432. ** been invoked previously for the same locking event. ^If the
  3433. ** busy callback returns 0, then no additional attempts are made to
  3434. ** access the database and [SQLITE_BUSY] is returned
  3435. ** to the application.
  3436. ** ^If the callback returns non-zero, then another attempt
  3437. ** is made to access the database and the cycle repeats.
  3438. **
  3439. ** The presence of a busy handler does not guarantee that it will be invoked
  3440. ** when there is lock contention. ^If SQLite determines that invoking the busy
  3441. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  3442. ** to the application instead of invoking the
  3443. ** busy handler.
  3444. ** Consider a scenario where one process is holding a read lock that
  3445. ** it is trying to promote to a reserved lock and
  3446. ** a second process is holding a reserved lock that it is trying
  3447. ** to promote to an exclusive lock. The first process cannot proceed
  3448. ** because it is blocked by the second and the second process cannot
  3449. ** proceed because it is blocked by the first. If both processes
  3450. ** invoke the busy handlers, neither will make any progress. Therefore,
  3451. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  3452. ** will induce the first process to release its read lock and allow
  3453. ** the second process to proceed.
  3454. **
  3455. ** ^The default busy callback is NULL.
  3456. **
  3457. ** ^(There can only be a single busy handler defined for each
  3458. ** [database connection]. Setting a new busy handler clears any
  3459. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  3460. ** or evaluating [PRAGMA busy_timeout=N] will change the
  3461. ** busy handler and thus clear any previously set busy handler.
  3462. **
  3463. ** The busy callback should not take any actions which modify the
  3464. ** database connection that invoked the busy handler. In other words,
  3465. ** the busy handler is not reentrant. Any such actions
  3466. ** result in undefined behavior.
  3467. **
  3468. ** A busy handler must not close the database connection
  3469. ** or [prepared statement] that invoked the busy handler.
  3470. */
  3471. SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
  3472. /*
  3473. ** CAPI3REF: Set A Busy Timeout
  3474. ** METHOD: sqlite3
  3475. **
  3476. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  3477. ** for a specified amount of time when a table is locked. ^The handler
  3478. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  3479. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  3480. ** the handler returns 0 which causes [sqlite3_step()] to return
  3481. ** [SQLITE_BUSY].
  3482. **
  3483. ** ^Calling this routine with an argument less than or equal to zero
  3484. ** turns off all busy handlers.
  3485. **
  3486. ** ^(There can only be a single busy handler for a particular
  3487. ** [database connection] at any given moment. If another busy handler
  3488. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  3489. ** this routine, that other busy handler is cleared.)^
  3490. **
  3491. ** See also: [PRAGMA busy_timeout]
  3492. */
  3493. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  3494. /*
  3495. ** CAPI3REF: Convenience Routines For Running Queries
  3496. ** METHOD: sqlite3
  3497. **
  3498. ** This is a legacy interface that is preserved for backwards compatibility.
  3499. ** Use of this interface is not recommended.
  3500. **
  3501. ** Definition: A <b>result table</b> is memory data structure created by the
  3502. ** [sqlite3_get_table()] interface. A result table records the
  3503. ** complete query results from one or more queries.
  3504. **
  3505. ** The table conceptually has a number of rows and columns. But
  3506. ** these numbers are not part of the result table itself. These
  3507. ** numbers are obtained separately. Let N be the number of rows
  3508. ** and M be the number of columns.
  3509. **
  3510. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  3511. ** There are (N+1)*M elements in the array. The first M pointers point
  3512. ** to zero-terminated strings that contain the names of the columns.
  3513. ** The remaining entries all point to query results. NULL values result
  3514. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  3515. ** string representation as returned by [sqlite3_column_text()].
  3516. **
  3517. ** A result table might consist of one or more memory allocations.
  3518. ** It is not safe to pass a result table directly to [sqlite3_free()].
  3519. ** A result table should be deallocated using [sqlite3_free_table()].
  3520. **
  3521. ** ^(As an example of the result table format, suppose a query result
  3522. ** is as follows:
  3523. **
  3524. ** <blockquote><pre>
  3525. ** Name | Age
  3526. ** -----------------------
  3527. ** Alice | 43
  3528. ** Bob | 28
  3529. ** Cindy | 21
  3530. ** </pre></blockquote>
  3531. **
  3532. ** There are two column (M==2) and three rows (N==3). Thus the
  3533. ** result table has 8 entries. Suppose the result table is stored
  3534. ** in an array names azResult. Then azResult holds this content:
  3535. **
  3536. ** <blockquote><pre>
  3537. ** azResult&#91;0] = "Name";
  3538. ** azResult&#91;1] = "Age";
  3539. ** azResult&#91;2] = "Alice";
  3540. ** azResult&#91;3] = "43";
  3541. ** azResult&#91;4] = "Bob";
  3542. ** azResult&#91;5] = "28";
  3543. ** azResult&#91;6] = "Cindy";
  3544. ** azResult&#91;7] = "21";
  3545. ** </pre></blockquote>)^
  3546. **
  3547. ** ^The sqlite3_get_table() function evaluates one or more
  3548. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  3549. ** string of its 2nd parameter and returns a result table to the
  3550. ** pointer given in its 3rd parameter.
  3551. **
  3552. ** After the application has finished with the result from sqlite3_get_table(),
  3553. ** it must pass the result table pointer to sqlite3_free_table() in order to
  3554. ** release the memory that was malloced. Because of the way the
  3555. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  3556. ** function must not try to call [sqlite3_free()] directly. Only
  3557. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  3558. **
  3559. ** The sqlite3_get_table() interface is implemented as a wrapper around
  3560. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  3561. ** to any internal data structures of SQLite. It uses only the public
  3562. ** interface defined here. As a consequence, errors that occur in the
  3563. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  3564. ** reflected in subsequent calls to [sqlite3_errcode()] or
  3565. ** [sqlite3_errmsg()].
  3566. */
  3567. SQLITE_API int sqlite3_get_table(
  3568. sqlite3 *db, /* An open database */
  3569. const char *zSql, /* SQL to be evaluated */
  3570. char ***pazResult, /* Results of the query */
  3571. int *pnRow, /* Number of result rows written here */
  3572. int *pnColumn, /* Number of result columns written here */
  3573. char **pzErrmsg /* Error msg written here */
  3574. );
  3575. SQLITE_API void sqlite3_free_table(char **result);
  3576. /*
  3577. ** CAPI3REF: Formatted String Printing Functions
  3578. **
  3579. ** These routines are work-alikes of the "printf()" family of functions
  3580. ** from the standard C library.
  3581. ** These routines understand most of the common formatting options from
  3582. ** the standard library printf()
  3583. ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
  3584. ** See the [built-in printf()] documentation for details.
  3585. **
  3586. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  3587. ** results into memory obtained from [sqlite3_malloc64()].
  3588. ** The strings returned by these two routines should be
  3589. ** released by [sqlite3_free()]. ^Both routines return a
  3590. ** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
  3591. ** memory to hold the resulting string.
  3592. **
  3593. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  3594. ** the standard C library. The result is written into the
  3595. ** buffer supplied as the second parameter whose size is given by
  3596. ** the first parameter. Note that the order of the
  3597. ** first two parameters is reversed from snprintf().)^ This is an
  3598. ** historical accident that cannot be fixed without breaking
  3599. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  3600. ** returns a pointer to its buffer instead of the number of
  3601. ** characters actually written into the buffer.)^ We admit that
  3602. ** the number of characters written would be a more useful return
  3603. ** value but we cannot change the implementation of sqlite3_snprintf()
  3604. ** now without breaking compatibility.
  3605. **
  3606. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  3607. ** guarantees that the buffer is always zero-terminated. ^The first
  3608. ** parameter "n" is the total size of the buffer, including space for
  3609. ** the zero terminator. So the longest string that can be completely
  3610. ** written will be n-1 characters.
  3611. **
  3612. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  3613. **
  3614. ** See also: [built-in printf()], [printf() SQL function]
  3615. */
  3616. SQLITE_API char *sqlite3_mprintf(const char*,...);
  3617. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  3618. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  3619. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  3620. /*
  3621. ** CAPI3REF: Memory Allocation Subsystem
  3622. **
  3623. ** The SQLite core uses these three routines for all of its own
  3624. ** internal memory allocation needs. "Core" in the previous sentence
  3625. ** does not include operating-system specific VFS implementation. The
  3626. ** Windows VFS uses native malloc() and free() for some operations.
  3627. **
  3628. ** ^The sqlite3_malloc() routine returns a pointer to a block
  3629. ** of memory at least N bytes in length, where N is the parameter.
  3630. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  3631. ** memory, it returns a NULL pointer. ^If the parameter N to
  3632. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  3633. ** a NULL pointer.
  3634. **
  3635. ** ^The sqlite3_malloc64(N) routine works just like
  3636. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  3637. ** of a signed 32-bit integer.
  3638. **
  3639. ** ^Calling sqlite3_free() with a pointer previously returned
  3640. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  3641. ** that it might be reused. ^The sqlite3_free() routine is
  3642. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  3643. ** to sqlite3_free() is harmless. After being freed, memory
  3644. ** should neither be read nor written. Even reading previously freed
  3645. ** memory might result in a segmentation fault or other severe error.
  3646. ** Memory corruption, a segmentation fault, or other severe error
  3647. ** might result if sqlite3_free() is called with a non-NULL pointer that
  3648. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  3649. **
  3650. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  3651. ** prior memory allocation X to be at least N bytes.
  3652. ** ^If the X parameter to sqlite3_realloc(X,N)
  3653. ** is a NULL pointer then its behavior is identical to calling
  3654. ** sqlite3_malloc(N).
  3655. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  3656. ** negative then the behavior is exactly the same as calling
  3657. ** sqlite3_free(X).
  3658. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  3659. ** of at least N bytes in size or NULL if insufficient memory is available.
  3660. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  3661. ** of the prior allocation are copied into the beginning of buffer returned
  3662. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  3663. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  3664. ** prior allocation is not freed.
  3665. **
  3666. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  3667. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  3668. ** of a 32-bit signed integer.
  3669. **
  3670. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  3671. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  3672. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  3673. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  3674. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  3675. ** sqlite3_msize(X) returns zero. If X points to something that is not
  3676. ** the beginning of memory allocation, or if it points to a formerly
  3677. ** valid memory allocation that has now been freed, then the behavior
  3678. ** of sqlite3_msize(X) is undefined and possibly harmful.
  3679. **
  3680. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  3681. ** sqlite3_malloc64(), and sqlite3_realloc64()
  3682. ** is always aligned to at least an 8 byte boundary, or to a
  3683. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  3684. ** option is used.
  3685. **
  3686. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  3687. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  3688. ** implementation of these routines to be omitted. That capability
  3689. ** is no longer provided. Only built-in memory allocators can be used.
  3690. **
  3691. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  3692. ** the system malloc() and free() directly when converting
  3693. ** filenames between the UTF-8 encoding used by SQLite
  3694. ** and whatever filename encoding is used by the particular Windows
  3695. ** installation. Memory allocation errors were detected, but
  3696. ** they were reported back as [SQLITE_CANTOPEN] or
  3697. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  3698. **
  3699. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  3700. ** must be either NULL or else pointers obtained from a prior
  3701. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  3702. ** not yet been released.
  3703. **
  3704. ** The application must not read or write any part of
  3705. ** a block of memory after it has been released using
  3706. ** [sqlite3_free()] or [sqlite3_realloc()].
  3707. */
  3708. SQLITE_API void *sqlite3_malloc(int);
  3709. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  3710. SQLITE_API void *sqlite3_realloc(void*, int);
  3711. SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  3712. SQLITE_API void sqlite3_free(void*);
  3713. SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  3714. /*
  3715. ** CAPI3REF: Memory Allocator Statistics
  3716. **
  3717. ** SQLite provides these two interfaces for reporting on the status
  3718. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  3719. ** routines, which form the built-in memory allocation subsystem.
  3720. **
  3721. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  3722. ** of memory currently outstanding (malloced but not freed).
  3723. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  3724. ** value of [sqlite3_memory_used()] since the high-water mark
  3725. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  3726. ** [sqlite3_memory_highwater()] include any overhead
  3727. ** added by SQLite in its implementation of [sqlite3_malloc()],
  3728. ** but not overhead added by the any underlying system library
  3729. ** routines that [sqlite3_malloc()] may call.
  3730. **
  3731. ** ^The memory high-water mark is reset to the current value of
  3732. ** [sqlite3_memory_used()] if and only if the parameter to
  3733. ** [sqlite3_memory_highwater()] is true. ^The value returned
  3734. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  3735. ** prior to the reset.
  3736. */
  3737. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  3738. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  3739. /*
  3740. ** CAPI3REF: Pseudo-Random Number Generator
  3741. **
  3742. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  3743. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  3744. ** already uses the largest possible [ROWID]. The PRNG is also used for
  3745. ** the build-in random() and randomblob() SQL functions. This interface allows
  3746. ** applications to access the same PRNG for other purposes.
  3747. **
  3748. ** ^A call to this routine stores N bytes of randomness into buffer P.
  3749. ** ^The P parameter can be a NULL pointer.
  3750. **
  3751. ** ^If this routine has not been previously called or if the previous
  3752. ** call had N less than one or a NULL pointer for P, then the PRNG is
  3753. ** seeded using randomness obtained from the xRandomness method of
  3754. ** the default [sqlite3_vfs] object.
  3755. ** ^If the previous call to this routine had an N of 1 or more and a
  3756. ** non-NULL P then the pseudo-randomness is generated
  3757. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  3758. ** method.
  3759. */
  3760. SQLITE_API void sqlite3_randomness(int N, void *P);
  3761. /*
  3762. ** CAPI3REF: Compile-Time Authorization Callbacks
  3763. ** METHOD: sqlite3
  3764. ** KEYWORDS: {authorizer callback}
  3765. **
  3766. ** ^This routine registers an authorizer callback with a particular
  3767. ** [database connection], supplied in the first argument.
  3768. ** ^The authorizer callback is invoked as SQL statements are being compiled
  3769. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  3770. ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
  3771. ** and [sqlite3_prepare16_v3()]. ^At various
  3772. ** points during the compilation process, as logic is being created
  3773. ** to perform various actions, the authorizer callback is invoked to
  3774. ** see if those actions are allowed. ^The authorizer callback should
  3775. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  3776. ** specific action but allow the SQL statement to continue to be
  3777. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  3778. ** rejected with an error. ^If the authorizer callback returns
  3779. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  3780. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  3781. ** the authorizer will fail with an error message.
  3782. **
  3783. ** When the callback returns [SQLITE_OK], that means the operation
  3784. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  3785. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  3786. ** authorizer will fail with an error message explaining that
  3787. ** access is denied.
  3788. **
  3789. ** ^The first parameter to the authorizer callback is a copy of the third
  3790. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  3791. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  3792. ** the particular action to be authorized. ^The third through sixth parameters
  3793. ** to the callback are either NULL pointers or zero-terminated strings
  3794. ** that contain additional details about the action to be authorized.
  3795. ** Applications must always be prepared to encounter a NULL pointer in any
  3796. ** of the third through the sixth parameters of the authorization callback.
  3797. **
  3798. ** ^If the action code is [SQLITE_READ]
  3799. ** and the callback returns [SQLITE_IGNORE] then the
  3800. ** [prepared statement] statement is constructed to substitute
  3801. ** a NULL value in place of the table column that would have
  3802. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  3803. ** return can be used to deny an untrusted user access to individual
  3804. ** columns of a table.
  3805. ** ^When a table is referenced by a [SELECT] but no column values are
  3806. ** extracted from that table (for example in a query like
  3807. ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
  3808. ** is invoked once for that table with a column name that is an empty string.
  3809. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  3810. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  3811. ** [truncate optimization] is disabled and all rows are deleted individually.
  3812. **
  3813. ** An authorizer is used when [sqlite3_prepare | preparing]
  3814. ** SQL statements from an untrusted source, to ensure that the SQL statements
  3815. ** do not try to access data they are not allowed to see, or that they do not
  3816. ** try to execute malicious statements that damage the database. For
  3817. ** example, an application may allow a user to enter arbitrary
  3818. ** SQL queries for evaluation by a database. But the application does
  3819. ** not want the user to be able to make arbitrary changes to the
  3820. ** database. An authorizer could then be put in place while the
  3821. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  3822. ** disallows everything except [SELECT] statements.
  3823. **
  3824. ** Applications that need to process SQL from untrusted sources
  3825. ** might also consider lowering resource limits using [sqlite3_limit()]
  3826. ** and limiting database size using the [max_page_count] [PRAGMA]
  3827. ** in addition to using an authorizer.
  3828. **
  3829. ** ^(Only a single authorizer can be in place on a database connection
  3830. ** at a time. Each call to sqlite3_set_authorizer overrides the
  3831. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  3832. ** The authorizer is disabled by default.
  3833. **
  3834. ** The authorizer callback must not do anything that will modify
  3835. ** the database connection that invoked the authorizer callback.
  3836. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3837. ** database connections for the meaning of "modify" in this paragraph.
  3838. **
  3839. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  3840. ** statement might be re-prepared during [sqlite3_step()] due to a
  3841. ** schema change. Hence, the application should ensure that the
  3842. ** correct authorizer callback remains in place during the [sqlite3_step()].
  3843. **
  3844. ** ^Note that the authorizer callback is invoked only during
  3845. ** [sqlite3_prepare()] or its variants. Authorization is not
  3846. ** performed during statement evaluation in [sqlite3_step()], unless
  3847. ** as stated in the previous paragraph, sqlite3_step() invokes
  3848. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  3849. */
  3850. SQLITE_API int sqlite3_set_authorizer(
  3851. sqlite3*,
  3852. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  3853. void *pUserData
  3854. );
  3855. /*
  3856. ** CAPI3REF: Authorizer Return Codes
  3857. **
  3858. ** The [sqlite3_set_authorizer | authorizer callback function] must
  3859. ** return either [SQLITE_OK] or one of these two constants in order
  3860. ** to signal SQLite whether or not the action is permitted. See the
  3861. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  3862. ** information.
  3863. **
  3864. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  3865. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  3866. */
  3867. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  3868. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  3869. /*
  3870. ** CAPI3REF: Authorizer Action Codes
  3871. **
  3872. ** The [sqlite3_set_authorizer()] interface registers a callback function
  3873. ** that is invoked to authorize certain SQL statement actions. The
  3874. ** second parameter to the callback is an integer code that specifies
  3875. ** what action is being authorized. These are the integer action codes that
  3876. ** the authorizer callback may be passed.
  3877. **
  3878. ** These action code values signify what kind of operation is to be
  3879. ** authorized. The 3rd and 4th parameters to the authorization
  3880. ** callback function will be parameters or NULL depending on which of these
  3881. ** codes is used as the second parameter. ^(The 5th parameter to the
  3882. ** authorizer callback is the name of the database ("main", "temp",
  3883. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  3884. ** is the name of the inner-most trigger or view that is responsible for
  3885. ** the access attempt or NULL if this access attempt is directly from
  3886. ** top-level SQL code.
  3887. */
  3888. /******************************************* 3rd ************ 4th ***********/
  3889. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  3890. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  3891. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  3892. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  3893. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  3894. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  3895. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  3896. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  3897. #define SQLITE_DELETE 9 /* Table Name NULL */
  3898. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  3899. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  3900. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  3901. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  3902. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  3903. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  3904. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  3905. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  3906. #define SQLITE_INSERT 18 /* Table Name NULL */
  3907. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  3908. #define SQLITE_READ 20 /* Table Name Column Name */
  3909. #define SQLITE_SELECT 21 /* NULL NULL */
  3910. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  3911. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  3912. #define SQLITE_ATTACH 24 /* Filename NULL */
  3913. #define SQLITE_DETACH 25 /* Database Name NULL */
  3914. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  3915. #define SQLITE_REINDEX 27 /* Index Name NULL */
  3916. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  3917. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  3918. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  3919. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  3920. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  3921. #define SQLITE_COPY 0 /* No longer used */
  3922. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  3923. /*
  3924. ** CAPI3REF: Tracing And Profiling Functions
  3925. ** METHOD: sqlite3
  3926. **
  3927. ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
  3928. ** instead of the routines described here.
  3929. **
  3930. ** These routines register callback functions that can be used for
  3931. ** tracing and profiling the execution of SQL statements.
  3932. **
  3933. ** ^The callback function registered by sqlite3_trace() is invoked at
  3934. ** various times when an SQL statement is being run by [sqlite3_step()].
  3935. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  3936. ** SQL statement text as the statement first begins executing.
  3937. ** ^(Additional sqlite3_trace() callbacks might occur
  3938. ** as each triggered subprogram is entered. The callbacks for triggers
  3939. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  3940. **
  3941. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  3942. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  3943. **
  3944. ** ^The callback function registered by sqlite3_profile() is invoked
  3945. ** as each SQL statement finishes. ^The profile callback contains
  3946. ** the original statement text and an estimate of wall-clock time
  3947. ** of how long that statement took to run. ^The profile callback
  3948. ** time is in units of nanoseconds, however the current implementation
  3949. ** is only capable of millisecond resolution so the six least significant
  3950. ** digits in the time are meaningless. Future versions of SQLite
  3951. ** might provide greater resolution on the profiler callback. The
  3952. ** sqlite3_profile() function is considered experimental and is
  3953. ** subject to change in future versions of SQLite.
  3954. */
  3955. SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
  3956. void(*xTrace)(void*,const char*), void*);
  3957. SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
  3958. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  3959. /*
  3960. ** CAPI3REF: SQL Trace Event Codes
  3961. ** KEYWORDS: SQLITE_TRACE
  3962. **
  3963. ** These constants identify classes of events that can be monitored
  3964. ** using the [sqlite3_trace_v2()] tracing logic. The M argument
  3965. ** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
  3966. ** the following constants. ^The first argument to the trace callback
  3967. ** is one of the following constants.
  3968. **
  3969. ** New tracing constants may be added in future releases.
  3970. **
  3971. ** ^A trace callback has four arguments: xCallback(T,C,P,X).
  3972. ** ^The T argument is one of the integer type codes above.
  3973. ** ^The C argument is a copy of the context pointer passed in as the
  3974. ** fourth argument to [sqlite3_trace_v2()].
  3975. ** The P and X arguments are pointers whose meanings depend on T.
  3976. **
  3977. ** <dl>
  3978. ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
  3979. ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
  3980. ** first begins running and possibly at other times during the
  3981. ** execution of the prepared statement, such as at the start of each
  3982. ** trigger subprogram. ^The P argument is a pointer to the
  3983. ** [prepared statement]. ^The X argument is a pointer to a string which
  3984. ** is the unexpanded SQL text of the prepared statement or an SQL comment
  3985. ** that indicates the invocation of a trigger. ^The callback can compute
  3986. ** the same text that would have been returned by the legacy [sqlite3_trace()]
  3987. ** interface by using the X argument when X begins with "--" and invoking
  3988. ** [sqlite3_expanded_sql(P)] otherwise.
  3989. **
  3990. ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
  3991. ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
  3992. ** information as is provided by the [sqlite3_profile()] callback.
  3993. ** ^The P argument is a pointer to the [prepared statement] and the
  3994. ** X argument points to a 64-bit integer which is the estimated of
  3995. ** the number of nanosecond that the prepared statement took to run.
  3996. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
  3997. **
  3998. ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
  3999. ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
  4000. ** statement generates a single row of result.
  4001. ** ^The P argument is a pointer to the [prepared statement] and the
  4002. ** X argument is unused.
  4003. **
  4004. ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
  4005. ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
  4006. ** connection closes.
  4007. ** ^The P argument is a pointer to the [database connection] object
  4008. ** and the X argument is unused.
  4009. ** </dl>
  4010. */
  4011. #define SQLITE_TRACE_STMT 0x01
  4012. #define SQLITE_TRACE_PROFILE 0x02
  4013. #define SQLITE_TRACE_ROW 0x04
  4014. #define SQLITE_TRACE_CLOSE 0x08
  4015. /*
  4016. ** CAPI3REF: SQL Trace Hook
  4017. ** METHOD: sqlite3
  4018. **
  4019. ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
  4020. ** function X against [database connection] D, using property mask M
  4021. ** and context pointer P. ^If the X callback is
  4022. ** NULL or if the M mask is zero, then tracing is disabled. The
  4023. ** M argument should be the bitwise OR-ed combination of
  4024. ** zero or more [SQLITE_TRACE] constants.
  4025. **
  4026. ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
  4027. ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
  4028. **
  4029. ** ^The X callback is invoked whenever any of the events identified by
  4030. ** mask M occur. ^The integer return value from the callback is currently
  4031. ** ignored, though this may change in future releases. Callback
  4032. ** implementations should return zero to ensure future compatibility.
  4033. **
  4034. ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
  4035. ** ^The T argument is one of the [SQLITE_TRACE]
  4036. ** constants to indicate why the callback was invoked.
  4037. ** ^The C argument is a copy of the context pointer.
  4038. ** The P and X arguments are pointers whose meanings depend on T.
  4039. **
  4040. ** The sqlite3_trace_v2() interface is intended to replace the legacy
  4041. ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
  4042. ** are deprecated.
  4043. */
  4044. SQLITE_API int sqlite3_trace_v2(
  4045. sqlite3*,
  4046. unsigned uMask,
  4047. int(*xCallback)(unsigned,void*,void*,void*),
  4048. void *pCtx
  4049. );
  4050. /*
  4051. ** CAPI3REF: Query Progress Callbacks
  4052. ** METHOD: sqlite3
  4053. **
  4054. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  4055. ** function X to be invoked periodically during long running calls to
  4056. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  4057. ** database connection D. An example use for this
  4058. ** interface is to keep a GUI updated during a large query.
  4059. **
  4060. ** ^The parameter P is passed through as the only parameter to the
  4061. ** callback function X. ^The parameter N is the approximate number of
  4062. ** [virtual machine instructions] that are evaluated between successive
  4063. ** invocations of the callback X. ^If N is less than one then the progress
  4064. ** handler is disabled.
  4065. **
  4066. ** ^Only a single progress handler may be defined at one time per
  4067. ** [database connection]; setting a new progress handler cancels the
  4068. ** old one. ^Setting parameter X to NULL disables the progress handler.
  4069. ** ^The progress handler is also disabled by setting N to a value less
  4070. ** than 1.
  4071. **
  4072. ** ^If the progress callback returns non-zero, the operation is
  4073. ** interrupted. This feature can be used to implement a
  4074. ** "Cancel" button on a GUI progress dialog box.
  4075. **
  4076. ** The progress handler callback must not do anything that will modify
  4077. ** the database connection that invoked the progress handler.
  4078. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4079. ** database connections for the meaning of "modify" in this paragraph.
  4080. **
  4081. */
  4082. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  4083. /*
  4084. ** CAPI3REF: Opening A New Database Connection
  4085. ** CONSTRUCTOR: sqlite3
  4086. **
  4087. ** ^These routines open an SQLite database file as specified by the
  4088. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  4089. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  4090. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  4091. ** returned in *ppDb, even if an error occurs. The only exception is that
  4092. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  4093. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  4094. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  4095. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  4096. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  4097. ** an English language description of the error following a failure of any
  4098. ** of the sqlite3_open() routines.
  4099. **
  4100. ** ^The default encoding will be UTF-8 for databases created using
  4101. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  4102. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  4103. **
  4104. ** Whether or not an error occurs when it is opened, resources
  4105. ** associated with the [database connection] handle should be released by
  4106. ** passing it to [sqlite3_close()] when it is no longer required.
  4107. **
  4108. ** The sqlite3_open_v2() interface works like sqlite3_open()
  4109. ** except that it accepts two additional parameters for additional control
  4110. ** over the new database connection. ^(The flags parameter to
  4111. ** sqlite3_open_v2() can take one of
  4112. ** the following three values, optionally combined with the
  4113. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  4114. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  4115. **
  4116. ** <dl>
  4117. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  4118. ** <dd>The database is opened in read-only mode. If the database does not
  4119. ** already exist, an error is returned.</dd>)^
  4120. **
  4121. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  4122. ** <dd>The database is opened for reading and writing if possible, or reading
  4123. ** only if the file is write protected by the operating system. In either
  4124. ** case the database must already exist, otherwise an error is returned.</dd>)^
  4125. **
  4126. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  4127. ** <dd>The database is opened for reading and writing, and is created if
  4128. ** it does not already exist. This is the behavior that is always used for
  4129. ** sqlite3_open() and sqlite3_open16().</dd>)^
  4130. ** </dl>
  4131. **
  4132. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  4133. ** combinations shown above optionally combined with other
  4134. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  4135. ** then the behavior is undefined.
  4136. **
  4137. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  4138. ** opens in the multi-thread [threading mode] as long as the single-thread
  4139. ** mode has not been set at compile-time or start-time. ^If the
  4140. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  4141. ** in the serialized [threading mode] unless single-thread was
  4142. ** previously selected at compile-time or start-time.
  4143. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  4144. ** eligible to use [shared cache mode], regardless of whether or not shared
  4145. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  4146. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  4147. ** participate in [shared cache mode] even if it is enabled.
  4148. **
  4149. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  4150. ** [sqlite3_vfs] object that defines the operating system interface that
  4151. ** the new database connection should use. ^If the fourth parameter is
  4152. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  4153. **
  4154. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  4155. ** is created for the connection. ^This in-memory database will vanish when
  4156. ** the database connection is closed. Future versions of SQLite might
  4157. ** make use of additional special filenames that begin with the ":" character.
  4158. ** It is recommended that when a database filename actually does begin with
  4159. ** a ":" character you should prefix the filename with a pathname such as
  4160. ** "./" to avoid ambiguity.
  4161. **
  4162. ** ^If the filename is an empty string, then a private, temporary
  4163. ** on-disk database will be created. ^This private database will be
  4164. ** automatically deleted as soon as the database connection is closed.
  4165. **
  4166. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  4167. **
  4168. ** ^If [URI filename] interpretation is enabled, and the filename argument
  4169. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  4170. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  4171. ** set in the third argument to sqlite3_open_v2(), or if it has
  4172. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  4173. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  4174. ** URI filename interpretation is turned off
  4175. ** by default, but future releases of SQLite might enable URI filename
  4176. ** interpretation by default. See "[URI filenames]" for additional
  4177. ** information.
  4178. **
  4179. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  4180. ** authority, then it must be either an empty string or the string
  4181. ** "localhost". ^If the authority is not an empty string or "localhost", an
  4182. ** error is returned to the caller. ^The fragment component of a URI, if
  4183. ** present, is ignored.
  4184. **
  4185. ** ^SQLite uses the path component of the URI as the name of the disk file
  4186. ** which contains the database. ^If the path begins with a '/' character,
  4187. ** then it is interpreted as an absolute path. ^If the path does not begin
  4188. ** with a '/' (meaning that the authority section is omitted from the URI)
  4189. ** then the path is interpreted as a relative path.
  4190. ** ^(On windows, the first component of an absolute path
  4191. ** is a drive specification (e.g. "C:").)^
  4192. **
  4193. ** [[core URI query parameters]]
  4194. ** The query component of a URI may contain parameters that are interpreted
  4195. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  4196. ** SQLite and its built-in [VFSes] interpret the
  4197. ** following query parameters:
  4198. **
  4199. ** <ul>
  4200. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  4201. ** a VFS object that provides the operating system interface that should
  4202. ** be used to access the database file on disk. ^If this option is set to
  4203. ** an empty string the default VFS object is used. ^Specifying an unknown
  4204. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  4205. ** present, then the VFS specified by the option takes precedence over
  4206. ** the value passed as the fourth parameter to sqlite3_open_v2().
  4207. **
  4208. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  4209. ** "rwc", or "memory". Attempting to set it to any other value is
  4210. ** an error)^.
  4211. ** ^If "ro" is specified, then the database is opened for read-only
  4212. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  4213. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  4214. ** "rw", then the database is opened for read-write (but not create)
  4215. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  4216. ** been set. ^Value "rwc" is equivalent to setting both
  4217. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  4218. ** set to "memory" then a pure [in-memory database] that never reads
  4219. ** or writes from disk is used. ^It is an error to specify a value for
  4220. ** the mode parameter that is less restrictive than that specified by
  4221. ** the flags passed in the third parameter to sqlite3_open_v2().
  4222. **
  4223. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  4224. ** "private". ^Setting it to "shared" is equivalent to setting the
  4225. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  4226. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  4227. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  4228. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  4229. ** a URI filename, its value overrides any behavior requested by setting
  4230. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  4231. **
  4232. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  4233. ** [powersafe overwrite] property does or does not apply to the
  4234. ** storage media on which the database file resides.
  4235. **
  4236. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  4237. ** which if set disables file locking in rollback journal modes. This
  4238. ** is useful for accessing a database on a filesystem that does not
  4239. ** support locking. Caution: Database corruption might result if two
  4240. ** or more processes write to the same database and any one of those
  4241. ** processes uses nolock=1.
  4242. **
  4243. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  4244. ** parameter that indicates that the database file is stored on
  4245. ** read-only media. ^When immutable is set, SQLite assumes that the
  4246. ** database file cannot be changed, even by a process with higher
  4247. ** privilege, and so the database is opened read-only and all locking
  4248. ** and change detection is disabled. Caution: Setting the immutable
  4249. ** property on a database file that does in fact change can result
  4250. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  4251. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  4252. **
  4253. ** </ul>
  4254. **
  4255. ** ^Specifying an unknown parameter in the query component of a URI is not an
  4256. ** error. Future versions of SQLite might understand additional query
  4257. ** parameters. See "[query parameters with special meaning to SQLite]" for
  4258. ** additional information.
  4259. **
  4260. ** [[URI filename examples]] <h3>URI filename examples</h3>
  4261. **
  4262. ** <table border="1" align=center cellpadding=5>
  4263. ** <tr><th> URI filenames <th> Results
  4264. ** <tr><td> file:data.db <td>
  4265. ** Open the file "data.db" in the current directory.
  4266. ** <tr><td> file:/home/fred/data.db<br>
  4267. ** file:///home/fred/data.db <br>
  4268. ** file://localhost/home/fred/data.db <br> <td>
  4269. ** Open the database file "/home/fred/data.db".
  4270. ** <tr><td> file://darkstar/home/fred/data.db <td>
  4271. ** An error. "darkstar" is not a recognized authority.
  4272. ** <tr><td style="white-space:nowrap">
  4273. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  4274. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  4275. ** C:. Note that the %20 escaping in this example is not strictly
  4276. ** necessary - space characters can be used literally
  4277. ** in URI filenames.
  4278. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  4279. ** Open file "data.db" in the current directory for read-only access.
  4280. ** Regardless of whether or not shared-cache mode is enabled by
  4281. ** default, use a private cache.
  4282. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  4283. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  4284. ** that uses dot-files in place of posix advisory locking.
  4285. ** <tr><td> file:data.db?mode=readonly <td>
  4286. ** An error. "readonly" is not a valid option for the "mode" parameter.
  4287. ** </table>
  4288. **
  4289. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  4290. ** query components of a URI. A hexadecimal escape sequence consists of a
  4291. ** percent sign - "%" - followed by exactly two hexadecimal digits
  4292. ** specifying an octet value. ^Before the path or query components of a
  4293. ** URI filename are interpreted, they are encoded using UTF-8 and all
  4294. ** hexadecimal escape sequences replaced by a single byte containing the
  4295. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  4296. ** the results are undefined.
  4297. **
  4298. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  4299. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  4300. ** codepage is currently defined. Filenames containing international
  4301. ** characters must be converted to UTF-8 prior to passing them into
  4302. ** sqlite3_open() or sqlite3_open_v2().
  4303. **
  4304. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4305. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  4306. ** features that require the use of temporary files may fail.
  4307. **
  4308. ** See also: [sqlite3_temp_directory]
  4309. */
  4310. SQLITE_API int sqlite3_open(
  4311. const char *filename, /* Database filename (UTF-8) */
  4312. sqlite3 **ppDb /* OUT: SQLite db handle */
  4313. );
  4314. SQLITE_API int sqlite3_open16(
  4315. const void *filename, /* Database filename (UTF-16) */
  4316. sqlite3 **ppDb /* OUT: SQLite db handle */
  4317. );
  4318. SQLITE_API int sqlite3_open_v2(
  4319. const char *filename, /* Database filename (UTF-8) */
  4320. sqlite3 **ppDb, /* OUT: SQLite db handle */
  4321. int flags, /* Flags */
  4322. const char *zVfs /* Name of VFS module to use */
  4323. );
  4324. /*
  4325. ** CAPI3REF: Obtain Values For URI Parameters
  4326. **
  4327. ** These are utility routines, useful to VFS implementations, that check
  4328. ** to see if a database file was a URI that contained a specific query
  4329. ** parameter, and if so obtains the value of that query parameter.
  4330. **
  4331. ** If F is the database filename pointer passed into the xOpen() method of
  4332. ** a VFS implementation when the flags parameter to xOpen() has one or
  4333. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  4334. ** P is the name of the query parameter, then
  4335. ** sqlite3_uri_parameter(F,P) returns the value of the P
  4336. ** parameter if it exists or a NULL pointer if P does not appear as a
  4337. ** query parameter on F. If P is a query parameter of F
  4338. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  4339. ** a pointer to an empty string.
  4340. **
  4341. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  4342. ** parameter and returns true (1) or false (0) according to the value
  4343. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  4344. ** value of query parameter P is one of "yes", "true", or "on" in any
  4345. ** case or if the value begins with a non-zero number. The
  4346. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  4347. ** query parameter P is one of "no", "false", or "off" in any case or
  4348. ** if the value begins with a numeric zero. If P is not a query
  4349. ** parameter on F or if the value of P is does not match any of the
  4350. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  4351. **
  4352. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  4353. ** 64-bit signed integer and returns that integer, or D if P does not
  4354. ** exist. If the value of P is something other than an integer, then
  4355. ** zero is returned.
  4356. **
  4357. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  4358. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  4359. ** is not a database file pathname pointer that SQLite passed into the xOpen
  4360. ** VFS method, then the behavior of this routine is undefined and probably
  4361. ** undesirable.
  4362. */
  4363. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  4364. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  4365. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  4366. /*
  4367. ** CAPI3REF: Error Codes And Messages
  4368. ** METHOD: sqlite3
  4369. **
  4370. ** ^If the most recent sqlite3_* API call associated with
  4371. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  4372. ** returns the numeric [result code] or [extended result code] for that
  4373. ** API call.
  4374. ** ^The sqlite3_extended_errcode()
  4375. ** interface is the same except that it always returns the
  4376. ** [extended result code] even when extended result codes are
  4377. ** disabled.
  4378. **
  4379. ** The values returned by sqlite3_errcode() and/or
  4380. ** sqlite3_extended_errcode() might change with each API call.
  4381. ** Except, there are some interfaces that are guaranteed to never
  4382. ** change the value of the error code. The error-code preserving
  4383. ** interfaces are:
  4384. **
  4385. ** <ul>
  4386. ** <li> sqlite3_errcode()
  4387. ** <li> sqlite3_extended_errcode()
  4388. ** <li> sqlite3_errmsg()
  4389. ** <li> sqlite3_errmsg16()
  4390. ** </ul>
  4391. **
  4392. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  4393. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  4394. ** ^(Memory to hold the error message string is managed internally.
  4395. ** The application does not need to worry about freeing the result.
  4396. ** However, the error string might be overwritten or deallocated by
  4397. ** subsequent calls to other SQLite interface functions.)^
  4398. **
  4399. ** ^The sqlite3_errstr() interface returns the English-language text
  4400. ** that describes the [result code], as UTF-8.
  4401. ** ^(Memory to hold the error message string is managed internally
  4402. ** and must not be freed by the application)^.
  4403. **
  4404. ** When the serialized [threading mode] is in use, it might be the
  4405. ** case that a second error occurs on a separate thread in between
  4406. ** the time of the first error and the call to these interfaces.
  4407. ** When that happens, the second error will be reported since these
  4408. ** interfaces always report the most recent result. To avoid
  4409. ** this, each thread can obtain exclusive use of the [database connection] D
  4410. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  4411. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  4412. ** all calls to the interfaces listed here are completed.
  4413. **
  4414. ** If an interface fails with SQLITE_MISUSE, that means the interface
  4415. ** was invoked incorrectly by the application. In that case, the
  4416. ** error code and message may or may not be set.
  4417. */
  4418. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  4419. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  4420. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  4421. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  4422. SQLITE_API const char *sqlite3_errstr(int);
  4423. /*
  4424. ** CAPI3REF: Prepared Statement Object
  4425. ** KEYWORDS: {prepared statement} {prepared statements}
  4426. **
  4427. ** An instance of this object represents a single SQL statement that
  4428. ** has been compiled into binary form and is ready to be evaluated.
  4429. **
  4430. ** Think of each SQL statement as a separate computer program. The
  4431. ** original SQL text is source code. A prepared statement object
  4432. ** is the compiled object code. All SQL must be converted into a
  4433. ** prepared statement before it can be run.
  4434. **
  4435. ** The life-cycle of a prepared statement object usually goes like this:
  4436. **
  4437. ** <ol>
  4438. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  4439. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  4440. ** interfaces.
  4441. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  4442. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  4443. ** to step 2. Do this zero or more times.
  4444. ** <li> Destroy the object using [sqlite3_finalize()].
  4445. ** </ol>
  4446. */
  4447. typedef struct sqlite3_stmt sqlite3_stmt;
  4448. /*
  4449. ** CAPI3REF: Run-time Limits
  4450. ** METHOD: sqlite3
  4451. **
  4452. ** ^(This interface allows the size of various constructs to be limited
  4453. ** on a connection by connection basis. The first parameter is the
  4454. ** [database connection] whose limit is to be set or queried. The
  4455. ** second parameter is one of the [limit categories] that define a
  4456. ** class of constructs to be size limited. The third parameter is the
  4457. ** new limit for that construct.)^
  4458. **
  4459. ** ^If the new limit is a negative number, the limit is unchanged.
  4460. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  4461. ** [limits | hard upper bound]
  4462. ** set at compile-time by a C preprocessor macro called
  4463. ** [limits | SQLITE_MAX_<i>NAME</i>].
  4464. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  4465. ** ^Attempts to increase a limit above its hard upper bound are
  4466. ** silently truncated to the hard upper bound.
  4467. **
  4468. ** ^Regardless of whether or not the limit was changed, the
  4469. ** [sqlite3_limit()] interface returns the prior value of the limit.
  4470. ** ^Hence, to find the current value of a limit without changing it,
  4471. ** simply invoke this interface with the third parameter set to -1.
  4472. **
  4473. ** Run-time limits are intended for use in applications that manage
  4474. ** both their own internal database and also databases that are controlled
  4475. ** by untrusted external sources. An example application might be a
  4476. ** web browser that has its own databases for storing history and
  4477. ** separate databases controlled by JavaScript applications downloaded
  4478. ** off the Internet. The internal databases can be given the
  4479. ** large, default limits. Databases managed by external sources can
  4480. ** be given much smaller limits designed to prevent a denial of service
  4481. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  4482. ** interface to further control untrusted SQL. The size of the database
  4483. ** created by an untrusted script can be contained using the
  4484. ** [max_page_count] [PRAGMA].
  4485. **
  4486. ** New run-time limit categories may be added in future releases.
  4487. */
  4488. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  4489. /*
  4490. ** CAPI3REF: Run-Time Limit Categories
  4491. ** KEYWORDS: {limit category} {*limit categories}
  4492. **
  4493. ** These constants define various performance limits
  4494. ** that can be lowered at run-time using [sqlite3_limit()].
  4495. ** The synopsis of the meanings of the various limits is shown below.
  4496. ** Additional information is available at [limits | Limits in SQLite].
  4497. **
  4498. ** <dl>
  4499. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  4500. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  4501. **
  4502. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  4503. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  4504. **
  4505. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  4506. ** <dd>The maximum number of columns in a table definition or in the
  4507. ** result set of a [SELECT] or the maximum number of columns in an index
  4508. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  4509. **
  4510. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  4511. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  4512. **
  4513. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  4514. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  4515. **
  4516. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  4517. ** <dd>The maximum number of instructions in a virtual machine program
  4518. ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
  4519. ** the equivalent tries to allocate space for more than this many opcodes
  4520. ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
  4521. **
  4522. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  4523. ** <dd>The maximum number of arguments on a function.</dd>)^
  4524. **
  4525. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  4526. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  4527. **
  4528. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  4529. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  4530. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  4531. ** [GLOB] operators.</dd>)^
  4532. **
  4533. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  4534. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  4535. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  4536. **
  4537. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  4538. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  4539. **
  4540. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  4541. ** <dd>The maximum number of auxiliary worker threads that a single
  4542. ** [prepared statement] may start.</dd>)^
  4543. ** </dl>
  4544. */
  4545. #define SQLITE_LIMIT_LENGTH 0
  4546. #define SQLITE_LIMIT_SQL_LENGTH 1
  4547. #define SQLITE_LIMIT_COLUMN 2
  4548. #define SQLITE_LIMIT_EXPR_DEPTH 3
  4549. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  4550. #define SQLITE_LIMIT_VDBE_OP 5
  4551. #define SQLITE_LIMIT_FUNCTION_ARG 6
  4552. #define SQLITE_LIMIT_ATTACHED 7
  4553. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  4554. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  4555. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  4556. #define SQLITE_LIMIT_WORKER_THREADS 11
  4557. /*
  4558. ** CAPI3REF: Prepare Flags
  4559. **
  4560. ** These constants define various flags that can be passed into
  4561. ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
  4562. ** [sqlite3_prepare16_v3()] interfaces.
  4563. **
  4564. ** New flags may be added in future releases of SQLite.
  4565. **
  4566. ** <dl>
  4567. ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
  4568. ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
  4569. ** that the prepared statement will be retained for a long time and
  4570. ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
  4571. ** and [sqlite3_prepare16_v3()] assume that the prepared statement will
  4572. ** be used just once or at most a few times and then destroyed using
  4573. ** [sqlite3_finalize()] relatively soon. The current implementation acts
  4574. ** on this hint by avoiding the use of [lookaside memory] so as not to
  4575. ** deplete the limited store of lookaside memory. Future versions of
  4576. ** SQLite may act on this hint differently.
  4577. **
  4578. ** [[SQLITE_PREPARE_NORMALIZE]] ^(<dt>SQLITE_PREPARE_NORMALIZE</dt>
  4579. ** <dd>The SQLITE_PREPARE_NORMALIZE flag indicates that a normalized
  4580. ** representation of the SQL statement should be calculated and then
  4581. ** associated with the prepared statement, which can be obtained via
  4582. ** the [sqlite3_normalized_sql()] interface.)^ The semantics used to
  4583. ** normalize a SQL statement are unspecified and subject to change.
  4584. ** At a minimum, literal values will be replaced with suitable
  4585. ** placeholders.
  4586. ** </dl>
  4587. */
  4588. #define SQLITE_PREPARE_PERSISTENT 0x01
  4589. #define SQLITE_PREPARE_NORMALIZE 0x02
  4590. /*
  4591. ** CAPI3REF: Compiling An SQL Statement
  4592. ** KEYWORDS: {SQL statement compiler}
  4593. ** METHOD: sqlite3
  4594. ** CONSTRUCTOR: sqlite3_stmt
  4595. **
  4596. ** To execute an SQL statement, it must first be compiled into a byte-code
  4597. ** program using one of these routines. Or, in other words, these routines
  4598. ** are constructors for the [prepared statement] object.
  4599. **
  4600. ** The preferred routine to use is [sqlite3_prepare_v2()]. The
  4601. ** [sqlite3_prepare()] interface is legacy and should be avoided.
  4602. ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
  4603. ** for special purposes.
  4604. **
  4605. ** The use of the UTF-8 interfaces is preferred, as SQLite currently
  4606. ** does all parsing using UTF-8. The UTF-16 interfaces are provided
  4607. ** as a convenience. The UTF-16 interfaces work by converting the
  4608. ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
  4609. **
  4610. ** The first argument, "db", is a [database connection] obtained from a
  4611. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  4612. ** [sqlite3_open16()]. The database connection must not have been closed.
  4613. **
  4614. ** The second argument, "zSql", is the statement to be compiled, encoded
  4615. ** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
  4616. ** and sqlite3_prepare_v3()
  4617. ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
  4618. ** and sqlite3_prepare16_v3() use UTF-16.
  4619. **
  4620. ** ^If the nByte argument is negative, then zSql is read up to the
  4621. ** first zero terminator. ^If nByte is positive, then it is the
  4622. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  4623. ** statement is generated.
  4624. ** If the caller knows that the supplied string is nul-terminated, then
  4625. ** there is a small performance advantage to passing an nByte parameter that
  4626. ** is the number of bytes in the input string <i>including</i>
  4627. ** the nul-terminator.
  4628. **
  4629. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  4630. ** past the end of the first SQL statement in zSql. These routines only
  4631. ** compile the first statement in zSql, so *pzTail is left pointing to
  4632. ** what remains uncompiled.
  4633. **
  4634. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  4635. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  4636. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  4637. ** string or a comment) then *ppStmt is set to NULL.
  4638. ** The calling procedure is responsible for deleting the compiled
  4639. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  4640. ** ppStmt may not be NULL.
  4641. **
  4642. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  4643. ** otherwise an [error code] is returned.
  4644. **
  4645. ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
  4646. ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
  4647. ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
  4648. ** are retained for backwards compatibility, but their use is discouraged.
  4649. ** ^In the "vX" interfaces, the prepared statement
  4650. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  4651. ** original SQL text. This causes the [sqlite3_step()] interface to
  4652. ** behave differently in three ways:
  4653. **
  4654. ** <ol>
  4655. ** <li>
  4656. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  4657. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  4658. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  4659. ** retries will occur before sqlite3_step() gives up and returns an error.
  4660. ** </li>
  4661. **
  4662. ** <li>
  4663. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  4664. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  4665. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  4666. ** and the application would have to make a second call to [sqlite3_reset()]
  4667. ** in order to find the underlying cause of the problem. With the "v2" prepare
  4668. ** interfaces, the underlying reason for the error is returned immediately.
  4669. ** </li>
  4670. **
  4671. ** <li>
  4672. ** ^If the specific value bound to [parameter | host parameter] in the
  4673. ** WHERE clause might influence the choice of query plan for a statement,
  4674. ** then the statement will be automatically recompiled, as if there had been
  4675. ** a schema change, on the first [sqlite3_step()] call following any change
  4676. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  4677. ** ^The specific value of WHERE-clause [parameter] might influence the
  4678. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  4679. ** or [GLOB] operator or if the parameter is compared to an indexed column
  4680. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  4681. ** </li>
  4682. ** </ol>
  4683. **
  4684. ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
  4685. ** the extra prepFlags parameter, which is a bit array consisting of zero or
  4686. ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
  4687. ** sqlite3_prepare_v2() interface works exactly the same as
  4688. ** sqlite3_prepare_v3() with a zero prepFlags parameter.
  4689. */
  4690. SQLITE_API int sqlite3_prepare(
  4691. sqlite3 *db, /* Database handle */
  4692. const char *zSql, /* SQL statement, UTF-8 encoded */
  4693. int nByte, /* Maximum length of zSql in bytes. */
  4694. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4695. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4696. );
  4697. SQLITE_API int sqlite3_prepare_v2(
  4698. sqlite3 *db, /* Database handle */
  4699. const char *zSql, /* SQL statement, UTF-8 encoded */
  4700. int nByte, /* Maximum length of zSql in bytes. */
  4701. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4702. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4703. );
  4704. SQLITE_API int sqlite3_prepare_v3(
  4705. sqlite3 *db, /* Database handle */
  4706. const char *zSql, /* SQL statement, UTF-8 encoded */
  4707. int nByte, /* Maximum length of zSql in bytes. */
  4708. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4709. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4710. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4711. );
  4712. SQLITE_API int sqlite3_prepare16(
  4713. sqlite3 *db, /* Database handle */
  4714. const void *zSql, /* SQL statement, UTF-16 encoded */
  4715. int nByte, /* Maximum length of zSql in bytes. */
  4716. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4717. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4718. );
  4719. SQLITE_API int sqlite3_prepare16_v2(
  4720. sqlite3 *db, /* Database handle */
  4721. const void *zSql, /* SQL statement, UTF-16 encoded */
  4722. int nByte, /* Maximum length of zSql in bytes. */
  4723. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4724. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4725. );
  4726. SQLITE_API int sqlite3_prepare16_v3(
  4727. sqlite3 *db, /* Database handle */
  4728. const void *zSql, /* SQL statement, UTF-16 encoded */
  4729. int nByte, /* Maximum length of zSql in bytes. */
  4730. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4731. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4732. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4733. );
  4734. /*
  4735. ** CAPI3REF: Retrieving Statement SQL
  4736. ** METHOD: sqlite3_stmt
  4737. **
  4738. ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  4739. ** SQL text used to create [prepared statement] P if P was
  4740. ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
  4741. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4742. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  4743. ** string containing the SQL text of prepared statement P with
  4744. ** [bound parameters] expanded.
  4745. ** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
  4746. ** string containing the normalized SQL text of prepared statement P. The
  4747. ** semantics used to normalize a SQL statement are unspecified and subject
  4748. ** to change. At a minimum, literal values will be replaced with suitable
  4749. ** placeholders.
  4750. **
  4751. ** ^(For example, if a prepared statement is created using the SQL
  4752. ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  4753. ** and parameter :xyz is unbound, then sqlite3_sql() will return
  4754. ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  4755. ** will return "SELECT 2345,NULL".)^
  4756. **
  4757. ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
  4758. ** is available to hold the result, or if the result would exceed the
  4759. ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  4760. **
  4761. ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  4762. ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
  4763. ** option causes sqlite3_expanded_sql() to always return NULL.
  4764. **
  4765. ** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
  4766. ** are managed by SQLite and are automatically freed when the prepared
  4767. ** statement is finalized.
  4768. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  4769. ** is obtained from [sqlite3_malloc()] and must be free by the application
  4770. ** by passing it to [sqlite3_free()].
  4771. */
  4772. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  4773. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  4774. SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
  4775. /*
  4776. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  4777. ** METHOD: sqlite3_stmt
  4778. **
  4779. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  4780. ** and only if the [prepared statement] X makes no direct changes to
  4781. ** the content of the database file.
  4782. **
  4783. ** Note that [application-defined SQL functions] or
  4784. ** [virtual tables] might change the database indirectly as a side effect.
  4785. ** ^(For example, if an application defines a function "eval()" that
  4786. ** calls [sqlite3_exec()], then the following SQL statement would
  4787. ** change the database file through side-effects:
  4788. **
  4789. ** <blockquote><pre>
  4790. ** SELECT eval('DELETE FROM t1') FROM t2;
  4791. ** </pre></blockquote>
  4792. **
  4793. ** But because the [SELECT] statement does not change the database file
  4794. ** directly, sqlite3_stmt_readonly() would still return true.)^
  4795. **
  4796. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  4797. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  4798. ** since the statements themselves do not actually modify the database but
  4799. ** rather they control the timing of when other statements modify the
  4800. ** database. ^The [ATTACH] and [DETACH] statements also cause
  4801. ** sqlite3_stmt_readonly() to return true since, while those statements
  4802. ** change the configuration of a database connection, they do not make
  4803. ** changes to the content of the database files on disk.
  4804. ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
  4805. ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
  4806. ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
  4807. ** sqlite3_stmt_readonly() returns false for those commands.
  4808. */
  4809. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  4810. /*
  4811. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  4812. ** METHOD: sqlite3_stmt
  4813. **
  4814. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  4815. ** [prepared statement] S has been stepped at least once using
  4816. ** [sqlite3_step(S)] but has neither run to completion (returned
  4817. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  4818. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  4819. ** interface returns false if S is a NULL pointer. If S is not a
  4820. ** NULL pointer and is not a pointer to a valid [prepared statement]
  4821. ** object, then the behavior is undefined and probably undesirable.
  4822. **
  4823. ** This interface can be used in combination [sqlite3_next_stmt()]
  4824. ** to locate all prepared statements associated with a database
  4825. ** connection that are in need of being reset. This can be used,
  4826. ** for example, in diagnostic routines to search for prepared
  4827. ** statements that are holding a transaction open.
  4828. */
  4829. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  4830. /*
  4831. ** CAPI3REF: Dynamically Typed Value Object
  4832. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  4833. **
  4834. ** SQLite uses the sqlite3_value object to represent all values
  4835. ** that can be stored in a database table. SQLite uses dynamic typing
  4836. ** for the values it stores. ^Values stored in sqlite3_value objects
  4837. ** can be integers, floating point values, strings, BLOBs, or NULL.
  4838. **
  4839. ** An sqlite3_value object may be either "protected" or "unprotected".
  4840. ** Some interfaces require a protected sqlite3_value. Other interfaces
  4841. ** will accept either a protected or an unprotected sqlite3_value.
  4842. ** Every interface that accepts sqlite3_value arguments specifies
  4843. ** whether or not it requires a protected sqlite3_value. The
  4844. ** [sqlite3_value_dup()] interface can be used to construct a new
  4845. ** protected sqlite3_value from an unprotected sqlite3_value.
  4846. **
  4847. ** The terms "protected" and "unprotected" refer to whether or not
  4848. ** a mutex is held. An internal mutex is held for a protected
  4849. ** sqlite3_value object but no mutex is held for an unprotected
  4850. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  4851. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  4852. ** or if SQLite is run in one of reduced mutex modes
  4853. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  4854. ** then there is no distinction between protected and unprotected
  4855. ** sqlite3_value objects and they can be used interchangeably. However,
  4856. ** for maximum code portability it is recommended that applications
  4857. ** still make the distinction between protected and unprotected
  4858. ** sqlite3_value objects even when not strictly required.
  4859. **
  4860. ** ^The sqlite3_value objects that are passed as parameters into the
  4861. ** implementation of [application-defined SQL functions] are protected.
  4862. ** ^The sqlite3_value object returned by
  4863. ** [sqlite3_column_value()] is unprotected.
  4864. ** Unprotected sqlite3_value objects may only be used as arguments
  4865. ** to [sqlite3_result_value()], [sqlite3_bind_value()], and
  4866. ** [sqlite3_value_dup()].
  4867. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  4868. ** interfaces require protected sqlite3_value objects.
  4869. */
  4870. typedef struct sqlite3_value sqlite3_value;
  4871. /*
  4872. ** CAPI3REF: SQL Function Context Object
  4873. **
  4874. ** The context in which an SQL function executes is stored in an
  4875. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  4876. ** is always first parameter to [application-defined SQL functions].
  4877. ** The application-defined SQL function implementation will pass this
  4878. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  4879. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  4880. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  4881. ** and/or [sqlite3_set_auxdata()].
  4882. */
  4883. typedef struct sqlite3_context sqlite3_context;
  4884. /*
  4885. ** CAPI3REF: Binding Values To Prepared Statements
  4886. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  4887. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  4888. ** METHOD: sqlite3_stmt
  4889. **
  4890. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  4891. ** literals may be replaced by a [parameter] that matches one of following
  4892. ** templates:
  4893. **
  4894. ** <ul>
  4895. ** <li> ?
  4896. ** <li> ?NNN
  4897. ** <li> :VVV
  4898. ** <li> @VVV
  4899. ** <li> $VVV
  4900. ** </ul>
  4901. **
  4902. ** In the templates above, NNN represents an integer literal,
  4903. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  4904. ** parameters (also called "host parameter names" or "SQL parameters")
  4905. ** can be set using the sqlite3_bind_*() routines defined here.
  4906. **
  4907. ** ^The first argument to the sqlite3_bind_*() routines is always
  4908. ** a pointer to the [sqlite3_stmt] object returned from
  4909. ** [sqlite3_prepare_v2()] or its variants.
  4910. **
  4911. ** ^The second argument is the index of the SQL parameter to be set.
  4912. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  4913. ** SQL parameter is used more than once, second and subsequent
  4914. ** occurrences have the same index as the first occurrence.
  4915. ** ^The index for named parameters can be looked up using the
  4916. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  4917. ** for "?NNN" parameters is the value of NNN.
  4918. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  4919. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  4920. **
  4921. ** ^The third argument is the value to bind to the parameter.
  4922. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4923. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  4924. ** is ignored and the end result is the same as sqlite3_bind_null().
  4925. **
  4926. ** ^(In those routines that have a fourth argument, its value is the
  4927. ** number of bytes in the parameter. To be clear: the value is the
  4928. ** number of <u>bytes</u> in the value, not the number of characters.)^
  4929. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4930. ** is negative, then the length of the string is
  4931. ** the number of bytes up to the first zero terminator.
  4932. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  4933. ** the behavior is undefined.
  4934. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  4935. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  4936. ** that parameter must be the byte offset
  4937. ** where the NUL terminator would occur assuming the string were NUL
  4938. ** terminated. If any NUL characters occur at byte offsets less than
  4939. ** the value of the fourth parameter then the resulting string value will
  4940. ** contain embedded NULs. The result of expressions involving strings
  4941. ** with embedded NULs is undefined.
  4942. **
  4943. ** ^The fifth argument to the BLOB and string binding interfaces
  4944. ** is a destructor used to dispose of the BLOB or
  4945. ** string after SQLite has finished with it. ^The destructor is called
  4946. ** to dispose of the BLOB or string even if the call to bind API fails.
  4947. ** ^If the fifth argument is
  4948. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  4949. ** information is in static, unmanaged space and does not need to be freed.
  4950. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  4951. ** SQLite makes its own private copy of the data immediately, before
  4952. ** the sqlite3_bind_*() routine returns.
  4953. **
  4954. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  4955. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  4956. ** to specify the encoding of the text in the third parameter. If
  4957. ** the sixth argument to sqlite3_bind_text64() is not one of the
  4958. ** allowed values shown above, or if the text encoding is different
  4959. ** from the encoding specified by the sixth parameter, then the behavior
  4960. ** is undefined.
  4961. **
  4962. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  4963. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  4964. ** (just an integer to hold its size) while it is being processed.
  4965. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  4966. ** content is later written using
  4967. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  4968. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  4969. **
  4970. ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
  4971. ** [prepared statement] S to have an SQL value of NULL, but to also be
  4972. ** associated with the pointer P of type T. ^D is either a NULL pointer or
  4973. ** a pointer to a destructor function for P. ^SQLite will invoke the
  4974. ** destructor D with a single argument of P when it is finished using
  4975. ** P. The T parameter should be a static string, preferably a string
  4976. ** literal. The sqlite3_bind_pointer() routine is part of the
  4977. ** [pointer passing interface] added for SQLite 3.20.0.
  4978. **
  4979. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  4980. ** for the [prepared statement] or with a prepared statement for which
  4981. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  4982. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  4983. ** routine is passed a [prepared statement] that has been finalized, the
  4984. ** result is undefined and probably harmful.
  4985. **
  4986. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  4987. ** ^Unbound parameters are interpreted as NULL.
  4988. **
  4989. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  4990. ** [error code] if anything goes wrong.
  4991. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  4992. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  4993. ** [SQLITE_MAX_LENGTH].
  4994. ** ^[SQLITE_RANGE] is returned if the parameter
  4995. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  4996. **
  4997. ** See also: [sqlite3_bind_parameter_count()],
  4998. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  4999. */
  5000. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  5001. SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  5002. void(*)(void*));
  5003. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  5004. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  5005. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  5006. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  5007. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  5008. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  5009. SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  5010. void(*)(void*), unsigned char encoding);
  5011. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  5012. SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
  5013. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  5014. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  5015. /*
  5016. ** CAPI3REF: Number Of SQL Parameters
  5017. ** METHOD: sqlite3_stmt
  5018. **
  5019. ** ^This routine can be used to find the number of [SQL parameters]
  5020. ** in a [prepared statement]. SQL parameters are tokens of the
  5021. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  5022. ** placeholders for values that are [sqlite3_bind_blob | bound]
  5023. ** to the parameters at a later time.
  5024. **
  5025. ** ^(This routine actually returns the index of the largest (rightmost)
  5026. ** parameter. For all forms except ?NNN, this will correspond to the
  5027. ** number of unique parameters. If parameters of the ?NNN form are used,
  5028. ** there may be gaps in the list.)^
  5029. **
  5030. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5031. ** [sqlite3_bind_parameter_name()], and
  5032. ** [sqlite3_bind_parameter_index()].
  5033. */
  5034. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  5035. /*
  5036. ** CAPI3REF: Name Of A Host Parameter
  5037. ** METHOD: sqlite3_stmt
  5038. **
  5039. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  5040. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  5041. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5042. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5043. ** respectively.
  5044. ** In other words, the initial ":" or "$" or "@" or "?"
  5045. ** is included as part of the name.)^
  5046. ** ^Parameters of the form "?" without a following integer have no name
  5047. ** and are referred to as "nameless" or "anonymous parameters".
  5048. **
  5049. ** ^The first host parameter has an index of 1, not 0.
  5050. **
  5051. ** ^If the value N is out of range or if the N-th parameter is
  5052. ** nameless, then NULL is returned. ^The returned string is
  5053. ** always in UTF-8 encoding even if the named parameter was
  5054. ** originally specified as UTF-16 in [sqlite3_prepare16()],
  5055. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  5056. **
  5057. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5058. ** [sqlite3_bind_parameter_count()], and
  5059. ** [sqlite3_bind_parameter_index()].
  5060. */
  5061. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  5062. /*
  5063. ** CAPI3REF: Index Of A Parameter With A Given Name
  5064. ** METHOD: sqlite3_stmt
  5065. **
  5066. ** ^Return the index of an SQL parameter given its name. ^The
  5067. ** index value returned is suitable for use as the second
  5068. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  5069. ** is returned if no matching parameter is found. ^The parameter
  5070. ** name must be given in UTF-8 even if the original statement
  5071. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
  5072. ** [sqlite3_prepare16_v3()].
  5073. **
  5074. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5075. ** [sqlite3_bind_parameter_count()], and
  5076. ** [sqlite3_bind_parameter_name()].
  5077. */
  5078. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  5079. /*
  5080. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  5081. ** METHOD: sqlite3_stmt
  5082. **
  5083. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  5084. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  5085. ** ^Use this routine to reset all host parameters to NULL.
  5086. */
  5087. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  5088. /*
  5089. ** CAPI3REF: Number Of Columns In A Result Set
  5090. ** METHOD: sqlite3_stmt
  5091. **
  5092. ** ^Return the number of columns in the result set returned by the
  5093. ** [prepared statement]. ^If this routine returns 0, that means the
  5094. ** [prepared statement] returns no data (for example an [UPDATE]).
  5095. ** ^However, just because this routine returns a positive number does not
  5096. ** mean that one or more rows of data will be returned. ^A SELECT statement
  5097. ** will always have a positive sqlite3_column_count() but depending on the
  5098. ** WHERE clause constraints and the table content, it might return no rows.
  5099. **
  5100. ** See also: [sqlite3_data_count()]
  5101. */
  5102. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  5103. /*
  5104. ** CAPI3REF: Column Names In A Result Set
  5105. ** METHOD: sqlite3_stmt
  5106. **
  5107. ** ^These routines return the name assigned to a particular column
  5108. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  5109. ** interface returns a pointer to a zero-terminated UTF-8 string
  5110. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  5111. ** UTF-16 string. ^The first parameter is the [prepared statement]
  5112. ** that implements the [SELECT] statement. ^The second parameter is the
  5113. ** column number. ^The leftmost column is number 0.
  5114. **
  5115. ** ^The returned string pointer is valid until either the [prepared statement]
  5116. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  5117. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5118. ** or until the next call to
  5119. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  5120. **
  5121. ** ^If sqlite3_malloc() fails during the processing of either routine
  5122. ** (for example during a conversion from UTF-8 to UTF-16) then a
  5123. ** NULL pointer is returned.
  5124. **
  5125. ** ^The name of a result column is the value of the "AS" clause for
  5126. ** that column, if there is an AS clause. If there is no AS clause
  5127. ** then the name of the column is unspecified and may change from
  5128. ** one release of SQLite to the next.
  5129. */
  5130. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  5131. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  5132. /*
  5133. ** CAPI3REF: Source Of Data In A Query Result
  5134. ** METHOD: sqlite3_stmt
  5135. **
  5136. ** ^These routines provide a means to determine the database, table, and
  5137. ** table column that is the origin of a particular result column in
  5138. ** [SELECT] statement.
  5139. ** ^The name of the database or table or column can be returned as
  5140. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  5141. ** the database name, the _table_ routines return the table name, and
  5142. ** the origin_ routines return the column name.
  5143. ** ^The returned string is valid until the [prepared statement] is destroyed
  5144. ** using [sqlite3_finalize()] or until the statement is automatically
  5145. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5146. ** or until the same information is requested
  5147. ** again in a different encoding.
  5148. **
  5149. ** ^The names returned are the original un-aliased names of the
  5150. ** database, table, and column.
  5151. **
  5152. ** ^The first argument to these interfaces is a [prepared statement].
  5153. ** ^These functions return information about the Nth result column returned by
  5154. ** the statement, where N is the second function argument.
  5155. ** ^The left-most column is column 0 for these routines.
  5156. **
  5157. ** ^If the Nth column returned by the statement is an expression or
  5158. ** subquery and is not a column value, then all of these functions return
  5159. ** NULL. ^These routine might also return NULL if a memory allocation error
  5160. ** occurs. ^Otherwise, they return the name of the attached database, table,
  5161. ** or column that query result column was extracted from.
  5162. **
  5163. ** ^As with all other SQLite APIs, those whose names end with "16" return
  5164. ** UTF-16 encoded strings and the other functions return UTF-8.
  5165. **
  5166. ** ^These APIs are only available if the library was compiled with the
  5167. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  5168. **
  5169. ** If two or more threads call one or more of these routines against the same
  5170. ** prepared statement and column at the same time then the results are
  5171. ** undefined.
  5172. **
  5173. ** If two or more threads call one or more
  5174. ** [sqlite3_column_database_name | column metadata interfaces]
  5175. ** for the same [prepared statement] and result column
  5176. ** at the same time then the results are undefined.
  5177. */
  5178. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  5179. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  5180. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  5181. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  5182. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  5183. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  5184. /*
  5185. ** CAPI3REF: Declared Datatype Of A Query Result
  5186. ** METHOD: sqlite3_stmt
  5187. **
  5188. ** ^(The first parameter is a [prepared statement].
  5189. ** If this statement is a [SELECT] statement and the Nth column of the
  5190. ** returned result set of that [SELECT] is a table column (not an
  5191. ** expression or subquery) then the declared type of the table
  5192. ** column is returned.)^ ^If the Nth column of the result set is an
  5193. ** expression or subquery, then a NULL pointer is returned.
  5194. ** ^The returned string is always UTF-8 encoded.
  5195. **
  5196. ** ^(For example, given the database schema:
  5197. **
  5198. ** CREATE TABLE t1(c1 VARIANT);
  5199. **
  5200. ** and the following statement to be compiled:
  5201. **
  5202. ** SELECT c1 + 1, c1 FROM t1;
  5203. **
  5204. ** this routine would return the string "VARIANT" for the second result
  5205. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  5206. **
  5207. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  5208. ** is declared to contain a particular type does not mean that the
  5209. ** data stored in that column is of the declared type. SQLite is
  5210. ** strongly typed, but the typing is dynamic not static. ^Type
  5211. ** is associated with individual values, not with the containers
  5212. ** used to hold those values.
  5213. */
  5214. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  5215. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  5216. /*
  5217. ** CAPI3REF: Evaluate An SQL Statement
  5218. ** METHOD: sqlite3_stmt
  5219. **
  5220. ** After a [prepared statement] has been prepared using any of
  5221. ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
  5222. ** or [sqlite3_prepare16_v3()] or one of the legacy
  5223. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  5224. ** must be called one or more times to evaluate the statement.
  5225. **
  5226. ** The details of the behavior of the sqlite3_step() interface depend
  5227. ** on whether the statement was prepared using the newer "vX" interfaces
  5228. ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
  5229. ** [sqlite3_prepare16_v2()] or the older legacy
  5230. ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  5231. ** new "vX" interface is recommended for new applications but the legacy
  5232. ** interface will continue to be supported.
  5233. **
  5234. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  5235. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  5236. ** ^With the "v2" interface, any of the other [result codes] or
  5237. ** [extended result codes] might be returned as well.
  5238. **
  5239. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  5240. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  5241. ** or occurs outside of an explicit transaction, then you can retry the
  5242. ** statement. If the statement is not a [COMMIT] and occurs within an
  5243. ** explicit transaction then you should rollback the transaction before
  5244. ** continuing.
  5245. **
  5246. ** ^[SQLITE_DONE] means that the statement has finished executing
  5247. ** successfully. sqlite3_step() should not be called again on this virtual
  5248. ** machine without first calling [sqlite3_reset()] to reset the virtual
  5249. ** machine back to its initial state.
  5250. **
  5251. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  5252. ** is returned each time a new row of data is ready for processing by the
  5253. ** caller. The values may be accessed using the [column access functions].
  5254. ** sqlite3_step() is called again to retrieve the next row of data.
  5255. **
  5256. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  5257. ** violation) has occurred. sqlite3_step() should not be called again on
  5258. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  5259. ** ^With the legacy interface, a more specific error code (for example,
  5260. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  5261. ** can be obtained by calling [sqlite3_reset()] on the
  5262. ** [prepared statement]. ^In the "v2" interface,
  5263. ** the more specific error code is returned directly by sqlite3_step().
  5264. **
  5265. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  5266. ** Perhaps it was called on a [prepared statement] that has
  5267. ** already been [sqlite3_finalize | finalized] or on one that had
  5268. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  5269. ** be the case that the same database connection is being used by two or
  5270. ** more threads at the same moment in time.
  5271. **
  5272. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  5273. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  5274. ** other than [SQLITE_ROW] before any subsequent invocation of
  5275. ** sqlite3_step(). Failure to reset the prepared statement using
  5276. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  5277. ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
  5278. ** sqlite3_step() began
  5279. ** calling [sqlite3_reset()] automatically in this circumstance rather
  5280. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  5281. ** break because any application that ever receives an SQLITE_MISUSE error
  5282. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  5283. ** can be used to restore the legacy behavior.
  5284. **
  5285. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  5286. ** API always returns a generic error code, [SQLITE_ERROR], following any
  5287. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  5288. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  5289. ** specific [error codes] that better describes the error.
  5290. ** We admit that this is a goofy design. The problem has been fixed
  5291. ** with the "v2" interface. If you prepare all of your SQL statements
  5292. ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
  5293. ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
  5294. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  5295. ** then the more specific [error codes] are returned directly
  5296. ** by sqlite3_step(). The use of the "vX" interfaces is recommended.
  5297. */
  5298. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  5299. /*
  5300. ** CAPI3REF: Number of columns in a result set
  5301. ** METHOD: sqlite3_stmt
  5302. **
  5303. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  5304. ** current row of the result set of [prepared statement] P.
  5305. ** ^If prepared statement P does not have results ready to return
  5306. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  5307. ** interfaces) then sqlite3_data_count(P) returns 0.
  5308. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  5309. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  5310. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  5311. ** will return non-zero if previous call to [sqlite3_step](P) returned
  5312. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  5313. ** where it always returns zero since each step of that multi-step
  5314. ** pragma returns 0 columns of data.
  5315. **
  5316. ** See also: [sqlite3_column_count()]
  5317. */
  5318. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  5319. /*
  5320. ** CAPI3REF: Fundamental Datatypes
  5321. ** KEYWORDS: SQLITE_TEXT
  5322. **
  5323. ** ^(Every value in SQLite has one of five fundamental datatypes:
  5324. **
  5325. ** <ul>
  5326. ** <li> 64-bit signed integer
  5327. ** <li> 64-bit IEEE floating point number
  5328. ** <li> string
  5329. ** <li> BLOB
  5330. ** <li> NULL
  5331. ** </ul>)^
  5332. **
  5333. ** These constants are codes for each of those types.
  5334. **
  5335. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  5336. ** for a completely different meaning. Software that links against both
  5337. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  5338. ** SQLITE_TEXT.
  5339. */
  5340. #define SQLITE_INTEGER 1
  5341. #define SQLITE_FLOAT 2
  5342. #define SQLITE_BLOB 4
  5343. #define SQLITE_NULL 5
  5344. #ifdef SQLITE_TEXT
  5345. # undef SQLITE_TEXT
  5346. #else
  5347. # define SQLITE_TEXT 3
  5348. #endif
  5349. #define SQLITE3_TEXT 3
  5350. /*
  5351. ** CAPI3REF: Result Values From A Query
  5352. ** KEYWORDS: {column access functions}
  5353. ** METHOD: sqlite3_stmt
  5354. **
  5355. ** <b>Summary:</b>
  5356. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5357. ** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
  5358. ** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
  5359. ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
  5360. ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
  5361. ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
  5362. ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
  5363. ** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
  5364. ** [sqlite3_value|unprotected sqlite3_value] object.
  5365. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5366. ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
  5367. ** or a UTF-8 TEXT result in bytes
  5368. ** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
  5369. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5370. ** TEXT in bytes
  5371. ** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
  5372. ** datatype of the result
  5373. ** </table></blockquote>
  5374. **
  5375. ** <b>Details:</b>
  5376. **
  5377. ** ^These routines return information about a single column of the current
  5378. ** result row of a query. ^In every case the first argument is a pointer
  5379. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  5380. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  5381. ** and the second argument is the index of the column for which information
  5382. ** should be returned. ^The leftmost column of the result set has the index 0.
  5383. ** ^The number of columns in the result can be determined using
  5384. ** [sqlite3_column_count()].
  5385. **
  5386. ** If the SQL statement does not currently point to a valid row, or if the
  5387. ** column index is out of range, the result is undefined.
  5388. ** These routines may only be called when the most recent call to
  5389. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  5390. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  5391. ** If any of these routines are called after [sqlite3_reset()] or
  5392. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  5393. ** something other than [SQLITE_ROW], the results are undefined.
  5394. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  5395. ** are called from a different thread while any of these routines
  5396. ** are pending, then the results are undefined.
  5397. **
  5398. ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
  5399. ** each return the value of a result column in a specific data format. If
  5400. ** the result column is not initially in the requested format (for example,
  5401. ** if the query returns an integer but the sqlite3_column_text() interface
  5402. ** is used to extract the value) then an automatic type conversion is performed.
  5403. **
  5404. ** ^The sqlite3_column_type() routine returns the
  5405. ** [SQLITE_INTEGER | datatype code] for the initial data type
  5406. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  5407. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
  5408. ** The return value of sqlite3_column_type() can be used to decide which
  5409. ** of the first six interface should be used to extract the column value.
  5410. ** The value returned by sqlite3_column_type() is only meaningful if no
  5411. ** automatic type conversions have occurred for the value in question.
  5412. ** After a type conversion, the result of calling sqlite3_column_type()
  5413. ** is undefined, though harmless. Future
  5414. ** versions of SQLite may change the behavior of sqlite3_column_type()
  5415. ** following a type conversion.
  5416. **
  5417. ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
  5418. ** or sqlite3_column_bytes16() interfaces can be used to determine the size
  5419. ** of that BLOB or string.
  5420. **
  5421. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  5422. ** routine returns the number of bytes in that BLOB or string.
  5423. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  5424. ** the string to UTF-8 and then returns the number of bytes.
  5425. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  5426. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  5427. ** the number of bytes in that string.
  5428. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  5429. **
  5430. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  5431. ** routine returns the number of bytes in that BLOB or string.
  5432. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  5433. ** the string to UTF-16 and then returns the number of bytes.
  5434. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  5435. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  5436. ** the number of bytes in that string.
  5437. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  5438. **
  5439. ** ^The values returned by [sqlite3_column_bytes()] and
  5440. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  5441. ** of the string. ^For clarity: the values returned by
  5442. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  5443. ** bytes in the string, not the number of characters.
  5444. **
  5445. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  5446. ** even empty strings, are always zero-terminated. ^The return
  5447. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  5448. **
  5449. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  5450. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  5451. ** an unprotected sqlite3_value object may only be used safely with
  5452. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  5453. ** If the [unprotected sqlite3_value] object returned by
  5454. ** [sqlite3_column_value()] is used in any other way, including calls
  5455. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  5456. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  5457. ** Hence, the sqlite3_column_value() interface
  5458. ** is normally only useful within the implementation of
  5459. ** [application-defined SQL functions] or [virtual tables], not within
  5460. ** top-level application code.
  5461. **
  5462. ** The these routines may attempt to convert the datatype of the result.
  5463. ** ^For example, if the internal representation is FLOAT and a text result
  5464. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  5465. ** conversion automatically. ^(The following table details the conversions
  5466. ** that are applied:
  5467. **
  5468. ** <blockquote>
  5469. ** <table border="1">
  5470. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  5471. **
  5472. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  5473. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  5474. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  5475. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  5476. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  5477. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  5478. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  5479. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  5480. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  5481. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  5482. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  5483. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  5484. ** <tr><td> TEXT <td> BLOB <td> No change
  5485. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  5486. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  5487. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  5488. ** </table>
  5489. ** </blockquote>)^
  5490. **
  5491. ** Note that when type conversions occur, pointers returned by prior
  5492. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  5493. ** sqlite3_column_text16() may be invalidated.
  5494. ** Type conversions and pointer invalidations might occur
  5495. ** in the following cases:
  5496. **
  5497. ** <ul>
  5498. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  5499. ** sqlite3_column_text16() is called. A zero-terminator might
  5500. ** need to be added to the string.</li>
  5501. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  5502. ** sqlite3_column_text16() is called. The content must be converted
  5503. ** to UTF-16.</li>
  5504. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  5505. ** sqlite3_column_text() is called. The content must be converted
  5506. ** to UTF-8.</li>
  5507. ** </ul>
  5508. **
  5509. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  5510. ** not invalidate a prior pointer, though of course the content of the buffer
  5511. ** that the prior pointer references will have been modified. Other kinds
  5512. ** of conversion are done in place when it is possible, but sometimes they
  5513. ** are not possible and in those cases prior pointers are invalidated.
  5514. **
  5515. ** The safest policy is to invoke these routines
  5516. ** in one of the following ways:
  5517. **
  5518. ** <ul>
  5519. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  5520. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  5521. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  5522. ** </ul>
  5523. **
  5524. ** In other words, you should call sqlite3_column_text(),
  5525. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  5526. ** into the desired format, then invoke sqlite3_column_bytes() or
  5527. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  5528. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  5529. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  5530. ** with calls to sqlite3_column_bytes().
  5531. **
  5532. ** ^The pointers returned are valid until a type conversion occurs as
  5533. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  5534. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  5535. ** and BLOBs is freed automatically. Do not pass the pointers returned
  5536. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  5537. ** [sqlite3_free()].
  5538. **
  5539. ** As long as the input parameters are correct, these routines will only
  5540. ** fail if an out-of-memory error occurs during a format conversion.
  5541. ** Only the following subset of interfaces are subject to out-of-memory
  5542. ** errors:
  5543. **
  5544. ** <ul>
  5545. ** <li> sqlite3_column_blob()
  5546. ** <li> sqlite3_column_text()
  5547. ** <li> sqlite3_column_text16()
  5548. ** <li> sqlite3_column_bytes()
  5549. ** <li> sqlite3_column_bytes16()
  5550. ** </ul>
  5551. **
  5552. ** If an out-of-memory error occurs, then the return value from these
  5553. ** routines is the same as if the column had contained an SQL NULL value.
  5554. ** Valid SQL NULL returns can be distinguished from out-of-memory errors
  5555. ** by invoking the [sqlite3_errcode()] immediately after the suspect
  5556. ** return value is obtained and before any
  5557. ** other SQLite interface is called on the same [database connection].
  5558. */
  5559. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  5560. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  5561. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  5562. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  5563. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  5564. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  5565. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  5566. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  5567. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  5568. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  5569. /*
  5570. ** CAPI3REF: Destroy A Prepared Statement Object
  5571. ** DESTRUCTOR: sqlite3_stmt
  5572. **
  5573. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  5574. ** ^If the most recent evaluation of the statement encountered no errors
  5575. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  5576. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  5577. ** sqlite3_finalize(S) returns the appropriate [error code] or
  5578. ** [extended error code].
  5579. **
  5580. ** ^The sqlite3_finalize(S) routine can be called at any point during
  5581. ** the life cycle of [prepared statement] S:
  5582. ** before statement S is ever evaluated, after
  5583. ** one or more calls to [sqlite3_reset()], or after any call
  5584. ** to [sqlite3_step()] regardless of whether or not the statement has
  5585. ** completed execution.
  5586. **
  5587. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  5588. **
  5589. ** The application must finalize every [prepared statement] in order to avoid
  5590. ** resource leaks. It is a grievous error for the application to try to use
  5591. ** a prepared statement after it has been finalized. Any use of a prepared
  5592. ** statement after it has been finalized can result in undefined and
  5593. ** undesirable behavior such as segfaults and heap corruption.
  5594. */
  5595. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  5596. /*
  5597. ** CAPI3REF: Reset A Prepared Statement Object
  5598. ** METHOD: sqlite3_stmt
  5599. **
  5600. ** The sqlite3_reset() function is called to reset a [prepared statement]
  5601. ** object back to its initial state, ready to be re-executed.
  5602. ** ^Any SQL statement variables that had values bound to them using
  5603. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  5604. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  5605. **
  5606. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  5607. ** back to the beginning of its program.
  5608. **
  5609. ** ^If the most recent call to [sqlite3_step(S)] for the
  5610. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  5611. ** or if [sqlite3_step(S)] has never before been called on S,
  5612. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  5613. **
  5614. ** ^If the most recent call to [sqlite3_step(S)] for the
  5615. ** [prepared statement] S indicated an error, then
  5616. ** [sqlite3_reset(S)] returns an appropriate [error code].
  5617. **
  5618. ** ^The [sqlite3_reset(S)] interface does not change the values
  5619. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  5620. */
  5621. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  5622. /*
  5623. ** CAPI3REF: Create Or Redefine SQL Functions
  5624. ** KEYWORDS: {function creation routines}
  5625. ** KEYWORDS: {application-defined SQL function}
  5626. ** KEYWORDS: {application-defined SQL functions}
  5627. ** METHOD: sqlite3
  5628. **
  5629. ** ^These functions (collectively known as "function creation routines")
  5630. ** are used to add SQL functions or aggregates or to redefine the behavior
  5631. ** of existing SQL functions or aggregates. The only differences between
  5632. ** the three "sqlite3_create_function*" routines are the text encoding
  5633. ** expected for the second parameter (the name of the function being
  5634. ** created) and the presence or absence of a destructor callback for
  5635. ** the application data pointer. Function sqlite3_create_window_function()
  5636. ** is similar, but allows the user to supply the extra callback functions
  5637. ** needed by [aggregate window functions].
  5638. **
  5639. ** ^The first parameter is the [database connection] to which the SQL
  5640. ** function is to be added. ^If an application uses more than one database
  5641. ** connection then application-defined SQL functions must be added
  5642. ** to each database connection separately.
  5643. **
  5644. ** ^The second parameter is the name of the SQL function to be created or
  5645. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  5646. ** representation, exclusive of the zero-terminator. ^Note that the name
  5647. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  5648. ** ^Any attempt to create a function with a longer name
  5649. ** will result in [SQLITE_MISUSE] being returned.
  5650. **
  5651. ** ^The third parameter (nArg)
  5652. ** is the number of arguments that the SQL function or
  5653. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  5654. ** aggregate may take any number of arguments between 0 and the limit
  5655. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  5656. ** parameter is less than -1 or greater than 127 then the behavior is
  5657. ** undefined.
  5658. **
  5659. ** ^The fourth parameter, eTextRep, specifies what
  5660. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  5661. ** its parameters. The application should set this parameter to
  5662. ** [SQLITE_UTF16LE] if the function implementation invokes
  5663. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  5664. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  5665. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  5666. ** otherwise. ^The same SQL function may be registered multiple times using
  5667. ** different preferred text encodings, with different implementations for
  5668. ** each encoding.
  5669. ** ^When multiple implementations of the same function are available, SQLite
  5670. ** will pick the one that involves the least amount of data conversion.
  5671. **
  5672. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  5673. ** to signal that the function will always return the same result given
  5674. ** the same inputs within a single SQL statement. Most SQL functions are
  5675. ** deterministic. The built-in [random()] SQL function is an example of a
  5676. ** function that is not deterministic. The SQLite query planner is able to
  5677. ** perform additional optimizations on deterministic functions, so use
  5678. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  5679. **
  5680. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  5681. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  5682. **
  5683. ** ^The sixth, seventh and eighth parameters passed to the three
  5684. ** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
  5685. ** pointers to C-language functions that implement the SQL function or
  5686. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  5687. ** callback only; NULL pointers must be passed as the xStep and xFinal
  5688. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  5689. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  5690. ** SQL function or aggregate, pass NULL pointers for all three function
  5691. ** callbacks.
  5692. **
  5693. ** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
  5694. ** and xInverse) passed to sqlite3_create_window_function are pointers to
  5695. ** C-language callbacks that implement the new function. xStep and xFinal
  5696. ** must both be non-NULL. xValue and xInverse may either both be NULL, in
  5697. ** which case a regular aggregate function is created, or must both be
  5698. ** non-NULL, in which case the new function may be used as either an aggregate
  5699. ** or aggregate window function. More details regarding the implementation
  5700. ** of aggregate window functions are
  5701. ** [user-defined window functions|available here].
  5702. **
  5703. ** ^(If the final parameter to sqlite3_create_function_v2() or
  5704. ** sqlite3_create_window_function() is not NULL, then it is destructor for
  5705. ** the application data pointer. The destructor is invoked when the function
  5706. ** is deleted, either by being overloaded or when the database connection
  5707. ** closes.)^ ^The destructor is also invoked if the call to
  5708. ** sqlite3_create_function_v2() fails. ^When the destructor callback is
  5709. ** invoked, it is passed a single argument which is a copy of the application
  5710. ** data pointer which was the fifth parameter to sqlite3_create_function_v2().
  5711. **
  5712. ** ^It is permitted to register multiple implementations of the same
  5713. ** functions with the same name but with either differing numbers of
  5714. ** arguments or differing preferred text encodings. ^SQLite will use
  5715. ** the implementation that most closely matches the way in which the
  5716. ** SQL function is used. ^A function implementation with a non-negative
  5717. ** nArg parameter is a better match than a function implementation with
  5718. ** a negative nArg. ^A function where the preferred text encoding
  5719. ** matches the database encoding is a better
  5720. ** match than a function where the encoding is different.
  5721. ** ^A function where the encoding difference is between UTF16le and UTF16be
  5722. ** is a closer match than a function where the encoding difference is
  5723. ** between UTF8 and UTF16.
  5724. **
  5725. ** ^Built-in functions may be overloaded by new application-defined functions.
  5726. **
  5727. ** ^An application-defined function is permitted to call other
  5728. ** SQLite interfaces. However, such calls must not
  5729. ** close the database connection nor finalize or reset the prepared
  5730. ** statement in which the function is running.
  5731. */
  5732. SQLITE_API int sqlite3_create_function(
  5733. sqlite3 *db,
  5734. const char *zFunctionName,
  5735. int nArg,
  5736. int eTextRep,
  5737. void *pApp,
  5738. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5739. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5740. void (*xFinal)(sqlite3_context*)
  5741. );
  5742. SQLITE_API int sqlite3_create_function16(
  5743. sqlite3 *db,
  5744. const void *zFunctionName,
  5745. int nArg,
  5746. int eTextRep,
  5747. void *pApp,
  5748. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5749. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5750. void (*xFinal)(sqlite3_context*)
  5751. );
  5752. SQLITE_API int sqlite3_create_function_v2(
  5753. sqlite3 *db,
  5754. const char *zFunctionName,
  5755. int nArg,
  5756. int eTextRep,
  5757. void *pApp,
  5758. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5759. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5760. void (*xFinal)(sqlite3_context*),
  5761. void(*xDestroy)(void*)
  5762. );
  5763. SQLITE_API int sqlite3_create_window_function(
  5764. sqlite3 *db,
  5765. const char *zFunctionName,
  5766. int nArg,
  5767. int eTextRep,
  5768. void *pApp,
  5769. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5770. void (*xFinal)(sqlite3_context*),
  5771. void (*xValue)(sqlite3_context*),
  5772. void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
  5773. void(*xDestroy)(void*)
  5774. );
  5775. /*
  5776. ** CAPI3REF: Text Encodings
  5777. **
  5778. ** These constant define integer codes that represent the various
  5779. ** text encodings supported by SQLite.
  5780. */
  5781. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  5782. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  5783. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  5784. #define SQLITE_UTF16 4 /* Use native byte order */
  5785. #define SQLITE_ANY 5 /* Deprecated */
  5786. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  5787. /*
  5788. ** CAPI3REF: Function Flags
  5789. **
  5790. ** These constants may be ORed together with the
  5791. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  5792. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  5793. ** [sqlite3_create_function_v2()].
  5794. */
  5795. #define SQLITE_DETERMINISTIC 0x800
  5796. /*
  5797. ** CAPI3REF: Deprecated Functions
  5798. ** DEPRECATED
  5799. **
  5800. ** These functions are [deprecated]. In order to maintain
  5801. ** backwards compatibility with older code, these functions continue
  5802. ** to be supported. However, new applications should avoid
  5803. ** the use of these functions. To encourage programmers to avoid
  5804. ** these functions, we will not explain what they do.
  5805. */
  5806. #ifndef SQLITE_OMIT_DEPRECATED
  5807. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  5808. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  5809. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  5810. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  5811. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  5812. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  5813. void*,sqlite3_int64);
  5814. #endif
  5815. /*
  5816. ** CAPI3REF: Obtaining SQL Values
  5817. ** METHOD: sqlite3_value
  5818. **
  5819. ** <b>Summary:</b>
  5820. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5821. ** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
  5822. ** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
  5823. ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
  5824. ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
  5825. ** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
  5826. ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
  5827. ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
  5828. ** the native byteorder
  5829. ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
  5830. ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
  5831. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5832. ** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
  5833. ** or a UTF-8 TEXT in bytes
  5834. ** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
  5835. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5836. ** TEXT in bytes
  5837. ** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
  5838. ** datatype of the value
  5839. ** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
  5840. ** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
  5841. ** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
  5842. ** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
  5843. ** against a virtual table.
  5844. ** </table></blockquote>
  5845. **
  5846. ** <b>Details:</b>
  5847. **
  5848. ** These routines extract type, size, and content information from
  5849. ** [protected sqlite3_value] objects. Protected sqlite3_value objects
  5850. ** are used to pass parameter information into implementation of
  5851. ** [application-defined SQL functions] and [virtual tables].
  5852. **
  5853. ** These routines work only with [protected sqlite3_value] objects.
  5854. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  5855. ** is not threadsafe.
  5856. **
  5857. ** ^These routines work just like the corresponding [column access functions]
  5858. ** except that these routines take a single [protected sqlite3_value] object
  5859. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  5860. **
  5861. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  5862. ** in the native byte-order of the host machine. ^The
  5863. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  5864. ** extract UTF-16 strings as big-endian and little-endian respectively.
  5865. **
  5866. ** ^If [sqlite3_value] object V was initialized
  5867. ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
  5868. ** and if X and Y are strings that compare equal according to strcmp(X,Y),
  5869. ** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
  5870. ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
  5871. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  5872. **
  5873. ** ^(The sqlite3_value_type(V) interface returns the
  5874. ** [SQLITE_INTEGER | datatype code] for the initial datatype of the
  5875. ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
  5876. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
  5877. ** Other interfaces might change the datatype for an sqlite3_value object.
  5878. ** For example, if the datatype is initially SQLITE_INTEGER and
  5879. ** sqlite3_value_text(V) is called to extract a text value for that
  5880. ** integer, then subsequent calls to sqlite3_value_type(V) might return
  5881. ** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
  5882. ** occurs is undefined and may change from one release of SQLite to the next.
  5883. **
  5884. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  5885. ** numeric affinity to the value. This means that an attempt is
  5886. ** made to convert the value to an integer or floating point. If
  5887. ** such a conversion is possible without loss of information (in other
  5888. ** words, if the value is a string that looks like a number)
  5889. ** then the conversion is performed. Otherwise no conversion occurs.
  5890. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  5891. **
  5892. ** ^Within the [xUpdate] method of a [virtual table], the
  5893. ** sqlite3_value_nochange(X) interface returns true if and only if
  5894. ** the column corresponding to X is unchanged by the UPDATE operation
  5895. ** that the xUpdate method call was invoked to implement and if
  5896. ** and the prior [xColumn] method call that was invoked to extracted
  5897. ** the value for that column returned without setting a result (probably
  5898. ** because it queried [sqlite3_vtab_nochange()] and found that the column
  5899. ** was unchanging). ^Within an [xUpdate] method, any value for which
  5900. ** sqlite3_value_nochange(X) is true will in all other respects appear
  5901. ** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other
  5902. ** than within an [xUpdate] method call for an UPDATE statement, then
  5903. ** the return value is arbitrary and meaningless.
  5904. **
  5905. ** Please pay particular attention to the fact that the pointer returned
  5906. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  5907. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  5908. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  5909. ** or [sqlite3_value_text16()].
  5910. **
  5911. ** These routines must be called from the same thread as
  5912. ** the SQL function that supplied the [sqlite3_value*] parameters.
  5913. **
  5914. ** As long as the input parameter is correct, these routines can only
  5915. ** fail if an out-of-memory error occurs during a format conversion.
  5916. ** Only the following subset of interfaces are subject to out-of-memory
  5917. ** errors:
  5918. **
  5919. ** <ul>
  5920. ** <li> sqlite3_value_blob()
  5921. ** <li> sqlite3_value_text()
  5922. ** <li> sqlite3_value_text16()
  5923. ** <li> sqlite3_value_text16le()
  5924. ** <li> sqlite3_value_text16be()
  5925. ** <li> sqlite3_value_bytes()
  5926. ** <li> sqlite3_value_bytes16()
  5927. ** </ul>
  5928. **
  5929. ** If an out-of-memory error occurs, then the return value from these
  5930. ** routines is the same as if the column had contained an SQL NULL value.
  5931. ** Valid SQL NULL returns can be distinguished from out-of-memory errors
  5932. ** by invoking the [sqlite3_errcode()] immediately after the suspect
  5933. ** return value is obtained and before any
  5934. ** other SQLite interface is called on the same [database connection].
  5935. */
  5936. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  5937. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  5938. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  5939. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  5940. SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
  5941. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  5942. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  5943. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  5944. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  5945. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  5946. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  5947. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  5948. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  5949. SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
  5950. /*
  5951. ** CAPI3REF: Finding The Subtype Of SQL Values
  5952. ** METHOD: sqlite3_value
  5953. **
  5954. ** The sqlite3_value_subtype(V) function returns the subtype for
  5955. ** an [application-defined SQL function] argument V. The subtype
  5956. ** information can be used to pass a limited amount of context from
  5957. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  5958. ** routine to set the subtype for the return value of an SQL function.
  5959. */
  5960. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
  5961. /*
  5962. ** CAPI3REF: Copy And Free SQL Values
  5963. ** METHOD: sqlite3_value
  5964. **
  5965. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  5966. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  5967. ** is a [protected sqlite3_value] object even if the input is not.
  5968. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  5969. ** memory allocation fails.
  5970. **
  5971. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  5972. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  5973. ** then sqlite3_value_free(V) is a harmless no-op.
  5974. */
  5975. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
  5976. SQLITE_API void sqlite3_value_free(sqlite3_value*);
  5977. /*
  5978. ** CAPI3REF: Obtain Aggregate Function Context
  5979. ** METHOD: sqlite3_context
  5980. **
  5981. ** Implementations of aggregate SQL functions use this
  5982. ** routine to allocate memory for storing their state.
  5983. **
  5984. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  5985. ** for a particular aggregate function, SQLite
  5986. ** allocates N of memory, zeroes out that memory, and returns a pointer
  5987. ** to the new memory. ^On second and subsequent calls to
  5988. ** sqlite3_aggregate_context() for the same aggregate function instance,
  5989. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  5990. ** called once for each invocation of the xStep callback and then one
  5991. ** last time when the xFinal callback is invoked. ^(When no rows match
  5992. ** an aggregate query, the xStep() callback of the aggregate function
  5993. ** implementation is never called and xFinal() is called exactly once.
  5994. ** In those cases, sqlite3_aggregate_context() might be called for the
  5995. ** first time from within xFinal().)^
  5996. **
  5997. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  5998. ** when first called if N is less than or equal to zero or if a memory
  5999. ** allocate error occurs.
  6000. **
  6001. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  6002. ** determined by the N parameter on first successful call. Changing the
  6003. ** value of N in subsequent call to sqlite3_aggregate_context() within
  6004. ** the same aggregate function instance will not resize the memory
  6005. ** allocation.)^ Within the xFinal callback, it is customary to set
  6006. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  6007. ** pointless memory allocations occur.
  6008. **
  6009. ** ^SQLite automatically frees the memory allocated by
  6010. ** sqlite3_aggregate_context() when the aggregate query concludes.
  6011. **
  6012. ** The first parameter must be a copy of the
  6013. ** [sqlite3_context | SQL function context] that is the first parameter
  6014. ** to the xStep or xFinal callback routine that implements the aggregate
  6015. ** function.
  6016. **
  6017. ** This routine must be called from the same thread in which
  6018. ** the aggregate SQL function is running.
  6019. */
  6020. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  6021. /*
  6022. ** CAPI3REF: User Data For Functions
  6023. ** METHOD: sqlite3_context
  6024. **
  6025. ** ^The sqlite3_user_data() interface returns a copy of
  6026. ** the pointer that was the pUserData parameter (the 5th parameter)
  6027. ** of the [sqlite3_create_function()]
  6028. ** and [sqlite3_create_function16()] routines that originally
  6029. ** registered the application defined function.
  6030. **
  6031. ** This routine must be called from the same thread in which
  6032. ** the application-defined function is running.
  6033. */
  6034. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  6035. /*
  6036. ** CAPI3REF: Database Connection For Functions
  6037. ** METHOD: sqlite3_context
  6038. **
  6039. ** ^The sqlite3_context_db_handle() interface returns a copy of
  6040. ** the pointer to the [database connection] (the 1st parameter)
  6041. ** of the [sqlite3_create_function()]
  6042. ** and [sqlite3_create_function16()] routines that originally
  6043. ** registered the application defined function.
  6044. */
  6045. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  6046. /*
  6047. ** CAPI3REF: Function Auxiliary Data
  6048. ** METHOD: sqlite3_context
  6049. **
  6050. ** These functions may be used by (non-aggregate) SQL functions to
  6051. ** associate metadata with argument values. If the same value is passed to
  6052. ** multiple invocations of the same SQL function during query execution, under
  6053. ** some circumstances the associated metadata may be preserved. An example
  6054. ** of where this might be useful is in a regular-expression matching
  6055. ** function. The compiled version of the regular expression can be stored as
  6056. ** metadata associated with the pattern string.
  6057. ** Then as long as the pattern string remains the same,
  6058. ** the compiled regular expression can be reused on multiple
  6059. ** invocations of the same function.
  6060. **
  6061. ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
  6062. ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
  6063. ** value to the application-defined function. ^N is zero for the left-most
  6064. ** function argument. ^If there is no metadata
  6065. ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
  6066. ** returns a NULL pointer.
  6067. **
  6068. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  6069. ** argument of the application-defined function. ^Subsequent
  6070. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  6071. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  6072. ** NULL if the metadata has been discarded.
  6073. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  6074. ** SQLite will invoke the destructor function X with parameter P exactly
  6075. ** once, when the metadata is discarded.
  6076. ** SQLite is free to discard the metadata at any time, including: <ul>
  6077. ** <li> ^(when the corresponding function parameter changes)^, or
  6078. ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  6079. ** SQL statement)^, or
  6080. ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
  6081. ** parameter)^, or
  6082. ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
  6083. ** allocation error occurs.)^ </ul>
  6084. **
  6085. ** Note the last bullet in particular. The destructor X in
  6086. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  6087. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  6088. ** should be called near the end of the function implementation and the
  6089. ** function implementation should not make any use of P after
  6090. ** sqlite3_set_auxdata() has been called.
  6091. **
  6092. ** ^(In practice, metadata is preserved between function calls for
  6093. ** function parameters that are compile-time constants, including literal
  6094. ** values and [parameters] and expressions composed from the same.)^
  6095. **
  6096. ** The value of the N parameter to these interfaces should be non-negative.
  6097. ** Future enhancements may make use of negative N values to define new
  6098. ** kinds of function caching behavior.
  6099. **
  6100. ** These routines must be called from the same thread in which
  6101. ** the SQL function is running.
  6102. */
  6103. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  6104. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  6105. /*
  6106. ** CAPI3REF: Constants Defining Special Destructor Behavior
  6107. **
  6108. ** These are special values for the destructor that is passed in as the
  6109. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  6110. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  6111. ** and will never change. It does not need to be destroyed. ^The
  6112. ** SQLITE_TRANSIENT value means that the content will likely change in
  6113. ** the near future and that SQLite should make its own private copy of
  6114. ** the content before returning.
  6115. **
  6116. ** The typedef is necessary to work around problems in certain
  6117. ** C++ compilers.
  6118. */
  6119. typedef void (*sqlite3_destructor_type)(void*);
  6120. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  6121. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  6122. /*
  6123. ** CAPI3REF: Setting The Result Of An SQL Function
  6124. ** METHOD: sqlite3_context
  6125. **
  6126. ** These routines are used by the xFunc or xFinal callbacks that
  6127. ** implement SQL functions and aggregates. See
  6128. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  6129. ** for additional information.
  6130. **
  6131. ** These functions work very much like the [parameter binding] family of
  6132. ** functions used to bind values to host parameters in prepared statements.
  6133. ** Refer to the [SQL parameter] documentation for additional information.
  6134. **
  6135. ** ^The sqlite3_result_blob() interface sets the result from
  6136. ** an application-defined function to be the BLOB whose content is pointed
  6137. ** to by the second parameter and which is N bytes long where N is the
  6138. ** third parameter.
  6139. **
  6140. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  6141. ** interfaces set the result of the application-defined function to be
  6142. ** a BLOB containing all zero bytes and N bytes in size.
  6143. **
  6144. ** ^The sqlite3_result_double() interface sets the result from
  6145. ** an application-defined function to be a floating point value specified
  6146. ** by its 2nd argument.
  6147. **
  6148. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  6149. ** cause the implemented SQL function to throw an exception.
  6150. ** ^SQLite uses the string pointed to by the
  6151. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  6152. ** as the text of an error message. ^SQLite interprets the error
  6153. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  6154. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  6155. ** byte order. ^If the third parameter to sqlite3_result_error()
  6156. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  6157. ** message all text up through the first zero character.
  6158. ** ^If the third parameter to sqlite3_result_error() or
  6159. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  6160. ** bytes (not characters) from the 2nd parameter as the error message.
  6161. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  6162. ** routines make a private copy of the error message text before
  6163. ** they return. Hence, the calling function can deallocate or
  6164. ** modify the text after they return without harm.
  6165. ** ^The sqlite3_result_error_code() function changes the error code
  6166. ** returned by SQLite as a result of an error in a function. ^By default,
  6167. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  6168. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  6169. **
  6170. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  6171. ** error indicating that a string or BLOB is too long to represent.
  6172. **
  6173. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  6174. ** error indicating that a memory allocation failed.
  6175. **
  6176. ** ^The sqlite3_result_int() interface sets the return value
  6177. ** of the application-defined function to be the 32-bit signed integer
  6178. ** value given in the 2nd argument.
  6179. ** ^The sqlite3_result_int64() interface sets the return value
  6180. ** of the application-defined function to be the 64-bit signed integer
  6181. ** value given in the 2nd argument.
  6182. **
  6183. ** ^The sqlite3_result_null() interface sets the return value
  6184. ** of the application-defined function to be NULL.
  6185. **
  6186. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  6187. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  6188. ** set the return value of the application-defined function to be
  6189. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  6190. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  6191. ** ^The sqlite3_result_text64() interface sets the return value of an
  6192. ** application-defined function to be a text string in an encoding
  6193. ** specified by the fifth (and last) parameter, which must be one
  6194. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  6195. ** ^SQLite takes the text result from the application from
  6196. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  6197. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6198. ** is negative, then SQLite takes result text from the 2nd parameter
  6199. ** through the first zero character.
  6200. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6201. ** is non-negative, then as many bytes (not characters) of the text
  6202. ** pointed to by the 2nd parameter are taken as the application-defined
  6203. ** function result. If the 3rd parameter is non-negative, then it
  6204. ** must be the byte offset into the string where the NUL terminator would
  6205. ** appear if the string where NUL terminated. If any NUL characters occur
  6206. ** in the string at a byte offset that is less than the value of the 3rd
  6207. ** parameter, then the resulting string will contain embedded NULs and the
  6208. ** result of expressions operating on strings with embedded NULs is undefined.
  6209. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6210. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  6211. ** function as the destructor on the text or BLOB result when it has
  6212. ** finished using that result.
  6213. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  6214. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  6215. ** assumes that the text or BLOB result is in constant space and does not
  6216. ** copy the content of the parameter nor call a destructor on the content
  6217. ** when it has finished using that result.
  6218. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6219. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  6220. ** then SQLite makes a copy of the result into space obtained
  6221. ** from [sqlite3_malloc()] before it returns.
  6222. **
  6223. ** ^The sqlite3_result_value() interface sets the result of
  6224. ** the application-defined function to be a copy of the
  6225. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  6226. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  6227. ** so that the [sqlite3_value] specified in the parameter may change or
  6228. ** be deallocated after sqlite3_result_value() returns without harm.
  6229. ** ^A [protected sqlite3_value] object may always be used where an
  6230. ** [unprotected sqlite3_value] object is required, so either
  6231. ** kind of [sqlite3_value] object can be used with this interface.
  6232. **
  6233. ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
  6234. ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
  6235. ** also associates the host-language pointer P or type T with that
  6236. ** NULL value such that the pointer can be retrieved within an
  6237. ** [application-defined SQL function] using [sqlite3_value_pointer()].
  6238. ** ^If the D parameter is not NULL, then it is a pointer to a destructor
  6239. ** for the P parameter. ^SQLite invokes D with P as its only argument
  6240. ** when SQLite is finished with P. The T parameter should be a static
  6241. ** string and preferably a string literal. The sqlite3_result_pointer()
  6242. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  6243. **
  6244. ** If these routines are called from within the different thread
  6245. ** than the one containing the application-defined function that received
  6246. ** the [sqlite3_context] pointer, the results are undefined.
  6247. */
  6248. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  6249. SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
  6250. sqlite3_uint64,void(*)(void*));
  6251. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  6252. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  6253. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  6254. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  6255. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  6256. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  6257. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  6258. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  6259. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  6260. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  6261. SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  6262. void(*)(void*), unsigned char encoding);
  6263. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  6264. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  6265. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  6266. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  6267. SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
  6268. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  6269. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  6270. /*
  6271. ** CAPI3REF: Setting The Subtype Of An SQL Function
  6272. ** METHOD: sqlite3_context
  6273. **
  6274. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  6275. ** the result from the [application-defined SQL function] with
  6276. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  6277. ** of the subtype T are preserved in current versions of SQLite;
  6278. ** higher order bits are discarded.
  6279. ** The number of subtype bytes preserved by SQLite might increase
  6280. ** in future releases of SQLite.
  6281. */
  6282. SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
  6283. /*
  6284. ** CAPI3REF: Define New Collating Sequences
  6285. ** METHOD: sqlite3
  6286. **
  6287. ** ^These functions add, remove, or modify a [collation] associated
  6288. ** with the [database connection] specified as the first argument.
  6289. **
  6290. ** ^The name of the collation is a UTF-8 string
  6291. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  6292. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  6293. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  6294. ** considered to be the same name.
  6295. **
  6296. ** ^(The third argument (eTextRep) must be one of the constants:
  6297. ** <ul>
  6298. ** <li> [SQLITE_UTF8],
  6299. ** <li> [SQLITE_UTF16LE],
  6300. ** <li> [SQLITE_UTF16BE],
  6301. ** <li> [SQLITE_UTF16], or
  6302. ** <li> [SQLITE_UTF16_ALIGNED].
  6303. ** </ul>)^
  6304. ** ^The eTextRep argument determines the encoding of strings passed
  6305. ** to the collating function callback, xCallback.
  6306. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  6307. ** force strings to be UTF16 with native byte order.
  6308. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  6309. ** on an even byte address.
  6310. **
  6311. ** ^The fourth argument, pArg, is an application data pointer that is passed
  6312. ** through as the first argument to the collating function callback.
  6313. **
  6314. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  6315. ** ^Multiple collating functions can be registered using the same name but
  6316. ** with different eTextRep parameters and SQLite will use whichever
  6317. ** function requires the least amount of data transformation.
  6318. ** ^If the xCallback argument is NULL then the collating function is
  6319. ** deleted. ^When all collating functions having the same name are deleted,
  6320. ** that collation is no longer usable.
  6321. **
  6322. ** ^The collating function callback is invoked with a copy of the pArg
  6323. ** application data pointer and with two strings in the encoding specified
  6324. ** by the eTextRep argument. The collating function must return an
  6325. ** integer that is negative, zero, or positive
  6326. ** if the first string is less than, equal to, or greater than the second,
  6327. ** respectively. A collating function must always return the same answer
  6328. ** given the same inputs. If two or more collating functions are registered
  6329. ** to the same collation name (using different eTextRep values) then all
  6330. ** must give an equivalent answer when invoked with equivalent strings.
  6331. ** The collating function must obey the following properties for all
  6332. ** strings A, B, and C:
  6333. **
  6334. ** <ol>
  6335. ** <li> If A==B then B==A.
  6336. ** <li> If A==B and B==C then A==C.
  6337. ** <li> If A&lt;B THEN B&gt;A.
  6338. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  6339. ** </ol>
  6340. **
  6341. ** If a collating function fails any of the above constraints and that
  6342. ** collating function is registered and used, then the behavior of SQLite
  6343. ** is undefined.
  6344. **
  6345. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  6346. ** with the addition that the xDestroy callback is invoked on pArg when
  6347. ** the collating function is deleted.
  6348. ** ^Collating functions are deleted when they are overridden by later
  6349. ** calls to the collation creation functions or when the
  6350. ** [database connection] is closed using [sqlite3_close()].
  6351. **
  6352. ** ^The xDestroy callback is <u>not</u> called if the
  6353. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  6354. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  6355. ** check the return code and dispose of the application data pointer
  6356. ** themselves rather than expecting SQLite to deal with it for them.
  6357. ** This is different from every other SQLite interface. The inconsistency
  6358. ** is unfortunate but cannot be changed without breaking backwards
  6359. ** compatibility.
  6360. **
  6361. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  6362. */
  6363. SQLITE_API int sqlite3_create_collation(
  6364. sqlite3*,
  6365. const char *zName,
  6366. int eTextRep,
  6367. void *pArg,
  6368. int(*xCompare)(void*,int,const void*,int,const void*)
  6369. );
  6370. SQLITE_API int sqlite3_create_collation_v2(
  6371. sqlite3*,
  6372. const char *zName,
  6373. int eTextRep,
  6374. void *pArg,
  6375. int(*xCompare)(void*,int,const void*,int,const void*),
  6376. void(*xDestroy)(void*)
  6377. );
  6378. SQLITE_API int sqlite3_create_collation16(
  6379. sqlite3*,
  6380. const void *zName,
  6381. int eTextRep,
  6382. void *pArg,
  6383. int(*xCompare)(void*,int,const void*,int,const void*)
  6384. );
  6385. /*
  6386. ** CAPI3REF: Collation Needed Callbacks
  6387. ** METHOD: sqlite3
  6388. **
  6389. ** ^To avoid having to register all collation sequences before a database
  6390. ** can be used, a single callback function may be registered with the
  6391. ** [database connection] to be invoked whenever an undefined collation
  6392. ** sequence is required.
  6393. **
  6394. ** ^If the function is registered using the sqlite3_collation_needed() API,
  6395. ** then it is passed the names of undefined collation sequences as strings
  6396. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  6397. ** the names are passed as UTF-16 in machine native byte order.
  6398. ** ^A call to either function replaces the existing collation-needed callback.
  6399. **
  6400. ** ^(When the callback is invoked, the first argument passed is a copy
  6401. ** of the second argument to sqlite3_collation_needed() or
  6402. ** sqlite3_collation_needed16(). The second argument is the database
  6403. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  6404. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  6405. ** sequence function required. The fourth parameter is the name of the
  6406. ** required collation sequence.)^
  6407. **
  6408. ** The callback function should register the desired collation using
  6409. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  6410. ** [sqlite3_create_collation_v2()].
  6411. */
  6412. SQLITE_API int sqlite3_collation_needed(
  6413. sqlite3*,
  6414. void*,
  6415. void(*)(void*,sqlite3*,int eTextRep,const char*)
  6416. );
  6417. SQLITE_API int sqlite3_collation_needed16(
  6418. sqlite3*,
  6419. void*,
  6420. void(*)(void*,sqlite3*,int eTextRep,const void*)
  6421. );
  6422. #ifdef SQLITE_HAS_CODEC
  6423. /*
  6424. ** Specify the key for an encrypted database. This routine should be
  6425. ** called right after sqlite3_open().
  6426. **
  6427. ** The code to implement this API is not available in the public release
  6428. ** of SQLite.
  6429. */
  6430. SQLITE_API int sqlite3_key(
  6431. sqlite3 *db, /* Database to be rekeyed */
  6432. const void *pKey, int nKey /* The key */
  6433. );
  6434. SQLITE_API int sqlite3_key_v2(
  6435. sqlite3 *db, /* Database to be rekeyed */
  6436. const char *zDbName, /* Name of the database */
  6437. const void *pKey, int nKey /* The key */
  6438. );
  6439. /*
  6440. ** Change the key on an open database. If the current database is not
  6441. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  6442. ** database is decrypted.
  6443. **
  6444. ** The code to implement this API is not available in the public release
  6445. ** of SQLite.
  6446. */
  6447. SQLITE_API int sqlite3_rekey(
  6448. sqlite3 *db, /* Database to be rekeyed */
  6449. const void *pKey, int nKey /* The new key */
  6450. );
  6451. SQLITE_API int sqlite3_rekey_v2(
  6452. sqlite3 *db, /* Database to be rekeyed */
  6453. const char *zDbName, /* Name of the database */
  6454. const void *pKey, int nKey /* The new key */
  6455. );
  6456. /*
  6457. ** Specify the activation key for a SEE database. Unless
  6458. ** activated, none of the SEE routines will work.
  6459. */
  6460. SQLITE_API void sqlite3_activate_see(
  6461. const char *zPassPhrase /* Activation phrase */
  6462. );
  6463. #endif
  6464. #ifdef SQLITE_ENABLE_CEROD
  6465. /*
  6466. ** Specify the activation key for a CEROD database. Unless
  6467. ** activated, none of the CEROD routines will work.
  6468. */
  6469. SQLITE_API void sqlite3_activate_cerod(
  6470. const char *zPassPhrase /* Activation phrase */
  6471. );
  6472. #endif
  6473. /*
  6474. ** CAPI3REF: Suspend Execution For A Short Time
  6475. **
  6476. ** The sqlite3_sleep() function causes the current thread to suspend execution
  6477. ** for at least a number of milliseconds specified in its parameter.
  6478. **
  6479. ** If the operating system does not support sleep requests with
  6480. ** millisecond time resolution, then the time will be rounded up to
  6481. ** the nearest second. The number of milliseconds of sleep actually
  6482. ** requested from the operating system is returned.
  6483. **
  6484. ** ^SQLite implements this interface by calling the xSleep()
  6485. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  6486. ** of the default VFS is not implemented correctly, or not implemented at
  6487. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  6488. ** in the previous paragraphs.
  6489. */
  6490. SQLITE_API int sqlite3_sleep(int);
  6491. /*
  6492. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  6493. **
  6494. ** ^(If this global variable is made to point to a string which is
  6495. ** the name of a folder (a.k.a. directory), then all temporary files
  6496. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  6497. ** will be placed in that directory.)^ ^If this variable
  6498. ** is a NULL pointer, then SQLite performs a search for an appropriate
  6499. ** temporary file directory.
  6500. **
  6501. ** Applications are strongly discouraged from using this global variable.
  6502. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  6503. ** But for all other platforms, it is highly recommended that applications
  6504. ** neither read nor write this variable. This global variable is a relic
  6505. ** that exists for backwards compatibility of legacy applications and should
  6506. ** be avoided in new projects.
  6507. **
  6508. ** It is not safe to read or modify this variable in more than one
  6509. ** thread at a time. It is not safe to read or modify this variable
  6510. ** if a [database connection] is being used at the same time in a separate
  6511. ** thread.
  6512. ** It is intended that this variable be set once
  6513. ** as part of process initialization and before any SQLite interface
  6514. ** routines have been called and that this variable remain unchanged
  6515. ** thereafter.
  6516. **
  6517. ** ^The [temp_store_directory pragma] may modify this variable and cause
  6518. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6519. ** the [temp_store_directory pragma] always assumes that any string
  6520. ** that this variable points to is held in memory obtained from
  6521. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6522. ** using [sqlite3_free].
  6523. ** Hence, if this variable is modified directly, either it should be
  6524. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6525. ** or else the use of the [temp_store_directory pragma] should be avoided.
  6526. ** Except when requested by the [temp_store_directory pragma], SQLite
  6527. ** does not free the memory that sqlite3_temp_directory points to. If
  6528. ** the application wants that memory to be freed, it must do
  6529. ** so itself, taking care to only do so after all [database connection]
  6530. ** objects have been destroyed.
  6531. **
  6532. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  6533. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  6534. ** features that require the use of temporary files may fail. Here is an
  6535. ** example of how to do this using C++ with the Windows Runtime:
  6536. **
  6537. ** <blockquote><pre>
  6538. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  6539. ** &nbsp; TemporaryFolder->Path->Data();
  6540. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  6541. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  6542. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  6543. ** &nbsp; NULL, NULL);
  6544. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  6545. ** </pre></blockquote>
  6546. */
  6547. SQLITE_API char *sqlite3_temp_directory;
  6548. /*
  6549. ** CAPI3REF: Name Of The Folder Holding Database Files
  6550. **
  6551. ** ^(If this global variable is made to point to a string which is
  6552. ** the name of a folder (a.k.a. directory), then all database files
  6553. ** specified with a relative pathname and created or accessed by
  6554. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  6555. ** to be relative to that directory.)^ ^If this variable is a NULL
  6556. ** pointer, then SQLite assumes that all database files specified
  6557. ** with a relative pathname are relative to the current directory
  6558. ** for the process. Only the windows VFS makes use of this global
  6559. ** variable; it is ignored by the unix VFS.
  6560. **
  6561. ** Changing the value of this variable while a database connection is
  6562. ** open can result in a corrupt database.
  6563. **
  6564. ** It is not safe to read or modify this variable in more than one
  6565. ** thread at a time. It is not safe to read or modify this variable
  6566. ** if a [database connection] is being used at the same time in a separate
  6567. ** thread.
  6568. ** It is intended that this variable be set once
  6569. ** as part of process initialization and before any SQLite interface
  6570. ** routines have been called and that this variable remain unchanged
  6571. ** thereafter.
  6572. **
  6573. ** ^The [data_store_directory pragma] may modify this variable and cause
  6574. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6575. ** the [data_store_directory pragma] always assumes that any string
  6576. ** that this variable points to is held in memory obtained from
  6577. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6578. ** using [sqlite3_free].
  6579. ** Hence, if this variable is modified directly, either it should be
  6580. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6581. ** or else the use of the [data_store_directory pragma] should be avoided.
  6582. */
  6583. SQLITE_API char *sqlite3_data_directory;
  6584. /*
  6585. ** CAPI3REF: Win32 Specific Interface
  6586. **
  6587. ** These interfaces are available only on Windows. The
  6588. ** [sqlite3_win32_set_directory] interface is used to set the value associated
  6589. ** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
  6590. ** zValue, depending on the value of the type parameter. The zValue parameter
  6591. ** should be NULL to cause the previous value to be freed via [sqlite3_free];
  6592. ** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
  6593. ** prior to being used. The [sqlite3_win32_set_directory] interface returns
  6594. ** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
  6595. ** or [SQLITE_NOMEM] if memory could not be allocated. The value of the
  6596. ** [sqlite3_data_directory] variable is intended to act as a replacement for
  6597. ** the current directory on the sub-platforms of Win32 where that concept is
  6598. ** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and
  6599. ** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
  6600. ** sqlite3_win32_set_directory interface except the string parameter must be
  6601. ** UTF-8 or UTF-16, respectively.
  6602. */
  6603. SQLITE_API int sqlite3_win32_set_directory(
  6604. unsigned long type, /* Identifier for directory being set or reset */
  6605. void *zValue /* New value for directory being set or reset */
  6606. );
  6607. SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
  6608. SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
  6609. /*
  6610. ** CAPI3REF: Win32 Directory Types
  6611. **
  6612. ** These macros are only available on Windows. They define the allowed values
  6613. ** for the type argument to the [sqlite3_win32_set_directory] interface.
  6614. */
  6615. #define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1
  6616. #define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2
  6617. /*
  6618. ** CAPI3REF: Test For Auto-Commit Mode
  6619. ** KEYWORDS: {autocommit mode}
  6620. ** METHOD: sqlite3
  6621. **
  6622. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  6623. ** zero if the given database connection is or is not in autocommit mode,
  6624. ** respectively. ^Autocommit mode is on by default.
  6625. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  6626. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  6627. **
  6628. ** If certain kinds of errors occur on a statement within a multi-statement
  6629. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  6630. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  6631. ** transaction might be rolled back automatically. The only way to
  6632. ** find out whether SQLite automatically rolled back the transaction after
  6633. ** an error is to use this function.
  6634. **
  6635. ** If another thread changes the autocommit status of the database
  6636. ** connection while this routine is running, then the return value
  6637. ** is undefined.
  6638. */
  6639. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  6640. /*
  6641. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  6642. ** METHOD: sqlite3_stmt
  6643. **
  6644. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  6645. ** to which a [prepared statement] belongs. ^The [database connection]
  6646. ** returned by sqlite3_db_handle is the same [database connection]
  6647. ** that was the first argument
  6648. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  6649. ** create the statement in the first place.
  6650. */
  6651. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  6652. /*
  6653. ** CAPI3REF: Return The Filename For A Database Connection
  6654. ** METHOD: sqlite3
  6655. **
  6656. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  6657. ** associated with database N of connection D. ^The main database file
  6658. ** has the name "main". If there is no attached database N on the database
  6659. ** connection D, or if database N is a temporary or in-memory database, then
  6660. ** a NULL pointer is returned.
  6661. **
  6662. ** ^The filename returned by this function is the output of the
  6663. ** xFullPathname method of the [VFS]. ^In other words, the filename
  6664. ** will be an absolute pathname, even if the filename used
  6665. ** to open the database originally was a URI or relative pathname.
  6666. */
  6667. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  6668. /*
  6669. ** CAPI3REF: Determine if a database is read-only
  6670. ** METHOD: sqlite3
  6671. **
  6672. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  6673. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  6674. ** the name of a database on connection D.
  6675. */
  6676. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  6677. /*
  6678. ** CAPI3REF: Find the next prepared statement
  6679. ** METHOD: sqlite3
  6680. **
  6681. ** ^This interface returns a pointer to the next [prepared statement] after
  6682. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  6683. ** then this interface returns a pointer to the first prepared statement
  6684. ** associated with the database connection pDb. ^If no prepared statement
  6685. ** satisfies the conditions of this routine, it returns NULL.
  6686. **
  6687. ** The [database connection] pointer D in a call to
  6688. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  6689. ** connection and in particular must not be a NULL pointer.
  6690. */
  6691. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  6692. /*
  6693. ** CAPI3REF: Commit And Rollback Notification Callbacks
  6694. ** METHOD: sqlite3
  6695. **
  6696. ** ^The sqlite3_commit_hook() interface registers a callback
  6697. ** function to be invoked whenever a transaction is [COMMIT | committed].
  6698. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  6699. ** for the same database connection is overridden.
  6700. ** ^The sqlite3_rollback_hook() interface registers a callback
  6701. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  6702. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  6703. ** for the same database connection is overridden.
  6704. ** ^The pArg argument is passed through to the callback.
  6705. ** ^If the callback on a commit hook function returns non-zero,
  6706. ** then the commit is converted into a rollback.
  6707. **
  6708. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  6709. ** return the P argument from the previous call of the same function
  6710. ** on the same [database connection] D, or NULL for
  6711. ** the first call for each function on D.
  6712. **
  6713. ** The commit and rollback hook callbacks are not reentrant.
  6714. ** The callback implementation must not do anything that will modify
  6715. ** the database connection that invoked the callback. Any actions
  6716. ** to modify the database connection must be deferred until after the
  6717. ** completion of the [sqlite3_step()] call that triggered the commit
  6718. ** or rollback hook in the first place.
  6719. ** Note that running any other SQL statements, including SELECT statements,
  6720. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  6721. ** the database connections for the meaning of "modify" in this paragraph.
  6722. **
  6723. ** ^Registering a NULL function disables the callback.
  6724. **
  6725. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  6726. ** operation is allowed to continue normally. ^If the commit hook
  6727. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  6728. ** ^The rollback hook is invoked on a rollback that results from a commit
  6729. ** hook returning non-zero, just as it would be with any other rollback.
  6730. **
  6731. ** ^For the purposes of this API, a transaction is said to have been
  6732. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  6733. ** an error or constraint causes an implicit rollback to occur.
  6734. ** ^The rollback callback is not invoked if a transaction is
  6735. ** automatically rolled back because the database connection is closed.
  6736. **
  6737. ** See also the [sqlite3_update_hook()] interface.
  6738. */
  6739. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  6740. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  6741. /*
  6742. ** CAPI3REF: Data Change Notification Callbacks
  6743. ** METHOD: sqlite3
  6744. **
  6745. ** ^The sqlite3_update_hook() interface registers a callback function
  6746. ** with the [database connection] identified by the first argument
  6747. ** to be invoked whenever a row is updated, inserted or deleted in
  6748. ** a [rowid table].
  6749. ** ^Any callback set by a previous call to this function
  6750. ** for the same database connection is overridden.
  6751. **
  6752. ** ^The second argument is a pointer to the function to invoke when a
  6753. ** row is updated, inserted or deleted in a rowid table.
  6754. ** ^The first argument to the callback is a copy of the third argument
  6755. ** to sqlite3_update_hook().
  6756. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  6757. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  6758. ** to be invoked.
  6759. ** ^The third and fourth arguments to the callback contain pointers to the
  6760. ** database and table name containing the affected row.
  6761. ** ^The final callback parameter is the [rowid] of the row.
  6762. ** ^In the case of an update, this is the [rowid] after the update takes place.
  6763. **
  6764. ** ^(The update hook is not invoked when internal system tables are
  6765. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  6766. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  6767. **
  6768. ** ^In the current implementation, the update hook
  6769. ** is not invoked when conflicting rows are deleted because of an
  6770. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  6771. ** invoked when rows are deleted using the [truncate optimization].
  6772. ** The exceptions defined in this paragraph might change in a future
  6773. ** release of SQLite.
  6774. **
  6775. ** The update hook implementation must not do anything that will modify
  6776. ** the database connection that invoked the update hook. Any actions
  6777. ** to modify the database connection must be deferred until after the
  6778. ** completion of the [sqlite3_step()] call that triggered the update hook.
  6779. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  6780. ** database connections for the meaning of "modify" in this paragraph.
  6781. **
  6782. ** ^The sqlite3_update_hook(D,C,P) function
  6783. ** returns the P argument from the previous call
  6784. ** on the same [database connection] D, or NULL for
  6785. ** the first call on D.
  6786. **
  6787. ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
  6788. ** and [sqlite3_preupdate_hook()] interfaces.
  6789. */
  6790. SQLITE_API void *sqlite3_update_hook(
  6791. sqlite3*,
  6792. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  6793. void*
  6794. );
  6795. /*
  6796. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  6797. **
  6798. ** ^(This routine enables or disables the sharing of the database cache
  6799. ** and schema data structures between [database connection | connections]
  6800. ** to the same database. Sharing is enabled if the argument is true
  6801. ** and disabled if the argument is false.)^
  6802. **
  6803. ** ^Cache sharing is enabled and disabled for an entire process.
  6804. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
  6805. ** In prior versions of SQLite,
  6806. ** sharing was enabled or disabled for each thread separately.
  6807. **
  6808. ** ^(The cache sharing mode set by this interface effects all subsequent
  6809. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  6810. ** Existing database connections continue use the sharing mode
  6811. ** that was in effect at the time they were opened.)^
  6812. **
  6813. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  6814. ** successfully. An [error code] is returned otherwise.)^
  6815. **
  6816. ** ^Shared cache is disabled by default. But this might change in
  6817. ** future releases of SQLite. Applications that care about shared
  6818. ** cache setting should set it explicitly.
  6819. **
  6820. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  6821. ** and will always return SQLITE_MISUSE. On those systems,
  6822. ** shared cache mode should be enabled per-database connection via
  6823. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  6824. **
  6825. ** This interface is threadsafe on processors where writing a
  6826. ** 32-bit integer is atomic.
  6827. **
  6828. ** See Also: [SQLite Shared-Cache Mode]
  6829. */
  6830. SQLITE_API int sqlite3_enable_shared_cache(int);
  6831. /*
  6832. ** CAPI3REF: Attempt To Free Heap Memory
  6833. **
  6834. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  6835. ** of heap memory by deallocating non-essential memory allocations
  6836. ** held by the database library. Memory used to cache database
  6837. ** pages to improve performance is an example of non-essential memory.
  6838. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  6839. ** which might be more or less than the amount requested.
  6840. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  6841. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6842. **
  6843. ** See also: [sqlite3_db_release_memory()]
  6844. */
  6845. SQLITE_API int sqlite3_release_memory(int);
  6846. /*
  6847. ** CAPI3REF: Free Memory Used By A Database Connection
  6848. ** METHOD: sqlite3
  6849. **
  6850. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  6851. ** memory as possible from database connection D. Unlike the
  6852. ** [sqlite3_release_memory()] interface, this interface is in effect even
  6853. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  6854. ** omitted.
  6855. **
  6856. ** See also: [sqlite3_release_memory()]
  6857. */
  6858. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  6859. /*
  6860. ** CAPI3REF: Impose A Limit On Heap Size
  6861. **
  6862. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  6863. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  6864. ** ^SQLite strives to keep heap memory utilization below the soft heap
  6865. ** limit by reducing the number of pages held in the page cache
  6866. ** as heap memory usages approaches the limit.
  6867. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  6868. ** below the limit, it will exceed the limit rather than generate
  6869. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  6870. ** is advisory only.
  6871. **
  6872. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  6873. ** the soft heap limit prior to the call, or negative in the case of an
  6874. ** error. ^If the argument N is negative
  6875. ** then no change is made to the soft heap limit. Hence, the current
  6876. ** size of the soft heap limit can be determined by invoking
  6877. ** sqlite3_soft_heap_limit64() with a negative argument.
  6878. **
  6879. ** ^If the argument N is zero then the soft heap limit is disabled.
  6880. **
  6881. ** ^(The soft heap limit is not enforced in the current implementation
  6882. ** if one or more of following conditions are true:
  6883. **
  6884. ** <ul>
  6885. ** <li> The soft heap limit is set to zero.
  6886. ** <li> Memory accounting is disabled using a combination of the
  6887. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  6888. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  6889. ** <li> An alternative page cache implementation is specified using
  6890. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  6891. ** <li> The page cache allocates from its own memory pool supplied
  6892. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  6893. ** from the heap.
  6894. ** </ul>)^
  6895. **
  6896. ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
  6897. ** the soft heap limit is enforced
  6898. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  6899. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  6900. ** the soft heap limit is enforced on every memory allocation. Without
  6901. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  6902. ** when memory is allocated by the page cache. Testing suggests that because
  6903. ** the page cache is the predominate memory user in SQLite, most
  6904. ** applications will achieve adequate soft heap limit enforcement without
  6905. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6906. **
  6907. ** The circumstances under which SQLite will enforce the soft heap limit may
  6908. ** changes in future releases of SQLite.
  6909. */
  6910. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  6911. /*
  6912. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  6913. ** DEPRECATED
  6914. **
  6915. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  6916. ** interface. This routine is provided for historical compatibility
  6917. ** only. All new applications should use the
  6918. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  6919. */
  6920. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  6921. /*
  6922. ** CAPI3REF: Extract Metadata About A Column Of A Table
  6923. ** METHOD: sqlite3
  6924. **
  6925. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  6926. ** information about column C of table T in database D
  6927. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  6928. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  6929. ** the final five arguments with appropriate values if the specified
  6930. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  6931. ** SQLITE_ERROR and if the specified column does not exist.
  6932. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  6933. ** NULL pointer, then this routine simply checks for the existence of the
  6934. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  6935. ** does not. If the table name parameter T in a call to
  6936. ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
  6937. ** undefined behavior.
  6938. **
  6939. ** ^The column is identified by the second, third and fourth parameters to
  6940. ** this function. ^(The second parameter is either the name of the database
  6941. ** (i.e. "main", "temp", or an attached database) containing the specified
  6942. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  6943. ** for the table using the same algorithm used by the database engine to
  6944. ** resolve unqualified table references.
  6945. **
  6946. ** ^The third and fourth parameters to this function are the table and column
  6947. ** name of the desired column, respectively.
  6948. **
  6949. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  6950. ** and subsequent parameters to this function. ^Any of these arguments may be
  6951. ** NULL, in which case the corresponding element of metadata is omitted.
  6952. **
  6953. ** ^(<blockquote>
  6954. ** <table border="1">
  6955. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  6956. **
  6957. ** <tr><td> 5th <td> const char* <td> Data type
  6958. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  6959. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  6960. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  6961. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  6962. ** </table>
  6963. ** </blockquote>)^
  6964. **
  6965. ** ^The memory pointed to by the character pointers returned for the
  6966. ** declaration type and collation sequence is valid until the next
  6967. ** call to any SQLite API function.
  6968. **
  6969. ** ^If the specified table is actually a view, an [error code] is returned.
  6970. **
  6971. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  6972. ** is not a [WITHOUT ROWID] table and an
  6973. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  6974. ** parameters are set for the explicitly declared column. ^(If there is no
  6975. ** [INTEGER PRIMARY KEY] column, then the outputs
  6976. ** for the [rowid] are set as follows:
  6977. **
  6978. ** <pre>
  6979. ** data type: "INTEGER"
  6980. ** collation sequence: "BINARY"
  6981. ** not null: 0
  6982. ** primary key: 1
  6983. ** auto increment: 0
  6984. ** </pre>)^
  6985. **
  6986. ** ^This function causes all database schemas to be read from disk and
  6987. ** parsed, if that has not already been done, and returns an error if
  6988. ** any errors are encountered while loading the schema.
  6989. */
  6990. SQLITE_API int sqlite3_table_column_metadata(
  6991. sqlite3 *db, /* Connection handle */
  6992. const char *zDbName, /* Database name or NULL */
  6993. const char *zTableName, /* Table name */
  6994. const char *zColumnName, /* Column name */
  6995. char const **pzDataType, /* OUTPUT: Declared data type */
  6996. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  6997. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  6998. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  6999. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  7000. );
  7001. /*
  7002. ** CAPI3REF: Load An Extension
  7003. ** METHOD: sqlite3
  7004. **
  7005. ** ^This interface loads an SQLite extension library from the named file.
  7006. **
  7007. ** ^The sqlite3_load_extension() interface attempts to load an
  7008. ** [SQLite extension] library contained in the file zFile. If
  7009. ** the file cannot be loaded directly, attempts are made to load
  7010. ** with various operating-system specific extensions added.
  7011. ** So for example, if "samplelib" cannot be loaded, then names like
  7012. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  7013. ** be tried also.
  7014. **
  7015. ** ^The entry point is zProc.
  7016. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  7017. ** entry point name on its own. It first tries "sqlite3_extension_init".
  7018. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  7019. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  7020. ** characters in the filename from the last "/" to the first following
  7021. ** "." and omitting any initial "lib".)^
  7022. ** ^The sqlite3_load_extension() interface returns
  7023. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  7024. ** ^If an error occurs and pzErrMsg is not 0, then the
  7025. ** [sqlite3_load_extension()] interface shall attempt to
  7026. ** fill *pzErrMsg with error message text stored in memory
  7027. ** obtained from [sqlite3_malloc()]. The calling function
  7028. ** should free this memory by calling [sqlite3_free()].
  7029. **
  7030. ** ^Extension loading must be enabled using
  7031. ** [sqlite3_enable_load_extension()] or
  7032. ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
  7033. ** prior to calling this API,
  7034. ** otherwise an error will be returned.
  7035. **
  7036. ** <b>Security warning:</b> It is recommended that the
  7037. ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
  7038. ** interface. The use of the [sqlite3_enable_load_extension()] interface
  7039. ** should be avoided. This will keep the SQL function [load_extension()]
  7040. ** disabled and prevent SQL injections from giving attackers
  7041. ** access to extension loading capabilities.
  7042. **
  7043. ** See also the [load_extension() SQL function].
  7044. */
  7045. SQLITE_API int sqlite3_load_extension(
  7046. sqlite3 *db, /* Load the extension into this database connection */
  7047. const char *zFile, /* Name of the shared library containing extension */
  7048. const char *zProc, /* Entry point. Derived from zFile if 0 */
  7049. char **pzErrMsg /* Put error message here if not 0 */
  7050. );
  7051. /*
  7052. ** CAPI3REF: Enable Or Disable Extension Loading
  7053. ** METHOD: sqlite3
  7054. **
  7055. ** ^So as not to open security holes in older applications that are
  7056. ** unprepared to deal with [extension loading], and as a means of disabling
  7057. ** [extension loading] while evaluating user-entered SQL, the following API
  7058. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  7059. **
  7060. ** ^Extension loading is off by default.
  7061. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  7062. ** to turn extension loading on and call it with onoff==0 to turn
  7063. ** it back off again.
  7064. **
  7065. ** ^This interface enables or disables both the C-API
  7066. ** [sqlite3_load_extension()] and the SQL function [load_extension()].
  7067. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
  7068. ** to enable or disable only the C-API.)^
  7069. **
  7070. ** <b>Security warning:</b> It is recommended that extension loading
  7071. ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
  7072. ** rather than this interface, so the [load_extension()] SQL function
  7073. ** remains disabled. This will prevent SQL injections from giving attackers
  7074. ** access to extension loading capabilities.
  7075. */
  7076. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  7077. /*
  7078. ** CAPI3REF: Automatically Load Statically Linked Extensions
  7079. **
  7080. ** ^This interface causes the xEntryPoint() function to be invoked for
  7081. ** each new [database connection] that is created. The idea here is that
  7082. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  7083. ** that is to be automatically loaded into all new database connections.
  7084. **
  7085. ** ^(Even though the function prototype shows that xEntryPoint() takes
  7086. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  7087. ** arguments and expects an integer result as if the signature of the
  7088. ** entry point where as follows:
  7089. **
  7090. ** <blockquote><pre>
  7091. ** &nbsp; int xEntryPoint(
  7092. ** &nbsp; sqlite3 *db,
  7093. ** &nbsp; const char **pzErrMsg,
  7094. ** &nbsp; const struct sqlite3_api_routines *pThunk
  7095. ** &nbsp; );
  7096. ** </pre></blockquote>)^
  7097. **
  7098. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  7099. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  7100. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  7101. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  7102. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  7103. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  7104. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  7105. **
  7106. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  7107. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  7108. ** will be called more than once for each database connection that is opened.
  7109. **
  7110. ** See also: [sqlite3_reset_auto_extension()]
  7111. ** and [sqlite3_cancel_auto_extension()]
  7112. */
  7113. SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
  7114. /*
  7115. ** CAPI3REF: Cancel Automatic Extension Loading
  7116. **
  7117. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  7118. ** initialization routine X that was registered using a prior call to
  7119. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  7120. ** routine returns 1 if initialization routine X was successfully
  7121. ** unregistered and it returns 0 if X was not on the list of initialization
  7122. ** routines.
  7123. */
  7124. SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
  7125. /*
  7126. ** CAPI3REF: Reset Automatic Extension Loading
  7127. **
  7128. ** ^This interface disables all automatic extensions previously
  7129. ** registered using [sqlite3_auto_extension()].
  7130. */
  7131. SQLITE_API void sqlite3_reset_auto_extension(void);
  7132. /*
  7133. ** The interface to the virtual-table mechanism is currently considered
  7134. ** to be experimental. The interface might change in incompatible ways.
  7135. ** If this is a problem for you, do not use the interface at this time.
  7136. **
  7137. ** When the virtual-table mechanism stabilizes, we will declare the
  7138. ** interface fixed, support it indefinitely, and remove this comment.
  7139. */
  7140. /*
  7141. ** Structures used by the virtual table interface
  7142. */
  7143. typedef struct sqlite3_vtab sqlite3_vtab;
  7144. typedef struct sqlite3_index_info sqlite3_index_info;
  7145. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  7146. typedef struct sqlite3_module sqlite3_module;
  7147. /*
  7148. ** CAPI3REF: Virtual Table Object
  7149. ** KEYWORDS: sqlite3_module {virtual table module}
  7150. **
  7151. ** This structure, sometimes called a "virtual table module",
  7152. ** defines the implementation of a [virtual tables].
  7153. ** This structure consists mostly of methods for the module.
  7154. **
  7155. ** ^A virtual table module is created by filling in a persistent
  7156. ** instance of this structure and passing a pointer to that instance
  7157. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  7158. ** ^The registration remains valid until it is replaced by a different
  7159. ** module or until the [database connection] closes. The content
  7160. ** of this structure must not change while it is registered with
  7161. ** any database connection.
  7162. */
  7163. struct sqlite3_module {
  7164. int iVersion;
  7165. int (*xCreate)(sqlite3*, void *pAux,
  7166. int argc, const char *const*argv,
  7167. sqlite3_vtab **ppVTab, char**);
  7168. int (*xConnect)(sqlite3*, void *pAux,
  7169. int argc, const char *const*argv,
  7170. sqlite3_vtab **ppVTab, char**);
  7171. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  7172. int (*xDisconnect)(sqlite3_vtab *pVTab);
  7173. int (*xDestroy)(sqlite3_vtab *pVTab);
  7174. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  7175. int (*xClose)(sqlite3_vtab_cursor*);
  7176. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  7177. int argc, sqlite3_value **argv);
  7178. int (*xNext)(sqlite3_vtab_cursor*);
  7179. int (*xEof)(sqlite3_vtab_cursor*);
  7180. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  7181. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  7182. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  7183. int (*xBegin)(sqlite3_vtab *pVTab);
  7184. int (*xSync)(sqlite3_vtab *pVTab);
  7185. int (*xCommit)(sqlite3_vtab *pVTab);
  7186. int (*xRollback)(sqlite3_vtab *pVTab);
  7187. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  7188. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  7189. void **ppArg);
  7190. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  7191. /* The methods above are in version 1 of the sqlite_module object. Those
  7192. ** below are for version 2 and greater. */
  7193. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  7194. int (*xRelease)(sqlite3_vtab *pVTab, int);
  7195. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  7196. /* The methods above are in versions 1 and 2 of the sqlite_module object.
  7197. ** Those below are for version 3 and greater. */
  7198. int (*xShadowName)(const char*);
  7199. };
  7200. /*
  7201. ** CAPI3REF: Virtual Table Indexing Information
  7202. ** KEYWORDS: sqlite3_index_info
  7203. **
  7204. ** The sqlite3_index_info structure and its substructures is used as part
  7205. ** of the [virtual table] interface to
  7206. ** pass information into and receive the reply from the [xBestIndex]
  7207. ** method of a [virtual table module]. The fields under **Inputs** are the
  7208. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  7209. ** results into the **Outputs** fields.
  7210. **
  7211. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  7212. **
  7213. ** <blockquote>column OP expr</blockquote>
  7214. **
  7215. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  7216. ** stored in aConstraint[].op using one of the
  7217. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  7218. ** ^(The index of the column is stored in
  7219. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  7220. ** expr on the right-hand side can be evaluated (and thus the constraint
  7221. ** is usable) and false if it cannot.)^
  7222. **
  7223. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  7224. ** and makes other simplifications to the WHERE clause in an attempt to
  7225. ** get as many WHERE clause terms into the form shown above as possible.
  7226. ** ^The aConstraint[] array only reports WHERE clause terms that are
  7227. ** relevant to the particular virtual table being queried.
  7228. **
  7229. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  7230. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  7231. **
  7232. ** The colUsed field indicates which columns of the virtual table may be
  7233. ** required by the current scan. Virtual table columns are numbered from
  7234. ** zero in the order in which they appear within the CREATE TABLE statement
  7235. ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  7236. ** the corresponding bit is set within the colUsed mask if the column may be
  7237. ** required by SQLite. If the table has at least 64 columns and any column
  7238. ** to the right of the first 63 is required, then bit 63 of colUsed is also
  7239. ** set. In other words, column iCol may be required if the expression
  7240. ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
  7241. ** non-zero.
  7242. **
  7243. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  7244. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  7245. ** the right-hand side of the corresponding aConstraint[] is evaluated
  7246. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  7247. ** is true, then the constraint is assumed to be fully handled by the
  7248. ** virtual table and is not checked again by SQLite.)^
  7249. **
  7250. ** ^The idxNum and idxPtr values are recorded and passed into the
  7251. ** [xFilter] method.
  7252. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  7253. ** needToFreeIdxPtr is true.
  7254. **
  7255. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  7256. ** the correct order to satisfy the ORDER BY clause so that no separate
  7257. ** sorting step is required.
  7258. **
  7259. ** ^The estimatedCost value is an estimate of the cost of a particular
  7260. ** strategy. A cost of N indicates that the cost of the strategy is similar
  7261. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  7262. ** indicates that the expense of the operation is similar to that of a
  7263. ** binary search on a unique indexed field of an SQLite table with N rows.
  7264. **
  7265. ** ^The estimatedRows value is an estimate of the number of rows that
  7266. ** will be returned by the strategy.
  7267. **
  7268. ** The xBestIndex method may optionally populate the idxFlags field with a
  7269. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  7270. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  7271. ** assumes that the strategy may visit at most one row.
  7272. **
  7273. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  7274. ** SQLite also assumes that if a call to the xUpdate() method is made as
  7275. ** part of the same statement to delete or update a virtual table row and the
  7276. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  7277. ** any database changes. In other words, if the xUpdate() returns
  7278. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  7279. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  7280. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  7281. ** the xUpdate method are automatically rolled back by SQLite.
  7282. **
  7283. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  7284. ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
  7285. ** If a virtual table extension is
  7286. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  7287. ** to read or write the estimatedRows field are undefined (but are likely
  7288. ** to included crashing the application). The estimatedRows field should
  7289. ** therefore only be used if [sqlite3_libversion_number()] returns a
  7290. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  7291. ** was added for [version 3.9.0] ([dateof:3.9.0]).
  7292. ** It may therefore only be used if
  7293. ** sqlite3_libversion_number() returns a value greater than or equal to
  7294. ** 3009000.
  7295. */
  7296. struct sqlite3_index_info {
  7297. /* Inputs */
  7298. int nConstraint; /* Number of entries in aConstraint */
  7299. struct sqlite3_index_constraint {
  7300. int iColumn; /* Column constrained. -1 for ROWID */
  7301. unsigned char op; /* Constraint operator */
  7302. unsigned char usable; /* True if this constraint is usable */
  7303. int iTermOffset; /* Used internally - xBestIndex should ignore */
  7304. } *aConstraint; /* Table of WHERE clause constraints */
  7305. int nOrderBy; /* Number of terms in the ORDER BY clause */
  7306. struct sqlite3_index_orderby {
  7307. int iColumn; /* Column number */
  7308. unsigned char desc; /* True for DESC. False for ASC. */
  7309. } *aOrderBy; /* The ORDER BY clause */
  7310. /* Outputs */
  7311. struct sqlite3_index_constraint_usage {
  7312. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  7313. unsigned char omit; /* Do not code a test for this constraint */
  7314. } *aConstraintUsage;
  7315. int idxNum; /* Number used to identify the index */
  7316. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  7317. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  7318. int orderByConsumed; /* True if output is already ordered */
  7319. double estimatedCost; /* Estimated cost of using this index */
  7320. /* Fields below are only available in SQLite 3.8.2 and later */
  7321. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  7322. /* Fields below are only available in SQLite 3.9.0 and later */
  7323. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  7324. /* Fields below are only available in SQLite 3.10.0 and later */
  7325. sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
  7326. };
  7327. /*
  7328. ** CAPI3REF: Virtual Table Scan Flags
  7329. **
  7330. ** Virtual table implementations are allowed to set the
  7331. ** [sqlite3_index_info].idxFlags field to some combination of
  7332. ** these bits.
  7333. */
  7334. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  7335. /*
  7336. ** CAPI3REF: Virtual Table Constraint Operator Codes
  7337. **
  7338. ** These macros defined the allowed values for the
  7339. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  7340. ** an operator that is part of a constraint term in the wHERE clause of
  7341. ** a query that uses a [virtual table].
  7342. */
  7343. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  7344. #define SQLITE_INDEX_CONSTRAINT_GT 4
  7345. #define SQLITE_INDEX_CONSTRAINT_LE 8
  7346. #define SQLITE_INDEX_CONSTRAINT_LT 16
  7347. #define SQLITE_INDEX_CONSTRAINT_GE 32
  7348. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  7349. #define SQLITE_INDEX_CONSTRAINT_LIKE 65
  7350. #define SQLITE_INDEX_CONSTRAINT_GLOB 66
  7351. #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
  7352. #define SQLITE_INDEX_CONSTRAINT_NE 68
  7353. #define SQLITE_INDEX_CONSTRAINT_ISNOT 69
  7354. #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
  7355. #define SQLITE_INDEX_CONSTRAINT_ISNULL 71
  7356. #define SQLITE_INDEX_CONSTRAINT_IS 72
  7357. #define SQLITE_INDEX_CONSTRAINT_FUNCTION 150
  7358. /*
  7359. ** CAPI3REF: Register A Virtual Table Implementation
  7360. ** METHOD: sqlite3
  7361. **
  7362. ** ^These routines are used to register a new [virtual table module] name.
  7363. ** ^Module names must be registered before
  7364. ** creating a new [virtual table] using the module and before using a
  7365. ** preexisting [virtual table] for the module.
  7366. **
  7367. ** ^The module name is registered on the [database connection] specified
  7368. ** by the first parameter. ^The name of the module is given by the
  7369. ** second parameter. ^The third parameter is a pointer to
  7370. ** the implementation of the [virtual table module]. ^The fourth
  7371. ** parameter is an arbitrary client data pointer that is passed through
  7372. ** into the [xCreate] and [xConnect] methods of the virtual table module
  7373. ** when a new virtual table is be being created or reinitialized.
  7374. **
  7375. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  7376. ** is a pointer to a destructor for the pClientData. ^SQLite will
  7377. ** invoke the destructor function (if it is not NULL) when SQLite
  7378. ** no longer needs the pClientData pointer. ^The destructor will also
  7379. ** be invoked if the call to sqlite3_create_module_v2() fails.
  7380. ** ^The sqlite3_create_module()
  7381. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  7382. ** destructor.
  7383. */
  7384. SQLITE_API int sqlite3_create_module(
  7385. sqlite3 *db, /* SQLite connection to register module with */
  7386. const char *zName, /* Name of the module */
  7387. const sqlite3_module *p, /* Methods for the module */
  7388. void *pClientData /* Client data for xCreate/xConnect */
  7389. );
  7390. SQLITE_API int sqlite3_create_module_v2(
  7391. sqlite3 *db, /* SQLite connection to register module with */
  7392. const char *zName, /* Name of the module */
  7393. const sqlite3_module *p, /* Methods for the module */
  7394. void *pClientData, /* Client data for xCreate/xConnect */
  7395. void(*xDestroy)(void*) /* Module destructor function */
  7396. );
  7397. /*
  7398. ** CAPI3REF: Virtual Table Instance Object
  7399. ** KEYWORDS: sqlite3_vtab
  7400. **
  7401. ** Every [virtual table module] implementation uses a subclass
  7402. ** of this object to describe a particular instance
  7403. ** of the [virtual table]. Each subclass will
  7404. ** be tailored to the specific needs of the module implementation.
  7405. ** The purpose of this superclass is to define certain fields that are
  7406. ** common to all module implementations.
  7407. **
  7408. ** ^Virtual tables methods can set an error message by assigning a
  7409. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  7410. ** take care that any prior string is freed by a call to [sqlite3_free()]
  7411. ** prior to assigning a new string to zErrMsg. ^After the error message
  7412. ** is delivered up to the client application, the string will be automatically
  7413. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  7414. */
  7415. struct sqlite3_vtab {
  7416. const sqlite3_module *pModule; /* The module for this virtual table */
  7417. int nRef; /* Number of open cursors */
  7418. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  7419. /* Virtual table implementations will typically add additional fields */
  7420. };
  7421. /*
  7422. ** CAPI3REF: Virtual Table Cursor Object
  7423. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  7424. **
  7425. ** Every [virtual table module] implementation uses a subclass of the
  7426. ** following structure to describe cursors that point into the
  7427. ** [virtual table] and are used
  7428. ** to loop through the virtual table. Cursors are created using the
  7429. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  7430. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  7431. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  7432. ** of the module. Each module implementation will define
  7433. ** the content of a cursor structure to suit its own needs.
  7434. **
  7435. ** This superclass exists in order to define fields of the cursor that
  7436. ** are common to all implementations.
  7437. */
  7438. struct sqlite3_vtab_cursor {
  7439. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  7440. /* Virtual table implementations will typically add additional fields */
  7441. };
  7442. /*
  7443. ** CAPI3REF: Declare The Schema Of A Virtual Table
  7444. **
  7445. ** ^The [xCreate] and [xConnect] methods of a
  7446. ** [virtual table module] call this interface
  7447. ** to declare the format (the names and datatypes of the columns) of
  7448. ** the virtual tables they implement.
  7449. */
  7450. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  7451. /*
  7452. ** CAPI3REF: Overload A Function For A Virtual Table
  7453. ** METHOD: sqlite3
  7454. **
  7455. ** ^(Virtual tables can provide alternative implementations of functions
  7456. ** using the [xFindFunction] method of the [virtual table module].
  7457. ** But global versions of those functions
  7458. ** must exist in order to be overloaded.)^
  7459. **
  7460. ** ^(This API makes sure a global version of a function with a particular
  7461. ** name and number of parameters exists. If no such function exists
  7462. ** before this API is called, a new function is created.)^ ^The implementation
  7463. ** of the new function always causes an exception to be thrown. So
  7464. ** the new function is not good for anything by itself. Its only
  7465. ** purpose is to be a placeholder function that can be overloaded
  7466. ** by a [virtual table].
  7467. */
  7468. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  7469. /*
  7470. ** The interface to the virtual-table mechanism defined above (back up
  7471. ** to a comment remarkably similar to this one) is currently considered
  7472. ** to be experimental. The interface might change in incompatible ways.
  7473. ** If this is a problem for you, do not use the interface at this time.
  7474. **
  7475. ** When the virtual-table mechanism stabilizes, we will declare the
  7476. ** interface fixed, support it indefinitely, and remove this comment.
  7477. */
  7478. /*
  7479. ** CAPI3REF: A Handle To An Open BLOB
  7480. ** KEYWORDS: {BLOB handle} {BLOB handles}
  7481. **
  7482. ** An instance of this object represents an open BLOB on which
  7483. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  7484. ** ^Objects of this type are created by [sqlite3_blob_open()]
  7485. ** and destroyed by [sqlite3_blob_close()].
  7486. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  7487. ** can be used to read or write small subsections of the BLOB.
  7488. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  7489. */
  7490. typedef struct sqlite3_blob sqlite3_blob;
  7491. /*
  7492. ** CAPI3REF: Open A BLOB For Incremental I/O
  7493. ** METHOD: sqlite3
  7494. ** CONSTRUCTOR: sqlite3_blob
  7495. **
  7496. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  7497. ** in row iRow, column zColumn, table zTable in database zDb;
  7498. ** in other words, the same BLOB that would be selected by:
  7499. **
  7500. ** <pre>
  7501. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  7502. ** </pre>)^
  7503. **
  7504. ** ^(Parameter zDb is not the filename that contains the database, but
  7505. ** rather the symbolic name of the database. For attached databases, this is
  7506. ** the name that appears after the AS keyword in the [ATTACH] statement.
  7507. ** For the main database file, the database name is "main". For TEMP
  7508. ** tables, the database name is "temp".)^
  7509. **
  7510. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  7511. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  7512. ** read-only access.
  7513. **
  7514. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  7515. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  7516. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  7517. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  7518. ** on *ppBlob after this function it returns.
  7519. **
  7520. ** This function fails with SQLITE_ERROR if any of the following are true:
  7521. ** <ul>
  7522. ** <li> ^(Database zDb does not exist)^,
  7523. ** <li> ^(Table zTable does not exist within database zDb)^,
  7524. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  7525. ** <li> ^(Column zColumn does not exist)^,
  7526. ** <li> ^(Row iRow is not present in the table)^,
  7527. ** <li> ^(The specified column of row iRow contains a value that is not
  7528. ** a TEXT or BLOB value)^,
  7529. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  7530. ** constraint and the blob is being opened for read/write access)^,
  7531. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  7532. ** column zColumn is part of a [child key] definition and the blob is
  7533. ** being opened for read/write access)^.
  7534. ** </ul>
  7535. **
  7536. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  7537. ** [database connection] error code and message accessible via
  7538. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7539. **
  7540. ** A BLOB referenced by sqlite3_blob_open() may be read using the
  7541. ** [sqlite3_blob_read()] interface and modified by using
  7542. ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
  7543. ** different row of the same table using the [sqlite3_blob_reopen()]
  7544. ** interface. However, the column, table, or database of a [BLOB handle]
  7545. ** cannot be changed after the [BLOB handle] is opened.
  7546. **
  7547. ** ^(If the row that a BLOB handle points to is modified by an
  7548. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  7549. ** then the BLOB handle is marked as "expired".
  7550. ** This is true if any column of the row is changed, even a column
  7551. ** other than the one the BLOB handle is open on.)^
  7552. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  7553. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  7554. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  7555. ** rolled back by the expiration of the BLOB. Such changes will eventually
  7556. ** commit if the transaction continues to completion.)^
  7557. **
  7558. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  7559. ** the opened blob. ^The size of a blob may not be changed by this
  7560. ** interface. Use the [UPDATE] SQL command to change the size of a
  7561. ** blob.
  7562. **
  7563. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  7564. ** and the built-in [zeroblob] SQL function may be used to create a
  7565. ** zero-filled blob to read or write using the incremental-blob interface.
  7566. **
  7567. ** To avoid a resource leak, every open [BLOB handle] should eventually
  7568. ** be released by a call to [sqlite3_blob_close()].
  7569. **
  7570. ** See also: [sqlite3_blob_close()],
  7571. ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
  7572. ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
  7573. */
  7574. SQLITE_API int sqlite3_blob_open(
  7575. sqlite3*,
  7576. const char *zDb,
  7577. const char *zTable,
  7578. const char *zColumn,
  7579. sqlite3_int64 iRow,
  7580. int flags,
  7581. sqlite3_blob **ppBlob
  7582. );
  7583. /*
  7584. ** CAPI3REF: Move a BLOB Handle to a New Row
  7585. ** METHOD: sqlite3_blob
  7586. **
  7587. ** ^This function is used to move an existing [BLOB handle] so that it points
  7588. ** to a different row of the same database table. ^The new row is identified
  7589. ** by the rowid value passed as the second argument. Only the row can be
  7590. ** changed. ^The database, table and column on which the blob handle is open
  7591. ** remain the same. Moving an existing [BLOB handle] to a new row is
  7592. ** faster than closing the existing handle and opening a new one.
  7593. **
  7594. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  7595. ** it must exist and there must be either a blob or text value stored in
  7596. ** the nominated column.)^ ^If the new row is not present in the table, or if
  7597. ** it does not contain a blob or text value, or if another error occurs, an
  7598. ** SQLite error code is returned and the blob handle is considered aborted.
  7599. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  7600. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  7601. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  7602. ** always returns zero.
  7603. **
  7604. ** ^This function sets the database handle error code and message.
  7605. */
  7606. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  7607. /*
  7608. ** CAPI3REF: Close A BLOB Handle
  7609. ** DESTRUCTOR: sqlite3_blob
  7610. **
  7611. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  7612. ** unconditionally. Even if this routine returns an error code, the
  7613. ** handle is still closed.)^
  7614. **
  7615. ** ^If the blob handle being closed was opened for read-write access, and if
  7616. ** the database is in auto-commit mode and there are no other open read-write
  7617. ** blob handles or active write statements, the current transaction is
  7618. ** committed. ^If an error occurs while committing the transaction, an error
  7619. ** code is returned and the transaction rolled back.
  7620. **
  7621. ** Calling this function with an argument that is not a NULL pointer or an
  7622. ** open blob handle results in undefined behaviour. ^Calling this routine
  7623. ** with a null pointer (such as would be returned by a failed call to
  7624. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  7625. ** is passed a valid open blob handle, the values returned by the
  7626. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  7627. */
  7628. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  7629. /*
  7630. ** CAPI3REF: Return The Size Of An Open BLOB
  7631. ** METHOD: sqlite3_blob
  7632. **
  7633. ** ^Returns the size in bytes of the BLOB accessible via the
  7634. ** successfully opened [BLOB handle] in its only argument. ^The
  7635. ** incremental blob I/O routines can only read or overwriting existing
  7636. ** blob content; they cannot change the size of a blob.
  7637. **
  7638. ** This routine only works on a [BLOB handle] which has been created
  7639. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7640. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7641. ** to this routine results in undefined and probably undesirable behavior.
  7642. */
  7643. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  7644. /*
  7645. ** CAPI3REF: Read Data From A BLOB Incrementally
  7646. ** METHOD: sqlite3_blob
  7647. **
  7648. ** ^(This function is used to read data from an open [BLOB handle] into a
  7649. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  7650. ** from the open BLOB, starting at offset iOffset.)^
  7651. **
  7652. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7653. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  7654. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  7655. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  7656. ** can be determined using the [sqlite3_blob_bytes()] interface.
  7657. **
  7658. ** ^An attempt to read from an expired [BLOB handle] fails with an
  7659. ** error code of [SQLITE_ABORT].
  7660. **
  7661. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  7662. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7663. **
  7664. ** This routine only works on a [BLOB handle] which has been created
  7665. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7666. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7667. ** to this routine results in undefined and probably undesirable behavior.
  7668. **
  7669. ** See also: [sqlite3_blob_write()].
  7670. */
  7671. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  7672. /*
  7673. ** CAPI3REF: Write Data Into A BLOB Incrementally
  7674. ** METHOD: sqlite3_blob
  7675. **
  7676. ** ^(This function is used to write data into an open [BLOB handle] from a
  7677. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  7678. ** into the open BLOB, starting at offset iOffset.)^
  7679. **
  7680. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  7681. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7682. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  7683. ** [database connection] error code and message accessible via
  7684. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7685. **
  7686. ** ^If the [BLOB handle] passed as the first argument was not opened for
  7687. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  7688. ** this function returns [SQLITE_READONLY].
  7689. **
  7690. ** This function may only modify the contents of the BLOB; it is
  7691. ** not possible to increase the size of a BLOB using this API.
  7692. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7693. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  7694. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  7695. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  7696. ** than zero [SQLITE_ERROR] is returned and no data is written.
  7697. **
  7698. ** ^An attempt to write to an expired [BLOB handle] fails with an
  7699. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  7700. ** before the [BLOB handle] expired are not rolled back by the
  7701. ** expiration of the handle, though of course those changes might
  7702. ** have been overwritten by the statement that expired the BLOB handle
  7703. ** or by other independent statements.
  7704. **
  7705. ** This routine only works on a [BLOB handle] which has been created
  7706. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7707. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7708. ** to this routine results in undefined and probably undesirable behavior.
  7709. **
  7710. ** See also: [sqlite3_blob_read()].
  7711. */
  7712. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  7713. /*
  7714. ** CAPI3REF: Virtual File System Objects
  7715. **
  7716. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  7717. ** that SQLite uses to interact
  7718. ** with the underlying operating system. Most SQLite builds come with a
  7719. ** single default VFS that is appropriate for the host computer.
  7720. ** New VFSes can be registered and existing VFSes can be unregistered.
  7721. ** The following interfaces are provided.
  7722. **
  7723. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  7724. ** ^Names are case sensitive.
  7725. ** ^Names are zero-terminated UTF-8 strings.
  7726. ** ^If there is no match, a NULL pointer is returned.
  7727. ** ^If zVfsName is NULL then the default VFS is returned.
  7728. **
  7729. ** ^New VFSes are registered with sqlite3_vfs_register().
  7730. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  7731. ** ^The same VFS can be registered multiple times without injury.
  7732. ** ^To make an existing VFS into the default VFS, register it again
  7733. ** with the makeDflt flag set. If two different VFSes with the
  7734. ** same name are registered, the behavior is undefined. If a
  7735. ** VFS is registered with a name that is NULL or an empty string,
  7736. ** then the behavior is undefined.
  7737. **
  7738. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  7739. ** ^(If the default VFS is unregistered, another VFS is chosen as
  7740. ** the default. The choice for the new VFS is arbitrary.)^
  7741. */
  7742. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  7743. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  7744. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  7745. /*
  7746. ** CAPI3REF: Mutexes
  7747. **
  7748. ** The SQLite core uses these routines for thread
  7749. ** synchronization. Though they are intended for internal
  7750. ** use by SQLite, code that links against SQLite is
  7751. ** permitted to use any of these routines.
  7752. **
  7753. ** The SQLite source code contains multiple implementations
  7754. ** of these mutex routines. An appropriate implementation
  7755. ** is selected automatically at compile-time. The following
  7756. ** implementations are available in the SQLite core:
  7757. **
  7758. ** <ul>
  7759. ** <li> SQLITE_MUTEX_PTHREADS
  7760. ** <li> SQLITE_MUTEX_W32
  7761. ** <li> SQLITE_MUTEX_NOOP
  7762. ** </ul>
  7763. **
  7764. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  7765. ** that does no real locking and is appropriate for use in
  7766. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  7767. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  7768. ** and Windows.
  7769. **
  7770. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  7771. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  7772. ** implementation is included with the library. In this case the
  7773. ** application must supply a custom mutex implementation using the
  7774. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  7775. ** before calling sqlite3_initialize() or any other public sqlite3_
  7776. ** function that calls sqlite3_initialize().
  7777. **
  7778. ** ^The sqlite3_mutex_alloc() routine allocates a new
  7779. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  7780. ** routine returns NULL if it is unable to allocate the requested
  7781. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  7782. ** integer constants:
  7783. **
  7784. ** <ul>
  7785. ** <li> SQLITE_MUTEX_FAST
  7786. ** <li> SQLITE_MUTEX_RECURSIVE
  7787. ** <li> SQLITE_MUTEX_STATIC_MASTER
  7788. ** <li> SQLITE_MUTEX_STATIC_MEM
  7789. ** <li> SQLITE_MUTEX_STATIC_OPEN
  7790. ** <li> SQLITE_MUTEX_STATIC_PRNG
  7791. ** <li> SQLITE_MUTEX_STATIC_LRU
  7792. ** <li> SQLITE_MUTEX_STATIC_PMEM
  7793. ** <li> SQLITE_MUTEX_STATIC_APP1
  7794. ** <li> SQLITE_MUTEX_STATIC_APP2
  7795. ** <li> SQLITE_MUTEX_STATIC_APP3
  7796. ** <li> SQLITE_MUTEX_STATIC_VFS1
  7797. ** <li> SQLITE_MUTEX_STATIC_VFS2
  7798. ** <li> SQLITE_MUTEX_STATIC_VFS3
  7799. ** </ul>
  7800. **
  7801. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  7802. ** cause sqlite3_mutex_alloc() to create
  7803. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  7804. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  7805. ** The mutex implementation does not need to make a distinction
  7806. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  7807. ** not want to. SQLite will only request a recursive mutex in
  7808. ** cases where it really needs one. If a faster non-recursive mutex
  7809. ** implementation is available on the host platform, the mutex subsystem
  7810. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  7811. **
  7812. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  7813. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  7814. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  7815. ** used by the current version of SQLite. Future versions of SQLite
  7816. ** may add additional static mutexes. Static mutexes are for internal
  7817. ** use by SQLite only. Applications that use SQLite mutexes should
  7818. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  7819. ** SQLITE_MUTEX_RECURSIVE.
  7820. **
  7821. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  7822. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  7823. ** returns a different mutex on every call. ^For the static
  7824. ** mutex types, the same mutex is returned on every call that has
  7825. ** the same type number.
  7826. **
  7827. ** ^The sqlite3_mutex_free() routine deallocates a previously
  7828. ** allocated dynamic mutex. Attempting to deallocate a static
  7829. ** mutex results in undefined behavior.
  7830. **
  7831. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  7832. ** to enter a mutex. ^If another thread is already within the mutex,
  7833. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  7834. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  7835. ** upon successful entry. ^(Mutexes created using
  7836. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  7837. ** In such cases, the
  7838. ** mutex must be exited an equal number of times before another thread
  7839. ** can enter.)^ If the same thread tries to enter any mutex other
  7840. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  7841. **
  7842. ** ^(Some systems (for example, Windows 95) do not support the operation
  7843. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  7844. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  7845. ** sqlite3_mutex_try() as an optimization so this is acceptable
  7846. ** behavior.)^
  7847. **
  7848. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  7849. ** previously entered by the same thread. The behavior
  7850. ** is undefined if the mutex is not currently entered by the
  7851. ** calling thread or is not currently allocated.
  7852. **
  7853. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  7854. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  7855. ** behave as no-ops.
  7856. **
  7857. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  7858. */
  7859. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  7860. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  7861. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  7862. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  7863. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  7864. /*
  7865. ** CAPI3REF: Mutex Methods Object
  7866. **
  7867. ** An instance of this structure defines the low-level routines
  7868. ** used to allocate and use mutexes.
  7869. **
  7870. ** Usually, the default mutex implementations provided by SQLite are
  7871. ** sufficient, however the application has the option of substituting a custom
  7872. ** implementation for specialized deployments or systems for which SQLite
  7873. ** does not provide a suitable implementation. In this case, the application
  7874. ** creates and populates an instance of this structure to pass
  7875. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  7876. ** Additionally, an instance of this structure can be used as an
  7877. ** output variable when querying the system for the current mutex
  7878. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  7879. **
  7880. ** ^The xMutexInit method defined by this structure is invoked as
  7881. ** part of system initialization by the sqlite3_initialize() function.
  7882. ** ^The xMutexInit routine is called by SQLite exactly once for each
  7883. ** effective call to [sqlite3_initialize()].
  7884. **
  7885. ** ^The xMutexEnd method defined by this structure is invoked as
  7886. ** part of system shutdown by the sqlite3_shutdown() function. The
  7887. ** implementation of this method is expected to release all outstanding
  7888. ** resources obtained by the mutex methods implementation, especially
  7889. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  7890. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  7891. **
  7892. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  7893. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  7894. ** xMutexNotheld) implement the following interfaces (respectively):
  7895. **
  7896. ** <ul>
  7897. ** <li> [sqlite3_mutex_alloc()] </li>
  7898. ** <li> [sqlite3_mutex_free()] </li>
  7899. ** <li> [sqlite3_mutex_enter()] </li>
  7900. ** <li> [sqlite3_mutex_try()] </li>
  7901. ** <li> [sqlite3_mutex_leave()] </li>
  7902. ** <li> [sqlite3_mutex_held()] </li>
  7903. ** <li> [sqlite3_mutex_notheld()] </li>
  7904. ** </ul>)^
  7905. **
  7906. ** The only difference is that the public sqlite3_XXX functions enumerated
  7907. ** above silently ignore any invocations that pass a NULL pointer instead
  7908. ** of a valid mutex handle. The implementations of the methods defined
  7909. ** by this structure are not required to handle this case, the results
  7910. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  7911. ** (i.e. it is acceptable to provide an implementation that segfaults if
  7912. ** it is passed a NULL pointer).
  7913. **
  7914. ** The xMutexInit() method must be threadsafe. It must be harmless to
  7915. ** invoke xMutexInit() multiple times within the same process and without
  7916. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  7917. ** xMutexInit() must be no-ops.
  7918. **
  7919. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  7920. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  7921. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  7922. ** memory allocation for a fast or recursive mutex.
  7923. **
  7924. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  7925. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  7926. ** If xMutexInit fails in any way, it is expected to clean up after itself
  7927. ** prior to returning.
  7928. */
  7929. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  7930. struct sqlite3_mutex_methods {
  7931. int (*xMutexInit)(void);
  7932. int (*xMutexEnd)(void);
  7933. sqlite3_mutex *(*xMutexAlloc)(int);
  7934. void (*xMutexFree)(sqlite3_mutex *);
  7935. void (*xMutexEnter)(sqlite3_mutex *);
  7936. int (*xMutexTry)(sqlite3_mutex *);
  7937. void (*xMutexLeave)(sqlite3_mutex *);
  7938. int (*xMutexHeld)(sqlite3_mutex *);
  7939. int (*xMutexNotheld)(sqlite3_mutex *);
  7940. };
  7941. /*
  7942. ** CAPI3REF: Mutex Verification Routines
  7943. **
  7944. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  7945. ** are intended for use inside assert() statements. The SQLite core
  7946. ** never uses these routines except inside an assert() and applications
  7947. ** are advised to follow the lead of the core. The SQLite core only
  7948. ** provides implementations for these routines when it is compiled
  7949. ** with the SQLITE_DEBUG flag. External mutex implementations
  7950. ** are only required to provide these routines if SQLITE_DEBUG is
  7951. ** defined and if NDEBUG is not defined.
  7952. **
  7953. ** These routines should return true if the mutex in their argument
  7954. ** is held or not held, respectively, by the calling thread.
  7955. **
  7956. ** The implementation is not required to provide versions of these
  7957. ** routines that actually work. If the implementation does not provide working
  7958. ** versions of these routines, it should at least provide stubs that always
  7959. ** return true so that one does not get spurious assertion failures.
  7960. **
  7961. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  7962. ** the routine should return 1. This seems counter-intuitive since
  7963. ** clearly the mutex cannot be held if it does not exist. But
  7964. ** the reason the mutex does not exist is because the build is not
  7965. ** using mutexes. And we do not want the assert() containing the
  7966. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  7967. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  7968. ** interface should also return 1 when given a NULL pointer.
  7969. */
  7970. #ifndef NDEBUG
  7971. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  7972. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  7973. #endif
  7974. /*
  7975. ** CAPI3REF: Mutex Types
  7976. **
  7977. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  7978. ** which is one of these integer constants.
  7979. **
  7980. ** The set of static mutexes may change from one SQLite release to the
  7981. ** next. Applications that override the built-in mutex logic must be
  7982. ** prepared to accommodate additional static mutexes.
  7983. */
  7984. #define SQLITE_MUTEX_FAST 0
  7985. #define SQLITE_MUTEX_RECURSIVE 1
  7986. #define SQLITE_MUTEX_STATIC_MASTER 2
  7987. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  7988. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  7989. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  7990. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
  7991. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  7992. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  7993. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  7994. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  7995. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  7996. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  7997. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  7998. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  7999. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  8000. /*
  8001. ** CAPI3REF: Retrieve the mutex for a database connection
  8002. ** METHOD: sqlite3
  8003. **
  8004. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  8005. ** serializes access to the [database connection] given in the argument
  8006. ** when the [threading mode] is Serialized.
  8007. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  8008. ** routine returns a NULL pointer.
  8009. */
  8010. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  8011. /*
  8012. ** CAPI3REF: Low-Level Control Of Database Files
  8013. ** METHOD: sqlite3
  8014. ** KEYWORDS: {file control}
  8015. **
  8016. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  8017. ** xFileControl method for the [sqlite3_io_methods] object associated
  8018. ** with a particular database identified by the second argument. ^The
  8019. ** name of the database is "main" for the main database or "temp" for the
  8020. ** TEMP database, or the name that appears after the AS keyword for
  8021. ** databases that are added using the [ATTACH] SQL command.
  8022. ** ^A NULL pointer can be used in place of "main" to refer to the
  8023. ** main database file.
  8024. ** ^The third and fourth parameters to this routine
  8025. ** are passed directly through to the second and third parameters of
  8026. ** the xFileControl method. ^The return value of the xFileControl
  8027. ** method becomes the return value of this routine.
  8028. **
  8029. ** A few opcodes for [sqlite3_file_control()] are handled directly
  8030. ** by the SQLite core and never invoke the
  8031. ** sqlite3_io_methods.xFileControl method.
  8032. ** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
  8033. ** a pointer to the underlying [sqlite3_file] object to be written into
  8034. ** the space pointed to by the 4th parameter. The
  8035. ** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns
  8036. ** the [sqlite3_file] object associated with the journal file instead of
  8037. ** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns
  8038. ** a pointer to the underlying [sqlite3_vfs] object for the file.
  8039. ** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter
  8040. ** from the pager.
  8041. **
  8042. ** ^If the second parameter (zDbName) does not match the name of any
  8043. ** open database file, then SQLITE_ERROR is returned. ^This error
  8044. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  8045. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  8046. ** also return SQLITE_ERROR. There is no way to distinguish between
  8047. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  8048. ** xFileControl method.
  8049. **
  8050. ** See also: [file control opcodes]
  8051. */
  8052. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  8053. /*
  8054. ** CAPI3REF: Testing Interface
  8055. **
  8056. ** ^The sqlite3_test_control() interface is used to read out internal
  8057. ** state of SQLite and to inject faults into SQLite for testing
  8058. ** purposes. ^The first parameter is an operation code that determines
  8059. ** the number, meaning, and operation of all subsequent parameters.
  8060. **
  8061. ** This interface is not for use by applications. It exists solely
  8062. ** for verifying the correct operation of the SQLite library. Depending
  8063. ** on how the SQLite library is compiled, this interface might not exist.
  8064. **
  8065. ** The details of the operation codes, their meanings, the parameters
  8066. ** they take, and what they do are all subject to change without notice.
  8067. ** Unlike most of the SQLite API, this function is not guaranteed to
  8068. ** operate consistently from one release to the next.
  8069. */
  8070. SQLITE_API int sqlite3_test_control(int op, ...);
  8071. /*
  8072. ** CAPI3REF: Testing Interface Operation Codes
  8073. **
  8074. ** These constants are the valid operation code parameters used
  8075. ** as the first argument to [sqlite3_test_control()].
  8076. **
  8077. ** These parameters and their meanings are subject to change
  8078. ** without notice. These values are for testing purposes only.
  8079. ** Applications should not use any of these parameters or the
  8080. ** [sqlite3_test_control()] interface.
  8081. */
  8082. #define SQLITE_TESTCTRL_FIRST 5
  8083. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  8084. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  8085. #define SQLITE_TESTCTRL_PRNG_RESET 7
  8086. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  8087. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  8088. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  8089. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  8090. #define SQLITE_TESTCTRL_ASSERT 12
  8091. #define SQLITE_TESTCTRL_ALWAYS 13
  8092. #define SQLITE_TESTCTRL_RESERVE 14
  8093. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  8094. #define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */
  8095. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
  8096. #define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17
  8097. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  8098. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  8099. #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
  8100. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  8101. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  8102. #define SQLITE_TESTCTRL_BYTEORDER 22
  8103. #define SQLITE_TESTCTRL_ISINIT 23
  8104. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  8105. #define SQLITE_TESTCTRL_IMPOSTER 25
  8106. #define SQLITE_TESTCTRL_PARSER_COVERAGE 26
  8107. #define SQLITE_TESTCTRL_LAST 26 /* Largest TESTCTRL */
  8108. /*
  8109. ** CAPI3REF: SQL Keyword Checking
  8110. **
  8111. ** These routines provide access to the set of SQL language keywords
  8112. ** recognized by SQLite. Applications can uses these routines to determine
  8113. ** whether or not a specific identifier needs to be escaped (for example,
  8114. ** by enclosing in double-quotes) so as not to confuse the parser.
  8115. **
  8116. ** The sqlite3_keyword_count() interface returns the number of distinct
  8117. ** keywords understood by SQLite.
  8118. **
  8119. ** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
  8120. ** makes *Z point to that keyword expressed as UTF8 and writes the number
  8121. ** of bytes in the keyword into *L. The string that *Z points to is not
  8122. ** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
  8123. ** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
  8124. ** or L are NULL or invalid pointers then calls to
  8125. ** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
  8126. **
  8127. ** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
  8128. ** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
  8129. ** if it is and zero if not.
  8130. **
  8131. ** The parser used by SQLite is forgiving. It is often possible to use
  8132. ** a keyword as an identifier as long as such use does not result in a
  8133. ** parsing ambiguity. For example, the statement
  8134. ** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
  8135. ** creates a new table named "BEGIN" with three columns named
  8136. ** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid
  8137. ** using keywords as identifiers. Common techniques used to avoid keyword
  8138. ** name collisions include:
  8139. ** <ul>
  8140. ** <li> Put all identifier names inside double-quotes. This is the official
  8141. ** SQL way to escape identifier names.
  8142. ** <li> Put identifier names inside &#91;...&#93;. This is not standard SQL,
  8143. ** but it is what SQL Server does and so lots of programmers use this
  8144. ** technique.
  8145. ** <li> Begin every identifier with the letter "Z" as no SQL keywords start
  8146. ** with "Z".
  8147. ** <li> Include a digit somewhere in every identifier name.
  8148. ** </ul>
  8149. **
  8150. ** Note that the number of keywords understood by SQLite can depend on
  8151. ** compile-time options. For example, "VACUUM" is not a keyword if
  8152. ** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
  8153. ** new keywords may be added to future releases of SQLite.
  8154. */
  8155. SQLITE_API int sqlite3_keyword_count(void);
  8156. SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
  8157. SQLITE_API int sqlite3_keyword_check(const char*,int);
  8158. /*
  8159. ** CAPI3REF: Dynamic String Object
  8160. ** KEYWORDS: {dynamic string}
  8161. **
  8162. ** An instance of the sqlite3_str object contains a dynamically-sized
  8163. ** string under construction.
  8164. **
  8165. ** The lifecycle of an sqlite3_str object is as follows:
  8166. ** <ol>
  8167. ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
  8168. ** <li> ^Text is appended to the sqlite3_str object using various
  8169. ** methods, such as [sqlite3_str_appendf()].
  8170. ** <li> ^The sqlite3_str object is destroyed and the string it created
  8171. ** is returned using the [sqlite3_str_finish()] interface.
  8172. ** </ol>
  8173. */
  8174. typedef struct sqlite3_str sqlite3_str;
  8175. /*
  8176. ** CAPI3REF: Create A New Dynamic String Object
  8177. ** CONSTRUCTOR: sqlite3_str
  8178. **
  8179. ** ^The [sqlite3_str_new(D)] interface allocates and initializes
  8180. ** a new [sqlite3_str] object. To avoid memory leaks, the object returned by
  8181. ** [sqlite3_str_new()] must be freed by a subsequent call to
  8182. ** [sqlite3_str_finish(X)].
  8183. **
  8184. ** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
  8185. ** valid [sqlite3_str] object, though in the event of an out-of-memory
  8186. ** error the returned object might be a special singleton that will
  8187. ** silently reject new text, always return SQLITE_NOMEM from
  8188. ** [sqlite3_str_errcode()], always return 0 for
  8189. ** [sqlite3_str_length()], and always return NULL from
  8190. ** [sqlite3_str_finish(X)]. It is always safe to use the value
  8191. ** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
  8192. ** to any of the other [sqlite3_str] methods.
  8193. **
  8194. ** The D parameter to [sqlite3_str_new(D)] may be NULL. If the
  8195. ** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
  8196. ** length of the string contained in the [sqlite3_str] object will be
  8197. ** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
  8198. ** of [SQLITE_MAX_LENGTH].
  8199. */
  8200. SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
  8201. /*
  8202. ** CAPI3REF: Finalize A Dynamic String
  8203. ** DESTRUCTOR: sqlite3_str
  8204. **
  8205. ** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
  8206. ** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
  8207. ** that contains the constructed string. The calling application should
  8208. ** pass the returned value to [sqlite3_free()] to avoid a memory leak.
  8209. ** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
  8210. ** errors were encountered during construction of the string. ^The
  8211. ** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
  8212. ** string in [sqlite3_str] object X is zero bytes long.
  8213. */
  8214. SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
  8215. /*
  8216. ** CAPI3REF: Add Content To A Dynamic String
  8217. ** METHOD: sqlite3_str
  8218. **
  8219. ** These interfaces add content to an sqlite3_str object previously obtained
  8220. ** from [sqlite3_str_new()].
  8221. **
  8222. ** ^The [sqlite3_str_appendf(X,F,...)] and
  8223. ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
  8224. ** functionality of SQLite to append formatted text onto the end of
  8225. ** [sqlite3_str] object X.
  8226. **
  8227. ** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
  8228. ** onto the end of the [sqlite3_str] object X. N must be non-negative.
  8229. ** S must contain at least N non-zero bytes of content. To append a
  8230. ** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
  8231. ** method instead.
  8232. **
  8233. ** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
  8234. ** zero-terminated string S onto the end of [sqlite3_str] object X.
  8235. **
  8236. ** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
  8237. ** single-byte character C onto the end of [sqlite3_str] object X.
  8238. ** ^This method can be used, for example, to add whitespace indentation.
  8239. **
  8240. ** ^The [sqlite3_str_reset(X)] method resets the string under construction
  8241. ** inside [sqlite3_str] object X back to zero bytes in length.
  8242. **
  8243. ** These methods do not return a result code. ^If an error occurs, that fact
  8244. ** is recorded in the [sqlite3_str] object and can be recovered by a
  8245. ** subsequent call to [sqlite3_str_errcode(X)].
  8246. */
  8247. SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
  8248. SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
  8249. SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
  8250. SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
  8251. SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
  8252. SQLITE_API void sqlite3_str_reset(sqlite3_str*);
  8253. /*
  8254. ** CAPI3REF: Status Of A Dynamic String
  8255. ** METHOD: sqlite3_str
  8256. **
  8257. ** These interfaces return the current status of an [sqlite3_str] object.
  8258. **
  8259. ** ^If any prior errors have occurred while constructing the dynamic string
  8260. ** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
  8261. ** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns
  8262. ** [SQLITE_NOMEM] following any out-of-memory error, or
  8263. ** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
  8264. ** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
  8265. **
  8266. ** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
  8267. ** of the dynamic string under construction in [sqlite3_str] object X.
  8268. ** ^The length returned by [sqlite3_str_length(X)] does not include the
  8269. ** zero-termination byte.
  8270. **
  8271. ** ^The [sqlite3_str_value(X)] method returns a pointer to the current
  8272. ** content of the dynamic string under construction in X. The value
  8273. ** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
  8274. ** and might be freed or altered by any subsequent method on the same
  8275. ** [sqlite3_str] object. Applications must not used the pointer returned
  8276. ** [sqlite3_str_value(X)] after any subsequent method call on the same
  8277. ** object. ^Applications may change the content of the string returned
  8278. ** by [sqlite3_str_value(X)] as long as they do not write into any bytes
  8279. ** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
  8280. ** write any byte after any subsequent sqlite3_str method call.
  8281. */
  8282. SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
  8283. SQLITE_API int sqlite3_str_length(sqlite3_str*);
  8284. SQLITE_API char *sqlite3_str_value(sqlite3_str*);
  8285. /*
  8286. ** CAPI3REF: SQLite Runtime Status
  8287. **
  8288. ** ^These interfaces are used to retrieve runtime status information
  8289. ** about the performance of SQLite, and optionally to reset various
  8290. ** highwater marks. ^The first argument is an integer code for
  8291. ** the specific parameter to measure. ^(Recognized integer codes
  8292. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  8293. ** ^The current value of the parameter is returned into *pCurrent.
  8294. ** ^The highest recorded value is returned in *pHighwater. ^If the
  8295. ** resetFlag is true, then the highest record value is reset after
  8296. ** *pHighwater is written. ^(Some parameters do not record the highest
  8297. ** value. For those parameters
  8298. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  8299. ** ^(Other parameters record only the highwater mark and not the current
  8300. ** value. For these latter parameters nothing is written into *pCurrent.)^
  8301. **
  8302. ** ^The sqlite3_status() and sqlite3_status64() routines return
  8303. ** SQLITE_OK on success and a non-zero [error code] on failure.
  8304. **
  8305. ** If either the current value or the highwater mark is too large to
  8306. ** be represented by a 32-bit integer, then the values returned by
  8307. ** sqlite3_status() are undefined.
  8308. **
  8309. ** See also: [sqlite3_db_status()]
  8310. */
  8311. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  8312. SQLITE_API int sqlite3_status64(
  8313. int op,
  8314. sqlite3_int64 *pCurrent,
  8315. sqlite3_int64 *pHighwater,
  8316. int resetFlag
  8317. );
  8318. /*
  8319. ** CAPI3REF: Status Parameters
  8320. ** KEYWORDS: {status parameters}
  8321. **
  8322. ** These integer constants designate various run-time status parameters
  8323. ** that can be returned by [sqlite3_status()].
  8324. **
  8325. ** <dl>
  8326. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  8327. ** <dd>This parameter is the current amount of memory checked out
  8328. ** using [sqlite3_malloc()], either directly or indirectly. The
  8329. ** figure includes calls made to [sqlite3_malloc()] by the application
  8330. ** and internal memory usage by the SQLite library. Auxiliary page-cache
  8331. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  8332. ** this parameter. The amount returned is the sum of the allocation
  8333. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  8334. **
  8335. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  8336. ** <dd>This parameter records the largest memory allocation request
  8337. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  8338. ** internal equivalents). Only the value returned in the
  8339. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  8340. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8341. **
  8342. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  8343. ** <dd>This parameter records the number of separate memory allocations
  8344. ** currently checked out.</dd>)^
  8345. **
  8346. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  8347. ** <dd>This parameter returns the number of pages used out of the
  8348. ** [pagecache memory allocator] that was configured using
  8349. ** [SQLITE_CONFIG_PAGECACHE]. The
  8350. ** value returned is in pages, not in bytes.</dd>)^
  8351. **
  8352. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  8353. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  8354. ** <dd>This parameter returns the number of bytes of page cache
  8355. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  8356. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  8357. ** returned value includes allocations that overflowed because they
  8358. ** where too large (they were larger than the "sz" parameter to
  8359. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  8360. ** no space was left in the page cache.</dd>)^
  8361. **
  8362. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  8363. ** <dd>This parameter records the largest memory allocation request
  8364. ** handed to [pagecache memory allocator]. Only the value returned in the
  8365. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  8366. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8367. **
  8368. ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
  8369. ** <dd>No longer used.</dd>
  8370. **
  8371. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  8372. ** <dd>No longer used.</dd>
  8373. **
  8374. ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  8375. ** <dd>No longer used.</dd>
  8376. **
  8377. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  8378. ** <dd>The *pHighwater parameter records the deepest parser stack.
  8379. ** The *pCurrent value is undefined. The *pHighwater value is only
  8380. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  8381. ** </dl>
  8382. **
  8383. ** New status parameters may be added from time to time.
  8384. */
  8385. #define SQLITE_STATUS_MEMORY_USED 0
  8386. #define SQLITE_STATUS_PAGECACHE_USED 1
  8387. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  8388. #define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */
  8389. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
  8390. #define SQLITE_STATUS_MALLOC_SIZE 5
  8391. #define SQLITE_STATUS_PARSER_STACK 6
  8392. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  8393. #define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
  8394. #define SQLITE_STATUS_MALLOC_COUNT 9
  8395. /*
  8396. ** CAPI3REF: Database Connection Status
  8397. ** METHOD: sqlite3
  8398. **
  8399. ** ^This interface is used to retrieve runtime status information
  8400. ** about a single [database connection]. ^The first argument is the
  8401. ** database connection object to be interrogated. ^The second argument
  8402. ** is an integer constant, taken from the set of
  8403. ** [SQLITE_DBSTATUS options], that
  8404. ** determines the parameter to interrogate. The set of
  8405. ** [SQLITE_DBSTATUS options] is likely
  8406. ** to grow in future releases of SQLite.
  8407. **
  8408. ** ^The current value of the requested parameter is written into *pCur
  8409. ** and the highest instantaneous value is written into *pHiwtr. ^If
  8410. ** the resetFlg is true, then the highest instantaneous value is
  8411. ** reset back down to the current value.
  8412. **
  8413. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  8414. ** non-zero [error code] on failure.
  8415. **
  8416. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  8417. */
  8418. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  8419. /*
  8420. ** CAPI3REF: Status Parameters for database connections
  8421. ** KEYWORDS: {SQLITE_DBSTATUS options}
  8422. **
  8423. ** These constants are the available integer "verbs" that can be passed as
  8424. ** the second argument to the [sqlite3_db_status()] interface.
  8425. **
  8426. ** New verbs may be added in future releases of SQLite. Existing verbs
  8427. ** might be discontinued. Applications should check the return code from
  8428. ** [sqlite3_db_status()] to make sure that the call worked.
  8429. ** The [sqlite3_db_status()] interface will return a non-zero error code
  8430. ** if a discontinued or unsupported verb is invoked.
  8431. **
  8432. ** <dl>
  8433. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  8434. ** <dd>This parameter returns the number of lookaside memory slots currently
  8435. ** checked out.</dd>)^
  8436. **
  8437. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  8438. ** <dd>This parameter returns the number malloc attempts that were
  8439. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  8440. ** the current value is always zero.)^
  8441. **
  8442. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  8443. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  8444. ** <dd>This parameter returns the number malloc attempts that might have
  8445. ** been satisfied using lookaside memory but failed due to the amount of
  8446. ** memory requested being larger than the lookaside slot size.
  8447. ** Only the high-water value is meaningful;
  8448. ** the current value is always zero.)^
  8449. **
  8450. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  8451. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  8452. ** <dd>This parameter returns the number malloc attempts that might have
  8453. ** been satisfied using lookaside memory but failed due to all lookaside
  8454. ** memory already being in use.
  8455. ** Only the high-water value is meaningful;
  8456. ** the current value is always zero.)^
  8457. **
  8458. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  8459. ** <dd>This parameter returns the approximate number of bytes of heap
  8460. ** memory used by all pager caches associated with the database connection.)^
  8461. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  8462. **
  8463. ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
  8464. ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
  8465. ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
  8466. ** pager cache is shared between two or more connections the bytes of heap
  8467. ** memory used by that pager cache is divided evenly between the attached
  8468. ** connections.)^ In other words, if none of the pager caches associated
  8469. ** with the database connection are shared, this request returns the same
  8470. ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
  8471. ** shared, the value returned by this call will be smaller than that returned
  8472. ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
  8473. ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
  8474. **
  8475. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  8476. ** <dd>This parameter returns the approximate number of bytes of heap
  8477. ** memory used to store the schema for all databases associated
  8478. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  8479. ** ^The full amount of memory used by the schemas is reported, even if the
  8480. ** schema memory is shared with other database connections due to
  8481. ** [shared cache mode] being enabled.
  8482. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  8483. **
  8484. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  8485. ** <dd>This parameter returns the approximate number of bytes of heap
  8486. ** and lookaside memory used by all prepared statements associated with
  8487. ** the database connection.)^
  8488. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  8489. ** </dd>
  8490. **
  8491. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  8492. ** <dd>This parameter returns the number of pager cache hits that have
  8493. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  8494. ** is always 0.
  8495. ** </dd>
  8496. **
  8497. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  8498. ** <dd>This parameter returns the number of pager cache misses that have
  8499. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  8500. ** is always 0.
  8501. ** </dd>
  8502. **
  8503. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  8504. ** <dd>This parameter returns the number of dirty cache entries that have
  8505. ** been written to disk. Specifically, the number of pages written to the
  8506. ** wal file in wal mode databases, or the number of pages written to the
  8507. ** database file in rollback mode databases. Any pages written as part of
  8508. ** transaction rollback or database recovery operations are not included.
  8509. ** If an IO or other error occurs while writing a page to disk, the effect
  8510. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  8511. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  8512. ** </dd>
  8513. **
  8514. ** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
  8515. ** <dd>This parameter returns the number of dirty cache entries that have
  8516. ** been written to disk in the middle of a transaction due to the page
  8517. ** cache overflowing. Transactions are more efficient if they are written
  8518. ** to disk all at once. When pages spill mid-transaction, that introduces
  8519. ** additional overhead. This parameter can be used help identify
  8520. ** inefficiencies that can be resolve by increasing the cache size.
  8521. ** </dd>
  8522. **
  8523. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  8524. ** <dd>This parameter returns zero for the current value if and only if
  8525. ** all foreign key constraints (deferred or immediate) have been
  8526. ** resolved.)^ ^The highwater mark is always 0.
  8527. ** </dd>
  8528. ** </dl>
  8529. */
  8530. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  8531. #define SQLITE_DBSTATUS_CACHE_USED 1
  8532. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  8533. #define SQLITE_DBSTATUS_STMT_USED 3
  8534. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  8535. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  8536. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  8537. #define SQLITE_DBSTATUS_CACHE_HIT 7
  8538. #define SQLITE_DBSTATUS_CACHE_MISS 8
  8539. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  8540. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  8541. #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
  8542. #define SQLITE_DBSTATUS_CACHE_SPILL 12
  8543. #define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */
  8544. /*
  8545. ** CAPI3REF: Prepared Statement Status
  8546. ** METHOD: sqlite3_stmt
  8547. **
  8548. ** ^(Each prepared statement maintains various
  8549. ** [SQLITE_STMTSTATUS counters] that measure the number
  8550. ** of times it has performed specific operations.)^ These counters can
  8551. ** be used to monitor the performance characteristics of the prepared
  8552. ** statements. For example, if the number of table steps greatly exceeds
  8553. ** the number of table searches or result rows, that would tend to indicate
  8554. ** that the prepared statement is using a full table scan rather than
  8555. ** an index.
  8556. **
  8557. ** ^(This interface is used to retrieve and reset counter values from
  8558. ** a [prepared statement]. The first argument is the prepared statement
  8559. ** object to be interrogated. The second argument
  8560. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  8561. ** to be interrogated.)^
  8562. ** ^The current value of the requested counter is returned.
  8563. ** ^If the resetFlg is true, then the counter is reset to zero after this
  8564. ** interface call returns.
  8565. **
  8566. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  8567. */
  8568. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  8569. /*
  8570. ** CAPI3REF: Status Parameters for prepared statements
  8571. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  8572. **
  8573. ** These preprocessor macros define integer codes that name counter
  8574. ** values associated with the [sqlite3_stmt_status()] interface.
  8575. ** The meanings of the various counters are as follows:
  8576. **
  8577. ** <dl>
  8578. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  8579. ** <dd>^This is the number of times that SQLite has stepped forward in
  8580. ** a table as part of a full table scan. Large numbers for this counter
  8581. ** may indicate opportunities for performance improvement through
  8582. ** careful use of indices.</dd>
  8583. **
  8584. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  8585. ** <dd>^This is the number of sort operations that have occurred.
  8586. ** A non-zero value in this counter may indicate an opportunity to
  8587. ** improvement performance through careful use of indices.</dd>
  8588. **
  8589. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  8590. ** <dd>^This is the number of rows inserted into transient indices that
  8591. ** were created automatically in order to help joins run faster.
  8592. ** A non-zero value in this counter may indicate an opportunity to
  8593. ** improvement performance by adding permanent indices that do not
  8594. ** need to be reinitialized each time the statement is run.</dd>
  8595. **
  8596. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  8597. ** <dd>^This is the number of virtual machine operations executed
  8598. ** by the prepared statement if that number is less than or equal
  8599. ** to 2147483647. The number of virtual machine operations can be
  8600. ** used as a proxy for the total work done by the prepared statement.
  8601. ** If the number of virtual machine operations exceeds 2147483647
  8602. ** then the value returned by this statement status code is undefined.
  8603. **
  8604. ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
  8605. ** <dd>^This is the number of times that the prepare statement has been
  8606. ** automatically regenerated due to schema changes or change to
  8607. ** [bound parameters] that might affect the query plan.
  8608. **
  8609. ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
  8610. ** <dd>^This is the number of times that the prepared statement has
  8611. ** been run. A single "run" for the purposes of this counter is one
  8612. ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
  8613. ** The counter is incremented on the first [sqlite3_step()] call of each
  8614. ** cycle.
  8615. **
  8616. ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
  8617. ** <dd>^This is the approximate number of bytes of heap memory
  8618. ** used to store the prepared statement. ^This value is not actually
  8619. ** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
  8620. ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
  8621. ** </dd>
  8622. ** </dl>
  8623. */
  8624. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  8625. #define SQLITE_STMTSTATUS_SORT 2
  8626. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  8627. #define SQLITE_STMTSTATUS_VM_STEP 4
  8628. #define SQLITE_STMTSTATUS_REPREPARE 5
  8629. #define SQLITE_STMTSTATUS_RUN 6
  8630. #define SQLITE_STMTSTATUS_MEMUSED 99
  8631. /*
  8632. ** CAPI3REF: Custom Page Cache Object
  8633. **
  8634. ** The sqlite3_pcache type is opaque. It is implemented by
  8635. ** the pluggable module. The SQLite core has no knowledge of
  8636. ** its size or internal structure and never deals with the
  8637. ** sqlite3_pcache object except by holding and passing pointers
  8638. ** to the object.
  8639. **
  8640. ** See [sqlite3_pcache_methods2] for additional information.
  8641. */
  8642. typedef struct sqlite3_pcache sqlite3_pcache;
  8643. /*
  8644. ** CAPI3REF: Custom Page Cache Object
  8645. **
  8646. ** The sqlite3_pcache_page object represents a single page in the
  8647. ** page cache. The page cache will allocate instances of this
  8648. ** object. Various methods of the page cache use pointers to instances
  8649. ** of this object as parameters or as their return value.
  8650. **
  8651. ** See [sqlite3_pcache_methods2] for additional information.
  8652. */
  8653. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  8654. struct sqlite3_pcache_page {
  8655. void *pBuf; /* The content of the page */
  8656. void *pExtra; /* Extra information associated with the page */
  8657. };
  8658. /*
  8659. ** CAPI3REF: Application Defined Page Cache.
  8660. ** KEYWORDS: {page cache}
  8661. **
  8662. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  8663. ** register an alternative page cache implementation by passing in an
  8664. ** instance of the sqlite3_pcache_methods2 structure.)^
  8665. ** In many applications, most of the heap memory allocated by
  8666. ** SQLite is used for the page cache.
  8667. ** By implementing a
  8668. ** custom page cache using this API, an application can better control
  8669. ** the amount of memory consumed by SQLite, the way in which
  8670. ** that memory is allocated and released, and the policies used to
  8671. ** determine exactly which parts of a database file are cached and for
  8672. ** how long.
  8673. **
  8674. ** The alternative page cache mechanism is an
  8675. ** extreme measure that is only needed by the most demanding applications.
  8676. ** The built-in page cache is recommended for most uses.
  8677. **
  8678. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  8679. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  8680. ** the application may discard the parameter after the call to
  8681. ** [sqlite3_config()] returns.)^
  8682. **
  8683. ** [[the xInit() page cache method]]
  8684. ** ^(The xInit() method is called once for each effective
  8685. ** call to [sqlite3_initialize()])^
  8686. ** (usually only once during the lifetime of the process). ^(The xInit()
  8687. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  8688. ** The intent of the xInit() method is to set up global data structures
  8689. ** required by the custom page cache implementation.
  8690. ** ^(If the xInit() method is NULL, then the
  8691. ** built-in default page cache is used instead of the application defined
  8692. ** page cache.)^
  8693. **
  8694. ** [[the xShutdown() page cache method]]
  8695. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  8696. ** It can be used to clean up
  8697. ** any outstanding resources before process shutdown, if required.
  8698. ** ^The xShutdown() method may be NULL.
  8699. **
  8700. ** ^SQLite automatically serializes calls to the xInit method,
  8701. ** so the xInit method need not be threadsafe. ^The
  8702. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  8703. ** not need to be threadsafe either. All other methods must be threadsafe
  8704. ** in multithreaded applications.
  8705. **
  8706. ** ^SQLite will never invoke xInit() more than once without an intervening
  8707. ** call to xShutdown().
  8708. **
  8709. ** [[the xCreate() page cache methods]]
  8710. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  8711. ** SQLite will typically create one cache instance for each open database file,
  8712. ** though this is not guaranteed. ^The
  8713. ** first parameter, szPage, is the size in bytes of the pages that must
  8714. ** be allocated by the cache. ^szPage will always a power of two. ^The
  8715. ** second parameter szExtra is a number of bytes of extra storage
  8716. ** associated with each page cache entry. ^The szExtra parameter will
  8717. ** a number less than 250. SQLite will use the
  8718. ** extra szExtra bytes on each page to store metadata about the underlying
  8719. ** database page on disk. The value passed into szExtra depends
  8720. ** on the SQLite version, the target platform, and how SQLite was compiled.
  8721. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  8722. ** created will be used to cache database pages of a file stored on disk, or
  8723. ** false if it is used for an in-memory database. The cache implementation
  8724. ** does not have to do anything special based with the value of bPurgeable;
  8725. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  8726. ** never invoke xUnpin() except to deliberately delete a page.
  8727. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  8728. ** false will always have the "discard" flag set to true.
  8729. ** ^Hence, a cache created with bPurgeable false will
  8730. ** never contain any unpinned pages.
  8731. **
  8732. ** [[the xCachesize() page cache method]]
  8733. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  8734. ** suggested maximum cache-size (number of pages stored by) the cache
  8735. ** instance passed as the first argument. This is the value configured using
  8736. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  8737. ** parameter, the implementation is not required to do anything with this
  8738. ** value; it is advisory only.
  8739. **
  8740. ** [[the xPagecount() page cache methods]]
  8741. ** The xPagecount() method must return the number of pages currently
  8742. ** stored in the cache, both pinned and unpinned.
  8743. **
  8744. ** [[the xFetch() page cache methods]]
  8745. ** The xFetch() method locates a page in the cache and returns a pointer to
  8746. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  8747. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  8748. ** pointer to a buffer of szPage bytes used to store the content of a
  8749. ** single database page. The pExtra element of sqlite3_pcache_page will be
  8750. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  8751. ** for each entry in the page cache.
  8752. **
  8753. ** The page to be fetched is determined by the key. ^The minimum key value
  8754. ** is 1. After it has been retrieved using xFetch, the page is considered
  8755. ** to be "pinned".
  8756. **
  8757. ** If the requested page is already in the page cache, then the page cache
  8758. ** implementation must return a pointer to the page buffer with its content
  8759. ** intact. If the requested page is not already in the cache, then the
  8760. ** cache implementation should use the value of the createFlag
  8761. ** parameter to help it determined what action to take:
  8762. **
  8763. ** <table border=1 width=85% align=center>
  8764. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  8765. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  8766. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  8767. ** Otherwise return NULL.
  8768. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  8769. ** NULL if allocating a new page is effectively impossible.
  8770. ** </table>
  8771. **
  8772. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  8773. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  8774. ** failed.)^ In between the to xFetch() calls, SQLite may
  8775. ** attempt to unpin one or more cache pages by spilling the content of
  8776. ** pinned pages to disk and synching the operating system disk cache.
  8777. **
  8778. ** [[the xUnpin() page cache method]]
  8779. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  8780. ** as its second argument. If the third parameter, discard, is non-zero,
  8781. ** then the page must be evicted from the cache.
  8782. ** ^If the discard parameter is
  8783. ** zero, then the page may be discarded or retained at the discretion of
  8784. ** page cache implementation. ^The page cache implementation
  8785. ** may choose to evict unpinned pages at any time.
  8786. **
  8787. ** The cache must not perform any reference counting. A single
  8788. ** call to xUnpin() unpins the page regardless of the number of prior calls
  8789. ** to xFetch().
  8790. **
  8791. ** [[the xRekey() page cache methods]]
  8792. ** The xRekey() method is used to change the key value associated with the
  8793. ** page passed as the second argument. If the cache
  8794. ** previously contains an entry associated with newKey, it must be
  8795. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  8796. ** to be pinned.
  8797. **
  8798. ** When SQLite calls the xTruncate() method, the cache must discard all
  8799. ** existing cache entries with page numbers (keys) greater than or equal
  8800. ** to the value of the iLimit parameter passed to xTruncate(). If any
  8801. ** of these pages are pinned, they are implicitly unpinned, meaning that
  8802. ** they can be safely discarded.
  8803. **
  8804. ** [[the xDestroy() page cache method]]
  8805. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  8806. ** All resources associated with the specified cache should be freed. ^After
  8807. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  8808. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  8809. ** functions.
  8810. **
  8811. ** [[the xShrink() page cache method]]
  8812. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  8813. ** free up as much of heap memory as possible. The page cache implementation
  8814. ** is not obligated to free any memory, but well-behaved implementations should
  8815. ** do their best.
  8816. */
  8817. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  8818. struct sqlite3_pcache_methods2 {
  8819. int iVersion;
  8820. void *pArg;
  8821. int (*xInit)(void*);
  8822. void (*xShutdown)(void*);
  8823. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  8824. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8825. int (*xPagecount)(sqlite3_pcache*);
  8826. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8827. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  8828. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  8829. unsigned oldKey, unsigned newKey);
  8830. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8831. void (*xDestroy)(sqlite3_pcache*);
  8832. void (*xShrink)(sqlite3_pcache*);
  8833. };
  8834. /*
  8835. ** This is the obsolete pcache_methods object that has now been replaced
  8836. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  8837. ** retained in the header file for backwards compatibility only.
  8838. */
  8839. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  8840. struct sqlite3_pcache_methods {
  8841. void *pArg;
  8842. int (*xInit)(void*);
  8843. void (*xShutdown)(void*);
  8844. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  8845. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8846. int (*xPagecount)(sqlite3_pcache*);
  8847. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8848. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  8849. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  8850. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8851. void (*xDestroy)(sqlite3_pcache*);
  8852. };
  8853. /*
  8854. ** CAPI3REF: Online Backup Object
  8855. **
  8856. ** The sqlite3_backup object records state information about an ongoing
  8857. ** online backup operation. ^The sqlite3_backup object is created by
  8858. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  8859. ** [sqlite3_backup_finish()].
  8860. **
  8861. ** See Also: [Using the SQLite Online Backup API]
  8862. */
  8863. typedef struct sqlite3_backup sqlite3_backup;
  8864. /*
  8865. ** CAPI3REF: Online Backup API.
  8866. **
  8867. ** The backup API copies the content of one database into another.
  8868. ** It is useful either for creating backups of databases or
  8869. ** for copying in-memory databases to or from persistent files.
  8870. **
  8871. ** See Also: [Using the SQLite Online Backup API]
  8872. **
  8873. ** ^SQLite holds a write transaction open on the destination database file
  8874. ** for the duration of the backup operation.
  8875. ** ^The source database is read-locked only while it is being read;
  8876. ** it is not locked continuously for the entire backup operation.
  8877. ** ^Thus, the backup may be performed on a live source database without
  8878. ** preventing other database connections from
  8879. ** reading or writing to the source database while the backup is underway.
  8880. **
  8881. ** ^(To perform a backup operation:
  8882. ** <ol>
  8883. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  8884. ** backup,
  8885. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  8886. ** the data between the two databases, and finally
  8887. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  8888. ** associated with the backup operation.
  8889. ** </ol>)^
  8890. ** There should be exactly one call to sqlite3_backup_finish() for each
  8891. ** successful call to sqlite3_backup_init().
  8892. **
  8893. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  8894. **
  8895. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  8896. ** [database connection] associated with the destination database
  8897. ** and the database name, respectively.
  8898. ** ^The database name is "main" for the main database, "temp" for the
  8899. ** temporary database, or the name specified after the AS keyword in
  8900. ** an [ATTACH] statement for an attached database.
  8901. ** ^The S and M arguments passed to
  8902. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  8903. ** and database name of the source database, respectively.
  8904. ** ^The source and destination [database connections] (parameters S and D)
  8905. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  8906. ** an error.
  8907. **
  8908. ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
  8909. ** there is already a read or read-write transaction open on the
  8910. ** destination database.
  8911. **
  8912. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  8913. ** returned and an error code and error message are stored in the
  8914. ** destination [database connection] D.
  8915. ** ^The error code and message for the failed call to sqlite3_backup_init()
  8916. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  8917. ** [sqlite3_errmsg16()] functions.
  8918. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  8919. ** [sqlite3_backup] object.
  8920. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  8921. ** sqlite3_backup_finish() functions to perform the specified backup
  8922. ** operation.
  8923. **
  8924. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  8925. **
  8926. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  8927. ** the source and destination databases specified by [sqlite3_backup] object B.
  8928. ** ^If N is negative, all remaining source pages are copied.
  8929. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  8930. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  8931. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  8932. ** from source to destination, then it returns [SQLITE_DONE].
  8933. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  8934. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  8935. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  8936. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  8937. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  8938. **
  8939. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  8940. ** <ol>
  8941. ** <li> the destination database was opened read-only, or
  8942. ** <li> the destination database is using write-ahead-log journaling
  8943. ** and the destination and source page sizes differ, or
  8944. ** <li> the destination database is an in-memory database and the
  8945. ** destination and source page sizes differ.
  8946. ** </ol>)^
  8947. **
  8948. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  8949. ** the [sqlite3_busy_handler | busy-handler function]
  8950. ** is invoked (if one is specified). ^If the
  8951. ** busy-handler returns non-zero before the lock is available, then
  8952. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  8953. ** sqlite3_backup_step() can be retried later. ^If the source
  8954. ** [database connection]
  8955. ** is being used to write to the source database when sqlite3_backup_step()
  8956. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  8957. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  8958. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  8959. ** [SQLITE_READONLY] is returned, then
  8960. ** there is no point in retrying the call to sqlite3_backup_step(). These
  8961. ** errors are considered fatal.)^ The application must accept
  8962. ** that the backup operation has failed and pass the backup operation handle
  8963. ** to the sqlite3_backup_finish() to release associated resources.
  8964. **
  8965. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  8966. ** on the destination file. ^The exclusive lock is not released until either
  8967. ** sqlite3_backup_finish() is called or the backup operation is complete
  8968. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  8969. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  8970. ** lasts for the duration of the sqlite3_backup_step() call.
  8971. ** ^Because the source database is not locked between calls to
  8972. ** sqlite3_backup_step(), the source database may be modified mid-way
  8973. ** through the backup process. ^If the source database is modified by an
  8974. ** external process or via a database connection other than the one being
  8975. ** used by the backup operation, then the backup will be automatically
  8976. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  8977. ** database is modified by the using the same database connection as is used
  8978. ** by the backup operation, then the backup database is automatically
  8979. ** updated at the same time.
  8980. **
  8981. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  8982. **
  8983. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  8984. ** application wishes to abandon the backup operation, the application
  8985. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  8986. ** ^The sqlite3_backup_finish() interfaces releases all
  8987. ** resources associated with the [sqlite3_backup] object.
  8988. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  8989. ** active write-transaction on the destination database is rolled back.
  8990. ** The [sqlite3_backup] object is invalid
  8991. ** and may not be used following a call to sqlite3_backup_finish().
  8992. **
  8993. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  8994. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  8995. ** sqlite3_backup_step() completed.
  8996. ** ^If an out-of-memory condition or IO error occurred during any prior
  8997. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  8998. ** sqlite3_backup_finish() returns the corresponding [error code].
  8999. **
  9000. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  9001. ** is not a permanent error and does not affect the return value of
  9002. ** sqlite3_backup_finish().
  9003. **
  9004. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  9005. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  9006. **
  9007. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  9008. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  9009. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  9010. ** in the source database at the conclusion of the most recent
  9011. ** sqlite3_backup_step().
  9012. ** ^(The values returned by these functions are only updated by
  9013. ** sqlite3_backup_step(). If the source database is modified in a way that
  9014. ** changes the size of the source database or the number of pages remaining,
  9015. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  9016. ** and sqlite3_backup_remaining() until after the next
  9017. ** sqlite3_backup_step().)^
  9018. **
  9019. ** <b>Concurrent Usage of Database Handles</b>
  9020. **
  9021. ** ^The source [database connection] may be used by the application for other
  9022. ** purposes while a backup operation is underway or being initialized.
  9023. ** ^If SQLite is compiled and configured to support threadsafe database
  9024. ** connections, then the source database connection may be used concurrently
  9025. ** from within other threads.
  9026. **
  9027. ** However, the application must guarantee that the destination
  9028. ** [database connection] is not passed to any other API (by any thread) after
  9029. ** sqlite3_backup_init() is called and before the corresponding call to
  9030. ** sqlite3_backup_finish(). SQLite does not currently check to see
  9031. ** if the application incorrectly accesses the destination [database connection]
  9032. ** and so no error code is reported, but the operations may malfunction
  9033. ** nevertheless. Use of the destination database connection while a
  9034. ** backup is in progress might also also cause a mutex deadlock.
  9035. **
  9036. ** If running in [shared cache mode], the application must
  9037. ** guarantee that the shared cache used by the destination database
  9038. ** is not accessed while the backup is running. In practice this means
  9039. ** that the application must guarantee that the disk file being
  9040. ** backed up to is not accessed by any connection within the process,
  9041. ** not just the specific connection that was passed to sqlite3_backup_init().
  9042. **
  9043. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  9044. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  9045. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  9046. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  9047. ** same time as another thread is invoking sqlite3_backup_step() it is
  9048. ** possible that they return invalid values.
  9049. */
  9050. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  9051. sqlite3 *pDest, /* Destination database handle */
  9052. const char *zDestName, /* Destination database name */
  9053. sqlite3 *pSource, /* Source database handle */
  9054. const char *zSourceName /* Source database name */
  9055. );
  9056. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  9057. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  9058. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  9059. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  9060. /*
  9061. ** CAPI3REF: Unlock Notification
  9062. ** METHOD: sqlite3
  9063. **
  9064. ** ^When running in shared-cache mode, a database operation may fail with
  9065. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  9066. ** individual tables within the shared-cache cannot be obtained. See
  9067. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  9068. ** ^This API may be used to register a callback that SQLite will invoke
  9069. ** when the connection currently holding the required lock relinquishes it.
  9070. ** ^This API is only available if the library was compiled with the
  9071. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  9072. **
  9073. ** See Also: [Using the SQLite Unlock Notification Feature].
  9074. **
  9075. ** ^Shared-cache locks are released when a database connection concludes
  9076. ** its current transaction, either by committing it or rolling it back.
  9077. **
  9078. ** ^When a connection (known as the blocked connection) fails to obtain a
  9079. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  9080. ** identity of the database connection (the blocking connection) that
  9081. ** has locked the required resource is stored internally. ^After an
  9082. ** application receives an SQLITE_LOCKED error, it may call the
  9083. ** sqlite3_unlock_notify() method with the blocked connection handle as
  9084. ** the first argument to register for a callback that will be invoked
  9085. ** when the blocking connections current transaction is concluded. ^The
  9086. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  9087. ** call that concludes the blocking connections transaction.
  9088. **
  9089. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  9090. ** there is a chance that the blocking connection will have already
  9091. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  9092. ** If this happens, then the specified callback is invoked immediately,
  9093. ** from within the call to sqlite3_unlock_notify().)^
  9094. **
  9095. ** ^If the blocked connection is attempting to obtain a write-lock on a
  9096. ** shared-cache table, and more than one other connection currently holds
  9097. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  9098. ** the other connections to use as the blocking connection.
  9099. **
  9100. ** ^(There may be at most one unlock-notify callback registered by a
  9101. ** blocked connection. If sqlite3_unlock_notify() is called when the
  9102. ** blocked connection already has a registered unlock-notify callback,
  9103. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  9104. ** called with a NULL pointer as its second argument, then any existing
  9105. ** unlock-notify callback is canceled. ^The blocked connections
  9106. ** unlock-notify callback may also be canceled by closing the blocked
  9107. ** connection using [sqlite3_close()].
  9108. **
  9109. ** The unlock-notify callback is not reentrant. If an application invokes
  9110. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  9111. ** crash or deadlock may be the result.
  9112. **
  9113. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  9114. ** returns SQLITE_OK.
  9115. **
  9116. ** <b>Callback Invocation Details</b>
  9117. **
  9118. ** When an unlock-notify callback is registered, the application provides a
  9119. ** single void* pointer that is passed to the callback when it is invoked.
  9120. ** However, the signature of the callback function allows SQLite to pass
  9121. ** it an array of void* context pointers. The first argument passed to
  9122. ** an unlock-notify callback is a pointer to an array of void* pointers,
  9123. ** and the second is the number of entries in the array.
  9124. **
  9125. ** When a blocking connections transaction is concluded, there may be
  9126. ** more than one blocked connection that has registered for an unlock-notify
  9127. ** callback. ^If two or more such blocked connections have specified the
  9128. ** same callback function, then instead of invoking the callback function
  9129. ** multiple times, it is invoked once with the set of void* context pointers
  9130. ** specified by the blocked connections bundled together into an array.
  9131. ** This gives the application an opportunity to prioritize any actions
  9132. ** related to the set of unblocked database connections.
  9133. **
  9134. ** <b>Deadlock Detection</b>
  9135. **
  9136. ** Assuming that after registering for an unlock-notify callback a
  9137. ** database waits for the callback to be issued before taking any further
  9138. ** action (a reasonable assumption), then using this API may cause the
  9139. ** application to deadlock. For example, if connection X is waiting for
  9140. ** connection Y's transaction to be concluded, and similarly connection
  9141. ** Y is waiting on connection X's transaction, then neither connection
  9142. ** will proceed and the system may remain deadlocked indefinitely.
  9143. **
  9144. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  9145. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  9146. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  9147. ** unlock-notify callback is registered. The system is said to be in
  9148. ** a deadlocked state if connection A has registered for an unlock-notify
  9149. ** callback on the conclusion of connection B's transaction, and connection
  9150. ** B has itself registered for an unlock-notify callback when connection
  9151. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  9152. ** the system is also considered to be deadlocked if connection B has
  9153. ** registered for an unlock-notify callback on the conclusion of connection
  9154. ** C's transaction, where connection C is waiting on connection A. ^Any
  9155. ** number of levels of indirection are allowed.
  9156. **
  9157. ** <b>The "DROP TABLE" Exception</b>
  9158. **
  9159. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  9160. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  9161. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  9162. ** SQLite checks if there are any currently executing SELECT statements
  9163. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  9164. ** returned. In this case there is no "blocking connection", so invoking
  9165. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  9166. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  9167. ** or "DROP INDEX" query, an infinite loop might be the result.
  9168. **
  9169. ** One way around this problem is to check the extended error code returned
  9170. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  9171. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  9172. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  9173. ** SQLITE_LOCKED.)^
  9174. */
  9175. SQLITE_API int sqlite3_unlock_notify(
  9176. sqlite3 *pBlocked, /* Waiting connection */
  9177. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  9178. void *pNotifyArg /* Argument to pass to xNotify */
  9179. );
  9180. /*
  9181. ** CAPI3REF: String Comparison
  9182. **
  9183. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  9184. ** and extensions to compare the contents of two buffers containing UTF-8
  9185. ** strings in a case-independent fashion, using the same definition of "case
  9186. ** independence" that SQLite uses internally when comparing identifiers.
  9187. */
  9188. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  9189. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  9190. /*
  9191. ** CAPI3REF: String Globbing
  9192. *
  9193. ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  9194. ** string X matches the [GLOB] pattern P.
  9195. ** ^The definition of [GLOB] pattern matching used in
  9196. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  9197. ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
  9198. ** is case sensitive.
  9199. **
  9200. ** Note that this routine returns zero on a match and non-zero if the strings
  9201. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9202. **
  9203. ** See also: [sqlite3_strlike()].
  9204. */
  9205. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  9206. /*
  9207. ** CAPI3REF: String LIKE Matching
  9208. *
  9209. ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  9210. ** string X matches the [LIKE] pattern P with escape character E.
  9211. ** ^The definition of [LIKE] pattern matching used in
  9212. ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  9213. ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
  9214. ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  9215. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  9216. ** insensitive - equivalent upper and lower case ASCII characters match
  9217. ** one another.
  9218. **
  9219. ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  9220. ** only ASCII characters are case folded.
  9221. **
  9222. ** Note that this routine returns zero on a match and non-zero if the strings
  9223. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9224. **
  9225. ** See also: [sqlite3_strglob()].
  9226. */
  9227. SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  9228. /*
  9229. ** CAPI3REF: Error Logging Interface
  9230. **
  9231. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  9232. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  9233. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  9234. ** used with [sqlite3_snprintf()] to generate the final output string.
  9235. **
  9236. ** The sqlite3_log() interface is intended for use by extensions such as
  9237. ** virtual tables, collating functions, and SQL functions. While there is
  9238. ** nothing to prevent an application from calling sqlite3_log(), doing so
  9239. ** is considered bad form.
  9240. **
  9241. ** The zFormat string must not be NULL.
  9242. **
  9243. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  9244. ** will not use dynamically allocated memory. The log message is stored in
  9245. ** a fixed-length buffer on the stack. If the log message is longer than
  9246. ** a few hundred characters, it will be truncated to the length of the
  9247. ** buffer.
  9248. */
  9249. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  9250. /*
  9251. ** CAPI3REF: Write-Ahead Log Commit Hook
  9252. ** METHOD: sqlite3
  9253. **
  9254. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  9255. ** is invoked each time data is committed to a database in wal mode.
  9256. **
  9257. ** ^(The callback is invoked by SQLite after the commit has taken place and
  9258. ** the associated write-lock on the database released)^, so the implementation
  9259. ** may read, write or [checkpoint] the database as required.
  9260. **
  9261. ** ^The first parameter passed to the callback function when it is invoked
  9262. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  9263. ** registering the callback. ^The second is a copy of the database handle.
  9264. ** ^The third parameter is the name of the database that was written to -
  9265. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  9266. ** is the number of pages currently in the write-ahead log file,
  9267. ** including those that were just committed.
  9268. **
  9269. ** The callback function should normally return [SQLITE_OK]. ^If an error
  9270. ** code is returned, that error will propagate back up through the
  9271. ** SQLite code base to cause the statement that provoked the callback
  9272. ** to report an error, though the commit will have still occurred. If the
  9273. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  9274. ** that does not correspond to any valid SQLite error code, the results
  9275. ** are undefined.
  9276. **
  9277. ** A single database handle may have at most a single write-ahead log callback
  9278. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  9279. ** previously registered write-ahead log callback. ^Note that the
  9280. ** [sqlite3_wal_autocheckpoint()] interface and the
  9281. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  9282. ** overwrite any prior [sqlite3_wal_hook()] settings.
  9283. */
  9284. SQLITE_API void *sqlite3_wal_hook(
  9285. sqlite3*,
  9286. int(*)(void *,sqlite3*,const char*,int),
  9287. void*
  9288. );
  9289. /*
  9290. ** CAPI3REF: Configure an auto-checkpoint
  9291. ** METHOD: sqlite3
  9292. **
  9293. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  9294. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  9295. ** to automatically [checkpoint]
  9296. ** after committing a transaction if there are N or
  9297. ** more frames in the [write-ahead log] file. ^Passing zero or
  9298. ** a negative value as the nFrame parameter disables automatic
  9299. ** checkpoints entirely.
  9300. **
  9301. ** ^The callback registered by this function replaces any existing callback
  9302. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  9303. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  9304. ** configured by this function.
  9305. **
  9306. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  9307. ** from SQL.
  9308. **
  9309. ** ^Checkpoints initiated by this mechanism are
  9310. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  9311. **
  9312. ** ^Every new [database connection] defaults to having the auto-checkpoint
  9313. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  9314. ** pages. The use of this interface
  9315. ** is only necessary if the default setting is found to be suboptimal
  9316. ** for a particular application.
  9317. */
  9318. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  9319. /*
  9320. ** CAPI3REF: Checkpoint a database
  9321. ** METHOD: sqlite3
  9322. **
  9323. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  9324. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  9325. **
  9326. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  9327. ** [write-ahead log] for database X on [database connection] D to be
  9328. ** transferred into the database file and for the write-ahead log to
  9329. ** be reset. See the [checkpointing] documentation for addition
  9330. ** information.
  9331. **
  9332. ** This interface used to be the only way to cause a checkpoint to
  9333. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  9334. ** interface was added. This interface is retained for backwards
  9335. ** compatibility and as a convenience for applications that need to manually
  9336. ** start a callback but which do not need the full power (and corresponding
  9337. ** complication) of [sqlite3_wal_checkpoint_v2()].
  9338. */
  9339. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  9340. /*
  9341. ** CAPI3REF: Checkpoint a database
  9342. ** METHOD: sqlite3
  9343. **
  9344. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  9345. ** operation on database X of [database connection] D in mode M. Status
  9346. ** information is written back into integers pointed to by L and C.)^
  9347. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  9348. **
  9349. ** <dl>
  9350. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  9351. ** ^Checkpoint as many frames as possible without waiting for any database
  9352. ** readers or writers to finish, then sync the database file if all frames
  9353. ** in the log were checkpointed. ^The [busy-handler callback]
  9354. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  9355. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  9356. ** if there are concurrent readers or writers.
  9357. **
  9358. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  9359. ** ^This mode blocks (it invokes the
  9360. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  9361. ** database writer and all readers are reading from the most recent database
  9362. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  9363. ** database file. ^This mode blocks new database writers while it is pending,
  9364. ** but new database readers are allowed to continue unimpeded.
  9365. **
  9366. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  9367. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  9368. ** that after checkpointing the log file it blocks (calls the
  9369. ** [busy-handler callback])
  9370. ** until all readers are reading from the database file only. ^This ensures
  9371. ** that the next writer will restart the log file from the beginning.
  9372. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  9373. ** database writer attempts while it is pending, but does not impede readers.
  9374. **
  9375. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  9376. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  9377. ** addition that it also truncates the log file to zero bytes just prior
  9378. ** to a successful return.
  9379. ** </dl>
  9380. **
  9381. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  9382. ** the log file or to -1 if the checkpoint could not run because
  9383. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  9384. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  9385. ** log file (including any that were already checkpointed before the function
  9386. ** was called) or to -1 if the checkpoint could not run due to an error or
  9387. ** because the database is not in WAL mode. ^Note that upon successful
  9388. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  9389. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  9390. **
  9391. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  9392. ** any other process is running a checkpoint operation at the same time, the
  9393. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  9394. ** busy-handler configured, it will not be invoked in this case.
  9395. **
  9396. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  9397. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  9398. ** obtained immediately, and a busy-handler is configured, it is invoked and
  9399. ** the writer lock retried until either the busy-handler returns 0 or the lock
  9400. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  9401. ** database readers as described above. ^If the busy-handler returns 0 before
  9402. ** the writer lock is obtained or while waiting for database readers, the
  9403. ** checkpoint operation proceeds from that point in the same way as
  9404. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  9405. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  9406. **
  9407. ** ^If parameter zDb is NULL or points to a zero length string, then the
  9408. ** specified operation is attempted on all WAL databases [attached] to
  9409. ** [database connection] db. In this case the
  9410. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  9411. ** an SQLITE_BUSY error is encountered when processing one or more of the
  9412. ** attached WAL databases, the operation is still attempted on any remaining
  9413. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  9414. ** error occurs while processing an attached database, processing is abandoned
  9415. ** and the error code is returned to the caller immediately. ^If no error
  9416. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  9417. ** databases, SQLITE_OK is returned.
  9418. **
  9419. ** ^If database zDb is the name of an attached database that is not in WAL
  9420. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  9421. ** zDb is not NULL (or a zero length string) and is not the name of any
  9422. ** attached database, SQLITE_ERROR is returned to the caller.
  9423. **
  9424. ** ^Unless it returns SQLITE_MISUSE,
  9425. ** the sqlite3_wal_checkpoint_v2() interface
  9426. ** sets the error information that is queried by
  9427. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  9428. **
  9429. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  9430. ** from SQL.
  9431. */
  9432. SQLITE_API int sqlite3_wal_checkpoint_v2(
  9433. sqlite3 *db, /* Database handle */
  9434. const char *zDb, /* Name of attached database (or NULL) */
  9435. int eMode, /* SQLITE_CHECKPOINT_* value */
  9436. int *pnLog, /* OUT: Size of WAL log in frames */
  9437. int *pnCkpt /* OUT: Total number of frames checkpointed */
  9438. );
  9439. /*
  9440. ** CAPI3REF: Checkpoint Mode Values
  9441. ** KEYWORDS: {checkpoint mode}
  9442. **
  9443. ** These constants define all valid values for the "checkpoint mode" passed
  9444. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  9445. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  9446. ** meaning of each of these checkpoint modes.
  9447. */
  9448. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  9449. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  9450. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  9451. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  9452. /*
  9453. ** CAPI3REF: Virtual Table Interface Configuration
  9454. **
  9455. ** This function may be called by either the [xConnect] or [xCreate] method
  9456. ** of a [virtual table] implementation to configure
  9457. ** various facets of the virtual table interface.
  9458. **
  9459. ** If this interface is invoked outside the context of an xConnect or
  9460. ** xCreate virtual table method then the behavior is undefined.
  9461. **
  9462. ** At present, there is only one option that may be configured using
  9463. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  9464. ** may be added in the future.
  9465. */
  9466. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  9467. /*
  9468. ** CAPI3REF: Virtual Table Configuration Options
  9469. **
  9470. ** These macros define the various options to the
  9471. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  9472. ** can use to customize and optimize their behavior.
  9473. **
  9474. ** <dl>
  9475. ** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
  9476. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  9477. ** <dd>Calls of the form
  9478. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  9479. ** where X is an integer. If X is zero, then the [virtual table] whose
  9480. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  9481. ** support constraints. In this configuration (which is the default) if
  9482. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  9483. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  9484. ** specified as part of the users SQL statement, regardless of the actual
  9485. ** ON CONFLICT mode specified.
  9486. **
  9487. ** If X is non-zero, then the virtual table implementation guarantees
  9488. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  9489. ** any modifications to internal or persistent data structures have been made.
  9490. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  9491. ** is able to roll back a statement or database transaction, and abandon
  9492. ** or continue processing the current SQL statement as appropriate.
  9493. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  9494. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  9495. ** had been ABORT.
  9496. **
  9497. ** Virtual table implementations that are required to handle OR REPLACE
  9498. ** must do so within the [xUpdate] method. If a call to the
  9499. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  9500. ** CONFLICT policy is REPLACE, the virtual table implementation should
  9501. ** silently replace the appropriate rows within the xUpdate callback and
  9502. ** return SQLITE_OK. Or, if this is not possible, it may return
  9503. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  9504. ** constraint handling.
  9505. ** </dl>
  9506. */
  9507. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  9508. /*
  9509. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  9510. **
  9511. ** This function may only be called from within a call to the [xUpdate] method
  9512. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  9513. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  9514. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  9515. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  9516. ** [virtual table].
  9517. */
  9518. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  9519. /*
  9520. ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
  9521. **
  9522. ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
  9523. ** method of a [virtual table], then it returns true if and only if the
  9524. ** column is being fetched as part of an UPDATE operation during which the
  9525. ** column value will not change. Applications might use this to substitute
  9526. ** a return value that is less expensive to compute and that the corresponding
  9527. ** [xUpdate] method understands as a "no-change" value.
  9528. **
  9529. ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
  9530. ** the column is not changed by the UPDATE statement, then the xColumn
  9531. ** method can optionally return without setting a result, without calling
  9532. ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
  9533. ** In that case, [sqlite3_value_nochange(X)] will return true for the
  9534. ** same column in the [xUpdate] method.
  9535. */
  9536. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
  9537. /*
  9538. ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
  9539. **
  9540. ** This function may only be called from within a call to the [xBestIndex]
  9541. ** method of a [virtual table].
  9542. **
  9543. ** The first argument must be the sqlite3_index_info object that is the
  9544. ** first parameter to the xBestIndex() method. The second argument must be
  9545. ** an index into the aConstraint[] array belonging to the sqlite3_index_info
  9546. ** structure passed to xBestIndex. This function returns a pointer to a buffer
  9547. ** containing the name of the collation sequence for the corresponding
  9548. ** constraint.
  9549. */
  9550. SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
  9551. /*
  9552. ** CAPI3REF: Conflict resolution modes
  9553. ** KEYWORDS: {conflict resolution mode}
  9554. **
  9555. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  9556. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  9557. ** is for the SQL statement being evaluated.
  9558. **
  9559. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  9560. ** return value from the [sqlite3_set_authorizer()] callback and that
  9561. ** [SQLITE_ABORT] is also a [result code].
  9562. */
  9563. #define SQLITE_ROLLBACK 1
  9564. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  9565. #define SQLITE_FAIL 3
  9566. /* #define SQLITE_ABORT 4 // Also an error code */
  9567. #define SQLITE_REPLACE 5
  9568. /*
  9569. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  9570. ** KEYWORDS: {scanstatus options}
  9571. **
  9572. ** The following constants can be used for the T parameter to the
  9573. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  9574. ** different metric for sqlite3_stmt_scanstatus() to return.
  9575. **
  9576. ** When the value returned to V is a string, space to hold that string is
  9577. ** managed by the prepared statement S and will be automatically freed when
  9578. ** S is finalized.
  9579. **
  9580. ** <dl>
  9581. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  9582. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  9583. ** set to the total number of times that the X-th loop has run.</dd>
  9584. **
  9585. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  9586. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  9587. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  9588. **
  9589. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  9590. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  9591. ** query planner's estimate for the average number of rows output from each
  9592. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  9593. ** then this value will approximate the quotient NVISIT/NLOOP and the
  9594. ** product of this value for all prior loops with the same SELECTID will
  9595. ** be the NLOOP value for the current loop.
  9596. **
  9597. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  9598. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9599. ** to a zero-terminated UTF-8 string containing the name of the index or table
  9600. ** used for the X-th loop.
  9601. **
  9602. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  9603. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9604. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  9605. ** description for the X-th loop.
  9606. **
  9607. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  9608. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  9609. ** "select-id" for the X-th loop. The select-id identifies which query or
  9610. ** subquery the loop is part of. The main query has a select-id of zero.
  9611. ** The select-id is the same value as is output in the first column
  9612. ** of an [EXPLAIN QUERY PLAN] query.
  9613. ** </dl>
  9614. */
  9615. #define SQLITE_SCANSTAT_NLOOP 0
  9616. #define SQLITE_SCANSTAT_NVISIT 1
  9617. #define SQLITE_SCANSTAT_EST 2
  9618. #define SQLITE_SCANSTAT_NAME 3
  9619. #define SQLITE_SCANSTAT_EXPLAIN 4
  9620. #define SQLITE_SCANSTAT_SELECTID 5
  9621. /*
  9622. ** CAPI3REF: Prepared Statement Scan Status
  9623. ** METHOD: sqlite3_stmt
  9624. **
  9625. ** This interface returns information about the predicted and measured
  9626. ** performance for pStmt. Advanced applications can use this
  9627. ** interface to compare the predicted and the measured performance and
  9628. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  9629. **
  9630. ** Since this interface is expected to be rarely used, it is only
  9631. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  9632. ** compile-time option.
  9633. **
  9634. ** The "iScanStatusOp" parameter determines which status information to return.
  9635. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  9636. ** of this interface is undefined.
  9637. ** ^The requested measurement is written into a variable pointed to by
  9638. ** the "pOut" parameter.
  9639. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  9640. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  9641. ** zero or greater than or equal to the total number of loops used to implement
  9642. ** the statement - a non-zero value is returned and the variable that pOut
  9643. ** points to is unchanged.
  9644. **
  9645. ** ^Statistics might not be available for all loops in all statements. ^In cases
  9646. ** where there exist loops with no available statistics, this function behaves
  9647. ** as if the loop did not exist - it returns non-zero and leave the variable
  9648. ** that pOut points to unchanged.
  9649. **
  9650. ** See also: [sqlite3_stmt_scanstatus_reset()]
  9651. */
  9652. SQLITE_API int sqlite3_stmt_scanstatus(
  9653. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  9654. int idx, /* Index of loop to report on */
  9655. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  9656. void *pOut /* Result written here */
  9657. );
  9658. /*
  9659. ** CAPI3REF: Zero Scan-Status Counters
  9660. ** METHOD: sqlite3_stmt
  9661. **
  9662. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  9663. **
  9664. ** This API is only available if the library is built with pre-processor
  9665. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  9666. */
  9667. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  9668. /*
  9669. ** CAPI3REF: Flush caches to disk mid-transaction
  9670. **
  9671. ** ^If a write-transaction is open on [database connection] D when the
  9672. ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  9673. ** pages in the pager-cache that are not currently in use are written out
  9674. ** to disk. A dirty page may be in use if a database cursor created by an
  9675. ** active SQL statement is reading from it, or if it is page 1 of a database
  9676. ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
  9677. ** interface flushes caches for all schemas - "main", "temp", and
  9678. ** any [attached] databases.
  9679. **
  9680. ** ^If this function needs to obtain extra database locks before dirty pages
  9681. ** can be flushed to disk, it does so. ^If those locks cannot be obtained
  9682. ** immediately and there is a busy-handler callback configured, it is invoked
  9683. ** in the usual manner. ^If the required lock still cannot be obtained, then
  9684. ** the database is skipped and an attempt made to flush any dirty pages
  9685. ** belonging to the next (if any) database. ^If any databases are skipped
  9686. ** because locks cannot be obtained, but no other error occurs, this
  9687. ** function returns SQLITE_BUSY.
  9688. **
  9689. ** ^If any other error occurs while flushing dirty pages to disk (for
  9690. ** example an IO error or out-of-memory condition), then processing is
  9691. ** abandoned and an SQLite [error code] is returned to the caller immediately.
  9692. **
  9693. ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  9694. **
  9695. ** ^This function does not set the database handle error code or message
  9696. ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  9697. */
  9698. SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
  9699. /*
  9700. ** CAPI3REF: The pre-update hook.
  9701. **
  9702. ** ^These interfaces are only available if SQLite is compiled using the
  9703. ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
  9704. **
  9705. ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
  9706. ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
  9707. ** on a database table.
  9708. ** ^At most one preupdate hook may be registered at a time on a single
  9709. ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
  9710. ** the previous setting.
  9711. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
  9712. ** with a NULL pointer as the second parameter.
  9713. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
  9714. ** the first parameter to callbacks.
  9715. **
  9716. ** ^The preupdate hook only fires for changes to real database tables; the
  9717. ** preupdate hook is not invoked for changes to [virtual tables] or to
  9718. ** system tables like sqlite_master or sqlite_stat1.
  9719. **
  9720. ** ^The second parameter to the preupdate callback is a pointer to
  9721. ** the [database connection] that registered the preupdate hook.
  9722. ** ^The third parameter to the preupdate callback is one of the constants
  9723. ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
  9724. ** kind of update operation that is about to occur.
  9725. ** ^(The fourth parameter to the preupdate callback is the name of the
  9726. ** database within the database connection that is being modified. This
  9727. ** will be "main" for the main database or "temp" for TEMP tables or
  9728. ** the name given after the AS keyword in the [ATTACH] statement for attached
  9729. ** databases.)^
  9730. ** ^The fifth parameter to the preupdate callback is the name of the
  9731. ** table that is being modified.
  9732. **
  9733. ** For an UPDATE or DELETE operation on a [rowid table], the sixth
  9734. ** parameter passed to the preupdate callback is the initial [rowid] of the
  9735. ** row being modified or deleted. For an INSERT operation on a rowid table,
  9736. ** or any operation on a WITHOUT ROWID table, the value of the sixth
  9737. ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
  9738. ** seventh parameter is the final rowid value of the row being inserted
  9739. ** or updated. The value of the seventh parameter passed to the callback
  9740. ** function is not defined for operations on WITHOUT ROWID tables, or for
  9741. ** INSERT operations on rowid tables.
  9742. **
  9743. ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
  9744. ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
  9745. ** provide additional information about a preupdate event. These routines
  9746. ** may only be called from within a preupdate callback. Invoking any of
  9747. ** these routines from outside of a preupdate callback or with a
  9748. ** [database connection] pointer that is different from the one supplied
  9749. ** to the preupdate callback results in undefined and probably undesirable
  9750. ** behavior.
  9751. **
  9752. ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
  9753. ** in the row that is being inserted, updated, or deleted.
  9754. **
  9755. ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
  9756. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9757. ** the table row before it is updated. The N parameter must be between 0
  9758. ** and one less than the number of columns or the behavior will be
  9759. ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
  9760. ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
  9761. ** behavior is undefined. The [sqlite3_value] that P points to
  9762. ** will be destroyed when the preupdate callback returns.
  9763. **
  9764. ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
  9765. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9766. ** the table row after it is updated. The N parameter must be between 0
  9767. ** and one less than the number of columns or the behavior will be
  9768. ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
  9769. ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
  9770. ** behavior is undefined. The [sqlite3_value] that P points to
  9771. ** will be destroyed when the preupdate callback returns.
  9772. **
  9773. ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
  9774. ** callback was invoked as a result of a direct insert, update, or delete
  9775. ** operation; or 1 for inserts, updates, or deletes invoked by top-level
  9776. ** triggers; or 2 for changes resulting from triggers called by top-level
  9777. ** triggers; and so forth.
  9778. **
  9779. ** See also: [sqlite3_update_hook()]
  9780. */
  9781. #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  9782. SQLITE_API void *sqlite3_preupdate_hook(
  9783. sqlite3 *db,
  9784. void(*xPreUpdate)(
  9785. void *pCtx, /* Copy of third arg to preupdate_hook() */
  9786. sqlite3 *db, /* Database handle */
  9787. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  9788. char const *zDb, /* Database name */
  9789. char const *zName, /* Table name */
  9790. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  9791. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  9792. ),
  9793. void*
  9794. );
  9795. SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
  9796. SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
  9797. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
  9798. SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
  9799. #endif
  9800. /*
  9801. ** CAPI3REF: Low-level system error code
  9802. **
  9803. ** ^Attempt to return the underlying operating system error code or error
  9804. ** number that caused the most recent I/O error or failure to open a file.
  9805. ** The return value is OS-dependent. For example, on unix systems, after
  9806. ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
  9807. ** called to get back the underlying "errno" that caused the problem, such
  9808. ** as ENOSPC, EAUTH, EISDIR, and so forth.
  9809. */
  9810. SQLITE_API int sqlite3_system_errno(sqlite3*);
  9811. /*
  9812. ** CAPI3REF: Database Snapshot
  9813. ** KEYWORDS: {snapshot} {sqlite3_snapshot}
  9814. **
  9815. ** An instance of the snapshot object records the state of a [WAL mode]
  9816. ** database for some specific point in history.
  9817. **
  9818. ** In [WAL mode], multiple [database connections] that are open on the
  9819. ** same database file can each be reading a different historical version
  9820. ** of the database file. When a [database connection] begins a read
  9821. ** transaction, that connection sees an unchanging copy of the database
  9822. ** as it existed for the point in time when the transaction first started.
  9823. ** Subsequent changes to the database from other connections are not seen
  9824. ** by the reader until a new read transaction is started.
  9825. **
  9826. ** The sqlite3_snapshot object records state information about an historical
  9827. ** version of the database file so that it is possible to later open a new read
  9828. ** transaction that sees that historical version of the database rather than
  9829. ** the most recent version.
  9830. */
  9831. typedef struct sqlite3_snapshot {
  9832. unsigned char hidden[48];
  9833. } sqlite3_snapshot;
  9834. /*
  9835. ** CAPI3REF: Record A Database Snapshot
  9836. ** CONSTRUCTOR: sqlite3_snapshot
  9837. **
  9838. ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  9839. ** new [sqlite3_snapshot] object that records the current state of
  9840. ** schema S in database connection D. ^On success, the
  9841. ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  9842. ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  9843. ** If there is not already a read-transaction open on schema S when
  9844. ** this function is called, one is opened automatically.
  9845. **
  9846. ** The following must be true for this function to succeed. If any of
  9847. ** the following statements are false when sqlite3_snapshot_get() is
  9848. ** called, SQLITE_ERROR is returned. The final value of *P is undefined
  9849. ** in this case.
  9850. **
  9851. ** <ul>
  9852. ** <li> The database handle must not be in [autocommit mode].
  9853. **
  9854. ** <li> Schema S of [database connection] D must be a [WAL mode] database.
  9855. **
  9856. ** <li> There must not be a write transaction open on schema S of database
  9857. ** connection D.
  9858. **
  9859. ** <li> One or more transactions must have been written to the current wal
  9860. ** file since it was created on disk (by any connection). This means
  9861. ** that a snapshot cannot be taken on a wal mode database with no wal
  9862. ** file immediately after it is first opened. At least one transaction
  9863. ** must be written to it first.
  9864. ** </ul>
  9865. **
  9866. ** This function may also return SQLITE_NOMEM. If it is called with the
  9867. ** database handle in autocommit mode but fails for some other reason,
  9868. ** whether or not a read transaction is opened on schema S is undefined.
  9869. **
  9870. ** The [sqlite3_snapshot] object returned from a successful call to
  9871. ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  9872. ** to avoid a memory leak.
  9873. **
  9874. ** The [sqlite3_snapshot_get()] interface is only available when the
  9875. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  9876. */
  9877. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
  9878. sqlite3 *db,
  9879. const char *zSchema,
  9880. sqlite3_snapshot **ppSnapshot
  9881. );
  9882. /*
  9883. ** CAPI3REF: Start a read transaction on an historical snapshot
  9884. ** METHOD: sqlite3_snapshot
  9885. **
  9886. ** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
  9887. ** transaction or upgrades an existing one for schema S of
  9888. ** [database connection] D such that the read transaction refers to
  9889. ** historical [snapshot] P, rather than the most recent change to the
  9890. ** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
  9891. ** on success or an appropriate [error code] if it fails.
  9892. **
  9893. ** ^In order to succeed, the database connection must not be in
  9894. ** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
  9895. ** is already a read transaction open on schema S, then the database handle
  9896. ** must have no active statements (SELECT statements that have been passed
  9897. ** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
  9898. ** SQLITE_ERROR is returned if either of these conditions is violated, or
  9899. ** if schema S does not exist, or if the snapshot object is invalid.
  9900. **
  9901. ** ^A call to sqlite3_snapshot_open() will fail to open if the specified
  9902. ** snapshot has been overwritten by a [checkpoint]. In this case
  9903. ** SQLITE_ERROR_SNAPSHOT is returned.
  9904. **
  9905. ** If there is already a read transaction open when this function is
  9906. ** invoked, then the same read transaction remains open (on the same
  9907. ** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
  9908. ** is returned. If another error code - for example SQLITE_PROTOCOL or an
  9909. ** SQLITE_IOERR error code - is returned, then the final state of the
  9910. ** read transaction is undefined. If SQLITE_OK is returned, then the
  9911. ** read transaction is now open on database snapshot P.
  9912. **
  9913. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
  9914. ** database connection D does not know that the database file for
  9915. ** schema S is in [WAL mode]. A database connection might not know
  9916. ** that the database file is in [WAL mode] if there has been no prior
  9917. ** I/O on that database connection, or if the database entered [WAL mode]
  9918. ** after the most recent I/O on the database connection.)^
  9919. ** (Hint: Run "[PRAGMA application_id]" against a newly opened
  9920. ** database connection in order to make it ready to use snapshots.)
  9921. **
  9922. ** The [sqlite3_snapshot_open()] interface is only available when the
  9923. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  9924. */
  9925. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
  9926. sqlite3 *db,
  9927. const char *zSchema,
  9928. sqlite3_snapshot *pSnapshot
  9929. );
  9930. /*
  9931. ** CAPI3REF: Destroy a snapshot
  9932. ** DESTRUCTOR: sqlite3_snapshot
  9933. **
  9934. ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  9935. ** The application must eventually free every [sqlite3_snapshot] object
  9936. ** using this routine to avoid a memory leak.
  9937. **
  9938. ** The [sqlite3_snapshot_free()] interface is only available when the
  9939. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  9940. */
  9941. SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
  9942. /*
  9943. ** CAPI3REF: Compare the ages of two snapshot handles.
  9944. ** METHOD: sqlite3_snapshot
  9945. **
  9946. ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
  9947. ** of two valid snapshot handles.
  9948. **
  9949. ** If the two snapshot handles are not associated with the same database
  9950. ** file, the result of the comparison is undefined.
  9951. **
  9952. ** Additionally, the result of the comparison is only valid if both of the
  9953. ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
  9954. ** last time the wal file was deleted. The wal file is deleted when the
  9955. ** database is changed back to rollback mode or when the number of database
  9956. ** clients drops to zero. If either snapshot handle was obtained before the
  9957. ** wal file was last deleted, the value returned by this function
  9958. ** is undefined.
  9959. **
  9960. ** Otherwise, this API returns a negative value if P1 refers to an older
  9961. ** snapshot than P2, zero if the two handles refer to the same database
  9962. ** snapshot, and a positive value if P1 is a newer snapshot than P2.
  9963. **
  9964. ** This interface is only available if SQLite is compiled with the
  9965. ** [SQLITE_ENABLE_SNAPSHOT] option.
  9966. */
  9967. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
  9968. sqlite3_snapshot *p1,
  9969. sqlite3_snapshot *p2
  9970. );
  9971. /*
  9972. ** CAPI3REF: Recover snapshots from a wal file
  9973. ** METHOD: sqlite3_snapshot
  9974. **
  9975. ** If a [WAL file] remains on disk after all database connections close
  9976. ** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]
  9977. ** or because the last process to have the database opened exited without
  9978. ** calling [sqlite3_close()]) and a new connection is subsequently opened
  9979. ** on that database and [WAL file], the [sqlite3_snapshot_open()] interface
  9980. ** will only be able to open the last transaction added to the WAL file
  9981. ** even though the WAL file contains other valid transactions.
  9982. **
  9983. ** This function attempts to scan the WAL file associated with database zDb
  9984. ** of database handle db and make all valid snapshots available to
  9985. ** sqlite3_snapshot_open(). It is an error if there is already a read
  9986. ** transaction open on the database, or if the database is not a WAL mode
  9987. ** database.
  9988. **
  9989. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  9990. **
  9991. ** This interface is only available if SQLite is compiled with the
  9992. ** [SQLITE_ENABLE_SNAPSHOT] option.
  9993. */
  9994. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
  9995. /*
  9996. ** CAPI3REF: Serialize a database
  9997. **
  9998. ** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
  9999. ** that is a serialization of the S database on [database connection] D.
  10000. ** If P is not a NULL pointer, then the size of the database in bytes
  10001. ** is written into *P.
  10002. **
  10003. ** For an ordinary on-disk database file, the serialization is just a
  10004. ** copy of the disk file. For an in-memory database or a "TEMP" database,
  10005. ** the serialization is the same sequence of bytes which would be written
  10006. ** to disk if that database where backed up to disk.
  10007. **
  10008. ** The usual case is that sqlite3_serialize() copies the serialization of
  10009. ** the database into memory obtained from [sqlite3_malloc64()] and returns
  10010. ** a pointer to that memory. The caller is responsible for freeing the
  10011. ** returned value to avoid a memory leak. However, if the F argument
  10012. ** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
  10013. ** are made, and the sqlite3_serialize() function will return a pointer
  10014. ** to the contiguous memory representation of the database that SQLite
  10015. ** is currently using for that database, or NULL if the no such contiguous
  10016. ** memory representation of the database exists. A contiguous memory
  10017. ** representation of the database will usually only exist if there has
  10018. ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
  10019. ** values of D and S.
  10020. ** The size of the database is written into *P even if the
  10021. ** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
  10022. ** of the database exists.
  10023. **
  10024. ** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
  10025. ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
  10026. ** allocation error occurs.
  10027. **
  10028. ** This interface is only available if SQLite is compiled with the
  10029. ** [SQLITE_ENABLE_DESERIALIZE] option.
  10030. */
  10031. SQLITE_API unsigned char *sqlite3_serialize(
  10032. sqlite3 *db, /* The database connection */
  10033. const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */
  10034. sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
  10035. unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */
  10036. );
  10037. /*
  10038. ** CAPI3REF: Flags for sqlite3_serialize
  10039. **
  10040. ** Zero or more of the following constants can be OR-ed together for
  10041. ** the F argument to [sqlite3_serialize(D,S,P,F)].
  10042. **
  10043. ** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
  10044. ** a pointer to contiguous in-memory database that it is currently using,
  10045. ** without making a copy of the database. If SQLite is not currently using
  10046. ** a contiguous in-memory database, then this option causes
  10047. ** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be
  10048. ** using a contiguous in-memory database if it has been initialized by a
  10049. ** prior call to [sqlite3_deserialize()].
  10050. */
  10051. #define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */
  10052. /*
  10053. ** CAPI3REF: Deserialize a database
  10054. **
  10055. ** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
  10056. ** [database connection] D to disconnect from database S and then
  10057. ** reopen S as an in-memory database based on the serialization contained
  10058. ** in P. The serialized database P is N bytes in size. M is the size of
  10059. ** the buffer P, which might be larger than N. If M is larger than N, and
  10060. ** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
  10061. ** permitted to add content to the in-memory database as long as the total
  10062. ** size does not exceed M bytes.
  10063. **
  10064. ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
  10065. ** invoke sqlite3_free() on the serialization buffer when the database
  10066. ** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
  10067. ** SQLite will try to increase the buffer size using sqlite3_realloc64()
  10068. ** if writes on the database cause it to grow larger than M bytes.
  10069. **
  10070. ** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
  10071. ** database is currently in a read transaction or is involved in a backup
  10072. ** operation.
  10073. **
  10074. ** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
  10075. ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
  10076. ** [sqlite3_free()] is invoked on argument P prior to returning.
  10077. **
  10078. ** This interface is only available if SQLite is compiled with the
  10079. ** [SQLITE_ENABLE_DESERIALIZE] option.
  10080. */
  10081. SQLITE_API int sqlite3_deserialize(
  10082. sqlite3 *db, /* The database connection */
  10083. const char *zSchema, /* Which DB to reopen with the deserialization */
  10084. unsigned char *pData, /* The serialized database content */
  10085. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  10086. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  10087. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  10088. );
  10089. /*
  10090. ** CAPI3REF: Flags for sqlite3_deserialize()
  10091. **
  10092. ** The following are allowed values for 6th argument (the F argument) to
  10093. ** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
  10094. **
  10095. ** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
  10096. ** in the P argument is held in memory obtained from [sqlite3_malloc64()]
  10097. ** and that SQLite should take ownership of this memory and automatically
  10098. ** free it when it has finished using it. Without this flag, the caller
  10099. ** is responsible for freeing any dynamically allocated memory.
  10100. **
  10101. ** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
  10102. ** grow the size of the database using calls to [sqlite3_realloc64()]. This
  10103. ** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
  10104. ** Without this flag, the deserialized database cannot increase in size beyond
  10105. ** the number of bytes specified by the M parameter.
  10106. **
  10107. ** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
  10108. ** should be treated as read-only.
  10109. */
  10110. #define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
  10111. #define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */
  10112. #define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
  10113. /*
  10114. ** Undo the hack that converts floating point types to integer for
  10115. ** builds on processors without floating point support.
  10116. */
  10117. #ifdef SQLITE_OMIT_FLOATING_POINT
  10118. # undef double
  10119. #endif
  10120. #if 0
  10121. } /* End of the 'extern "C"' block */
  10122. #endif
  10123. #endif /* SQLITE3_H */
  10124. /******** Begin file sqlite3rtree.h *********/
  10125. /*
  10126. ** 2010 August 30
  10127. **
  10128. ** The author disclaims copyright to this source code. In place of
  10129. ** a legal notice, here is a blessing:
  10130. **
  10131. ** May you do good and not evil.
  10132. ** May you find forgiveness for yourself and forgive others.
  10133. ** May you share freely, never taking more than you give.
  10134. **
  10135. *************************************************************************
  10136. */
  10137. #ifndef _SQLITE3RTREE_H_
  10138. #define _SQLITE3RTREE_H_
  10139. #if 0
  10140. extern "C" {
  10141. #endif
  10142. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  10143. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  10144. /* The double-precision datatype used by RTree depends on the
  10145. ** SQLITE_RTREE_INT_ONLY compile-time option.
  10146. */
  10147. #ifdef SQLITE_RTREE_INT_ONLY
  10148. typedef sqlite3_int64 sqlite3_rtree_dbl;
  10149. #else
  10150. typedef double sqlite3_rtree_dbl;
  10151. #endif
  10152. /*
  10153. ** Register a geometry callback named zGeom that can be used as part of an
  10154. ** R-Tree geometry query as follows:
  10155. **
  10156. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  10157. */
  10158. SQLITE_API int sqlite3_rtree_geometry_callback(
  10159. sqlite3 *db,
  10160. const char *zGeom,
  10161. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  10162. void *pContext
  10163. );
  10164. /*
  10165. ** A pointer to a structure of the following type is passed as the first
  10166. ** argument to callbacks registered using rtree_geometry_callback().
  10167. */
  10168. struct sqlite3_rtree_geometry {
  10169. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  10170. int nParam; /* Size of array aParam[] */
  10171. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  10172. void *pUser; /* Callback implementation user data */
  10173. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  10174. };
  10175. /*
  10176. ** Register a 2nd-generation geometry callback named zScore that can be
  10177. ** used as part of an R-Tree geometry query as follows:
  10178. **
  10179. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  10180. */
  10181. SQLITE_API int sqlite3_rtree_query_callback(
  10182. sqlite3 *db,
  10183. const char *zQueryFunc,
  10184. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  10185. void *pContext,
  10186. void (*xDestructor)(void*)
  10187. );
  10188. /*
  10189. ** A pointer to a structure of the following type is passed as the
  10190. ** argument to scored geometry callback registered using
  10191. ** sqlite3_rtree_query_callback().
  10192. **
  10193. ** Note that the first 5 fields of this structure are identical to
  10194. ** sqlite3_rtree_geometry. This structure is a subclass of
  10195. ** sqlite3_rtree_geometry.
  10196. */
  10197. struct sqlite3_rtree_query_info {
  10198. void *pContext; /* pContext from when function registered */
  10199. int nParam; /* Number of function parameters */
  10200. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  10201. void *pUser; /* callback can use this, if desired */
  10202. void (*xDelUser)(void*); /* function to free pUser */
  10203. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  10204. unsigned int *anQueue; /* Number of pending entries in the queue */
  10205. int nCoord; /* Number of coordinates */
  10206. int iLevel; /* Level of current node or entry */
  10207. int mxLevel; /* The largest iLevel value in the tree */
  10208. sqlite3_int64 iRowid; /* Rowid for current entry */
  10209. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  10210. int eParentWithin; /* Visibility of parent node */
  10211. int eWithin; /* OUT: Visibility */
  10212. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  10213. /* The following fields are only available in 3.8.11 and later */
  10214. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  10215. };
  10216. /*
  10217. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  10218. */
  10219. #define NOT_WITHIN 0 /* Object completely outside of query region */
  10220. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  10221. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  10222. #if 0
  10223. } /* end of the 'extern "C"' block */
  10224. #endif
  10225. #endif /* ifndef _SQLITE3RTREE_H_ */
  10226. /******** End of sqlite3rtree.h *********/
  10227. /******** Begin file sqlite3session.h *********/
  10228. #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
  10229. #define __SQLITESESSION_H_ 1
  10230. /*
  10231. ** Make sure we can call this stuff from C++.
  10232. */
  10233. #if 0
  10234. extern "C" {
  10235. #endif
  10236. /*
  10237. ** CAPI3REF: Session Object Handle
  10238. **
  10239. ** An instance of this object is a [session] that can be used to
  10240. ** record changes to a database.
  10241. */
  10242. typedef struct sqlite3_session sqlite3_session;
  10243. /*
  10244. ** CAPI3REF: Changeset Iterator Handle
  10245. **
  10246. ** An instance of this object acts as a cursor for iterating
  10247. ** over the elements of a [changeset] or [patchset].
  10248. */
  10249. typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
  10250. /*
  10251. ** CAPI3REF: Create A New Session Object
  10252. ** CONSTRUCTOR: sqlite3_session
  10253. **
  10254. ** Create a new session object attached to database handle db. If successful,
  10255. ** a pointer to the new object is written to *ppSession and SQLITE_OK is
  10256. ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
  10257. ** error code (e.g. SQLITE_NOMEM) is returned.
  10258. **
  10259. ** It is possible to create multiple session objects attached to a single
  10260. ** database handle.
  10261. **
  10262. ** Session objects created using this function should be deleted using the
  10263. ** [sqlite3session_delete()] function before the database handle that they
  10264. ** are attached to is itself closed. If the database handle is closed before
  10265. ** the session object is deleted, then the results of calling any session
  10266. ** module function, including [sqlite3session_delete()] on the session object
  10267. ** are undefined.
  10268. **
  10269. ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
  10270. ** is not possible for an application to register a pre-update hook on a
  10271. ** database handle that has one or more session objects attached. Nor is
  10272. ** it possible to create a session object attached to a database handle for
  10273. ** which a pre-update hook is already defined. The results of attempting
  10274. ** either of these things are undefined.
  10275. **
  10276. ** The session object will be used to create changesets for tables in
  10277. ** database zDb, where zDb is either "main", or "temp", or the name of an
  10278. ** attached database. It is not an error if database zDb is not attached
  10279. ** to the database when the session object is created.
  10280. */
  10281. SQLITE_API int sqlite3session_create(
  10282. sqlite3 *db, /* Database handle */
  10283. const char *zDb, /* Name of db (e.g. "main") */
  10284. sqlite3_session **ppSession /* OUT: New session object */
  10285. );
  10286. /*
  10287. ** CAPI3REF: Delete A Session Object
  10288. ** DESTRUCTOR: sqlite3_session
  10289. **
  10290. ** Delete a session object previously allocated using
  10291. ** [sqlite3session_create()]. Once a session object has been deleted, the
  10292. ** results of attempting to use pSession with any other session module
  10293. ** function are undefined.
  10294. **
  10295. ** Session objects must be deleted before the database handle to which they
  10296. ** are attached is closed. Refer to the documentation for
  10297. ** [sqlite3session_create()] for details.
  10298. */
  10299. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
  10300. /*
  10301. ** CAPI3REF: Enable Or Disable A Session Object
  10302. ** METHOD: sqlite3_session
  10303. **
  10304. ** Enable or disable the recording of changes by a session object. When
  10305. ** enabled, a session object records changes made to the database. When
  10306. ** disabled - it does not. A newly created session object is enabled.
  10307. ** Refer to the documentation for [sqlite3session_changeset()] for further
  10308. ** details regarding how enabling and disabling a session object affects
  10309. ** the eventual changesets.
  10310. **
  10311. ** Passing zero to this function disables the session. Passing a value
  10312. ** greater than zero enables it. Passing a value less than zero is a
  10313. ** no-op, and may be used to query the current state of the session.
  10314. **
  10315. ** The return value indicates the final state of the session object: 0 if
  10316. ** the session is disabled, or 1 if it is enabled.
  10317. */
  10318. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
  10319. /*
  10320. ** CAPI3REF: Set Or Clear the Indirect Change Flag
  10321. ** METHOD: sqlite3_session
  10322. **
  10323. ** Each change recorded by a session object is marked as either direct or
  10324. ** indirect. A change is marked as indirect if either:
  10325. **
  10326. ** <ul>
  10327. ** <li> The session object "indirect" flag is set when the change is
  10328. ** made, or
  10329. ** <li> The change is made by an SQL trigger or foreign key action
  10330. ** instead of directly as a result of a users SQL statement.
  10331. ** </ul>
  10332. **
  10333. ** If a single row is affected by more than one operation within a session,
  10334. ** then the change is considered indirect if all operations meet the criteria
  10335. ** for an indirect change above, or direct otherwise.
  10336. **
  10337. ** This function is used to set, clear or query the session object indirect
  10338. ** flag. If the second argument passed to this function is zero, then the
  10339. ** indirect flag is cleared. If it is greater than zero, the indirect flag
  10340. ** is set. Passing a value less than zero does not modify the current value
  10341. ** of the indirect flag, and may be used to query the current state of the
  10342. ** indirect flag for the specified session object.
  10343. **
  10344. ** The return value indicates the final state of the indirect flag: 0 if
  10345. ** it is clear, or 1 if it is set.
  10346. */
  10347. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
  10348. /*
  10349. ** CAPI3REF: Attach A Table To A Session Object
  10350. ** METHOD: sqlite3_session
  10351. **
  10352. ** If argument zTab is not NULL, then it is the name of a table to attach
  10353. ** to the session object passed as the first argument. All subsequent changes
  10354. ** made to the table while the session object is enabled will be recorded. See
  10355. ** documentation for [sqlite3session_changeset()] for further details.
  10356. **
  10357. ** Or, if argument zTab is NULL, then changes are recorded for all tables
  10358. ** in the database. If additional tables are added to the database (by
  10359. ** executing "CREATE TABLE" statements) after this call is made, changes for
  10360. ** the new tables are also recorded.
  10361. **
  10362. ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
  10363. ** defined as part of their CREATE TABLE statement. It does not matter if the
  10364. ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
  10365. ** KEY may consist of a single column, or may be a composite key.
  10366. **
  10367. ** It is not an error if the named table does not exist in the database. Nor
  10368. ** is it an error if the named table does not have a PRIMARY KEY. However,
  10369. ** no changes will be recorded in either of these scenarios.
  10370. **
  10371. ** Changes are not recorded for individual rows that have NULL values stored
  10372. ** in one or more of their PRIMARY KEY columns.
  10373. **
  10374. ** SQLITE_OK is returned if the call completes without error. Or, if an error
  10375. ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  10376. **
  10377. ** <h3>Special sqlite_stat1 Handling</h3>
  10378. **
  10379. ** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
  10380. ** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
  10381. ** <pre>
  10382. ** &nbsp; CREATE TABLE sqlite_stat1(tbl,idx,stat)
  10383. ** </pre>
  10384. **
  10385. ** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
  10386. ** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
  10387. ** are recorded for rows for which (idx IS NULL) is true. However, for such
  10388. ** rows a zero-length blob (SQL value X'') is stored in the changeset or
  10389. ** patchset instead of a NULL value. This allows such changesets to be
  10390. ** manipulated by legacy implementations of sqlite3changeset_invert(),
  10391. ** concat() and similar.
  10392. **
  10393. ** The sqlite3changeset_apply() function automatically converts the
  10394. ** zero-length blob back to a NULL value when updating the sqlite_stat1
  10395. ** table. However, if the application calls sqlite3changeset_new(),
  10396. ** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
  10397. ** iterator directly (including on a changeset iterator passed to a
  10398. ** conflict-handler callback) then the X'' value is returned. The application
  10399. ** must translate X'' to NULL itself if required.
  10400. **
  10401. ** Legacy (older than 3.22.0) versions of the sessions module cannot capture
  10402. ** changes made to the sqlite_stat1 table. Legacy versions of the
  10403. ** sqlite3changeset_apply() function silently ignore any modifications to the
  10404. ** sqlite_stat1 table that are part of a changeset or patchset.
  10405. */
  10406. SQLITE_API int sqlite3session_attach(
  10407. sqlite3_session *pSession, /* Session object */
  10408. const char *zTab /* Table name */
  10409. );
  10410. /*
  10411. ** CAPI3REF: Set a table filter on a Session Object.
  10412. ** METHOD: sqlite3_session
  10413. **
  10414. ** The second argument (xFilter) is the "filter callback". For changes to rows
  10415. ** in tables that are not attached to the Session object, the filter is called
  10416. ** to determine whether changes to the table's rows should be tracked or not.
  10417. ** If xFilter returns 0, changes is not tracked. Note that once a table is
  10418. ** attached, xFilter will not be called again.
  10419. */
  10420. SQLITE_API void sqlite3session_table_filter(
  10421. sqlite3_session *pSession, /* Session object */
  10422. int(*xFilter)(
  10423. void *pCtx, /* Copy of third arg to _filter_table() */
  10424. const char *zTab /* Table name */
  10425. ),
  10426. void *pCtx /* First argument passed to xFilter */
  10427. );
  10428. /*
  10429. ** CAPI3REF: Generate A Changeset From A Session Object
  10430. ** METHOD: sqlite3_session
  10431. **
  10432. ** Obtain a changeset containing changes to the tables attached to the
  10433. ** session object passed as the first argument. If successful,
  10434. ** set *ppChangeset to point to a buffer containing the changeset
  10435. ** and *pnChangeset to the size of the changeset in bytes before returning
  10436. ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
  10437. ** zero and return an SQLite error code.
  10438. **
  10439. ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
  10440. ** each representing a change to a single row of an attached table. An INSERT
  10441. ** change contains the values of each field of a new database row. A DELETE
  10442. ** contains the original values of each field of a deleted database row. An
  10443. ** UPDATE change contains the original values of each field of an updated
  10444. ** database row along with the updated values for each updated non-primary-key
  10445. ** column. It is not possible for an UPDATE change to represent a change that
  10446. ** modifies the values of primary key columns. If such a change is made, it
  10447. ** is represented in a changeset as a DELETE followed by an INSERT.
  10448. **
  10449. ** Changes are not recorded for rows that have NULL values stored in one or
  10450. ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
  10451. ** no corresponding change is present in the changesets returned by this
  10452. ** function. If an existing row with one or more NULL values stored in
  10453. ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
  10454. ** only an INSERT is appears in the changeset. Similarly, if an existing row
  10455. ** with non-NULL PRIMARY KEY values is updated so that one or more of its
  10456. ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
  10457. ** DELETE change only.
  10458. **
  10459. ** The contents of a changeset may be traversed using an iterator created
  10460. ** using the [sqlite3changeset_start()] API. A changeset may be applied to
  10461. ** a database with a compatible schema using the [sqlite3changeset_apply()]
  10462. ** API.
  10463. **
  10464. ** Within a changeset generated by this function, all changes related to a
  10465. ** single table are grouped together. In other words, when iterating through
  10466. ** a changeset or when applying a changeset to a database, all changes related
  10467. ** to a single table are processed before moving on to the next table. Tables
  10468. ** are sorted in the same order in which they were attached (or auto-attached)
  10469. ** to the sqlite3_session object. The order in which the changes related to
  10470. ** a single table are stored is undefined.
  10471. **
  10472. ** Following a successful call to this function, it is the responsibility of
  10473. ** the caller to eventually free the buffer that *ppChangeset points to using
  10474. ** [sqlite3_free()].
  10475. **
  10476. ** <h3>Changeset Generation</h3>
  10477. **
  10478. ** Once a table has been attached to a session object, the session object
  10479. ** records the primary key values of all new rows inserted into the table.
  10480. ** It also records the original primary key and other column values of any
  10481. ** deleted or updated rows. For each unique primary key value, data is only
  10482. ** recorded once - the first time a row with said primary key is inserted,
  10483. ** updated or deleted in the lifetime of the session.
  10484. **
  10485. ** There is one exception to the previous paragraph: when a row is inserted,
  10486. ** updated or deleted, if one or more of its primary key columns contain a
  10487. ** NULL value, no record of the change is made.
  10488. **
  10489. ** The session object therefore accumulates two types of records - those
  10490. ** that consist of primary key values only (created when the user inserts
  10491. ** a new record) and those that consist of the primary key values and the
  10492. ** original values of other table columns (created when the users deletes
  10493. ** or updates a record).
  10494. **
  10495. ** When this function is called, the requested changeset is created using
  10496. ** both the accumulated records and the current contents of the database
  10497. ** file. Specifically:
  10498. **
  10499. ** <ul>
  10500. ** <li> For each record generated by an insert, the database is queried
  10501. ** for a row with a matching primary key. If one is found, an INSERT
  10502. ** change is added to the changeset. If no such row is found, no change
  10503. ** is added to the changeset.
  10504. **
  10505. ** <li> For each record generated by an update or delete, the database is
  10506. ** queried for a row with a matching primary key. If such a row is
  10507. ** found and one or more of the non-primary key fields have been
  10508. ** modified from their original values, an UPDATE change is added to
  10509. ** the changeset. Or, if no such row is found in the table, a DELETE
  10510. ** change is added to the changeset. If there is a row with a matching
  10511. ** primary key in the database, but all fields contain their original
  10512. ** values, no change is added to the changeset.
  10513. ** </ul>
  10514. **
  10515. ** This means, amongst other things, that if a row is inserted and then later
  10516. ** deleted while a session object is active, neither the insert nor the delete
  10517. ** will be present in the changeset. Or if a row is deleted and then later a
  10518. ** row with the same primary key values inserted while a session object is
  10519. ** active, the resulting changeset will contain an UPDATE change instead of
  10520. ** a DELETE and an INSERT.
  10521. **
  10522. ** When a session object is disabled (see the [sqlite3session_enable()] API),
  10523. ** it does not accumulate records when rows are inserted, updated or deleted.
  10524. ** This may appear to have some counter-intuitive effects if a single row
  10525. ** is written to more than once during a session. For example, if a row
  10526. ** is inserted while a session object is enabled, then later deleted while
  10527. ** the same session object is disabled, no INSERT record will appear in the
  10528. ** changeset, even though the delete took place while the session was disabled.
  10529. ** Or, if one field of a row is updated while a session is disabled, and
  10530. ** another field of the same row is updated while the session is enabled, the
  10531. ** resulting changeset will contain an UPDATE change that updates both fields.
  10532. */
  10533. SQLITE_API int sqlite3session_changeset(
  10534. sqlite3_session *pSession, /* Session object */
  10535. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  10536. void **ppChangeset /* OUT: Buffer containing changeset */
  10537. );
  10538. /*
  10539. ** CAPI3REF: Load The Difference Between Tables Into A Session
  10540. ** METHOD: sqlite3_session
  10541. **
  10542. ** If it is not already attached to the session object passed as the first
  10543. ** argument, this function attaches table zTbl in the same manner as the
  10544. ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
  10545. ** does not have a primary key, this function is a no-op (but does not return
  10546. ** an error).
  10547. **
  10548. ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
  10549. ** attached to the same database handle as the session object that contains
  10550. ** a table compatible with the table attached to the session by this function.
  10551. ** A table is considered compatible if it:
  10552. **
  10553. ** <ul>
  10554. ** <li> Has the same name,
  10555. ** <li> Has the same set of columns declared in the same order, and
  10556. ** <li> Has the same PRIMARY KEY definition.
  10557. ** </ul>
  10558. **
  10559. ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
  10560. ** are compatible but do not have any PRIMARY KEY columns, it is not an error
  10561. ** but no changes are added to the session object. As with other session
  10562. ** APIs, tables without PRIMARY KEYs are simply ignored.
  10563. **
  10564. ** This function adds a set of changes to the session object that could be
  10565. ** used to update the table in database zFrom (call this the "from-table")
  10566. ** so that its content is the same as the table attached to the session
  10567. ** object (call this the "to-table"). Specifically:
  10568. **
  10569. ** <ul>
  10570. ** <li> For each row (primary key) that exists in the to-table but not in
  10571. ** the from-table, an INSERT record is added to the session object.
  10572. **
  10573. ** <li> For each row (primary key) that exists in the to-table but not in
  10574. ** the from-table, a DELETE record is added to the session object.
  10575. **
  10576. ** <li> For each row (primary key) that exists in both tables, but features
  10577. ** different non-PK values in each, an UPDATE record is added to the
  10578. ** session.
  10579. ** </ul>
  10580. **
  10581. ** To clarify, if this function is called and then a changeset constructed
  10582. ** using [sqlite3session_changeset()], then after applying that changeset to
  10583. ** database zFrom the contents of the two compatible tables would be
  10584. ** identical.
  10585. **
  10586. ** It an error if database zFrom does not exist or does not contain the
  10587. ** required compatible table.
  10588. **
  10589. ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
  10590. ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
  10591. ** may be set to point to a buffer containing an English language error
  10592. ** message. It is the responsibility of the caller to free this buffer using
  10593. ** sqlite3_free().
  10594. */
  10595. SQLITE_API int sqlite3session_diff(
  10596. sqlite3_session *pSession,
  10597. const char *zFromDb,
  10598. const char *zTbl,
  10599. char **pzErrMsg
  10600. );
  10601. /*
  10602. ** CAPI3REF: Generate A Patchset From A Session Object
  10603. ** METHOD: sqlite3_session
  10604. **
  10605. ** The differences between a patchset and a changeset are that:
  10606. **
  10607. ** <ul>
  10608. ** <li> DELETE records consist of the primary key fields only. The
  10609. ** original values of other fields are omitted.
  10610. ** <li> The original values of any modified fields are omitted from
  10611. ** UPDATE records.
  10612. ** </ul>
  10613. **
  10614. ** A patchset blob may be used with up to date versions of all
  10615. ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
  10616. ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
  10617. ** attempting to use a patchset blob with old versions of the
  10618. ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
  10619. **
  10620. ** Because the non-primary key "old.*" fields are omitted, no
  10621. ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
  10622. ** is passed to the sqlite3changeset_apply() API. Other conflict types work
  10623. ** in the same way as for changesets.
  10624. **
  10625. ** Changes within a patchset are ordered in the same way as for changesets
  10626. ** generated by the sqlite3session_changeset() function (i.e. all changes for
  10627. ** a single table are grouped together, tables appear in the order in which
  10628. ** they were attached to the session object).
  10629. */
  10630. SQLITE_API int sqlite3session_patchset(
  10631. sqlite3_session *pSession, /* Session object */
  10632. int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
  10633. void **ppPatchset /* OUT: Buffer containing patchset */
  10634. );
  10635. /*
  10636. ** CAPI3REF: Test if a changeset has recorded any changes.
  10637. **
  10638. ** Return non-zero if no changes to attached tables have been recorded by
  10639. ** the session object passed as the first argument. Otherwise, if one or
  10640. ** more changes have been recorded, return zero.
  10641. **
  10642. ** Even if this function returns zero, it is possible that calling
  10643. ** [sqlite3session_changeset()] on the session handle may still return a
  10644. ** changeset that contains no changes. This can happen when a row in
  10645. ** an attached table is modified and then later on the original values
  10646. ** are restored. However, if this function returns non-zero, then it is
  10647. ** guaranteed that a call to sqlite3session_changeset() will return a
  10648. ** changeset containing zero changes.
  10649. */
  10650. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
  10651. /*
  10652. ** CAPI3REF: Create An Iterator To Traverse A Changeset
  10653. ** CONSTRUCTOR: sqlite3_changeset_iter
  10654. **
  10655. ** Create an iterator used to iterate through the contents of a changeset.
  10656. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
  10657. ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
  10658. ** SQLite error code is returned.
  10659. **
  10660. ** The following functions can be used to advance and query a changeset
  10661. ** iterator created by this function:
  10662. **
  10663. ** <ul>
  10664. ** <li> [sqlite3changeset_next()]
  10665. ** <li> [sqlite3changeset_op()]
  10666. ** <li> [sqlite3changeset_new()]
  10667. ** <li> [sqlite3changeset_old()]
  10668. ** </ul>
  10669. **
  10670. ** It is the responsibility of the caller to eventually destroy the iterator
  10671. ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
  10672. ** changeset (pChangeset) must remain valid until after the iterator is
  10673. ** destroyed.
  10674. **
  10675. ** Assuming the changeset blob was created by one of the
  10676. ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
  10677. ** [sqlite3changeset_invert()] functions, all changes within the changeset
  10678. ** that apply to a single table are grouped together. This means that when
  10679. ** an application iterates through a changeset using an iterator created by
  10680. ** this function, all changes that relate to a single table are visited
  10681. ** consecutively. There is no chance that the iterator will visit a change
  10682. ** the applies to table X, then one for table Y, and then later on visit
  10683. ** another change for table X.
  10684. **
  10685. ** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
  10686. ** may be modified by passing a combination of
  10687. ** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
  10688. **
  10689. ** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>
  10690. ** and therefore subject to change.
  10691. */
  10692. SQLITE_API int sqlite3changeset_start(
  10693. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  10694. int nChangeset, /* Size of changeset blob in bytes */
  10695. void *pChangeset /* Pointer to blob containing changeset */
  10696. );
  10697. SQLITE_API int sqlite3changeset_start_v2(
  10698. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  10699. int nChangeset, /* Size of changeset blob in bytes */
  10700. void *pChangeset, /* Pointer to blob containing changeset */
  10701. int flags /* SESSION_CHANGESETSTART_* flags */
  10702. );
  10703. /*
  10704. ** CAPI3REF: Flags for sqlite3changeset_start_v2
  10705. **
  10706. ** The following flags may passed via the 4th parameter to
  10707. ** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
  10708. **
  10709. ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
  10710. ** Invert the changeset while iterating through it. This is equivalent to
  10711. ** inverting a changeset using sqlite3changeset_invert() before applying it.
  10712. ** It is an error to specify this flag with a patchset.
  10713. */
  10714. #define SQLITE_CHANGESETSTART_INVERT 0x0002
  10715. /*
  10716. ** CAPI3REF: Advance A Changeset Iterator
  10717. ** METHOD: sqlite3_changeset_iter
  10718. **
  10719. ** This function may only be used with iterators created by function
  10720. ** [sqlite3changeset_start()]. If it is called on an iterator passed to
  10721. ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
  10722. ** is returned and the call has no effect.
  10723. **
  10724. ** Immediately after an iterator is created by sqlite3changeset_start(), it
  10725. ** does not point to any change in the changeset. Assuming the changeset
  10726. ** is not empty, the first call to this function advances the iterator to
  10727. ** point to the first change in the changeset. Each subsequent call advances
  10728. ** the iterator to point to the next change in the changeset (if any). If
  10729. ** no error occurs and the iterator points to a valid change after a call
  10730. ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
  10731. ** Otherwise, if all changes in the changeset have already been visited,
  10732. ** SQLITE_DONE is returned.
  10733. **
  10734. ** If an error occurs, an SQLite error code is returned. Possible error
  10735. ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
  10736. ** SQLITE_NOMEM.
  10737. */
  10738. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
  10739. /*
  10740. ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
  10741. ** METHOD: sqlite3_changeset_iter
  10742. **
  10743. ** The pIter argument passed to this function may either be an iterator
  10744. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10745. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10746. ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
  10747. ** is not the case, this function returns [SQLITE_MISUSE].
  10748. **
  10749. ** If argument pzTab is not NULL, then *pzTab is set to point to a
  10750. ** nul-terminated utf-8 encoded string containing the name of the table
  10751. ** affected by the current change. The buffer remains valid until either
  10752. ** sqlite3changeset_next() is called on the iterator or until the
  10753. ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
  10754. ** set to the number of columns in the table affected by the change. If
  10755. ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
  10756. ** is an indirect change, or false (0) otherwise. See the documentation for
  10757. ** [sqlite3session_indirect()] for a description of direct and indirect
  10758. ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
  10759. ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
  10760. ** type of change that the iterator currently points to.
  10761. **
  10762. ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
  10763. ** SQLite error code is returned. The values of the output variables may not
  10764. ** be trusted in this case.
  10765. */
  10766. SQLITE_API int sqlite3changeset_op(
  10767. sqlite3_changeset_iter *pIter, /* Iterator object */
  10768. const char **pzTab, /* OUT: Pointer to table name */
  10769. int *pnCol, /* OUT: Number of columns in table */
  10770. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  10771. int *pbIndirect /* OUT: True for an 'indirect' change */
  10772. );
  10773. /*
  10774. ** CAPI3REF: Obtain The Primary Key Definition Of A Table
  10775. ** METHOD: sqlite3_changeset_iter
  10776. **
  10777. ** For each modified table, a changeset includes the following:
  10778. **
  10779. ** <ul>
  10780. ** <li> The number of columns in the table, and
  10781. ** <li> Which of those columns make up the tables PRIMARY KEY.
  10782. ** </ul>
  10783. **
  10784. ** This function is used to find which columns comprise the PRIMARY KEY of
  10785. ** the table modified by the change that iterator pIter currently points to.
  10786. ** If successful, *pabPK is set to point to an array of nCol entries, where
  10787. ** nCol is the number of columns in the table. Elements of *pabPK are set to
  10788. ** 0x01 if the corresponding column is part of the tables primary key, or
  10789. ** 0x00 if it is not.
  10790. **
  10791. ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
  10792. ** in the table.
  10793. **
  10794. ** If this function is called when the iterator does not point to a valid
  10795. ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
  10796. ** SQLITE_OK is returned and the output variables populated as described
  10797. ** above.
  10798. */
  10799. SQLITE_API int sqlite3changeset_pk(
  10800. sqlite3_changeset_iter *pIter, /* Iterator object */
  10801. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  10802. int *pnCol /* OUT: Number of entries in output array */
  10803. );
  10804. /*
  10805. ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
  10806. ** METHOD: sqlite3_changeset_iter
  10807. **
  10808. ** The pIter argument passed to this function may either be an iterator
  10809. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10810. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10811. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10812. ** Furthermore, it may only be called if the type of change that the iterator
  10813. ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
  10814. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10815. **
  10816. ** Argument iVal must be greater than or equal to 0, and less than the number
  10817. ** of columns in the table affected by the current change. Otherwise,
  10818. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10819. **
  10820. ** If successful, this function sets *ppValue to point to a protected
  10821. ** sqlite3_value object containing the iVal'th value from the vector of
  10822. ** original row values stored as part of the UPDATE or DELETE change and
  10823. ** returns SQLITE_OK. The name of the function comes from the fact that this
  10824. ** is similar to the "old.*" columns available to update or delete triggers.
  10825. **
  10826. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10827. ** is returned and *ppValue is set to NULL.
  10828. */
  10829. SQLITE_API int sqlite3changeset_old(
  10830. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10831. int iVal, /* Column number */
  10832. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  10833. );
  10834. /*
  10835. ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
  10836. ** METHOD: sqlite3_changeset_iter
  10837. **
  10838. ** The pIter argument passed to this function may either be an iterator
  10839. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10840. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10841. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10842. ** Furthermore, it may only be called if the type of change that the iterator
  10843. ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
  10844. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10845. **
  10846. ** Argument iVal must be greater than or equal to 0, and less than the number
  10847. ** of columns in the table affected by the current change. Otherwise,
  10848. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10849. **
  10850. ** If successful, this function sets *ppValue to point to a protected
  10851. ** sqlite3_value object containing the iVal'th value from the vector of
  10852. ** new row values stored as part of the UPDATE or INSERT change and
  10853. ** returns SQLITE_OK. If the change is an UPDATE and does not include
  10854. ** a new value for the requested column, *ppValue is set to NULL and
  10855. ** SQLITE_OK returned. The name of the function comes from the fact that
  10856. ** this is similar to the "new.*" columns available to update or delete
  10857. ** triggers.
  10858. **
  10859. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10860. ** is returned and *ppValue is set to NULL.
  10861. */
  10862. SQLITE_API int sqlite3changeset_new(
  10863. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10864. int iVal, /* Column number */
  10865. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  10866. );
  10867. /*
  10868. ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
  10869. ** METHOD: sqlite3_changeset_iter
  10870. **
  10871. ** This function should only be used with iterator objects passed to a
  10872. ** conflict-handler callback by [sqlite3changeset_apply()] with either
  10873. ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
  10874. ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
  10875. ** is set to NULL.
  10876. **
  10877. ** Argument iVal must be greater than or equal to 0, and less than the number
  10878. ** of columns in the table affected by the current change. Otherwise,
  10879. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10880. **
  10881. ** If successful, this function sets *ppValue to point to a protected
  10882. ** sqlite3_value object containing the iVal'th value from the
  10883. ** "conflicting row" associated with the current conflict-handler callback
  10884. ** and returns SQLITE_OK.
  10885. **
  10886. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10887. ** is returned and *ppValue is set to NULL.
  10888. */
  10889. SQLITE_API int sqlite3changeset_conflict(
  10890. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10891. int iVal, /* Column number */
  10892. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  10893. );
  10894. /*
  10895. ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
  10896. ** METHOD: sqlite3_changeset_iter
  10897. **
  10898. ** This function may only be called with an iterator passed to an
  10899. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  10900. ** it sets the output variable to the total number of known foreign key
  10901. ** violations in the destination database and returns SQLITE_OK.
  10902. **
  10903. ** In all other cases this function returns SQLITE_MISUSE.
  10904. */
  10905. SQLITE_API int sqlite3changeset_fk_conflicts(
  10906. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10907. int *pnOut /* OUT: Number of FK violations */
  10908. );
  10909. /*
  10910. ** CAPI3REF: Finalize A Changeset Iterator
  10911. ** METHOD: sqlite3_changeset_iter
  10912. **
  10913. ** This function is used to finalize an iterator allocated with
  10914. ** [sqlite3changeset_start()].
  10915. **
  10916. ** This function should only be called on iterators created using the
  10917. ** [sqlite3changeset_start()] function. If an application calls this
  10918. ** function with an iterator passed to a conflict-handler by
  10919. ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
  10920. ** call has no effect.
  10921. **
  10922. ** If an error was encountered within a call to an sqlite3changeset_xxx()
  10923. ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
  10924. ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
  10925. ** to that error is returned by this function. Otherwise, SQLITE_OK is
  10926. ** returned. This is to allow the following pattern (pseudo-code):
  10927. **
  10928. ** <pre>
  10929. ** sqlite3changeset_start();
  10930. ** while( SQLITE_ROW==sqlite3changeset_next() ){
  10931. ** // Do something with change.
  10932. ** }
  10933. ** rc = sqlite3changeset_finalize();
  10934. ** if( rc!=SQLITE_OK ){
  10935. ** // An error has occurred
  10936. ** }
  10937. ** </pre>
  10938. */
  10939. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
  10940. /*
  10941. ** CAPI3REF: Invert A Changeset
  10942. **
  10943. ** This function is used to "invert" a changeset object. Applying an inverted
  10944. ** changeset to a database reverses the effects of applying the uninverted
  10945. ** changeset. Specifically:
  10946. **
  10947. ** <ul>
  10948. ** <li> Each DELETE change is changed to an INSERT, and
  10949. ** <li> Each INSERT change is changed to a DELETE, and
  10950. ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
  10951. ** </ul>
  10952. **
  10953. ** This function does not change the order in which changes appear within
  10954. ** the changeset. It merely reverses the sense of each individual change.
  10955. **
  10956. ** If successful, a pointer to a buffer containing the inverted changeset
  10957. ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
  10958. ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
  10959. ** zeroed and an SQLite error code returned.
  10960. **
  10961. ** It is the responsibility of the caller to eventually call sqlite3_free()
  10962. ** on the *ppOut pointer to free the buffer allocation following a successful
  10963. ** call to this function.
  10964. **
  10965. ** WARNING/TODO: This function currently assumes that the input is a valid
  10966. ** changeset. If it is not, the results are undefined.
  10967. */
  10968. SQLITE_API int sqlite3changeset_invert(
  10969. int nIn, const void *pIn, /* Input changeset */
  10970. int *pnOut, void **ppOut /* OUT: Inverse of input */
  10971. );
  10972. /*
  10973. ** CAPI3REF: Concatenate Two Changeset Objects
  10974. **
  10975. ** This function is used to concatenate two changesets, A and B, into a
  10976. ** single changeset. The result is a changeset equivalent to applying
  10977. ** changeset A followed by changeset B.
  10978. **
  10979. ** This function combines the two input changesets using an
  10980. ** sqlite3_changegroup object. Calling it produces similar results as the
  10981. ** following code fragment:
  10982. **
  10983. ** <pre>
  10984. ** sqlite3_changegroup *pGrp;
  10985. ** rc = sqlite3_changegroup_new(&pGrp);
  10986. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
  10987. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
  10988. ** if( rc==SQLITE_OK ){
  10989. ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  10990. ** }else{
  10991. ** *ppOut = 0;
  10992. ** *pnOut = 0;
  10993. ** }
  10994. ** </pre>
  10995. **
  10996. ** Refer to the sqlite3_changegroup documentation below for details.
  10997. */
  10998. SQLITE_API int sqlite3changeset_concat(
  10999. int nA, /* Number of bytes in buffer pA */
  11000. void *pA, /* Pointer to buffer containing changeset A */
  11001. int nB, /* Number of bytes in buffer pB */
  11002. void *pB, /* Pointer to buffer containing changeset B */
  11003. int *pnOut, /* OUT: Number of bytes in output changeset */
  11004. void **ppOut /* OUT: Buffer containing output changeset */
  11005. );
  11006. /*
  11007. ** CAPI3REF: Changegroup Handle
  11008. **
  11009. ** A changegroup is an object used to combine two or more
  11010. ** [changesets] or [patchsets]
  11011. */
  11012. typedef struct sqlite3_changegroup sqlite3_changegroup;
  11013. /*
  11014. ** CAPI3REF: Create A New Changegroup Object
  11015. ** CONSTRUCTOR: sqlite3_changegroup
  11016. **
  11017. ** An sqlite3_changegroup object is used to combine two or more changesets
  11018. ** (or patchsets) into a single changeset (or patchset). A single changegroup
  11019. ** object may combine changesets or patchsets, but not both. The output is
  11020. ** always in the same format as the input.
  11021. **
  11022. ** If successful, this function returns SQLITE_OK and populates (*pp) with
  11023. ** a pointer to a new sqlite3_changegroup object before returning. The caller
  11024. ** should eventually free the returned object using a call to
  11025. ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
  11026. ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
  11027. **
  11028. ** The usual usage pattern for an sqlite3_changegroup object is as follows:
  11029. **
  11030. ** <ul>
  11031. ** <li> It is created using a call to sqlite3changegroup_new().
  11032. **
  11033. ** <li> Zero or more changesets (or patchsets) are added to the object
  11034. ** by calling sqlite3changegroup_add().
  11035. **
  11036. ** <li> The result of combining all input changesets together is obtained
  11037. ** by the application via a call to sqlite3changegroup_output().
  11038. **
  11039. ** <li> The object is deleted using a call to sqlite3changegroup_delete().
  11040. ** </ul>
  11041. **
  11042. ** Any number of calls to add() and output() may be made between the calls to
  11043. ** new() and delete(), and in any order.
  11044. **
  11045. ** As well as the regular sqlite3changegroup_add() and
  11046. ** sqlite3changegroup_output() functions, also available are the streaming
  11047. ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
  11048. */
  11049. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
  11050. /*
  11051. ** CAPI3REF: Add A Changeset To A Changegroup
  11052. ** METHOD: sqlite3_changegroup
  11053. **
  11054. ** Add all changes within the changeset (or patchset) in buffer pData (size
  11055. ** nData bytes) to the changegroup.
  11056. **
  11057. ** If the buffer contains a patchset, then all prior calls to this function
  11058. ** on the same changegroup object must also have specified patchsets. Or, if
  11059. ** the buffer contains a changeset, so must have the earlier calls to this
  11060. ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
  11061. ** to the changegroup.
  11062. **
  11063. ** Rows within the changeset and changegroup are identified by the values in
  11064. ** their PRIMARY KEY columns. A change in the changeset is considered to
  11065. ** apply to the same row as a change already present in the changegroup if
  11066. ** the two rows have the same primary key.
  11067. **
  11068. ** Changes to rows that do not already appear in the changegroup are
  11069. ** simply copied into it. Or, if both the new changeset and the changegroup
  11070. ** contain changes that apply to a single row, the final contents of the
  11071. ** changegroup depends on the type of each change, as follows:
  11072. **
  11073. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  11074. ** <tr><th style="white-space:pre">Existing Change </th>
  11075. ** <th style="white-space:pre">New Change </th>
  11076. ** <th>Output Change
  11077. ** <tr><td>INSERT <td>INSERT <td>
  11078. ** The new change is ignored. This case does not occur if the new
  11079. ** changeset was recorded immediately after the changesets already
  11080. ** added to the changegroup.
  11081. ** <tr><td>INSERT <td>UPDATE <td>
  11082. ** The INSERT change remains in the changegroup. The values in the
  11083. ** INSERT change are modified as if the row was inserted by the
  11084. ** existing change and then updated according to the new change.
  11085. ** <tr><td>INSERT <td>DELETE <td>
  11086. ** The existing INSERT is removed from the changegroup. The DELETE is
  11087. ** not added.
  11088. ** <tr><td>UPDATE <td>INSERT <td>
  11089. ** The new change is ignored. This case does not occur if the new
  11090. ** changeset was recorded immediately after the changesets already
  11091. ** added to the changegroup.
  11092. ** <tr><td>UPDATE <td>UPDATE <td>
  11093. ** The existing UPDATE remains within the changegroup. It is amended
  11094. ** so that the accompanying values are as if the row was updated once
  11095. ** by the existing change and then again by the new change.
  11096. ** <tr><td>UPDATE <td>DELETE <td>
  11097. ** The existing UPDATE is replaced by the new DELETE within the
  11098. ** changegroup.
  11099. ** <tr><td>DELETE <td>INSERT <td>
  11100. ** If one or more of the column values in the row inserted by the
  11101. ** new change differ from those in the row deleted by the existing
  11102. ** change, the existing DELETE is replaced by an UPDATE within the
  11103. ** changegroup. Otherwise, if the inserted row is exactly the same
  11104. ** as the deleted row, the existing DELETE is simply discarded.
  11105. ** <tr><td>DELETE <td>UPDATE <td>
  11106. ** The new change is ignored. This case does not occur if the new
  11107. ** changeset was recorded immediately after the changesets already
  11108. ** added to the changegroup.
  11109. ** <tr><td>DELETE <td>DELETE <td>
  11110. ** The new change is ignored. This case does not occur if the new
  11111. ** changeset was recorded immediately after the changesets already
  11112. ** added to the changegroup.
  11113. ** </table>
  11114. **
  11115. ** If the new changeset contains changes to a table that is already present
  11116. ** in the changegroup, then the number of columns and the position of the
  11117. ** primary key columns for the table must be consistent. If this is not the
  11118. ** case, this function fails with SQLITE_SCHEMA. If the input changeset
  11119. ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
  11120. ** returned. Or, if an out-of-memory condition occurs during processing, this
  11121. ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
  11122. ** final contents of the changegroup is undefined.
  11123. **
  11124. ** If no error occurs, SQLITE_OK is returned.
  11125. */
  11126. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
  11127. /*
  11128. ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
  11129. ** METHOD: sqlite3_changegroup
  11130. **
  11131. ** Obtain a buffer containing a changeset (or patchset) representing the
  11132. ** current contents of the changegroup. If the inputs to the changegroup
  11133. ** were themselves changesets, the output is a changeset. Or, if the
  11134. ** inputs were patchsets, the output is also a patchset.
  11135. **
  11136. ** As with the output of the sqlite3session_changeset() and
  11137. ** sqlite3session_patchset() functions, all changes related to a single
  11138. ** table are grouped together in the output of this function. Tables appear
  11139. ** in the same order as for the very first changeset added to the changegroup.
  11140. ** If the second or subsequent changesets added to the changegroup contain
  11141. ** changes for tables that do not appear in the first changeset, they are
  11142. ** appended onto the end of the output changeset, again in the order in
  11143. ** which they are first encountered.
  11144. **
  11145. ** If an error occurs, an SQLite error code is returned and the output
  11146. ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
  11147. ** is returned and the output variables are set to the size of and a
  11148. ** pointer to the output buffer, respectively. In this case it is the
  11149. ** responsibility of the caller to eventually free the buffer using a
  11150. ** call to sqlite3_free().
  11151. */
  11152. SQLITE_API int sqlite3changegroup_output(
  11153. sqlite3_changegroup*,
  11154. int *pnData, /* OUT: Size of output buffer in bytes */
  11155. void **ppData /* OUT: Pointer to output buffer */
  11156. );
  11157. /*
  11158. ** CAPI3REF: Delete A Changegroup Object
  11159. ** DESTRUCTOR: sqlite3_changegroup
  11160. */
  11161. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
  11162. /*
  11163. ** CAPI3REF: Apply A Changeset To A Database
  11164. **
  11165. ** Apply a changeset or patchset to a database. These functions attempt to
  11166. ** update the "main" database attached to handle db with the changes found in
  11167. ** the changeset passed via the second and third arguments.
  11168. **
  11169. ** The fourth argument (xFilter) passed to these functions is the "filter
  11170. ** callback". If it is not NULL, then for each table affected by at least one
  11171. ** change in the changeset, the filter callback is invoked with
  11172. ** the table name as the second argument, and a copy of the context pointer
  11173. ** passed as the sixth argument as the first. If the "filter callback"
  11174. ** returns zero, then no attempt is made to apply any changes to the table.
  11175. ** Otherwise, if the return value is non-zero or the xFilter argument to
  11176. ** is NULL, all changes related to the table are attempted.
  11177. **
  11178. ** For each table that is not excluded by the filter callback, this function
  11179. ** tests that the target database contains a compatible table. A table is
  11180. ** considered compatible if all of the following are true:
  11181. **
  11182. ** <ul>
  11183. ** <li> The table has the same name as the name recorded in the
  11184. ** changeset, and
  11185. ** <li> The table has at least as many columns as recorded in the
  11186. ** changeset, and
  11187. ** <li> The table has primary key columns in the same position as
  11188. ** recorded in the changeset.
  11189. ** </ul>
  11190. **
  11191. ** If there is no compatible table, it is not an error, but none of the
  11192. ** changes associated with the table are applied. A warning message is issued
  11193. ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
  11194. ** one such warning is issued for each table in the changeset.
  11195. **
  11196. ** For each change for which there is a compatible table, an attempt is made
  11197. ** to modify the table contents according to the UPDATE, INSERT or DELETE
  11198. ** change. If a change cannot be applied cleanly, the conflict handler
  11199. ** function passed as the fifth argument to sqlite3changeset_apply() may be
  11200. ** invoked. A description of exactly when the conflict handler is invoked for
  11201. ** each type of change is below.
  11202. **
  11203. ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
  11204. ** of passing anything other than a valid function pointer as the xConflict
  11205. ** argument are undefined.
  11206. **
  11207. ** Each time the conflict handler function is invoked, it must return one
  11208. ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
  11209. ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
  11210. ** if the second argument passed to the conflict handler is either
  11211. ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
  11212. ** returns an illegal value, any changes already made are rolled back and
  11213. ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
  11214. ** actions are taken by sqlite3changeset_apply() depending on the value
  11215. ** returned by each invocation of the conflict-handler function. Refer to
  11216. ** the documentation for the three
  11217. ** [SQLITE_CHANGESET_OMIT|available return values] for details.
  11218. **
  11219. ** <dl>
  11220. ** <dt>DELETE Changes<dd>
  11221. ** For each DELETE change, the function checks if the target database
  11222. ** contains a row with the same primary key value (or values) as the
  11223. ** original row values stored in the changeset. If it does, and the values
  11224. ** stored in all non-primary key columns also match the values stored in
  11225. ** the changeset the row is deleted from the target database.
  11226. **
  11227. ** If a row with matching primary key values is found, but one or more of
  11228. ** the non-primary key fields contains a value different from the original
  11229. ** row value stored in the changeset, the conflict-handler function is
  11230. ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
  11231. ** database table has more columns than are recorded in the changeset,
  11232. ** only the values of those non-primary key fields are compared against
  11233. ** the current database contents - any trailing database table columns
  11234. ** are ignored.
  11235. **
  11236. ** If no row with matching primary key values is found in the database,
  11237. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  11238. ** passed as the second argument.
  11239. **
  11240. ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
  11241. ** (which can only happen if a foreign key constraint is violated), the
  11242. ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
  11243. ** passed as the second argument. This includes the case where the DELETE
  11244. ** operation is attempted because an earlier call to the conflict handler
  11245. ** function returned [SQLITE_CHANGESET_REPLACE].
  11246. **
  11247. ** <dt>INSERT Changes<dd>
  11248. ** For each INSERT change, an attempt is made to insert the new row into
  11249. ** the database. If the changeset row contains fewer fields than the
  11250. ** database table, the trailing fields are populated with their default
  11251. ** values.
  11252. **
  11253. ** If the attempt to insert the row fails because the database already
  11254. ** contains a row with the same primary key values, the conflict handler
  11255. ** function is invoked with the second argument set to
  11256. ** [SQLITE_CHANGESET_CONFLICT].
  11257. **
  11258. ** If the attempt to insert the row fails because of some other constraint
  11259. ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
  11260. ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
  11261. ** This includes the case where the INSERT operation is re-attempted because
  11262. ** an earlier call to the conflict handler function returned
  11263. ** [SQLITE_CHANGESET_REPLACE].
  11264. **
  11265. ** <dt>UPDATE Changes<dd>
  11266. ** For each UPDATE change, the function checks if the target database
  11267. ** contains a row with the same primary key value (or values) as the
  11268. ** original row values stored in the changeset. If it does, and the values
  11269. ** stored in all modified non-primary key columns also match the values
  11270. ** stored in the changeset the row is updated within the target database.
  11271. **
  11272. ** If a row with matching primary key values is found, but one or more of
  11273. ** the modified non-primary key fields contains a value different from an
  11274. ** original row value stored in the changeset, the conflict-handler function
  11275. ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
  11276. ** UPDATE changes only contain values for non-primary key fields that are
  11277. ** to be modified, only those fields need to match the original values to
  11278. ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
  11279. **
  11280. ** If no row with matching primary key values is found in the database,
  11281. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  11282. ** passed as the second argument.
  11283. **
  11284. ** If the UPDATE operation is attempted, but SQLite returns
  11285. ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
  11286. ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
  11287. ** This includes the case where the UPDATE operation is attempted after
  11288. ** an earlier call to the conflict handler function returned
  11289. ** [SQLITE_CHANGESET_REPLACE].
  11290. ** </dl>
  11291. **
  11292. ** It is safe to execute SQL statements, including those that write to the
  11293. ** table that the callback related to, from within the xConflict callback.
  11294. ** This can be used to further customize the applications conflict
  11295. ** resolution strategy.
  11296. **
  11297. ** All changes made by these functions are enclosed in a savepoint transaction.
  11298. ** If any other error (aside from a constraint failure when attempting to
  11299. ** write to the target database) occurs, then the savepoint transaction is
  11300. ** rolled back, restoring the target database to its original state, and an
  11301. ** SQLite error code returned.
  11302. **
  11303. ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
  11304. ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
  11305. ** may set (*ppRebase) to point to a "rebase" that may be used with the
  11306. ** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
  11307. ** is set to the size of the buffer in bytes. It is the responsibility of the
  11308. ** caller to eventually free any such buffer using sqlite3_free(). The buffer
  11309. ** is only allocated and populated if one or more conflicts were encountered
  11310. ** while applying the patchset. See comments surrounding the sqlite3_rebaser
  11311. ** APIs for further details.
  11312. **
  11313. ** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
  11314. ** may be modified by passing a combination of
  11315. ** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
  11316. **
  11317. ** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
  11318. ** and therefore subject to change.
  11319. */
  11320. SQLITE_API int sqlite3changeset_apply(
  11321. sqlite3 *db, /* Apply change to "main" db of this handle */
  11322. int nChangeset, /* Size of changeset in bytes */
  11323. void *pChangeset, /* Changeset blob */
  11324. int(*xFilter)(
  11325. void *pCtx, /* Copy of sixth arg to _apply() */
  11326. const char *zTab /* Table name */
  11327. ),
  11328. int(*xConflict)(
  11329. void *pCtx, /* Copy of sixth arg to _apply() */
  11330. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11331. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11332. ),
  11333. void *pCtx /* First argument passed to xConflict */
  11334. );
  11335. SQLITE_API int sqlite3changeset_apply_v2(
  11336. sqlite3 *db, /* Apply change to "main" db of this handle */
  11337. int nChangeset, /* Size of changeset in bytes */
  11338. void *pChangeset, /* Changeset blob */
  11339. int(*xFilter)(
  11340. void *pCtx, /* Copy of sixth arg to _apply() */
  11341. const char *zTab /* Table name */
  11342. ),
  11343. int(*xConflict)(
  11344. void *pCtx, /* Copy of sixth arg to _apply() */
  11345. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11346. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11347. ),
  11348. void *pCtx, /* First argument passed to xConflict */
  11349. void **ppRebase, int *pnRebase, /* OUT: Rebase data */
  11350. int flags /* SESSION_CHANGESETAPPLY_* flags */
  11351. );
  11352. /*
  11353. ** CAPI3REF: Flags for sqlite3changeset_apply_v2
  11354. **
  11355. ** The following flags may passed via the 9th parameter to
  11356. ** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
  11357. **
  11358. ** <dl>
  11359. ** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
  11360. ** Usually, the sessions module encloses all operations performed by
  11361. ** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
  11362. ** SAVEPOINT is committed if the changeset or patchset is successfully
  11363. ** applied, or rolled back if an error occurs. Specifying this flag
  11364. ** causes the sessions module to omit this savepoint. In this case, if the
  11365. ** caller has an open transaction or savepoint when apply_v2() is called,
  11366. ** it may revert the partially applied changeset by rolling it back.
  11367. **
  11368. ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
  11369. ** Invert the changeset before applying it. This is equivalent to inverting
  11370. ** a changeset using sqlite3changeset_invert() before applying it. It is
  11371. ** an error to specify this flag with a patchset.
  11372. */
  11373. #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001
  11374. #define SQLITE_CHANGESETAPPLY_INVERT 0x0002
  11375. /*
  11376. ** CAPI3REF: Constants Passed To The Conflict Handler
  11377. **
  11378. ** Values that may be passed as the second argument to a conflict-handler.
  11379. **
  11380. ** <dl>
  11381. ** <dt>SQLITE_CHANGESET_DATA<dd>
  11382. ** The conflict handler is invoked with CHANGESET_DATA as the second argument
  11383. ** when processing a DELETE or UPDATE change if a row with the required
  11384. ** PRIMARY KEY fields is present in the database, but one or more other
  11385. ** (non primary-key) fields modified by the update do not contain the
  11386. ** expected "before" values.
  11387. **
  11388. ** The conflicting row, in this case, is the database row with the matching
  11389. ** primary key.
  11390. **
  11391. ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
  11392. ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
  11393. ** argument when processing a DELETE or UPDATE change if a row with the
  11394. ** required PRIMARY KEY fields is not present in the database.
  11395. **
  11396. ** There is no conflicting row in this case. The results of invoking the
  11397. ** sqlite3changeset_conflict() API are undefined.
  11398. **
  11399. ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
  11400. ** CHANGESET_CONFLICT is passed as the second argument to the conflict
  11401. ** handler while processing an INSERT change if the operation would result
  11402. ** in duplicate primary key values.
  11403. **
  11404. ** The conflicting row in this case is the database row with the matching
  11405. ** primary key.
  11406. **
  11407. ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
  11408. ** If foreign key handling is enabled, and applying a changeset leaves the
  11409. ** database in a state containing foreign key violations, the conflict
  11410. ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
  11411. ** exactly once before the changeset is committed. If the conflict handler
  11412. ** returns CHANGESET_OMIT, the changes, including those that caused the
  11413. ** foreign key constraint violation, are committed. Or, if it returns
  11414. ** CHANGESET_ABORT, the changeset is rolled back.
  11415. **
  11416. ** No current or conflicting row information is provided. The only function
  11417. ** it is possible to call on the supplied sqlite3_changeset_iter handle
  11418. ** is sqlite3changeset_fk_conflicts().
  11419. **
  11420. ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
  11421. ** If any other constraint violation occurs while applying a change (i.e.
  11422. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
  11423. ** invoked with CHANGESET_CONSTRAINT as the second argument.
  11424. **
  11425. ** There is no conflicting row in this case. The results of invoking the
  11426. ** sqlite3changeset_conflict() API are undefined.
  11427. **
  11428. ** </dl>
  11429. */
  11430. #define SQLITE_CHANGESET_DATA 1
  11431. #define SQLITE_CHANGESET_NOTFOUND 2
  11432. #define SQLITE_CHANGESET_CONFLICT 3
  11433. #define SQLITE_CHANGESET_CONSTRAINT 4
  11434. #define SQLITE_CHANGESET_FOREIGN_KEY 5
  11435. /*
  11436. ** CAPI3REF: Constants Returned By The Conflict Handler
  11437. **
  11438. ** A conflict handler callback must return one of the following three values.
  11439. **
  11440. ** <dl>
  11441. ** <dt>SQLITE_CHANGESET_OMIT<dd>
  11442. ** If a conflict handler returns this value no special action is taken. The
  11443. ** change that caused the conflict is not applied. The session module
  11444. ** continues to the next change in the changeset.
  11445. **
  11446. ** <dt>SQLITE_CHANGESET_REPLACE<dd>
  11447. ** This value may only be returned if the second argument to the conflict
  11448. ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
  11449. ** is not the case, any changes applied so far are rolled back and the
  11450. ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
  11451. **
  11452. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
  11453. ** handler, then the conflicting row is either updated or deleted, depending
  11454. ** on the type of change.
  11455. **
  11456. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
  11457. ** handler, then the conflicting row is removed from the database and a
  11458. ** second attempt to apply the change is made. If this second attempt fails,
  11459. ** the original row is restored to the database before continuing.
  11460. **
  11461. ** <dt>SQLITE_CHANGESET_ABORT<dd>
  11462. ** If this value is returned, any changes applied so far are rolled back
  11463. ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
  11464. ** </dl>
  11465. */
  11466. #define SQLITE_CHANGESET_OMIT 0
  11467. #define SQLITE_CHANGESET_REPLACE 1
  11468. #define SQLITE_CHANGESET_ABORT 2
  11469. /*
  11470. ** CAPI3REF: Rebasing changesets
  11471. ** EXPERIMENTAL
  11472. **
  11473. ** Suppose there is a site hosting a database in state S0. And that
  11474. ** modifications are made that move that database to state S1 and a
  11475. ** changeset recorded (the "local" changeset). Then, a changeset based
  11476. ** on S0 is received from another site (the "remote" changeset) and
  11477. ** applied to the database. The database is then in state
  11478. ** (S1+"remote"), where the exact state depends on any conflict
  11479. ** resolution decisions (OMIT or REPLACE) made while applying "remote".
  11480. ** Rebasing a changeset is to update it to take those conflict
  11481. ** resolution decisions into account, so that the same conflicts
  11482. ** do not have to be resolved elsewhere in the network.
  11483. **
  11484. ** For example, if both the local and remote changesets contain an
  11485. ** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
  11486. **
  11487. ** local: INSERT INTO t1 VALUES(1, 'v1');
  11488. ** remote: INSERT INTO t1 VALUES(1, 'v2');
  11489. **
  11490. ** and the conflict resolution is REPLACE, then the INSERT change is
  11491. ** removed from the local changeset (it was overridden). Or, if the
  11492. ** conflict resolution was "OMIT", then the local changeset is modified
  11493. ** to instead contain:
  11494. **
  11495. ** UPDATE t1 SET b = 'v2' WHERE a=1;
  11496. **
  11497. ** Changes within the local changeset are rebased as follows:
  11498. **
  11499. ** <dl>
  11500. ** <dt>Local INSERT<dd>
  11501. ** This may only conflict with a remote INSERT. If the conflict
  11502. ** resolution was OMIT, then add an UPDATE change to the rebased
  11503. ** changeset. Or, if the conflict resolution was REPLACE, add
  11504. ** nothing to the rebased changeset.
  11505. **
  11506. ** <dt>Local DELETE<dd>
  11507. ** This may conflict with a remote UPDATE or DELETE. In both cases the
  11508. ** only possible resolution is OMIT. If the remote operation was a
  11509. ** DELETE, then add no change to the rebased changeset. If the remote
  11510. ** operation was an UPDATE, then the old.* fields of change are updated
  11511. ** to reflect the new.* values in the UPDATE.
  11512. **
  11513. ** <dt>Local UPDATE<dd>
  11514. ** This may conflict with a remote UPDATE or DELETE. If it conflicts
  11515. ** with a DELETE, and the conflict resolution was OMIT, then the update
  11516. ** is changed into an INSERT. Any undefined values in the new.* record
  11517. ** from the update change are filled in using the old.* values from
  11518. ** the conflicting DELETE. Or, if the conflict resolution was REPLACE,
  11519. ** the UPDATE change is simply omitted from the rebased changeset.
  11520. **
  11521. ** If conflict is with a remote UPDATE and the resolution is OMIT, then
  11522. ** the old.* values are rebased using the new.* values in the remote
  11523. ** change. Or, if the resolution is REPLACE, then the change is copied
  11524. ** into the rebased changeset with updates to columns also updated by
  11525. ** the conflicting remote UPDATE removed. If this means no columns would
  11526. ** be updated, the change is omitted.
  11527. ** </dl>
  11528. **
  11529. ** A local change may be rebased against multiple remote changes
  11530. ** simultaneously. If a single key is modified by multiple remote
  11531. ** changesets, they are combined as follows before the local changeset
  11532. ** is rebased:
  11533. **
  11534. ** <ul>
  11535. ** <li> If there has been one or more REPLACE resolutions on a
  11536. ** key, it is rebased according to a REPLACE.
  11537. **
  11538. ** <li> If there have been no REPLACE resolutions on a key, then
  11539. ** the local changeset is rebased according to the most recent
  11540. ** of the OMIT resolutions.
  11541. ** </ul>
  11542. **
  11543. ** Note that conflict resolutions from multiple remote changesets are
  11544. ** combined on a per-field basis, not per-row. This means that in the
  11545. ** case of multiple remote UPDATE operations, some fields of a single
  11546. ** local change may be rebased for REPLACE while others are rebased for
  11547. ** OMIT.
  11548. **
  11549. ** In order to rebase a local changeset, the remote changeset must first
  11550. ** be applied to the local database using sqlite3changeset_apply_v2() and
  11551. ** the buffer of rebase information captured. Then:
  11552. **
  11553. ** <ol>
  11554. ** <li> An sqlite3_rebaser object is created by calling
  11555. ** sqlite3rebaser_create().
  11556. ** <li> The new object is configured with the rebase buffer obtained from
  11557. ** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
  11558. ** If the local changeset is to be rebased against multiple remote
  11559. ** changesets, then sqlite3rebaser_configure() should be called
  11560. ** multiple times, in the same order that the multiple
  11561. ** sqlite3changeset_apply_v2() calls were made.
  11562. ** <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
  11563. ** <li> The sqlite3_rebaser object is deleted by calling
  11564. ** sqlite3rebaser_delete().
  11565. ** </ol>
  11566. */
  11567. typedef struct sqlite3_rebaser sqlite3_rebaser;
  11568. /*
  11569. ** CAPI3REF: Create a changeset rebaser object.
  11570. ** EXPERIMENTAL
  11571. **
  11572. ** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
  11573. ** point to the new object and return SQLITE_OK. Otherwise, if an error
  11574. ** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
  11575. ** to NULL.
  11576. */
  11577. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
  11578. /*
  11579. ** CAPI3REF: Configure a changeset rebaser object.
  11580. ** EXPERIMENTAL
  11581. **
  11582. ** Configure the changeset rebaser object to rebase changesets according
  11583. ** to the conflict resolutions described by buffer pRebase (size nRebase
  11584. ** bytes), which must have been obtained from a previous call to
  11585. ** sqlite3changeset_apply_v2().
  11586. */
  11587. SQLITE_API int sqlite3rebaser_configure(
  11588. sqlite3_rebaser*,
  11589. int nRebase, const void *pRebase
  11590. );
  11591. /*
  11592. ** CAPI3REF: Rebase a changeset
  11593. ** EXPERIMENTAL
  11594. **
  11595. ** Argument pIn must point to a buffer containing a changeset nIn bytes
  11596. ** in size. This function allocates and populates a buffer with a copy
  11597. ** of the changeset rebased rebased according to the configuration of the
  11598. ** rebaser object passed as the first argument. If successful, (*ppOut)
  11599. ** is set to point to the new buffer containing the rebased changset and
  11600. ** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
  11601. ** responsibility of the caller to eventually free the new buffer using
  11602. ** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
  11603. ** are set to zero and an SQLite error code returned.
  11604. */
  11605. SQLITE_API int sqlite3rebaser_rebase(
  11606. sqlite3_rebaser*,
  11607. int nIn, const void *pIn,
  11608. int *pnOut, void **ppOut
  11609. );
  11610. /*
  11611. ** CAPI3REF: Delete a changeset rebaser object.
  11612. ** EXPERIMENTAL
  11613. **
  11614. ** Delete the changeset rebaser object and all associated resources. There
  11615. ** should be one call to this function for each successful invocation
  11616. ** of sqlite3rebaser_create().
  11617. */
  11618. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
  11619. /*
  11620. ** CAPI3REF: Streaming Versions of API functions.
  11621. **
  11622. ** The six streaming API xxx_strm() functions serve similar purposes to the
  11623. ** corresponding non-streaming API functions:
  11624. **
  11625. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  11626. ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
  11627. ** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
  11628. ** <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
  11629. ** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
  11630. ** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
  11631. ** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
  11632. ** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
  11633. ** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
  11634. ** </table>
  11635. **
  11636. ** Non-streaming functions that accept changesets (or patchsets) as input
  11637. ** require that the entire changeset be stored in a single buffer in memory.
  11638. ** Similarly, those that return a changeset or patchset do so by returning
  11639. ** a pointer to a single large buffer allocated using sqlite3_malloc().
  11640. ** Normally this is convenient. However, if an application running in a
  11641. ** low-memory environment is required to handle very large changesets, the
  11642. ** large contiguous memory allocations required can become onerous.
  11643. **
  11644. ** In order to avoid this problem, instead of a single large buffer, input
  11645. ** is passed to a streaming API functions by way of a callback function that
  11646. ** the sessions module invokes to incrementally request input data as it is
  11647. ** required. In all cases, a pair of API function parameters such as
  11648. **
  11649. ** <pre>
  11650. ** &nbsp; int nChangeset,
  11651. ** &nbsp; void *pChangeset,
  11652. ** </pre>
  11653. **
  11654. ** Is replaced by:
  11655. **
  11656. ** <pre>
  11657. ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
  11658. ** &nbsp; void *pIn,
  11659. ** </pre>
  11660. **
  11661. ** Each time the xInput callback is invoked by the sessions module, the first
  11662. ** argument passed is a copy of the supplied pIn context pointer. The second
  11663. ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
  11664. ** error occurs the xInput method should copy up to (*pnData) bytes of data
  11665. ** into the buffer and set (*pnData) to the actual number of bytes copied
  11666. ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
  11667. ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
  11668. ** error code should be returned. In all cases, if an xInput callback returns
  11669. ** an error, all processing is abandoned and the streaming API function
  11670. ** returns a copy of the error code to the caller.
  11671. **
  11672. ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
  11673. ** invoked by the sessions module at any point during the lifetime of the
  11674. ** iterator. If such an xInput callback returns an error, the iterator enters
  11675. ** an error state, whereby all subsequent calls to iterator functions
  11676. ** immediately fail with the same error code as returned by xInput.
  11677. **
  11678. ** Similarly, streaming API functions that return changesets (or patchsets)
  11679. ** return them in chunks by way of a callback function instead of via a
  11680. ** pointer to a single large buffer. In this case, a pair of parameters such
  11681. ** as:
  11682. **
  11683. ** <pre>
  11684. ** &nbsp; int *pnChangeset,
  11685. ** &nbsp; void **ppChangeset,
  11686. ** </pre>
  11687. **
  11688. ** Is replaced by:
  11689. **
  11690. ** <pre>
  11691. ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
  11692. ** &nbsp; void *pOut
  11693. ** </pre>
  11694. **
  11695. ** The xOutput callback is invoked zero or more times to return data to
  11696. ** the application. The first parameter passed to each call is a copy of the
  11697. ** pOut pointer supplied by the application. The second parameter, pData,
  11698. ** points to a buffer nData bytes in size containing the chunk of output
  11699. ** data being returned. If the xOutput callback successfully processes the
  11700. ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
  11701. ** it should return some other SQLite error code. In this case processing
  11702. ** is immediately abandoned and the streaming API function returns a copy
  11703. ** of the xOutput error code to the application.
  11704. **
  11705. ** The sessions module never invokes an xOutput callback with the third
  11706. ** parameter set to a value less than or equal to zero. Other than this,
  11707. ** no guarantees are made as to the size of the chunks of data returned.
  11708. */
  11709. SQLITE_API int sqlite3changeset_apply_strm(
  11710. sqlite3 *db, /* Apply change to "main" db of this handle */
  11711. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  11712. void *pIn, /* First arg for xInput */
  11713. int(*xFilter)(
  11714. void *pCtx, /* Copy of sixth arg to _apply() */
  11715. const char *zTab /* Table name */
  11716. ),
  11717. int(*xConflict)(
  11718. void *pCtx, /* Copy of sixth arg to _apply() */
  11719. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11720. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11721. ),
  11722. void *pCtx /* First argument passed to xConflict */
  11723. );
  11724. SQLITE_API int sqlite3changeset_apply_v2_strm(
  11725. sqlite3 *db, /* Apply change to "main" db of this handle */
  11726. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  11727. void *pIn, /* First arg for xInput */
  11728. int(*xFilter)(
  11729. void *pCtx, /* Copy of sixth arg to _apply() */
  11730. const char *zTab /* Table name */
  11731. ),
  11732. int(*xConflict)(
  11733. void *pCtx, /* Copy of sixth arg to _apply() */
  11734. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11735. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11736. ),
  11737. void *pCtx, /* First argument passed to xConflict */
  11738. void **ppRebase, int *pnRebase,
  11739. int flags
  11740. );
  11741. SQLITE_API int sqlite3changeset_concat_strm(
  11742. int (*xInputA)(void *pIn, void *pData, int *pnData),
  11743. void *pInA,
  11744. int (*xInputB)(void *pIn, void *pData, int *pnData),
  11745. void *pInB,
  11746. int (*xOutput)(void *pOut, const void *pData, int nData),
  11747. void *pOut
  11748. );
  11749. SQLITE_API int sqlite3changeset_invert_strm(
  11750. int (*xInput)(void *pIn, void *pData, int *pnData),
  11751. void *pIn,
  11752. int (*xOutput)(void *pOut, const void *pData, int nData),
  11753. void *pOut
  11754. );
  11755. SQLITE_API int sqlite3changeset_start_strm(
  11756. sqlite3_changeset_iter **pp,
  11757. int (*xInput)(void *pIn, void *pData, int *pnData),
  11758. void *pIn
  11759. );
  11760. SQLITE_API int sqlite3changeset_start_v2_strm(
  11761. sqlite3_changeset_iter **pp,
  11762. int (*xInput)(void *pIn, void *pData, int *pnData),
  11763. void *pIn,
  11764. int flags
  11765. );
  11766. SQLITE_API int sqlite3session_changeset_strm(
  11767. sqlite3_session *pSession,
  11768. int (*xOutput)(void *pOut, const void *pData, int nData),
  11769. void *pOut
  11770. );
  11771. SQLITE_API int sqlite3session_patchset_strm(
  11772. sqlite3_session *pSession,
  11773. int (*xOutput)(void *pOut, const void *pData, int nData),
  11774. void *pOut
  11775. );
  11776. SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
  11777. int (*xInput)(void *pIn, void *pData, int *pnData),
  11778. void *pIn
  11779. );
  11780. SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
  11781. int (*xOutput)(void *pOut, const void *pData, int nData),
  11782. void *pOut
  11783. );
  11784. SQLITE_API int sqlite3rebaser_rebase_strm(
  11785. sqlite3_rebaser *pRebaser,
  11786. int (*xInput)(void *pIn, void *pData, int *pnData),
  11787. void *pIn,
  11788. int (*xOutput)(void *pOut, const void *pData, int nData),
  11789. void *pOut
  11790. );
  11791. /*
  11792. ** CAPI3REF: Configure global parameters
  11793. **
  11794. ** The sqlite3session_config() interface is used to make global configuration
  11795. ** changes to the sessions module in order to tune it to the specific needs
  11796. ** of the application.
  11797. **
  11798. ** The sqlite3session_config() interface is not threadsafe. If it is invoked
  11799. ** while any other thread is inside any other sessions method then the
  11800. ** results are undefined. Furthermore, if it is invoked after any sessions
  11801. ** related objects have been created, the results are also undefined.
  11802. **
  11803. ** The first argument to the sqlite3session_config() function must be one
  11804. ** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
  11805. ** interpretation of the (void*) value passed as the second parameter and
  11806. ** the effect of calling this function depends on the value of the first
  11807. ** parameter.
  11808. **
  11809. ** <dl>
  11810. ** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>
  11811. ** By default, the sessions module streaming interfaces attempt to input
  11812. ** and output data in approximately 1 KiB chunks. This operand may be used
  11813. ** to set and query the value of this configuration setting. The pointer
  11814. ** passed as the second argument must point to a value of type (int).
  11815. ** If this value is greater than 0, it is used as the new streaming data
  11816. ** chunk size for both input and output. Before returning, the (int) value
  11817. ** pointed to by pArg is set to the final value of the streaming interface
  11818. ** chunk size.
  11819. ** </dl>
  11820. **
  11821. ** This function returns SQLITE_OK if successful, or an SQLite error code
  11822. ** otherwise.
  11823. */
  11824. SQLITE_API int sqlite3session_config(int op, void *pArg);
  11825. /*
  11826. ** CAPI3REF: Values for sqlite3session_config().
  11827. */
  11828. #define SQLITE_SESSION_CONFIG_STRMSIZE 1
  11829. /*
  11830. ** Make sure we can call this stuff from C++.
  11831. */
  11832. #if 0
  11833. }
  11834. #endif
  11835. #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
  11836. /******** End of sqlite3session.h *********/
  11837. /******** Begin file fts5.h *********/
  11838. /*
  11839. ** 2014 May 31
  11840. **
  11841. ** The author disclaims copyright to this source code. In place of
  11842. ** a legal notice, here is a blessing:
  11843. **
  11844. ** May you do good and not evil.
  11845. ** May you find forgiveness for yourself and forgive others.
  11846. ** May you share freely, never taking more than you give.
  11847. **
  11848. ******************************************************************************
  11849. **
  11850. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  11851. ** FTS5 may be extended with:
  11852. **
  11853. ** * custom tokenizers, and
  11854. ** * custom auxiliary functions.
  11855. */
  11856. #ifndef _FTS5_H
  11857. #define _FTS5_H
  11858. #if 0
  11859. extern "C" {
  11860. #endif
  11861. /*************************************************************************
  11862. ** CUSTOM AUXILIARY FUNCTIONS
  11863. **
  11864. ** Virtual table implementations may overload SQL functions by implementing
  11865. ** the sqlite3_module.xFindFunction() method.
  11866. */
  11867. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  11868. typedef struct Fts5Context Fts5Context;
  11869. typedef struct Fts5PhraseIter Fts5PhraseIter;
  11870. typedef void (*fts5_extension_function)(
  11871. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  11872. Fts5Context *pFts, /* First arg to pass to pApi functions */
  11873. sqlite3_context *pCtx, /* Context for returning result/error */
  11874. int nVal, /* Number of values in apVal[] array */
  11875. sqlite3_value **apVal /* Array of trailing arguments */
  11876. );
  11877. struct Fts5PhraseIter {
  11878. const unsigned char *a;
  11879. const unsigned char *b;
  11880. };
  11881. /*
  11882. ** EXTENSION API FUNCTIONS
  11883. **
  11884. ** xUserData(pFts):
  11885. ** Return a copy of the context pointer the extension function was
  11886. ** registered with.
  11887. **
  11888. ** xColumnTotalSize(pFts, iCol, pnToken):
  11889. ** If parameter iCol is less than zero, set output variable *pnToken
  11890. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  11891. ** non-negative but less than the number of columns in the table, return
  11892. ** the total number of tokens in column iCol, considering all rows in
  11893. ** the FTS5 table.
  11894. **
  11895. ** If parameter iCol is greater than or equal to the number of columns
  11896. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  11897. ** an OOM condition or IO error), an appropriate SQLite error code is
  11898. ** returned.
  11899. **
  11900. ** xColumnCount(pFts):
  11901. ** Return the number of columns in the table.
  11902. **
  11903. ** xColumnSize(pFts, iCol, pnToken):
  11904. ** If parameter iCol is less than zero, set output variable *pnToken
  11905. ** to the total number of tokens in the current row. Or, if iCol is
  11906. ** non-negative but less than the number of columns in the table, set
  11907. ** *pnToken to the number of tokens in column iCol of the current row.
  11908. **
  11909. ** If parameter iCol is greater than or equal to the number of columns
  11910. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  11911. ** an OOM condition or IO error), an appropriate SQLite error code is
  11912. ** returned.
  11913. **
  11914. ** This function may be quite inefficient if used with an FTS5 table
  11915. ** created with the "columnsize=0" option.
  11916. **
  11917. ** xColumnText:
  11918. ** This function attempts to retrieve the text of column iCol of the
  11919. ** current document. If successful, (*pz) is set to point to a buffer
  11920. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  11921. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  11922. ** if an error occurs, an SQLite error code is returned and the final values
  11923. ** of (*pz) and (*pn) are undefined.
  11924. **
  11925. ** xPhraseCount:
  11926. ** Returns the number of phrases in the current query expression.
  11927. **
  11928. ** xPhraseSize:
  11929. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  11930. ** are numbered starting from zero.
  11931. **
  11932. ** xInstCount:
  11933. ** Set *pnInst to the total number of occurrences of all phrases within
  11934. ** the query within the current row. Return SQLITE_OK if successful, or
  11935. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  11936. **
  11937. ** This API can be quite slow if used with an FTS5 table created with the
  11938. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  11939. ** with either "detail=none" or "detail=column" and "content=" option
  11940. ** (i.e. if it is a contentless table), then this API always returns 0.
  11941. **
  11942. ** xInst:
  11943. ** Query for the details of phrase match iIdx within the current row.
  11944. ** Phrase matches are numbered starting from zero, so the iIdx argument
  11945. ** should be greater than or equal to zero and smaller than the value
  11946. ** output by xInstCount().
  11947. **
  11948. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  11949. ** to the column in which it occurs and *piOff the token offset of the
  11950. ** first token of the phrase. The exception is if the table was created
  11951. ** with the offsets=0 option specified. In this case *piOff is always
  11952. ** set to -1.
  11953. **
  11954. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  11955. ** if an error occurs.
  11956. **
  11957. ** This API can be quite slow if used with an FTS5 table created with the
  11958. ** "detail=none" or "detail=column" option.
  11959. **
  11960. ** xRowid:
  11961. ** Returns the rowid of the current row.
  11962. **
  11963. ** xTokenize:
  11964. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  11965. **
  11966. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  11967. ** This API function is used to query the FTS table for phrase iPhrase
  11968. ** of the current query. Specifically, a query equivalent to:
  11969. **
  11970. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  11971. **
  11972. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  11973. ** current query is executed. Any column filter that applies to
  11974. ** phrase iPhrase of the current query is included in $p. For each
  11975. ** row visited, the callback function passed as the fourth argument
  11976. ** is invoked. The context and API objects passed to the callback
  11977. ** function may be used to access the properties of each matched row.
  11978. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  11979. ** the third argument to pUserData.
  11980. **
  11981. ** If the callback function returns any value other than SQLITE_OK, the
  11982. ** query is abandoned and the xQueryPhrase function returns immediately.
  11983. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  11984. ** Otherwise, the error code is propagated upwards.
  11985. **
  11986. ** If the query runs to completion without incident, SQLITE_OK is returned.
  11987. ** Or, if some error occurs before the query completes or is aborted by
  11988. ** the callback, an SQLite error code is returned.
  11989. **
  11990. **
  11991. ** xSetAuxdata(pFts5, pAux, xDelete)
  11992. **
  11993. ** Save the pointer passed as the second argument as the extension functions
  11994. ** "auxiliary data". The pointer may then be retrieved by the current or any
  11995. ** future invocation of the same fts5 extension function made as part of
  11996. ** of the same MATCH query using the xGetAuxdata() API.
  11997. **
  11998. ** Each extension function is allocated a single auxiliary data slot for
  11999. ** each FTS query (MATCH expression). If the extension function is invoked
  12000. ** more than once for a single FTS query, then all invocations share a
  12001. ** single auxiliary data context.
  12002. **
  12003. ** If there is already an auxiliary data pointer when this function is
  12004. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  12005. ** was specified along with the original pointer, it is invoked at this
  12006. ** point.
  12007. **
  12008. ** The xDelete callback, if one is specified, is also invoked on the
  12009. ** auxiliary data pointer after the FTS5 query has finished.
  12010. **
  12011. ** If an error (e.g. an OOM condition) occurs within this function, an
  12012. ** the auxiliary data is set to NULL and an error code returned. If the
  12013. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  12014. ** pointer before returning.
  12015. **
  12016. **
  12017. ** xGetAuxdata(pFts5, bClear)
  12018. **
  12019. ** Returns the current auxiliary data pointer for the fts5 extension
  12020. ** function. See the xSetAuxdata() method for details.
  12021. **
  12022. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  12023. ** (set to NULL) before this function returns. In this case the xDelete,
  12024. ** if any, is not invoked.
  12025. **
  12026. **
  12027. ** xRowCount(pFts5, pnRow)
  12028. **
  12029. ** This function is used to retrieve the total number of rows in the table.
  12030. ** In other words, the same value that would be returned by:
  12031. **
  12032. ** SELECT count(*) FROM ftstable;
  12033. **
  12034. ** xPhraseFirst()
  12035. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  12036. ** method, to iterate through all instances of a single query phrase within
  12037. ** the current row. This is the same information as is accessible via the
  12038. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  12039. ** to use, this API may be faster under some circumstances. To iterate
  12040. ** through instances of phrase iPhrase, use the following code:
  12041. **
  12042. ** Fts5PhraseIter iter;
  12043. ** int iCol, iOff;
  12044. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  12045. ** iCol>=0;
  12046. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  12047. ** ){
  12048. ** // An instance of phrase iPhrase at offset iOff of column iCol
  12049. ** }
  12050. **
  12051. ** The Fts5PhraseIter structure is defined above. Applications should not
  12052. ** modify this structure directly - it should only be used as shown above
  12053. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  12054. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  12055. **
  12056. ** This API can be quite slow if used with an FTS5 table created with the
  12057. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  12058. ** with either "detail=none" or "detail=column" and "content=" option
  12059. ** (i.e. if it is a contentless table), then this API always iterates
  12060. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  12061. **
  12062. ** xPhraseNext()
  12063. ** See xPhraseFirst above.
  12064. **
  12065. ** xPhraseFirstColumn()
  12066. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  12067. ** and xPhraseNext() APIs described above. The difference is that instead
  12068. ** of iterating through all instances of a phrase in the current row, these
  12069. ** APIs are used to iterate through the set of columns in the current row
  12070. ** that contain one or more instances of a specified phrase. For example:
  12071. **
  12072. ** Fts5PhraseIter iter;
  12073. ** int iCol;
  12074. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  12075. ** iCol>=0;
  12076. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  12077. ** ){
  12078. ** // Column iCol contains at least one instance of phrase iPhrase
  12079. ** }
  12080. **
  12081. ** This API can be quite slow if used with an FTS5 table created with the
  12082. ** "detail=none" option. If the FTS5 table is created with either
  12083. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  12084. ** then this API always iterates through an empty set (all calls to
  12085. ** xPhraseFirstColumn() set iCol to -1).
  12086. **
  12087. ** The information accessed using this API and its companion
  12088. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  12089. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  12090. ** significantly more efficient than those alternatives when used with
  12091. ** "detail=column" tables.
  12092. **
  12093. ** xPhraseNextColumn()
  12094. ** See xPhraseFirstColumn above.
  12095. */
  12096. struct Fts5ExtensionApi {
  12097. int iVersion; /* Currently always set to 3 */
  12098. void *(*xUserData)(Fts5Context*);
  12099. int (*xColumnCount)(Fts5Context*);
  12100. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  12101. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  12102. int (*xTokenize)(Fts5Context*,
  12103. const char *pText, int nText, /* Text to tokenize */
  12104. void *pCtx, /* Context passed to xToken() */
  12105. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  12106. );
  12107. int (*xPhraseCount)(Fts5Context*);
  12108. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  12109. int (*xInstCount)(Fts5Context*, int *pnInst);
  12110. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  12111. sqlite3_int64 (*xRowid)(Fts5Context*);
  12112. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  12113. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  12114. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  12115. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  12116. );
  12117. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  12118. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  12119. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  12120. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  12121. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  12122. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  12123. };
  12124. /*
  12125. ** CUSTOM AUXILIARY FUNCTIONS
  12126. *************************************************************************/
  12127. /*************************************************************************
  12128. ** CUSTOM TOKENIZERS
  12129. **
  12130. ** Applications may also register custom tokenizer types. A tokenizer
  12131. ** is registered by providing fts5 with a populated instance of the
  12132. ** following structure. All structure methods must be defined, setting
  12133. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  12134. ** behaviour. The structure methods are expected to function as follows:
  12135. **
  12136. ** xCreate:
  12137. ** This function is used to allocate and initialize a tokenizer instance.
  12138. ** A tokenizer instance is required to actually tokenize text.
  12139. **
  12140. ** The first argument passed to this function is a copy of the (void*)
  12141. ** pointer provided by the application when the fts5_tokenizer object
  12142. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  12143. ** The second and third arguments are an array of nul-terminated strings
  12144. ** containing the tokenizer arguments, if any, specified following the
  12145. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  12146. ** to create the FTS5 table.
  12147. **
  12148. ** The final argument is an output variable. If successful, (*ppOut)
  12149. ** should be set to point to the new tokenizer handle and SQLITE_OK
  12150. ** returned. If an error occurs, some value other than SQLITE_OK should
  12151. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  12152. ** is undefined.
  12153. **
  12154. ** xDelete:
  12155. ** This function is invoked to delete a tokenizer handle previously
  12156. ** allocated using xCreate(). Fts5 guarantees that this function will
  12157. ** be invoked exactly once for each successful call to xCreate().
  12158. **
  12159. ** xTokenize:
  12160. ** This function is expected to tokenize the nText byte string indicated
  12161. ** by argument pText. pText may or may not be nul-terminated. The first
  12162. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  12163. ** returned by an earlier call to xCreate().
  12164. **
  12165. ** The second argument indicates the reason that FTS5 is requesting
  12166. ** tokenization of the supplied text. This is always one of the following
  12167. ** four values:
  12168. **
  12169. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  12170. ** or removed from the FTS table. The tokenizer is being invoked to
  12171. ** determine the set of tokens to add to (or delete from) the
  12172. ** FTS index.
  12173. **
  12174. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  12175. ** against the FTS index. The tokenizer is being called to tokenize
  12176. ** a bareword or quoted string specified as part of the query.
  12177. **
  12178. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  12179. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  12180. ** followed by a "*" character, indicating that the last token
  12181. ** returned by the tokenizer will be treated as a token prefix.
  12182. **
  12183. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  12184. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  12185. ** function. Or an fts5_api.xColumnSize() request made by the same
  12186. ** on a columnsize=0 database.
  12187. ** </ul>
  12188. **
  12189. ** For each token in the input string, the supplied callback xToken() must
  12190. ** be invoked. The first argument to it should be a copy of the pointer
  12191. ** passed as the second argument to xTokenize(). The third and fourth
  12192. ** arguments are a pointer to a buffer containing the token text, and the
  12193. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  12194. ** of the first byte of and first byte immediately following the text from
  12195. ** which the token is derived within the input.
  12196. **
  12197. ** The second argument passed to the xToken() callback ("tflags") should
  12198. ** normally be set to 0. The exception is if the tokenizer supports
  12199. ** synonyms. In this case see the discussion below for details.
  12200. **
  12201. ** FTS5 assumes the xToken() callback is invoked for each token in the
  12202. ** order that they occur within the input text.
  12203. **
  12204. ** If an xToken() callback returns any value other than SQLITE_OK, then
  12205. ** the tokenization should be abandoned and the xTokenize() method should
  12206. ** immediately return a copy of the xToken() return value. Or, if the
  12207. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  12208. ** if an error occurs with the xTokenize() implementation itself, it
  12209. ** may abandon the tokenization and return any error code other than
  12210. ** SQLITE_OK or SQLITE_DONE.
  12211. **
  12212. ** SYNONYM SUPPORT
  12213. **
  12214. ** Custom tokenizers may also support synonyms. Consider a case in which a
  12215. ** user wishes to query for a phrase such as "first place". Using the
  12216. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  12217. ** of "first place" within the document set, but not alternative forms
  12218. ** such as "1st place". In some applications, it would be better to match
  12219. ** all instances of "first place" or "1st place" regardless of which form
  12220. ** the user specified in the MATCH query text.
  12221. **
  12222. ** There are several ways to approach this in FTS5:
  12223. **
  12224. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  12225. ** In the above example, this means that the tokenizer returns the
  12226. ** same token for inputs "first" and "1st". Say that token is in
  12227. ** fact "first", so that when the user inserts the document "I won
  12228. ** 1st place" entries are added to the index for tokens "i", "won",
  12229. ** "first" and "place". If the user then queries for '1st + place',
  12230. ** the tokenizer substitutes "first" for "1st" and the query works
  12231. ** as expected.
  12232. **
  12233. ** <li> By adding multiple synonyms for a single term to the FTS index.
  12234. ** In this case, when tokenizing query text, the tokenizer may
  12235. ** provide multiple synonyms for a single term within the document.
  12236. ** FTS5 then queries the index for each synonym individually. For
  12237. ** example, faced with the query:
  12238. **
  12239. ** <codeblock>
  12240. ** ... MATCH 'first place'</codeblock>
  12241. **
  12242. ** the tokenizer offers both "1st" and "first" as synonyms for the
  12243. ** first token in the MATCH query and FTS5 effectively runs a query
  12244. ** similar to:
  12245. **
  12246. ** <codeblock>
  12247. ** ... MATCH '(first OR 1st) place'</codeblock>
  12248. **
  12249. ** except that, for the purposes of auxiliary functions, the query
  12250. ** still appears to contain just two phrases - "(first OR 1st)"
  12251. ** being treated as a single phrase.
  12252. **
  12253. ** <li> By adding multiple synonyms for a single term to the FTS index.
  12254. ** Using this method, when tokenizing document text, the tokenizer
  12255. ** provides multiple synonyms for each token. So that when a
  12256. ** document such as "I won first place" is tokenized, entries are
  12257. ** added to the FTS index for "i", "won", "first", "1st" and
  12258. ** "place".
  12259. **
  12260. ** This way, even if the tokenizer does not provide synonyms
  12261. ** when tokenizing query text (it should not - to do would be
  12262. ** inefficient), it doesn't matter if the user queries for
  12263. ** 'first + place' or '1st + place', as there are entries in the
  12264. ** FTS index corresponding to both forms of the first token.
  12265. ** </ol>
  12266. **
  12267. ** Whether it is parsing document or query text, any call to xToken that
  12268. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  12269. ** is considered to supply a synonym for the previous token. For example,
  12270. ** when parsing the document "I won first place", a tokenizer that supports
  12271. ** synonyms would call xToken() 5 times, as follows:
  12272. **
  12273. ** <codeblock>
  12274. ** xToken(pCtx, 0, "i", 1, 0, 1);
  12275. ** xToken(pCtx, 0, "won", 3, 2, 5);
  12276. ** xToken(pCtx, 0, "first", 5, 6, 11);
  12277. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  12278. ** xToken(pCtx, 0, "place", 5, 12, 17);
  12279. **</codeblock>
  12280. **
  12281. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  12282. ** xToken() is called. Multiple synonyms may be specified for a single token
  12283. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  12284. ** There is no limit to the number of synonyms that may be provided for a
  12285. ** single token.
  12286. **
  12287. ** In many cases, method (1) above is the best approach. It does not add
  12288. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  12289. ** so it is efficient in terms of disk space and query speed. However, it
  12290. ** does not support prefix queries very well. If, as suggested above, the
  12291. ** token "first" is substituted for "1st" by the tokenizer, then the query:
  12292. **
  12293. ** <codeblock>
  12294. ** ... MATCH '1s*'</codeblock>
  12295. **
  12296. ** will not match documents that contain the token "1st" (as the tokenizer
  12297. ** will probably not map "1s" to any prefix of "first").
  12298. **
  12299. ** For full prefix support, method (3) may be preferred. In this case,
  12300. ** because the index contains entries for both "first" and "1st", prefix
  12301. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  12302. ** extra entries are added to the FTS index, this method uses more space
  12303. ** within the database.
  12304. **
  12305. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  12306. ** a query such as '1s*' will match documents that contain the literal
  12307. ** token "1st", but not "first" (assuming the tokenizer is not able to
  12308. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  12309. ** will match against "1st" and "first". This method does not require
  12310. ** extra disk space, as no extra entries are added to the FTS index.
  12311. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  12312. ** as separate queries of the FTS index are required for each synonym.
  12313. **
  12314. ** When using methods (2) or (3), it is important that the tokenizer only
  12315. ** provide synonyms when tokenizing document text (method (2)) or query
  12316. ** text (method (3)), not both. Doing so will not cause any errors, but is
  12317. ** inefficient.
  12318. */
  12319. typedef struct Fts5Tokenizer Fts5Tokenizer;
  12320. typedef struct fts5_tokenizer fts5_tokenizer;
  12321. struct fts5_tokenizer {
  12322. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  12323. void (*xDelete)(Fts5Tokenizer*);
  12324. int (*xTokenize)(Fts5Tokenizer*,
  12325. void *pCtx,
  12326. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  12327. const char *pText, int nText,
  12328. int (*xToken)(
  12329. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  12330. int tflags, /* Mask of FTS5_TOKEN_* flags */
  12331. const char *pToken, /* Pointer to buffer containing token */
  12332. int nToken, /* Size of token in bytes */
  12333. int iStart, /* Byte offset of token within input text */
  12334. int iEnd /* Byte offset of end of token within input text */
  12335. )
  12336. );
  12337. };
  12338. /* Flags that may be passed as the third argument to xTokenize() */
  12339. #define FTS5_TOKENIZE_QUERY 0x0001
  12340. #define FTS5_TOKENIZE_PREFIX 0x0002
  12341. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  12342. #define FTS5_TOKENIZE_AUX 0x0008
  12343. /* Flags that may be passed by the tokenizer implementation back to FTS5
  12344. ** as the third argument to the supplied xToken callback. */
  12345. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  12346. /*
  12347. ** END OF CUSTOM TOKENIZERS
  12348. *************************************************************************/
  12349. /*************************************************************************
  12350. ** FTS5 EXTENSION REGISTRATION API
  12351. */
  12352. typedef struct fts5_api fts5_api;
  12353. struct fts5_api {
  12354. int iVersion; /* Currently always set to 2 */
  12355. /* Create a new tokenizer */
  12356. int (*xCreateTokenizer)(
  12357. fts5_api *pApi,
  12358. const char *zName,
  12359. void *pContext,
  12360. fts5_tokenizer *pTokenizer,
  12361. void (*xDestroy)(void*)
  12362. );
  12363. /* Find an existing tokenizer */
  12364. int (*xFindTokenizer)(
  12365. fts5_api *pApi,
  12366. const char *zName,
  12367. void **ppContext,
  12368. fts5_tokenizer *pTokenizer
  12369. );
  12370. /* Create a new auxiliary function */
  12371. int (*xCreateFunction)(
  12372. fts5_api *pApi,
  12373. const char *zName,
  12374. void *pContext,
  12375. fts5_extension_function xFunction,
  12376. void (*xDestroy)(void*)
  12377. );
  12378. };
  12379. /*
  12380. ** END OF REGISTRATION API
  12381. *************************************************************************/
  12382. #if 0
  12383. } /* end of the 'extern "C"' block */
  12384. #endif
  12385. #endif /* _FTS5_H */
  12386. /******** End of fts5.h *********/
  12387. /************** End of sqlite3.h *********************************************/
  12388. /************** Continuing where we left off in sqliteInt.h ******************/
  12389. /*
  12390. ** Include the configuration header output by 'configure' if we're using the
  12391. ** autoconf-based build
  12392. */
  12393. #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
  12394. /* #include "config.h" */
  12395. #define SQLITECONFIG_H 1
  12396. #endif
  12397. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  12398. /************** Begin file sqliteLimit.h *************************************/
  12399. /*
  12400. ** 2007 May 7
  12401. **
  12402. ** The author disclaims copyright to this source code. In place of
  12403. ** a legal notice, here is a blessing:
  12404. **
  12405. ** May you do good and not evil.
  12406. ** May you find forgiveness for yourself and forgive others.
  12407. ** May you share freely, never taking more than you give.
  12408. **
  12409. *************************************************************************
  12410. **
  12411. ** This file defines various limits of what SQLite can process.
  12412. */
  12413. /*
  12414. ** The maximum length of a TEXT or BLOB in bytes. This also
  12415. ** limits the size of a row in a table or index.
  12416. **
  12417. ** The hard limit is the ability of a 32-bit signed integer
  12418. ** to count the size: 2^31-1 or 2147483647.
  12419. */
  12420. #ifndef SQLITE_MAX_LENGTH
  12421. # define SQLITE_MAX_LENGTH 1000000000
  12422. #endif
  12423. /*
  12424. ** This is the maximum number of
  12425. **
  12426. ** * Columns in a table
  12427. ** * Columns in an index
  12428. ** * Columns in a view
  12429. ** * Terms in the SET clause of an UPDATE statement
  12430. ** * Terms in the result set of a SELECT statement
  12431. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  12432. ** * Terms in the VALUES clause of an INSERT statement
  12433. **
  12434. ** The hard upper limit here is 32676. Most database people will
  12435. ** tell you that in a well-normalized database, you usually should
  12436. ** not have more than a dozen or so columns in any table. And if
  12437. ** that is the case, there is no point in having more than a few
  12438. ** dozen values in any of the other situations described above.
  12439. */
  12440. #ifndef SQLITE_MAX_COLUMN
  12441. # define SQLITE_MAX_COLUMN 2000
  12442. #endif
  12443. /*
  12444. ** The maximum length of a single SQL statement in bytes.
  12445. **
  12446. ** It used to be the case that setting this value to zero would
  12447. ** turn the limit off. That is no longer true. It is not possible
  12448. ** to turn this limit off.
  12449. */
  12450. #ifndef SQLITE_MAX_SQL_LENGTH
  12451. # define SQLITE_MAX_SQL_LENGTH 1000000000
  12452. #endif
  12453. /*
  12454. ** The maximum depth of an expression tree. This is limited to
  12455. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  12456. ** want to place more severe limits on the complexity of an
  12457. ** expression.
  12458. **
  12459. ** A value of 0 used to mean that the limit was not enforced.
  12460. ** But that is no longer true. The limit is now strictly enforced
  12461. ** at all times.
  12462. */
  12463. #ifndef SQLITE_MAX_EXPR_DEPTH
  12464. # define SQLITE_MAX_EXPR_DEPTH 1000
  12465. #endif
  12466. /*
  12467. ** The maximum number of terms in a compound SELECT statement.
  12468. ** The code generator for compound SELECT statements does one
  12469. ** level of recursion for each term. A stack overflow can result
  12470. ** if the number of terms is too large. In practice, most SQL
  12471. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  12472. ** any limit on the number of terms in a compount SELECT.
  12473. */
  12474. #ifndef SQLITE_MAX_COMPOUND_SELECT
  12475. # define SQLITE_MAX_COMPOUND_SELECT 500
  12476. #endif
  12477. /*
  12478. ** The maximum number of opcodes in a VDBE program.
  12479. ** Not currently enforced.
  12480. */
  12481. #ifndef SQLITE_MAX_VDBE_OP
  12482. # define SQLITE_MAX_VDBE_OP 250000000
  12483. #endif
  12484. /*
  12485. ** The maximum number of arguments to an SQL function.
  12486. */
  12487. #ifndef SQLITE_MAX_FUNCTION_ARG
  12488. # define SQLITE_MAX_FUNCTION_ARG 127
  12489. #endif
  12490. /*
  12491. ** The suggested maximum number of in-memory pages to use for
  12492. ** the main database table and for temporary tables.
  12493. **
  12494. ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
  12495. ** which means the cache size is limited to 2048000 bytes of memory.
  12496. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  12497. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  12498. */
  12499. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  12500. # define SQLITE_DEFAULT_CACHE_SIZE -2000
  12501. #endif
  12502. /*
  12503. ** The default number of frames to accumulate in the log file before
  12504. ** checkpointing the database in WAL mode.
  12505. */
  12506. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  12507. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  12508. #endif
  12509. /*
  12510. ** The maximum number of attached databases. This must be between 0
  12511. ** and 125. The upper bound of 125 is because the attached databases are
  12512. ** counted using a signed 8-bit integer which has a maximum value of 127
  12513. ** and we have to allow 2 extra counts for the "main" and "temp" databases.
  12514. */
  12515. #ifndef SQLITE_MAX_ATTACHED
  12516. # define SQLITE_MAX_ATTACHED 10
  12517. #endif
  12518. /*
  12519. ** The maximum value of a ?nnn wildcard that the parser will accept.
  12520. */
  12521. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  12522. # define SQLITE_MAX_VARIABLE_NUMBER 999
  12523. #endif
  12524. /* Maximum page size. The upper bound on this value is 65536. This a limit
  12525. ** imposed by the use of 16-bit offsets within each page.
  12526. **
  12527. ** Earlier versions of SQLite allowed the user to change this value at
  12528. ** compile time. This is no longer permitted, on the grounds that it creates
  12529. ** a library that is technically incompatible with an SQLite library
  12530. ** compiled with a different limit. If a process operating on a database
  12531. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  12532. ** compiled with the default page-size limit will not be able to rollback
  12533. ** the aborted transaction. This could lead to database corruption.
  12534. */
  12535. #ifdef SQLITE_MAX_PAGE_SIZE
  12536. # undef SQLITE_MAX_PAGE_SIZE
  12537. #endif
  12538. #define SQLITE_MAX_PAGE_SIZE 65536
  12539. /*
  12540. ** The default size of a database page.
  12541. */
  12542. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  12543. # define SQLITE_DEFAULT_PAGE_SIZE 4096
  12544. #endif
  12545. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  12546. # undef SQLITE_DEFAULT_PAGE_SIZE
  12547. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  12548. #endif
  12549. /*
  12550. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  12551. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  12552. ** device characteristics (sector-size and atomic write() support),
  12553. ** SQLite may choose a larger value. This constant is the maximum value
  12554. ** SQLite will choose on its own.
  12555. */
  12556. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  12557. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  12558. #endif
  12559. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  12560. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  12561. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  12562. #endif
  12563. /*
  12564. ** Maximum number of pages in one database file.
  12565. **
  12566. ** This is really just the default value for the max_page_count pragma.
  12567. ** This value can be lowered (or raised) at run-time using that the
  12568. ** max_page_count macro.
  12569. */
  12570. #ifndef SQLITE_MAX_PAGE_COUNT
  12571. # define SQLITE_MAX_PAGE_COUNT 1073741823
  12572. #endif
  12573. /*
  12574. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  12575. ** operator.
  12576. */
  12577. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  12578. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  12579. #endif
  12580. /*
  12581. ** Maximum depth of recursion for triggers.
  12582. **
  12583. ** A value of 1 means that a trigger program will not be able to itself
  12584. ** fire any triggers. A value of 0 means that no trigger programs at all
  12585. ** may be executed.
  12586. */
  12587. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  12588. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  12589. #endif
  12590. /************** End of sqliteLimit.h *****************************************/
  12591. /************** Continuing where we left off in sqliteInt.h ******************/
  12592. /* Disable nuisance warnings on Borland compilers */
  12593. #if defined(__BORLANDC__)
  12594. #pragma warn -rch /* unreachable code */
  12595. #pragma warn -ccc /* Condition is always true or false */
  12596. #pragma warn -aus /* Assigned value is never used */
  12597. #pragma warn -csu /* Comparing signed and unsigned */
  12598. #pragma warn -spa /* Suspicious pointer arithmetic */
  12599. #endif
  12600. /*
  12601. ** Include standard header files as necessary
  12602. */
  12603. #ifdef HAVE_STDINT_H
  12604. #include <stdint.h>
  12605. #endif
  12606. #ifdef HAVE_INTTYPES_H
  12607. #include <inttypes.h>
  12608. #endif
  12609. /*
  12610. ** The following macros are used to cast pointers to integers and
  12611. ** integers to pointers. The way you do this varies from one compiler
  12612. ** to the next, so we have developed the following set of #if statements
  12613. ** to generate appropriate macros for a wide range of compilers.
  12614. **
  12615. ** The correct "ANSI" way to do this is to use the intptr_t type.
  12616. ** Unfortunately, that typedef is not available on all compilers, or
  12617. ** if it is available, it requires an #include of specific headers
  12618. ** that vary from one machine to the next.
  12619. **
  12620. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  12621. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  12622. ** So we have to define the macros in different ways depending on the
  12623. ** compiler.
  12624. */
  12625. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  12626. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  12627. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  12628. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  12629. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  12630. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  12631. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  12632. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  12633. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  12634. #else /* Generates a warning - but it always works */
  12635. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  12636. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  12637. #endif
  12638. /*
  12639. ** A macro to hint to the compiler that a function should not be
  12640. ** inlined.
  12641. */
  12642. #if defined(__GNUC__)
  12643. # define SQLITE_NOINLINE __attribute__((noinline))
  12644. #elif defined(_MSC_VER) && _MSC_VER>=1310
  12645. # define SQLITE_NOINLINE __declspec(noinline)
  12646. #else
  12647. # define SQLITE_NOINLINE
  12648. #endif
  12649. /*
  12650. ** Make sure that the compiler intrinsics we desire are enabled when
  12651. ** compiling with an appropriate version of MSVC unless prevented by
  12652. ** the SQLITE_DISABLE_INTRINSIC define.
  12653. */
  12654. #if !defined(SQLITE_DISABLE_INTRINSIC)
  12655. # if defined(_MSC_VER) && _MSC_VER>=1400
  12656. # if !defined(_WIN32_WCE)
  12657. # include <intrin.h>
  12658. # pragma intrinsic(_byteswap_ushort)
  12659. # pragma intrinsic(_byteswap_ulong)
  12660. # pragma intrinsic(_byteswap_uint64)
  12661. # pragma intrinsic(_ReadWriteBarrier)
  12662. # else
  12663. # include <cmnintrin.h>
  12664. # endif
  12665. # endif
  12666. #endif
  12667. /*
  12668. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  12669. ** 0 means mutexes are permanently disable and the library is never
  12670. ** threadsafe. 1 means the library is serialized which is the highest
  12671. ** level of threadsafety. 2 means the library is multithreaded - multiple
  12672. ** threads can use SQLite as long as no two threads try to use the same
  12673. ** database connection at the same time.
  12674. **
  12675. ** Older versions of SQLite used an optional THREADSAFE macro.
  12676. ** We support that for legacy.
  12677. **
  12678. ** To ensure that the correct value of "THREADSAFE" is reported when querying
  12679. ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
  12680. ** logic is partially replicated in ctime.c. If it is updated here, it should
  12681. ** also be updated there.
  12682. */
  12683. #if !defined(SQLITE_THREADSAFE)
  12684. # if defined(THREADSAFE)
  12685. # define SQLITE_THREADSAFE THREADSAFE
  12686. # else
  12687. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  12688. # endif
  12689. #endif
  12690. /*
  12691. ** Powersafe overwrite is on by default. But can be turned off using
  12692. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  12693. */
  12694. #ifndef SQLITE_POWERSAFE_OVERWRITE
  12695. # define SQLITE_POWERSAFE_OVERWRITE 1
  12696. #endif
  12697. /*
  12698. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  12699. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  12700. ** which case memory allocation statistics are disabled by default.
  12701. */
  12702. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  12703. # define SQLITE_DEFAULT_MEMSTATUS 1
  12704. #endif
  12705. /*
  12706. ** Exactly one of the following macros must be defined in order to
  12707. ** specify which memory allocation subsystem to use.
  12708. **
  12709. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  12710. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  12711. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  12712. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  12713. **
  12714. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  12715. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  12716. ** will cause HeapValidate to be called. If heap validation should fail, an
  12717. ** assertion will be triggered.
  12718. **
  12719. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  12720. ** the default.
  12721. */
  12722. #if defined(SQLITE_SYSTEM_MALLOC) \
  12723. + defined(SQLITE_WIN32_MALLOC) \
  12724. + defined(SQLITE_ZERO_MALLOC) \
  12725. + defined(SQLITE_MEMDEBUG)>1
  12726. # error "Two or more of the following compile-time configuration options\
  12727. are defined but at most one is allowed:\
  12728. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  12729. SQLITE_ZERO_MALLOC"
  12730. #endif
  12731. #if defined(SQLITE_SYSTEM_MALLOC) \
  12732. + defined(SQLITE_WIN32_MALLOC) \
  12733. + defined(SQLITE_ZERO_MALLOC) \
  12734. + defined(SQLITE_MEMDEBUG)==0
  12735. # define SQLITE_SYSTEM_MALLOC 1
  12736. #endif
  12737. /*
  12738. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  12739. ** sizes of memory allocations below this value where possible.
  12740. */
  12741. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  12742. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  12743. #endif
  12744. /*
  12745. ** We need to define _XOPEN_SOURCE as follows in order to enable
  12746. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  12747. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  12748. ** it.
  12749. */
  12750. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  12751. # define _XOPEN_SOURCE 600
  12752. #endif
  12753. /*
  12754. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  12755. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  12756. ** make it true by defining or undefining NDEBUG.
  12757. **
  12758. ** Setting NDEBUG makes the code smaller and faster by disabling the
  12759. ** assert() statements in the code. So we want the default action
  12760. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  12761. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  12762. ** feature.
  12763. */
  12764. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  12765. # define NDEBUG 1
  12766. #endif
  12767. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  12768. # undef NDEBUG
  12769. #endif
  12770. /*
  12771. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  12772. */
  12773. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  12774. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  12775. #endif
  12776. /*
  12777. ** The testcase() macro is used to aid in coverage testing. When
  12778. ** doing coverage testing, the condition inside the argument to
  12779. ** testcase() must be evaluated both true and false in order to
  12780. ** get full branch coverage. The testcase() macro is inserted
  12781. ** to help ensure adequate test coverage in places where simple
  12782. ** condition/decision coverage is inadequate. For example, testcase()
  12783. ** can be used to make sure boundary values are tested. For
  12784. ** bitmask tests, testcase() can be used to make sure each bit
  12785. ** is significant and used at least once. On switch statements
  12786. ** where multiple cases go to the same block of code, testcase()
  12787. ** can insure that all cases are evaluated.
  12788. **
  12789. */
  12790. #ifdef SQLITE_COVERAGE_TEST
  12791. SQLITE_PRIVATE void sqlite3Coverage(int);
  12792. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  12793. #else
  12794. # define testcase(X)
  12795. #endif
  12796. /*
  12797. ** The TESTONLY macro is used to enclose variable declarations or
  12798. ** other bits of code that are needed to support the arguments
  12799. ** within testcase() and assert() macros.
  12800. */
  12801. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  12802. # define TESTONLY(X) X
  12803. #else
  12804. # define TESTONLY(X)
  12805. #endif
  12806. /*
  12807. ** Sometimes we need a small amount of code such as a variable initialization
  12808. ** to setup for a later assert() statement. We do not want this code to
  12809. ** appear when assert() is disabled. The following macro is therefore
  12810. ** used to contain that setup code. The "VVA" acronym stands for
  12811. ** "Verification, Validation, and Accreditation". In other words, the
  12812. ** code within VVA_ONLY() will only run during verification processes.
  12813. */
  12814. #ifndef NDEBUG
  12815. # define VVA_ONLY(X) X
  12816. #else
  12817. # define VVA_ONLY(X)
  12818. #endif
  12819. /*
  12820. ** The ALWAYS and NEVER macros surround boolean expressions which
  12821. ** are intended to always be true or false, respectively. Such
  12822. ** expressions could be omitted from the code completely. But they
  12823. ** are included in a few cases in order to enhance the resilience
  12824. ** of SQLite to unexpected behavior - to make the code "self-healing"
  12825. ** or "ductile" rather than being "brittle" and crashing at the first
  12826. ** hint of unplanned behavior.
  12827. **
  12828. ** In other words, ALWAYS and NEVER are added for defensive code.
  12829. **
  12830. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  12831. ** be true and false so that the unreachable code they specify will
  12832. ** not be counted as untested code.
  12833. */
  12834. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  12835. # define ALWAYS(X) (1)
  12836. # define NEVER(X) (0)
  12837. #elif !defined(NDEBUG)
  12838. # define ALWAYS(X) ((X)?1:(assert(0),0))
  12839. # define NEVER(X) ((X)?(assert(0),1):0)
  12840. #else
  12841. # define ALWAYS(X) (X)
  12842. # define NEVER(X) (X)
  12843. #endif
  12844. /*
  12845. ** Some conditionals are optimizations only. In other words, if the
  12846. ** conditionals are replaced with a constant 1 (true) or 0 (false) then
  12847. ** the correct answer is still obtained, though perhaps not as quickly.
  12848. **
  12849. ** The following macros mark these optimizations conditionals.
  12850. */
  12851. #if defined(SQLITE_MUTATION_TEST)
  12852. # define OK_IF_ALWAYS_TRUE(X) (1)
  12853. # define OK_IF_ALWAYS_FALSE(X) (0)
  12854. #else
  12855. # define OK_IF_ALWAYS_TRUE(X) (X)
  12856. # define OK_IF_ALWAYS_FALSE(X) (X)
  12857. #endif
  12858. /*
  12859. ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
  12860. ** defined. We need to defend against those failures when testing with
  12861. ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
  12862. ** during a normal build. The following macro can be used to disable tests
  12863. ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
  12864. */
  12865. #if defined(SQLITE_TEST_REALLOC_STRESS)
  12866. # define ONLY_IF_REALLOC_STRESS(X) (X)
  12867. #elif !defined(NDEBUG)
  12868. # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
  12869. #else
  12870. # define ONLY_IF_REALLOC_STRESS(X) (0)
  12871. #endif
  12872. /*
  12873. ** Declarations used for tracing the operating system interfaces.
  12874. */
  12875. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  12876. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  12877. extern int sqlite3OSTrace;
  12878. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  12879. # define SQLITE_HAVE_OS_TRACE
  12880. #else
  12881. # define OSTRACE(X)
  12882. # undef SQLITE_HAVE_OS_TRACE
  12883. #endif
  12884. /*
  12885. ** Is the sqlite3ErrName() function needed in the build? Currently,
  12886. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  12887. ** OSTRACE is enabled), and by several "test*.c" files (which are
  12888. ** compiled using SQLITE_TEST).
  12889. */
  12890. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  12891. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  12892. # define SQLITE_NEED_ERR_NAME
  12893. #else
  12894. # undef SQLITE_NEED_ERR_NAME
  12895. #endif
  12896. /*
  12897. ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
  12898. */
  12899. #ifdef SQLITE_OMIT_EXPLAIN
  12900. # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
  12901. #endif
  12902. /*
  12903. ** Return true (non-zero) if the input is an integer that is too large
  12904. ** to fit in 32-bits. This macro is used inside of various testcase()
  12905. ** macros to verify that we have tested SQLite for large-file support.
  12906. */
  12907. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  12908. /*
  12909. ** The macro unlikely() is a hint that surrounds a boolean
  12910. ** expression that is usually false. Macro likely() surrounds
  12911. ** a boolean expression that is usually true. These hints could,
  12912. ** in theory, be used by the compiler to generate better code, but
  12913. ** currently they are just comments for human readers.
  12914. */
  12915. #define likely(X) (X)
  12916. #define unlikely(X) (X)
  12917. /************** Include hash.h in the middle of sqliteInt.h ******************/
  12918. /************** Begin file hash.h ********************************************/
  12919. /*
  12920. ** 2001 September 22
  12921. **
  12922. ** The author disclaims copyright to this source code. In place of
  12923. ** a legal notice, here is a blessing:
  12924. **
  12925. ** May you do good and not evil.
  12926. ** May you find forgiveness for yourself and forgive others.
  12927. ** May you share freely, never taking more than you give.
  12928. **
  12929. *************************************************************************
  12930. ** This is the header file for the generic hash-table implementation
  12931. ** used in SQLite.
  12932. */
  12933. #ifndef SQLITE_HASH_H
  12934. #define SQLITE_HASH_H
  12935. /* Forward declarations of structures. */
  12936. typedef struct Hash Hash;
  12937. typedef struct HashElem HashElem;
  12938. /* A complete hash table is an instance of the following structure.
  12939. ** The internals of this structure are intended to be opaque -- client
  12940. ** code should not attempt to access or modify the fields of this structure
  12941. ** directly. Change this structure only by using the routines below.
  12942. ** However, some of the "procedures" and "functions" for modifying and
  12943. ** accessing this structure are really macros, so we can't really make
  12944. ** this structure opaque.
  12945. **
  12946. ** All elements of the hash table are on a single doubly-linked list.
  12947. ** Hash.first points to the head of this list.
  12948. **
  12949. ** There are Hash.htsize buckets. Each bucket points to a spot in
  12950. ** the global doubly-linked list. The contents of the bucket are the
  12951. ** element pointed to plus the next _ht.count-1 elements in the list.
  12952. **
  12953. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  12954. ** by a linear search of the global list. For small tables, the
  12955. ** Hash.ht table is never allocated because if there are few elements
  12956. ** in the table, it is faster to do a linear search than to manage
  12957. ** the hash table.
  12958. */
  12959. struct Hash {
  12960. unsigned int htsize; /* Number of buckets in the hash table */
  12961. unsigned int count; /* Number of entries in this table */
  12962. HashElem *first; /* The first element of the array */
  12963. struct _ht { /* the hash table */
  12964. int count; /* Number of entries with this hash */
  12965. HashElem *chain; /* Pointer to first entry with this hash */
  12966. } *ht;
  12967. };
  12968. /* Each element in the hash table is an instance of the following
  12969. ** structure. All elements are stored on a single doubly-linked list.
  12970. **
  12971. ** Again, this structure is intended to be opaque, but it can't really
  12972. ** be opaque because it is used by macros.
  12973. */
  12974. struct HashElem {
  12975. HashElem *next, *prev; /* Next and previous elements in the table */
  12976. void *data; /* Data associated with this element */
  12977. const char *pKey; /* Key associated with this element */
  12978. };
  12979. /*
  12980. ** Access routines. To delete, insert a NULL pointer.
  12981. */
  12982. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  12983. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  12984. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  12985. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  12986. /*
  12987. ** Macros for looping over all elements of a hash table. The idiom is
  12988. ** like this:
  12989. **
  12990. ** Hash h;
  12991. ** HashElem *p;
  12992. ** ...
  12993. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  12994. ** SomeStructure *pData = sqliteHashData(p);
  12995. ** // do something with pData
  12996. ** }
  12997. */
  12998. #define sqliteHashFirst(H) ((H)->first)
  12999. #define sqliteHashNext(E) ((E)->next)
  13000. #define sqliteHashData(E) ((E)->data)
  13001. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  13002. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  13003. /*
  13004. ** Number of entries in a hash table
  13005. */
  13006. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  13007. #endif /* SQLITE_HASH_H */
  13008. /************** End of hash.h ************************************************/
  13009. /************** Continuing where we left off in sqliteInt.h ******************/
  13010. /************** Include parse.h in the middle of sqliteInt.h *****************/
  13011. /************** Begin file parse.h *******************************************/
  13012. #define TK_SEMI 1
  13013. #define TK_EXPLAIN 2
  13014. #define TK_QUERY 3
  13015. #define TK_PLAN 4
  13016. #define TK_BEGIN 5
  13017. #define TK_TRANSACTION 6
  13018. #define TK_DEFERRED 7
  13019. #define TK_IMMEDIATE 8
  13020. #define TK_EXCLUSIVE 9
  13021. #define TK_COMMIT 10
  13022. #define TK_END 11
  13023. #define TK_ROLLBACK 12
  13024. #define TK_SAVEPOINT 13
  13025. #define TK_RELEASE 14
  13026. #define TK_TO 15
  13027. #define TK_TABLE 16
  13028. #define TK_CREATE 17
  13029. #define TK_IF 18
  13030. #define TK_NOT 19
  13031. #define TK_EXISTS 20
  13032. #define TK_TEMP 21
  13033. #define TK_LP 22
  13034. #define TK_RP 23
  13035. #define TK_AS 24
  13036. #define TK_WITHOUT 25
  13037. #define TK_COMMA 26
  13038. #define TK_ABORT 27
  13039. #define TK_ACTION 28
  13040. #define TK_AFTER 29
  13041. #define TK_ANALYZE 30
  13042. #define TK_ASC 31
  13043. #define TK_ATTACH 32
  13044. #define TK_BEFORE 33
  13045. #define TK_BY 34
  13046. #define TK_CASCADE 35
  13047. #define TK_CAST 36
  13048. #define TK_CONFLICT 37
  13049. #define TK_DATABASE 38
  13050. #define TK_DESC 39
  13051. #define TK_DETACH 40
  13052. #define TK_EACH 41
  13053. #define TK_FAIL 42
  13054. #define TK_OR 43
  13055. #define TK_AND 44
  13056. #define TK_IS 45
  13057. #define TK_MATCH 46
  13058. #define TK_LIKE_KW 47
  13059. #define TK_BETWEEN 48
  13060. #define TK_IN 49
  13061. #define TK_ISNULL 50
  13062. #define TK_NOTNULL 51
  13063. #define TK_NE 52
  13064. #define TK_EQ 53
  13065. #define TK_GT 54
  13066. #define TK_LE 55
  13067. #define TK_LT 56
  13068. #define TK_GE 57
  13069. #define TK_ESCAPE 58
  13070. #define TK_ID 59
  13071. #define TK_COLUMNKW 60
  13072. #define TK_DO 61
  13073. #define TK_FOR 62
  13074. #define TK_IGNORE 63
  13075. #define TK_INITIALLY 64
  13076. #define TK_INSTEAD 65
  13077. #define TK_NO 66
  13078. #define TK_KEY 67
  13079. #define TK_OF 68
  13080. #define TK_OFFSET 69
  13081. #define TK_PRAGMA 70
  13082. #define TK_RAISE 71
  13083. #define TK_RECURSIVE 72
  13084. #define TK_REPLACE 73
  13085. #define TK_RESTRICT 74
  13086. #define TK_ROW 75
  13087. #define TK_ROWS 76
  13088. #define TK_TRIGGER 77
  13089. #define TK_VACUUM 78
  13090. #define TK_VIEW 79
  13091. #define TK_VIRTUAL 80
  13092. #define TK_WITH 81
  13093. #define TK_CURRENT 82
  13094. #define TK_FOLLOWING 83
  13095. #define TK_PARTITION 84
  13096. #define TK_PRECEDING 85
  13097. #define TK_RANGE 86
  13098. #define TK_UNBOUNDED 87
  13099. #define TK_REINDEX 88
  13100. #define TK_RENAME 89
  13101. #define TK_CTIME_KW 90
  13102. #define TK_ANY 91
  13103. #define TK_BITAND 92
  13104. #define TK_BITOR 93
  13105. #define TK_LSHIFT 94
  13106. #define TK_RSHIFT 95
  13107. #define TK_PLUS 96
  13108. #define TK_MINUS 97
  13109. #define TK_STAR 98
  13110. #define TK_SLASH 99
  13111. #define TK_REM 100
  13112. #define TK_CONCAT 101
  13113. #define TK_COLLATE 102
  13114. #define TK_BITNOT 103
  13115. #define TK_ON 104
  13116. #define TK_INDEXED 105
  13117. #define TK_STRING 106
  13118. #define TK_JOIN_KW 107
  13119. #define TK_CONSTRAINT 108
  13120. #define TK_DEFAULT 109
  13121. #define TK_NULL 110
  13122. #define TK_PRIMARY 111
  13123. #define TK_UNIQUE 112
  13124. #define TK_CHECK 113
  13125. #define TK_REFERENCES 114
  13126. #define TK_AUTOINCR 115
  13127. #define TK_INSERT 116
  13128. #define TK_DELETE 117
  13129. #define TK_UPDATE 118
  13130. #define TK_SET 119
  13131. #define TK_DEFERRABLE 120
  13132. #define TK_FOREIGN 121
  13133. #define TK_DROP 122
  13134. #define TK_UNION 123
  13135. #define TK_ALL 124
  13136. #define TK_EXCEPT 125
  13137. #define TK_INTERSECT 126
  13138. #define TK_SELECT 127
  13139. #define TK_VALUES 128
  13140. #define TK_DISTINCT 129
  13141. #define TK_DOT 130
  13142. #define TK_FROM 131
  13143. #define TK_JOIN 132
  13144. #define TK_USING 133
  13145. #define TK_ORDER 134
  13146. #define TK_GROUP 135
  13147. #define TK_HAVING 136
  13148. #define TK_LIMIT 137
  13149. #define TK_WHERE 138
  13150. #define TK_INTO 139
  13151. #define TK_NOTHING 140
  13152. #define TK_FLOAT 141
  13153. #define TK_BLOB 142
  13154. #define TK_INTEGER 143
  13155. #define TK_VARIABLE 144
  13156. #define TK_CASE 145
  13157. #define TK_WHEN 146
  13158. #define TK_THEN 147
  13159. #define TK_ELSE 148
  13160. #define TK_INDEX 149
  13161. #define TK_ALTER 150
  13162. #define TK_ADD 151
  13163. #define TK_WINDOW 152
  13164. #define TK_OVER 153
  13165. #define TK_FILTER 154
  13166. #define TK_TRUEFALSE 155
  13167. #define TK_ISNOT 156
  13168. #define TK_FUNCTION 157
  13169. #define TK_COLUMN 158
  13170. #define TK_AGG_FUNCTION 159
  13171. #define TK_AGG_COLUMN 160
  13172. #define TK_UMINUS 161
  13173. #define TK_UPLUS 162
  13174. #define TK_TRUTH 163
  13175. #define TK_REGISTER 164
  13176. #define TK_VECTOR 165
  13177. #define TK_SELECT_COLUMN 166
  13178. #define TK_IF_NULL_ROW 167
  13179. #define TK_ASTERISK 168
  13180. #define TK_SPAN 169
  13181. #define TK_END_OF_FILE 170
  13182. #define TK_UNCLOSED_STRING 171
  13183. #define TK_SPACE 172
  13184. #define TK_ILLEGAL 173
  13185. /* The token codes above must all fit in 8 bits */
  13186. #define TKFLG_MASK 0xff
  13187. /* Flags that can be added to a token code when it is not
  13188. ** being stored in a u8: */
  13189. #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
  13190. /************** End of parse.h ***********************************************/
  13191. /************** Continuing where we left off in sqliteInt.h ******************/
  13192. #include <stdio.h>
  13193. #include <stdlib.h>
  13194. #include <string.h>
  13195. #include <assert.h>
  13196. #include <stddef.h>
  13197. /*
  13198. ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
  13199. ** This allows better measurements of where memcpy() is used when running
  13200. ** cachegrind. But this macro version of memcpy() is very slow so it
  13201. ** should not be used in production. This is a performance measurement
  13202. ** hack only.
  13203. */
  13204. #ifdef SQLITE_INLINE_MEMCPY
  13205. # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
  13206. int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
  13207. #endif
  13208. /*
  13209. ** If compiling for a processor that lacks floating point support,
  13210. ** substitute integer for floating-point
  13211. */
  13212. #ifdef SQLITE_OMIT_FLOATING_POINT
  13213. # define double sqlite_int64
  13214. # define float sqlite_int64
  13215. # define LONGDOUBLE_TYPE sqlite_int64
  13216. # ifndef SQLITE_BIG_DBL
  13217. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  13218. # endif
  13219. # define SQLITE_OMIT_DATETIME_FUNCS 1
  13220. # define SQLITE_OMIT_TRACE 1
  13221. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  13222. # undef SQLITE_HAVE_ISNAN
  13223. #endif
  13224. #ifndef SQLITE_BIG_DBL
  13225. # define SQLITE_BIG_DBL (1e99)
  13226. #endif
  13227. /*
  13228. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  13229. ** afterward. Having this macro allows us to cause the C compiler
  13230. ** to omit code used by TEMP tables without messy #ifndef statements.
  13231. */
  13232. #ifdef SQLITE_OMIT_TEMPDB
  13233. #define OMIT_TEMPDB 1
  13234. #else
  13235. #define OMIT_TEMPDB 0
  13236. #endif
  13237. /*
  13238. ** The "file format" number is an integer that is incremented whenever
  13239. ** the VDBE-level file format changes. The following macros define the
  13240. ** the default file format for new databases and the maximum file format
  13241. ** that the library can read.
  13242. */
  13243. #define SQLITE_MAX_FILE_FORMAT 4
  13244. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  13245. # define SQLITE_DEFAULT_FILE_FORMAT 4
  13246. #endif
  13247. /*
  13248. ** Determine whether triggers are recursive by default. This can be
  13249. ** changed at run-time using a pragma.
  13250. */
  13251. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  13252. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  13253. #endif
  13254. /*
  13255. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  13256. ** on the command-line
  13257. */
  13258. #ifndef SQLITE_TEMP_STORE
  13259. # define SQLITE_TEMP_STORE 1
  13260. #endif
  13261. /*
  13262. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  13263. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  13264. ** to zero.
  13265. */
  13266. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  13267. # undef SQLITE_MAX_WORKER_THREADS
  13268. # define SQLITE_MAX_WORKER_THREADS 0
  13269. #endif
  13270. #ifndef SQLITE_MAX_WORKER_THREADS
  13271. # define SQLITE_MAX_WORKER_THREADS 8
  13272. #endif
  13273. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  13274. # define SQLITE_DEFAULT_WORKER_THREADS 0
  13275. #endif
  13276. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  13277. # undef SQLITE_MAX_WORKER_THREADS
  13278. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  13279. #endif
  13280. /*
  13281. ** The default initial allocation for the pagecache when using separate
  13282. ** pagecaches for each database connection. A positive number is the
  13283. ** number of pages. A negative number N translations means that a buffer
  13284. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  13285. **
  13286. ** The default value of "20" was choosen to minimize the run-time of the
  13287. ** speedtest1 test program with options: --shrink-memory --reprepare
  13288. */
  13289. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  13290. # define SQLITE_DEFAULT_PCACHE_INITSZ 20
  13291. #endif
  13292. /*
  13293. ** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
  13294. */
  13295. #ifndef SQLITE_DEFAULT_SORTERREF_SIZE
  13296. # define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
  13297. #endif
  13298. /*
  13299. ** The compile-time options SQLITE_MMAP_READWRITE and
  13300. ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
  13301. ** You must choose one or the other (or neither) but not both.
  13302. */
  13303. #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  13304. #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  13305. #endif
  13306. /*
  13307. ** GCC does not define the offsetof() macro so we'll have to do it
  13308. ** ourselves.
  13309. */
  13310. #ifndef offsetof
  13311. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  13312. #endif
  13313. /*
  13314. ** Macros to compute minimum and maximum of two numbers.
  13315. */
  13316. #ifndef MIN
  13317. # define MIN(A,B) ((A)<(B)?(A):(B))
  13318. #endif
  13319. #ifndef MAX
  13320. # define MAX(A,B) ((A)>(B)?(A):(B))
  13321. #endif
  13322. /*
  13323. ** Swap two objects of type TYPE.
  13324. */
  13325. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  13326. /*
  13327. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  13328. ** not, there are still machines out there that use EBCDIC.)
  13329. */
  13330. #if 'A' == '\301'
  13331. # define SQLITE_EBCDIC 1
  13332. #else
  13333. # define SQLITE_ASCII 1
  13334. #endif
  13335. /*
  13336. ** Integers of known sizes. These typedefs might change for architectures
  13337. ** where the sizes very. Preprocessor macros are available so that the
  13338. ** types can be conveniently redefined at compile-type. Like this:
  13339. **
  13340. ** cc '-DUINTPTR_TYPE=long long int' ...
  13341. */
  13342. #ifndef UINT32_TYPE
  13343. # ifdef HAVE_UINT32_T
  13344. # define UINT32_TYPE uint32_t
  13345. # else
  13346. # define UINT32_TYPE unsigned int
  13347. # endif
  13348. #endif
  13349. #ifndef UINT16_TYPE
  13350. # ifdef HAVE_UINT16_T
  13351. # define UINT16_TYPE uint16_t
  13352. # else
  13353. # define UINT16_TYPE unsigned short int
  13354. # endif
  13355. #endif
  13356. #ifndef INT16_TYPE
  13357. # ifdef HAVE_INT16_T
  13358. # define INT16_TYPE int16_t
  13359. # else
  13360. # define INT16_TYPE short int
  13361. # endif
  13362. #endif
  13363. #ifndef UINT8_TYPE
  13364. # ifdef HAVE_UINT8_T
  13365. # define UINT8_TYPE uint8_t
  13366. # else
  13367. # define UINT8_TYPE unsigned char
  13368. # endif
  13369. #endif
  13370. #ifndef INT8_TYPE
  13371. # ifdef HAVE_INT8_T
  13372. # define INT8_TYPE int8_t
  13373. # else
  13374. # define INT8_TYPE signed char
  13375. # endif
  13376. #endif
  13377. #ifndef LONGDOUBLE_TYPE
  13378. # define LONGDOUBLE_TYPE long double
  13379. #endif
  13380. typedef sqlite_int64 i64; /* 8-byte signed integer */
  13381. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  13382. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  13383. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  13384. typedef INT16_TYPE i16; /* 2-byte signed integer */
  13385. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  13386. typedef INT8_TYPE i8; /* 1-byte signed integer */
  13387. /*
  13388. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  13389. ** that can be stored in a u32 without loss of data. The value
  13390. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  13391. ** have to specify the value in the less intuitive manner shown:
  13392. */
  13393. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  13394. /*
  13395. ** The datatype used to store estimates of the number of rows in a
  13396. ** table or index. This is an unsigned integer type. For 99.9% of
  13397. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  13398. ** can be used at compile-time if desired.
  13399. */
  13400. #ifdef SQLITE_64BIT_STATS
  13401. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  13402. #else
  13403. typedef u32 tRowcnt; /* 32-bit is the default */
  13404. #endif
  13405. /*
  13406. ** Estimated quantities used for query planning are stored as 16-bit
  13407. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  13408. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  13409. ** But the allowed values are "grainy". Not every value is representable.
  13410. ** For example, quantities 16 and 17 are both represented by a LogEst
  13411. ** of 40. However, since LogEst quantities are suppose to be estimates,
  13412. ** not exact values, this imprecision is not a problem.
  13413. **
  13414. ** "LogEst" is short for "Logarithmic Estimate".
  13415. **
  13416. ** Examples:
  13417. ** 1 -> 0 20 -> 43 10000 -> 132
  13418. ** 2 -> 10 25 -> 46 25000 -> 146
  13419. ** 3 -> 16 100 -> 66 1000000 -> 199
  13420. ** 4 -> 20 1000 -> 99 1048576 -> 200
  13421. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  13422. **
  13423. ** The LogEst can be negative to indicate fractional values.
  13424. ** Examples:
  13425. **
  13426. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  13427. */
  13428. typedef INT16_TYPE LogEst;
  13429. /*
  13430. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  13431. */
  13432. #ifndef SQLITE_PTRSIZE
  13433. # if defined(__SIZEOF_POINTER__)
  13434. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  13435. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  13436. defined(_M_ARM) || defined(__arm__) || defined(__x86) || \
  13437. (defined(__TOS_AIX__) && !defined(__64BIT__))
  13438. # define SQLITE_PTRSIZE 4
  13439. # else
  13440. # define SQLITE_PTRSIZE 8
  13441. # endif
  13442. #endif
  13443. /* The uptr type is an unsigned integer large enough to hold a pointer
  13444. */
  13445. #if defined(HAVE_STDINT_H)
  13446. typedef uintptr_t uptr;
  13447. #elif SQLITE_PTRSIZE==4
  13448. typedef u32 uptr;
  13449. #else
  13450. typedef u64 uptr;
  13451. #endif
  13452. /*
  13453. ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  13454. ** something between S (inclusive) and E (exclusive).
  13455. **
  13456. ** In other words, S is a buffer and E is a pointer to the first byte after
  13457. ** the end of buffer S. This macro returns true if P points to something
  13458. ** contained within the buffer S.
  13459. */
  13460. #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
  13461. /*
  13462. ** Macros to determine whether the machine is big or little endian,
  13463. ** and whether or not that determination is run-time or compile-time.
  13464. **
  13465. ** For best performance, an attempt is made to guess at the byte-order
  13466. ** using C-preprocessor macros. If that is unsuccessful, or if
  13467. ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
  13468. ** at run-time.
  13469. */
  13470. #ifndef SQLITE_BYTEORDER
  13471. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  13472. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  13473. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  13474. defined(__arm__) || defined(_M_ARM64)
  13475. # define SQLITE_BYTEORDER 1234
  13476. # elif defined(sparc) || defined(__ppc__)
  13477. # define SQLITE_BYTEORDER 4321
  13478. # else
  13479. # define SQLITE_BYTEORDER 0
  13480. # endif
  13481. #endif
  13482. #if SQLITE_BYTEORDER==4321
  13483. # define SQLITE_BIGENDIAN 1
  13484. # define SQLITE_LITTLEENDIAN 0
  13485. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  13486. #elif SQLITE_BYTEORDER==1234
  13487. # define SQLITE_BIGENDIAN 0
  13488. # define SQLITE_LITTLEENDIAN 1
  13489. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  13490. #else
  13491. # ifdef SQLITE_AMALGAMATION
  13492. const int sqlite3one = 1;
  13493. # else
  13494. extern const int sqlite3one;
  13495. # endif
  13496. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  13497. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  13498. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  13499. #endif
  13500. /*
  13501. ** Constants for the largest and smallest possible 64-bit signed integers.
  13502. ** These macros are designed to work correctly on both 32-bit and 64-bit
  13503. ** compilers.
  13504. */
  13505. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  13506. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  13507. /*
  13508. ** Round up a number to the next larger multiple of 8. This is used
  13509. ** to force 8-byte alignment on 64-bit architectures.
  13510. */
  13511. #define ROUND8(x) (((x)+7)&~7)
  13512. /*
  13513. ** Round down to the nearest multiple of 8
  13514. */
  13515. #define ROUNDDOWN8(x) ((x)&~7)
  13516. /*
  13517. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  13518. ** macro is used only within assert() to verify that the code gets
  13519. ** all alignment restrictions correct.
  13520. **
  13521. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  13522. ** underlying malloc() implementation might return us 4-byte aligned
  13523. ** pointers. In that case, only verify 4-byte alignment.
  13524. */
  13525. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  13526. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  13527. #else
  13528. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  13529. #endif
  13530. /*
  13531. ** Disable MMAP on platforms where it is known to not work
  13532. */
  13533. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  13534. # undef SQLITE_MAX_MMAP_SIZE
  13535. # define SQLITE_MAX_MMAP_SIZE 0
  13536. #endif
  13537. /*
  13538. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  13539. */
  13540. #ifdef __APPLE__
  13541. # include <TargetConditionals.h>
  13542. #endif
  13543. #ifndef SQLITE_MAX_MMAP_SIZE
  13544. # if defined(__linux__) \
  13545. || defined(_WIN32) \
  13546. || (defined(__APPLE__) && defined(__MACH__)) \
  13547. || defined(__sun) \
  13548. || defined(__FreeBSD__) \
  13549. || defined(__DragonFly__)
  13550. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  13551. # else
  13552. # define SQLITE_MAX_MMAP_SIZE 0
  13553. # endif
  13554. #endif
  13555. /*
  13556. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  13557. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  13558. ** not exceed the maximum mmap size.
  13559. */
  13560. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  13561. # define SQLITE_DEFAULT_MMAP_SIZE 0
  13562. #endif
  13563. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  13564. # undef SQLITE_DEFAULT_MMAP_SIZE
  13565. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  13566. #endif
  13567. /*
  13568. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  13569. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  13570. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  13571. */
  13572. #ifdef SQLITE_ENABLE_STAT4
  13573. # undef SQLITE_ENABLE_STAT3
  13574. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  13575. #elif SQLITE_ENABLE_STAT3
  13576. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  13577. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  13578. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  13579. #endif
  13580. /*
  13581. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  13582. ** the Select query generator tracing logic is turned on.
  13583. */
  13584. #if defined(SQLITE_ENABLE_SELECTTRACE)
  13585. # define SELECTTRACE_ENABLED 1
  13586. #else
  13587. # define SELECTTRACE_ENABLED 0
  13588. #endif
  13589. /*
  13590. ** An instance of the following structure is used to store the busy-handler
  13591. ** callback for a given sqlite handle.
  13592. **
  13593. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  13594. ** callback for the database handle. Each pager opened via the sqlite
  13595. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  13596. ** callback is currently invoked only from within pager.c.
  13597. */
  13598. typedef struct BusyHandler BusyHandler;
  13599. struct BusyHandler {
  13600. int (*xBusyHandler)(void *,int); /* The busy callback */
  13601. void *pBusyArg; /* First arg to busy callback */
  13602. int nBusy; /* Incremented with each busy call */
  13603. u8 bExtraFileArg; /* Include sqlite3_file as callback arg */
  13604. };
  13605. /*
  13606. ** Name of the master database table. The master database table
  13607. ** is a special table that holds the names and attributes of all
  13608. ** user tables and indices.
  13609. */
  13610. #define MASTER_NAME "sqlite_master"
  13611. #define TEMP_MASTER_NAME "sqlite_temp_master"
  13612. /*
  13613. ** The root-page of the master database table.
  13614. */
  13615. #define MASTER_ROOT 1
  13616. /*
  13617. ** The name of the schema table.
  13618. */
  13619. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  13620. /*
  13621. ** A convenience macro that returns the number of elements in
  13622. ** an array.
  13623. */
  13624. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  13625. /*
  13626. ** Determine if the argument is a power of two
  13627. */
  13628. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  13629. /*
  13630. ** The following value as a destructor means to use sqlite3DbFree().
  13631. ** The sqlite3DbFree() routine requires two parameters instead of the
  13632. ** one parameter that destructors normally want. So we have to introduce
  13633. ** this magic value that the code knows to handle differently. Any
  13634. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  13635. ** and SQLITE_TRANSIENT.
  13636. */
  13637. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  13638. /*
  13639. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  13640. ** not support Writable Static Data (WSD) such as global and static variables.
  13641. ** All variables must either be on the stack or dynamically allocated from
  13642. ** the heap. When WSD is unsupported, the variable declarations scattered
  13643. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  13644. ** macro is used for this purpose. And instead of referencing the variable
  13645. ** directly, we use its constant as a key to lookup the run-time allocated
  13646. ** buffer that holds real variable. The constant is also the initializer
  13647. ** for the run-time allocated buffer.
  13648. **
  13649. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  13650. ** macros become no-ops and have zero performance impact.
  13651. */
  13652. #ifdef SQLITE_OMIT_WSD
  13653. #define SQLITE_WSD const
  13654. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  13655. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  13656. SQLITE_API int sqlite3_wsd_init(int N, int J);
  13657. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  13658. #else
  13659. #define SQLITE_WSD
  13660. #define GLOBAL(t,v) v
  13661. #define sqlite3GlobalConfig sqlite3Config
  13662. #endif
  13663. /*
  13664. ** The following macros are used to suppress compiler warnings and to
  13665. ** make it clear to human readers when a function parameter is deliberately
  13666. ** left unused within the body of a function. This usually happens when
  13667. ** a function is called via a function pointer. For example the
  13668. ** implementation of an SQL aggregate step callback may not use the
  13669. ** parameter indicating the number of arguments passed to the aggregate,
  13670. ** if it knows that this is enforced elsewhere.
  13671. **
  13672. ** When a function parameter is not used at all within the body of a function,
  13673. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  13674. ** However, these macros may also be used to suppress warnings related to
  13675. ** parameters that may or may not be used depending on compilation options.
  13676. ** For example those parameters only used in assert() statements. In these
  13677. ** cases the parameters are named as per the usual conventions.
  13678. */
  13679. #define UNUSED_PARAMETER(x) (void)(x)
  13680. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  13681. /*
  13682. ** Forward references to structures
  13683. */
  13684. typedef struct AggInfo AggInfo;
  13685. typedef struct AuthContext AuthContext;
  13686. typedef struct AutoincInfo AutoincInfo;
  13687. typedef struct Bitvec Bitvec;
  13688. typedef struct CollSeq CollSeq;
  13689. typedef struct Column Column;
  13690. typedef struct Db Db;
  13691. typedef struct Schema Schema;
  13692. typedef struct Expr Expr;
  13693. typedef struct ExprList ExprList;
  13694. typedef struct FKey FKey;
  13695. typedef struct FuncDestructor FuncDestructor;
  13696. typedef struct FuncDef FuncDef;
  13697. typedef struct FuncDefHash FuncDefHash;
  13698. typedef struct IdList IdList;
  13699. typedef struct Index Index;
  13700. typedef struct IndexSample IndexSample;
  13701. typedef struct KeyClass KeyClass;
  13702. typedef struct KeyInfo KeyInfo;
  13703. typedef struct Lookaside Lookaside;
  13704. typedef struct LookasideSlot LookasideSlot;
  13705. typedef struct Module Module;
  13706. typedef struct NameContext NameContext;
  13707. typedef struct Parse Parse;
  13708. typedef struct PreUpdate PreUpdate;
  13709. typedef struct PrintfArguments PrintfArguments;
  13710. typedef struct RenameToken RenameToken;
  13711. typedef struct RowSet RowSet;
  13712. typedef struct Savepoint Savepoint;
  13713. typedef struct Select Select;
  13714. typedef struct SQLiteThread SQLiteThread;
  13715. typedef struct SelectDest SelectDest;
  13716. typedef struct SrcList SrcList;
  13717. typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
  13718. typedef struct Table Table;
  13719. typedef struct TableLock TableLock;
  13720. typedef struct Token Token;
  13721. typedef struct TreeView TreeView;
  13722. typedef struct Trigger Trigger;
  13723. typedef struct TriggerPrg TriggerPrg;
  13724. typedef struct TriggerStep TriggerStep;
  13725. typedef struct UnpackedRecord UnpackedRecord;
  13726. typedef struct Upsert Upsert;
  13727. typedef struct VTable VTable;
  13728. typedef struct VtabCtx VtabCtx;
  13729. typedef struct Walker Walker;
  13730. typedef struct WhereInfo WhereInfo;
  13731. typedef struct Window Window;
  13732. typedef struct With With;
  13733. /*
  13734. ** The bitmask datatype defined below is used for various optimizations.
  13735. **
  13736. ** Changing this from a 64-bit to a 32-bit type limits the number of
  13737. ** tables in a join to 32 instead of 64. But it also reduces the size
  13738. ** of the library by 738 bytes on ix86.
  13739. */
  13740. #ifdef SQLITE_BITMASK_TYPE
  13741. typedef SQLITE_BITMASK_TYPE Bitmask;
  13742. #else
  13743. typedef u64 Bitmask;
  13744. #endif
  13745. /*
  13746. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  13747. */
  13748. #define BMS ((int)(sizeof(Bitmask)*8))
  13749. /*
  13750. ** A bit in a Bitmask
  13751. */
  13752. #define MASKBIT(n) (((Bitmask)1)<<(n))
  13753. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  13754. #define ALLBITS ((Bitmask)-1)
  13755. /* A VList object records a mapping between parameters/variables/wildcards
  13756. ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
  13757. ** variable number associated with that parameter. See the format description
  13758. ** on the sqlite3VListAdd() routine for more information. A VList is really
  13759. ** just an array of integers.
  13760. */
  13761. typedef int VList;
  13762. /*
  13763. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  13764. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  13765. ** pointer types (i.e. FuncDef) defined above.
  13766. */
  13767. /************** Include btree.h in the middle of sqliteInt.h *****************/
  13768. /************** Begin file btree.h *******************************************/
  13769. /*
  13770. ** 2001 September 15
  13771. **
  13772. ** The author disclaims copyright to this source code. In place of
  13773. ** a legal notice, here is a blessing:
  13774. **
  13775. ** May you do good and not evil.
  13776. ** May you find forgiveness for yourself and forgive others.
  13777. ** May you share freely, never taking more than you give.
  13778. **
  13779. *************************************************************************
  13780. ** This header file defines the interface that the sqlite B-Tree file
  13781. ** subsystem. See comments in the source code for a detailed description
  13782. ** of what each interface routine does.
  13783. */
  13784. #ifndef SQLITE_BTREE_H
  13785. #define SQLITE_BTREE_H
  13786. /* TODO: This definition is just included so other modules compile. It
  13787. ** needs to be revisited.
  13788. */
  13789. #define SQLITE_N_BTREE_META 16
  13790. /*
  13791. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  13792. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  13793. */
  13794. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  13795. #define SQLITE_DEFAULT_AUTOVACUUM 0
  13796. #endif
  13797. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  13798. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  13799. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  13800. /*
  13801. ** Forward declarations of structure
  13802. */
  13803. typedef struct Btree Btree;
  13804. typedef struct BtCursor BtCursor;
  13805. typedef struct BtShared BtShared;
  13806. typedef struct BtreePayload BtreePayload;
  13807. SQLITE_PRIVATE int sqlite3BtreeOpen(
  13808. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  13809. const char *zFilename, /* Name of database file to open */
  13810. sqlite3 *db, /* Associated database connection */
  13811. Btree **ppBtree, /* Return open Btree* here */
  13812. int flags, /* Flags */
  13813. int vfsFlags /* Flags passed through to VFS open */
  13814. );
  13815. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  13816. ** following values.
  13817. **
  13818. ** NOTE: These values must match the corresponding PAGER_ values in
  13819. ** pager.h.
  13820. */
  13821. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  13822. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  13823. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  13824. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  13825. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  13826. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  13827. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
  13828. #if SQLITE_MAX_MMAP_SIZE>0
  13829. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  13830. #endif
  13831. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  13832. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  13833. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  13834. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  13835. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  13836. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  13837. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  13838. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  13839. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  13840. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  13841. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);
  13842. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  13843. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  13844. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  13845. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  13846. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  13847. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  13848. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  13849. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  13850. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  13851. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  13852. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  13853. #ifndef SQLITE_OMIT_SHARED_CACHE
  13854. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  13855. #endif
  13856. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  13857. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  13858. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  13859. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  13860. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  13861. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  13862. ** of the flags shown below.
  13863. **
  13864. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  13865. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  13866. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  13867. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  13868. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  13869. ** indices.)
  13870. */
  13871. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  13872. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  13873. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  13874. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  13875. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  13876. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  13877. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  13878. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  13879. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  13880. /*
  13881. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  13882. ** should be one of the following values. The integer values are assigned
  13883. ** to constants so that the offset of the corresponding field in an
  13884. ** SQLite database header may be found using the following formula:
  13885. **
  13886. ** offset = 36 + (idx * 4)
  13887. **
  13888. ** For example, the free-page-count field is located at byte offset 36 of
  13889. ** the database file header. The incr-vacuum-flag field is located at
  13890. ** byte offset 64 (== 36+4*7).
  13891. **
  13892. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  13893. ** It is a read-only number computed by the pager. But we merge it with
  13894. ** the header value access routines since its access pattern is the same.
  13895. ** Call it a "virtual meta value".
  13896. */
  13897. #define BTREE_FREE_PAGE_COUNT 0
  13898. #define BTREE_SCHEMA_VERSION 1
  13899. #define BTREE_FILE_FORMAT 2
  13900. #define BTREE_DEFAULT_CACHE_SIZE 3
  13901. #define BTREE_LARGEST_ROOT_PAGE 4
  13902. #define BTREE_TEXT_ENCODING 5
  13903. #define BTREE_USER_VERSION 6
  13904. #define BTREE_INCR_VACUUM 7
  13905. #define BTREE_APPLICATION_ID 8
  13906. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  13907. /*
  13908. ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
  13909. ** interface.
  13910. **
  13911. ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
  13912. **
  13913. ** The first argument is an Expr* (which is guaranteed to be constant for
  13914. ** the lifetime of the cursor) that defines constraints on which rows
  13915. ** might be fetched with this cursor. The Expr* tree may contain
  13916. ** TK_REGISTER nodes that refer to values stored in the array of registers
  13917. ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
  13918. ** then the value of the node is the value in Mem[pExpr.iTable]. Any
  13919. ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
  13920. ** column of the b-tree of the cursor. The Expr tree will not contain
  13921. ** any function calls nor subqueries nor references to b-trees other than
  13922. ** the cursor being hinted.
  13923. **
  13924. ** The design of the _RANGE hint is aid b-tree implementations that try
  13925. ** to prefetch content from remote machines - to provide those
  13926. ** implementations with limits on what needs to be prefetched and thereby
  13927. ** reduce network bandwidth.
  13928. **
  13929. ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
  13930. ** standard SQLite. The other hints are provided for extentions that use
  13931. ** the SQLite parser and code generator but substitute their own storage
  13932. ** engine.
  13933. */
  13934. #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
  13935. /*
  13936. ** Values that may be OR'd together to form the argument to the
  13937. ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
  13938. **
  13939. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  13940. ** to be filled with content that is already in sorted order.
  13941. **
  13942. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  13943. ** OP_SeekLE opcodes for a range search, but where the range of entries
  13944. ** selected will all have the same key. In other words, the cursor will
  13945. ** be used only for equality key searches.
  13946. **
  13947. */
  13948. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  13949. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  13950. /*
  13951. ** Flags passed as the third argument to sqlite3BtreeCursor().
  13952. **
  13953. ** For read-only cursors the wrFlag argument is always zero. For read-write
  13954. ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
  13955. ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
  13956. ** only be used by SQLite for the following:
  13957. **
  13958. ** * to seek to and then delete specific entries, and/or
  13959. **
  13960. ** * to read values that will be used to create keys that other
  13961. ** BTREE_FORDELETE cursors will seek to and delete.
  13962. **
  13963. ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
  13964. ** by this, the native b-tree engine of SQLite, but it is available to
  13965. ** alternative storage engines that might be substituted in place of this
  13966. ** b-tree system. For alternative storage engines in which a delete of
  13967. ** the main table row automatically deletes corresponding index rows,
  13968. ** the FORDELETE flag hint allows those alternative storage engines to
  13969. ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
  13970. ** and DELETE operations as no-ops, and any READ operation against a
  13971. ** FORDELETE cursor may return a null row: 0x01 0x00.
  13972. */
  13973. #define BTREE_WRCSR 0x00000004 /* read-write cursor */
  13974. #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
  13975. SQLITE_PRIVATE int sqlite3BtreeCursor(
  13976. Btree*, /* BTree containing table to open */
  13977. int iTable, /* Index of root page */
  13978. int wrFlag, /* 1 for writing. 0 for read-only */
  13979. struct KeyInfo*, /* First argument to compare function */
  13980. BtCursor *pCursor /* Space to write cursor structure */
  13981. );
  13982. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
  13983. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  13984. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  13985. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
  13986. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  13987. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
  13988. #endif
  13989. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  13990. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  13991. BtCursor*,
  13992. UnpackedRecord *pUnKey,
  13993. i64 intKey,
  13994. int bias,
  13995. int *pRes
  13996. );
  13997. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  13998. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  13999. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
  14000. /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
  14001. #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
  14002. #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
  14003. #define BTREE_APPEND 0x08 /* Insert is likely an append */
  14004. /* An instance of the BtreePayload object describes the content of a single
  14005. ** entry in either an index or table btree.
  14006. **
  14007. ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
  14008. ** an arbitrary key and no data. These btrees have pKey,nKey set to the
  14009. ** key and the pData,nData,nZero fields are uninitialized. The aMem,nMem
  14010. ** fields give an array of Mem objects that are a decomposition of the key.
  14011. ** The nMem field might be zero, indicating that no decomposition is available.
  14012. **
  14013. ** Table btrees (used for rowid tables) contain an integer rowid used as
  14014. ** the key and passed in the nKey field. The pKey field is zero.
  14015. ** pData,nData hold the content of the new entry. nZero extra zero bytes
  14016. ** are appended to the end of the content when constructing the entry.
  14017. ** The aMem,nMem fields are uninitialized for table btrees.
  14018. **
  14019. ** Field usage summary:
  14020. **
  14021. ** Table BTrees Index Btrees
  14022. **
  14023. ** pKey always NULL encoded key
  14024. ** nKey the ROWID length of pKey
  14025. ** pData data not used
  14026. ** aMem not used decomposed key value
  14027. ** nMem not used entries in aMem
  14028. ** nData length of pData not used
  14029. ** nZero extra zeros after pData not used
  14030. **
  14031. ** This object is used to pass information into sqlite3BtreeInsert(). The
  14032. ** same information used to be passed as five separate parameters. But placing
  14033. ** the information into this object helps to keep the interface more
  14034. ** organized and understandable, and it also helps the resulting code to
  14035. ** run a little faster by using fewer registers for parameter passing.
  14036. */
  14037. struct BtreePayload {
  14038. const void *pKey; /* Key content for indexes. NULL for tables */
  14039. sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
  14040. const void *pData; /* Data for tables. */
  14041. sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
  14042. u16 nMem; /* Number of aMem[] value. Might be zero */
  14043. int nData; /* Size of pData. 0 if none. */
  14044. int nZero; /* Extra zero data appended after pData,nData */
  14045. };
  14046. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
  14047. int flags, int seekResult);
  14048. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  14049. #ifndef SQLITE_OMIT_WINDOWFUNC
  14050. SQLITE_PRIVATE void sqlite3BtreeSkipNext(BtCursor*);
  14051. #endif
  14052. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  14053. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
  14054. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  14055. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
  14056. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
  14057. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  14058. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
  14059. #endif
  14060. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
  14061. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
  14062. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
  14063. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  14064. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  14065. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
  14066. #ifndef SQLITE_OMIT_INCRBLOB
  14067. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
  14068. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  14069. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  14070. #endif
  14071. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  14072. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  14073. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  14074. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  14075. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  14076. #ifndef NDEBUG
  14077. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  14078. #endif
  14079. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
  14080. #ifndef SQLITE_OMIT_BTREECOUNT
  14081. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  14082. #endif
  14083. #ifdef SQLITE_TEST
  14084. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  14085. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  14086. #endif
  14087. #ifndef SQLITE_OMIT_WAL
  14088. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  14089. #endif
  14090. /*
  14091. ** If we are not using shared cache, then there is no need to
  14092. ** use mutexes to access the BtShared structures. So make the
  14093. ** Enter and Leave procedures no-ops.
  14094. */
  14095. #ifndef SQLITE_OMIT_SHARED_CACHE
  14096. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  14097. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  14098. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  14099. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  14100. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
  14101. #else
  14102. # define sqlite3BtreeEnter(X)
  14103. # define sqlite3BtreeEnterAll(X)
  14104. # define sqlite3BtreeSharable(X) 0
  14105. # define sqlite3BtreeEnterCursor(X)
  14106. # define sqlite3BtreeConnectionCount(X) 1
  14107. #endif
  14108. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  14109. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  14110. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  14111. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  14112. #ifndef NDEBUG
  14113. /* These routines are used inside assert() statements only. */
  14114. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  14115. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  14116. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  14117. #endif
  14118. #else
  14119. # define sqlite3BtreeLeave(X)
  14120. # define sqlite3BtreeLeaveCursor(X)
  14121. # define sqlite3BtreeLeaveAll(X)
  14122. # define sqlite3BtreeHoldsMutex(X) 1
  14123. # define sqlite3BtreeHoldsAllMutexes(X) 1
  14124. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  14125. #endif
  14126. #endif /* SQLITE_BTREE_H */
  14127. /************** End of btree.h ***********************************************/
  14128. /************** Continuing where we left off in sqliteInt.h ******************/
  14129. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  14130. /************** Begin file vdbe.h ********************************************/
  14131. /*
  14132. ** 2001 September 15
  14133. **
  14134. ** The author disclaims copyright to this source code. In place of
  14135. ** a legal notice, here is a blessing:
  14136. **
  14137. ** May you do good and not evil.
  14138. ** May you find forgiveness for yourself and forgive others.
  14139. ** May you share freely, never taking more than you give.
  14140. **
  14141. *************************************************************************
  14142. ** Header file for the Virtual DataBase Engine (VDBE)
  14143. **
  14144. ** This header defines the interface to the virtual database engine
  14145. ** or VDBE. The VDBE implements an abstract machine that runs a
  14146. ** simple program to access and modify the underlying database.
  14147. */
  14148. #ifndef SQLITE_VDBE_H
  14149. #define SQLITE_VDBE_H
  14150. /* #include <stdio.h> */
  14151. /*
  14152. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  14153. ** in the source file sqliteVdbe.c are allowed to see the insides
  14154. ** of this structure.
  14155. */
  14156. typedef struct Vdbe Vdbe;
  14157. /*
  14158. ** The names of the following types declared in vdbeInt.h are required
  14159. ** for the VdbeOp definition.
  14160. */
  14161. typedef struct sqlite3_value Mem;
  14162. typedef struct SubProgram SubProgram;
  14163. /*
  14164. ** A single instruction of the virtual machine has an opcode
  14165. ** and as many as three operands. The instruction is recorded
  14166. ** as an instance of the following structure:
  14167. */
  14168. struct VdbeOp {
  14169. u8 opcode; /* What operation to perform */
  14170. signed char p4type; /* One of the P4_xxx constants for p4 */
  14171. u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
  14172. int p1; /* First operand */
  14173. int p2; /* Second parameter (often the jump destination) */
  14174. int p3; /* The third parameter */
  14175. union p4union { /* fourth parameter */
  14176. int i; /* Integer value if p4type==P4_INT32 */
  14177. void *p; /* Generic pointer */
  14178. char *z; /* Pointer to data for string (char array) types */
  14179. i64 *pI64; /* Used when p4type is P4_INT64 */
  14180. double *pReal; /* Used when p4type is P4_REAL */
  14181. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  14182. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  14183. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  14184. Mem *pMem; /* Used when p4type is P4_MEM */
  14185. VTable *pVtab; /* Used when p4type is P4_VTAB */
  14186. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  14187. int *ai; /* Used when p4type is P4_INTARRAY */
  14188. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  14189. Table *pTab; /* Used when p4type is P4_TABLE */
  14190. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  14191. Expr *pExpr; /* Used when p4type is P4_EXPR */
  14192. #endif
  14193. int (*xAdvance)(BtCursor *, int);
  14194. } p4;
  14195. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  14196. char *zComment; /* Comment to improve readability */
  14197. #endif
  14198. #ifdef VDBE_PROFILE
  14199. u32 cnt; /* Number of times this instruction was executed */
  14200. u64 cycles; /* Total time spent executing this instruction */
  14201. #endif
  14202. #ifdef SQLITE_VDBE_COVERAGE
  14203. u32 iSrcLine; /* Source-code line that generated this opcode
  14204. ** with flags in the upper 8 bits */
  14205. #endif
  14206. };
  14207. typedef struct VdbeOp VdbeOp;
  14208. /*
  14209. ** A sub-routine used to implement a trigger program.
  14210. */
  14211. struct SubProgram {
  14212. VdbeOp *aOp; /* Array of opcodes for sub-program */
  14213. int nOp; /* Elements in aOp[] */
  14214. int nMem; /* Number of memory cells required */
  14215. int nCsr; /* Number of cursors required */
  14216. u8 *aOnce; /* Array of OP_Once flags */
  14217. void *token; /* id that may be used to recursive triggers */
  14218. SubProgram *pNext; /* Next sub-program already visited */
  14219. };
  14220. /*
  14221. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  14222. ** it takes up less space.
  14223. */
  14224. struct VdbeOpList {
  14225. u8 opcode; /* What operation to perform */
  14226. signed char p1; /* First operand */
  14227. signed char p2; /* Second parameter (often the jump destination) */
  14228. signed char p3; /* Third parameter */
  14229. };
  14230. typedef struct VdbeOpList VdbeOpList;
  14231. /*
  14232. ** Allowed values of VdbeOp.p4type
  14233. */
  14234. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  14235. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  14236. #define P4_STATIC (-1) /* Pointer to a static string */
  14237. #define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
  14238. #define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
  14239. #define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
  14240. #define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  14241. #define P4_TABLE (-6) /* P4 is a pointer to a Table structure */
  14242. /* Above do not own any resources. Must free those below */
  14243. #define P4_FREE_IF_LE (-7)
  14244. #define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */
  14245. #define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */
  14246. #define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */
  14247. #define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */
  14248. #define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */
  14249. #define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */
  14250. #define P4_REAL (-13) /* P4 is a 64-bit floating point value */
  14251. #define P4_INT64 (-14) /* P4 is a 64-bit signed integer */
  14252. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  14253. #define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
  14254. #define P4_DYNBLOB (-17) /* Pointer to memory from sqliteMalloc() */
  14255. /* Error message codes for OP_Halt */
  14256. #define P5_ConstraintNotNull 1
  14257. #define P5_ConstraintUnique 2
  14258. #define P5_ConstraintCheck 3
  14259. #define P5_ConstraintFK 4
  14260. /*
  14261. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  14262. ** number of columns of data returned by the statement.
  14263. */
  14264. #define COLNAME_NAME 0
  14265. #define COLNAME_DECLTYPE 1
  14266. #define COLNAME_DATABASE 2
  14267. #define COLNAME_TABLE 3
  14268. #define COLNAME_COLUMN 4
  14269. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  14270. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  14271. #else
  14272. # ifdef SQLITE_OMIT_DECLTYPE
  14273. # define COLNAME_N 1 /* Store only the name */
  14274. # else
  14275. # define COLNAME_N 2 /* Store the name and decltype */
  14276. # endif
  14277. #endif
  14278. /*
  14279. ** The following macro converts a relative address in the p2 field
  14280. ** of a VdbeOp structure into a negative number so that
  14281. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  14282. ** the macro again restores the address.
  14283. */
  14284. #define ADDR(X) (-1-(X))
  14285. /*
  14286. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  14287. ** header file that defines a number for each opcode used by the VDBE.
  14288. */
  14289. /************** Include opcodes.h in the middle of vdbe.h ********************/
  14290. /************** Begin file opcodes.h *****************************************/
  14291. /* Automatically generated. Do not edit */
  14292. /* See the tool/mkopcodeh.tcl script for details */
  14293. #define OP_Savepoint 0
  14294. #define OP_AutoCommit 1
  14295. #define OP_Transaction 2
  14296. #define OP_SorterNext 3 /* jump */
  14297. #define OP_Prev 4 /* jump */
  14298. #define OP_Next 5 /* jump */
  14299. #define OP_Checkpoint 6
  14300. #define OP_JournalMode 7
  14301. #define OP_Vacuum 8
  14302. #define OP_VFilter 9 /* jump, synopsis: iplan=r[P3] zplan='P4' */
  14303. #define OP_VUpdate 10 /* synopsis: data=r[P3@P2] */
  14304. #define OP_Goto 11 /* jump */
  14305. #define OP_Gosub 12 /* jump */
  14306. #define OP_InitCoroutine 13 /* jump */
  14307. #define OP_Yield 14 /* jump */
  14308. #define OP_MustBeInt 15 /* jump */
  14309. #define OP_Jump 16 /* jump */
  14310. #define OP_Once 17 /* jump */
  14311. #define OP_If 18 /* jump */
  14312. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  14313. #define OP_IfNot 20 /* jump */
  14314. #define OP_IfNullRow 21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
  14315. #define OP_SeekLT 22 /* jump, synopsis: key=r[P3@P4] */
  14316. #define OP_SeekLE 23 /* jump, synopsis: key=r[P3@P4] */
  14317. #define OP_SeekGE 24 /* jump, synopsis: key=r[P3@P4] */
  14318. #define OP_SeekGT 25 /* jump, synopsis: key=r[P3@P4] */
  14319. #define OP_IfNoHope 26 /* jump, synopsis: key=r[P3@P4] */
  14320. #define OP_NoConflict 27 /* jump, synopsis: key=r[P3@P4] */
  14321. #define OP_NotFound 28 /* jump, synopsis: key=r[P3@P4] */
  14322. #define OP_Found 29 /* jump, synopsis: key=r[P3@P4] */
  14323. #define OP_SeekRowid 30 /* jump, synopsis: intkey=r[P3] */
  14324. #define OP_NotExists 31 /* jump, synopsis: intkey=r[P3] */
  14325. #define OP_Last 32 /* jump */
  14326. #define OP_IfSmaller 33 /* jump */
  14327. #define OP_SorterSort 34 /* jump */
  14328. #define OP_Sort 35 /* jump */
  14329. #define OP_Rewind 36 /* jump */
  14330. #define OP_IdxLE 37 /* jump, synopsis: key=r[P3@P4] */
  14331. #define OP_IdxGT 38 /* jump, synopsis: key=r[P3@P4] */
  14332. #define OP_IdxLT 39 /* jump, synopsis: key=r[P3@P4] */
  14333. #define OP_IdxGE 40 /* jump, synopsis: key=r[P3@P4] */
  14334. #define OP_RowSetRead 41 /* jump, synopsis: r[P3]=rowset(P1) */
  14335. #define OP_RowSetTest 42 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
  14336. #define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  14337. #define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  14338. #define OP_Program 45 /* jump */
  14339. #define OP_FkIfZero 46 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
  14340. #define OP_IfPos 47 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  14341. #define OP_IfNotZero 48 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
  14342. #define OP_DecrJumpZero 49 /* jump, synopsis: if (--r[P1])==0 goto P2 */
  14343. #define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  14344. #define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  14345. #define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
  14346. #define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
  14347. #define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
  14348. #define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
  14349. #define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
  14350. #define OP_Ge 57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
  14351. #define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */
  14352. #define OP_IncrVacuum 59 /* jump */
  14353. #define OP_VNext 60 /* jump */
  14354. #define OP_Init 61 /* jump, synopsis: Start at P2 */
  14355. #define OP_PureFunc0 62
  14356. #define OP_Function0 63 /* synopsis: r[P3]=func(r[P2@P5]) */
  14357. #define OP_PureFunc 64
  14358. #define OP_Function 65 /* synopsis: r[P3]=func(r[P2@P5]) */
  14359. #define OP_Return 66
  14360. #define OP_EndCoroutine 67
  14361. #define OP_HaltIfNull 68 /* synopsis: if r[P3]=null halt */
  14362. #define OP_Halt 69
  14363. #define OP_Integer 70 /* synopsis: r[P2]=P1 */
  14364. #define OP_Int64 71 /* synopsis: r[P2]=P4 */
  14365. #define OP_String 72 /* synopsis: r[P2]='P4' (len=P1) */
  14366. #define OP_Null 73 /* synopsis: r[P2..P3]=NULL */
  14367. #define OP_SoftNull 74 /* synopsis: r[P1]=NULL */
  14368. #define OP_Blob 75 /* synopsis: r[P2]=P4 (len=P1) */
  14369. #define OP_Variable 76 /* synopsis: r[P2]=parameter(P1,P4) */
  14370. #define OP_Move 77 /* synopsis: r[P2@P3]=r[P1@P3] */
  14371. #define OP_Copy 78 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  14372. #define OP_SCopy 79 /* synopsis: r[P2]=r[P1] */
  14373. #define OP_IntCopy 80 /* synopsis: r[P2]=r[P1] */
  14374. #define OP_ResultRow 81 /* synopsis: output=r[P1@P2] */
  14375. #define OP_CollSeq 82
  14376. #define OP_AddImm 83 /* synopsis: r[P1]=r[P1]+P2 */
  14377. #define OP_RealAffinity 84
  14378. #define OP_Cast 85 /* synopsis: affinity(r[P1]) */
  14379. #define OP_Permutation 86
  14380. #define OP_Compare 87 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  14381. #define OP_IsTrue 88 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
  14382. #define OP_Offset 89 /* synopsis: r[P3] = sqlite_offset(P1) */
  14383. #define OP_Column 90 /* synopsis: r[P3]=PX */
  14384. #define OP_Affinity 91 /* synopsis: affinity(r[P1@P2]) */
  14385. #define OP_BitAnd 92 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  14386. #define OP_BitOr 93 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  14387. #define OP_ShiftLeft 94 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  14388. #define OP_ShiftRight 95 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  14389. #define OP_Add 96 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  14390. #define OP_Subtract 97 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  14391. #define OP_Multiply 98 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  14392. #define OP_Divide 99 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  14393. #define OP_Remainder 100 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  14394. #define OP_Concat 101 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  14395. #define OP_MakeRecord 102 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  14396. #define OP_BitNot 103 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
  14397. #define OP_Count 104 /* synopsis: r[P2]=count() */
  14398. #define OP_ReadCookie 105
  14399. #define OP_String8 106 /* same as TK_STRING, synopsis: r[P2]='P4' */
  14400. #define OP_SetCookie 107
  14401. #define OP_ReopenIdx 108 /* synopsis: root=P2 iDb=P3 */
  14402. #define OP_OpenRead 109 /* synopsis: root=P2 iDb=P3 */
  14403. #define OP_OpenWrite 110 /* synopsis: root=P2 iDb=P3 */
  14404. #define OP_OpenDup 111
  14405. #define OP_OpenAutoindex 112 /* synopsis: nColumn=P2 */
  14406. #define OP_OpenEphemeral 113 /* synopsis: nColumn=P2 */
  14407. #define OP_SorterOpen 114
  14408. #define OP_SequenceTest 115 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  14409. #define OP_OpenPseudo 116 /* synopsis: P3 columns in r[P2] */
  14410. #define OP_Close 117
  14411. #define OP_ColumnsUsed 118
  14412. #define OP_SeekHit 119 /* synopsis: seekHit=P2 */
  14413. #define OP_Sequence 120 /* synopsis: r[P2]=cursor[P1].ctr++ */
  14414. #define OP_NewRowid 121 /* synopsis: r[P2]=rowid */
  14415. #define OP_Insert 122 /* synopsis: intkey=r[P3] data=r[P2] */
  14416. #define OP_InsertInt 123 /* synopsis: intkey=P3 data=r[P2] */
  14417. #define OP_Delete 124
  14418. #define OP_ResetCount 125
  14419. #define OP_SorterCompare 126 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  14420. #define OP_SorterData 127 /* synopsis: r[P2]=data */
  14421. #define OP_RowData 128 /* synopsis: r[P2]=data */
  14422. #define OP_Rowid 129 /* synopsis: r[P2]=rowid */
  14423. #define OP_NullRow 130
  14424. #define OP_SeekEnd 131
  14425. #define OP_SorterInsert 132 /* synopsis: key=r[P2] */
  14426. #define OP_IdxInsert 133 /* synopsis: key=r[P2] */
  14427. #define OP_IdxDelete 134 /* synopsis: key=r[P2@P3] */
  14428. #define OP_DeferredSeek 135 /* synopsis: Move P3 to P1.rowid if needed */
  14429. #define OP_IdxRowid 136 /* synopsis: r[P2]=rowid */
  14430. #define OP_Destroy 137
  14431. #define OP_Clear 138
  14432. #define OP_ResetSorter 139
  14433. #define OP_CreateBtree 140 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
  14434. #define OP_Real 141 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  14435. #define OP_SqlExec 142
  14436. #define OP_ParseSchema 143
  14437. #define OP_LoadAnalysis 144
  14438. #define OP_DropTable 145
  14439. #define OP_DropIndex 146
  14440. #define OP_DropTrigger 147
  14441. #define OP_IntegrityCk 148
  14442. #define OP_RowSetAdd 149 /* synopsis: rowset(P1)=r[P2] */
  14443. #define OP_Param 150
  14444. #define OP_FkCounter 151 /* synopsis: fkctr[P1]+=P2 */
  14445. #define OP_MemMax 152 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  14446. #define OP_OffsetLimit 153 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
  14447. #define OP_AggInverse 154 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
  14448. #define OP_AggStep 155 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  14449. #define OP_AggStep1 156 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  14450. #define OP_AggValue 157 /* synopsis: r[P3]=value N=P2 */
  14451. #define OP_AggFinal 158 /* synopsis: accum=r[P1] N=P2 */
  14452. #define OP_Expire 159
  14453. #define OP_TableLock 160 /* synopsis: iDb=P1 root=P2 write=P3 */
  14454. #define OP_VBegin 161
  14455. #define OP_VCreate 162
  14456. #define OP_VDestroy 163
  14457. #define OP_VOpen 164
  14458. #define OP_VColumn 165 /* synopsis: r[P3]=vcolumn(P2) */
  14459. #define OP_VRename 166
  14460. #define OP_Pagecount 167
  14461. #define OP_MaxPgcnt 168
  14462. #define OP_Trace 169
  14463. #define OP_CursorHint 170
  14464. #define OP_Noop 171
  14465. #define OP_Explain 172
  14466. #define OP_Abortable 173
  14467. /* Properties such as "out2" or "jump" that are specified in
  14468. ** comments following the "case" for each opcode in the vdbe.c
  14469. ** are encoded into bitvectors as follows:
  14470. */
  14471. #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
  14472. #define OPFLG_IN1 0x02 /* in1: P1 is an input */
  14473. #define OPFLG_IN2 0x04 /* in2: P2 is an input */
  14474. #define OPFLG_IN3 0x08 /* in3: P3 is an input */
  14475. #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
  14476. #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
  14477. #define OPFLG_INITIALIZER {\
  14478. /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\
  14479. /* 8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\
  14480. /* 16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x01, 0x09, 0x09,\
  14481. /* 24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
  14482. /* 32 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
  14483. /* 40 */ 0x01, 0x23, 0x0b, 0x26, 0x26, 0x01, 0x01, 0x03,\
  14484. /* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
  14485. /* 56 */ 0x0b, 0x0b, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,\
  14486. /* 64 */ 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10,\
  14487. /* 72 */ 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10,\
  14488. /* 80 */ 0x10, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\
  14489. /* 88 */ 0x12, 0x20, 0x00, 0x00, 0x26, 0x26, 0x26, 0x26,\
  14490. /* 96 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x12,\
  14491. /* 104 */ 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14492. /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14493. /* 120 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14494. /* 128 */ 0x00, 0x10, 0x00, 0x00, 0x04, 0x04, 0x00, 0x00,\
  14495. /* 136 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
  14496. /* 144 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x00,\
  14497. /* 152 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14498. /* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
  14499. /* 168 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,}
  14500. /* The sqlite3P2Values() routine is able to run faster if it knows
  14501. ** the value of the largest JUMP opcode. The smaller the maximum
  14502. ** JUMP opcode the better, so the mkopcodeh.tcl script that
  14503. ** generated this include file strives to group all JUMP opcodes
  14504. ** together near the beginning of the list.
  14505. */
  14506. #define SQLITE_MX_JUMP_OPCODE 61 /* Maximum JUMP opcode */
  14507. /************** End of opcodes.h *********************************************/
  14508. /************** Continuing where we left off in vdbe.h ***********************/
  14509. /*
  14510. ** Additional non-public SQLITE_PREPARE_* flags
  14511. */
  14512. #define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
  14513. #define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */
  14514. /*
  14515. ** Prototypes for the VDBE interface. See comments on the implementation
  14516. ** for a description of what each of these routines does.
  14517. */
  14518. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  14519. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  14520. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  14521. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  14522. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  14523. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  14524. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  14525. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  14526. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  14527. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  14528. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  14529. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
  14530. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  14531. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
  14532. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
  14533. #else
  14534. # define sqlite3VdbeVerifyNoMallocRequired(A,B)
  14535. # define sqlite3VdbeVerifyNoResultRow(A)
  14536. #endif
  14537. #if defined(SQLITE_DEBUG)
  14538. SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
  14539. #else
  14540. # define sqlite3VdbeVerifyAbortable(A,B)
  14541. #endif
  14542. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
  14543. #ifndef SQLITE_OMIT_EXPLAIN
  14544. SQLITE_PRIVATE void sqlite3VdbeExplain(Parse*,u8,const char*,...);
  14545. SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse*);
  14546. SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse*);
  14547. # define ExplainQueryPlan(P) sqlite3VdbeExplain P
  14548. # define ExplainQueryPlanPop(P) sqlite3VdbeExplainPop(P)
  14549. # define ExplainQueryPlanParent(P) sqlite3VdbeExplainParent(P)
  14550. #else
  14551. # define ExplainQueryPlan(P)
  14552. # define ExplainQueryPlanPop(P)
  14553. # define ExplainQueryPlanParent(P) 0
  14554. #endif
  14555. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  14556. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
  14557. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  14558. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  14559. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  14560. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
  14561. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  14562. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  14563. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  14564. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  14565. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
  14566. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  14567. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  14568. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  14569. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  14570. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  14571. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
  14572. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  14573. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  14574. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  14575. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  14576. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  14577. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  14578. #ifdef SQLITE_DEBUG
  14579. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  14580. #endif
  14581. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  14582. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  14583. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  14584. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  14585. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  14586. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  14587. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  14588. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
  14589. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
  14590. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  14591. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  14592. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  14593. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  14594. #ifndef SQLITE_OMIT_TRACE
  14595. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  14596. #endif
  14597. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  14598. SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);
  14599. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  14600. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  14601. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  14602. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
  14603. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  14604. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  14605. #ifndef SQLITE_OMIT_TRIGGER
  14606. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  14607. #endif
  14608. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
  14609. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  14610. ** each VDBE opcode.
  14611. **
  14612. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  14613. ** comments in VDBE programs that show key decision points in the code
  14614. ** generator.
  14615. */
  14616. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  14617. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  14618. # define VdbeComment(X) sqlite3VdbeComment X
  14619. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  14620. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  14621. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  14622. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  14623. # else
  14624. # define VdbeModuleComment(X)
  14625. # endif
  14626. #else
  14627. # define VdbeComment(X)
  14628. # define VdbeNoopComment(X)
  14629. # define VdbeModuleComment(X)
  14630. #endif
  14631. /*
  14632. ** The VdbeCoverage macros are used to set a coverage testing point
  14633. ** for VDBE branch instructions. The coverage testing points are line
  14634. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  14635. ** only works with an amalagmation build. That's ok since a VDBE branch
  14636. ** coverage build designed for testing the test suite only. No application
  14637. ** should ever ship with VDBE branch coverage measuring turned on.
  14638. **
  14639. ** VdbeCoverage(v) // Mark the previously coded instruction
  14640. ** // as a branch
  14641. **
  14642. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  14643. **
  14644. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  14645. **
  14646. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  14647. **
  14648. ** VdbeCoverageNeverNull(v) // Previous three-way branch is only
  14649. ** // taken on the first two ways. The
  14650. ** // NULL option is not possible
  14651. **
  14652. ** VdbeCoverageEqNe(v) // Previous OP_Jump is only interested
  14653. ** // in distingishing equal and not-equal.
  14654. **
  14655. ** Every VDBE branch operation must be tagged with one of the macros above.
  14656. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  14657. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  14658. ** routine in vdbe.c, alerting the developer to the missed tag.
  14659. **
  14660. ** During testing, the test application will invoke
  14661. ** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback
  14662. ** routine that is invoked as each bytecode branch is taken. The callback
  14663. ** contains the sqlite3.c source line number ov the VdbeCoverage macro and
  14664. ** flags to indicate whether or not the branch was taken. The test application
  14665. ** is responsible for keeping track of this and reporting byte-code branches
  14666. ** that are never taken.
  14667. **
  14668. ** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the
  14669. ** vdbe.c source file for additional information.
  14670. */
  14671. #ifdef SQLITE_VDBE_COVERAGE
  14672. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  14673. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  14674. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  14675. # define VdbeCoverageAlwaysTaken(v) \
  14676. sqlite3VdbeSetLineNumber(v,__LINE__|0x5000000);
  14677. # define VdbeCoverageNeverTaken(v) \
  14678. sqlite3VdbeSetLineNumber(v,__LINE__|0x6000000);
  14679. # define VdbeCoverageNeverNull(v) \
  14680. sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
  14681. # define VdbeCoverageNeverNullIf(v,x) \
  14682. if(x)sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
  14683. # define VdbeCoverageEqNe(v) \
  14684. sqlite3VdbeSetLineNumber(v,__LINE__|0x8000000);
  14685. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  14686. #else
  14687. # define VdbeCoverage(v)
  14688. # define VdbeCoverageIf(v,x)
  14689. # define VdbeCoverageAlwaysTaken(v)
  14690. # define VdbeCoverageNeverTaken(v)
  14691. # define VdbeCoverageNeverNull(v)
  14692. # define VdbeCoverageNeverNullIf(v,x)
  14693. # define VdbeCoverageEqNe(v)
  14694. # define VDBE_OFFSET_LINENO(x) 0
  14695. #endif
  14696. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  14697. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  14698. #else
  14699. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  14700. #endif
  14701. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  14702. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
  14703. #endif
  14704. #endif /* SQLITE_VDBE_H */
  14705. /************** End of vdbe.h ************************************************/
  14706. /************** Continuing where we left off in sqliteInt.h ******************/
  14707. /************** Include pager.h in the middle of sqliteInt.h *****************/
  14708. /************** Begin file pager.h *******************************************/
  14709. /*
  14710. ** 2001 September 15
  14711. **
  14712. ** The author disclaims copyright to this source code. In place of
  14713. ** a legal notice, here is a blessing:
  14714. **
  14715. ** May you do good and not evil.
  14716. ** May you find forgiveness for yourself and forgive others.
  14717. ** May you share freely, never taking more than you give.
  14718. **
  14719. *************************************************************************
  14720. ** This header file defines the interface that the sqlite page cache
  14721. ** subsystem. The page cache subsystem reads and writes a file a page
  14722. ** at a time and provides a journal for rollback.
  14723. */
  14724. #ifndef SQLITE_PAGER_H
  14725. #define SQLITE_PAGER_H
  14726. /*
  14727. ** Default maximum size for persistent journal files. A negative
  14728. ** value means no limit. This value may be overridden using the
  14729. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  14730. */
  14731. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  14732. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  14733. #endif
  14734. /*
  14735. ** The type used to represent a page number. The first page in a file
  14736. ** is called page 1. 0 is used to represent "not a page".
  14737. */
  14738. typedef u32 Pgno;
  14739. /*
  14740. ** Each open file is managed by a separate instance of the "Pager" structure.
  14741. */
  14742. typedef struct Pager Pager;
  14743. /*
  14744. ** Handle type for pages.
  14745. */
  14746. typedef struct PgHdr DbPage;
  14747. /*
  14748. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  14749. ** reserved for working around a windows/posix incompatibility). It is
  14750. ** used in the journal to signify that the remainder of the journal file
  14751. ** is devoted to storing a master journal name - there are no more pages to
  14752. ** roll back. See comments for function writeMasterJournal() in pager.c
  14753. ** for details.
  14754. */
  14755. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  14756. /*
  14757. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  14758. **
  14759. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  14760. */
  14761. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  14762. #define PAGER_MEMORY 0x0002 /* In-memory database */
  14763. /*
  14764. ** Valid values for the second argument to sqlite3PagerLockingMode().
  14765. */
  14766. #define PAGER_LOCKINGMODE_QUERY -1
  14767. #define PAGER_LOCKINGMODE_NORMAL 0
  14768. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  14769. /*
  14770. ** Numeric constants that encode the journalmode.
  14771. **
  14772. ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
  14773. ** are exposed in the API via the "PRAGMA journal_mode" command and
  14774. ** therefore cannot be changed without a compatibility break.
  14775. */
  14776. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  14777. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  14778. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  14779. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  14780. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  14781. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  14782. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  14783. /*
  14784. ** Flags that make up the mask passed to sqlite3PagerGet().
  14785. */
  14786. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  14787. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  14788. /*
  14789. ** Flags for sqlite3PagerSetFlags()
  14790. **
  14791. ** Value constraints (enforced via assert()):
  14792. ** PAGER_FULLFSYNC == SQLITE_FullFSync
  14793. ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
  14794. ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
  14795. */
  14796. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  14797. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  14798. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  14799. #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
  14800. #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
  14801. #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
  14802. #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
  14803. #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
  14804. #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
  14805. /*
  14806. ** The remainder of this file contains the declarations of the functions
  14807. ** that make up the Pager sub-system API. See source code comments for
  14808. ** a detailed description of each routine.
  14809. */
  14810. /* Open and close a Pager connection. */
  14811. SQLITE_PRIVATE int sqlite3PagerOpen(
  14812. sqlite3_vfs*,
  14813. Pager **ppPager,
  14814. const char*,
  14815. int,
  14816. int,
  14817. int,
  14818. void(*)(DbPage*)
  14819. );
  14820. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
  14821. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  14822. /* Functions used to configure a Pager object. */
  14823. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
  14824. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  14825. #ifdef SQLITE_HAS_CODEC
  14826. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
  14827. #endif
  14828. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  14829. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  14830. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
  14831. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  14832. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  14833. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  14834. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  14835. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  14836. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  14837. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  14838. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  14839. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  14840. SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
  14841. /* Functions used to obtain and release page references. */
  14842. SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  14843. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  14844. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  14845. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  14846. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  14847. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
  14848. /* Operations on page references. */
  14849. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  14850. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  14851. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  14852. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  14853. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  14854. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  14855. /* Functions used to manage pager transactions and savepoints. */
  14856. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  14857. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  14858. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  14859. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  14860. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  14861. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  14862. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  14863. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  14864. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  14865. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  14866. #ifndef SQLITE_OMIT_WAL
  14867. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
  14868. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  14869. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  14870. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  14871. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
  14872. # ifdef SQLITE_ENABLE_SNAPSHOT
  14873. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
  14874. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
  14875. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
  14876. SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
  14877. SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager);
  14878. # endif
  14879. #endif
  14880. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  14881. SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
  14882. #endif
  14883. #ifdef SQLITE_ENABLE_ZIPVFS
  14884. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  14885. #endif
  14886. /* Functions used to query pager state and configuration. */
  14887. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  14888. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  14889. #ifdef SQLITE_DEBUG
  14890. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  14891. #endif
  14892. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  14893. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  14894. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
  14895. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  14896. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
  14897. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  14898. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  14899. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  14900. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  14901. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
  14902. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  14903. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  14904. SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager);
  14905. #else
  14906. # define sqlite3PagerResetLockTimeout(X)
  14907. #endif
  14908. /* Functions used to truncate the database file. */
  14909. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  14910. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  14911. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  14912. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  14913. #endif
  14914. /* Functions to support testing and debugging. */
  14915. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  14916. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  14917. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  14918. #endif
  14919. #ifdef SQLITE_TEST
  14920. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  14921. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  14922. void disable_simulated_io_errors(void);
  14923. void enable_simulated_io_errors(void);
  14924. #else
  14925. # define disable_simulated_io_errors()
  14926. # define enable_simulated_io_errors()
  14927. #endif
  14928. #endif /* SQLITE_PAGER_H */
  14929. /************** End of pager.h ***********************************************/
  14930. /************** Continuing where we left off in sqliteInt.h ******************/
  14931. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  14932. /************** Begin file pcache.h ******************************************/
  14933. /*
  14934. ** 2008 August 05
  14935. **
  14936. ** The author disclaims copyright to this source code. In place of
  14937. ** a legal notice, here is a blessing:
  14938. **
  14939. ** May you do good and not evil.
  14940. ** May you find forgiveness for yourself and forgive others.
  14941. ** May you share freely, never taking more than you give.
  14942. **
  14943. *************************************************************************
  14944. ** This header file defines the interface that the sqlite page cache
  14945. ** subsystem.
  14946. */
  14947. #ifndef _PCACHE_H_
  14948. typedef struct PgHdr PgHdr;
  14949. typedef struct PCache PCache;
  14950. /*
  14951. ** Every page in the cache is controlled by an instance of the following
  14952. ** structure.
  14953. */
  14954. struct PgHdr {
  14955. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  14956. void *pData; /* Page data */
  14957. void *pExtra; /* Extra content */
  14958. PCache *pCache; /* PRIVATE: Cache that owns this page */
  14959. PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
  14960. Pager *pPager; /* The pager this page is part of */
  14961. Pgno pgno; /* Page number for this page */
  14962. #ifdef SQLITE_CHECK_PAGES
  14963. u32 pageHash; /* Hash of page content */
  14964. #endif
  14965. u16 flags; /* PGHDR flags defined below */
  14966. /**********************************************************************
  14967. ** Elements above, except pCache, are public. All that follow are
  14968. ** private to pcache.c and should not be accessed by other modules.
  14969. ** pCache is grouped with the public elements for efficiency.
  14970. */
  14971. i16 nRef; /* Number of users of this page */
  14972. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  14973. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  14974. /* NB: pDirtyNext and pDirtyPrev are undefined if the
  14975. ** PgHdr object is not dirty */
  14976. };
  14977. /* Bit values for PgHdr.flags */
  14978. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  14979. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  14980. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  14981. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  14982. ** writing this page to the database */
  14983. #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
  14984. #define PGHDR_MMAP 0x020 /* This is an mmap page object */
  14985. #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
  14986. /* Initialize and shutdown the page cache subsystem */
  14987. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  14988. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  14989. /* Page cache buffer management:
  14990. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  14991. */
  14992. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  14993. /* Create a new pager cache.
  14994. ** Under memory stress, invoke xStress to try to make pages clean.
  14995. ** Only clean and unpinned pages can be reclaimed.
  14996. */
  14997. SQLITE_PRIVATE int sqlite3PcacheOpen(
  14998. int szPage, /* Size of every page */
  14999. int szExtra, /* Extra space associated with each page */
  15000. int bPurgeable, /* True if pages are on backing store */
  15001. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  15002. void *pStress, /* Argument to xStress */
  15003. PCache *pToInit /* Preallocated space for the PCache */
  15004. );
  15005. /* Modify the page-size after the cache has been created. */
  15006. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  15007. /* Return the size in bytes of a PCache object. Used to preallocate
  15008. ** storage space.
  15009. */
  15010. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  15011. /* One release per successful fetch. Page is pinned until released.
  15012. ** Reference counted.
  15013. */
  15014. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  15015. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  15016. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  15017. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  15018. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  15019. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  15020. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  15021. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  15022. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
  15023. /* Change a page number. Used by incr-vacuum. */
  15024. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  15025. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  15026. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  15027. /* Get a list of all dirty pages in the cache, sorted by page number */
  15028. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  15029. /* Reset and close the cache object */
  15030. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  15031. /* Clear flags from pages of the page cache */
  15032. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  15033. /* Discard the contents of the cache */
  15034. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  15035. /* Return the total number of outstanding page references */
  15036. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  15037. /* Increment the reference count of an existing page */
  15038. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  15039. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  15040. /* Return the total number of pages stored in the cache */
  15041. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  15042. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  15043. /* Iterate through all dirty pages currently stored in the cache. This
  15044. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  15045. ** library is built.
  15046. */
  15047. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  15048. #endif
  15049. #if defined(SQLITE_DEBUG)
  15050. /* Check invariants on a PgHdr object */
  15051. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
  15052. #endif
  15053. /* Set and get the suggested cache-size for the specified pager-cache.
  15054. **
  15055. ** If no global maximum is configured, then the system attempts to limit
  15056. ** the total number of pages cached by purgeable pager-caches to the sum
  15057. ** of the suggested cache-sizes.
  15058. */
  15059. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  15060. #ifdef SQLITE_TEST
  15061. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  15062. #endif
  15063. /* Set or get the suggested spill-size for the specified pager-cache.
  15064. **
  15065. ** The spill-size is the minimum number of pages in cache before the cache
  15066. ** will attempt to spill dirty pages by calling xStress.
  15067. */
  15068. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
  15069. /* Free up as much memory as possible from the page cache */
  15070. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  15071. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  15072. /* Try to return memory used by the pcache module to the main memory heap */
  15073. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  15074. #endif
  15075. #ifdef SQLITE_TEST
  15076. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  15077. #endif
  15078. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  15079. /* Return the header size */
  15080. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  15081. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  15082. /* Number of dirty pages as a percentage of the configured cache size */
  15083. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
  15084. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  15085. SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
  15086. #endif
  15087. #endif /* _PCACHE_H_ */
  15088. /************** End of pcache.h **********************************************/
  15089. /************** Continuing where we left off in sqliteInt.h ******************/
  15090. /************** Include os.h in the middle of sqliteInt.h ********************/
  15091. /************** Begin file os.h **********************************************/
  15092. /*
  15093. ** 2001 September 16
  15094. **
  15095. ** The author disclaims copyright to this source code. In place of
  15096. ** a legal notice, here is a blessing:
  15097. **
  15098. ** May you do good and not evil.
  15099. ** May you find forgiveness for yourself and forgive others.
  15100. ** May you share freely, never taking more than you give.
  15101. **
  15102. ******************************************************************************
  15103. **
  15104. ** This header file (together with is companion C source-code file
  15105. ** "os.c") attempt to abstract the underlying operating system so that
  15106. ** the SQLite library will work on both POSIX and windows systems.
  15107. **
  15108. ** This header file is #include-ed by sqliteInt.h and thus ends up
  15109. ** being included by every source file.
  15110. */
  15111. #ifndef _SQLITE_OS_H_
  15112. #define _SQLITE_OS_H_
  15113. /*
  15114. ** Attempt to automatically detect the operating system and setup the
  15115. ** necessary pre-processor macros for it.
  15116. */
  15117. /************** Include os_setup.h in the middle of os.h *********************/
  15118. /************** Begin file os_setup.h ****************************************/
  15119. /*
  15120. ** 2013 November 25
  15121. **
  15122. ** The author disclaims copyright to this source code. In place of
  15123. ** a legal notice, here is a blessing:
  15124. **
  15125. ** May you do good and not evil.
  15126. ** May you find forgiveness for yourself and forgive others.
  15127. ** May you share freely, never taking more than you give.
  15128. **
  15129. ******************************************************************************
  15130. **
  15131. ** This file contains pre-processor directives related to operating system
  15132. ** detection and/or setup.
  15133. */
  15134. #ifndef SQLITE_OS_SETUP_H
  15135. #define SQLITE_OS_SETUP_H
  15136. /*
  15137. ** Figure out if we are dealing with Unix, Windows, or some other operating
  15138. ** system.
  15139. **
  15140. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  15141. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  15142. ** the three will be 1. The other two will be 0.
  15143. */
  15144. #if defined(SQLITE_OS_OTHER)
  15145. # if SQLITE_OS_OTHER==1
  15146. # undef SQLITE_OS_UNIX
  15147. # define SQLITE_OS_UNIX 0
  15148. # undef SQLITE_OS_WIN
  15149. # define SQLITE_OS_WIN 0
  15150. # else
  15151. # undef SQLITE_OS_OTHER
  15152. # endif
  15153. #endif
  15154. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  15155. # define SQLITE_OS_OTHER 0
  15156. # ifndef SQLITE_OS_WIN
  15157. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  15158. defined(__MINGW32__) || defined(__BORLANDC__)
  15159. # define SQLITE_OS_WIN 1
  15160. # define SQLITE_OS_UNIX 0
  15161. # else
  15162. # define SQLITE_OS_WIN 0
  15163. # define SQLITE_OS_UNIX 1
  15164. # endif
  15165. # else
  15166. # define SQLITE_OS_UNIX 0
  15167. # endif
  15168. #else
  15169. # ifndef SQLITE_OS_WIN
  15170. # define SQLITE_OS_WIN 0
  15171. # endif
  15172. #endif
  15173. #endif /* SQLITE_OS_SETUP_H */
  15174. /************** End of os_setup.h ********************************************/
  15175. /************** Continuing where we left off in os.h *************************/
  15176. /* If the SET_FULLSYNC macro is not defined above, then make it
  15177. ** a no-op
  15178. */
  15179. #ifndef SET_FULLSYNC
  15180. # define SET_FULLSYNC(x,y)
  15181. #endif
  15182. /*
  15183. ** The default size of a disk sector
  15184. */
  15185. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  15186. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  15187. #endif
  15188. /*
  15189. ** Temporary files are named starting with this prefix followed by 16 random
  15190. ** alphanumeric characters, and no file extension. They are stored in the
  15191. ** OS's standard temporary file directory, and are deleted prior to exit.
  15192. ** If sqlite is being embedded in another program, you may wish to change the
  15193. ** prefix to reflect your program's name, so that if your program exits
  15194. ** prematurely, old temporary files can be easily identified. This can be done
  15195. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  15196. **
  15197. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  15198. ** Mcafee started using SQLite in their anti-virus product and it
  15199. ** started putting files with the "sqlite" name in the c:/temp folder.
  15200. ** This annoyed many windows users. Those users would then do a
  15201. ** Google search for "sqlite", find the telephone numbers of the
  15202. ** developers and call to wake them up at night and complain.
  15203. ** For this reason, the default name prefix is changed to be "sqlite"
  15204. ** spelled backwards. So the temp files are still identified, but
  15205. ** anybody smart enough to figure out the code is also likely smart
  15206. ** enough to know that calling the developer will not help get rid
  15207. ** of the file.
  15208. */
  15209. #ifndef SQLITE_TEMP_FILE_PREFIX
  15210. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  15211. #endif
  15212. /*
  15213. ** The following values may be passed as the second argument to
  15214. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  15215. **
  15216. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  15217. ** RESERVED: A single process may hold a RESERVED lock on a file at
  15218. ** any time. Other processes may hold and obtain new SHARED locks.
  15219. ** PENDING: A single process may hold a PENDING lock on a file at
  15220. ** any one time. Existing SHARED locks may persist, but no new
  15221. ** SHARED locks may be obtained by other processes.
  15222. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  15223. **
  15224. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  15225. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  15226. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  15227. ** sqlite3OsLock().
  15228. */
  15229. #define NO_LOCK 0
  15230. #define SHARED_LOCK 1
  15231. #define RESERVED_LOCK 2
  15232. #define PENDING_LOCK 3
  15233. #define EXCLUSIVE_LOCK 4
  15234. /*
  15235. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  15236. **
  15237. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  15238. ** those functions are not available. So we use only LockFile() and
  15239. ** UnlockFile().
  15240. **
  15241. ** LockFile() prevents not just writing but also reading by other processes.
  15242. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  15243. ** byte out of a specific range of bytes. The lock byte is obtained at
  15244. ** random so two separate readers can probably access the file at the
  15245. ** same time, unless they are unlucky and choose the same lock byte.
  15246. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  15247. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  15248. ** a single byte of the file that is designated as the reserved lock byte.
  15249. ** A PENDING_LOCK is obtained by locking a designated byte different from
  15250. ** the RESERVED_LOCK byte.
  15251. **
  15252. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  15253. ** which means we can use reader/writer locks. When reader/writer locks
  15254. ** are used, the lock is placed on the same range of bytes that is used
  15255. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  15256. ** will support two or more Win95 readers or two or more WinNT readers.
  15257. ** But a single Win95 reader will lock out all WinNT readers and a single
  15258. ** WinNT reader will lock out all other Win95 readers.
  15259. **
  15260. ** The following #defines specify the range of bytes used for locking.
  15261. ** SHARED_SIZE is the number of bytes available in the pool from which
  15262. ** a random byte is selected for a shared lock. The pool of bytes for
  15263. ** shared locks begins at SHARED_FIRST.
  15264. **
  15265. ** The same locking strategy and
  15266. ** byte ranges are used for Unix. This leaves open the possibility of having
  15267. ** clients on win95, winNT, and unix all talking to the same shared file
  15268. ** and all locking correctly. To do so would require that samba (or whatever
  15269. ** tool is being used for file sharing) implements locks correctly between
  15270. ** windows and unix. I'm guessing that isn't likely to happen, but by
  15271. ** using the same locking range we are at least open to the possibility.
  15272. **
  15273. ** Locking in windows is manditory. For this reason, we cannot store
  15274. ** actual data in the bytes used for locking. The pager never allocates
  15275. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  15276. ** that all locks will fit on a single page even at the minimum page size.
  15277. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  15278. ** is set high so that we don't have to allocate an unused page except
  15279. ** for very large databases. But one should test the page skipping logic
  15280. ** by setting PENDING_BYTE low and running the entire regression suite.
  15281. **
  15282. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  15283. ** file format. Depending on how it is changed, you might not notice
  15284. ** the incompatibility right away, even running a full regression test.
  15285. ** The default location of PENDING_BYTE is the first byte past the
  15286. ** 1GB boundary.
  15287. **
  15288. */
  15289. #ifdef SQLITE_OMIT_WSD
  15290. # define PENDING_BYTE (0x40000000)
  15291. #else
  15292. # define PENDING_BYTE sqlite3PendingByte
  15293. #endif
  15294. #define RESERVED_BYTE (PENDING_BYTE+1)
  15295. #define SHARED_FIRST (PENDING_BYTE+2)
  15296. #define SHARED_SIZE 510
  15297. /*
  15298. ** Wrapper around OS specific sqlite3_os_init() function.
  15299. */
  15300. SQLITE_PRIVATE int sqlite3OsInit(void);
  15301. /*
  15302. ** Functions for accessing sqlite3_file methods
  15303. */
  15304. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
  15305. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  15306. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  15307. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  15308. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  15309. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  15310. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  15311. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  15312. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  15313. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  15314. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  15315. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  15316. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  15317. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  15318. #ifndef SQLITE_OMIT_WAL
  15319. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  15320. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  15321. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  15322. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  15323. #endif /* SQLITE_OMIT_WAL */
  15324. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  15325. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  15326. /*
  15327. ** Functions for accessing sqlite3_vfs methods
  15328. */
  15329. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  15330. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  15331. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  15332. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  15333. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  15334. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  15335. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  15336. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  15337. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  15338. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  15339. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  15340. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  15341. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
  15342. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  15343. /*
  15344. ** Convenience functions for opening and closing files using
  15345. ** sqlite3_malloc() to obtain space for the file-handle structure.
  15346. */
  15347. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  15348. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
  15349. #endif /* _SQLITE_OS_H_ */
  15350. /************** End of os.h **************************************************/
  15351. /************** Continuing where we left off in sqliteInt.h ******************/
  15352. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  15353. /************** Begin file mutex.h *******************************************/
  15354. /*
  15355. ** 2007 August 28
  15356. **
  15357. ** The author disclaims copyright to this source code. In place of
  15358. ** a legal notice, here is a blessing:
  15359. **
  15360. ** May you do good and not evil.
  15361. ** May you find forgiveness for yourself and forgive others.
  15362. ** May you share freely, never taking more than you give.
  15363. **
  15364. *************************************************************************
  15365. **
  15366. ** This file contains the common header for all mutex implementations.
  15367. ** The sqliteInt.h header #includes this file so that it is available
  15368. ** to all source files. We break it out in an effort to keep the code
  15369. ** better organized.
  15370. **
  15371. ** NOTE: source files should *not* #include this header file directly.
  15372. ** Source files should #include the sqliteInt.h file and let that file
  15373. ** include this one indirectly.
  15374. */
  15375. /*
  15376. ** Figure out what version of the code to use. The choices are
  15377. **
  15378. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  15379. ** mutexes implementation cannot be overridden
  15380. ** at start-time.
  15381. **
  15382. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  15383. ** mutual exclusion is provided. But this
  15384. ** implementation can be overridden at
  15385. ** start-time.
  15386. **
  15387. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  15388. **
  15389. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  15390. */
  15391. #if !SQLITE_THREADSAFE
  15392. # define SQLITE_MUTEX_OMIT
  15393. #endif
  15394. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  15395. # if SQLITE_OS_UNIX
  15396. # define SQLITE_MUTEX_PTHREADS
  15397. # elif SQLITE_OS_WIN
  15398. # define SQLITE_MUTEX_W32
  15399. # else
  15400. # define SQLITE_MUTEX_NOOP
  15401. # endif
  15402. #endif
  15403. #ifdef SQLITE_MUTEX_OMIT
  15404. /*
  15405. ** If this is a no-op implementation, implement everything as macros.
  15406. */
  15407. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  15408. #define sqlite3_mutex_free(X)
  15409. #define sqlite3_mutex_enter(X)
  15410. #define sqlite3_mutex_try(X) SQLITE_OK
  15411. #define sqlite3_mutex_leave(X)
  15412. #define sqlite3_mutex_held(X) ((void)(X),1)
  15413. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  15414. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  15415. #define sqlite3MutexInit() SQLITE_OK
  15416. #define sqlite3MutexEnd()
  15417. #define MUTEX_LOGIC(X)
  15418. #else
  15419. #define MUTEX_LOGIC(X) X
  15420. #endif /* defined(SQLITE_MUTEX_OMIT) */
  15421. /************** End of mutex.h ***********************************************/
  15422. /************** Continuing where we left off in sqliteInt.h ******************/
  15423. /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
  15424. ** synchronous setting to EXTRA. It is no longer supported.
  15425. */
  15426. #ifdef SQLITE_EXTRA_DURABLE
  15427. # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
  15428. # define SQLITE_DEFAULT_SYNCHRONOUS 3
  15429. #endif
  15430. /*
  15431. ** Default synchronous levels.
  15432. **
  15433. ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
  15434. ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
  15435. **
  15436. ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
  15437. ** OFF 1 0
  15438. ** NORMAL 2 1
  15439. ** FULL 3 2
  15440. ** EXTRA 4 3
  15441. **
  15442. ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
  15443. ** In other words, the zero-based numbers are used for all external interfaces
  15444. ** and the one-based values are used internally.
  15445. */
  15446. #ifndef SQLITE_DEFAULT_SYNCHRONOUS
  15447. # define SQLITE_DEFAULT_SYNCHRONOUS 2
  15448. #endif
  15449. #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  15450. # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
  15451. #endif
  15452. /*
  15453. ** Each database file to be accessed by the system is an instance
  15454. ** of the following structure. There are normally two of these structures
  15455. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  15456. ** aDb[1] is the database file used to hold temporary tables. Additional
  15457. ** databases may be attached.
  15458. */
  15459. struct Db {
  15460. char *zDbSName; /* Name of this database. (schema name, not filename) */
  15461. Btree *pBt; /* The B*Tree structure for this database file */
  15462. u8 safety_level; /* How aggressive at syncing data to disk */
  15463. u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
  15464. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  15465. };
  15466. /*
  15467. ** An instance of the following structure stores a database schema.
  15468. **
  15469. ** Most Schema objects are associated with a Btree. The exception is
  15470. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  15471. ** In shared cache mode, a single Schema object can be shared by multiple
  15472. ** Btrees that refer to the same underlying BtShared object.
  15473. **
  15474. ** Schema objects are automatically deallocated when the last Btree that
  15475. ** references them is destroyed. The TEMP Schema is manually freed by
  15476. ** sqlite3_close().
  15477. *
  15478. ** A thread must be holding a mutex on the corresponding Btree in order
  15479. ** to access Schema content. This implies that the thread must also be
  15480. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  15481. ** For a TEMP Schema, only the connection mutex is required.
  15482. */
  15483. struct Schema {
  15484. int schema_cookie; /* Database schema version number for this file */
  15485. int iGeneration; /* Generation counter. Incremented with each change */
  15486. Hash tblHash; /* All tables indexed by name */
  15487. Hash idxHash; /* All (named) indices indexed by name */
  15488. Hash trigHash; /* All triggers indexed by name */
  15489. Hash fkeyHash; /* All foreign keys by referenced table name */
  15490. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  15491. u8 file_format; /* Schema format version for this file */
  15492. u8 enc; /* Text encoding used by this database */
  15493. u16 schemaFlags; /* Flags associated with this schema */
  15494. int cache_size; /* Number of pages to use in the cache */
  15495. };
  15496. /*
  15497. ** These macros can be used to test, set, or clear bits in the
  15498. ** Db.pSchema->flags field.
  15499. */
  15500. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  15501. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  15502. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  15503. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  15504. /*
  15505. ** Allowed values for the DB.pSchema->flags field.
  15506. **
  15507. ** The DB_SchemaLoaded flag is set after the database schema has been
  15508. ** read into internal hash tables.
  15509. **
  15510. ** DB_UnresetViews means that one or more views have column names that
  15511. ** have been filled out. If the schema changes, these column names might
  15512. ** changes and so the view will need to be reset.
  15513. */
  15514. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  15515. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  15516. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  15517. #define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
  15518. /*
  15519. ** The number of different kinds of things that can be limited
  15520. ** using the sqlite3_limit() interface.
  15521. */
  15522. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  15523. /*
  15524. ** Lookaside malloc is a set of fixed-size buffers that can be used
  15525. ** to satisfy small transient memory allocation requests for objects
  15526. ** associated with a particular database connection. The use of
  15527. ** lookaside malloc provides a significant performance enhancement
  15528. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  15529. ** SQL statements.
  15530. **
  15531. ** The Lookaside structure holds configuration information about the
  15532. ** lookaside malloc subsystem. Each available memory allocation in
  15533. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  15534. ** objects.
  15535. **
  15536. ** Lookaside allocations are only allowed for objects that are associated
  15537. ** with a particular database connection. Hence, schema information cannot
  15538. ** be stored in lookaside because in shared cache mode the schema information
  15539. ** is shared by multiple database connections. Therefore, while parsing
  15540. ** schema information, the Lookaside.bEnabled flag is cleared so that
  15541. ** lookaside allocations are not used to construct the schema objects.
  15542. */
  15543. struct Lookaside {
  15544. u32 bDisable; /* Only operate the lookaside when zero */
  15545. u16 sz; /* Size of each buffer in bytes */
  15546. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  15547. u32 nSlot; /* Number of lookaside slots allocated */
  15548. u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  15549. LookasideSlot *pInit; /* List of buffers not previously used */
  15550. LookasideSlot *pFree; /* List of available buffers */
  15551. void *pStart; /* First byte of available memory space */
  15552. void *pEnd; /* First byte past end of available space */
  15553. };
  15554. struct LookasideSlot {
  15555. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  15556. };
  15557. /*
  15558. ** A hash table for built-in function definitions. (Application-defined
  15559. ** functions use a regular table table from hash.h.)
  15560. **
  15561. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  15562. ** Collisions are on the FuncDef.u.pHash chain. Use the SQLITE_FUNC_HASH()
  15563. ** macro to compute a hash on the function name.
  15564. */
  15565. #define SQLITE_FUNC_HASH_SZ 23
  15566. struct FuncDefHash {
  15567. FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
  15568. };
  15569. #define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
  15570. #ifdef SQLITE_USER_AUTHENTICATION
  15571. /*
  15572. ** Information held in the "sqlite3" database connection object and used
  15573. ** to manage user authentication.
  15574. */
  15575. typedef struct sqlite3_userauth sqlite3_userauth;
  15576. struct sqlite3_userauth {
  15577. u8 authLevel; /* Current authentication level */
  15578. int nAuthPW; /* Size of the zAuthPW in bytes */
  15579. char *zAuthPW; /* Password used to authenticate */
  15580. char *zAuthUser; /* User name used to authenticate */
  15581. };
  15582. /* Allowed values for sqlite3_userauth.authLevel */
  15583. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  15584. #define UAUTH_Fail 1 /* User authentication failed */
  15585. #define UAUTH_User 2 /* Authenticated as a normal user */
  15586. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  15587. /* Functions used only by user authorization logic */
  15588. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  15589. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  15590. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  15591. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  15592. #endif /* SQLITE_USER_AUTHENTICATION */
  15593. /*
  15594. ** typedef for the authorization callback function.
  15595. */
  15596. #ifdef SQLITE_USER_AUTHENTICATION
  15597. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  15598. const char*, const char*);
  15599. #else
  15600. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  15601. const char*);
  15602. #endif
  15603. #ifndef SQLITE_OMIT_DEPRECATED
  15604. /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
  15605. ** in the style of sqlite3_trace()
  15606. */
  15607. #define SQLITE_TRACE_LEGACY 0x80
  15608. #else
  15609. #define SQLITE_TRACE_LEGACY 0
  15610. #endif /* SQLITE_OMIT_DEPRECATED */
  15611. /*
  15612. ** Each database connection is an instance of the following structure.
  15613. */
  15614. struct sqlite3 {
  15615. sqlite3_vfs *pVfs; /* OS Interface */
  15616. struct Vdbe *pVdbe; /* List of active virtual machines */
  15617. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  15618. sqlite3_mutex *mutex; /* Connection mutex */
  15619. Db *aDb; /* All backends */
  15620. int nDb; /* Number of backends currently in use */
  15621. u32 mDbFlags; /* flags recording internal state */
  15622. u64 flags; /* flags settable by pragmas. See below */
  15623. i64 lastRowid; /* ROWID of most recent insert (see above) */
  15624. i64 szMmap; /* Default mmap_size setting */
  15625. u32 nSchemaLock; /* Do not reset the schema when non-zero */
  15626. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  15627. int errCode; /* Most recent error code (SQLITE_*) */
  15628. int errMask; /* & result codes with this before returning */
  15629. int iSysErrno; /* Errno value from last system error */
  15630. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  15631. u8 enc; /* Text encoding */
  15632. u8 autoCommit; /* The auto-commit flag. */
  15633. u8 temp_store; /* 1: file 2: memory 0: default */
  15634. u8 mallocFailed; /* True if we have seen a malloc failure */
  15635. u8 bBenignMalloc; /* Do not require OOMs if true */
  15636. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  15637. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  15638. u8 suppressErr; /* Do not issue error messages if true */
  15639. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  15640. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  15641. u8 mTrace; /* zero or more SQLITE_TRACE flags */
  15642. u8 noSharedCache; /* True if no shared-cache backends */
  15643. u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
  15644. int nextPagesize; /* Pagesize after VACUUM if >0 */
  15645. u32 magic; /* Magic number for detect library misuse */
  15646. int nChange; /* Value returned by sqlite3_changes() */
  15647. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  15648. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  15649. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  15650. struct sqlite3InitInfo { /* Information used during initialization */
  15651. int newTnum; /* Rootpage of table being initialized */
  15652. u8 iDb; /* Which db file is being initialized */
  15653. u8 busy; /* TRUE if currently initializing */
  15654. unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
  15655. unsigned imposterTable : 1; /* Building an imposter table */
  15656. unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */
  15657. } init;
  15658. int nVdbeActive; /* Number of VDBEs currently running */
  15659. int nVdbeRead; /* Number of active VDBEs that read or write */
  15660. int nVdbeWrite; /* Number of active VDBEs that read and write */
  15661. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  15662. int nVDestroy; /* Number of active OP_VDestroy operations */
  15663. int nExtension; /* Number of loaded extensions */
  15664. void **aExtension; /* Array of shared library handles */
  15665. int (*xTrace)(u32,void*,void*,void*); /* Trace function */
  15666. void *pTraceArg; /* Argument to the trace function */
  15667. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  15668. void *pProfileArg; /* Argument to profile function */
  15669. void *pCommitArg; /* Argument to xCommitCallback() */
  15670. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  15671. void *pRollbackArg; /* Argument to xRollbackCallback() */
  15672. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  15673. void *pUpdateArg;
  15674. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  15675. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  15676. void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
  15677. void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
  15678. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
  15679. );
  15680. PreUpdate *pPreUpdate; /* Context for active pre-update callback */
  15681. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  15682. #ifndef SQLITE_OMIT_WAL
  15683. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  15684. void *pWalArg;
  15685. #endif
  15686. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  15687. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  15688. void *pCollNeededArg;
  15689. sqlite3_value *pErr; /* Most recent error message */
  15690. union {
  15691. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  15692. double notUsed1; /* Spacer */
  15693. } u1;
  15694. Lookaside lookaside; /* Lookaside malloc configuration */
  15695. #ifndef SQLITE_OMIT_AUTHORIZATION
  15696. sqlite3_xauth xAuth; /* Access authorization function */
  15697. void *pAuthArg; /* 1st argument to the access auth function */
  15698. #endif
  15699. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  15700. int (*xProgress)(void *); /* The progress callback */
  15701. void *pProgressArg; /* Argument to the progress callback */
  15702. unsigned nProgressOps; /* Number of opcodes for progress callback */
  15703. #endif
  15704. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15705. int nVTrans; /* Allocated size of aVTrans */
  15706. Hash aModule; /* populated by sqlite3_create_module() */
  15707. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  15708. VTable **aVTrans; /* Virtual tables with open transactions */
  15709. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  15710. #endif
  15711. Hash aFunc; /* Hash table of connection functions */
  15712. Hash aCollSeq; /* All collating sequences */
  15713. BusyHandler busyHandler; /* Busy callback */
  15714. Db aDbStatic[2]; /* Static space for the 2 default backends */
  15715. Savepoint *pSavepoint; /* List of active savepoints */
  15716. int busyTimeout; /* Busy handler timeout, in msec */
  15717. int nSavepoint; /* Number of non-transaction savepoints */
  15718. int nStatement; /* Number of nested statement-transactions */
  15719. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  15720. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  15721. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  15722. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  15723. /* The following variables are all protected by the STATIC_MASTER
  15724. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  15725. **
  15726. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  15727. ** unlock so that it can proceed.
  15728. **
  15729. ** When X.pBlockingConnection==Y, that means that something that X tried
  15730. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  15731. ** held by Y.
  15732. */
  15733. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  15734. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  15735. void *pUnlockArg; /* Argument to xUnlockNotify */
  15736. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  15737. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  15738. #endif
  15739. #ifdef SQLITE_USER_AUTHENTICATION
  15740. sqlite3_userauth auth; /* User authentication information */
  15741. #endif
  15742. };
  15743. /*
  15744. ** A macro to discover the encoding of a database.
  15745. */
  15746. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  15747. #define ENC(db) ((db)->enc)
  15748. /*
  15749. ** Possible values for the sqlite3.flags.
  15750. **
  15751. ** Value constraints (enforced via assert()):
  15752. ** SQLITE_FullFSync == PAGER_FULLFSYNC
  15753. ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
  15754. ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
  15755. */
  15756. #define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_MASTER */
  15757. #define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
  15758. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  15759. #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
  15760. #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
  15761. #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
  15762. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  15763. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  15764. /* DELETE, or UPDATE and return */
  15765. /* the count using a callback. */
  15766. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  15767. /* result set is empty */
  15768. #define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
  15769. #define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
  15770. #define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
  15771. #define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
  15772. #define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
  15773. #define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
  15774. #define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
  15775. #define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
  15776. #define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
  15777. #define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
  15778. #define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
  15779. #define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
  15780. #define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
  15781. #define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
  15782. #define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee*/
  15783. #define SQLITE_TriggerEQP 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */
  15784. #define SQLITE_ResetDatabase 0x02000000 /* Reset the database */
  15785. #define SQLITE_LegacyAlter 0x04000000 /* Legacy ALTER TABLE behaviour */
  15786. #define SQLITE_NoSchemaError 0x08000000 /* Do not report schema parse errors*/
  15787. #define SQLITE_Defensive 0x10000000 /* Input SQL is likely hostile */
  15788. /* Flags used only if debugging */
  15789. #define HI(X) ((u64)(X)<<32)
  15790. #ifdef SQLITE_DEBUG
  15791. #define SQLITE_SqlTrace HI(0x0001) /* Debug print SQL as it executes */
  15792. #define SQLITE_VdbeListing HI(0x0002) /* Debug listings of VDBE progs */
  15793. #define SQLITE_VdbeTrace HI(0x0004) /* True to trace VDBE execution */
  15794. #define SQLITE_VdbeAddopTrace HI(0x0008) /* Trace sqlite3VdbeAddOp() calls */
  15795. #define SQLITE_VdbeEQP HI(0x0010) /* Debug EXPLAIN QUERY PLAN */
  15796. #endif
  15797. /*
  15798. ** Allowed values for sqlite3.mDbFlags
  15799. */
  15800. #define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
  15801. #define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
  15802. #define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
  15803. #define DBFLAG_SchemaKnownOk 0x0008 /* Schema is known to be valid */
  15804. /*
  15805. ** Bits of the sqlite3.dbOptFlags field that are used by the
  15806. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  15807. ** selectively disable various optimizations.
  15808. */
  15809. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  15810. /* 0x0002 available for reuse */
  15811. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  15812. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  15813. #define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */
  15814. #define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */
  15815. #define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */
  15816. #define SQLITE_Transitive 0x0080 /* Transitive constraints */
  15817. #define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */
  15818. #define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */
  15819. #define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */
  15820. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  15821. /* TH3 expects the Stat34 ^^^^^^ value to be 0x0800. Don't change it */
  15822. #define SQLITE_PushDown 0x1000 /* The push-down optimization */
  15823. #define SQLITE_SimplifyJoin 0x2000 /* Convert LEFT JOIN to JOIN */
  15824. #define SQLITE_SkipScan 0x4000 /* Skip-scans */
  15825. #define SQLITE_PropagateConst 0x8000 /* The constant propagation opt */
  15826. #define SQLITE_AllOpts 0xffff /* All optimizations */
  15827. /*
  15828. ** Macros for testing whether or not optimizations are enabled or disabled.
  15829. */
  15830. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  15831. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  15832. /*
  15833. ** Return true if it OK to factor constant expressions into the initialization
  15834. ** code. The argument is a Parse object for the code generator.
  15835. */
  15836. #define ConstFactorOk(P) ((P)->okConstFactor)
  15837. /*
  15838. ** Possible values for the sqlite.magic field.
  15839. ** The numbers are obtained at random and have no special meaning, other
  15840. ** than being distinct from one another.
  15841. */
  15842. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  15843. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  15844. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  15845. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  15846. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  15847. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  15848. /*
  15849. ** Each SQL function is defined by an instance of the following
  15850. ** structure. For global built-in functions (ex: substr(), max(), count())
  15851. ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
  15852. ** For per-connection application-defined functions, a pointer to this
  15853. ** structure is held in the db->aHash hash table.
  15854. **
  15855. ** The u.pHash field is used by the global built-ins. The u.pDestructor
  15856. ** field is used by per-connection app-def functions.
  15857. */
  15858. struct FuncDef {
  15859. i8 nArg; /* Number of arguments. -1 means unlimited */
  15860. u32 funcFlags; /* Some combination of SQLITE_FUNC_* */
  15861. void *pUserData; /* User data parameter */
  15862. FuncDef *pNext; /* Next function with same name */
  15863. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
  15864. void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
  15865. void (*xValue)(sqlite3_context*); /* Current agg value */
  15866. void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
  15867. const char *zName; /* SQL name of the function. */
  15868. union {
  15869. FuncDef *pHash; /* Next with a different name but the same hash */
  15870. FuncDestructor *pDestructor; /* Reference counted destructor function */
  15871. } u;
  15872. };
  15873. /*
  15874. ** This structure encapsulates a user-function destructor callback (as
  15875. ** configured using create_function_v2()) and a reference counter. When
  15876. ** create_function_v2() is called to create a function with a destructor,
  15877. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  15878. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  15879. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  15880. ** member of each of the new FuncDef objects is set to point to the allocated
  15881. ** FuncDestructor.
  15882. **
  15883. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  15884. ** count on this object is decremented. When it reaches 0, the destructor
  15885. ** is invoked and the FuncDestructor structure freed.
  15886. */
  15887. struct FuncDestructor {
  15888. int nRef;
  15889. void (*xDestroy)(void *);
  15890. void *pUserData;
  15891. };
  15892. /*
  15893. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  15894. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
  15895. ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
  15896. ** are assert() statements in the code to verify this.
  15897. **
  15898. ** Value constraints (enforced via assert()):
  15899. ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
  15900. ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
  15901. ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
  15902. ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
  15903. ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
  15904. */
  15905. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  15906. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  15907. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  15908. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  15909. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  15910. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  15911. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  15912. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  15913. #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
  15914. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  15915. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  15916. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  15917. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  15918. ** single query - might change over time */
  15919. #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
  15920. #define SQLITE_FUNC_OFFSET 0x8000 /* Built-in sqlite_offset() function */
  15921. #define SQLITE_FUNC_WINDOW 0x00010000 /* Built-in window-only function */
  15922. #define SQLITE_FUNC_WINDOW_SIZE 0x20000 /* Requires partition size as arg. */
  15923. #define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
  15924. /*
  15925. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  15926. ** used to create the initializers for the FuncDef structures.
  15927. **
  15928. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  15929. ** Used to create a scalar function definition of a function zName
  15930. ** implemented by C function xFunc that accepts nArg arguments. The
  15931. ** value passed as iArg is cast to a (void*) and made available
  15932. ** as the user-data (sqlite3_user_data()) for the function. If
  15933. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  15934. **
  15935. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  15936. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  15937. **
  15938. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  15939. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  15940. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  15941. ** and functions like sqlite_version() that can change, but not during
  15942. ** a single query. The iArg is ignored. The user-data is always set
  15943. ** to a NULL pointer. The bNC parameter is not used.
  15944. **
  15945. ** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
  15946. ** Used for "pure" date/time functions, this macro is like DFUNCTION
  15947. ** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
  15948. ** ignored and the user-data for these functions is set to an
  15949. ** arbitrary non-NULL pointer. The bNC parameter is not used.
  15950. **
  15951. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  15952. ** Used to create an aggregate function definition implemented by
  15953. ** the C functions xStep and xFinal. The first four parameters
  15954. ** are interpreted in the same way as the first 4 parameters to
  15955. ** FUNCTION().
  15956. **
  15957. ** WFUNCTION(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
  15958. ** Used to create an aggregate function definition implemented by
  15959. ** the C functions xStep and xFinal. The first four parameters
  15960. ** are interpreted in the same way as the first 4 parameters to
  15961. ** FUNCTION().
  15962. **
  15963. ** LIKEFUNC(zName, nArg, pArg, flags)
  15964. ** Used to create a scalar function definition of a function zName
  15965. ** that accepts nArg arguments and is implemented by a call to C
  15966. ** function likeFunc. Argument pArg is cast to a (void *) and made
  15967. ** available as the function user-data (sqlite3_user_data()). The
  15968. ** FuncDef.flags variable is set to the value passed as the flags
  15969. ** parameter.
  15970. */
  15971. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  15972. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  15973. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  15974. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  15975. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  15976. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  15977. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  15978. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
  15979. 0, 0, xFunc, 0, 0, 0, #zName, {0} }
  15980. #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
  15981. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
  15982. (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
  15983. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  15984. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  15985. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  15986. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  15987. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  15988. pArg, 0, xFunc, 0, 0, 0, #zName, }
  15989. #define LIKEFUNC(zName, nArg, arg, flags) \
  15990. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  15991. (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
  15992. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue) \
  15993. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  15994. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,0,#zName, {0}}
  15995. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  15996. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  15997. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xFinal,0,#zName, {0}}
  15998. #define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
  15999. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
  16000. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
  16001. #define INTERNAL_FUNCTION(zName, nArg, xFunc) \
  16002. {nArg, SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
  16003. 0, 0, xFunc, 0, 0, 0, #zName, {0} }
  16004. /*
  16005. ** All current savepoints are stored in a linked list starting at
  16006. ** sqlite3.pSavepoint. The first element in the list is the most recently
  16007. ** opened savepoint. Savepoints are added to the list by the vdbe
  16008. ** OP_Savepoint instruction.
  16009. */
  16010. struct Savepoint {
  16011. char *zName; /* Savepoint name (nul-terminated) */
  16012. i64 nDeferredCons; /* Number of deferred fk violations */
  16013. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  16014. Savepoint *pNext; /* Parent savepoint (if any) */
  16015. };
  16016. /*
  16017. ** The following are used as the second parameter to sqlite3Savepoint(),
  16018. ** and as the P1 argument to the OP_Savepoint instruction.
  16019. */
  16020. #define SAVEPOINT_BEGIN 0
  16021. #define SAVEPOINT_RELEASE 1
  16022. #define SAVEPOINT_ROLLBACK 2
  16023. /*
  16024. ** Each SQLite module (virtual table definition) is defined by an
  16025. ** instance of the following structure, stored in the sqlite3.aModule
  16026. ** hash table.
  16027. */
  16028. struct Module {
  16029. const sqlite3_module *pModule; /* Callback pointers */
  16030. const char *zName; /* Name passed to create_module() */
  16031. void *pAux; /* pAux passed to create_module() */
  16032. void (*xDestroy)(void *); /* Module destructor function */
  16033. Table *pEpoTab; /* Eponymous table for this module */
  16034. };
  16035. /*
  16036. ** information about each column of an SQL table is held in an instance
  16037. ** of this structure.
  16038. */
  16039. struct Column {
  16040. char *zName; /* Name of this column, \000, then the type */
  16041. Expr *pDflt; /* Default value of this column */
  16042. char *zColl; /* Collating sequence. If NULL, use the default */
  16043. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  16044. char affinity; /* One of the SQLITE_AFF_... values */
  16045. u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
  16046. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  16047. };
  16048. /* Allowed values for Column.colFlags:
  16049. */
  16050. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  16051. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  16052. #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
  16053. #define COLFLAG_UNIQUE 0x0008 /* Column def contains "UNIQUE" or "PK" */
  16054. #define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */
  16055. /*
  16056. ** A "Collating Sequence" is defined by an instance of the following
  16057. ** structure. Conceptually, a collating sequence consists of a name and
  16058. ** a comparison routine that defines the order of that sequence.
  16059. **
  16060. ** If CollSeq.xCmp is NULL, it means that the
  16061. ** collating sequence is undefined. Indices built on an undefined
  16062. ** collating sequence may not be read or written.
  16063. */
  16064. struct CollSeq {
  16065. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  16066. u8 enc; /* Text encoding handled by xCmp() */
  16067. void *pUser; /* First argument to xCmp() */
  16068. int (*xCmp)(void*,int, const void*, int, const void*);
  16069. void (*xDel)(void*); /* Destructor for pUser */
  16070. };
  16071. /*
  16072. ** A sort order can be either ASC or DESC.
  16073. */
  16074. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  16075. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  16076. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  16077. /*
  16078. ** Column affinity types.
  16079. **
  16080. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  16081. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  16082. ** the speed a little by numbering the values consecutively.
  16083. **
  16084. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  16085. ** when multiple affinity types are concatenated into a string and
  16086. ** used as the P4 operand, they will be more readable.
  16087. **
  16088. ** Note also that the numeric types are grouped together so that testing
  16089. ** for a numeric type is a single comparison. And the BLOB type is first.
  16090. */
  16091. #define SQLITE_AFF_BLOB 'A'
  16092. #define SQLITE_AFF_TEXT 'B'
  16093. #define SQLITE_AFF_NUMERIC 'C'
  16094. #define SQLITE_AFF_INTEGER 'D'
  16095. #define SQLITE_AFF_REAL 'E'
  16096. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  16097. /*
  16098. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  16099. ** affinity value.
  16100. */
  16101. #define SQLITE_AFF_MASK 0x47
  16102. /*
  16103. ** Additional bit values that can be ORed with an affinity without
  16104. ** changing the affinity.
  16105. **
  16106. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  16107. ** It causes an assert() to fire if either operand to a comparison
  16108. ** operator is NULL. It is added to certain comparison operators to
  16109. ** prove that the operands are always NOT NULL.
  16110. */
  16111. #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
  16112. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  16113. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  16114. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  16115. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  16116. /*
  16117. ** An object of this type is created for each virtual table present in
  16118. ** the database schema.
  16119. **
  16120. ** If the database schema is shared, then there is one instance of this
  16121. ** structure for each database connection (sqlite3*) that uses the shared
  16122. ** schema. This is because each database connection requires its own unique
  16123. ** instance of the sqlite3_vtab* handle used to access the virtual table
  16124. ** implementation. sqlite3_vtab* handles can not be shared between
  16125. ** database connections, even when the rest of the in-memory database
  16126. ** schema is shared, as the implementation often stores the database
  16127. ** connection handle passed to it via the xConnect() or xCreate() method
  16128. ** during initialization internally. This database connection handle may
  16129. ** then be used by the virtual table implementation to access real tables
  16130. ** within the database. So that they appear as part of the callers
  16131. ** transaction, these accesses need to be made via the same database
  16132. ** connection as that used to execute SQL operations on the virtual table.
  16133. **
  16134. ** All VTable objects that correspond to a single table in a shared
  16135. ** database schema are initially stored in a linked-list pointed to by
  16136. ** the Table.pVTable member variable of the corresponding Table object.
  16137. ** When an sqlite3_prepare() operation is required to access the virtual
  16138. ** table, it searches the list for the VTable that corresponds to the
  16139. ** database connection doing the preparing so as to use the correct
  16140. ** sqlite3_vtab* handle in the compiled query.
  16141. **
  16142. ** When an in-memory Table object is deleted (for example when the
  16143. ** schema is being reloaded for some reason), the VTable objects are not
  16144. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  16145. ** immediately. Instead, they are moved from the Table.pVTable list to
  16146. ** another linked list headed by the sqlite3.pDisconnect member of the
  16147. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  16148. ** next time a statement is prepared using said sqlite3*. This is done
  16149. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  16150. ** Refer to comments above function sqlite3VtabUnlockList() for an
  16151. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  16152. ** list without holding the corresponding sqlite3.mutex mutex.
  16153. **
  16154. ** The memory for objects of this type is always allocated by
  16155. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  16156. ** the first argument.
  16157. */
  16158. struct VTable {
  16159. sqlite3 *db; /* Database connection associated with this table */
  16160. Module *pMod; /* Pointer to module implementation */
  16161. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  16162. int nRef; /* Number of pointers to this structure */
  16163. u8 bConstraint; /* True if constraints are supported */
  16164. int iSavepoint; /* Depth of the SAVEPOINT stack */
  16165. VTable *pNext; /* Next in linked list (see above) */
  16166. };
  16167. /*
  16168. ** The schema for each SQL table and view is represented in memory
  16169. ** by an instance of the following structure.
  16170. */
  16171. struct Table {
  16172. char *zName; /* Name of the table or view */
  16173. Column *aCol; /* Information about each column */
  16174. #ifdef SQLITE_ENABLE_NORMALIZE
  16175. Hash *pColHash; /* All columns indexed by name */
  16176. #endif
  16177. Index *pIndex; /* List of SQL indexes on this table. */
  16178. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  16179. FKey *pFKey; /* Linked list of all foreign keys in this table */
  16180. char *zColAff; /* String defining the affinity of each column */
  16181. ExprList *pCheck; /* All CHECK constraints */
  16182. /* ... also used as column name list in a VIEW */
  16183. int tnum; /* Root BTree page for this table */
  16184. u32 nTabRef; /* Number of pointers to this Table */
  16185. u32 tabFlags; /* Mask of TF_* values */
  16186. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  16187. i16 nCol; /* Number of columns in this table */
  16188. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  16189. LogEst szTabRow; /* Estimated size of each table row in bytes */
  16190. #ifdef SQLITE_ENABLE_COSTMULT
  16191. LogEst costMult; /* Cost multiplier for using this table */
  16192. #endif
  16193. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  16194. #ifndef SQLITE_OMIT_ALTERTABLE
  16195. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  16196. #endif
  16197. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16198. int nModuleArg; /* Number of arguments to the module */
  16199. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  16200. VTable *pVTable; /* List of VTable objects. */
  16201. #endif
  16202. Trigger *pTrigger; /* List of triggers stored in pSchema */
  16203. Schema *pSchema; /* Schema that contains this table */
  16204. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  16205. };
  16206. /*
  16207. ** Allowed values for Table.tabFlags.
  16208. **
  16209. ** TF_OOOHidden applies to tables or view that have hidden columns that are
  16210. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  16211. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  16212. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  16213. ** special handling during INSERT processing.
  16214. */
  16215. #define TF_Readonly 0x0001 /* Read-only system table */
  16216. #define TF_Ephemeral 0x0002 /* An ephemeral table */
  16217. #define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
  16218. #define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
  16219. #define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
  16220. #define TF_WithoutRowid 0x0020 /* No rowid. PRIMARY KEY is the key */
  16221. #define TF_NoVisibleRowid 0x0040 /* No user-visible "rowid" column */
  16222. #define TF_OOOHidden 0x0080 /* Out-of-Order hidden columns */
  16223. #define TF_StatsUsed 0x0100 /* Query planner decisions affected by
  16224. ** Index.aiRowLogEst[] values */
  16225. #define TF_HasNotNull 0x0200 /* Contains NOT NULL constraints */
  16226. #define TF_Shadow 0x0400 /* True for a shadow table */
  16227. /*
  16228. ** Test to see whether or not a table is a virtual table. This is
  16229. ** done as a macro so that it will be optimized out when virtual
  16230. ** table support is omitted from the build.
  16231. */
  16232. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16233. # define IsVirtual(X) ((X)->nModuleArg)
  16234. #else
  16235. # define IsVirtual(X) 0
  16236. #endif
  16237. /*
  16238. ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
  16239. ** only works for non-virtual tables (ordinary tables and views) and is
  16240. ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
  16241. ** IsHiddenColumn() macro is general purpose.
  16242. */
  16243. #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
  16244. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16245. # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16246. #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
  16247. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16248. # define IsOrdinaryHiddenColumn(X) 0
  16249. #else
  16250. # define IsHiddenColumn(X) 0
  16251. # define IsOrdinaryHiddenColumn(X) 0
  16252. #endif
  16253. /* Does the table have a rowid */
  16254. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  16255. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  16256. /*
  16257. ** Each foreign key constraint is an instance of the following structure.
  16258. **
  16259. ** A foreign key is associated with two tables. The "from" table is
  16260. ** the table that contains the REFERENCES clause that creates the foreign
  16261. ** key. The "to" table is the table that is named in the REFERENCES clause.
  16262. ** Consider this example:
  16263. **
  16264. ** CREATE TABLE ex1(
  16265. ** a INTEGER PRIMARY KEY,
  16266. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  16267. ** );
  16268. **
  16269. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  16270. ** Equivalent names:
  16271. **
  16272. ** from-table == child-table
  16273. ** to-table == parent-table
  16274. **
  16275. ** Each REFERENCES clause generates an instance of the following structure
  16276. ** which is attached to the from-table. The to-table need not exist when
  16277. ** the from-table is created. The existence of the to-table is not checked.
  16278. **
  16279. ** The list of all parents for child Table X is held at X.pFKey.
  16280. **
  16281. ** A list of all children for a table named Z (which might not even exist)
  16282. ** is held in Schema.fkeyHash with a hash key of Z.
  16283. */
  16284. struct FKey {
  16285. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  16286. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  16287. char *zTo; /* Name of table that the key points to (aka: Parent) */
  16288. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  16289. FKey *pPrevTo; /* Previous with the same zTo */
  16290. int nCol; /* Number of columns in this key */
  16291. /* EV: R-30323-21917 */
  16292. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  16293. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  16294. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  16295. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  16296. int iFrom; /* Index of column in pFrom */
  16297. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  16298. } aCol[1]; /* One entry for each of nCol columns */
  16299. };
  16300. /*
  16301. ** SQLite supports many different ways to resolve a constraint
  16302. ** error. ROLLBACK processing means that a constraint violation
  16303. ** causes the operation in process to fail and for the current transaction
  16304. ** to be rolled back. ABORT processing means the operation in process
  16305. ** fails and any prior changes from that one operation are backed out,
  16306. ** but the transaction is not rolled back. FAIL processing means that
  16307. ** the operation in progress stops and returns an error code. But prior
  16308. ** changes due to the same operation are not backed out and no rollback
  16309. ** occurs. IGNORE means that the particular row that caused the constraint
  16310. ** error is not inserted or updated. Processing continues and no error
  16311. ** is returned. REPLACE means that preexisting database rows that caused
  16312. ** a UNIQUE constraint violation are removed so that the new insert or
  16313. ** update can proceed. Processing continues and no error is reported.
  16314. **
  16315. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  16316. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  16317. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  16318. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  16319. ** referenced table row is propagated into the row that holds the
  16320. ** foreign key.
  16321. **
  16322. ** The following symbolic values are used to record which type
  16323. ** of action to take.
  16324. */
  16325. #define OE_None 0 /* There is no constraint to check */
  16326. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  16327. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  16328. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  16329. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  16330. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  16331. #define OE_Update 6 /* Process as a DO UPDATE in an upsert */
  16332. #define OE_Restrict 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  16333. #define OE_SetNull 8 /* Set the foreign key value to NULL */
  16334. #define OE_SetDflt 9 /* Set the foreign key value to its default */
  16335. #define OE_Cascade 10 /* Cascade the changes */
  16336. #define OE_Default 11 /* Do whatever the default action is */
  16337. /*
  16338. ** An instance of the following structure is passed as the first
  16339. ** argument to sqlite3VdbeKeyCompare and is used to control the
  16340. ** comparison of the two index keys.
  16341. **
  16342. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  16343. ** are nField slots for the columns of an index then one extra slot
  16344. ** for the rowid at the end.
  16345. */
  16346. struct KeyInfo {
  16347. u32 nRef; /* Number of references to this KeyInfo object */
  16348. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  16349. u16 nKeyField; /* Number of key columns in the index */
  16350. u16 nAllField; /* Total columns, including key plus others */
  16351. sqlite3 *db; /* The database connection */
  16352. u8 *aSortOrder; /* Sort order for each column. */
  16353. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  16354. };
  16355. /*
  16356. ** This object holds a record which has been parsed out into individual
  16357. ** fields, for the purposes of doing a comparison.
  16358. **
  16359. ** A record is an object that contains one or more fields of data.
  16360. ** Records are used to store the content of a table row and to store
  16361. ** the key of an index. A blob encoding of a record is created by
  16362. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  16363. ** OP_Column opcode.
  16364. **
  16365. ** An instance of this object serves as a "key" for doing a search on
  16366. ** an index b+tree. The goal of the search is to find the entry that
  16367. ** is closed to the key described by this object. This object might hold
  16368. ** just a prefix of the key. The number of fields is given by
  16369. ** pKeyInfo->nField.
  16370. **
  16371. ** The r1 and r2 fields are the values to return if this key is less than
  16372. ** or greater than a key in the btree, respectively. These are normally
  16373. ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
  16374. ** is in DESC order.
  16375. **
  16376. ** The key comparison functions actually return default_rc when they find
  16377. ** an equals comparison. default_rc can be -1, 0, or +1. If there are
  16378. ** multiple entries in the b-tree with the same key (when only looking
  16379. ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
  16380. ** cause the search to find the last match, or +1 to cause the search to
  16381. ** find the first match.
  16382. **
  16383. ** The key comparison functions will set eqSeen to true if they ever
  16384. ** get and equal results when comparing this structure to a b-tree record.
  16385. ** When default_rc!=0, the search might end up on the record immediately
  16386. ** before the first match or immediately after the last match. The
  16387. ** eqSeen field will indicate whether or not an exact match exists in the
  16388. ** b-tree.
  16389. */
  16390. struct UnpackedRecord {
  16391. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  16392. Mem *aMem; /* Values */
  16393. u16 nField; /* Number of entries in apMem[] */
  16394. i8 default_rc; /* Comparison result if keys are equal */
  16395. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  16396. i8 r1; /* Value to return if (lhs < rhs) */
  16397. i8 r2; /* Value to return if (lhs > rhs) */
  16398. u8 eqSeen; /* True if an equality comparison has been seen */
  16399. };
  16400. /*
  16401. ** Each SQL index is represented in memory by an
  16402. ** instance of the following structure.
  16403. **
  16404. ** The columns of the table that are to be indexed are described
  16405. ** by the aiColumn[] field of this structure. For example, suppose
  16406. ** we have the following table and index:
  16407. **
  16408. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  16409. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  16410. **
  16411. ** In the Table structure describing Ex1, nCol==3 because there are
  16412. ** three columns in the table. In the Index structure describing
  16413. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  16414. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  16415. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  16416. ** The second column to be indexed (c1) has an index of 0 in
  16417. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  16418. **
  16419. ** The Index.onError field determines whether or not the indexed columns
  16420. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  16421. ** it means this is not a unique index. Otherwise it is a unique index
  16422. ** and the value of Index.onError indicate the which conflict resolution
  16423. ** algorithm to employ whenever an attempt is made to insert a non-unique
  16424. ** element.
  16425. **
  16426. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  16427. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  16428. ** table as part of parsing an existing database schema), transient instances
  16429. ** of this structure may be created. In this case the Index.tnum variable is
  16430. ** used to store the address of a VDBE instruction, not a database page
  16431. ** number (it cannot - the database page is not allocated until the VDBE
  16432. ** program is executed). See convertToWithoutRowidTable() for details.
  16433. */
  16434. struct Index {
  16435. char *zName; /* Name of this index */
  16436. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  16437. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  16438. Table *pTable; /* The SQL table being indexed */
  16439. char *zColAff; /* String defining the affinity of each column */
  16440. Index *pNext; /* The next index associated with the same table */
  16441. Schema *pSchema; /* Schema containing this index */
  16442. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  16443. const char **azColl; /* Array of collation sequence names for index */
  16444. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  16445. ExprList *aColExpr; /* Column expressions */
  16446. int tnum; /* DB Page containing root of this index */
  16447. LogEst szIdxRow; /* Estimated average row size in bytes */
  16448. u16 nKeyCol; /* Number of columns forming the key */
  16449. u16 nColumn; /* Number of columns stored in the index */
  16450. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  16451. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  16452. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  16453. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  16454. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  16455. unsigned isCovering:1; /* True if this is a covering index */
  16456. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  16457. unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
  16458. unsigned bNoQuery:1; /* Do not use this index to optimize queries */
  16459. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  16460. int nSample; /* Number of elements in aSample[] */
  16461. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  16462. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  16463. IndexSample *aSample; /* Samples of the left-most key */
  16464. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  16465. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  16466. #endif
  16467. Bitmask colNotIdxed; /* 0 for unindexed columns in pTab */
  16468. };
  16469. /*
  16470. ** Allowed values for Index.idxType
  16471. */
  16472. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  16473. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  16474. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  16475. /* Return true if index X is a PRIMARY KEY index */
  16476. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  16477. /* Return true if index X is a UNIQUE index */
  16478. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  16479. /* The Index.aiColumn[] values are normally positive integer. But
  16480. ** there are some negative values that have special meaning:
  16481. */
  16482. #define XN_ROWID (-1) /* Indexed column is the rowid */
  16483. #define XN_EXPR (-2) /* Indexed column is an expression */
  16484. /*
  16485. ** Each sample stored in the sqlite_stat3 table is represented in memory
  16486. ** using a structure of this type. See documentation at the top of the
  16487. ** analyze.c source file for additional information.
  16488. */
  16489. struct IndexSample {
  16490. void *p; /* Pointer to sampled record */
  16491. int n; /* Size of record in bytes */
  16492. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  16493. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  16494. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  16495. };
  16496. /*
  16497. ** Possible values to use within the flags argument to sqlite3GetToken().
  16498. */
  16499. #define SQLITE_TOKEN_QUOTED 0x1 /* Token is a quoted identifier. */
  16500. #define SQLITE_TOKEN_KEYWORD 0x2 /* Token is a keyword. */
  16501. /*
  16502. ** Each token coming out of the lexer is an instance of
  16503. ** this structure. Tokens are also used as part of an expression.
  16504. **
  16505. ** The memory that "z" points to is owned by other objects. Take care
  16506. ** that the owner of the "z" string does not deallocate the string before
  16507. ** the Token goes out of scope! Very often, the "z" points to some place
  16508. ** in the middle of the Parse.zSql text. But it might also point to a
  16509. ** static string.
  16510. */
  16511. struct Token {
  16512. const char *z; /* Text of the token. Not NULL-terminated! */
  16513. unsigned int n; /* Number of characters in this token */
  16514. };
  16515. /*
  16516. ** An instance of this structure contains information needed to generate
  16517. ** code for a SELECT that contains aggregate functions.
  16518. **
  16519. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  16520. ** pointer to this structure. The Expr.iColumn field is the index in
  16521. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  16522. ** code for that node.
  16523. **
  16524. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  16525. ** original Select structure that describes the SELECT statement. These
  16526. ** fields do not need to be freed when deallocating the AggInfo structure.
  16527. */
  16528. struct AggInfo {
  16529. u8 directMode; /* Direct rendering mode means take data directly
  16530. ** from source tables rather than from accumulators */
  16531. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  16532. ** than the source table */
  16533. int sortingIdx; /* Cursor number of the sorting index */
  16534. int sortingIdxPTab; /* Cursor number of pseudo-table */
  16535. int nSortingColumn; /* Number of columns in the sorting index */
  16536. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  16537. ExprList *pGroupBy; /* The group by clause */
  16538. struct AggInfo_col { /* For each column used in source tables */
  16539. Table *pTab; /* Source table */
  16540. int iTable; /* Cursor number of the source table */
  16541. int iColumn; /* Column number within the source table */
  16542. int iSorterColumn; /* Column number in the sorting index */
  16543. int iMem; /* Memory location that acts as accumulator */
  16544. Expr *pExpr; /* The original expression */
  16545. } *aCol;
  16546. int nColumn; /* Number of used entries in aCol[] */
  16547. int nAccumulator; /* Number of columns that show through to the output.
  16548. ** Additional columns are used only as parameters to
  16549. ** aggregate functions */
  16550. struct AggInfo_func { /* For each aggregate function */
  16551. Expr *pExpr; /* Expression encoding the function */
  16552. FuncDef *pFunc; /* The aggregate function implementation */
  16553. int iMem; /* Memory location that acts as accumulator */
  16554. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  16555. } *aFunc;
  16556. int nFunc; /* Number of entries in aFunc[] */
  16557. };
  16558. /*
  16559. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  16560. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  16561. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  16562. ** it uses less memory in the Expr object, which is a big memory user
  16563. ** in systems with lots of prepared statements. And few applications
  16564. ** need more than about 10 or 20 variables. But some extreme users want
  16565. ** to have prepared statements with over 32767 variables, and for them
  16566. ** the option is available (at compile-time).
  16567. */
  16568. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  16569. typedef i16 ynVar;
  16570. #else
  16571. typedef int ynVar;
  16572. #endif
  16573. /*
  16574. ** Each node of an expression in the parse tree is an instance
  16575. ** of this structure.
  16576. **
  16577. ** Expr.op is the opcode. The integer parser token codes are reused
  16578. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  16579. ** code representing the ">=" operator. This same integer code is reused
  16580. ** to represent the greater-than-or-equal-to operator in the expression
  16581. ** tree.
  16582. **
  16583. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  16584. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  16585. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  16586. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  16587. ** then Expr.token contains the name of the function.
  16588. **
  16589. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  16590. ** binary operator. Either or both may be NULL.
  16591. **
  16592. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  16593. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  16594. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  16595. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  16596. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  16597. ** valid.
  16598. **
  16599. ** An expression of the form ID or ID.ID refers to a column in a table.
  16600. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  16601. ** the integer cursor number of a VDBE cursor pointing to that table and
  16602. ** Expr.iColumn is the column number for the specific column. If the
  16603. ** expression is used as a result in an aggregate SELECT, then the
  16604. ** value is also stored in the Expr.iAgg column in the aggregate so that
  16605. ** it can be accessed after all aggregates are computed.
  16606. **
  16607. ** If the expression is an unbound variable marker (a question mark
  16608. ** character '?' in the original SQL) then the Expr.iTable holds the index
  16609. ** number for that variable.
  16610. **
  16611. ** If the expression is a subquery then Expr.iColumn holds an integer
  16612. ** register number containing the result of the subquery. If the
  16613. ** subquery gives a constant result, then iTable is -1. If the subquery
  16614. ** gives a different answer at different times during statement processing
  16615. ** then iTable is the address of a subroutine that computes the subquery.
  16616. **
  16617. ** If the Expr is of type OP_Column, and the table it is selecting from
  16618. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  16619. ** corresponding table definition.
  16620. **
  16621. ** ALLOCATION NOTES:
  16622. **
  16623. ** Expr objects can use a lot of memory space in database schema. To
  16624. ** help reduce memory requirements, sometimes an Expr object will be
  16625. ** truncated. And to reduce the number of memory allocations, sometimes
  16626. ** two or more Expr objects will be stored in a single memory allocation,
  16627. ** together with Expr.zToken strings.
  16628. **
  16629. ** If the EP_Reduced and EP_TokenOnly flags are set when
  16630. ** an Expr object is truncated. When EP_Reduced is set, then all
  16631. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  16632. ** are contained within the same memory allocation. Note, however, that
  16633. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  16634. ** allocated, regardless of whether or not EP_Reduced is set.
  16635. */
  16636. struct Expr {
  16637. u8 op; /* Operation performed by this node */
  16638. char affinity; /* The affinity of the column or 0 if not a column */
  16639. u32 flags; /* Various flags. EP_* See below */
  16640. union {
  16641. char *zToken; /* Token value. Zero terminated and dequoted */
  16642. int iValue; /* Non-negative integer value if EP_IntValue */
  16643. } u;
  16644. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  16645. ** space is allocated for the fields below this point. An attempt to
  16646. ** access them will result in a segfault or malfunction.
  16647. *********************************************************************/
  16648. Expr *pLeft; /* Left subnode */
  16649. Expr *pRight; /* Right subnode */
  16650. union {
  16651. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  16652. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  16653. } x;
  16654. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  16655. ** space is allocated for the fields below this point. An attempt to
  16656. ** access them will result in a segfault or malfunction.
  16657. *********************************************************************/
  16658. #if SQLITE_MAX_EXPR_DEPTH>0
  16659. int nHeight; /* Height of the tree headed by this node */
  16660. #endif
  16661. int iTable; /* TK_COLUMN: cursor number of table holding column
  16662. ** TK_REGISTER: register number
  16663. ** TK_TRIGGER: 1 -> new, 0 -> old
  16664. ** EP_Unlikely: 134217728 times likelihood
  16665. ** TK_SELECT: 1st register of result vector */
  16666. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  16667. ** TK_VARIABLE: variable number (always >= 1).
  16668. ** TK_SELECT_COLUMN: column of the result vector */
  16669. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  16670. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  16671. u8 op2; /* TK_REGISTER: original value of Expr.op
  16672. ** TK_COLUMN: the value of p5 for OP_Column
  16673. ** TK_AGG_FUNCTION: nesting depth */
  16674. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  16675. union {
  16676. Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL
  16677. ** for a column of an index on an expression */
  16678. Window *pWin; /* TK_FUNCTION: Window definition for the func */
  16679. } y;
  16680. };
  16681. /*
  16682. ** The following are the meanings of bits in the Expr.flags field.
  16683. */
  16684. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  16685. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  16686. #define EP_HasFunc 0x000004 /* Contains one or more functions of any kind */
  16687. #define EP_FixedCol 0x000008 /* TK_Column with a known fixed value */
  16688. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  16689. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  16690. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  16691. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  16692. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  16693. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  16694. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  16695. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  16696. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  16697. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  16698. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  16699. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  16700. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  16701. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  16702. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  16703. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  16704. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  16705. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  16706. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  16707. #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
  16708. #define EP_WinFunc 0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
  16709. /*
  16710. ** The EP_Propagate mask is a set of properties that automatically propagate
  16711. ** upwards into parent nodes.
  16712. */
  16713. #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
  16714. /*
  16715. ** These macros can be used to test, set, or clear bits in the
  16716. ** Expr.flags field.
  16717. */
  16718. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  16719. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  16720. #define ExprSetProperty(E,P) (E)->flags|=(P)
  16721. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  16722. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  16723. ** and Accreditation only. It works like ExprSetProperty() during VVA
  16724. ** processes but is a no-op for delivery.
  16725. */
  16726. #ifdef SQLITE_DEBUG
  16727. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  16728. #else
  16729. # define ExprSetVVAProperty(E,P)
  16730. #endif
  16731. /*
  16732. ** Macros to determine the number of bytes required by a normal Expr
  16733. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  16734. ** and an Expr struct with the EP_TokenOnly flag set.
  16735. */
  16736. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  16737. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  16738. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  16739. /*
  16740. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  16741. ** above sqlite3ExprDup() for details.
  16742. */
  16743. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  16744. /*
  16745. ** A list of expressions. Each expression may optionally have a
  16746. ** name. An expr/name combination can be used in several ways, such
  16747. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  16748. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  16749. ** also be used as the argument to a function, in which case the a.zName
  16750. ** field is not used.
  16751. **
  16752. ** By default the Expr.zSpan field holds a human-readable description of
  16753. ** the expression that is used in the generation of error messages and
  16754. ** column labels. In this case, Expr.zSpan is typically the text of a
  16755. ** column expression as it exists in a SELECT statement. However, if
  16756. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  16757. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  16758. ** form is used for name resolution with nested FROM clauses.
  16759. */
  16760. struct ExprList {
  16761. int nExpr; /* Number of expressions on the list */
  16762. struct ExprList_item { /* For each expression in the list */
  16763. Expr *pExpr; /* The parse tree for this expression */
  16764. char *zName; /* Token associated with this expression */
  16765. char *zSpan; /* Original text of the expression */
  16766. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  16767. unsigned done :1; /* A flag to indicate when processing is finished */
  16768. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  16769. unsigned reusable :1; /* Constant expression is reusable */
  16770. unsigned bSorterRef :1; /* Defer evaluation until after sorting */
  16771. union {
  16772. struct {
  16773. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  16774. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  16775. } x;
  16776. int iConstExprReg; /* Register in which Expr value is cached */
  16777. } u;
  16778. } a[1]; /* One slot for each expression in the list */
  16779. };
  16780. /*
  16781. ** An instance of this structure can hold a simple list of identifiers,
  16782. ** such as the list "a,b,c" in the following statements:
  16783. **
  16784. ** INSERT INTO t(a,b,c) VALUES ...;
  16785. ** CREATE INDEX idx ON t(a,b,c);
  16786. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  16787. **
  16788. ** The IdList.a.idx field is used when the IdList represents the list of
  16789. ** column names after a table name in an INSERT statement. In the statement
  16790. **
  16791. ** INSERT INTO t(a,b,c) ...
  16792. **
  16793. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  16794. */
  16795. struct IdList {
  16796. struct IdList_item {
  16797. char *zName; /* Name of the identifier */
  16798. int idx; /* Index in some Table.aCol[] of a column named zName */
  16799. } *a;
  16800. int nId; /* Number of identifiers on the list */
  16801. };
  16802. /*
  16803. ** The following structure describes the FROM clause of a SELECT statement.
  16804. ** Each table or subquery in the FROM clause is a separate element of
  16805. ** the SrcList.a[] array.
  16806. **
  16807. ** With the addition of multiple database support, the following structure
  16808. ** can also be used to describe a particular table such as the table that
  16809. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  16810. ** such a table must be a simple name: ID. But in SQLite, the table can
  16811. ** now be identified by a database name, a dot, then the table name: ID.ID.
  16812. **
  16813. ** The jointype starts out showing the join type between the current table
  16814. ** and the next table on the list. The parser builds the list this way.
  16815. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  16816. ** jointype expresses the join between the table and the previous table.
  16817. **
  16818. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  16819. ** contains more than 63 columns and the 64-th or later column is used.
  16820. */
  16821. struct SrcList {
  16822. int nSrc; /* Number of tables or subqueries in the FROM clause */
  16823. u32 nAlloc; /* Number of entries allocated in a[] below */
  16824. struct SrcList_item {
  16825. Schema *pSchema; /* Schema to which this item is fixed */
  16826. char *zDatabase; /* Name of database holding this table */
  16827. char *zName; /* Name of the table */
  16828. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  16829. Table *pTab; /* An SQL table corresponding to zName */
  16830. Select *pSelect; /* A SELECT statement used in place of a table name */
  16831. int addrFillSub; /* Address of subroutine to manifest a subquery */
  16832. int regReturn; /* Register holding return address of addrFillSub */
  16833. int regResult; /* Registers holding results of a co-routine */
  16834. struct {
  16835. u8 jointype; /* Type of join between this table and the previous */
  16836. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  16837. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  16838. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  16839. unsigned isCorrelated :1; /* True if sub-query is correlated */
  16840. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  16841. unsigned isRecursive :1; /* True for recursive reference in WITH */
  16842. } fg;
  16843. int iCursor; /* The VDBE cursor number used to access this table */
  16844. Expr *pOn; /* The ON clause of a join */
  16845. IdList *pUsing; /* The USING clause of a join */
  16846. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  16847. union {
  16848. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  16849. ExprList *pFuncArg; /* Arguments to table-valued-function */
  16850. } u1;
  16851. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  16852. } a[1]; /* One entry for each identifier on the list */
  16853. };
  16854. /*
  16855. ** Permitted values of the SrcList.a.jointype field
  16856. */
  16857. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  16858. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  16859. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  16860. #define JT_LEFT 0x0008 /* Left outer join */
  16861. #define JT_RIGHT 0x0010 /* Right outer join */
  16862. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  16863. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  16864. /*
  16865. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  16866. ** and the WhereInfo.wctrlFlags member.
  16867. **
  16868. ** Value constraints (enforced via assert()):
  16869. ** WHERE_USE_LIMIT == SF_FixedLimit
  16870. */
  16871. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  16872. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  16873. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  16874. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  16875. #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
  16876. #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
  16877. #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
  16878. ** the OR optimization */
  16879. #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
  16880. #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
  16881. #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
  16882. #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
  16883. #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
  16884. #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
  16885. #define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */
  16886. /* 0x2000 not currently used */
  16887. #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
  16888. /* 0x8000 not currently used */
  16889. /* Allowed return values from sqlite3WhereIsDistinct()
  16890. */
  16891. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  16892. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  16893. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  16894. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  16895. /*
  16896. ** A NameContext defines a context in which to resolve table and column
  16897. ** names. The context consists of a list of tables (the pSrcList) field and
  16898. ** a list of named expression (pEList). The named expression list may
  16899. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  16900. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  16901. ** pEList corresponds to the result set of a SELECT and is NULL for
  16902. ** other statements.
  16903. **
  16904. ** NameContexts can be nested. When resolving names, the inner-most
  16905. ** context is searched first. If no match is found, the next outer
  16906. ** context is checked. If there is still no match, the next context
  16907. ** is checked. This process continues until either a match is found
  16908. ** or all contexts are check. When a match is found, the nRef member of
  16909. ** the context containing the match is incremented.
  16910. **
  16911. ** Each subquery gets a new NameContext. The pNext field points to the
  16912. ** NameContext in the parent query. Thus the process of scanning the
  16913. ** NameContext list corresponds to searching through successively outer
  16914. ** subqueries looking for a match.
  16915. */
  16916. struct NameContext {
  16917. Parse *pParse; /* The parser */
  16918. SrcList *pSrcList; /* One or more tables used to resolve names */
  16919. union {
  16920. ExprList *pEList; /* Optional list of result-set columns */
  16921. AggInfo *pAggInfo; /* Information about aggregates at this level */
  16922. Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */
  16923. } uNC;
  16924. NameContext *pNext; /* Next outer name context. NULL for outermost */
  16925. int nRef; /* Number of names resolved by this context */
  16926. int nErr; /* Number of errors encountered while resolving names */
  16927. u16 ncFlags; /* Zero or more NC_* flags defined below */
  16928. Select *pWinSelect; /* SELECT statement for any window functions */
  16929. };
  16930. /*
  16931. ** Allowed values for the NameContext, ncFlags field.
  16932. **
  16933. ** Value constraints (all checked via assert()):
  16934. ** NC_HasAgg == SF_HasAgg
  16935. ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
  16936. **
  16937. */
  16938. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  16939. #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
  16940. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  16941. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  16942. #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
  16943. #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
  16944. #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
  16945. #define NC_UEList 0x0080 /* True if uNC.pEList is used */
  16946. #define NC_UAggInfo 0x0100 /* True if uNC.pAggInfo is used */
  16947. #define NC_UUpsert 0x0200 /* True if uNC.pUpsert is used */
  16948. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  16949. #define NC_Complex 0x2000 /* True if a function or subquery seen */
  16950. #define NC_AllowWin 0x4000 /* Window functions are allowed here */
  16951. /*
  16952. ** An instance of the following object describes a single ON CONFLICT
  16953. ** clause in an upsert.
  16954. **
  16955. ** The pUpsertTarget field is only set if the ON CONFLICT clause includes
  16956. ** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
  16957. ** conflict-target clause.) The pUpsertTargetWhere is the optional
  16958. ** WHERE clause used to identify partial unique indexes.
  16959. **
  16960. ** pUpsertSet is the list of column=expr terms of the UPDATE statement.
  16961. ** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The
  16962. ** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
  16963. ** WHERE clause is omitted.
  16964. */
  16965. struct Upsert {
  16966. ExprList *pUpsertTarget; /* Optional description of conflicting index */
  16967. Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
  16968. ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */
  16969. Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */
  16970. /* The fields above comprise the parse tree for the upsert clause.
  16971. ** The fields below are used to transfer information from the INSERT
  16972. ** processing down into the UPDATE processing while generating code.
  16973. ** Upsert owns the memory allocated above, but not the memory below. */
  16974. Index *pUpsertIdx; /* Constraint that pUpsertTarget identifies */
  16975. SrcList *pUpsertSrc; /* Table to be updated */
  16976. int regData; /* First register holding array of VALUES */
  16977. int iDataCur; /* Index of the data cursor */
  16978. int iIdxCur; /* Index of the first index cursor */
  16979. };
  16980. /*
  16981. ** An instance of the following structure contains all information
  16982. ** needed to generate code for a single SELECT statement.
  16983. **
  16984. ** See the header comment on the computeLimitRegisters() routine for a
  16985. ** detailed description of the meaning of the iLimit and iOffset fields.
  16986. **
  16987. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  16988. ** These addresses must be stored so that we can go back and fill in
  16989. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  16990. ** the number of columns in P2 can be computed at the same time
  16991. ** as the OP_OpenEphm instruction is coded because not
  16992. ** enough information about the compound query is known at that point.
  16993. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  16994. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  16995. ** sequences for the ORDER BY clause.
  16996. */
  16997. struct Select {
  16998. ExprList *pEList; /* The fields of the result */
  16999. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  17000. LogEst nSelectRow; /* Estimated number of result rows */
  17001. u32 selFlags; /* Various SF_* values */
  17002. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  17003. u32 selId; /* Unique identifier number for this SELECT */
  17004. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  17005. SrcList *pSrc; /* The FROM clause */
  17006. Expr *pWhere; /* The WHERE clause */
  17007. ExprList *pGroupBy; /* The GROUP BY clause */
  17008. Expr *pHaving; /* The HAVING clause */
  17009. ExprList *pOrderBy; /* The ORDER BY clause */
  17010. Select *pPrior; /* Prior select in a compound select statement */
  17011. Select *pNext; /* Next select to the left in a compound */
  17012. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  17013. With *pWith; /* WITH clause attached to this select. Or NULL. */
  17014. #ifndef SQLITE_OMIT_WINDOWFUNC
  17015. Window *pWin; /* List of window functions */
  17016. Window *pWinDefn; /* List of named window definitions */
  17017. #endif
  17018. };
  17019. /*
  17020. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  17021. ** "Select Flag".
  17022. **
  17023. ** Value constraints (all checked via assert())
  17024. ** SF_HasAgg == NC_HasAgg
  17025. ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
  17026. ** SF_FixedLimit == WHERE_USE_LIMIT
  17027. */
  17028. #define SF_Distinct 0x00001 /* Output should be DISTINCT */
  17029. #define SF_All 0x00002 /* Includes the ALL keyword */
  17030. #define SF_Resolved 0x00004 /* Identifiers have been resolved */
  17031. #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
  17032. #define SF_HasAgg 0x00010 /* Contains aggregate functions */
  17033. #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
  17034. #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
  17035. #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
  17036. #define SF_Compound 0x00100 /* Part of a compound query */
  17037. #define SF_Values 0x00200 /* Synthesized from VALUES clause */
  17038. #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
  17039. #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
  17040. #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
  17041. #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
  17042. #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
  17043. #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
  17044. #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
  17045. #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
  17046. #define SF_ComplexResult 0x40000 /* Result contains subquery or function */
  17047. /*
  17048. ** The results of a SELECT can be distributed in several ways, as defined
  17049. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  17050. ** Type".
  17051. **
  17052. ** SRT_Union Store results as a key in a temporary index
  17053. ** identified by pDest->iSDParm.
  17054. **
  17055. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  17056. **
  17057. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  17058. ** set is not empty.
  17059. **
  17060. ** SRT_Discard Throw the results away. This is used by SELECT
  17061. ** statements within triggers whose only purpose is
  17062. ** the side-effects of functions.
  17063. **
  17064. ** All of the above are free to ignore their ORDER BY clause. Those that
  17065. ** follow must honor the ORDER BY clause.
  17066. **
  17067. ** SRT_Output Generate a row of output (using the OP_ResultRow
  17068. ** opcode) for each row in the result set.
  17069. **
  17070. ** SRT_Mem Only valid if the result is a single column.
  17071. ** Store the first column of the first result row
  17072. ** in register pDest->iSDParm then abandon the rest
  17073. ** of the query. This destination implies "LIMIT 1".
  17074. **
  17075. ** SRT_Set The result must be a single column. Store each
  17076. ** row of result as the key in table pDest->iSDParm.
  17077. ** Apply the affinity pDest->affSdst before storing
  17078. ** results. Used to implement "IN (SELECT ...)".
  17079. **
  17080. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  17081. ** the result there. The cursor is left open after
  17082. ** returning. This is like SRT_Table except that
  17083. ** this destination uses OP_OpenEphemeral to create
  17084. ** the table first.
  17085. **
  17086. ** SRT_Coroutine Generate a co-routine that returns a new row of
  17087. ** results each time it is invoked. The entry point
  17088. ** of the co-routine is stored in register pDest->iSDParm
  17089. ** and the result row is stored in pDest->nDest registers
  17090. ** starting with pDest->iSdst.
  17091. **
  17092. ** SRT_Table Store results in temporary table pDest->iSDParm.
  17093. ** SRT_Fifo This is like SRT_EphemTab except that the table
  17094. ** is assumed to already be open. SRT_Fifo has
  17095. ** the additional property of being able to ignore
  17096. ** the ORDER BY clause.
  17097. **
  17098. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  17099. ** But also use temporary table pDest->iSDParm+1 as
  17100. ** a record of all prior results and ignore any duplicate
  17101. ** rows. Name means: "Distinct Fifo".
  17102. **
  17103. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  17104. ** an index). Append a sequence number so that all entries
  17105. ** are distinct.
  17106. **
  17107. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  17108. ** the same record has never been stored before. The
  17109. ** index at pDest->iSDParm+1 hold all prior stores.
  17110. */
  17111. #define SRT_Union 1 /* Store result as keys in an index */
  17112. #define SRT_Except 2 /* Remove result from a UNION index */
  17113. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  17114. #define SRT_Discard 4 /* Do not save the results anywhere */
  17115. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  17116. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  17117. #define SRT_Queue 7 /* Store result in an queue */
  17118. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  17119. /* The ORDER BY clause is ignored for all of the above */
  17120. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  17121. #define SRT_Output 9 /* Output each row of result */
  17122. #define SRT_Mem 10 /* Store result in a memory cell */
  17123. #define SRT_Set 11 /* Store results as keys in an index */
  17124. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  17125. #define SRT_Coroutine 13 /* Generate a single row of result */
  17126. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  17127. /*
  17128. ** An instance of this object describes where to put of the results of
  17129. ** a SELECT statement.
  17130. */
  17131. struct SelectDest {
  17132. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  17133. int iSDParm; /* A parameter used by the eDest disposal method */
  17134. int iSdst; /* Base register where results are written */
  17135. int nSdst; /* Number of registers allocated */
  17136. char *zAffSdst; /* Affinity used when eDest==SRT_Set */
  17137. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  17138. };
  17139. /*
  17140. ** During code generation of statements that do inserts into AUTOINCREMENT
  17141. ** tables, the following information is attached to the Table.u.autoInc.p
  17142. ** pointer of each autoincrement table to record some side information that
  17143. ** the code generator needs. We have to keep per-table autoincrement
  17144. ** information in case inserts are done within triggers. Triggers do not
  17145. ** normally coordinate their activities, but we do need to coordinate the
  17146. ** loading and saving of autoincrement information.
  17147. */
  17148. struct AutoincInfo {
  17149. AutoincInfo *pNext; /* Next info block in a list of them all */
  17150. Table *pTab; /* Table this info block refers to */
  17151. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  17152. int regCtr; /* Memory register holding the rowid counter */
  17153. };
  17154. /*
  17155. ** At least one instance of the following structure is created for each
  17156. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  17157. ** statement. All such objects are stored in the linked list headed at
  17158. ** Parse.pTriggerPrg and deleted once statement compilation has been
  17159. ** completed.
  17160. **
  17161. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  17162. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  17163. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  17164. ** The Parse.pTriggerPrg list never contains two entries with the same
  17165. ** values for both pTrigger and orconf.
  17166. **
  17167. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  17168. ** accessed (or set to 0 for triggers fired as a result of INSERT
  17169. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  17170. ** a mask of new.* columns used by the program.
  17171. */
  17172. struct TriggerPrg {
  17173. Trigger *pTrigger; /* Trigger this program was coded from */
  17174. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  17175. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  17176. int orconf; /* Default ON CONFLICT policy */
  17177. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  17178. };
  17179. /*
  17180. ** The yDbMask datatype for the bitmask of all attached databases.
  17181. */
  17182. #if SQLITE_MAX_ATTACHED>30
  17183. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  17184. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  17185. # define DbMaskZero(M) memset((M),0,sizeof(M))
  17186. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  17187. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  17188. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  17189. #else
  17190. typedef unsigned int yDbMask;
  17191. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  17192. # define DbMaskZero(M) (M)=0
  17193. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  17194. # define DbMaskAllZero(M) (M)==0
  17195. # define DbMaskNonZero(M) (M)!=0
  17196. #endif
  17197. /*
  17198. ** An SQL parser context. A copy of this structure is passed through
  17199. ** the parser and down into all the parser action routine in order to
  17200. ** carry around information that is global to the entire parse.
  17201. **
  17202. ** The structure is divided into two parts. When the parser and code
  17203. ** generate call themselves recursively, the first part of the structure
  17204. ** is constant but the second part is reset at the beginning and end of
  17205. ** each recursion.
  17206. **
  17207. ** The nTableLock and aTableLock variables are only used if the shared-cache
  17208. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  17209. ** used to store the set of table-locks required by the statement being
  17210. ** compiled. Function sqlite3TableLock() is used to add entries to the
  17211. ** list.
  17212. */
  17213. struct Parse {
  17214. sqlite3 *db; /* The main database structure */
  17215. char *zErrMsg; /* An error message */
  17216. Vdbe *pVdbe; /* An engine for executing database bytecode */
  17217. int rc; /* Return code from execution */
  17218. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  17219. u8 checkSchema; /* Causes schema cookie check after an error */
  17220. u8 nested; /* Number of nested calls to the parser/code generator */
  17221. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  17222. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  17223. u8 mayAbort; /* True if statement may throw an ABORT exception */
  17224. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  17225. u8 okConstFactor; /* OK to factor out constants */
  17226. u8 disableLookaside; /* Number of times lookaside has been disabled */
  17227. int nRangeReg; /* Size of the temporary register block */
  17228. int iRangeReg; /* First register in temporary register block */
  17229. int nErr; /* Number of errors seen */
  17230. int nTab; /* Number of previously allocated VDBE cursors */
  17231. int nMem; /* Number of memory cells used so far */
  17232. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  17233. int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
  17234. int iSelfTab; /* Table associated with an index on expr, or negative
  17235. ** of the base register during check-constraint eval */
  17236. int nLabel; /* Number of labels used */
  17237. int *aLabel; /* Space to hold the labels */
  17238. ExprList *pConstExpr;/* Constant expressions */
  17239. Token constraintName;/* Name of the constraint currently being parsed */
  17240. yDbMask writeMask; /* Start a write transaction on these databases */
  17241. yDbMask cookieMask; /* Bitmask of schema verified databases */
  17242. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  17243. int regRoot; /* Register holding root page number for new objects */
  17244. int nMaxArg; /* Max args passed to user function by sub-program */
  17245. int nSelect; /* Number of SELECT stmts. Counter for Select.selId */
  17246. #ifndef SQLITE_OMIT_SHARED_CACHE
  17247. int nTableLock; /* Number of locks in aTableLock */
  17248. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  17249. #endif
  17250. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  17251. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  17252. Table *pTriggerTab; /* Table triggers are being coded for */
  17253. int addrCrTab; /* Address of OP_CreateBtree opcode on CREATE TABLE */
  17254. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  17255. u32 oldmask; /* Mask of old.* columns referenced */
  17256. u32 newmask; /* Mask of new.* columns referenced */
  17257. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  17258. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  17259. u8 disableTriggers; /* True to disable triggers */
  17260. /**************************************************************************
  17261. ** Fields above must be initialized to zero. The fields that follow,
  17262. ** down to the beginning of the recursive section, do not need to be
  17263. ** initialized as they will be set before being used. The boundary is
  17264. ** determined by offsetof(Parse,aTempReg).
  17265. **************************************************************************/
  17266. int aTempReg[8]; /* Holding area for temporary registers */
  17267. Token sNameToken; /* Token with unqualified schema object name */
  17268. /************************************************************************
  17269. ** Above is constant between recursions. Below is reset before and after
  17270. ** each recursion. The boundary between these two regions is determined
  17271. ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
  17272. ** first field in the recursive region.
  17273. ************************************************************************/
  17274. Token sLastToken; /* The last token parsed */
  17275. ynVar nVar; /* Number of '?' variables seen in the SQL so far */
  17276. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  17277. u8 explain; /* True if the EXPLAIN flag is found on the query */
  17278. #if !(defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE))
  17279. u8 eParseMode; /* PARSE_MODE_XXX constant */
  17280. #endif
  17281. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17282. int nVtabLock; /* Number of virtual tables to lock */
  17283. #endif
  17284. int nHeight; /* Expression tree height of current sub-select */
  17285. #ifndef SQLITE_OMIT_EXPLAIN
  17286. int addrExplain; /* Address of current OP_Explain opcode */
  17287. #endif
  17288. VList *pVList; /* Mapping between variable names and numbers */
  17289. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  17290. const char *zTail; /* All SQL text past the last semicolon parsed */
  17291. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  17292. Index *pNewIndex; /* An index being constructed by CREATE INDEX */
  17293. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  17294. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  17295. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17296. Token sArg; /* Complete text of a module argument */
  17297. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  17298. #endif
  17299. Table *pZombieTab; /* List of Table objects to delete after code gen */
  17300. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  17301. With *pWith; /* Current WITH clause, or NULL */
  17302. With *pWithToFree; /* Free this WITH object at the end of the parse */
  17303. #ifndef SQLITE_OMIT_ALTERTABLE
  17304. RenameToken *pRename; /* Tokens subject to renaming by ALTER TABLE */
  17305. #endif
  17306. };
  17307. #define PARSE_MODE_NORMAL 0
  17308. #define PARSE_MODE_DECLARE_VTAB 1
  17309. #define PARSE_MODE_RENAME_COLUMN 2
  17310. #define PARSE_MODE_RENAME_TABLE 3
  17311. /*
  17312. ** Sizes and pointers of various parts of the Parse object.
  17313. */
  17314. #define PARSE_HDR_SZ offsetof(Parse,aTempReg) /* Recursive part w/o aColCache*/
  17315. #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
  17316. #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
  17317. #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
  17318. /*
  17319. ** Return true if currently inside an sqlite3_declare_vtab() call.
  17320. */
  17321. #ifdef SQLITE_OMIT_VIRTUALTABLE
  17322. #define IN_DECLARE_VTAB 0
  17323. #else
  17324. #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
  17325. #endif
  17326. #if defined(SQLITE_OMIT_ALTERTABLE)
  17327. #define IN_RENAME_OBJECT 0
  17328. #else
  17329. #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME_COLUMN)
  17330. #endif
  17331. #if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
  17332. #define IN_SPECIAL_PARSE 0
  17333. #else
  17334. #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
  17335. #endif
  17336. /*
  17337. ** An instance of the following structure can be declared on a stack and used
  17338. ** to save the Parse.zAuthContext value so that it can be restored later.
  17339. */
  17340. struct AuthContext {
  17341. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  17342. Parse *pParse; /* The Parse structure */
  17343. };
  17344. /*
  17345. ** Bitfield flags for P5 value in various opcodes.
  17346. **
  17347. ** Value constraints (enforced via assert()):
  17348. ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
  17349. ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
  17350. ** OPFLAG_BULKCSR == BTREE_BULKLOAD
  17351. ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
  17352. ** OPFLAG_FORDELETE == BTREE_FORDELETE
  17353. ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
  17354. ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
  17355. */
  17356. #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
  17357. /* Also used in P2 (not P5) of OP_Delete */
  17358. #define OPFLAG_NOCHNG 0x01 /* OP_VColumn nochange for UPDATE */
  17359. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  17360. #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
  17361. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  17362. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  17363. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  17364. #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
  17365. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  17366. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  17367. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  17368. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  17369. #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
  17370. #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
  17371. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  17372. #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
  17373. #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
  17374. #define OPFLAG_NOCHNG_MAGIC 0x6d /* OP_MakeRecord: serialtype 10 is ok */
  17375. /*
  17376. * Each trigger present in the database schema is stored as an instance of
  17377. * struct Trigger.
  17378. *
  17379. * Pointers to instances of struct Trigger are stored in two ways.
  17380. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  17381. * database). This allows Trigger structures to be retrieved by name.
  17382. * 2. All triggers associated with a single table form a linked list, using the
  17383. * pNext member of struct Trigger. A pointer to the first element of the
  17384. * linked list is stored as the "pTrigger" member of the associated
  17385. * struct Table.
  17386. *
  17387. * The "step_list" member points to the first element of a linked list
  17388. * containing the SQL statements specified as the trigger program.
  17389. */
  17390. struct Trigger {
  17391. char *zName; /* The name of the trigger */
  17392. char *table; /* The table or view to which the trigger applies */
  17393. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  17394. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  17395. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  17396. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  17397. the <column-list> is stored here */
  17398. Schema *pSchema; /* Schema containing the trigger */
  17399. Schema *pTabSchema; /* Schema containing the table */
  17400. TriggerStep *step_list; /* Link list of trigger program steps */
  17401. Trigger *pNext; /* Next trigger associated with the table */
  17402. };
  17403. /*
  17404. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  17405. ** determine which.
  17406. **
  17407. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  17408. ** In that cases, the constants below can be ORed together.
  17409. */
  17410. #define TRIGGER_BEFORE 1
  17411. #define TRIGGER_AFTER 2
  17412. /*
  17413. * An instance of struct TriggerStep is used to store a single SQL statement
  17414. * that is a part of a trigger-program.
  17415. *
  17416. * Instances of struct TriggerStep are stored in a singly linked list (linked
  17417. * using the "pNext" member) referenced by the "step_list" member of the
  17418. * associated struct Trigger instance. The first element of the linked list is
  17419. * the first step of the trigger-program.
  17420. *
  17421. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  17422. * "SELECT" statement. The meanings of the other members is determined by the
  17423. * value of "op" as follows:
  17424. *
  17425. * (op == TK_INSERT)
  17426. * orconf -> stores the ON CONFLICT algorithm
  17427. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  17428. * this stores a pointer to the SELECT statement. Otherwise NULL.
  17429. * zTarget -> Dequoted name of the table to insert into.
  17430. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  17431. * this stores values to be inserted. Otherwise NULL.
  17432. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  17433. * statement, then this stores the column-names to be
  17434. * inserted into.
  17435. *
  17436. * (op == TK_DELETE)
  17437. * zTarget -> Dequoted name of the table to delete from.
  17438. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  17439. * Otherwise NULL.
  17440. *
  17441. * (op == TK_UPDATE)
  17442. * zTarget -> Dequoted name of the table to update.
  17443. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  17444. * Otherwise NULL.
  17445. * pExprList -> A list of the columns to update and the expressions to update
  17446. * them to. See sqlite3Update() documentation of "pChanges"
  17447. * argument.
  17448. *
  17449. */
  17450. struct TriggerStep {
  17451. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  17452. u8 orconf; /* OE_Rollback etc. */
  17453. Trigger *pTrig; /* The trigger that this step is a part of */
  17454. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  17455. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  17456. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  17457. ExprList *pExprList; /* SET clause for UPDATE */
  17458. IdList *pIdList; /* Column names for INSERT */
  17459. Upsert *pUpsert; /* Upsert clauses on an INSERT */
  17460. char *zSpan; /* Original SQL text of this command */
  17461. TriggerStep *pNext; /* Next in the link-list */
  17462. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  17463. };
  17464. /*
  17465. ** The following structure contains information used by the sqliteFix...
  17466. ** routines as they walk the parse tree to make database references
  17467. ** explicit.
  17468. */
  17469. typedef struct DbFixer DbFixer;
  17470. struct DbFixer {
  17471. Parse *pParse; /* The parsing context. Error messages written here */
  17472. Schema *pSchema; /* Fix items to this schema */
  17473. int bVarOnly; /* Check for variable references only */
  17474. const char *zDb; /* Make sure all objects are contained in this database */
  17475. const char *zType; /* Type of the container - used for error messages */
  17476. const Token *pName; /* Name of the container - used for error messages */
  17477. };
  17478. /*
  17479. ** An objected used to accumulate the text of a string where we
  17480. ** do not necessarily know how big the string will be in the end.
  17481. */
  17482. struct sqlite3_str {
  17483. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  17484. char *zText; /* The string collected so far */
  17485. u32 nAlloc; /* Amount of space allocated in zText */
  17486. u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  17487. u32 nChar; /* Length of the string so far */
  17488. u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */
  17489. u8 printfFlags; /* SQLITE_PRINTF flags below */
  17490. };
  17491. #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
  17492. #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
  17493. #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
  17494. #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
  17495. /*
  17496. ** A pointer to this structure is used to communicate information
  17497. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  17498. */
  17499. typedef struct {
  17500. sqlite3 *db; /* The database being initialized */
  17501. char **pzErrMsg; /* Error message stored here */
  17502. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  17503. int rc; /* Result code stored here */
  17504. u32 mInitFlags; /* Flags controlling error messages */
  17505. } InitData;
  17506. /*
  17507. ** Allowed values for mInitFlags
  17508. */
  17509. #define INITFLAG_AlterTable 0x0001 /* This is a reparse after ALTER TABLE */
  17510. /*
  17511. ** Structure containing global configuration data for the SQLite library.
  17512. **
  17513. ** This structure also contains some state information.
  17514. */
  17515. struct Sqlite3Config {
  17516. int bMemstat; /* True to enable memory status */
  17517. int bCoreMutex; /* True to enable core mutexing */
  17518. int bFullMutex; /* True to enable full mutexing */
  17519. int bOpenUri; /* True to interpret filenames as URIs */
  17520. int bUseCis; /* Use covering indices for full-scans */
  17521. int bSmallMalloc; /* Avoid large memory allocations if true */
  17522. int mxStrlen; /* Maximum string length */
  17523. int neverCorrupt; /* Database is always well-formed */
  17524. int szLookaside; /* Default lookaside buffer size */
  17525. int nLookaside; /* Default lookaside buffer count */
  17526. int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
  17527. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  17528. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  17529. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  17530. void *pHeap; /* Heap storage space */
  17531. int nHeap; /* Size of pHeap[] */
  17532. int mnReq, mxReq; /* Min and max heap requests sizes */
  17533. sqlite3_int64 szMmap; /* mmap() space per open file */
  17534. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  17535. void *pPage; /* Page cache memory */
  17536. int szPage; /* Size of each page in pPage[] */
  17537. int nPage; /* Number of pages in pPage[] */
  17538. int mxParserStack; /* maximum depth of the parser stack */
  17539. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  17540. u32 szPma; /* Maximum Sorter PMA size */
  17541. /* The above might be initialized to non-zero. The following need to always
  17542. ** initially be zero, however. */
  17543. int isInit; /* True after initialization has finished */
  17544. int inProgress; /* True while initialization in progress */
  17545. int isMutexInit; /* True after mutexes are initialized */
  17546. int isMallocInit; /* True after malloc is initialized */
  17547. int isPCacheInit; /* True after malloc is initialized */
  17548. int nRefInitMutex; /* Number of users of pInitMutex */
  17549. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  17550. void (*xLog)(void*,int,const char*); /* Function for logging */
  17551. void *pLogArg; /* First argument to xLog() */
  17552. #ifdef SQLITE_ENABLE_SQLLOG
  17553. void(*xSqllog)(void*,sqlite3*,const char*, int);
  17554. void *pSqllogArg;
  17555. #endif
  17556. #ifdef SQLITE_VDBE_COVERAGE
  17557. /* The following callback (if not NULL) is invoked on every VDBE branch
  17558. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  17559. */
  17560. void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx); /* Callback */
  17561. void *pVdbeBranchArg; /* 1st argument */
  17562. #endif
  17563. #ifndef SQLITE_UNTESTABLE
  17564. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  17565. #endif
  17566. int bLocaltimeFault; /* True to fail localtime() calls */
  17567. int bInternalFunctions; /* Internal SQL functions are visible */
  17568. int iOnceResetThreshold; /* When to reset OP_Once counters */
  17569. u32 szSorterRef; /* Min size in bytes to use sorter-refs */
  17570. };
  17571. /*
  17572. ** This macro is used inside of assert() statements to indicate that
  17573. ** the assert is only valid on a well-formed database. Instead of:
  17574. **
  17575. ** assert( X );
  17576. **
  17577. ** One writes:
  17578. **
  17579. ** assert( X || CORRUPT_DB );
  17580. **
  17581. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  17582. ** that the database is definitely corrupt, only that it might be corrupt.
  17583. ** For most test cases, CORRUPT_DB is set to false using a special
  17584. ** sqlite3_test_control(). This enables assert() statements to prove
  17585. ** things that are always true for well-formed databases.
  17586. */
  17587. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  17588. /*
  17589. ** Context pointer passed down through the tree-walk.
  17590. */
  17591. struct Walker {
  17592. Parse *pParse; /* Parser context. */
  17593. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  17594. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  17595. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  17596. int walkerDepth; /* Number of subqueries */
  17597. u8 eCode; /* A small processing code */
  17598. union { /* Extra data for callback */
  17599. NameContext *pNC; /* Naming context */
  17600. int n; /* A counter */
  17601. int iCur; /* A cursor number */
  17602. SrcList *pSrcList; /* FROM clause */
  17603. struct SrcCount *pSrcCount; /* Counting column references */
  17604. struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
  17605. int *aiCol; /* array of column indexes */
  17606. struct IdxCover *pIdxCover; /* Check for index coverage */
  17607. struct IdxExprTrans *pIdxTrans; /* Convert idxed expr to column */
  17608. ExprList *pGroupBy; /* GROUP BY clause */
  17609. Select *pSelect; /* HAVING to WHERE clause ctx */
  17610. struct WindowRewrite *pRewrite; /* Window rewrite context */
  17611. struct WhereConst *pConst; /* WHERE clause constants */
  17612. struct RenameCtx *pRename; /* RENAME COLUMN context */
  17613. } u;
  17614. };
  17615. /* Forward declarations */
  17616. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  17617. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  17618. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  17619. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  17620. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  17621. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
  17622. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
  17623. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
  17624. #ifdef SQLITE_DEBUG
  17625. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
  17626. #endif
  17627. /*
  17628. ** Return code from the parse-tree walking primitives and their
  17629. ** callbacks.
  17630. */
  17631. #define WRC_Continue 0 /* Continue down into children */
  17632. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  17633. #define WRC_Abort 2 /* Abandon the tree walk */
  17634. /*
  17635. ** An instance of this structure represents a set of one or more CTEs
  17636. ** (common table expressions) created by a single WITH clause.
  17637. */
  17638. struct With {
  17639. int nCte; /* Number of CTEs in the WITH clause */
  17640. With *pOuter; /* Containing WITH clause, or NULL */
  17641. struct Cte { /* For each CTE in the WITH clause.... */
  17642. char *zName; /* Name of this CTE */
  17643. ExprList *pCols; /* List of explicit column names, or NULL */
  17644. Select *pSelect; /* The definition of this CTE */
  17645. const char *zCteErr; /* Error message for circular references */
  17646. } a[1];
  17647. };
  17648. #ifdef SQLITE_DEBUG
  17649. /*
  17650. ** An instance of the TreeView object is used for printing the content of
  17651. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  17652. */
  17653. struct TreeView {
  17654. int iLevel; /* Which level of the tree we are on */
  17655. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  17656. };
  17657. #endif /* SQLITE_DEBUG */
  17658. /*
  17659. ** This object is used in varioius ways, all related to window functions
  17660. **
  17661. ** (1) A single instance of this structure is attached to the
  17662. ** the Expr.pWin field for each window function in an expression tree.
  17663. ** This object holds the information contained in the OVER clause,
  17664. ** plus additional fields used during code generation.
  17665. **
  17666. ** (2) All window functions in a single SELECT form a linked-list
  17667. ** attached to Select.pWin. The Window.pFunc and Window.pExpr
  17668. ** fields point back to the expression that is the window function.
  17669. **
  17670. ** (3) The terms of the WINDOW clause of a SELECT are instances of this
  17671. ** object on a linked list attached to Select.pWinDefn.
  17672. **
  17673. ** The uses (1) and (2) are really the same Window object that just happens
  17674. ** to be accessible in two different ways. Use (3) is are separate objects.
  17675. */
  17676. struct Window {
  17677. char *zName; /* Name of window (may be NULL) */
  17678. ExprList *pPartition; /* PARTITION BY clause */
  17679. ExprList *pOrderBy; /* ORDER BY clause */
  17680. u8 eType; /* TK_RANGE or TK_ROWS */
  17681. u8 eStart; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
  17682. u8 eEnd; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
  17683. Expr *pStart; /* Expression for "<expr> PRECEDING" */
  17684. Expr *pEnd; /* Expression for "<expr> FOLLOWING" */
  17685. Window *pNextWin; /* Next window function belonging to this SELECT */
  17686. Expr *pFilter; /* The FILTER expression */
  17687. FuncDef *pFunc; /* The function */
  17688. int iEphCsr; /* Partition buffer or Peer buffer */
  17689. int regAccum;
  17690. int regResult;
  17691. int csrApp; /* Function cursor (used by min/max) */
  17692. int regApp; /* Function register (also used by min/max) */
  17693. int regPart; /* First in a set of registers holding PARTITION BY
  17694. ** and ORDER BY values for the window */
  17695. Expr *pOwner; /* Expression object this window is attached to */
  17696. int nBufferCol; /* Number of columns in buffer table */
  17697. int iArgCol; /* Offset of first argument for this function */
  17698. };
  17699. #ifndef SQLITE_OMIT_WINDOWFUNC
  17700. SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*);
  17701. SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);
  17702. SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*);
  17703. SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);
  17704. SQLITE_PRIVATE int sqlite3WindowCompare(Parse*, Window*, Window*);
  17705. SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Window*);
  17706. SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
  17707. SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
  17708. SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, struct SrcList_item*);
  17709. SQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
  17710. SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
  17711. SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
  17712. SQLITE_PRIVATE void sqlite3WindowFunctions(void);
  17713. #else
  17714. # define sqlite3WindowDelete(a,b)
  17715. # define sqlite3WindowFunctions()
  17716. # define sqlite3WindowAttach(a,b,c)
  17717. #endif
  17718. /*
  17719. ** Assuming zIn points to the first byte of a UTF-8 character,
  17720. ** advance zIn to point to the first byte of the next UTF-8 character.
  17721. */
  17722. #define SQLITE_SKIP_UTF8(zIn) { \
  17723. if( (*(zIn++))>=0xc0 ){ \
  17724. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  17725. } \
  17726. }
  17727. /*
  17728. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  17729. ** the same name but without the _BKPT suffix. These macros invoke
  17730. ** routines that report the line-number on which the error originated
  17731. ** using sqlite3_log(). The routines also provide a convenient place
  17732. ** to set a debugger breakpoint.
  17733. */
  17734. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
  17735. SQLITE_PRIVATE int sqlite3CorruptError(int);
  17736. SQLITE_PRIVATE int sqlite3MisuseError(int);
  17737. SQLITE_PRIVATE int sqlite3CantopenError(int);
  17738. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  17739. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  17740. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  17741. #ifdef SQLITE_DEBUG
  17742. SQLITE_PRIVATE int sqlite3NomemError(int);
  17743. SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
  17744. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno);
  17745. # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
  17746. # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
  17747. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
  17748. #else
  17749. # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
  17750. # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
  17751. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
  17752. #endif
  17753. /*
  17754. ** FTS3 and FTS4 both require virtual table support
  17755. */
  17756. #if defined(SQLITE_OMIT_VIRTUALTABLE)
  17757. # undef SQLITE_ENABLE_FTS3
  17758. # undef SQLITE_ENABLE_FTS4
  17759. #endif
  17760. /*
  17761. ** FTS4 is really an extension for FTS3. It is enabled using the
  17762. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  17763. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  17764. */
  17765. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  17766. # define SQLITE_ENABLE_FTS3 1
  17767. #endif
  17768. /*
  17769. ** The ctype.h header is needed for non-ASCII systems. It is also
  17770. ** needed by FTS3 when FTS3 is included in the amalgamation.
  17771. */
  17772. #if !defined(SQLITE_ASCII) || \
  17773. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  17774. # include <ctype.h>
  17775. #endif
  17776. /*
  17777. ** The following macros mimic the standard library functions toupper(),
  17778. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  17779. ** sqlite versions only work for ASCII characters, regardless of locale.
  17780. */
  17781. #ifdef SQLITE_ASCII
  17782. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  17783. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  17784. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  17785. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  17786. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  17787. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  17788. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  17789. # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
  17790. #else
  17791. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  17792. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  17793. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  17794. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  17795. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  17796. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  17797. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  17798. # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
  17799. #endif
  17800. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  17801. /*
  17802. ** Internal function prototypes
  17803. */
  17804. SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
  17805. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  17806. #define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
  17807. SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
  17808. #define sqlite3StrNICmp sqlite3_strnicmp
  17809. SQLITE_PRIVATE int sqlite3MallocInit(void);
  17810. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  17811. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  17812. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  17813. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  17814. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  17815. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
  17816. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  17817. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  17818. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
  17819. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  17820. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  17821. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  17822. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  17823. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
  17824. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  17825. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  17826. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  17827. SQLITE_PRIVATE void sqlite3PageFree(void*);
  17828. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  17829. #ifndef SQLITE_UNTESTABLE
  17830. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  17831. #endif
  17832. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  17833. /*
  17834. ** On systems with ample stack space and that support alloca(), make
  17835. ** use of alloca() to obtain space for large automatic objects. By default,
  17836. ** obtain space from malloc().
  17837. **
  17838. ** The alloca() routine never returns NULL. This will cause code paths
  17839. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  17840. */
  17841. #ifdef SQLITE_USE_ALLOCA
  17842. # define sqlite3StackAllocRaw(D,N) alloca(N)
  17843. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  17844. # define sqlite3StackFree(D,P)
  17845. #else
  17846. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  17847. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  17848. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  17849. #endif
  17850. /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
  17851. ** are, disable MEMSYS3
  17852. */
  17853. #ifdef SQLITE_ENABLE_MEMSYS5
  17854. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  17855. #undef SQLITE_ENABLE_MEMSYS3
  17856. #endif
  17857. #ifdef SQLITE_ENABLE_MEMSYS3
  17858. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  17859. #endif
  17860. #ifndef SQLITE_MUTEX_OMIT
  17861. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  17862. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  17863. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  17864. SQLITE_PRIVATE int sqlite3MutexInit(void);
  17865. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  17866. #endif
  17867. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  17868. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  17869. #else
  17870. # define sqlite3MemoryBarrier()
  17871. #endif
  17872. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  17873. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  17874. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  17875. SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
  17876. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
  17877. /* Access to mutexes used by sqlite3_status() */
  17878. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  17879. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  17880. #if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
  17881. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
  17882. #else
  17883. # define sqlite3MutexWarnOnContention(x)
  17884. #endif
  17885. #ifndef SQLITE_OMIT_FLOATING_POINT
  17886. SQLITE_PRIVATE int sqlite3IsNaN(double);
  17887. #else
  17888. # define sqlite3IsNaN(X) 0
  17889. #endif
  17890. /*
  17891. ** An instance of the following structure holds information about SQL
  17892. ** functions arguments that are the parameters to the printf() function.
  17893. */
  17894. struct PrintfArguments {
  17895. int nArg; /* Total number of arguments */
  17896. int nUsed; /* Number of arguments used so far */
  17897. sqlite3_value **apArg; /* The argument values */
  17898. };
  17899. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  17900. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  17901. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  17902. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  17903. #endif
  17904. #if defined(SQLITE_TEST)
  17905. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  17906. #endif
  17907. #if defined(SQLITE_DEBUG)
  17908. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  17909. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
  17910. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  17911. SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
  17912. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  17913. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
  17914. #ifndef SQLITE_OMIT_WINDOWFUNC
  17915. SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
  17916. SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
  17917. #endif
  17918. #endif
  17919. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  17920. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  17921. SQLITE_PRIVATE void sqlite3Dequote(char*);
  17922. SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
  17923. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  17924. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  17925. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  17926. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  17927. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  17928. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  17929. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  17930. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  17931. #ifdef SQLITE_DEBUG
  17932. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
  17933. #endif
  17934. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  17935. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  17936. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  17937. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
  17938. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
  17939. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  17940. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*, int);
  17941. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
  17942. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  17943. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  17944. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
  17945. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
  17946. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  17947. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
  17948. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  17949. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  17950. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  17951. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  17952. SQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);
  17953. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  17954. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17955. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
  17956. #endif
  17957. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  17958. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  17959. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  17960. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  17961. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  17962. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  17963. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
  17964. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  17965. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  17966. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  17967. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  17968. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  17969. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  17970. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
  17971. #else
  17972. # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
  17973. #endif
  17974. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
  17975. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  17976. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  17977. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  17978. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
  17979. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  17980. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  17981. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  17982. sqlite3_vfs**,char**,char **);
  17983. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  17984. #ifdef SQLITE_UNTESTABLE
  17985. # define sqlite3FaultSim(X) SQLITE_OK
  17986. #else
  17987. SQLITE_PRIVATE int sqlite3FaultSim(int);
  17988. #endif
  17989. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  17990. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  17991. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  17992. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  17993. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  17994. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  17995. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  17996. #ifndef SQLITE_UNTESTABLE
  17997. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  17998. #endif
  17999. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*);
  18000. SQLITE_PRIVATE void sqlite3RowSetDelete(void*);
  18001. SQLITE_PRIVATE void sqlite3RowSetClear(void*);
  18002. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  18003. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  18004. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  18005. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  18006. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  18007. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  18008. #else
  18009. # define sqlite3ViewGetColumnNames(A,B) 0
  18010. #endif
  18011. #if SQLITE_MAX_ATTACHED>30
  18012. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  18013. #endif
  18014. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  18015. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  18016. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  18017. SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);
  18018. #ifndef SQLITE_OMIT_AUTOINCREMENT
  18019. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  18020. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  18021. #else
  18022. # define sqlite3AutoincrementBegin(X)
  18023. # define sqlite3AutoincrementEnd(X)
  18024. #endif
  18025. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
  18026. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  18027. SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
  18028. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  18029. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  18030. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  18031. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  18032. Token*, Select*, Expr*, IdList*);
  18033. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  18034. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  18035. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  18036. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  18037. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  18038. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  18039. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  18040. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  18041. SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  18042. Expr*, int, int, u8);
  18043. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  18044. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  18045. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  18046. Expr*,ExprList*,u32,Expr*);
  18047. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  18048. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  18049. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  18050. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  18051. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  18052. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
  18053. #endif
  18054. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
  18055. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
  18056. Upsert*);
  18057. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  18058. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  18059. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
  18060. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  18061. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  18062. SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
  18063. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  18064. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  18065. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  18066. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  18067. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  18068. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  18069. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  18070. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  18071. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  18072. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  18073. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  18074. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  18075. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
  18076. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  18077. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
  18078. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  18079. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  18080. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  18081. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  18082. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  18083. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  18084. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  18085. #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
  18086. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  18087. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  18088. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  18089. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  18090. #define LOCATE_VIEW 0x01
  18091. #define LOCATE_NOERR 0x02
  18092. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
  18093. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
  18094. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  18095. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  18096. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  18097. SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
  18098. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
  18099. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  18100. SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
  18101. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
  18102. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  18103. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
  18104. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
  18105. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  18106. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  18107. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
  18108. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  18109. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  18110. #ifndef SQLITE_UNTESTABLE
  18111. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  18112. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  18113. #endif
  18114. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  18115. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  18116. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  18117. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  18118. SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
  18119. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  18120. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  18121. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  18122. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
  18123. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
  18124. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  18125. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  18126. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  18127. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
  18128. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  18129. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  18130. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
  18131. #endif
  18132. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  18133. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  18134. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  18135. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  18136. #ifdef SQLITE_ENABLE_NORMALIZE
  18137. SQLITE_PRIVATE int sqlite3IsRowidN(const char*, int);
  18138. #endif
  18139. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  18140. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  18141. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  18142. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  18143. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  18144. SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
  18145. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  18146. u8,u8,int,int*,int*,Upsert*);
  18147. #ifdef SQLITE_ENABLE_NULL_TRIM
  18148. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
  18149. #else
  18150. # define sqlite3SetMakeRecordP5(A,B)
  18151. #endif
  18152. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  18153. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
  18154. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  18155. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  18156. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  18157. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  18158. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  18159. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  18160. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  18161. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  18162. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  18163. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  18164. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  18165. #ifdef SQLITE_ENABLE_NORMALIZE
  18166. SQLITE_PRIVATE FuncDef *sqlite3FunctionSearchN(int,const char*,int);
  18167. #endif
  18168. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
  18169. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
  18170. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
  18171. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  18172. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
  18173. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  18174. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  18175. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  18176. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  18177. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
  18178. #endif
  18179. #ifndef SQLITE_OMIT_TRIGGER
  18180. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  18181. Expr*,int, int);
  18182. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  18183. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  18184. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  18185. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  18186. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  18187. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  18188. int, int, int);
  18189. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  18190. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  18191. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  18192. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
  18193. const char*,const char*);
  18194. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
  18195. Select*,u8,Upsert*,
  18196. const char*,const char*);
  18197. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,ExprList*, Expr*, u8,
  18198. const char*,const char*);
  18199. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
  18200. const char*,const char*);
  18201. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  18202. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  18203. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  18204. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  18205. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  18206. #else
  18207. # define sqlite3TriggersExist(B,C,D,E,F) 0
  18208. # define sqlite3DeleteTrigger(A,B)
  18209. # define sqlite3DropTriggerPtr(A,B)
  18210. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  18211. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  18212. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  18213. # define sqlite3TriggerList(X, Y) 0
  18214. # define sqlite3ParseToplevel(p) p
  18215. # define sqlite3IsToplevel(p) 1
  18216. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  18217. #endif
  18218. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  18219. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  18220. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  18221. #ifndef SQLITE_OMIT_AUTHORIZATION
  18222. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  18223. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  18224. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  18225. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  18226. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  18227. #else
  18228. # define sqlite3AuthRead(a,b,c,d)
  18229. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  18230. # define sqlite3AuthContextPush(a,b,c)
  18231. # define sqlite3AuthContextPop(a) ((void)(a))
  18232. #endif
  18233. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  18234. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  18235. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  18236. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  18237. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  18238. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  18239. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  18240. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  18241. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  18242. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  18243. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  18244. #ifndef SQLITE_OMIT_UTF16
  18245. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  18246. #endif
  18247. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  18248. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  18249. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  18250. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  18251. #ifndef SQLITE_OMIT_VIRTUALTABLE
  18252. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  18253. #endif
  18254. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  18255. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  18256. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  18257. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  18258. #endif
  18259. SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
  18260. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
  18261. SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
  18262. /*
  18263. ** Routines to read and write variable-length integers. These used to
  18264. ** be defined locally, but now we use the varint routines in the util.c
  18265. ** file.
  18266. */
  18267. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  18268. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  18269. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  18270. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  18271. /*
  18272. ** The common case is for a varint to be a single byte. They following
  18273. ** macros handle the common case without a procedure call, but then call
  18274. ** the procedure for larger varints.
  18275. */
  18276. #define getVarint32(A,B) \
  18277. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  18278. #define putVarint32(A,B) \
  18279. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  18280. sqlite3PutVarint((A),(B)))
  18281. #define getVarint sqlite3GetVarint
  18282. #define putVarint sqlite3PutVarint
  18283. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  18284. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  18285. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  18286. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  18287. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
  18288. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  18289. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  18290. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  18291. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  18292. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  18293. SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
  18294. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  18295. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  18296. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  18297. #if defined(SQLITE_NEED_ERR_NAME)
  18298. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  18299. #endif
  18300. #ifdef SQLITE_ENABLE_DESERIALIZE
  18301. SQLITE_PRIVATE int sqlite3MemdbInit(void);
  18302. #endif
  18303. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  18304. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  18305. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  18306. SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);
  18307. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  18308. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  18309. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
  18310. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
  18311. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  18312. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  18313. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  18314. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  18315. SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
  18316. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  18317. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  18318. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  18319. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  18320. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  18321. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  18322. #ifdef SQLITE_ENABLE_8_3_NAMES
  18323. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  18324. #else
  18325. # define sqlite3FileSuffix3(X,Y)
  18326. #endif
  18327. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  18328. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  18329. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  18330. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  18331. void(*)(void*));
  18332. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  18333. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  18334. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  18335. #ifndef SQLITE_OMIT_UTF16
  18336. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  18337. #endif
  18338. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  18339. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  18340. #ifndef SQLITE_AMALGAMATION
  18341. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  18342. SQLITE_PRIVATE const char sqlite3StrBINARY[];
  18343. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  18344. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  18345. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  18346. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  18347. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  18348. #ifndef SQLITE_OMIT_WSD
  18349. SQLITE_PRIVATE int sqlite3PendingByte;
  18350. #endif
  18351. #endif
  18352. #ifdef VDBE_PROFILE
  18353. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
  18354. #endif
  18355. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  18356. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  18357. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  18358. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  18359. SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
  18360. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  18361. #ifdef SQLITE_ENABLE_NORMALIZE
  18362. SQLITE_PRIVATE int sqlite3GetTokenNormalized(const unsigned char *, int *, int *);
  18363. #endif
  18364. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  18365. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
  18366. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
  18367. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  18368. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  18369. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  18370. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  18371. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  18372. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  18373. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  18374. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  18375. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  18376. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  18377. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  18378. SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse*, void*, Token*);
  18379. SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, void *pTo, void *pFrom);
  18380. SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);
  18381. SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
  18382. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  18383. SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);
  18384. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  18385. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*, sqlite3_file*);
  18386. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  18387. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  18388. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  18389. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  18390. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  18391. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  18392. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  18393. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  18394. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  18395. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  18396. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  18397. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  18398. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  18399. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  18400. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
  18401. #ifdef SQLITE_DEBUG
  18402. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  18403. #endif
  18404. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  18405. void (*)(sqlite3_context*,int,sqlite3_value **),
  18406. void (*)(sqlite3_context*,int,sqlite3_value **),
  18407. void (*)(sqlite3_context*),
  18408. void (*)(sqlite3_context*),
  18409. void (*)(sqlite3_context*,int,sqlite3_value **),
  18410. FuncDestructor *pDestructor
  18411. );
  18412. SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
  18413. SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
  18414. SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
  18415. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  18416. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  18417. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  18418. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  18419. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  18420. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  18421. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  18422. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  18423. #ifndef SQLITE_OMIT_SUBQUERY
  18424. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
  18425. #else
  18426. # define sqlite3ExprCheckIN(x,y) SQLITE_OK
  18427. #endif
  18428. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  18429. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  18430. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  18431. Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
  18432. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  18433. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  18434. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  18435. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
  18436. #endif
  18437. /*
  18438. ** The interface to the LEMON-generated parser
  18439. */
  18440. #ifndef SQLITE_AMALGAMATION
  18441. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
  18442. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  18443. #endif
  18444. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token);
  18445. SQLITE_PRIVATE int sqlite3ParserFallback(int);
  18446. #ifdef YYTRACKMAXSTACKDEPTH
  18447. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  18448. #endif
  18449. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  18450. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  18451. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  18452. #else
  18453. # define sqlite3CloseExtensions(X)
  18454. #endif
  18455. #ifndef SQLITE_OMIT_SHARED_CACHE
  18456. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  18457. #else
  18458. #define sqlite3TableLock(v,w,x,y,z)
  18459. #endif
  18460. #ifdef SQLITE_TEST
  18461. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  18462. #endif
  18463. #ifdef SQLITE_OMIT_VIRTUALTABLE
  18464. # define sqlite3VtabClear(Y)
  18465. # define sqlite3VtabSync(X,Y) SQLITE_OK
  18466. # define sqlite3VtabRollback(X)
  18467. # define sqlite3VtabCommit(X)
  18468. # define sqlite3VtabInSync(db) 0
  18469. # define sqlite3VtabLock(X)
  18470. # define sqlite3VtabUnlock(X)
  18471. # define sqlite3VtabUnlockList(X)
  18472. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  18473. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  18474. #else
  18475. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  18476. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  18477. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  18478. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  18479. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  18480. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  18481. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  18482. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  18483. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  18484. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  18485. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  18486. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  18487. sqlite3*,
  18488. const char*,
  18489. const sqlite3_module*,
  18490. void*,
  18491. void(*)(void*)
  18492. );
  18493. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  18494. #endif
  18495. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  18496. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  18497. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  18498. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  18499. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  18500. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  18501. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  18502. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  18503. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  18504. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  18505. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  18506. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  18507. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  18508. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  18509. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  18510. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  18511. #ifdef SQLITE_ENABLE_NORMALIZE
  18512. SQLITE_PRIVATE void sqlite3Normalize(Vdbe*, const char*, int, u8);
  18513. #endif
  18514. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  18515. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  18516. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  18517. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  18518. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  18519. #ifndef SQLITE_OMIT_WAL
  18520. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  18521. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  18522. #endif
  18523. #ifndef SQLITE_OMIT_CTE
  18524. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  18525. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  18526. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  18527. #else
  18528. #define sqlite3WithPush(x,y,z)
  18529. #define sqlite3WithDelete(x,y)
  18530. #endif
  18531. #ifndef SQLITE_OMIT_UPSERT
  18532. SQLITE_PRIVATE Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*);
  18533. SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3*,Upsert*);
  18534. SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
  18535. SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
  18536. SQLITE_PRIVATE void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
  18537. #else
  18538. #define sqlite3UpsertNew(v,w,x,y,z) ((Upsert*)0)
  18539. #define sqlite3UpsertDelete(x,y)
  18540. #define sqlite3UpsertDup(x,y) ((Upsert*)0)
  18541. #endif
  18542. /* Declarations for functions in fkey.c. All of these are replaced by
  18543. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  18544. ** key functionality is available. If OMIT_TRIGGER is defined but
  18545. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  18546. ** this case foreign keys are parsed, but no other functionality is
  18547. ** provided (enforcement of FK constraints requires the triggers sub-system).
  18548. */
  18549. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  18550. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  18551. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  18552. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  18553. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  18554. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  18555. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  18556. #else
  18557. #define sqlite3FkActions(a,b,c,d,e,f)
  18558. #define sqlite3FkCheck(a,b,c,d,e,f)
  18559. #define sqlite3FkDropTable(a,b,c)
  18560. #define sqlite3FkOldmask(a,b) 0
  18561. #define sqlite3FkRequired(a,b,c,d) 0
  18562. #define sqlite3FkReferences(a) 0
  18563. #endif
  18564. #ifndef SQLITE_OMIT_FOREIGN_KEY
  18565. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  18566. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  18567. #else
  18568. #define sqlite3FkDelete(a,b)
  18569. #define sqlite3FkLocateIndex(a,b,c,d,e)
  18570. #endif
  18571. /*
  18572. ** Available fault injectors. Should be numbered beginning with 0.
  18573. */
  18574. #define SQLITE_FAULTINJECTOR_MALLOC 0
  18575. #define SQLITE_FAULTINJECTOR_COUNT 1
  18576. /*
  18577. ** The interface to the code in fault.c used for identifying "benign"
  18578. ** malloc failures. This is only present if SQLITE_UNTESTABLE
  18579. ** is not defined.
  18580. */
  18581. #ifndef SQLITE_UNTESTABLE
  18582. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  18583. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  18584. #else
  18585. #define sqlite3BeginBenignMalloc()
  18586. #define sqlite3EndBenignMalloc()
  18587. #endif
  18588. /*
  18589. ** Allowed return values from sqlite3FindInIndex()
  18590. */
  18591. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  18592. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  18593. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  18594. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  18595. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  18596. /*
  18597. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  18598. */
  18599. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  18600. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  18601. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  18602. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
  18603. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  18604. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  18605. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  18606. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  18607. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  18608. #endif
  18609. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
  18610. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  18611. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  18612. #if SQLITE_MAX_EXPR_DEPTH>0
  18613. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  18614. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  18615. #else
  18616. #define sqlite3SelectExprHeight(x) 0
  18617. #define sqlite3ExprCheckHeight(x,y)
  18618. #endif
  18619. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  18620. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  18621. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  18622. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  18623. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  18624. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  18625. #else
  18626. #define sqlite3ConnectionBlocked(x,y)
  18627. #define sqlite3ConnectionUnlocked(x)
  18628. #define sqlite3ConnectionClosed(x)
  18629. #endif
  18630. #ifdef SQLITE_DEBUG
  18631. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  18632. #endif
  18633. #if defined(YYCOVERAGE)
  18634. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE*);
  18635. #endif
  18636. /*
  18637. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  18638. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  18639. ** print I/O tracing messages.
  18640. */
  18641. #ifdef SQLITE_ENABLE_IOTRACE
  18642. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  18643. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  18644. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  18645. #else
  18646. # define IOTRACE(A)
  18647. # define sqlite3VdbeIOTraceSql(X)
  18648. #endif
  18649. /*
  18650. ** These routines are available for the mem2.c debugging memory allocator
  18651. ** only. They are used to verify that different "types" of memory
  18652. ** allocations are properly tracked by the system.
  18653. **
  18654. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  18655. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  18656. ** a single bit set.
  18657. **
  18658. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  18659. ** argument match the type set by the previous sqlite3MemdebugSetType().
  18660. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  18661. **
  18662. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  18663. ** argument match the type set by the previous sqlite3MemdebugSetType().
  18664. **
  18665. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  18666. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  18667. ** it might have been allocated by lookaside, except the allocation was
  18668. ** too large or lookaside was already full. It is important to verify
  18669. ** that allocations that might have been satisfied by lookaside are not
  18670. ** passed back to non-lookaside free() routines. Asserts such as the
  18671. ** example above are placed on the non-lookaside free() routines to verify
  18672. ** this constraint.
  18673. **
  18674. ** All of this is no-op for a production build. It only comes into
  18675. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  18676. */
  18677. #ifdef SQLITE_MEMDEBUG
  18678. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  18679. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  18680. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  18681. #else
  18682. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  18683. # define sqlite3MemdebugHasType(X,Y) 1
  18684. # define sqlite3MemdebugNoType(X,Y) 1
  18685. #endif
  18686. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  18687. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  18688. #define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
  18689. /*
  18690. ** Threading interface
  18691. */
  18692. #if SQLITE_MAX_WORKER_THREADS>0
  18693. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  18694. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  18695. #endif
  18696. #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
  18697. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
  18698. #endif
  18699. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  18700. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  18701. #endif
  18702. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
  18703. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
  18704. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
  18705. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
  18706. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
  18707. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  18708. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
  18709. #endif
  18710. #endif /* SQLITEINT_H */
  18711. /************** End of sqliteInt.h *******************************************/
  18712. /************** Begin file global.c ******************************************/
  18713. /*
  18714. ** 2008 June 13
  18715. **
  18716. ** The author disclaims copyright to this source code. In place of
  18717. ** a legal notice, here is a blessing:
  18718. **
  18719. ** May you do good and not evil.
  18720. ** May you find forgiveness for yourself and forgive others.
  18721. ** May you share freely, never taking more than you give.
  18722. **
  18723. *************************************************************************
  18724. **
  18725. ** This file contains definitions of global variables and constants.
  18726. */
  18727. /* #include "sqliteInt.h" */
  18728. /* An array to map all upper-case characters into their corresponding
  18729. ** lower-case character.
  18730. **
  18731. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  18732. ** handle case conversions for the UTF character set since the tables
  18733. ** involved are nearly as big or bigger than SQLite itself.
  18734. */
  18735. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  18736. #ifdef SQLITE_ASCII
  18737. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  18738. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  18739. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  18740. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  18741. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  18742. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  18743. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  18744. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  18745. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  18746. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  18747. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  18748. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  18749. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  18750. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  18751. 252,253,254,255
  18752. #endif
  18753. #ifdef SQLITE_EBCDIC
  18754. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  18755. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  18756. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  18757. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  18758. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  18759. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  18760. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  18761. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  18762. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  18763. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  18764. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  18765. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  18766. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  18767. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  18768. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  18769. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  18770. #endif
  18771. };
  18772. /*
  18773. ** The following 256 byte lookup table is used to support SQLites built-in
  18774. ** equivalents to the following standard library functions:
  18775. **
  18776. ** isspace() 0x01
  18777. ** isalpha() 0x02
  18778. ** isdigit() 0x04
  18779. ** isalnum() 0x06
  18780. ** isxdigit() 0x08
  18781. ** toupper() 0x20
  18782. ** SQLite identifier character 0x40
  18783. ** Quote character 0x80
  18784. **
  18785. ** Bit 0x20 is set if the mapped character requires translation to upper
  18786. ** case. i.e. if the character is a lower-case ASCII character.
  18787. ** If x is a lower-case ASCII character, then its upper-case equivalent
  18788. ** is (x - 0x20). Therefore toupper() can be implemented as:
  18789. **
  18790. ** (x & ~(map[x]&0x20))
  18791. **
  18792. ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
  18793. ** array. tolower() is used more often than toupper() by SQLite.
  18794. **
  18795. ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
  18796. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  18797. ** non-ASCII UTF character. Hence the test for whether or not a character is
  18798. ** part of an identifier is 0x46.
  18799. */
  18800. #ifdef SQLITE_ASCII
  18801. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  18802. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  18803. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  18804. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  18805. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  18806. 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
  18807. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  18808. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  18809. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  18810. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  18811. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  18812. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  18813. 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  18814. 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  18815. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  18816. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  18817. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  18818. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  18819. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  18820. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  18821. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  18822. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  18823. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  18824. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  18825. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  18826. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  18827. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  18828. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  18829. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  18830. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  18831. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  18832. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  18833. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  18834. };
  18835. #endif
  18836. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  18837. ** compatibility for legacy applications, the URI filename capability is
  18838. ** disabled by default.
  18839. **
  18840. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  18841. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  18842. **
  18843. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  18844. ** disabled. The default value may be changed by compiling with the
  18845. ** SQLITE_USE_URI symbol defined.
  18846. **
  18847. ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
  18848. ** enabled.
  18849. */
  18850. #ifndef SQLITE_USE_URI
  18851. # ifdef SQLITE_HAS_CODEC
  18852. # define SQLITE_USE_URI 1
  18853. # else
  18854. # define SQLITE_USE_URI 0
  18855. # endif
  18856. #endif
  18857. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  18858. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  18859. ** that compile-time option is omitted.
  18860. */
  18861. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  18862. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  18863. #endif
  18864. /* The minimum PMA size is set to this value multiplied by the database
  18865. ** page size in bytes.
  18866. */
  18867. #ifndef SQLITE_SORTER_PMASZ
  18868. # define SQLITE_SORTER_PMASZ 250
  18869. #endif
  18870. /* Statement journals spill to disk when their size exceeds the following
  18871. ** threshold (in bytes). 0 means that statement journals are created and
  18872. ** written to disk immediately (the default behavior for SQLite versions
  18873. ** before 3.12.0). -1 means always keep the entire statement journal in
  18874. ** memory. (The statement journal is also always held entirely in memory
  18875. ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
  18876. ** setting.)
  18877. */
  18878. #ifndef SQLITE_STMTJRNL_SPILL
  18879. # define SQLITE_STMTJRNL_SPILL (64*1024)
  18880. #endif
  18881. /*
  18882. ** The default lookaside-configuration, the format "SZ,N". SZ is the
  18883. ** number of bytes in each lookaside slot (should be a multiple of 8)
  18884. ** and N is the number of slots. The lookaside-configuration can be
  18885. ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
  18886. ** or at run-time for an individual database connection using
  18887. ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
  18888. */
  18889. #ifndef SQLITE_DEFAULT_LOOKASIDE
  18890. # define SQLITE_DEFAULT_LOOKASIDE 1200,100
  18891. #endif
  18892. /*
  18893. ** The following singleton contains the global configuration for
  18894. ** the SQLite library.
  18895. */
  18896. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  18897. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  18898. 1, /* bCoreMutex */
  18899. SQLITE_THREADSAFE==1, /* bFullMutex */
  18900. SQLITE_USE_URI, /* bOpenUri */
  18901. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  18902. 0, /* bSmallMalloc */
  18903. 0x7ffffffe, /* mxStrlen */
  18904. 0, /* neverCorrupt */
  18905. SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
  18906. SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
  18907. {0,0,0,0,0,0,0,0}, /* m */
  18908. {0,0,0,0,0,0,0,0,0}, /* mutex */
  18909. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  18910. (void*)0, /* pHeap */
  18911. 0, /* nHeap */
  18912. 0, 0, /* mnHeap, mxHeap */
  18913. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  18914. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  18915. (void*)0, /* pPage */
  18916. 0, /* szPage */
  18917. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  18918. 0, /* mxParserStack */
  18919. 0, /* sharedCacheEnabled */
  18920. SQLITE_SORTER_PMASZ, /* szPma */
  18921. /* All the rest should always be initialized to zero */
  18922. 0, /* isInit */
  18923. 0, /* inProgress */
  18924. 0, /* isMutexInit */
  18925. 0, /* isMallocInit */
  18926. 0, /* isPCacheInit */
  18927. 0, /* nRefInitMutex */
  18928. 0, /* pInitMutex */
  18929. 0, /* xLog */
  18930. 0, /* pLogArg */
  18931. #ifdef SQLITE_ENABLE_SQLLOG
  18932. 0, /* xSqllog */
  18933. 0, /* pSqllogArg */
  18934. #endif
  18935. #ifdef SQLITE_VDBE_COVERAGE
  18936. 0, /* xVdbeBranch */
  18937. 0, /* pVbeBranchArg */
  18938. #endif
  18939. #ifndef SQLITE_UNTESTABLE
  18940. 0, /* xTestCallback */
  18941. #endif
  18942. 0, /* bLocaltimeFault */
  18943. 0, /* bInternalFunctions */
  18944. 0x7ffffffe, /* iOnceResetThreshold */
  18945. SQLITE_DEFAULT_SORTERREF_SIZE /* szSorterRef */
  18946. };
  18947. /*
  18948. ** Hash table for global functions - functions common to all
  18949. ** database connections. After initialization, this table is
  18950. ** read-only.
  18951. */
  18952. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  18953. /*
  18954. ** Constant tokens for values 0 and 1.
  18955. */
  18956. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  18957. { "0", 1 },
  18958. { "1", 1 }
  18959. };
  18960. #ifdef VDBE_PROFILE
  18961. /*
  18962. ** The following performance counter can be used in place of
  18963. ** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
  18964. */
  18965. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
  18966. #endif
  18967. /*
  18968. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  18969. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  18970. ** the database page that contains the pending byte. It never attempts
  18971. ** to read or write that page. The pending byte page is set aside
  18972. ** for use by the VFS layers as space for managing file locks.
  18973. **
  18974. ** During testing, it is often desirable to move the pending byte to
  18975. ** a different position in the file. This allows code that has to
  18976. ** deal with the pending byte to run on files that are much smaller
  18977. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  18978. ** move the pending byte.
  18979. **
  18980. ** IMPORTANT: Changing the pending byte to any value other than
  18981. ** 0x40000000 results in an incompatible database file format!
  18982. ** Changing the pending byte during operation will result in undefined
  18983. ** and incorrect behavior.
  18984. */
  18985. #ifndef SQLITE_OMIT_WSD
  18986. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  18987. #endif
  18988. /* #include "opcodes.h" */
  18989. /*
  18990. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  18991. ** created by mkopcodeh.awk during compilation. Data is obtained
  18992. ** from the comments following the "case OP_xxxx:" statements in
  18993. ** the vdbe.c file.
  18994. */
  18995. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  18996. /*
  18997. ** Name of the default collating sequence
  18998. */
  18999. SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
  19000. /************** End of global.c **********************************************/
  19001. /************** Begin file status.c ******************************************/
  19002. /*
  19003. ** 2008 June 18
  19004. **
  19005. ** The author disclaims copyright to this source code. In place of
  19006. ** a legal notice, here is a blessing:
  19007. **
  19008. ** May you do good and not evil.
  19009. ** May you find forgiveness for yourself and forgive others.
  19010. ** May you share freely, never taking more than you give.
  19011. **
  19012. *************************************************************************
  19013. **
  19014. ** This module implements the sqlite3_status() interface and related
  19015. ** functionality.
  19016. */
  19017. /* #include "sqliteInt.h" */
  19018. /************** Include vdbeInt.h in the middle of status.c ******************/
  19019. /************** Begin file vdbeInt.h *****************************************/
  19020. /*
  19021. ** 2003 September 6
  19022. **
  19023. ** The author disclaims copyright to this source code. In place of
  19024. ** a legal notice, here is a blessing:
  19025. **
  19026. ** May you do good and not evil.
  19027. ** May you find forgiveness for yourself and forgive others.
  19028. ** May you share freely, never taking more than you give.
  19029. **
  19030. *************************************************************************
  19031. ** This is the header file for information that is private to the
  19032. ** VDBE. This information used to all be at the top of the single
  19033. ** source code file "vdbe.c". When that file became too big (over
  19034. ** 6000 lines long) it was split up into several smaller files and
  19035. ** this header information was factored out.
  19036. */
  19037. #ifndef SQLITE_VDBEINT_H
  19038. #define SQLITE_VDBEINT_H
  19039. /*
  19040. ** The maximum number of times that a statement will try to reparse
  19041. ** itself before giving up and returning SQLITE_SCHEMA.
  19042. */
  19043. #ifndef SQLITE_MAX_SCHEMA_RETRY
  19044. # define SQLITE_MAX_SCHEMA_RETRY 50
  19045. #endif
  19046. /*
  19047. ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
  19048. ** "explain" P4 display logic is enabled.
  19049. */
  19050. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  19051. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  19052. # define VDBE_DISPLAY_P4 1
  19053. #else
  19054. # define VDBE_DISPLAY_P4 0
  19055. #endif
  19056. /*
  19057. ** SQL is translated into a sequence of instructions to be
  19058. ** executed by a virtual machine. Each instruction is an instance
  19059. ** of the following structure.
  19060. */
  19061. typedef struct VdbeOp Op;
  19062. /*
  19063. ** Boolean values
  19064. */
  19065. typedef unsigned Bool;
  19066. /* Opaque type used by code in vdbesort.c */
  19067. typedef struct VdbeSorter VdbeSorter;
  19068. /* Elements of the linked list at Vdbe.pAuxData */
  19069. typedef struct AuxData AuxData;
  19070. /* Types of VDBE cursors */
  19071. #define CURTYPE_BTREE 0
  19072. #define CURTYPE_SORTER 1
  19073. #define CURTYPE_VTAB 2
  19074. #define CURTYPE_PSEUDO 3
  19075. /*
  19076. ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
  19077. **
  19078. ** * A b-tree cursor
  19079. ** - In the main database or in an ephemeral database
  19080. ** - On either an index or a table
  19081. ** * A sorter
  19082. ** * A virtual table
  19083. ** * A one-row "pseudotable" stored in a single register
  19084. */
  19085. typedef struct VdbeCursor VdbeCursor;
  19086. struct VdbeCursor {
  19087. u8 eCurType; /* One of the CURTYPE_* values above */
  19088. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  19089. u8 nullRow; /* True if pointing to a row with no data */
  19090. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  19091. u8 isTable; /* True for rowid tables. False for indexes */
  19092. #ifdef SQLITE_DEBUG
  19093. u8 seekOp; /* Most recent seek operation on this cursor */
  19094. u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
  19095. #endif
  19096. Bool isEphemeral:1; /* True for an ephemeral table */
  19097. Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
  19098. Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
  19099. Bool seekHit:1; /* See the OP_SeekHit and OP_IfNoHope opcodes */
  19100. Btree *pBtx; /* Separate file holding temporary table */
  19101. i64 seqCount; /* Sequence counter */
  19102. int *aAltMap; /* Mapping from table to index column numbers */
  19103. /* Cached OP_Column parse information is only valid if cacheStatus matches
  19104. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  19105. ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
  19106. ** the cache is out of date. */
  19107. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  19108. int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
  19109. ** if there have been no prior seeks on the cursor. */
  19110. /* seekResult does not distinguish between "no seeks have ever occurred
  19111. ** on this cursor" and "the most recent seek was an exact match".
  19112. ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
  19113. /* When a new VdbeCursor is allocated, only the fields above are zeroed.
  19114. ** The fields that follow are uninitialized, and must be individually
  19115. ** initialized prior to first use. */
  19116. VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
  19117. union {
  19118. BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
  19119. sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
  19120. VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
  19121. } uc;
  19122. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  19123. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  19124. Pgno pgnoRoot; /* Root page of the open btree cursor */
  19125. i16 nField; /* Number of fields in the header */
  19126. u16 nHdrParsed; /* Number of header fields parsed so far */
  19127. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  19128. u32 *aOffset; /* Pointer to aType[nField] */
  19129. const u8 *aRow; /* Data for the current row, if all on one page */
  19130. u32 payloadSize; /* Total number of bytes in the record */
  19131. u32 szRow; /* Byte available in aRow */
  19132. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  19133. u64 maskUsed; /* Mask of columns used by this cursor */
  19134. #endif
  19135. /* 2*nField extra array elements allocated for aType[], beyond the one
  19136. ** static element declared in the structure. nField total array slots for
  19137. ** aType[] and nField+1 array slots for aOffset[] */
  19138. u32 aType[1]; /* Type values record decode. MUST BE LAST */
  19139. };
  19140. /*
  19141. ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
  19142. */
  19143. #define CACHE_STALE 0
  19144. /*
  19145. ** When a sub-program is executed (OP_Program), a structure of this type
  19146. ** is allocated to store the current value of the program counter, as
  19147. ** well as the current memory cell array and various other frame specific
  19148. ** values stored in the Vdbe struct. When the sub-program is finished,
  19149. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  19150. ** restoring the state of the VM to as it was before the sub-program
  19151. ** began executing.
  19152. **
  19153. ** The memory for a VdbeFrame object is allocated and managed by a memory
  19154. ** cell in the parent (calling) frame. When the memory cell is deleted or
  19155. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  19156. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  19157. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  19158. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  19159. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  19160. ** child frame are released.
  19161. **
  19162. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  19163. ** set to NULL if the currently executing frame is the main program.
  19164. */
  19165. typedef struct VdbeFrame VdbeFrame;
  19166. struct VdbeFrame {
  19167. Vdbe *v; /* VM this frame belongs to */
  19168. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  19169. Op *aOp; /* Program instructions for parent frame */
  19170. i64 *anExec; /* Event counters from parent frame */
  19171. Mem *aMem; /* Array of memory cells for parent frame */
  19172. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  19173. u8 *aOnce; /* Bitmask used by OP_Once */
  19174. void *token; /* Copy of SubProgram.token */
  19175. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  19176. AuxData *pAuxData; /* Linked list of auxdata allocations */
  19177. #if SQLITE_DEBUG
  19178. u32 iFrameMagic; /* magic number for sanity checking */
  19179. #endif
  19180. int nCursor; /* Number of entries in apCsr */
  19181. int pc; /* Program Counter in parent (calling) frame */
  19182. int nOp; /* Size of aOp array */
  19183. int nMem; /* Number of entries in aMem */
  19184. int nChildMem; /* Number of memory cells for child frame */
  19185. int nChildCsr; /* Number of cursors for child frame */
  19186. int nChange; /* Statement changes (Vdbe.nChange) */
  19187. int nDbChange; /* Value of db->nChange */
  19188. };
  19189. /* Magic number for sanity checking on VdbeFrame objects */
  19190. #define SQLITE_FRAME_MAGIC 0x879fb71e
  19191. /*
  19192. ** Return a pointer to the array of registers allocated for use
  19193. ** by a VdbeFrame.
  19194. */
  19195. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  19196. /*
  19197. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  19198. ** structures. Each Mem struct may cache multiple representations (string,
  19199. ** integer etc.) of the same value.
  19200. */
  19201. struct sqlite3_value {
  19202. union MemValue {
  19203. double r; /* Real value used when MEM_Real is set in flags */
  19204. i64 i; /* Integer value used when MEM_Int is set in flags */
  19205. int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
  19206. const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
  19207. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  19208. } u;
  19209. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  19210. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  19211. u8 eSubtype; /* Subtype for this value */
  19212. int n; /* Number of characters in string value, excluding '\0' */
  19213. char *z; /* String or BLOB value */
  19214. /* ShallowCopy only needs to copy the information above */
  19215. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  19216. int szMalloc; /* Size of the zMalloc allocation */
  19217. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  19218. sqlite3 *db; /* The associated database connection */
  19219. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  19220. #ifdef SQLITE_DEBUG
  19221. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  19222. u16 mScopyFlags; /* flags value immediately after the shallow copy */
  19223. #endif
  19224. };
  19225. /*
  19226. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  19227. ** follows.
  19228. */
  19229. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  19230. /* One or more of the following flags are set to indicate the validOK
  19231. ** representations of the value stored in the Mem struct.
  19232. **
  19233. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  19234. ** For a pointer type created using sqlite3_bind_pointer() or
  19235. ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
  19236. **
  19237. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  19238. ** Usually this is encoded in the same unicode encoding as the main
  19239. ** database (see below for exceptions). If the MEM_Term flag is also
  19240. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  19241. ** flags may coexist with the MEM_Str flag.
  19242. */
  19243. #define MEM_Null 0x0001 /* Value is NULL (or a pointer) */
  19244. #define MEM_Str 0x0002 /* Value is a string */
  19245. #define MEM_Int 0x0004 /* Value is an integer */
  19246. #define MEM_Real 0x0008 /* Value is a real number */
  19247. #define MEM_Blob 0x0010 /* Value is a BLOB */
  19248. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  19249. /* Available 0x0020 */
  19250. /* Available 0x0040 */
  19251. #define MEM_Undefined 0x0080 /* Value is undefined */
  19252. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  19253. #define MEM_TypeMask 0xc1ff /* Mask of type bits */
  19254. /* Whenever Mem contains a valid string or blob representation, one of
  19255. ** the following flags must be set to determine the memory management
  19256. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  19257. ** string is \000 or \u0000 terminated
  19258. */
  19259. #define MEM_Term 0x0200 /* String in Mem.z is zero terminated */
  19260. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  19261. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  19262. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  19263. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  19264. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  19265. #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
  19266. #ifdef SQLITE_OMIT_INCRBLOB
  19267. #undef MEM_Zero
  19268. #define MEM_Zero 0x0000
  19269. #endif
  19270. /* Return TRUE if Mem X contains dynamically allocated content - anything
  19271. ** that needs to be deallocated to avoid a leak.
  19272. */
  19273. #define VdbeMemDynamic(X) \
  19274. (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)
  19275. /*
  19276. ** Clear any existing type flags from a Mem and replace them with f
  19277. */
  19278. #define MemSetTypeFlag(p, f) \
  19279. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  19280. /*
  19281. ** Return true if a memory cell is not marked as invalid. This macro
  19282. ** is for use inside assert() statements only.
  19283. */
  19284. #ifdef SQLITE_DEBUG
  19285. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  19286. #endif
  19287. /*
  19288. ** Each auxiliary data pointer stored by a user defined function
  19289. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  19290. ** of this structure. All such structures associated with a single VM
  19291. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  19292. ** when the VM is halted (if not before).
  19293. */
  19294. struct AuxData {
  19295. int iAuxOp; /* Instruction number of OP_Function opcode */
  19296. int iAuxArg; /* Index of function argument. */
  19297. void *pAux; /* Aux data pointer */
  19298. void (*xDeleteAux)(void*); /* Destructor for the aux data */
  19299. AuxData *pNextAux; /* Next element in list */
  19300. };
  19301. /*
  19302. ** The "context" argument for an installable function. A pointer to an
  19303. ** instance of this structure is the first argument to the routines used
  19304. ** implement the SQL functions.
  19305. **
  19306. ** There is a typedef for this structure in sqlite.h. So all routines,
  19307. ** even the public interface to SQLite, can use a pointer to this structure.
  19308. ** But this file is the only place where the internal details of this
  19309. ** structure are known.
  19310. **
  19311. ** This structure is defined inside of vdbeInt.h because it uses substructures
  19312. ** (Mem) which are only defined there.
  19313. */
  19314. struct sqlite3_context {
  19315. Mem *pOut; /* The return value is stored here */
  19316. FuncDef *pFunc; /* Pointer to function information */
  19317. Mem *pMem; /* Memory cell used to store aggregate context */
  19318. Vdbe *pVdbe; /* The VM that owns this context */
  19319. int iOp; /* Instruction number of OP_Function */
  19320. int isError; /* Error code returned by the function. */
  19321. u8 skipFlag; /* Skip accumulator loading if true */
  19322. u8 argc; /* Number of arguments */
  19323. sqlite3_value *argv[1]; /* Argument set */
  19324. };
  19325. /* A bitfield type for use inside of structures. Always follow with :N where
  19326. ** N is the number of bits.
  19327. */
  19328. typedef unsigned bft; /* Bit Field Type */
  19329. typedef struct ScanStatus ScanStatus;
  19330. struct ScanStatus {
  19331. int addrExplain; /* OP_Explain for loop */
  19332. int addrLoop; /* Address of "loops" counter */
  19333. int addrVisit; /* Address of "rows visited" counter */
  19334. int iSelectID; /* The "Select-ID" for this loop */
  19335. LogEst nEst; /* Estimated output rows per loop */
  19336. char *zName; /* Name of table or index */
  19337. };
  19338. /*
  19339. ** An instance of the virtual machine. This structure contains the complete
  19340. ** state of the virtual machine.
  19341. **
  19342. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  19343. ** is really a pointer to an instance of this structure.
  19344. */
  19345. struct Vdbe {
  19346. sqlite3 *db; /* The database connection that owns this statement */
  19347. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  19348. Parse *pParse; /* Parsing context used to create this Vdbe */
  19349. ynVar nVar; /* Number of entries in aVar[] */
  19350. u32 magic; /* Magic number for sanity checking */
  19351. int nMem; /* Number of memory locations currently allocated */
  19352. int nCursor; /* Number of slots in apCsr[] */
  19353. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  19354. int pc; /* The program counter */
  19355. int rc; /* Value to return */
  19356. int nChange; /* Number of db changes made since last reset */
  19357. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  19358. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  19359. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  19360. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  19361. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  19362. /* When allocating a new Vdbe object, all of the fields below should be
  19363. ** initialized to zero or NULL */
  19364. Op *aOp; /* Space to hold the virtual machine's program */
  19365. Mem *aMem; /* The memory locations */
  19366. Mem **apArg; /* Arguments to currently executing user function */
  19367. Mem *aColName; /* Column names to return */
  19368. Mem *pResultSet; /* Pointer to an array of results */
  19369. char *zErrMsg; /* Error message written here */
  19370. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  19371. Mem *aVar; /* Values for the OP_Variable opcode. */
  19372. VList *pVList; /* Name of variables */
  19373. #ifndef SQLITE_OMIT_TRACE
  19374. i64 startTime; /* Time when query started - used for profiling */
  19375. #endif
  19376. int nOp; /* Number of instructions in the program */
  19377. #ifdef SQLITE_DEBUG
  19378. int rcApp; /* errcode set by sqlite3_result_error_code() */
  19379. u32 nWrite; /* Number of write operations that have occurred */
  19380. #endif
  19381. u16 nResColumn; /* Number of columns in one row of the result set */
  19382. u8 errorAction; /* Recovery action to do in case of an error */
  19383. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  19384. u8 prepFlags; /* SQLITE_PREPARE_* flags */
  19385. bft expired:2; /* 1: recompile VM immediately 2: when convenient */
  19386. bft explain:2; /* True if EXPLAIN present on SQL command */
  19387. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  19388. bft changeCntOn:1; /* True to update the change-counter */
  19389. bft runOnlyOnce:1; /* Automatically expire on reset */
  19390. bft usesStmtJournal:1; /* True if uses a statement journal */
  19391. bft readOnly:1; /* True for statements that do not write */
  19392. bft bIsReader:1; /* True for statements that read */
  19393. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  19394. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  19395. u32 aCounter[7]; /* Counters used by sqlite3_stmt_status() */
  19396. char *zSql; /* Text of the SQL statement that generated this */
  19397. #ifdef SQLITE_ENABLE_NORMALIZE
  19398. char *zNormSql; /* Normalization of the associated SQL statement */
  19399. #endif
  19400. void *pFree; /* Free this when deleting the vdbe */
  19401. VdbeFrame *pFrame; /* Parent frame */
  19402. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  19403. int nFrame; /* Number of frames in pFrame list */
  19404. u32 expmask; /* Binding to these vars invalidates VM */
  19405. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  19406. AuxData *pAuxData; /* Linked list of auxdata allocations */
  19407. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  19408. i64 *anExec; /* Number of times each op has been executed */
  19409. int nScan; /* Entries in aScan[] */
  19410. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  19411. #endif
  19412. };
  19413. /*
  19414. ** The following are allowed values for Vdbe.magic
  19415. */
  19416. #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
  19417. #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
  19418. #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
  19419. #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
  19420. #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
  19421. /*
  19422. ** Structure used to store the context required by the
  19423. ** sqlite3_preupdate_*() API functions.
  19424. */
  19425. struct PreUpdate {
  19426. Vdbe *v;
  19427. VdbeCursor *pCsr; /* Cursor to read old values from */
  19428. int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
  19429. u8 *aRecord; /* old.* database record */
  19430. KeyInfo keyinfo;
  19431. UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
  19432. UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
  19433. int iNewReg; /* Register for new.* values */
  19434. i64 iKey1; /* First key value passed to hook */
  19435. i64 iKey2; /* Second key value passed to hook */
  19436. Mem *aNew; /* Array of new.* values */
  19437. Table *pTab; /* Schema object being upated */
  19438. Index *pPk; /* PK index if pTab is WITHOUT ROWID */
  19439. };
  19440. /*
  19441. ** Function prototypes
  19442. */
  19443. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  19444. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  19445. void sqliteVdbePopStack(Vdbe*,int);
  19446. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
  19447. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  19448. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  19449. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
  19450. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
  19451. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  19452. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  19453. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
  19454. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  19455. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  19456. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  19457. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  19458. #ifndef SQLITE_OMIT_EXPLAIN
  19459. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  19460. #endif
  19461. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  19462. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  19463. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  19464. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  19465. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  19466. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  19467. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  19468. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  19469. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  19470. #ifdef SQLITE_OMIT_FLOATING_POINT
  19471. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  19472. #else
  19473. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  19474. #endif
  19475. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
  19476. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  19477. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  19478. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  19479. #ifdef SQLITE_DEBUG
  19480. SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*);
  19481. #endif
  19482. SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*);
  19483. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  19484. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  19485. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  19486. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  19487. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  19488. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
  19489. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  19490. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  19491. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  19492. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  19493. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
  19494. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  19495. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  19496. #ifndef SQLITE_OMIT_WINDOWFUNC
  19497. SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
  19498. #endif
  19499. #ifndef SQLITE_OMIT_EXPLAIN
  19500. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  19501. #endif
  19502. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  19503. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  19504. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  19505. #ifdef SQLITE_DEBUG
  19506. SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame*);
  19507. #endif
  19508. SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*); /* Destructor on Mem */
  19509. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */
  19510. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  19511. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  19512. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
  19513. #endif
  19514. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  19515. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  19516. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  19517. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  19518. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  19519. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
  19520. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  19521. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  19522. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  19523. #ifdef SQLITE_DEBUG
  19524. SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
  19525. SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe*);
  19526. #else
  19527. # define sqlite3VdbeIncrWriteCounter(V,C)
  19528. # define sqlite3VdbeAssertAbortable(V)
  19529. #endif
  19530. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  19531. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  19532. #else
  19533. # define sqlite3VdbeEnter(X)
  19534. #endif
  19535. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  19536. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  19537. #else
  19538. # define sqlite3VdbeLeave(X)
  19539. #endif
  19540. #ifdef SQLITE_DEBUG
  19541. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  19542. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  19543. #endif
  19544. #ifndef SQLITE_OMIT_FOREIGN_KEY
  19545. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  19546. #else
  19547. # define sqlite3VdbeCheckFk(p,i) 0
  19548. #endif
  19549. #ifdef SQLITE_DEBUG
  19550. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  19551. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  19552. #endif
  19553. #ifndef SQLITE_OMIT_UTF16
  19554. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  19555. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  19556. #endif
  19557. #ifndef SQLITE_OMIT_INCRBLOB
  19558. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  19559. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  19560. #else
  19561. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  19562. #define ExpandBlob(P) SQLITE_OK
  19563. #endif
  19564. #endif /* !defined(SQLITE_VDBEINT_H) */
  19565. /************** End of vdbeInt.h *********************************************/
  19566. /************** Continuing where we left off in status.c *********************/
  19567. /*
  19568. ** Variables in which to record status information.
  19569. */
  19570. #if SQLITE_PTRSIZE>4
  19571. typedef sqlite3_int64 sqlite3StatValueType;
  19572. #else
  19573. typedef u32 sqlite3StatValueType;
  19574. #endif
  19575. typedef struct sqlite3StatType sqlite3StatType;
  19576. static SQLITE_WSD struct sqlite3StatType {
  19577. sqlite3StatValueType nowValue[10]; /* Current value */
  19578. sqlite3StatValueType mxValue[10]; /* Maximum value */
  19579. } sqlite3Stat = { {0,}, {0,} };
  19580. /*
  19581. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  19582. ** mutex, or by the pcache1 mutex. The following array determines which.
  19583. */
  19584. static const char statMutex[] = {
  19585. 0, /* SQLITE_STATUS_MEMORY_USED */
  19586. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  19587. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  19588. 0, /* SQLITE_STATUS_SCRATCH_USED */
  19589. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  19590. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  19591. 0, /* SQLITE_STATUS_PARSER_STACK */
  19592. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  19593. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  19594. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  19595. };
  19596. /* The "wsdStat" macro will resolve to the status information
  19597. ** state vector. If writable static data is unsupported on the target,
  19598. ** we have to locate the state vector at run-time. In the more common
  19599. ** case where writable static data is supported, wsdStat can refer directly
  19600. ** to the "sqlite3Stat" state vector declared above.
  19601. */
  19602. #ifdef SQLITE_OMIT_WSD
  19603. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  19604. # define wsdStat x[0]
  19605. #else
  19606. # define wsdStatInit
  19607. # define wsdStat sqlite3Stat
  19608. #endif
  19609. /*
  19610. ** Return the current value of a status parameter. The caller must
  19611. ** be holding the appropriate mutex.
  19612. */
  19613. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  19614. wsdStatInit;
  19615. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19616. assert( op>=0 && op<ArraySize(statMutex) );
  19617. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19618. : sqlite3MallocMutex()) );
  19619. return wsdStat.nowValue[op];
  19620. }
  19621. /*
  19622. ** Add N to the value of a status record. The caller must hold the
  19623. ** appropriate mutex. (Locking is checked by assert()).
  19624. **
  19625. ** The StatusUp() routine can accept positive or negative values for N.
  19626. ** The value of N is added to the current status value and the high-water
  19627. ** mark is adjusted if necessary.
  19628. **
  19629. ** The StatusDown() routine lowers the current value by N. The highwater
  19630. ** mark is unchanged. N must be non-negative for StatusDown().
  19631. */
  19632. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  19633. wsdStatInit;
  19634. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19635. assert( op>=0 && op<ArraySize(statMutex) );
  19636. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19637. : sqlite3MallocMutex()) );
  19638. wsdStat.nowValue[op] += N;
  19639. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  19640. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  19641. }
  19642. }
  19643. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  19644. wsdStatInit;
  19645. assert( N>=0 );
  19646. assert( op>=0 && op<ArraySize(statMutex) );
  19647. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19648. : sqlite3MallocMutex()) );
  19649. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19650. wsdStat.nowValue[op] -= N;
  19651. }
  19652. /*
  19653. ** Adjust the highwater mark if necessary.
  19654. ** The caller must hold the appropriate mutex.
  19655. */
  19656. SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
  19657. sqlite3StatValueType newValue;
  19658. wsdStatInit;
  19659. assert( X>=0 );
  19660. newValue = (sqlite3StatValueType)X;
  19661. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19662. assert( op>=0 && op<ArraySize(statMutex) );
  19663. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19664. : sqlite3MallocMutex()) );
  19665. assert( op==SQLITE_STATUS_MALLOC_SIZE
  19666. || op==SQLITE_STATUS_PAGECACHE_SIZE
  19667. || op==SQLITE_STATUS_PARSER_STACK );
  19668. if( newValue>wsdStat.mxValue[op] ){
  19669. wsdStat.mxValue[op] = newValue;
  19670. }
  19671. }
  19672. /*
  19673. ** Query status information.
  19674. */
  19675. SQLITE_API int sqlite3_status64(
  19676. int op,
  19677. sqlite3_int64 *pCurrent,
  19678. sqlite3_int64 *pHighwater,
  19679. int resetFlag
  19680. ){
  19681. sqlite3_mutex *pMutex;
  19682. wsdStatInit;
  19683. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  19684. return SQLITE_MISUSE_BKPT;
  19685. }
  19686. #ifdef SQLITE_ENABLE_API_ARMOR
  19687. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  19688. #endif
  19689. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  19690. sqlite3_mutex_enter(pMutex);
  19691. *pCurrent = wsdStat.nowValue[op];
  19692. *pHighwater = wsdStat.mxValue[op];
  19693. if( resetFlag ){
  19694. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  19695. }
  19696. sqlite3_mutex_leave(pMutex);
  19697. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  19698. return SQLITE_OK;
  19699. }
  19700. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  19701. sqlite3_int64 iCur = 0, iHwtr = 0;
  19702. int rc;
  19703. #ifdef SQLITE_ENABLE_API_ARMOR
  19704. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  19705. #endif
  19706. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  19707. if( rc==0 ){
  19708. *pCurrent = (int)iCur;
  19709. *pHighwater = (int)iHwtr;
  19710. }
  19711. return rc;
  19712. }
  19713. /*
  19714. ** Return the number of LookasideSlot elements on the linked list
  19715. */
  19716. static u32 countLookasideSlots(LookasideSlot *p){
  19717. u32 cnt = 0;
  19718. while( p ){
  19719. p = p->pNext;
  19720. cnt++;
  19721. }
  19722. return cnt;
  19723. }
  19724. /*
  19725. ** Count the number of slots of lookaside memory that are outstanding
  19726. */
  19727. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
  19728. u32 nInit = countLookasideSlots(db->lookaside.pInit);
  19729. u32 nFree = countLookasideSlots(db->lookaside.pFree);
  19730. if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
  19731. return db->lookaside.nSlot - (nInit+nFree);
  19732. }
  19733. /*
  19734. ** Query status information for a single database connection
  19735. */
  19736. SQLITE_API int sqlite3_db_status(
  19737. sqlite3 *db, /* The database connection whose status is desired */
  19738. int op, /* Status verb */
  19739. int *pCurrent, /* Write current value here */
  19740. int *pHighwater, /* Write high-water mark here */
  19741. int resetFlag /* Reset high-water mark if true */
  19742. ){
  19743. int rc = SQLITE_OK; /* Return code */
  19744. #ifdef SQLITE_ENABLE_API_ARMOR
  19745. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  19746. return SQLITE_MISUSE_BKPT;
  19747. }
  19748. #endif
  19749. sqlite3_mutex_enter(db->mutex);
  19750. switch( op ){
  19751. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  19752. *pCurrent = sqlite3LookasideUsed(db, pHighwater);
  19753. if( resetFlag ){
  19754. LookasideSlot *p = db->lookaside.pFree;
  19755. if( p ){
  19756. while( p->pNext ) p = p->pNext;
  19757. p->pNext = db->lookaside.pInit;
  19758. db->lookaside.pInit = db->lookaside.pFree;
  19759. db->lookaside.pFree = 0;
  19760. }
  19761. }
  19762. break;
  19763. }
  19764. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  19765. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  19766. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  19767. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  19768. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  19769. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  19770. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  19771. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  19772. *pCurrent = 0;
  19773. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  19774. if( resetFlag ){
  19775. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  19776. }
  19777. break;
  19778. }
  19779. /*
  19780. ** Return an approximation for the amount of memory currently used
  19781. ** by all pagers associated with the given database connection. The
  19782. ** highwater mark is meaningless and is returned as zero.
  19783. */
  19784. case SQLITE_DBSTATUS_CACHE_USED_SHARED:
  19785. case SQLITE_DBSTATUS_CACHE_USED: {
  19786. int totalUsed = 0;
  19787. int i;
  19788. sqlite3BtreeEnterAll(db);
  19789. for(i=0; i<db->nDb; i++){
  19790. Btree *pBt = db->aDb[i].pBt;
  19791. if( pBt ){
  19792. Pager *pPager = sqlite3BtreePager(pBt);
  19793. int nByte = sqlite3PagerMemUsed(pPager);
  19794. if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
  19795. nByte = nByte / sqlite3BtreeConnectionCount(pBt);
  19796. }
  19797. totalUsed += nByte;
  19798. }
  19799. }
  19800. sqlite3BtreeLeaveAll(db);
  19801. *pCurrent = totalUsed;
  19802. *pHighwater = 0;
  19803. break;
  19804. }
  19805. /*
  19806. ** *pCurrent gets an accurate estimate of the amount of memory used
  19807. ** to store the schema for all databases (main, temp, and any ATTACHed
  19808. ** databases. *pHighwater is set to zero.
  19809. */
  19810. case SQLITE_DBSTATUS_SCHEMA_USED: {
  19811. int i; /* Used to iterate through schemas */
  19812. int nByte = 0; /* Used to accumulate return value */
  19813. sqlite3BtreeEnterAll(db);
  19814. db->pnBytesFreed = &nByte;
  19815. for(i=0; i<db->nDb; i++){
  19816. Schema *pSchema = db->aDb[i].pSchema;
  19817. if( ALWAYS(pSchema!=0) ){
  19818. HashElem *p;
  19819. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  19820. pSchema->tblHash.count
  19821. + pSchema->trigHash.count
  19822. + pSchema->idxHash.count
  19823. + pSchema->fkeyHash.count
  19824. );
  19825. nByte += sqlite3_msize(pSchema->tblHash.ht);
  19826. nByte += sqlite3_msize(pSchema->trigHash.ht);
  19827. nByte += sqlite3_msize(pSchema->idxHash.ht);
  19828. nByte += sqlite3_msize(pSchema->fkeyHash.ht);
  19829. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  19830. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  19831. }
  19832. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  19833. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  19834. }
  19835. }
  19836. }
  19837. db->pnBytesFreed = 0;
  19838. sqlite3BtreeLeaveAll(db);
  19839. *pHighwater = 0;
  19840. *pCurrent = nByte;
  19841. break;
  19842. }
  19843. /*
  19844. ** *pCurrent gets an accurate estimate of the amount of memory used
  19845. ** to store all prepared statements.
  19846. ** *pHighwater is set to zero.
  19847. */
  19848. case SQLITE_DBSTATUS_STMT_USED: {
  19849. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  19850. int nByte = 0; /* Used to accumulate return value */
  19851. db->pnBytesFreed = &nByte;
  19852. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  19853. sqlite3VdbeClearObject(db, pVdbe);
  19854. sqlite3DbFree(db, pVdbe);
  19855. }
  19856. db->pnBytesFreed = 0;
  19857. *pHighwater = 0; /* IMP: R-64479-57858 */
  19858. *pCurrent = nByte;
  19859. break;
  19860. }
  19861. /*
  19862. ** Set *pCurrent to the total cache hits or misses encountered by all
  19863. ** pagers the database handle is connected to. *pHighwater is always set
  19864. ** to zero.
  19865. */
  19866. case SQLITE_DBSTATUS_CACHE_SPILL:
  19867. op = SQLITE_DBSTATUS_CACHE_WRITE+1;
  19868. /* Fall through into the next case */
  19869. case SQLITE_DBSTATUS_CACHE_HIT:
  19870. case SQLITE_DBSTATUS_CACHE_MISS:
  19871. case SQLITE_DBSTATUS_CACHE_WRITE:{
  19872. int i;
  19873. int nRet = 0;
  19874. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  19875. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  19876. for(i=0; i<db->nDb; i++){
  19877. if( db->aDb[i].pBt ){
  19878. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  19879. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  19880. }
  19881. }
  19882. *pHighwater = 0; /* IMP: R-42420-56072 */
  19883. /* IMP: R-54100-20147 */
  19884. /* IMP: R-29431-39229 */
  19885. *pCurrent = nRet;
  19886. break;
  19887. }
  19888. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  19889. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  19890. ** have been satisfied. The *pHighwater is always set to zero.
  19891. */
  19892. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  19893. *pHighwater = 0; /* IMP: R-11967-56545 */
  19894. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  19895. break;
  19896. }
  19897. default: {
  19898. rc = SQLITE_ERROR;
  19899. }
  19900. }
  19901. sqlite3_mutex_leave(db->mutex);
  19902. return rc;
  19903. }
  19904. /************** End of status.c **********************************************/
  19905. /************** Begin file date.c ********************************************/
  19906. /*
  19907. ** 2003 October 31
  19908. **
  19909. ** The author disclaims copyright to this source code. In place of
  19910. ** a legal notice, here is a blessing:
  19911. **
  19912. ** May you do good and not evil.
  19913. ** May you find forgiveness for yourself and forgive others.
  19914. ** May you share freely, never taking more than you give.
  19915. **
  19916. *************************************************************************
  19917. ** This file contains the C functions that implement date and time
  19918. ** functions for SQLite.
  19919. **
  19920. ** There is only one exported symbol in this file - the function
  19921. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  19922. ** All other code has file scope.
  19923. **
  19924. ** SQLite processes all times and dates as julian day numbers. The
  19925. ** dates and times are stored as the number of days since noon
  19926. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  19927. ** calendar system.
  19928. **
  19929. ** 1970-01-01 00:00:00 is JD 2440587.5
  19930. ** 2000-01-01 00:00:00 is JD 2451544.5
  19931. **
  19932. ** This implementation requires years to be expressed as a 4-digit number
  19933. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  19934. ** be represented, even though julian day numbers allow a much wider
  19935. ** range of dates.
  19936. **
  19937. ** The Gregorian calendar system is used for all dates and times,
  19938. ** even those that predate the Gregorian calendar. Historians usually
  19939. ** use the julian calendar for dates prior to 1582-10-15 and for some
  19940. ** dates afterwards, depending on locale. Beware of this difference.
  19941. **
  19942. ** The conversion algorithms are implemented based on descriptions
  19943. ** in the following text:
  19944. **
  19945. ** Jean Meeus
  19946. ** Astronomical Algorithms, 2nd Edition, 1998
  19947. ** ISBN 0-943396-61-1
  19948. ** Willmann-Bell, Inc
  19949. ** Richmond, Virginia (USA)
  19950. */
  19951. /* #include "sqliteInt.h" */
  19952. /* #include <stdlib.h> */
  19953. /* #include <assert.h> */
  19954. #include <time.h>
  19955. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  19956. /*
  19957. ** The MSVC CRT on Windows CE may not have a localtime() function.
  19958. ** So declare a substitute. The substitute function itself is
  19959. ** defined in "os_win.c".
  19960. */
  19961. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  19962. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  19963. struct tm *__cdecl localtime(const time_t *);
  19964. #endif
  19965. /*
  19966. ** A structure for holding a single date and time.
  19967. */
  19968. typedef struct DateTime DateTime;
  19969. struct DateTime {
  19970. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  19971. int Y, M, D; /* Year, month, and day */
  19972. int h, m; /* Hour and minutes */
  19973. int tz; /* Timezone offset in minutes */
  19974. double s; /* Seconds */
  19975. char validJD; /* True (1) if iJD is valid */
  19976. char rawS; /* Raw numeric value stored in s */
  19977. char validYMD; /* True (1) if Y,M,D are valid */
  19978. char validHMS; /* True (1) if h,m,s are valid */
  19979. char validTZ; /* True (1) if tz is valid */
  19980. char tzSet; /* Timezone was set explicitly */
  19981. char isError; /* An overflow has occurred */
  19982. };
  19983. /*
  19984. ** Convert zDate into one or more integers according to the conversion
  19985. ** specifier zFormat.
  19986. **
  19987. ** zFormat[] contains 4 characters for each integer converted, except for
  19988. ** the last integer which is specified by three characters. The meaning
  19989. ** of a four-character format specifiers ABCD is:
  19990. **
  19991. ** A: number of digits to convert. Always "2" or "4".
  19992. ** B: minimum value. Always "0" or "1".
  19993. ** C: maximum value, decoded as:
  19994. ** a: 12
  19995. ** b: 14
  19996. ** c: 24
  19997. ** d: 31
  19998. ** e: 59
  19999. ** f: 9999
  20000. ** D: the separator character, or \000 to indicate this is the
  20001. ** last number to convert.
  20002. **
  20003. ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
  20004. ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
  20005. ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
  20006. ** the 2-digit day which is the last integer in the set.
  20007. **
  20008. ** The function returns the number of successful conversions.
  20009. */
  20010. static int getDigits(const char *zDate, const char *zFormat, ...){
  20011. /* The aMx[] array translates the 3rd character of each format
  20012. ** spec into a max size: a b c d e f */
  20013. static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
  20014. va_list ap;
  20015. int cnt = 0;
  20016. char nextC;
  20017. va_start(ap, zFormat);
  20018. do{
  20019. char N = zFormat[0] - '0';
  20020. char min = zFormat[1] - '0';
  20021. int val = 0;
  20022. u16 max;
  20023. assert( zFormat[2]>='a' && zFormat[2]<='f' );
  20024. max = aMx[zFormat[2] - 'a'];
  20025. nextC = zFormat[3];
  20026. val = 0;
  20027. while( N-- ){
  20028. if( !sqlite3Isdigit(*zDate) ){
  20029. goto end_getDigits;
  20030. }
  20031. val = val*10 + *zDate - '0';
  20032. zDate++;
  20033. }
  20034. if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
  20035. goto end_getDigits;
  20036. }
  20037. *va_arg(ap,int*) = val;
  20038. zDate++;
  20039. cnt++;
  20040. zFormat += 4;
  20041. }while( nextC );
  20042. end_getDigits:
  20043. va_end(ap);
  20044. return cnt;
  20045. }
  20046. /*
  20047. ** Parse a timezone extension on the end of a date-time.
  20048. ** The extension is of the form:
  20049. **
  20050. ** (+/-)HH:MM
  20051. **
  20052. ** Or the "zulu" notation:
  20053. **
  20054. ** Z
  20055. **
  20056. ** If the parse is successful, write the number of minutes
  20057. ** of change in p->tz and return 0. If a parser error occurs,
  20058. ** return non-zero.
  20059. **
  20060. ** A missing specifier is not considered an error.
  20061. */
  20062. static int parseTimezone(const char *zDate, DateTime *p){
  20063. int sgn = 0;
  20064. int nHr, nMn;
  20065. int c;
  20066. while( sqlite3Isspace(*zDate) ){ zDate++; }
  20067. p->tz = 0;
  20068. c = *zDate;
  20069. if( c=='-' ){
  20070. sgn = -1;
  20071. }else if( c=='+' ){
  20072. sgn = +1;
  20073. }else if( c=='Z' || c=='z' ){
  20074. zDate++;
  20075. goto zulu_time;
  20076. }else{
  20077. return c!=0;
  20078. }
  20079. zDate++;
  20080. if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
  20081. return 1;
  20082. }
  20083. zDate += 5;
  20084. p->tz = sgn*(nMn + nHr*60);
  20085. zulu_time:
  20086. while( sqlite3Isspace(*zDate) ){ zDate++; }
  20087. p->tzSet = 1;
  20088. return *zDate!=0;
  20089. }
  20090. /*
  20091. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  20092. ** The HH, MM, and SS must each be exactly 2 digits. The
  20093. ** fractional seconds FFFF can be one or more digits.
  20094. **
  20095. ** Return 1 if there is a parsing error and 0 on success.
  20096. */
  20097. static int parseHhMmSs(const char *zDate, DateTime *p){
  20098. int h, m, s;
  20099. double ms = 0.0;
  20100. if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
  20101. return 1;
  20102. }
  20103. zDate += 5;
  20104. if( *zDate==':' ){
  20105. zDate++;
  20106. if( getDigits(zDate, "20e", &s)!=1 ){
  20107. return 1;
  20108. }
  20109. zDate += 2;
  20110. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  20111. double rScale = 1.0;
  20112. zDate++;
  20113. while( sqlite3Isdigit(*zDate) ){
  20114. ms = ms*10.0 + *zDate - '0';
  20115. rScale *= 10.0;
  20116. zDate++;
  20117. }
  20118. ms /= rScale;
  20119. }
  20120. }else{
  20121. s = 0;
  20122. }
  20123. p->validJD = 0;
  20124. p->rawS = 0;
  20125. p->validHMS = 1;
  20126. p->h = h;
  20127. p->m = m;
  20128. p->s = s + ms;
  20129. if( parseTimezone(zDate, p) ) return 1;
  20130. p->validTZ = (p->tz!=0)?1:0;
  20131. return 0;
  20132. }
  20133. /*
  20134. ** Put the DateTime object into its error state.
  20135. */
  20136. static void datetimeError(DateTime *p){
  20137. memset(p, 0, sizeof(*p));
  20138. p->isError = 1;
  20139. }
  20140. /*
  20141. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  20142. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  20143. **
  20144. ** Reference: Meeus page 61
  20145. */
  20146. static void computeJD(DateTime *p){
  20147. int Y, M, D, A, B, X1, X2;
  20148. if( p->validJD ) return;
  20149. if( p->validYMD ){
  20150. Y = p->Y;
  20151. M = p->M;
  20152. D = p->D;
  20153. }else{
  20154. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  20155. M = 1;
  20156. D = 1;
  20157. }
  20158. if( Y<-4713 || Y>9999 || p->rawS ){
  20159. datetimeError(p);
  20160. return;
  20161. }
  20162. if( M<=2 ){
  20163. Y--;
  20164. M += 12;
  20165. }
  20166. A = Y/100;
  20167. B = 2 - A + (A/4);
  20168. X1 = 36525*(Y+4716)/100;
  20169. X2 = 306001*(M+1)/10000;
  20170. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  20171. p->validJD = 1;
  20172. if( p->validHMS ){
  20173. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  20174. if( p->validTZ ){
  20175. p->iJD -= p->tz*60000;
  20176. p->validYMD = 0;
  20177. p->validHMS = 0;
  20178. p->validTZ = 0;
  20179. }
  20180. }
  20181. }
  20182. /*
  20183. ** Parse dates of the form
  20184. **
  20185. ** YYYY-MM-DD HH:MM:SS.FFF
  20186. ** YYYY-MM-DD HH:MM:SS
  20187. ** YYYY-MM-DD HH:MM
  20188. ** YYYY-MM-DD
  20189. **
  20190. ** Write the result into the DateTime structure and return 0
  20191. ** on success and 1 if the input string is not a well-formed
  20192. ** date.
  20193. */
  20194. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  20195. int Y, M, D, neg;
  20196. if( zDate[0]=='-' ){
  20197. zDate++;
  20198. neg = 1;
  20199. }else{
  20200. neg = 0;
  20201. }
  20202. if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
  20203. return 1;
  20204. }
  20205. zDate += 10;
  20206. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  20207. if( parseHhMmSs(zDate, p)==0 ){
  20208. /* We got the time */
  20209. }else if( *zDate==0 ){
  20210. p->validHMS = 0;
  20211. }else{
  20212. return 1;
  20213. }
  20214. p->validJD = 0;
  20215. p->validYMD = 1;
  20216. p->Y = neg ? -Y : Y;
  20217. p->M = M;
  20218. p->D = D;
  20219. if( p->validTZ ){
  20220. computeJD(p);
  20221. }
  20222. return 0;
  20223. }
  20224. /*
  20225. ** Set the time to the current time reported by the VFS.
  20226. **
  20227. ** Return the number of errors.
  20228. */
  20229. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  20230. p->iJD = sqlite3StmtCurrentTime(context);
  20231. if( p->iJD>0 ){
  20232. p->validJD = 1;
  20233. return 0;
  20234. }else{
  20235. return 1;
  20236. }
  20237. }
  20238. /*
  20239. ** Input "r" is a numeric quantity which might be a julian day number,
  20240. ** or the number of seconds since 1970. If the value if r is within
  20241. ** range of a julian day number, install it as such and set validJD.
  20242. ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
  20243. */
  20244. static void setRawDateNumber(DateTime *p, double r){
  20245. p->s = r;
  20246. p->rawS = 1;
  20247. if( r>=0.0 && r<5373484.5 ){
  20248. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  20249. p->validJD = 1;
  20250. }
  20251. }
  20252. /*
  20253. ** Attempt to parse the given string into a julian day number. Return
  20254. ** the number of errors.
  20255. **
  20256. ** The following are acceptable forms for the input string:
  20257. **
  20258. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  20259. ** DDDD.DD
  20260. ** now
  20261. **
  20262. ** In the first form, the +/-HH:MM is always optional. The fractional
  20263. ** seconds extension (the ".FFF") is optional. The seconds portion
  20264. ** (":SS.FFF") is option. The year and date can be omitted as long
  20265. ** as there is a time string. The time string can be omitted as long
  20266. ** as there is a year and date.
  20267. */
  20268. static int parseDateOrTime(
  20269. sqlite3_context *context,
  20270. const char *zDate,
  20271. DateTime *p
  20272. ){
  20273. double r;
  20274. if( parseYyyyMmDd(zDate,p)==0 ){
  20275. return 0;
  20276. }else if( parseHhMmSs(zDate, p)==0 ){
  20277. return 0;
  20278. }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
  20279. return setDateTimeToCurrent(context, p);
  20280. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  20281. setRawDateNumber(p, r);
  20282. return 0;
  20283. }
  20284. return 1;
  20285. }
  20286. /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
  20287. ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
  20288. ** for DateTime.iJD.
  20289. **
  20290. ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
  20291. ** such a large integer literal, so we have to encode it.
  20292. */
  20293. #define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
  20294. /*
  20295. ** Return TRUE if the given julian day number is within range.
  20296. **
  20297. ** The input is the JulianDay times 86400000.
  20298. */
  20299. static int validJulianDay(sqlite3_int64 iJD){
  20300. return iJD>=0 && iJD<=INT_464269060799999;
  20301. }
  20302. /*
  20303. ** Compute the Year, Month, and Day from the julian day number.
  20304. */
  20305. static void computeYMD(DateTime *p){
  20306. int Z, A, B, C, D, E, X1;
  20307. if( p->validYMD ) return;
  20308. if( !p->validJD ){
  20309. p->Y = 2000;
  20310. p->M = 1;
  20311. p->D = 1;
  20312. }else if( !validJulianDay(p->iJD) ){
  20313. datetimeError(p);
  20314. return;
  20315. }else{
  20316. Z = (int)((p->iJD + 43200000)/86400000);
  20317. A = (int)((Z - 1867216.25)/36524.25);
  20318. A = Z + 1 + A - (A/4);
  20319. B = A + 1524;
  20320. C = (int)((B - 122.1)/365.25);
  20321. D = (36525*(C&32767))/100;
  20322. E = (int)((B-D)/30.6001);
  20323. X1 = (int)(30.6001*E);
  20324. p->D = B - D - X1;
  20325. p->M = E<14 ? E-1 : E-13;
  20326. p->Y = p->M>2 ? C - 4716 : C - 4715;
  20327. }
  20328. p->validYMD = 1;
  20329. }
  20330. /*
  20331. ** Compute the Hour, Minute, and Seconds from the julian day number.
  20332. */
  20333. static void computeHMS(DateTime *p){
  20334. int s;
  20335. if( p->validHMS ) return;
  20336. computeJD(p);
  20337. s = (int)((p->iJD + 43200000) % 86400000);
  20338. p->s = s/1000.0;
  20339. s = (int)p->s;
  20340. p->s -= s;
  20341. p->h = s/3600;
  20342. s -= p->h*3600;
  20343. p->m = s/60;
  20344. p->s += s - p->m*60;
  20345. p->rawS = 0;
  20346. p->validHMS = 1;
  20347. }
  20348. /*
  20349. ** Compute both YMD and HMS
  20350. */
  20351. static void computeYMD_HMS(DateTime *p){
  20352. computeYMD(p);
  20353. computeHMS(p);
  20354. }
  20355. /*
  20356. ** Clear the YMD and HMS and the TZ
  20357. */
  20358. static void clearYMD_HMS_TZ(DateTime *p){
  20359. p->validYMD = 0;
  20360. p->validHMS = 0;
  20361. p->validTZ = 0;
  20362. }
  20363. #ifndef SQLITE_OMIT_LOCALTIME
  20364. /*
  20365. ** On recent Windows platforms, the localtime_s() function is available
  20366. ** as part of the "Secure CRT". It is essentially equivalent to
  20367. ** localtime_r() available under most POSIX platforms, except that the
  20368. ** order of the parameters is reversed.
  20369. **
  20370. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  20371. **
  20372. ** If the user has not indicated to use localtime_r() or localtime_s()
  20373. ** already, check for an MSVC build environment that provides
  20374. ** localtime_s().
  20375. */
  20376. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  20377. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  20378. #undef HAVE_LOCALTIME_S
  20379. #define HAVE_LOCALTIME_S 1
  20380. #endif
  20381. /*
  20382. ** The following routine implements the rough equivalent of localtime_r()
  20383. ** using whatever operating-system specific localtime facility that
  20384. ** is available. This routine returns 0 on success and
  20385. ** non-zero on any kind of error.
  20386. **
  20387. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  20388. ** routine will always fail.
  20389. **
  20390. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  20391. ** library function localtime_r() is used to assist in the calculation of
  20392. ** local time.
  20393. */
  20394. static int osLocaltime(time_t *t, struct tm *pTm){
  20395. int rc;
  20396. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  20397. struct tm *pX;
  20398. #if SQLITE_THREADSAFE>0
  20399. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  20400. #endif
  20401. sqlite3_mutex_enter(mutex);
  20402. pX = localtime(t);
  20403. #ifndef SQLITE_UNTESTABLE
  20404. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  20405. #endif
  20406. if( pX ) *pTm = *pX;
  20407. sqlite3_mutex_leave(mutex);
  20408. rc = pX==0;
  20409. #else
  20410. #ifndef SQLITE_UNTESTABLE
  20411. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  20412. #endif
  20413. #if HAVE_LOCALTIME_R
  20414. rc = localtime_r(t, pTm)==0;
  20415. #else
  20416. rc = localtime_s(pTm, t);
  20417. #endif /* HAVE_LOCALTIME_R */
  20418. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  20419. return rc;
  20420. }
  20421. #endif /* SQLITE_OMIT_LOCALTIME */
  20422. #ifndef SQLITE_OMIT_LOCALTIME
  20423. /*
  20424. ** Compute the difference (in milliseconds) between localtime and UTC
  20425. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  20426. ** return this value and set *pRc to SQLITE_OK.
  20427. **
  20428. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  20429. ** is undefined in this case.
  20430. */
  20431. static sqlite3_int64 localtimeOffset(
  20432. DateTime *p, /* Date at which to calculate offset */
  20433. sqlite3_context *pCtx, /* Write error here if one occurs */
  20434. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  20435. ){
  20436. DateTime x, y;
  20437. time_t t;
  20438. struct tm sLocal;
  20439. /* Initialize the contents of sLocal to avoid a compiler warning. */
  20440. memset(&sLocal, 0, sizeof(sLocal));
  20441. x = *p;
  20442. computeYMD_HMS(&x);
  20443. if( x.Y<1971 || x.Y>=2038 ){
  20444. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  20445. ** works for years between 1970 and 2037. For dates outside this range,
  20446. ** SQLite attempts to map the year into an equivalent year within this
  20447. ** range, do the calculation, then map the year back.
  20448. */
  20449. x.Y = 2000;
  20450. x.M = 1;
  20451. x.D = 1;
  20452. x.h = 0;
  20453. x.m = 0;
  20454. x.s = 0.0;
  20455. } else {
  20456. int s = (int)(x.s + 0.5);
  20457. x.s = s;
  20458. }
  20459. x.tz = 0;
  20460. x.validJD = 0;
  20461. computeJD(&x);
  20462. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  20463. if( osLocaltime(&t, &sLocal) ){
  20464. sqlite3_result_error(pCtx, "local time unavailable", -1);
  20465. *pRc = SQLITE_ERROR;
  20466. return 0;
  20467. }
  20468. y.Y = sLocal.tm_year + 1900;
  20469. y.M = sLocal.tm_mon + 1;
  20470. y.D = sLocal.tm_mday;
  20471. y.h = sLocal.tm_hour;
  20472. y.m = sLocal.tm_min;
  20473. y.s = sLocal.tm_sec;
  20474. y.validYMD = 1;
  20475. y.validHMS = 1;
  20476. y.validJD = 0;
  20477. y.rawS = 0;
  20478. y.validTZ = 0;
  20479. y.isError = 0;
  20480. computeJD(&y);
  20481. *pRc = SQLITE_OK;
  20482. return y.iJD - x.iJD;
  20483. }
  20484. #endif /* SQLITE_OMIT_LOCALTIME */
  20485. /*
  20486. ** The following table defines various date transformations of the form
  20487. **
  20488. ** 'NNN days'
  20489. **
  20490. ** Where NNN is an arbitrary floating-point number and "days" can be one
  20491. ** of several units of time.
  20492. */
  20493. static const struct {
  20494. u8 eType; /* Transformation type code */
  20495. u8 nName; /* Length of th name */
  20496. char *zName; /* Name of the transformation */
  20497. double rLimit; /* Maximum NNN value for this transform */
  20498. double rXform; /* Constant used for this transform */
  20499. } aXformType[] = {
  20500. { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
  20501. { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) },
  20502. { 0, 4, "hour", 128963628.0, 86400000.0/24.0 },
  20503. { 0, 3, "day", 5373485.0, 86400000.0 },
  20504. { 1, 5, "month", 176546.0, 30.0*86400000.0 },
  20505. { 2, 4, "year", 14713.0, 365.0*86400000.0 },
  20506. };
  20507. /*
  20508. ** Process a modifier to a date-time stamp. The modifiers are
  20509. ** as follows:
  20510. **
  20511. ** NNN days
  20512. ** NNN hours
  20513. ** NNN minutes
  20514. ** NNN.NNNN seconds
  20515. ** NNN months
  20516. ** NNN years
  20517. ** start of month
  20518. ** start of year
  20519. ** start of week
  20520. ** start of day
  20521. ** weekday N
  20522. ** unixepoch
  20523. ** localtime
  20524. ** utc
  20525. **
  20526. ** Return 0 on success and 1 if there is any kind of error. If the error
  20527. ** is in a system call (i.e. localtime()), then an error message is written
  20528. ** to context pCtx. If the error is an unrecognized modifier, no error is
  20529. ** written to pCtx.
  20530. */
  20531. static int parseModifier(
  20532. sqlite3_context *pCtx, /* Function context */
  20533. const char *z, /* The text of the modifier */
  20534. int n, /* Length of zMod in bytes */
  20535. DateTime *p /* The date/time value to be modified */
  20536. ){
  20537. int rc = 1;
  20538. double r;
  20539. switch(sqlite3UpperToLower[(u8)z[0]] ){
  20540. #ifndef SQLITE_OMIT_LOCALTIME
  20541. case 'l': {
  20542. /* localtime
  20543. **
  20544. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  20545. ** show local time.
  20546. */
  20547. if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
  20548. computeJD(p);
  20549. p->iJD += localtimeOffset(p, pCtx, &rc);
  20550. clearYMD_HMS_TZ(p);
  20551. }
  20552. break;
  20553. }
  20554. #endif
  20555. case 'u': {
  20556. /*
  20557. ** unixepoch
  20558. **
  20559. ** Treat the current value of p->s as the number of
  20560. ** seconds since 1970. Convert to a real julian day number.
  20561. */
  20562. if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
  20563. r = p->s*1000.0 + 210866760000000.0;
  20564. if( r>=0.0 && r<464269060800000.0 ){
  20565. clearYMD_HMS_TZ(p);
  20566. p->iJD = (sqlite3_int64)r;
  20567. p->validJD = 1;
  20568. p->rawS = 0;
  20569. rc = 0;
  20570. }
  20571. }
  20572. #ifndef SQLITE_OMIT_LOCALTIME
  20573. else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
  20574. if( p->tzSet==0 ){
  20575. sqlite3_int64 c1;
  20576. computeJD(p);
  20577. c1 = localtimeOffset(p, pCtx, &rc);
  20578. if( rc==SQLITE_OK ){
  20579. p->iJD -= c1;
  20580. clearYMD_HMS_TZ(p);
  20581. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  20582. }
  20583. p->tzSet = 1;
  20584. }else{
  20585. rc = SQLITE_OK;
  20586. }
  20587. }
  20588. #endif
  20589. break;
  20590. }
  20591. case 'w': {
  20592. /*
  20593. ** weekday N
  20594. **
  20595. ** Move the date to the same time on the next occurrence of
  20596. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  20597. ** date is already on the appropriate weekday, this is a no-op.
  20598. */
  20599. if( sqlite3_strnicmp(z, "weekday ", 8)==0
  20600. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  20601. && (n=(int)r)==r && n>=0 && r<7 ){
  20602. sqlite3_int64 Z;
  20603. computeYMD_HMS(p);
  20604. p->validTZ = 0;
  20605. p->validJD = 0;
  20606. computeJD(p);
  20607. Z = ((p->iJD + 129600000)/86400000) % 7;
  20608. if( Z>n ) Z -= 7;
  20609. p->iJD += (n - Z)*86400000;
  20610. clearYMD_HMS_TZ(p);
  20611. rc = 0;
  20612. }
  20613. break;
  20614. }
  20615. case 's': {
  20616. /*
  20617. ** start of TTTTT
  20618. **
  20619. ** Move the date backwards to the beginning of the current day,
  20620. ** or month or year.
  20621. */
  20622. if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
  20623. if( !p->validJD && !p->validYMD && !p->validHMS ) break;
  20624. z += 9;
  20625. computeYMD(p);
  20626. p->validHMS = 1;
  20627. p->h = p->m = 0;
  20628. p->s = 0.0;
  20629. p->rawS = 0;
  20630. p->validTZ = 0;
  20631. p->validJD = 0;
  20632. if( sqlite3_stricmp(z,"month")==0 ){
  20633. p->D = 1;
  20634. rc = 0;
  20635. }else if( sqlite3_stricmp(z,"year")==0 ){
  20636. p->M = 1;
  20637. p->D = 1;
  20638. rc = 0;
  20639. }else if( sqlite3_stricmp(z,"day")==0 ){
  20640. rc = 0;
  20641. }
  20642. break;
  20643. }
  20644. case '+':
  20645. case '-':
  20646. case '0':
  20647. case '1':
  20648. case '2':
  20649. case '3':
  20650. case '4':
  20651. case '5':
  20652. case '6':
  20653. case '7':
  20654. case '8':
  20655. case '9': {
  20656. double rRounder;
  20657. int i;
  20658. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  20659. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  20660. rc = 1;
  20661. break;
  20662. }
  20663. if( z[n]==':' ){
  20664. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  20665. ** specified number of hours, minutes, seconds, and fractional seconds
  20666. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  20667. ** omitted.
  20668. */
  20669. const char *z2 = z;
  20670. DateTime tx;
  20671. sqlite3_int64 day;
  20672. if( !sqlite3Isdigit(*z2) ) z2++;
  20673. memset(&tx, 0, sizeof(tx));
  20674. if( parseHhMmSs(z2, &tx) ) break;
  20675. computeJD(&tx);
  20676. tx.iJD -= 43200000;
  20677. day = tx.iJD/86400000;
  20678. tx.iJD -= day*86400000;
  20679. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  20680. computeJD(p);
  20681. clearYMD_HMS_TZ(p);
  20682. p->iJD += tx.iJD;
  20683. rc = 0;
  20684. break;
  20685. }
  20686. /* If control reaches this point, it means the transformation is
  20687. ** one of the forms like "+NNN days". */
  20688. z += n;
  20689. while( sqlite3Isspace(*z) ) z++;
  20690. n = sqlite3Strlen30(z);
  20691. if( n>10 || n<3 ) break;
  20692. if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
  20693. computeJD(p);
  20694. rc = 1;
  20695. rRounder = r<0 ? -0.5 : +0.5;
  20696. for(i=0; i<ArraySize(aXformType); i++){
  20697. if( aXformType[i].nName==n
  20698. && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
  20699. && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
  20700. ){
  20701. switch( aXformType[i].eType ){
  20702. case 1: { /* Special processing to add months */
  20703. int x;
  20704. computeYMD_HMS(p);
  20705. p->M += (int)r;
  20706. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  20707. p->Y += x;
  20708. p->M -= x*12;
  20709. p->validJD = 0;
  20710. r -= (int)r;
  20711. break;
  20712. }
  20713. case 2: { /* Special processing to add years */
  20714. int y = (int)r;
  20715. computeYMD_HMS(p);
  20716. p->Y += y;
  20717. p->validJD = 0;
  20718. r -= (int)r;
  20719. break;
  20720. }
  20721. }
  20722. computeJD(p);
  20723. p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
  20724. rc = 0;
  20725. break;
  20726. }
  20727. }
  20728. clearYMD_HMS_TZ(p);
  20729. break;
  20730. }
  20731. default: {
  20732. break;
  20733. }
  20734. }
  20735. return rc;
  20736. }
  20737. /*
  20738. ** Process time function arguments. argv[0] is a date-time stamp.
  20739. ** argv[1] and following are modifiers. Parse them all and write
  20740. ** the resulting time into the DateTime structure p. Return 0
  20741. ** on success and 1 if there are any errors.
  20742. **
  20743. ** If there are zero parameters (if even argv[0] is undefined)
  20744. ** then assume a default value of "now" for argv[0].
  20745. */
  20746. static int isDate(
  20747. sqlite3_context *context,
  20748. int argc,
  20749. sqlite3_value **argv,
  20750. DateTime *p
  20751. ){
  20752. int i, n;
  20753. const unsigned char *z;
  20754. int eType;
  20755. memset(p, 0, sizeof(*p));
  20756. if( argc==0 ){
  20757. return setDateTimeToCurrent(context, p);
  20758. }
  20759. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  20760. || eType==SQLITE_INTEGER ){
  20761. setRawDateNumber(p, sqlite3_value_double(argv[0]));
  20762. }else{
  20763. z = sqlite3_value_text(argv[0]);
  20764. if( !z || parseDateOrTime(context, (char*)z, p) ){
  20765. return 1;
  20766. }
  20767. }
  20768. for(i=1; i<argc; i++){
  20769. z = sqlite3_value_text(argv[i]);
  20770. n = sqlite3_value_bytes(argv[i]);
  20771. if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
  20772. }
  20773. computeJD(p);
  20774. if( p->isError || !validJulianDay(p->iJD) ) return 1;
  20775. return 0;
  20776. }
  20777. /*
  20778. ** The following routines implement the various date and time functions
  20779. ** of SQLite.
  20780. */
  20781. /*
  20782. ** julianday( TIMESTRING, MOD, MOD, ...)
  20783. **
  20784. ** Return the julian day number of the date specified in the arguments
  20785. */
  20786. static void juliandayFunc(
  20787. sqlite3_context *context,
  20788. int argc,
  20789. sqlite3_value **argv
  20790. ){
  20791. DateTime x;
  20792. if( isDate(context, argc, argv, &x)==0 ){
  20793. computeJD(&x);
  20794. sqlite3_result_double(context, x.iJD/86400000.0);
  20795. }
  20796. }
  20797. /*
  20798. ** datetime( TIMESTRING, MOD, MOD, ...)
  20799. **
  20800. ** Return YYYY-MM-DD HH:MM:SS
  20801. */
  20802. static void datetimeFunc(
  20803. sqlite3_context *context,
  20804. int argc,
  20805. sqlite3_value **argv
  20806. ){
  20807. DateTime x;
  20808. if( isDate(context, argc, argv, &x)==0 ){
  20809. char zBuf[100];
  20810. computeYMD_HMS(&x);
  20811. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  20812. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  20813. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20814. }
  20815. }
  20816. /*
  20817. ** time( TIMESTRING, MOD, MOD, ...)
  20818. **
  20819. ** Return HH:MM:SS
  20820. */
  20821. static void timeFunc(
  20822. sqlite3_context *context,
  20823. int argc,
  20824. sqlite3_value **argv
  20825. ){
  20826. DateTime x;
  20827. if( isDate(context, argc, argv, &x)==0 ){
  20828. char zBuf[100];
  20829. computeHMS(&x);
  20830. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  20831. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20832. }
  20833. }
  20834. /*
  20835. ** date( TIMESTRING, MOD, MOD, ...)
  20836. **
  20837. ** Return YYYY-MM-DD
  20838. */
  20839. static void dateFunc(
  20840. sqlite3_context *context,
  20841. int argc,
  20842. sqlite3_value **argv
  20843. ){
  20844. DateTime x;
  20845. if( isDate(context, argc, argv, &x)==0 ){
  20846. char zBuf[100];
  20847. computeYMD(&x);
  20848. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  20849. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20850. }
  20851. }
  20852. /*
  20853. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  20854. **
  20855. ** Return a string described by FORMAT. Conversions as follows:
  20856. **
  20857. ** %d day of month
  20858. ** %f ** fractional seconds SS.SSS
  20859. ** %H hour 00-24
  20860. ** %j day of year 000-366
  20861. ** %J ** julian day number
  20862. ** %m month 01-12
  20863. ** %M minute 00-59
  20864. ** %s seconds since 1970-01-01
  20865. ** %S seconds 00-59
  20866. ** %w day of week 0-6 sunday==0
  20867. ** %W week of year 00-53
  20868. ** %Y year 0000-9999
  20869. ** %% %
  20870. */
  20871. static void strftimeFunc(
  20872. sqlite3_context *context,
  20873. int argc,
  20874. sqlite3_value **argv
  20875. ){
  20876. DateTime x;
  20877. u64 n;
  20878. size_t i,j;
  20879. char *z;
  20880. sqlite3 *db;
  20881. const char *zFmt;
  20882. char zBuf[100];
  20883. if( argc==0 ) return;
  20884. zFmt = (const char*)sqlite3_value_text(argv[0]);
  20885. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  20886. db = sqlite3_context_db_handle(context);
  20887. for(i=0, n=1; zFmt[i]; i++, n++){
  20888. if( zFmt[i]=='%' ){
  20889. switch( zFmt[i+1] ){
  20890. case 'd':
  20891. case 'H':
  20892. case 'm':
  20893. case 'M':
  20894. case 'S':
  20895. case 'W':
  20896. n++;
  20897. /* fall thru */
  20898. case 'w':
  20899. case '%':
  20900. break;
  20901. case 'f':
  20902. n += 8;
  20903. break;
  20904. case 'j':
  20905. n += 3;
  20906. break;
  20907. case 'Y':
  20908. n += 8;
  20909. break;
  20910. case 's':
  20911. case 'J':
  20912. n += 50;
  20913. break;
  20914. default:
  20915. return; /* ERROR. return a NULL */
  20916. }
  20917. i++;
  20918. }
  20919. }
  20920. testcase( n==sizeof(zBuf)-1 );
  20921. testcase( n==sizeof(zBuf) );
  20922. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  20923. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  20924. if( n<sizeof(zBuf) ){
  20925. z = zBuf;
  20926. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  20927. sqlite3_result_error_toobig(context);
  20928. return;
  20929. }else{
  20930. z = sqlite3DbMallocRawNN(db, (int)n);
  20931. if( z==0 ){
  20932. sqlite3_result_error_nomem(context);
  20933. return;
  20934. }
  20935. }
  20936. computeJD(&x);
  20937. computeYMD_HMS(&x);
  20938. for(i=j=0; zFmt[i]; i++){
  20939. if( zFmt[i]!='%' ){
  20940. z[j++] = zFmt[i];
  20941. }else{
  20942. i++;
  20943. switch( zFmt[i] ){
  20944. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  20945. case 'f': {
  20946. double s = x.s;
  20947. if( s>59.999 ) s = 59.999;
  20948. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  20949. j += sqlite3Strlen30(&z[j]);
  20950. break;
  20951. }
  20952. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  20953. case 'W': /* Fall thru */
  20954. case 'j': {
  20955. int nDay; /* Number of days since 1st day of year */
  20956. DateTime y = x;
  20957. y.validJD = 0;
  20958. y.M = 1;
  20959. y.D = 1;
  20960. computeJD(&y);
  20961. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  20962. if( zFmt[i]=='W' ){
  20963. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  20964. wd = (int)(((x.iJD+43200000)/86400000)%7);
  20965. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  20966. j += 2;
  20967. }else{
  20968. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  20969. j += 3;
  20970. }
  20971. break;
  20972. }
  20973. case 'J': {
  20974. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  20975. j+=sqlite3Strlen30(&z[j]);
  20976. break;
  20977. }
  20978. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  20979. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  20980. case 's': {
  20981. sqlite3_snprintf(30,&z[j],"%lld",
  20982. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  20983. j += sqlite3Strlen30(&z[j]);
  20984. break;
  20985. }
  20986. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  20987. case 'w': {
  20988. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  20989. break;
  20990. }
  20991. case 'Y': {
  20992. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  20993. break;
  20994. }
  20995. default: z[j++] = '%'; break;
  20996. }
  20997. }
  20998. }
  20999. z[j] = 0;
  21000. sqlite3_result_text(context, z, -1,
  21001. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  21002. }
  21003. /*
  21004. ** current_time()
  21005. **
  21006. ** This function returns the same value as time('now').
  21007. */
  21008. static void ctimeFunc(
  21009. sqlite3_context *context,
  21010. int NotUsed,
  21011. sqlite3_value **NotUsed2
  21012. ){
  21013. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21014. timeFunc(context, 0, 0);
  21015. }
  21016. /*
  21017. ** current_date()
  21018. **
  21019. ** This function returns the same value as date('now').
  21020. */
  21021. static void cdateFunc(
  21022. sqlite3_context *context,
  21023. int NotUsed,
  21024. sqlite3_value **NotUsed2
  21025. ){
  21026. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21027. dateFunc(context, 0, 0);
  21028. }
  21029. /*
  21030. ** current_timestamp()
  21031. **
  21032. ** This function returns the same value as datetime('now').
  21033. */
  21034. static void ctimestampFunc(
  21035. sqlite3_context *context,
  21036. int NotUsed,
  21037. sqlite3_value **NotUsed2
  21038. ){
  21039. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21040. datetimeFunc(context, 0, 0);
  21041. }
  21042. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  21043. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  21044. /*
  21045. ** If the library is compiled to omit the full-scale date and time
  21046. ** handling (to get a smaller binary), the following minimal version
  21047. ** of the functions current_time(), current_date() and current_timestamp()
  21048. ** are included instead. This is to support column declarations that
  21049. ** include "DEFAULT CURRENT_TIME" etc.
  21050. **
  21051. ** This function uses the C-library functions time(), gmtime()
  21052. ** and strftime(). The format string to pass to strftime() is supplied
  21053. ** as the user-data for the function.
  21054. */
  21055. static void currentTimeFunc(
  21056. sqlite3_context *context,
  21057. int argc,
  21058. sqlite3_value **argv
  21059. ){
  21060. time_t t;
  21061. char *zFormat = (char *)sqlite3_user_data(context);
  21062. sqlite3_int64 iT;
  21063. struct tm *pTm;
  21064. struct tm sNow;
  21065. char zBuf[20];
  21066. UNUSED_PARAMETER(argc);
  21067. UNUSED_PARAMETER(argv);
  21068. iT = sqlite3StmtCurrentTime(context);
  21069. if( iT<=0 ) return;
  21070. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  21071. #if HAVE_GMTIME_R
  21072. pTm = gmtime_r(&t, &sNow);
  21073. #else
  21074. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  21075. pTm = gmtime(&t);
  21076. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  21077. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  21078. #endif
  21079. if( pTm ){
  21080. strftime(zBuf, 20, zFormat, &sNow);
  21081. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  21082. }
  21083. }
  21084. #endif
  21085. /*
  21086. ** This function registered all of the above C functions as SQL
  21087. ** functions. This should be the only routine in this file with
  21088. ** external linkage.
  21089. */
  21090. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  21091. static FuncDef aDateTimeFuncs[] = {
  21092. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  21093. PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
  21094. PURE_DATE(date, -1, 0, 0, dateFunc ),
  21095. PURE_DATE(time, -1, 0, 0, timeFunc ),
  21096. PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
  21097. PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
  21098. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  21099. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  21100. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  21101. #else
  21102. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  21103. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  21104. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  21105. #endif
  21106. };
  21107. sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
  21108. }
  21109. /************** End of date.c ************************************************/
  21110. /************** Begin file os.c **********************************************/
  21111. /*
  21112. ** 2005 November 29
  21113. **
  21114. ** The author disclaims copyright to this source code. In place of
  21115. ** a legal notice, here is a blessing:
  21116. **
  21117. ** May you do good and not evil.
  21118. ** May you find forgiveness for yourself and forgive others.
  21119. ** May you share freely, never taking more than you give.
  21120. **
  21121. ******************************************************************************
  21122. **
  21123. ** This file contains OS interface code that is common to all
  21124. ** architectures.
  21125. */
  21126. /* #include "sqliteInt.h" */
  21127. /*
  21128. ** If we compile with the SQLITE_TEST macro set, then the following block
  21129. ** of code will give us the ability to simulate a disk I/O error. This
  21130. ** is used for testing the I/O recovery logic.
  21131. */
  21132. #if defined(SQLITE_TEST)
  21133. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  21134. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  21135. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  21136. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  21137. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  21138. SQLITE_API int sqlite3_diskfull_pending = 0;
  21139. SQLITE_API int sqlite3_diskfull = 0;
  21140. #endif /* defined(SQLITE_TEST) */
  21141. /*
  21142. ** When testing, also keep a count of the number of open files.
  21143. */
  21144. #if defined(SQLITE_TEST)
  21145. SQLITE_API int sqlite3_open_file_count = 0;
  21146. #endif /* defined(SQLITE_TEST) */
  21147. /*
  21148. ** The default SQLite sqlite3_vfs implementations do not allocate
  21149. ** memory (actually, os_unix.c allocates a small amount of memory
  21150. ** from within OsOpen()), but some third-party implementations may.
  21151. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  21152. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  21153. **
  21154. ** The following functions are instrumented for malloc() failure
  21155. ** testing:
  21156. **
  21157. ** sqlite3OsRead()
  21158. ** sqlite3OsWrite()
  21159. ** sqlite3OsSync()
  21160. ** sqlite3OsFileSize()
  21161. ** sqlite3OsLock()
  21162. ** sqlite3OsCheckReservedLock()
  21163. ** sqlite3OsFileControl()
  21164. ** sqlite3OsShmMap()
  21165. ** sqlite3OsOpen()
  21166. ** sqlite3OsDelete()
  21167. ** sqlite3OsAccess()
  21168. ** sqlite3OsFullPathname()
  21169. **
  21170. */
  21171. #if defined(SQLITE_TEST)
  21172. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  21173. #define DO_OS_MALLOC_TEST(x) \
  21174. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
  21175. void *pTstAlloc = sqlite3Malloc(10); \
  21176. if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
  21177. sqlite3_free(pTstAlloc); \
  21178. }
  21179. #else
  21180. #define DO_OS_MALLOC_TEST(x)
  21181. #endif
  21182. /*
  21183. ** The following routines are convenience wrappers around methods
  21184. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  21185. ** of this would be completely automatic if SQLite were coded using
  21186. ** C++ instead of plain old C.
  21187. */
  21188. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
  21189. if( pId->pMethods ){
  21190. pId->pMethods->xClose(pId);
  21191. pId->pMethods = 0;
  21192. }
  21193. }
  21194. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  21195. DO_OS_MALLOC_TEST(id);
  21196. return id->pMethods->xRead(id, pBuf, amt, offset);
  21197. }
  21198. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  21199. DO_OS_MALLOC_TEST(id);
  21200. return id->pMethods->xWrite(id, pBuf, amt, offset);
  21201. }
  21202. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  21203. return id->pMethods->xTruncate(id, size);
  21204. }
  21205. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  21206. DO_OS_MALLOC_TEST(id);
  21207. return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
  21208. }
  21209. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  21210. DO_OS_MALLOC_TEST(id);
  21211. return id->pMethods->xFileSize(id, pSize);
  21212. }
  21213. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  21214. DO_OS_MALLOC_TEST(id);
  21215. return id->pMethods->xLock(id, lockType);
  21216. }
  21217. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  21218. return id->pMethods->xUnlock(id, lockType);
  21219. }
  21220. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  21221. DO_OS_MALLOC_TEST(id);
  21222. return id->pMethods->xCheckReservedLock(id, pResOut);
  21223. }
  21224. /*
  21225. ** Use sqlite3OsFileControl() when we are doing something that might fail
  21226. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  21227. ** when simply tossing information over the wall to the VFS and we do not
  21228. ** really care if the VFS receives and understands the information since it
  21229. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  21230. ** routine has no return value since the return value would be meaningless.
  21231. */
  21232. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  21233. if( id->pMethods==0 ) return SQLITE_NOTFOUND;
  21234. #ifdef SQLITE_TEST
  21235. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
  21236. && op!=SQLITE_FCNTL_LOCK_TIMEOUT
  21237. ){
  21238. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  21239. ** is using a regular VFS, it is called after the corresponding
  21240. ** transaction has been committed. Injecting a fault at this point
  21241. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  21242. ** but the transaction is committed anyway.
  21243. **
  21244. ** The core must call OsFileControl() though, not OsFileControlHint(),
  21245. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  21246. ** means the commit really has failed and an error should be returned
  21247. ** to the user. */
  21248. DO_OS_MALLOC_TEST(id);
  21249. }
  21250. #endif
  21251. return id->pMethods->xFileControl(id, op, pArg);
  21252. }
  21253. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  21254. if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
  21255. }
  21256. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  21257. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  21258. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  21259. }
  21260. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  21261. return id->pMethods->xDeviceCharacteristics(id);
  21262. }
  21263. #ifndef SQLITE_OMIT_WAL
  21264. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  21265. return id->pMethods->xShmLock(id, offset, n, flags);
  21266. }
  21267. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  21268. id->pMethods->xShmBarrier(id);
  21269. }
  21270. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  21271. return id->pMethods->xShmUnmap(id, deleteFlag);
  21272. }
  21273. SQLITE_PRIVATE int sqlite3OsShmMap(
  21274. sqlite3_file *id, /* Database file handle */
  21275. int iPage,
  21276. int pgsz,
  21277. int bExtend, /* True to extend file if necessary */
  21278. void volatile **pp /* OUT: Pointer to mapping */
  21279. ){
  21280. DO_OS_MALLOC_TEST(id);
  21281. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  21282. }
  21283. #endif /* SQLITE_OMIT_WAL */
  21284. #if SQLITE_MAX_MMAP_SIZE>0
  21285. /* The real implementation of xFetch and xUnfetch */
  21286. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  21287. DO_OS_MALLOC_TEST(id);
  21288. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  21289. }
  21290. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  21291. return id->pMethods->xUnfetch(id, iOff, p);
  21292. }
  21293. #else
  21294. /* No-op stubs to use when memory-mapped I/O is disabled */
  21295. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  21296. *pp = 0;
  21297. return SQLITE_OK;
  21298. }
  21299. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  21300. return SQLITE_OK;
  21301. }
  21302. #endif
  21303. /*
  21304. ** The next group of routines are convenience wrappers around the
  21305. ** VFS methods.
  21306. */
  21307. SQLITE_PRIVATE int sqlite3OsOpen(
  21308. sqlite3_vfs *pVfs,
  21309. const char *zPath,
  21310. sqlite3_file *pFile,
  21311. int flags,
  21312. int *pFlagsOut
  21313. ){
  21314. int rc;
  21315. DO_OS_MALLOC_TEST(0);
  21316. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  21317. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  21318. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  21319. ** reaching the VFS. */
  21320. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  21321. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  21322. return rc;
  21323. }
  21324. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  21325. DO_OS_MALLOC_TEST(0);
  21326. assert( dirSync==0 || dirSync==1 );
  21327. return pVfs->xDelete(pVfs, zPath, dirSync);
  21328. }
  21329. SQLITE_PRIVATE int sqlite3OsAccess(
  21330. sqlite3_vfs *pVfs,
  21331. const char *zPath,
  21332. int flags,
  21333. int *pResOut
  21334. ){
  21335. DO_OS_MALLOC_TEST(0);
  21336. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  21337. }
  21338. SQLITE_PRIVATE int sqlite3OsFullPathname(
  21339. sqlite3_vfs *pVfs,
  21340. const char *zPath,
  21341. int nPathOut,
  21342. char *zPathOut
  21343. ){
  21344. DO_OS_MALLOC_TEST(0);
  21345. zPathOut[0] = 0;
  21346. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  21347. }
  21348. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  21349. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  21350. return pVfs->xDlOpen(pVfs, zPath);
  21351. }
  21352. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  21353. pVfs->xDlError(pVfs, nByte, zBufOut);
  21354. }
  21355. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  21356. return pVfs->xDlSym(pVfs, pHdle, zSym);
  21357. }
  21358. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  21359. pVfs->xDlClose(pVfs, pHandle);
  21360. }
  21361. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  21362. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  21363. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  21364. }
  21365. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  21366. return pVfs->xSleep(pVfs, nMicro);
  21367. }
  21368. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
  21369. return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
  21370. }
  21371. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  21372. int rc;
  21373. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  21374. ** method to get the current date and time if that method is available
  21375. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  21376. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  21377. ** unavailable.
  21378. */
  21379. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  21380. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  21381. }else{
  21382. double r;
  21383. rc = pVfs->xCurrentTime(pVfs, &r);
  21384. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  21385. }
  21386. return rc;
  21387. }
  21388. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  21389. sqlite3_vfs *pVfs,
  21390. const char *zFile,
  21391. sqlite3_file **ppFile,
  21392. int flags,
  21393. int *pOutFlags
  21394. ){
  21395. int rc;
  21396. sqlite3_file *pFile;
  21397. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  21398. if( pFile ){
  21399. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  21400. if( rc!=SQLITE_OK ){
  21401. sqlite3_free(pFile);
  21402. }else{
  21403. *ppFile = pFile;
  21404. }
  21405. }else{
  21406. rc = SQLITE_NOMEM_BKPT;
  21407. }
  21408. return rc;
  21409. }
  21410. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
  21411. assert( pFile );
  21412. sqlite3OsClose(pFile);
  21413. sqlite3_free(pFile);
  21414. }
  21415. /*
  21416. ** This function is a wrapper around the OS specific implementation of
  21417. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  21418. ** ability to simulate a malloc failure, so that the handling of an
  21419. ** error in sqlite3_os_init() by the upper layers can be tested.
  21420. */
  21421. SQLITE_PRIVATE int sqlite3OsInit(void){
  21422. void *p = sqlite3_malloc(10);
  21423. if( p==0 ) return SQLITE_NOMEM_BKPT;
  21424. sqlite3_free(p);
  21425. return sqlite3_os_init();
  21426. }
  21427. /*
  21428. ** The list of all registered VFS implementations.
  21429. */
  21430. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  21431. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  21432. /*
  21433. ** Locate a VFS by name. If no name is given, simply return the
  21434. ** first VFS on the list.
  21435. */
  21436. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  21437. sqlite3_vfs *pVfs = 0;
  21438. #if SQLITE_THREADSAFE
  21439. sqlite3_mutex *mutex;
  21440. #endif
  21441. #ifndef SQLITE_OMIT_AUTOINIT
  21442. int rc = sqlite3_initialize();
  21443. if( rc ) return 0;
  21444. #endif
  21445. #if SQLITE_THREADSAFE
  21446. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  21447. #endif
  21448. sqlite3_mutex_enter(mutex);
  21449. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  21450. if( zVfs==0 ) break;
  21451. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  21452. }
  21453. sqlite3_mutex_leave(mutex);
  21454. return pVfs;
  21455. }
  21456. /*
  21457. ** Unlink a VFS from the linked list
  21458. */
  21459. static void vfsUnlink(sqlite3_vfs *pVfs){
  21460. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  21461. if( pVfs==0 ){
  21462. /* No-op */
  21463. }else if( vfsList==pVfs ){
  21464. vfsList = pVfs->pNext;
  21465. }else if( vfsList ){
  21466. sqlite3_vfs *p = vfsList;
  21467. while( p->pNext && p->pNext!=pVfs ){
  21468. p = p->pNext;
  21469. }
  21470. if( p->pNext==pVfs ){
  21471. p->pNext = pVfs->pNext;
  21472. }
  21473. }
  21474. }
  21475. /*
  21476. ** Register a VFS with the system. It is harmless to register the same
  21477. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  21478. ** true.
  21479. */
  21480. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  21481. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  21482. #ifndef SQLITE_OMIT_AUTOINIT
  21483. int rc = sqlite3_initialize();
  21484. if( rc ) return rc;
  21485. #endif
  21486. #ifdef SQLITE_ENABLE_API_ARMOR
  21487. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  21488. #endif
  21489. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  21490. sqlite3_mutex_enter(mutex);
  21491. vfsUnlink(pVfs);
  21492. if( makeDflt || vfsList==0 ){
  21493. pVfs->pNext = vfsList;
  21494. vfsList = pVfs;
  21495. }else{
  21496. pVfs->pNext = vfsList->pNext;
  21497. vfsList->pNext = pVfs;
  21498. }
  21499. assert(vfsList);
  21500. sqlite3_mutex_leave(mutex);
  21501. return SQLITE_OK;
  21502. }
  21503. /*
  21504. ** Unregister a VFS so that it is no longer accessible.
  21505. */
  21506. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  21507. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  21508. #ifndef SQLITE_OMIT_AUTOINIT
  21509. int rc = sqlite3_initialize();
  21510. if( rc ) return rc;
  21511. #endif
  21512. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  21513. sqlite3_mutex_enter(mutex);
  21514. vfsUnlink(pVfs);
  21515. sqlite3_mutex_leave(mutex);
  21516. return SQLITE_OK;
  21517. }
  21518. /************** End of os.c **************************************************/
  21519. /************** Begin file fault.c *******************************************/
  21520. /*
  21521. ** 2008 Jan 22
  21522. **
  21523. ** The author disclaims copyright to this source code. In place of
  21524. ** a legal notice, here is a blessing:
  21525. **
  21526. ** May you do good and not evil.
  21527. ** May you find forgiveness for yourself and forgive others.
  21528. ** May you share freely, never taking more than you give.
  21529. **
  21530. *************************************************************************
  21531. **
  21532. ** This file contains code to support the concept of "benign"
  21533. ** malloc failures (when the xMalloc() or xRealloc() method of the
  21534. ** sqlite3_mem_methods structure fails to allocate a block of memory
  21535. ** and returns 0).
  21536. **
  21537. ** Most malloc failures are non-benign. After they occur, SQLite
  21538. ** abandons the current operation and returns an error code (usually
  21539. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  21540. ** fatal. For example, if a malloc fails while resizing a hash table, this
  21541. ** is completely recoverable simply by not carrying out the resize. The
  21542. ** hash table will continue to function normally. So a malloc failure
  21543. ** during a hash table resize is a benign fault.
  21544. */
  21545. /* #include "sqliteInt.h" */
  21546. #ifndef SQLITE_UNTESTABLE
  21547. /*
  21548. ** Global variables.
  21549. */
  21550. typedef struct BenignMallocHooks BenignMallocHooks;
  21551. static SQLITE_WSD struct BenignMallocHooks {
  21552. void (*xBenignBegin)(void);
  21553. void (*xBenignEnd)(void);
  21554. } sqlite3Hooks = { 0, 0 };
  21555. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  21556. ** structure. If writable static data is unsupported on the target,
  21557. ** we have to locate the state vector at run-time. In the more common
  21558. ** case where writable static data is supported, wsdHooks can refer directly
  21559. ** to the "sqlite3Hooks" state vector declared above.
  21560. */
  21561. #ifdef SQLITE_OMIT_WSD
  21562. # define wsdHooksInit \
  21563. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  21564. # define wsdHooks x[0]
  21565. #else
  21566. # define wsdHooksInit
  21567. # define wsdHooks sqlite3Hooks
  21568. #endif
  21569. /*
  21570. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  21571. ** sqlite3EndBenignMalloc() are called, respectively.
  21572. */
  21573. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  21574. void (*xBenignBegin)(void),
  21575. void (*xBenignEnd)(void)
  21576. ){
  21577. wsdHooksInit;
  21578. wsdHooks.xBenignBegin = xBenignBegin;
  21579. wsdHooks.xBenignEnd = xBenignEnd;
  21580. }
  21581. /*
  21582. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  21583. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  21584. ** indicates that subsequent malloc failures are non-benign.
  21585. */
  21586. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  21587. wsdHooksInit;
  21588. if( wsdHooks.xBenignBegin ){
  21589. wsdHooks.xBenignBegin();
  21590. }
  21591. }
  21592. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  21593. wsdHooksInit;
  21594. if( wsdHooks.xBenignEnd ){
  21595. wsdHooks.xBenignEnd();
  21596. }
  21597. }
  21598. #endif /* #ifndef SQLITE_UNTESTABLE */
  21599. /************** End of fault.c ***********************************************/
  21600. /************** Begin file mem0.c ********************************************/
  21601. /*
  21602. ** 2008 October 28
  21603. **
  21604. ** The author disclaims copyright to this source code. In place of
  21605. ** a legal notice, here is a blessing:
  21606. **
  21607. ** May you do good and not evil.
  21608. ** May you find forgiveness for yourself and forgive others.
  21609. ** May you share freely, never taking more than you give.
  21610. **
  21611. *************************************************************************
  21612. **
  21613. ** This file contains a no-op memory allocation drivers for use when
  21614. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  21615. ** here always fail. SQLite will not operate with these drivers. These
  21616. ** are merely placeholders. Real drivers must be substituted using
  21617. ** sqlite3_config() before SQLite will operate.
  21618. */
  21619. /* #include "sqliteInt.h" */
  21620. /*
  21621. ** This version of the memory allocator is the default. It is
  21622. ** used when no other memory allocator is specified using compile-time
  21623. ** macros.
  21624. */
  21625. #ifdef SQLITE_ZERO_MALLOC
  21626. /*
  21627. ** No-op versions of all memory allocation routines
  21628. */
  21629. static void *sqlite3MemMalloc(int nByte){ return 0; }
  21630. static void sqlite3MemFree(void *pPrior){ return; }
  21631. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  21632. static int sqlite3MemSize(void *pPrior){ return 0; }
  21633. static int sqlite3MemRoundup(int n){ return n; }
  21634. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  21635. static void sqlite3MemShutdown(void *NotUsed){ return; }
  21636. /*
  21637. ** This routine is the only routine in this file with external linkage.
  21638. **
  21639. ** Populate the low-level memory allocation function pointers in
  21640. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  21641. */
  21642. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  21643. static const sqlite3_mem_methods defaultMethods = {
  21644. sqlite3MemMalloc,
  21645. sqlite3MemFree,
  21646. sqlite3MemRealloc,
  21647. sqlite3MemSize,
  21648. sqlite3MemRoundup,
  21649. sqlite3MemInit,
  21650. sqlite3MemShutdown,
  21651. 0
  21652. };
  21653. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  21654. }
  21655. #endif /* SQLITE_ZERO_MALLOC */
  21656. /************** End of mem0.c ************************************************/
  21657. /************** Begin file mem1.c ********************************************/
  21658. /*
  21659. ** 2007 August 14
  21660. **
  21661. ** The author disclaims copyright to this source code. In place of
  21662. ** a legal notice, here is a blessing:
  21663. **
  21664. ** May you do good and not evil.
  21665. ** May you find forgiveness for yourself and forgive others.
  21666. ** May you share freely, never taking more than you give.
  21667. **
  21668. *************************************************************************
  21669. **
  21670. ** This file contains low-level memory allocation drivers for when
  21671. ** SQLite will use the standard C-library malloc/realloc/free interface
  21672. ** to obtain the memory it needs.
  21673. **
  21674. ** This file contains implementations of the low-level memory allocation
  21675. ** routines specified in the sqlite3_mem_methods object. The content of
  21676. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  21677. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  21678. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  21679. ** default configuration is to use memory allocation routines in this
  21680. ** file.
  21681. **
  21682. ** C-preprocessor macro summary:
  21683. **
  21684. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  21685. ** the malloc_usable_size() interface exists
  21686. ** on the target platform. Or, this symbol
  21687. ** can be set manually, if desired.
  21688. ** If an equivalent interface exists by
  21689. ** a different name, using a separate -D
  21690. ** option to rename it.
  21691. **
  21692. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  21693. ** memory allocator. Set this symbol to enable
  21694. ** building on older macs.
  21695. **
  21696. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  21697. ** _msize() on windows systems. This might
  21698. ** be necessary when compiling for Delphi,
  21699. ** for example.
  21700. */
  21701. /* #include "sqliteInt.h" */
  21702. /*
  21703. ** This version of the memory allocator is the default. It is
  21704. ** used when no other memory allocator is specified using compile-time
  21705. ** macros.
  21706. */
  21707. #ifdef SQLITE_SYSTEM_MALLOC
  21708. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  21709. /*
  21710. ** Use the zone allocator available on apple products unless the
  21711. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  21712. */
  21713. #include <sys/sysctl.h>
  21714. #include <malloc/malloc.h>
  21715. #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
  21716. #include <libkern/OSAtomic.h>
  21717. #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
  21718. static malloc_zone_t* _sqliteZone_;
  21719. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  21720. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  21721. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  21722. #define SQLITE_MALLOCSIZE(x) \
  21723. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  21724. #else /* if not __APPLE__ */
  21725. /*
  21726. ** Use standard C library malloc and free on non-Apple systems.
  21727. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  21728. */
  21729. #define SQLITE_MALLOC(x) malloc(x)
  21730. #define SQLITE_FREE(x) free(x)
  21731. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  21732. /*
  21733. ** The malloc.h header file is needed for malloc_usable_size() function
  21734. ** on some systems (e.g. Linux).
  21735. */
  21736. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  21737. # define SQLITE_USE_MALLOC_H 1
  21738. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  21739. /*
  21740. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  21741. ** use of _msize() is automatic, but can be disabled by compiling with
  21742. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  21743. ** the malloc.h header file.
  21744. */
  21745. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  21746. # define SQLITE_USE_MALLOC_H
  21747. # define SQLITE_USE_MSIZE
  21748. #endif
  21749. /*
  21750. ** Include the malloc.h header file, if necessary. Also set define macro
  21751. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  21752. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  21753. ** The memory size function can always be overridden manually by defining
  21754. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  21755. */
  21756. #if defined(SQLITE_USE_MALLOC_H)
  21757. # include <malloc.h>
  21758. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  21759. # if !defined(SQLITE_MALLOCSIZE)
  21760. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  21761. # endif
  21762. # elif defined(SQLITE_USE_MSIZE)
  21763. # if !defined(SQLITE_MALLOCSIZE)
  21764. # define SQLITE_MALLOCSIZE _msize
  21765. # endif
  21766. # endif
  21767. #endif /* defined(SQLITE_USE_MALLOC_H) */
  21768. #endif /* __APPLE__ or not __APPLE__ */
  21769. /*
  21770. ** Like malloc(), but remember the size of the allocation
  21771. ** so that we can find it later using sqlite3MemSize().
  21772. **
  21773. ** For this low-level routine, we are guaranteed that nByte>0 because
  21774. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  21775. ** routines.
  21776. */
  21777. static void *sqlite3MemMalloc(int nByte){
  21778. #ifdef SQLITE_MALLOCSIZE
  21779. void *p;
  21780. testcase( ROUND8(nByte)==nByte );
  21781. p = SQLITE_MALLOC( nByte );
  21782. if( p==0 ){
  21783. testcase( sqlite3GlobalConfig.xLog!=0 );
  21784. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  21785. }
  21786. return p;
  21787. #else
  21788. sqlite3_int64 *p;
  21789. assert( nByte>0 );
  21790. testcase( ROUND8(nByte)!=nByte );
  21791. p = SQLITE_MALLOC( nByte+8 );
  21792. if( p ){
  21793. p[0] = nByte;
  21794. p++;
  21795. }else{
  21796. testcase( sqlite3GlobalConfig.xLog!=0 );
  21797. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  21798. }
  21799. return (void *)p;
  21800. #endif
  21801. }
  21802. /*
  21803. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  21804. ** or sqlite3MemRealloc().
  21805. **
  21806. ** For this low-level routine, we already know that pPrior!=0 since
  21807. ** cases where pPrior==0 will have been intecepted and dealt with
  21808. ** by higher-level routines.
  21809. */
  21810. static void sqlite3MemFree(void *pPrior){
  21811. #ifdef SQLITE_MALLOCSIZE
  21812. SQLITE_FREE(pPrior);
  21813. #else
  21814. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  21815. assert( pPrior!=0 );
  21816. p--;
  21817. SQLITE_FREE(p);
  21818. #endif
  21819. }
  21820. /*
  21821. ** Report the allocated size of a prior return from xMalloc()
  21822. ** or xRealloc().
  21823. */
  21824. static int sqlite3MemSize(void *pPrior){
  21825. #ifdef SQLITE_MALLOCSIZE
  21826. assert( pPrior!=0 );
  21827. return (int)SQLITE_MALLOCSIZE(pPrior);
  21828. #else
  21829. sqlite3_int64 *p;
  21830. assert( pPrior!=0 );
  21831. p = (sqlite3_int64*)pPrior;
  21832. p--;
  21833. return (int)p[0];
  21834. #endif
  21835. }
  21836. /*
  21837. ** Like realloc(). Resize an allocation previously obtained from
  21838. ** sqlite3MemMalloc().
  21839. **
  21840. ** For this low-level interface, we know that pPrior!=0. Cases where
  21841. ** pPrior==0 while have been intercepted by higher-level routine and
  21842. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  21843. ** cases where nByte<=0 will have been intercepted by higher-level
  21844. ** routines and redirected to xFree.
  21845. */
  21846. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  21847. #ifdef SQLITE_MALLOCSIZE
  21848. void *p = SQLITE_REALLOC(pPrior, nByte);
  21849. if( p==0 ){
  21850. testcase( sqlite3GlobalConfig.xLog!=0 );
  21851. sqlite3_log(SQLITE_NOMEM,
  21852. "failed memory resize %u to %u bytes",
  21853. SQLITE_MALLOCSIZE(pPrior), nByte);
  21854. }
  21855. return p;
  21856. #else
  21857. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  21858. assert( pPrior!=0 && nByte>0 );
  21859. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  21860. p--;
  21861. p = SQLITE_REALLOC(p, nByte+8 );
  21862. if( p ){
  21863. p[0] = nByte;
  21864. p++;
  21865. }else{
  21866. testcase( sqlite3GlobalConfig.xLog!=0 );
  21867. sqlite3_log(SQLITE_NOMEM,
  21868. "failed memory resize %u to %u bytes",
  21869. sqlite3MemSize(pPrior), nByte);
  21870. }
  21871. return (void*)p;
  21872. #endif
  21873. }
  21874. /*
  21875. ** Round up a request size to the next valid allocation size.
  21876. */
  21877. static int sqlite3MemRoundup(int n){
  21878. return ROUND8(n);
  21879. }
  21880. /*
  21881. ** Initialize this module.
  21882. */
  21883. static int sqlite3MemInit(void *NotUsed){
  21884. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  21885. int cpuCount;
  21886. size_t len;
  21887. if( _sqliteZone_ ){
  21888. return SQLITE_OK;
  21889. }
  21890. len = sizeof(cpuCount);
  21891. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  21892. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  21893. if( cpuCount>1 ){
  21894. /* defer MT decisions to system malloc */
  21895. _sqliteZone_ = malloc_default_zone();
  21896. }else{
  21897. /* only 1 core, use our own zone to contention over global locks,
  21898. ** e.g. we have our own dedicated locks */
  21899. _sqliteZone_ = malloc_create_zone(4096, 0);
  21900. malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
  21901. }
  21902. #endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
  21903. UNUSED_PARAMETER(NotUsed);
  21904. return SQLITE_OK;
  21905. }
  21906. /*
  21907. ** Deinitialize this module.
  21908. */
  21909. static void sqlite3MemShutdown(void *NotUsed){
  21910. UNUSED_PARAMETER(NotUsed);
  21911. return;
  21912. }
  21913. /*
  21914. ** This routine is the only routine in this file with external linkage.
  21915. **
  21916. ** Populate the low-level memory allocation function pointers in
  21917. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  21918. */
  21919. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  21920. static const sqlite3_mem_methods defaultMethods = {
  21921. sqlite3MemMalloc,
  21922. sqlite3MemFree,
  21923. sqlite3MemRealloc,
  21924. sqlite3MemSize,
  21925. sqlite3MemRoundup,
  21926. sqlite3MemInit,
  21927. sqlite3MemShutdown,
  21928. 0
  21929. };
  21930. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  21931. }
  21932. #endif /* SQLITE_SYSTEM_MALLOC */
  21933. /************** End of mem1.c ************************************************/
  21934. /************** Begin file mem2.c ********************************************/
  21935. /*
  21936. ** 2007 August 15
  21937. **
  21938. ** The author disclaims copyright to this source code. In place of
  21939. ** a legal notice, here is a blessing:
  21940. **
  21941. ** May you do good and not evil.
  21942. ** May you find forgiveness for yourself and forgive others.
  21943. ** May you share freely, never taking more than you give.
  21944. **
  21945. *************************************************************************
  21946. **
  21947. ** This file contains low-level memory allocation drivers for when
  21948. ** SQLite will use the standard C-library malloc/realloc/free interface
  21949. ** to obtain the memory it needs while adding lots of additional debugging
  21950. ** information to each allocation in order to help detect and fix memory
  21951. ** leaks and memory usage errors.
  21952. **
  21953. ** This file contains implementations of the low-level memory allocation
  21954. ** routines specified in the sqlite3_mem_methods object.
  21955. */
  21956. /* #include "sqliteInt.h" */
  21957. /*
  21958. ** This version of the memory allocator is used only if the
  21959. ** SQLITE_MEMDEBUG macro is defined
  21960. */
  21961. #ifdef SQLITE_MEMDEBUG
  21962. /*
  21963. ** The backtrace functionality is only available with GLIBC
  21964. */
  21965. #ifdef __GLIBC__
  21966. extern int backtrace(void**,int);
  21967. extern void backtrace_symbols_fd(void*const*,int,int);
  21968. #else
  21969. # define backtrace(A,B) 1
  21970. # define backtrace_symbols_fd(A,B,C)
  21971. #endif
  21972. /* #include <stdio.h> */
  21973. /*
  21974. ** Each memory allocation looks like this:
  21975. **
  21976. ** ------------------------------------------------------------------------
  21977. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  21978. ** ------------------------------------------------------------------------
  21979. **
  21980. ** The application code sees only a pointer to the allocation. We have
  21981. ** to back up from the allocation pointer to find the MemBlockHdr. The
  21982. ** MemBlockHdr tells us the size of the allocation and the number of
  21983. ** backtrace pointers. There is also a guard word at the end of the
  21984. ** MemBlockHdr.
  21985. */
  21986. struct MemBlockHdr {
  21987. i64 iSize; /* Size of this allocation */
  21988. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  21989. char nBacktrace; /* Number of backtraces on this alloc */
  21990. char nBacktraceSlots; /* Available backtrace slots */
  21991. u8 nTitle; /* Bytes of title; includes '\0' */
  21992. u8 eType; /* Allocation type code */
  21993. int iForeGuard; /* Guard word for sanity */
  21994. };
  21995. /*
  21996. ** Guard words
  21997. */
  21998. #define FOREGUARD 0x80F5E153
  21999. #define REARGUARD 0xE4676B53
  22000. /*
  22001. ** Number of malloc size increments to track.
  22002. */
  22003. #define NCSIZE 1000
  22004. /*
  22005. ** All of the static variables used by this module are collected
  22006. ** into a single structure named "mem". This is to keep the
  22007. ** static variables organized and to reduce namespace pollution
  22008. ** when this module is combined with other in the amalgamation.
  22009. */
  22010. static struct {
  22011. /*
  22012. ** Mutex to control access to the memory allocation subsystem.
  22013. */
  22014. sqlite3_mutex *mutex;
  22015. /*
  22016. ** Head and tail of a linked list of all outstanding allocations
  22017. */
  22018. struct MemBlockHdr *pFirst;
  22019. struct MemBlockHdr *pLast;
  22020. /*
  22021. ** The number of levels of backtrace to save in new allocations.
  22022. */
  22023. int nBacktrace;
  22024. void (*xBacktrace)(int, int, void **);
  22025. /*
  22026. ** Title text to insert in front of each block
  22027. */
  22028. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  22029. char zTitle[100]; /* The title text */
  22030. /*
  22031. ** sqlite3MallocDisallow() increments the following counter.
  22032. ** sqlite3MallocAllow() decrements it.
  22033. */
  22034. int disallow; /* Do not allow memory allocation */
  22035. /*
  22036. ** Gather statistics on the sizes of memory allocations.
  22037. ** nAlloc[i] is the number of allocation attempts of i*8
  22038. ** bytes. i==NCSIZE is the number of allocation attempts for
  22039. ** sizes more than NCSIZE*8 bytes.
  22040. */
  22041. int nAlloc[NCSIZE]; /* Total number of allocations */
  22042. int nCurrent[NCSIZE]; /* Current number of allocations */
  22043. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  22044. } mem;
  22045. /*
  22046. ** Adjust memory usage statistics
  22047. */
  22048. static void adjustStats(int iSize, int increment){
  22049. int i = ROUND8(iSize)/8;
  22050. if( i>NCSIZE-1 ){
  22051. i = NCSIZE - 1;
  22052. }
  22053. if( increment>0 ){
  22054. mem.nAlloc[i]++;
  22055. mem.nCurrent[i]++;
  22056. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  22057. mem.mxCurrent[i] = mem.nCurrent[i];
  22058. }
  22059. }else{
  22060. mem.nCurrent[i]--;
  22061. assert( mem.nCurrent[i]>=0 );
  22062. }
  22063. }
  22064. /*
  22065. ** Given an allocation, find the MemBlockHdr for that allocation.
  22066. **
  22067. ** This routine checks the guards at either end of the allocation and
  22068. ** if they are incorrect it asserts.
  22069. */
  22070. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  22071. struct MemBlockHdr *p;
  22072. int *pInt;
  22073. u8 *pU8;
  22074. int nReserve;
  22075. p = (struct MemBlockHdr*)pAllocation;
  22076. p--;
  22077. assert( p->iForeGuard==(int)FOREGUARD );
  22078. nReserve = ROUND8(p->iSize);
  22079. pInt = (int*)pAllocation;
  22080. pU8 = (u8*)pAllocation;
  22081. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  22082. /* This checks any of the "extra" bytes allocated due
  22083. ** to rounding up to an 8 byte boundary to ensure
  22084. ** they haven't been overwritten.
  22085. */
  22086. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  22087. return p;
  22088. }
  22089. /*
  22090. ** Return the number of bytes currently allocated at address p.
  22091. */
  22092. static int sqlite3MemSize(void *p){
  22093. struct MemBlockHdr *pHdr;
  22094. if( !p ){
  22095. return 0;
  22096. }
  22097. pHdr = sqlite3MemsysGetHeader(p);
  22098. return (int)pHdr->iSize;
  22099. }
  22100. /*
  22101. ** Initialize the memory allocation subsystem.
  22102. */
  22103. static int sqlite3MemInit(void *NotUsed){
  22104. UNUSED_PARAMETER(NotUsed);
  22105. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  22106. if( !sqlite3GlobalConfig.bMemstat ){
  22107. /* If memory status is enabled, then the malloc.c wrapper will already
  22108. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  22109. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  22110. }
  22111. return SQLITE_OK;
  22112. }
  22113. /*
  22114. ** Deinitialize the memory allocation subsystem.
  22115. */
  22116. static void sqlite3MemShutdown(void *NotUsed){
  22117. UNUSED_PARAMETER(NotUsed);
  22118. mem.mutex = 0;
  22119. }
  22120. /*
  22121. ** Round up a request size to the next valid allocation size.
  22122. */
  22123. static int sqlite3MemRoundup(int n){
  22124. return ROUND8(n);
  22125. }
  22126. /*
  22127. ** Fill a buffer with pseudo-random bytes. This is used to preset
  22128. ** the content of a new memory allocation to unpredictable values and
  22129. ** to clear the content of a freed allocation to unpredictable values.
  22130. */
  22131. static void randomFill(char *pBuf, int nByte){
  22132. unsigned int x, y, r;
  22133. x = SQLITE_PTR_TO_INT(pBuf);
  22134. y = nByte | 1;
  22135. while( nByte >= 4 ){
  22136. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  22137. y = y*1103515245 + 12345;
  22138. r = x ^ y;
  22139. *(int*)pBuf = r;
  22140. pBuf += 4;
  22141. nByte -= 4;
  22142. }
  22143. while( nByte-- > 0 ){
  22144. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  22145. y = y*1103515245 + 12345;
  22146. r = x ^ y;
  22147. *(pBuf++) = r & 0xff;
  22148. }
  22149. }
  22150. /*
  22151. ** Allocate nByte bytes of memory.
  22152. */
  22153. static void *sqlite3MemMalloc(int nByte){
  22154. struct MemBlockHdr *pHdr;
  22155. void **pBt;
  22156. char *z;
  22157. int *pInt;
  22158. void *p = 0;
  22159. int totalSize;
  22160. int nReserve;
  22161. sqlite3_mutex_enter(mem.mutex);
  22162. assert( mem.disallow==0 );
  22163. nReserve = ROUND8(nByte);
  22164. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  22165. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  22166. p = malloc(totalSize);
  22167. if( p ){
  22168. z = p;
  22169. pBt = (void**)&z[mem.nTitle];
  22170. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  22171. pHdr->pNext = 0;
  22172. pHdr->pPrev = mem.pLast;
  22173. if( mem.pLast ){
  22174. mem.pLast->pNext = pHdr;
  22175. }else{
  22176. mem.pFirst = pHdr;
  22177. }
  22178. mem.pLast = pHdr;
  22179. pHdr->iForeGuard = FOREGUARD;
  22180. pHdr->eType = MEMTYPE_HEAP;
  22181. pHdr->nBacktraceSlots = mem.nBacktrace;
  22182. pHdr->nTitle = mem.nTitle;
  22183. if( mem.nBacktrace ){
  22184. void *aAddr[40];
  22185. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  22186. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  22187. assert(pBt[0]);
  22188. if( mem.xBacktrace ){
  22189. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  22190. }
  22191. }else{
  22192. pHdr->nBacktrace = 0;
  22193. }
  22194. if( mem.nTitle ){
  22195. memcpy(z, mem.zTitle, mem.nTitle);
  22196. }
  22197. pHdr->iSize = nByte;
  22198. adjustStats(nByte, +1);
  22199. pInt = (int*)&pHdr[1];
  22200. pInt[nReserve/sizeof(int)] = REARGUARD;
  22201. randomFill((char*)pInt, nByte);
  22202. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  22203. p = (void*)pInt;
  22204. }
  22205. sqlite3_mutex_leave(mem.mutex);
  22206. return p;
  22207. }
  22208. /*
  22209. ** Free memory.
  22210. */
  22211. static void sqlite3MemFree(void *pPrior){
  22212. struct MemBlockHdr *pHdr;
  22213. void **pBt;
  22214. char *z;
  22215. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  22216. || mem.mutex!=0 );
  22217. pHdr = sqlite3MemsysGetHeader(pPrior);
  22218. pBt = (void**)pHdr;
  22219. pBt -= pHdr->nBacktraceSlots;
  22220. sqlite3_mutex_enter(mem.mutex);
  22221. if( pHdr->pPrev ){
  22222. assert( pHdr->pPrev->pNext==pHdr );
  22223. pHdr->pPrev->pNext = pHdr->pNext;
  22224. }else{
  22225. assert( mem.pFirst==pHdr );
  22226. mem.pFirst = pHdr->pNext;
  22227. }
  22228. if( pHdr->pNext ){
  22229. assert( pHdr->pNext->pPrev==pHdr );
  22230. pHdr->pNext->pPrev = pHdr->pPrev;
  22231. }else{
  22232. assert( mem.pLast==pHdr );
  22233. mem.pLast = pHdr->pPrev;
  22234. }
  22235. z = (char*)pBt;
  22236. z -= pHdr->nTitle;
  22237. adjustStats((int)pHdr->iSize, -1);
  22238. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  22239. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  22240. free(z);
  22241. sqlite3_mutex_leave(mem.mutex);
  22242. }
  22243. /*
  22244. ** Change the size of an existing memory allocation.
  22245. **
  22246. ** For this debugging implementation, we *always* make a copy of the
  22247. ** allocation into a new place in memory. In this way, if the
  22248. ** higher level code is using pointer to the old allocation, it is
  22249. ** much more likely to break and we are much more liking to find
  22250. ** the error.
  22251. */
  22252. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  22253. struct MemBlockHdr *pOldHdr;
  22254. void *pNew;
  22255. assert( mem.disallow==0 );
  22256. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  22257. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  22258. pNew = sqlite3MemMalloc(nByte);
  22259. if( pNew ){
  22260. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  22261. if( nByte>pOldHdr->iSize ){
  22262. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  22263. }
  22264. sqlite3MemFree(pPrior);
  22265. }
  22266. return pNew;
  22267. }
  22268. /*
  22269. ** Populate the low-level memory allocation function pointers in
  22270. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  22271. */
  22272. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  22273. static const sqlite3_mem_methods defaultMethods = {
  22274. sqlite3MemMalloc,
  22275. sqlite3MemFree,
  22276. sqlite3MemRealloc,
  22277. sqlite3MemSize,
  22278. sqlite3MemRoundup,
  22279. sqlite3MemInit,
  22280. sqlite3MemShutdown,
  22281. 0
  22282. };
  22283. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  22284. }
  22285. /*
  22286. ** Set the "type" of an allocation.
  22287. */
  22288. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  22289. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  22290. struct MemBlockHdr *pHdr;
  22291. pHdr = sqlite3MemsysGetHeader(p);
  22292. assert( pHdr->iForeGuard==FOREGUARD );
  22293. pHdr->eType = eType;
  22294. }
  22295. }
  22296. /*
  22297. ** Return TRUE if the mask of type in eType matches the type of the
  22298. ** allocation p. Also return true if p==NULL.
  22299. **
  22300. ** This routine is designed for use within an assert() statement, to
  22301. ** verify the type of an allocation. For example:
  22302. **
  22303. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  22304. */
  22305. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  22306. int rc = 1;
  22307. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  22308. struct MemBlockHdr *pHdr;
  22309. pHdr = sqlite3MemsysGetHeader(p);
  22310. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  22311. if( (pHdr->eType&eType)==0 ){
  22312. rc = 0;
  22313. }
  22314. }
  22315. return rc;
  22316. }
  22317. /*
  22318. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  22319. ** allocation p. Also return true if p==NULL.
  22320. **
  22321. ** This routine is designed for use within an assert() statement, to
  22322. ** verify the type of an allocation. For example:
  22323. **
  22324. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  22325. */
  22326. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  22327. int rc = 1;
  22328. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  22329. struct MemBlockHdr *pHdr;
  22330. pHdr = sqlite3MemsysGetHeader(p);
  22331. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  22332. if( (pHdr->eType&eType)!=0 ){
  22333. rc = 0;
  22334. }
  22335. }
  22336. return rc;
  22337. }
  22338. /*
  22339. ** Set the number of backtrace levels kept for each allocation.
  22340. ** A value of zero turns off backtracing. The number is always rounded
  22341. ** up to a multiple of 2.
  22342. */
  22343. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  22344. if( depth<0 ){ depth = 0; }
  22345. if( depth>20 ){ depth = 20; }
  22346. depth = (depth+1)&0xfe;
  22347. mem.nBacktrace = depth;
  22348. }
  22349. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  22350. mem.xBacktrace = xBacktrace;
  22351. }
  22352. /*
  22353. ** Set the title string for subsequent allocations.
  22354. */
  22355. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  22356. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  22357. sqlite3_mutex_enter(mem.mutex);
  22358. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  22359. memcpy(mem.zTitle, zTitle, n);
  22360. mem.zTitle[n] = 0;
  22361. mem.nTitle = ROUND8(n);
  22362. sqlite3_mutex_leave(mem.mutex);
  22363. }
  22364. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  22365. struct MemBlockHdr *pHdr;
  22366. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  22367. void **pBt = (void**)pHdr;
  22368. pBt -= pHdr->nBacktraceSlots;
  22369. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  22370. }
  22371. }
  22372. /*
  22373. ** Open the file indicated and write a log of all unfreed memory
  22374. ** allocations into that log.
  22375. */
  22376. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  22377. FILE *out;
  22378. struct MemBlockHdr *pHdr;
  22379. void **pBt;
  22380. int i;
  22381. out = fopen(zFilename, "w");
  22382. if( out==0 ){
  22383. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  22384. zFilename);
  22385. return;
  22386. }
  22387. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  22388. char *z = (char*)pHdr;
  22389. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  22390. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  22391. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  22392. if( pHdr->nBacktrace ){
  22393. fflush(out);
  22394. pBt = (void**)pHdr;
  22395. pBt -= pHdr->nBacktraceSlots;
  22396. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  22397. fprintf(out, "\n");
  22398. }
  22399. }
  22400. fprintf(out, "COUNTS:\n");
  22401. for(i=0; i<NCSIZE-1; i++){
  22402. if( mem.nAlloc[i] ){
  22403. fprintf(out, " %5d: %10d %10d %10d\n",
  22404. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  22405. }
  22406. }
  22407. if( mem.nAlloc[NCSIZE-1] ){
  22408. fprintf(out, " %5d: %10d %10d %10d\n",
  22409. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  22410. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  22411. }
  22412. fclose(out);
  22413. }
  22414. /*
  22415. ** Return the number of times sqlite3MemMalloc() has been called.
  22416. */
  22417. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  22418. int i;
  22419. int nTotal = 0;
  22420. for(i=0; i<NCSIZE; i++){
  22421. nTotal += mem.nAlloc[i];
  22422. }
  22423. return nTotal;
  22424. }
  22425. #endif /* SQLITE_MEMDEBUG */
  22426. /************** End of mem2.c ************************************************/
  22427. /************** Begin file mem3.c ********************************************/
  22428. /*
  22429. ** 2007 October 14
  22430. **
  22431. ** The author disclaims copyright to this source code. In place of
  22432. ** a legal notice, here is a blessing:
  22433. **
  22434. ** May you do good and not evil.
  22435. ** May you find forgiveness for yourself and forgive others.
  22436. ** May you share freely, never taking more than you give.
  22437. **
  22438. *************************************************************************
  22439. ** This file contains the C functions that implement a memory
  22440. ** allocation subsystem for use by SQLite.
  22441. **
  22442. ** This version of the memory allocation subsystem omits all
  22443. ** use of malloc(). The SQLite user supplies a block of memory
  22444. ** before calling sqlite3_initialize() from which allocations
  22445. ** are made and returned by the xMalloc() and xRealloc()
  22446. ** implementations. Once sqlite3_initialize() has been called,
  22447. ** the amount of memory available to SQLite is fixed and cannot
  22448. ** be changed.
  22449. **
  22450. ** This version of the memory allocation subsystem is included
  22451. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  22452. */
  22453. /* #include "sqliteInt.h" */
  22454. /*
  22455. ** This version of the memory allocator is only built into the library
  22456. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  22457. ** mean that the library will use a memory-pool by default, just that
  22458. ** it is available. The mempool allocator is activated by calling
  22459. ** sqlite3_config().
  22460. */
  22461. #ifdef SQLITE_ENABLE_MEMSYS3
  22462. /*
  22463. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  22464. */
  22465. #define MX_SMALL 10
  22466. /*
  22467. ** Number of freelist hash slots
  22468. */
  22469. #define N_HASH 61
  22470. /*
  22471. ** A memory allocation (also called a "chunk") consists of two or
  22472. ** more blocks where each block is 8 bytes. The first 8 bytes are
  22473. ** a header that is not returned to the user.
  22474. **
  22475. ** A chunk is two or more blocks that is either checked out or
  22476. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  22477. ** size of the allocation in blocks if the allocation is free.
  22478. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  22479. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  22480. ** is true if the previous chunk is checked out and false if the
  22481. ** previous chunk is free. The u.hdr.prevSize field is the size of
  22482. ** the previous chunk in blocks if the previous chunk is on the
  22483. ** freelist. If the previous chunk is checked out, then
  22484. ** u.hdr.prevSize can be part of the data for that chunk and should
  22485. ** not be read or written.
  22486. **
  22487. ** We often identify a chunk by its index in mem3.aPool[]. When
  22488. ** this is done, the chunk index refers to the second block of
  22489. ** the chunk. In this way, the first chunk has an index of 1.
  22490. ** A chunk index of 0 means "no such chunk" and is the equivalent
  22491. ** of a NULL pointer.
  22492. **
  22493. ** The second block of free chunks is of the form u.list. The
  22494. ** two fields form a double-linked list of chunks of related sizes.
  22495. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  22496. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  22497. **
  22498. ** The second block of a chunk is user data if the chunk is checked
  22499. ** out. If a chunk is checked out, the user data may extend into
  22500. ** the u.hdr.prevSize value of the following chunk.
  22501. */
  22502. typedef struct Mem3Block Mem3Block;
  22503. struct Mem3Block {
  22504. union {
  22505. struct {
  22506. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  22507. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  22508. } hdr;
  22509. struct {
  22510. u32 next; /* Index in mem3.aPool[] of next free chunk */
  22511. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  22512. } list;
  22513. } u;
  22514. };
  22515. /*
  22516. ** All of the static variables used by this module are collected
  22517. ** into a single structure named "mem3". This is to keep the
  22518. ** static variables organized and to reduce namespace pollution
  22519. ** when this module is combined with other in the amalgamation.
  22520. */
  22521. static SQLITE_WSD struct Mem3Global {
  22522. /*
  22523. ** Memory available for allocation. nPool is the size of the array
  22524. ** (in Mem3Blocks) pointed to by aPool less 2.
  22525. */
  22526. u32 nPool;
  22527. Mem3Block *aPool;
  22528. /*
  22529. ** True if we are evaluating an out-of-memory callback.
  22530. */
  22531. int alarmBusy;
  22532. /*
  22533. ** Mutex to control access to the memory allocation subsystem.
  22534. */
  22535. sqlite3_mutex *mutex;
  22536. /*
  22537. ** The minimum amount of free space that we have seen.
  22538. */
  22539. u32 mnMaster;
  22540. /*
  22541. ** iMaster is the index of the master chunk. Most new allocations
  22542. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  22543. ** of the current master. iMaster is 0 if there is not master chunk.
  22544. ** The master chunk is not in either the aiHash[] or aiSmall[].
  22545. */
  22546. u32 iMaster;
  22547. u32 szMaster;
  22548. /*
  22549. ** Array of lists of free blocks according to the block size
  22550. ** for smaller chunks, or a hash on the block size for larger
  22551. ** chunks.
  22552. */
  22553. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  22554. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  22555. } mem3 = { 97535575 };
  22556. #define mem3 GLOBAL(struct Mem3Global, mem3)
  22557. /*
  22558. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  22559. ** on. *pRoot is the list that i is a member of.
  22560. */
  22561. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  22562. u32 next = mem3.aPool[i].u.list.next;
  22563. u32 prev = mem3.aPool[i].u.list.prev;
  22564. assert( sqlite3_mutex_held(mem3.mutex) );
  22565. if( prev==0 ){
  22566. *pRoot = next;
  22567. }else{
  22568. mem3.aPool[prev].u.list.next = next;
  22569. }
  22570. if( next ){
  22571. mem3.aPool[next].u.list.prev = prev;
  22572. }
  22573. mem3.aPool[i].u.list.next = 0;
  22574. mem3.aPool[i].u.list.prev = 0;
  22575. }
  22576. /*
  22577. ** Unlink the chunk at index i from
  22578. ** whatever list is currently a member of.
  22579. */
  22580. static void memsys3Unlink(u32 i){
  22581. u32 size, hash;
  22582. assert( sqlite3_mutex_held(mem3.mutex) );
  22583. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  22584. assert( i>=1 );
  22585. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22586. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  22587. assert( size>=2 );
  22588. if( size <= MX_SMALL ){
  22589. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  22590. }else{
  22591. hash = size % N_HASH;
  22592. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  22593. }
  22594. }
  22595. /*
  22596. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  22597. ** at *pRoot.
  22598. */
  22599. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  22600. assert( sqlite3_mutex_held(mem3.mutex) );
  22601. mem3.aPool[i].u.list.next = *pRoot;
  22602. mem3.aPool[i].u.list.prev = 0;
  22603. if( *pRoot ){
  22604. mem3.aPool[*pRoot].u.list.prev = i;
  22605. }
  22606. *pRoot = i;
  22607. }
  22608. /*
  22609. ** Link the chunk at index i into either the appropriate
  22610. ** small chunk list, or into the large chunk hash table.
  22611. */
  22612. static void memsys3Link(u32 i){
  22613. u32 size, hash;
  22614. assert( sqlite3_mutex_held(mem3.mutex) );
  22615. assert( i>=1 );
  22616. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  22617. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22618. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  22619. assert( size>=2 );
  22620. if( size <= MX_SMALL ){
  22621. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  22622. }else{
  22623. hash = size % N_HASH;
  22624. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  22625. }
  22626. }
  22627. /*
  22628. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  22629. ** will already be held (obtained by code in malloc.c) if
  22630. ** sqlite3GlobalConfig.bMemStat is true.
  22631. */
  22632. static void memsys3Enter(void){
  22633. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  22634. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  22635. }
  22636. sqlite3_mutex_enter(mem3.mutex);
  22637. }
  22638. static void memsys3Leave(void){
  22639. sqlite3_mutex_leave(mem3.mutex);
  22640. }
  22641. /*
  22642. ** Called when we are unable to satisfy an allocation of nBytes.
  22643. */
  22644. static void memsys3OutOfMemory(int nByte){
  22645. if( !mem3.alarmBusy ){
  22646. mem3.alarmBusy = 1;
  22647. assert( sqlite3_mutex_held(mem3.mutex) );
  22648. sqlite3_mutex_leave(mem3.mutex);
  22649. sqlite3_release_memory(nByte);
  22650. sqlite3_mutex_enter(mem3.mutex);
  22651. mem3.alarmBusy = 0;
  22652. }
  22653. }
  22654. /*
  22655. ** Chunk i is a free chunk that has been unlinked. Adjust its
  22656. ** size parameters for check-out and return a pointer to the
  22657. ** user portion of the chunk.
  22658. */
  22659. static void *memsys3Checkout(u32 i, u32 nBlock){
  22660. u32 x;
  22661. assert( sqlite3_mutex_held(mem3.mutex) );
  22662. assert( i>=1 );
  22663. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  22664. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  22665. x = mem3.aPool[i-1].u.hdr.size4x;
  22666. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  22667. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  22668. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  22669. return &mem3.aPool[i];
  22670. }
  22671. /*
  22672. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  22673. ** Return a pointer to the new allocation. Or, if the master chunk
  22674. ** is not large enough, return 0.
  22675. */
  22676. static void *memsys3FromMaster(u32 nBlock){
  22677. assert( sqlite3_mutex_held(mem3.mutex) );
  22678. assert( mem3.szMaster>=nBlock );
  22679. if( nBlock>=mem3.szMaster-1 ){
  22680. /* Use the entire master */
  22681. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  22682. mem3.iMaster = 0;
  22683. mem3.szMaster = 0;
  22684. mem3.mnMaster = 0;
  22685. return p;
  22686. }else{
  22687. /* Split the master block. Return the tail. */
  22688. u32 newi, x;
  22689. newi = mem3.iMaster + mem3.szMaster - nBlock;
  22690. assert( newi > mem3.iMaster+1 );
  22691. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  22692. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  22693. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  22694. mem3.szMaster -= nBlock;
  22695. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  22696. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22697. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22698. if( mem3.szMaster < mem3.mnMaster ){
  22699. mem3.mnMaster = mem3.szMaster;
  22700. }
  22701. return (void*)&mem3.aPool[newi];
  22702. }
  22703. }
  22704. /*
  22705. ** *pRoot is the head of a list of free chunks of the same size
  22706. ** or same size hash. In other words, *pRoot is an entry in either
  22707. ** mem3.aiSmall[] or mem3.aiHash[].
  22708. **
  22709. ** This routine examines all entries on the given list and tries
  22710. ** to coalesce each entries with adjacent free chunks.
  22711. **
  22712. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  22713. ** the current mem3.iMaster with the new larger chunk. In order for
  22714. ** this mem3.iMaster replacement to work, the master chunk must be
  22715. ** linked into the hash tables. That is not the normal state of
  22716. ** affairs, of course. The calling routine must link the master
  22717. ** chunk before invoking this routine, then must unlink the (possibly
  22718. ** changed) master chunk once this routine has finished.
  22719. */
  22720. static void memsys3Merge(u32 *pRoot){
  22721. u32 iNext, prev, size, i, x;
  22722. assert( sqlite3_mutex_held(mem3.mutex) );
  22723. for(i=*pRoot; i>0; i=iNext){
  22724. iNext = mem3.aPool[i].u.list.next;
  22725. size = mem3.aPool[i-1].u.hdr.size4x;
  22726. assert( (size&1)==0 );
  22727. if( (size&2)==0 ){
  22728. memsys3UnlinkFromList(i, pRoot);
  22729. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  22730. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  22731. if( prev==iNext ){
  22732. iNext = mem3.aPool[prev].u.list.next;
  22733. }
  22734. memsys3Unlink(prev);
  22735. size = i + size/4 - prev;
  22736. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  22737. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  22738. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  22739. memsys3Link(prev);
  22740. i = prev;
  22741. }else{
  22742. size /= 4;
  22743. }
  22744. if( size>mem3.szMaster ){
  22745. mem3.iMaster = i;
  22746. mem3.szMaster = size;
  22747. }
  22748. }
  22749. }
  22750. /*
  22751. ** Return a block of memory of at least nBytes in size.
  22752. ** Return NULL if unable.
  22753. **
  22754. ** This function assumes that the necessary mutexes, if any, are
  22755. ** already held by the caller. Hence "Unsafe".
  22756. */
  22757. static void *memsys3MallocUnsafe(int nByte){
  22758. u32 i;
  22759. u32 nBlock;
  22760. u32 toFree;
  22761. assert( sqlite3_mutex_held(mem3.mutex) );
  22762. assert( sizeof(Mem3Block)==8 );
  22763. if( nByte<=12 ){
  22764. nBlock = 2;
  22765. }else{
  22766. nBlock = (nByte + 11)/8;
  22767. }
  22768. assert( nBlock>=2 );
  22769. /* STEP 1:
  22770. ** Look for an entry of the correct size in either the small
  22771. ** chunk table or in the large chunk hash table. This is
  22772. ** successful most of the time (about 9 times out of 10).
  22773. */
  22774. if( nBlock <= MX_SMALL ){
  22775. i = mem3.aiSmall[nBlock-2];
  22776. if( i>0 ){
  22777. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  22778. return memsys3Checkout(i, nBlock);
  22779. }
  22780. }else{
  22781. int hash = nBlock % N_HASH;
  22782. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  22783. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  22784. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  22785. return memsys3Checkout(i, nBlock);
  22786. }
  22787. }
  22788. }
  22789. /* STEP 2:
  22790. ** Try to satisfy the allocation by carving a piece off of the end
  22791. ** of the master chunk. This step usually works if step 1 fails.
  22792. */
  22793. if( mem3.szMaster>=nBlock ){
  22794. return memsys3FromMaster(nBlock);
  22795. }
  22796. /* STEP 3:
  22797. ** Loop through the entire memory pool. Coalesce adjacent free
  22798. ** chunks. Recompute the master chunk as the largest free chunk.
  22799. ** Then try again to satisfy the allocation by carving a piece off
  22800. ** of the end of the master chunk. This step happens very
  22801. ** rarely (we hope!)
  22802. */
  22803. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  22804. memsys3OutOfMemory(toFree);
  22805. if( mem3.iMaster ){
  22806. memsys3Link(mem3.iMaster);
  22807. mem3.iMaster = 0;
  22808. mem3.szMaster = 0;
  22809. }
  22810. for(i=0; i<N_HASH; i++){
  22811. memsys3Merge(&mem3.aiHash[i]);
  22812. }
  22813. for(i=0; i<MX_SMALL-1; i++){
  22814. memsys3Merge(&mem3.aiSmall[i]);
  22815. }
  22816. if( mem3.szMaster ){
  22817. memsys3Unlink(mem3.iMaster);
  22818. if( mem3.szMaster>=nBlock ){
  22819. return memsys3FromMaster(nBlock);
  22820. }
  22821. }
  22822. }
  22823. /* If none of the above worked, then we fail. */
  22824. return 0;
  22825. }
  22826. /*
  22827. ** Free an outstanding memory allocation.
  22828. **
  22829. ** This function assumes that the necessary mutexes, if any, are
  22830. ** already held by the caller. Hence "Unsafe".
  22831. */
  22832. static void memsys3FreeUnsafe(void *pOld){
  22833. Mem3Block *p = (Mem3Block*)pOld;
  22834. int i;
  22835. u32 size, x;
  22836. assert( sqlite3_mutex_held(mem3.mutex) );
  22837. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  22838. i = p - mem3.aPool;
  22839. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  22840. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22841. assert( i+size<=mem3.nPool+1 );
  22842. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  22843. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  22844. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  22845. memsys3Link(i);
  22846. /* Try to expand the master using the newly freed chunk */
  22847. if( mem3.iMaster ){
  22848. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  22849. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  22850. mem3.iMaster -= size;
  22851. mem3.szMaster += size;
  22852. memsys3Unlink(mem3.iMaster);
  22853. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22854. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22855. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  22856. }
  22857. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22858. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  22859. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  22860. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  22861. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22862. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  22863. }
  22864. }
  22865. }
  22866. /*
  22867. ** Return the size of an outstanding allocation, in bytes. The
  22868. ** size returned omits the 8-byte header overhead. This only
  22869. ** works for chunks that are currently checked out.
  22870. */
  22871. static int memsys3Size(void *p){
  22872. Mem3Block *pBlock;
  22873. assert( p!=0 );
  22874. pBlock = (Mem3Block*)p;
  22875. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  22876. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  22877. }
  22878. /*
  22879. ** Round up a request size to the next valid allocation size.
  22880. */
  22881. static int memsys3Roundup(int n){
  22882. if( n<=12 ){
  22883. return 12;
  22884. }else{
  22885. return ((n+11)&~7) - 4;
  22886. }
  22887. }
  22888. /*
  22889. ** Allocate nBytes of memory.
  22890. */
  22891. static void *memsys3Malloc(int nBytes){
  22892. sqlite3_int64 *p;
  22893. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  22894. memsys3Enter();
  22895. p = memsys3MallocUnsafe(nBytes);
  22896. memsys3Leave();
  22897. return (void*)p;
  22898. }
  22899. /*
  22900. ** Free memory.
  22901. */
  22902. static void memsys3Free(void *pPrior){
  22903. assert( pPrior );
  22904. memsys3Enter();
  22905. memsys3FreeUnsafe(pPrior);
  22906. memsys3Leave();
  22907. }
  22908. /*
  22909. ** Change the size of an existing memory allocation
  22910. */
  22911. static void *memsys3Realloc(void *pPrior, int nBytes){
  22912. int nOld;
  22913. void *p;
  22914. if( pPrior==0 ){
  22915. return sqlite3_malloc(nBytes);
  22916. }
  22917. if( nBytes<=0 ){
  22918. sqlite3_free(pPrior);
  22919. return 0;
  22920. }
  22921. nOld = memsys3Size(pPrior);
  22922. if( nBytes<=nOld && nBytes>=nOld-128 ){
  22923. return pPrior;
  22924. }
  22925. memsys3Enter();
  22926. p = memsys3MallocUnsafe(nBytes);
  22927. if( p ){
  22928. if( nOld<nBytes ){
  22929. memcpy(p, pPrior, nOld);
  22930. }else{
  22931. memcpy(p, pPrior, nBytes);
  22932. }
  22933. memsys3FreeUnsafe(pPrior);
  22934. }
  22935. memsys3Leave();
  22936. return p;
  22937. }
  22938. /*
  22939. ** Initialize this module.
  22940. */
  22941. static int memsys3Init(void *NotUsed){
  22942. UNUSED_PARAMETER(NotUsed);
  22943. if( !sqlite3GlobalConfig.pHeap ){
  22944. return SQLITE_ERROR;
  22945. }
  22946. /* Store a pointer to the memory block in global structure mem3. */
  22947. assert( sizeof(Mem3Block)==8 );
  22948. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  22949. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  22950. /* Initialize the master block. */
  22951. mem3.szMaster = mem3.nPool;
  22952. mem3.mnMaster = mem3.szMaster;
  22953. mem3.iMaster = 1;
  22954. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  22955. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  22956. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  22957. return SQLITE_OK;
  22958. }
  22959. /*
  22960. ** Deinitialize this module.
  22961. */
  22962. static void memsys3Shutdown(void *NotUsed){
  22963. UNUSED_PARAMETER(NotUsed);
  22964. mem3.mutex = 0;
  22965. return;
  22966. }
  22967. /*
  22968. ** Open the file indicated and write a log of all unfreed memory
  22969. ** allocations into that log.
  22970. */
  22971. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  22972. #ifdef SQLITE_DEBUG
  22973. FILE *out;
  22974. u32 i, j;
  22975. u32 size;
  22976. if( zFilename==0 || zFilename[0]==0 ){
  22977. out = stdout;
  22978. }else{
  22979. out = fopen(zFilename, "w");
  22980. if( out==0 ){
  22981. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  22982. zFilename);
  22983. return;
  22984. }
  22985. }
  22986. memsys3Enter();
  22987. fprintf(out, "CHUNKS:\n");
  22988. for(i=1; i<=mem3.nPool; i+=size/4){
  22989. size = mem3.aPool[i-1].u.hdr.size4x;
  22990. if( size/4<=1 ){
  22991. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  22992. assert( 0 );
  22993. break;
  22994. }
  22995. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  22996. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  22997. assert( 0 );
  22998. break;
  22999. }
  23000. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  23001. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  23002. assert( 0 );
  23003. break;
  23004. }
  23005. if( size&1 ){
  23006. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  23007. }else{
  23008. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  23009. i==mem3.iMaster ? " **master**" : "");
  23010. }
  23011. }
  23012. for(i=0; i<MX_SMALL-1; i++){
  23013. if( mem3.aiSmall[i]==0 ) continue;
  23014. fprintf(out, "small(%2d):", i);
  23015. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  23016. fprintf(out, " %p(%d)", &mem3.aPool[j],
  23017. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  23018. }
  23019. fprintf(out, "\n");
  23020. }
  23021. for(i=0; i<N_HASH; i++){
  23022. if( mem3.aiHash[i]==0 ) continue;
  23023. fprintf(out, "hash(%2d):", i);
  23024. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  23025. fprintf(out, " %p(%d)", &mem3.aPool[j],
  23026. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  23027. }
  23028. fprintf(out, "\n");
  23029. }
  23030. fprintf(out, "master=%d\n", mem3.iMaster);
  23031. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  23032. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  23033. sqlite3_mutex_leave(mem3.mutex);
  23034. if( out==stdout ){
  23035. fflush(stdout);
  23036. }else{
  23037. fclose(out);
  23038. }
  23039. #else
  23040. UNUSED_PARAMETER(zFilename);
  23041. #endif
  23042. }
  23043. /*
  23044. ** This routine is the only routine in this file with external
  23045. ** linkage.
  23046. **
  23047. ** Populate the low-level memory allocation function pointers in
  23048. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  23049. ** arguments specify the block of memory to manage.
  23050. **
  23051. ** This routine is only called by sqlite3_config(), and therefore
  23052. ** is not required to be threadsafe (it is not).
  23053. */
  23054. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  23055. static const sqlite3_mem_methods mempoolMethods = {
  23056. memsys3Malloc,
  23057. memsys3Free,
  23058. memsys3Realloc,
  23059. memsys3Size,
  23060. memsys3Roundup,
  23061. memsys3Init,
  23062. memsys3Shutdown,
  23063. 0
  23064. };
  23065. return &mempoolMethods;
  23066. }
  23067. #endif /* SQLITE_ENABLE_MEMSYS3 */
  23068. /************** End of mem3.c ************************************************/
  23069. /************** Begin file mem5.c ********************************************/
  23070. /*
  23071. ** 2007 October 14
  23072. **
  23073. ** The author disclaims copyright to this source code. In place of
  23074. ** a legal notice, here is a blessing:
  23075. **
  23076. ** May you do good and not evil.
  23077. ** May you find forgiveness for yourself and forgive others.
  23078. ** May you share freely, never taking more than you give.
  23079. **
  23080. *************************************************************************
  23081. ** This file contains the C functions that implement a memory
  23082. ** allocation subsystem for use by SQLite.
  23083. **
  23084. ** This version of the memory allocation subsystem omits all
  23085. ** use of malloc(). The application gives SQLite a block of memory
  23086. ** before calling sqlite3_initialize() from which allocations
  23087. ** are made and returned by the xMalloc() and xRealloc()
  23088. ** implementations. Once sqlite3_initialize() has been called,
  23089. ** the amount of memory available to SQLite is fixed and cannot
  23090. ** be changed.
  23091. **
  23092. ** This version of the memory allocation subsystem is included
  23093. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  23094. **
  23095. ** This memory allocator uses the following algorithm:
  23096. **
  23097. ** 1. All memory allocation sizes are rounded up to a power of 2.
  23098. **
  23099. ** 2. If two adjacent free blocks are the halves of a larger block,
  23100. ** then the two blocks are coalesced into the single larger block.
  23101. **
  23102. ** 3. New memory is allocated from the first available free block.
  23103. **
  23104. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  23105. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  23106. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  23107. **
  23108. ** Let n be the size of the largest allocation divided by the minimum
  23109. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  23110. ** be the maximum amount of memory ever outstanding at one time. Let
  23111. ** N be the total amount of memory available for allocation. Robson
  23112. ** proved that this memory allocator will never breakdown due to
  23113. ** fragmentation as long as the following constraint holds:
  23114. **
  23115. ** N >= M*(1 + log2(n)/2) - n + 1
  23116. **
  23117. ** The sqlite3_status() logic tracks the maximum values of n and M so
  23118. ** that an application can, at any time, verify this constraint.
  23119. */
  23120. /* #include "sqliteInt.h" */
  23121. /*
  23122. ** This version of the memory allocator is used only when
  23123. ** SQLITE_ENABLE_MEMSYS5 is defined.
  23124. */
  23125. #ifdef SQLITE_ENABLE_MEMSYS5
  23126. /*
  23127. ** A minimum allocation is an instance of the following structure.
  23128. ** Larger allocations are an array of these structures where the
  23129. ** size of the array is a power of 2.
  23130. **
  23131. ** The size of this object must be a power of two. That fact is
  23132. ** verified in memsys5Init().
  23133. */
  23134. typedef struct Mem5Link Mem5Link;
  23135. struct Mem5Link {
  23136. int next; /* Index of next free chunk */
  23137. int prev; /* Index of previous free chunk */
  23138. };
  23139. /*
  23140. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  23141. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  23142. ** it is not actually possible to reach this limit.
  23143. */
  23144. #define LOGMAX 30
  23145. /*
  23146. ** Masks used for mem5.aCtrl[] elements.
  23147. */
  23148. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  23149. #define CTRL_FREE 0x20 /* True if not checked out */
  23150. /*
  23151. ** All of the static variables used by this module are collected
  23152. ** into a single structure named "mem5". This is to keep the
  23153. ** static variables organized and to reduce namespace pollution
  23154. ** when this module is combined with other in the amalgamation.
  23155. */
  23156. static SQLITE_WSD struct Mem5Global {
  23157. /*
  23158. ** Memory available for allocation
  23159. */
  23160. int szAtom; /* Smallest possible allocation in bytes */
  23161. int nBlock; /* Number of szAtom sized blocks in zPool */
  23162. u8 *zPool; /* Memory available to be allocated */
  23163. /*
  23164. ** Mutex to control access to the memory allocation subsystem.
  23165. */
  23166. sqlite3_mutex *mutex;
  23167. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23168. /*
  23169. ** Performance statistics
  23170. */
  23171. u64 nAlloc; /* Total number of calls to malloc */
  23172. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  23173. u64 totalExcess; /* Total internal fragmentation */
  23174. u32 currentOut; /* Current checkout, including internal fragmentation */
  23175. u32 currentCount; /* Current number of distinct checkouts */
  23176. u32 maxOut; /* Maximum instantaneous currentOut */
  23177. u32 maxCount; /* Maximum instantaneous currentCount */
  23178. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  23179. #endif
  23180. /*
  23181. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  23182. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  23183. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
  23184. */
  23185. int aiFreelist[LOGMAX+1];
  23186. /*
  23187. ** Space for tracking which blocks are checked out and the size
  23188. ** of each block. One byte per block.
  23189. */
  23190. u8 *aCtrl;
  23191. } mem5;
  23192. /*
  23193. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  23194. */
  23195. #define mem5 GLOBAL(struct Mem5Global, mem5)
  23196. /*
  23197. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  23198. ** structures, return a pointer to the idx-th such link.
  23199. */
  23200. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  23201. /*
  23202. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  23203. ** on. It should be found on mem5.aiFreelist[iLogsize].
  23204. */
  23205. static void memsys5Unlink(int i, int iLogsize){
  23206. int next, prev;
  23207. assert( i>=0 && i<mem5.nBlock );
  23208. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  23209. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  23210. next = MEM5LINK(i)->next;
  23211. prev = MEM5LINK(i)->prev;
  23212. if( prev<0 ){
  23213. mem5.aiFreelist[iLogsize] = next;
  23214. }else{
  23215. MEM5LINK(prev)->next = next;
  23216. }
  23217. if( next>=0 ){
  23218. MEM5LINK(next)->prev = prev;
  23219. }
  23220. }
  23221. /*
  23222. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  23223. ** free list.
  23224. */
  23225. static void memsys5Link(int i, int iLogsize){
  23226. int x;
  23227. assert( sqlite3_mutex_held(mem5.mutex) );
  23228. assert( i>=0 && i<mem5.nBlock );
  23229. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  23230. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  23231. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  23232. MEM5LINK(i)->prev = -1;
  23233. if( x>=0 ){
  23234. assert( x<mem5.nBlock );
  23235. MEM5LINK(x)->prev = i;
  23236. }
  23237. mem5.aiFreelist[iLogsize] = i;
  23238. }
  23239. /*
  23240. ** Obtain or release the mutex needed to access global data structures.
  23241. */
  23242. static void memsys5Enter(void){
  23243. sqlite3_mutex_enter(mem5.mutex);
  23244. }
  23245. static void memsys5Leave(void){
  23246. sqlite3_mutex_leave(mem5.mutex);
  23247. }
  23248. /*
  23249. ** Return the size of an outstanding allocation, in bytes.
  23250. ** This only works for chunks that are currently checked out.
  23251. */
  23252. static int memsys5Size(void *p){
  23253. int iSize, i;
  23254. assert( p!=0 );
  23255. i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  23256. assert( i>=0 && i<mem5.nBlock );
  23257. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  23258. return iSize;
  23259. }
  23260. /*
  23261. ** Return a block of memory of at least nBytes in size.
  23262. ** Return NULL if unable. Return NULL if nBytes==0.
  23263. **
  23264. ** The caller guarantees that nByte is positive.
  23265. **
  23266. ** The caller has obtained a mutex prior to invoking this
  23267. ** routine so there is never any chance that two or more
  23268. ** threads can be in this routine at the same time.
  23269. */
  23270. static void *memsys5MallocUnsafe(int nByte){
  23271. int i; /* Index of a mem5.aPool[] slot */
  23272. int iBin; /* Index into mem5.aiFreelist[] */
  23273. int iFullSz; /* Size of allocation rounded up to power of 2 */
  23274. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  23275. /* nByte must be a positive */
  23276. assert( nByte>0 );
  23277. /* No more than 1GiB per allocation */
  23278. if( nByte > 0x40000000 ) return 0;
  23279. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23280. /* Keep track of the maximum allocation request. Even unfulfilled
  23281. ** requests are counted */
  23282. if( (u32)nByte>mem5.maxRequest ){
  23283. mem5.maxRequest = nByte;
  23284. }
  23285. #endif
  23286. /* Round nByte up to the next valid power of two */
  23287. for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
  23288. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  23289. ** block. If not, then split a block of the next larger power of
  23290. ** two in order to create a new free block of size iLogsize.
  23291. */
  23292. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  23293. if( iBin>LOGMAX ){
  23294. testcase( sqlite3GlobalConfig.xLog!=0 );
  23295. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  23296. return 0;
  23297. }
  23298. i = mem5.aiFreelist[iBin];
  23299. memsys5Unlink(i, iBin);
  23300. while( iBin>iLogsize ){
  23301. int newSize;
  23302. iBin--;
  23303. newSize = 1 << iBin;
  23304. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  23305. memsys5Link(i+newSize, iBin);
  23306. }
  23307. mem5.aCtrl[i] = iLogsize;
  23308. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23309. /* Update allocator performance statistics. */
  23310. mem5.nAlloc++;
  23311. mem5.totalAlloc += iFullSz;
  23312. mem5.totalExcess += iFullSz - nByte;
  23313. mem5.currentCount++;
  23314. mem5.currentOut += iFullSz;
  23315. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  23316. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  23317. #endif
  23318. #ifdef SQLITE_DEBUG
  23319. /* Make sure the allocated memory does not assume that it is set to zero
  23320. ** or retains a value from a previous allocation */
  23321. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  23322. #endif
  23323. /* Return a pointer to the allocated memory. */
  23324. return (void*)&mem5.zPool[i*mem5.szAtom];
  23325. }
  23326. /*
  23327. ** Free an outstanding memory allocation.
  23328. */
  23329. static void memsys5FreeUnsafe(void *pOld){
  23330. u32 size, iLogsize;
  23331. int iBlock;
  23332. /* Set iBlock to the index of the block pointed to by pOld in
  23333. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  23334. */
  23335. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  23336. /* Check that the pointer pOld points to a valid, non-free block. */
  23337. assert( iBlock>=0 && iBlock<mem5.nBlock );
  23338. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  23339. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  23340. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  23341. size = 1<<iLogsize;
  23342. assert( iBlock+size-1<(u32)mem5.nBlock );
  23343. mem5.aCtrl[iBlock] |= CTRL_FREE;
  23344. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  23345. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23346. assert( mem5.currentCount>0 );
  23347. assert( mem5.currentOut>=(size*mem5.szAtom) );
  23348. mem5.currentCount--;
  23349. mem5.currentOut -= size*mem5.szAtom;
  23350. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  23351. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  23352. #endif
  23353. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  23354. while( ALWAYS(iLogsize<LOGMAX) ){
  23355. int iBuddy;
  23356. if( (iBlock>>iLogsize) & 1 ){
  23357. iBuddy = iBlock - size;
  23358. assert( iBuddy>=0 );
  23359. }else{
  23360. iBuddy = iBlock + size;
  23361. if( iBuddy>=mem5.nBlock ) break;
  23362. }
  23363. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  23364. memsys5Unlink(iBuddy, iLogsize);
  23365. iLogsize++;
  23366. if( iBuddy<iBlock ){
  23367. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  23368. mem5.aCtrl[iBlock] = 0;
  23369. iBlock = iBuddy;
  23370. }else{
  23371. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  23372. mem5.aCtrl[iBuddy] = 0;
  23373. }
  23374. size *= 2;
  23375. }
  23376. #ifdef SQLITE_DEBUG
  23377. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  23378. ** not used after being freed */
  23379. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  23380. #endif
  23381. memsys5Link(iBlock, iLogsize);
  23382. }
  23383. /*
  23384. ** Allocate nBytes of memory.
  23385. */
  23386. static void *memsys5Malloc(int nBytes){
  23387. sqlite3_int64 *p = 0;
  23388. if( nBytes>0 ){
  23389. memsys5Enter();
  23390. p = memsys5MallocUnsafe(nBytes);
  23391. memsys5Leave();
  23392. }
  23393. return (void*)p;
  23394. }
  23395. /*
  23396. ** Free memory.
  23397. **
  23398. ** The outer layer memory allocator prevents this routine from
  23399. ** being called with pPrior==0.
  23400. */
  23401. static void memsys5Free(void *pPrior){
  23402. assert( pPrior!=0 );
  23403. memsys5Enter();
  23404. memsys5FreeUnsafe(pPrior);
  23405. memsys5Leave();
  23406. }
  23407. /*
  23408. ** Change the size of an existing memory allocation.
  23409. **
  23410. ** The outer layer memory allocator prevents this routine from
  23411. ** being called with pPrior==0.
  23412. **
  23413. ** nBytes is always a value obtained from a prior call to
  23414. ** memsys5Round(). Hence nBytes is always a non-negative power
  23415. ** of two. If nBytes==0 that means that an oversize allocation
  23416. ** (an allocation larger than 0x40000000) was requested and this
  23417. ** routine should return 0 without freeing pPrior.
  23418. */
  23419. static void *memsys5Realloc(void *pPrior, int nBytes){
  23420. int nOld;
  23421. void *p;
  23422. assert( pPrior!=0 );
  23423. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  23424. assert( nBytes>=0 );
  23425. if( nBytes==0 ){
  23426. return 0;
  23427. }
  23428. nOld = memsys5Size(pPrior);
  23429. if( nBytes<=nOld ){
  23430. return pPrior;
  23431. }
  23432. p = memsys5Malloc(nBytes);
  23433. if( p ){
  23434. memcpy(p, pPrior, nOld);
  23435. memsys5Free(pPrior);
  23436. }
  23437. return p;
  23438. }
  23439. /*
  23440. ** Round up a request size to the next valid allocation size. If
  23441. ** the allocation is too large to be handled by this allocation system,
  23442. ** return 0.
  23443. **
  23444. ** All allocations must be a power of two and must be expressed by a
  23445. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  23446. ** or 1073741824 bytes.
  23447. */
  23448. static int memsys5Roundup(int n){
  23449. int iFullSz;
  23450. if( n > 0x40000000 ) return 0;
  23451. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  23452. return iFullSz;
  23453. }
  23454. /*
  23455. ** Return the ceiling of the logarithm base 2 of iValue.
  23456. **
  23457. ** Examples: memsys5Log(1) -> 0
  23458. ** memsys5Log(2) -> 1
  23459. ** memsys5Log(4) -> 2
  23460. ** memsys5Log(5) -> 3
  23461. ** memsys5Log(8) -> 3
  23462. ** memsys5Log(9) -> 4
  23463. */
  23464. static int memsys5Log(int iValue){
  23465. int iLog;
  23466. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  23467. return iLog;
  23468. }
  23469. /*
  23470. ** Initialize the memory allocator.
  23471. **
  23472. ** This routine is not threadsafe. The caller must be holding a mutex
  23473. ** to prevent multiple threads from entering at the same time.
  23474. */
  23475. static int memsys5Init(void *NotUsed){
  23476. int ii; /* Loop counter */
  23477. int nByte; /* Number of bytes of memory available to this allocator */
  23478. u8 *zByte; /* Memory usable by this allocator */
  23479. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  23480. int iOffset; /* An offset into mem5.aCtrl[] */
  23481. UNUSED_PARAMETER(NotUsed);
  23482. /* For the purposes of this routine, disable the mutex */
  23483. mem5.mutex = 0;
  23484. /* The size of a Mem5Link object must be a power of two. Verify that
  23485. ** this is case.
  23486. */
  23487. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  23488. nByte = sqlite3GlobalConfig.nHeap;
  23489. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  23490. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  23491. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  23492. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  23493. mem5.szAtom = (1<<nMinLog);
  23494. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  23495. mem5.szAtom = mem5.szAtom << 1;
  23496. }
  23497. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  23498. mem5.zPool = zByte;
  23499. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  23500. for(ii=0; ii<=LOGMAX; ii++){
  23501. mem5.aiFreelist[ii] = -1;
  23502. }
  23503. iOffset = 0;
  23504. for(ii=LOGMAX; ii>=0; ii--){
  23505. int nAlloc = (1<<ii);
  23506. if( (iOffset+nAlloc)<=mem5.nBlock ){
  23507. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  23508. memsys5Link(iOffset, ii);
  23509. iOffset += nAlloc;
  23510. }
  23511. assert((iOffset+nAlloc)>mem5.nBlock);
  23512. }
  23513. /* If a mutex is required for normal operation, allocate one */
  23514. if( sqlite3GlobalConfig.bMemstat==0 ){
  23515. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  23516. }
  23517. return SQLITE_OK;
  23518. }
  23519. /*
  23520. ** Deinitialize this module.
  23521. */
  23522. static void memsys5Shutdown(void *NotUsed){
  23523. UNUSED_PARAMETER(NotUsed);
  23524. mem5.mutex = 0;
  23525. return;
  23526. }
  23527. #ifdef SQLITE_TEST
  23528. /*
  23529. ** Open the file indicated and write a log of all unfreed memory
  23530. ** allocations into that log.
  23531. */
  23532. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  23533. FILE *out;
  23534. int i, j, n;
  23535. int nMinLog;
  23536. if( zFilename==0 || zFilename[0]==0 ){
  23537. out = stdout;
  23538. }else{
  23539. out = fopen(zFilename, "w");
  23540. if( out==0 ){
  23541. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  23542. zFilename);
  23543. return;
  23544. }
  23545. }
  23546. memsys5Enter();
  23547. nMinLog = memsys5Log(mem5.szAtom);
  23548. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  23549. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  23550. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  23551. }
  23552. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  23553. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  23554. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  23555. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  23556. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  23557. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  23558. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  23559. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  23560. memsys5Leave();
  23561. if( out==stdout ){
  23562. fflush(stdout);
  23563. }else{
  23564. fclose(out);
  23565. }
  23566. }
  23567. #endif
  23568. /*
  23569. ** This routine is the only routine in this file with external
  23570. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  23571. ** struct populated with the memsys5 methods.
  23572. */
  23573. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  23574. static const sqlite3_mem_methods memsys5Methods = {
  23575. memsys5Malloc,
  23576. memsys5Free,
  23577. memsys5Realloc,
  23578. memsys5Size,
  23579. memsys5Roundup,
  23580. memsys5Init,
  23581. memsys5Shutdown,
  23582. 0
  23583. };
  23584. return &memsys5Methods;
  23585. }
  23586. #endif /* SQLITE_ENABLE_MEMSYS5 */
  23587. /************** End of mem5.c ************************************************/
  23588. /************** Begin file mutex.c *******************************************/
  23589. /*
  23590. ** 2007 August 14
  23591. **
  23592. ** The author disclaims copyright to this source code. In place of
  23593. ** a legal notice, here is a blessing:
  23594. **
  23595. ** May you do good and not evil.
  23596. ** May you find forgiveness for yourself and forgive others.
  23597. ** May you share freely, never taking more than you give.
  23598. **
  23599. *************************************************************************
  23600. ** This file contains the C functions that implement mutexes.
  23601. **
  23602. ** This file contains code that is common across all mutex implementations.
  23603. */
  23604. /* #include "sqliteInt.h" */
  23605. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  23606. /*
  23607. ** For debugging purposes, record when the mutex subsystem is initialized
  23608. ** and uninitialized so that we can assert() if there is an attempt to
  23609. ** allocate a mutex while the system is uninitialized.
  23610. */
  23611. static SQLITE_WSD int mutexIsInit = 0;
  23612. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  23613. #ifndef SQLITE_MUTEX_OMIT
  23614. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  23615. /*
  23616. ** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
  23617. ** the implementation of a wrapper around the system default mutex
  23618. ** implementation (sqlite3DefaultMutex()).
  23619. **
  23620. ** Most calls are passed directly through to the underlying default
  23621. ** mutex implementation. Except, if a mutex is configured by calling
  23622. ** sqlite3MutexWarnOnContention() on it, then if contention is ever
  23623. ** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
  23624. **
  23625. ** This type of mutex is used as the database handle mutex when testing
  23626. ** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
  23627. */
  23628. /*
  23629. ** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
  23630. ** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
  23631. ** allocated by the system mutex implementation. Variable iType is usually set
  23632. ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
  23633. ** or one of the static mutex identifiers. Or, if this is a recursive mutex
  23634. ** that has been configured using sqlite3MutexWarnOnContention(), it is
  23635. ** set to SQLITE_MUTEX_WARNONCONTENTION.
  23636. */
  23637. typedef struct CheckMutex CheckMutex;
  23638. struct CheckMutex {
  23639. int iType;
  23640. sqlite3_mutex *mutex;
  23641. };
  23642. #define SQLITE_MUTEX_WARNONCONTENTION (-1)
  23643. /*
  23644. ** Pointer to real mutex methods object used by the CheckMutex
  23645. ** implementation. Set by checkMutexInit().
  23646. */
  23647. static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
  23648. #ifdef SQLITE_DEBUG
  23649. static int checkMutexHeld(sqlite3_mutex *p){
  23650. return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
  23651. }
  23652. static int checkMutexNotheld(sqlite3_mutex *p){
  23653. return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
  23654. }
  23655. #endif
  23656. /*
  23657. ** Initialize and deinitialize the mutex subsystem.
  23658. */
  23659. static int checkMutexInit(void){
  23660. pGlobalMutexMethods = sqlite3DefaultMutex();
  23661. return SQLITE_OK;
  23662. }
  23663. static int checkMutexEnd(void){
  23664. pGlobalMutexMethods = 0;
  23665. return SQLITE_OK;
  23666. }
  23667. /*
  23668. ** Allocate a mutex.
  23669. */
  23670. static sqlite3_mutex *checkMutexAlloc(int iType){
  23671. static CheckMutex staticMutexes[] = {
  23672. {2, 0}, {3, 0}, {4, 0}, {5, 0},
  23673. {6, 0}, {7, 0}, {8, 0}, {9, 0},
  23674. {10, 0}, {11, 0}, {12, 0}, {13, 0}
  23675. };
  23676. CheckMutex *p = 0;
  23677. assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
  23678. if( iType<2 ){
  23679. p = sqlite3MallocZero(sizeof(CheckMutex));
  23680. if( p==0 ) return 0;
  23681. p->iType = iType;
  23682. }else{
  23683. #ifdef SQLITE_ENABLE_API_ARMOR
  23684. if( iType-2>=ArraySize(staticMutexes) ){
  23685. (void)SQLITE_MISUSE_BKPT;
  23686. return 0;
  23687. }
  23688. #endif
  23689. p = &staticMutexes[iType-2];
  23690. }
  23691. if( p->mutex==0 ){
  23692. p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
  23693. if( p->mutex==0 ){
  23694. if( iType<2 ){
  23695. sqlite3_free(p);
  23696. }
  23697. p = 0;
  23698. }
  23699. }
  23700. return (sqlite3_mutex*)p;
  23701. }
  23702. /*
  23703. ** Free a mutex.
  23704. */
  23705. static void checkMutexFree(sqlite3_mutex *p){
  23706. assert( SQLITE_MUTEX_RECURSIVE<2 );
  23707. assert( SQLITE_MUTEX_FAST<2 );
  23708. assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
  23709. #if SQLITE_ENABLE_API_ARMOR
  23710. if( ((CheckMutex*)p)->iType<2 )
  23711. #endif
  23712. {
  23713. CheckMutex *pCheck = (CheckMutex*)p;
  23714. pGlobalMutexMethods->xMutexFree(pCheck->mutex);
  23715. sqlite3_free(pCheck);
  23716. }
  23717. #ifdef SQLITE_ENABLE_API_ARMOR
  23718. else{
  23719. (void)SQLITE_MISUSE_BKPT;
  23720. }
  23721. #endif
  23722. }
  23723. /*
  23724. ** Enter the mutex.
  23725. */
  23726. static void checkMutexEnter(sqlite3_mutex *p){
  23727. CheckMutex *pCheck = (CheckMutex*)p;
  23728. if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
  23729. if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
  23730. return;
  23731. }
  23732. sqlite3_log(SQLITE_MISUSE,
  23733. "illegal multi-threaded access to database connection"
  23734. );
  23735. }
  23736. pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
  23737. }
  23738. /*
  23739. ** Enter the mutex (do not block).
  23740. */
  23741. static int checkMutexTry(sqlite3_mutex *p){
  23742. CheckMutex *pCheck = (CheckMutex*)p;
  23743. return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
  23744. }
  23745. /*
  23746. ** Leave the mutex.
  23747. */
  23748. static void checkMutexLeave(sqlite3_mutex *p){
  23749. CheckMutex *pCheck = (CheckMutex*)p;
  23750. pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
  23751. }
  23752. sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
  23753. static const sqlite3_mutex_methods sMutex = {
  23754. checkMutexInit,
  23755. checkMutexEnd,
  23756. checkMutexAlloc,
  23757. checkMutexFree,
  23758. checkMutexEnter,
  23759. checkMutexTry,
  23760. checkMutexLeave,
  23761. #ifdef SQLITE_DEBUG
  23762. checkMutexHeld,
  23763. checkMutexNotheld
  23764. #else
  23765. 0,
  23766. 0
  23767. #endif
  23768. };
  23769. return &sMutex;
  23770. }
  23771. /*
  23772. ** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
  23773. ** one on which there should be no contention.
  23774. */
  23775. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
  23776. if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
  23777. CheckMutex *pCheck = (CheckMutex*)p;
  23778. assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
  23779. pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
  23780. }
  23781. }
  23782. #endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
  23783. /*
  23784. ** Initialize the mutex system.
  23785. */
  23786. SQLITE_PRIVATE int sqlite3MutexInit(void){
  23787. int rc = SQLITE_OK;
  23788. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  23789. /* If the xMutexAlloc method has not been set, then the user did not
  23790. ** install a mutex implementation via sqlite3_config() prior to
  23791. ** sqlite3_initialize() being called. This block copies pointers to
  23792. ** the default implementation into the sqlite3GlobalConfig structure.
  23793. */
  23794. sqlite3_mutex_methods const *pFrom;
  23795. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  23796. if( sqlite3GlobalConfig.bCoreMutex ){
  23797. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  23798. pFrom = multiThreadedCheckMutex();
  23799. #else
  23800. pFrom = sqlite3DefaultMutex();
  23801. #endif
  23802. }else{
  23803. pFrom = sqlite3NoopMutex();
  23804. }
  23805. pTo->xMutexInit = pFrom->xMutexInit;
  23806. pTo->xMutexEnd = pFrom->xMutexEnd;
  23807. pTo->xMutexFree = pFrom->xMutexFree;
  23808. pTo->xMutexEnter = pFrom->xMutexEnter;
  23809. pTo->xMutexTry = pFrom->xMutexTry;
  23810. pTo->xMutexLeave = pFrom->xMutexLeave;
  23811. pTo->xMutexHeld = pFrom->xMutexHeld;
  23812. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  23813. sqlite3MemoryBarrier();
  23814. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  23815. }
  23816. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  23817. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  23818. #ifdef SQLITE_DEBUG
  23819. GLOBAL(int, mutexIsInit) = 1;
  23820. #endif
  23821. return rc;
  23822. }
  23823. /*
  23824. ** Shutdown the mutex system. This call frees resources allocated by
  23825. ** sqlite3MutexInit().
  23826. */
  23827. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  23828. int rc = SQLITE_OK;
  23829. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  23830. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  23831. }
  23832. #ifdef SQLITE_DEBUG
  23833. GLOBAL(int, mutexIsInit) = 0;
  23834. #endif
  23835. return rc;
  23836. }
  23837. /*
  23838. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  23839. */
  23840. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  23841. #ifndef SQLITE_OMIT_AUTOINIT
  23842. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  23843. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  23844. #endif
  23845. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  23846. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  23847. }
  23848. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  23849. if( !sqlite3GlobalConfig.bCoreMutex ){
  23850. return 0;
  23851. }
  23852. assert( GLOBAL(int, mutexIsInit) );
  23853. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  23854. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  23855. }
  23856. /*
  23857. ** Free a dynamic mutex.
  23858. */
  23859. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  23860. if( p ){
  23861. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  23862. sqlite3GlobalConfig.mutex.xMutexFree(p);
  23863. }
  23864. }
  23865. /*
  23866. ** Obtain the mutex p. If some other thread already has the mutex, block
  23867. ** until it can be obtained.
  23868. */
  23869. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  23870. if( p ){
  23871. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  23872. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  23873. }
  23874. }
  23875. /*
  23876. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  23877. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  23878. */
  23879. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  23880. int rc = SQLITE_OK;
  23881. if( p ){
  23882. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  23883. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  23884. }
  23885. return rc;
  23886. }
  23887. /*
  23888. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  23889. ** entered by the same thread. The behavior is undefined if the mutex
  23890. ** is not currently entered. If a NULL pointer is passed as an argument
  23891. ** this function is a no-op.
  23892. */
  23893. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  23894. if( p ){
  23895. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  23896. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  23897. }
  23898. }
  23899. #ifndef NDEBUG
  23900. /*
  23901. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  23902. ** intended for use inside assert() statements.
  23903. */
  23904. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  23905. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  23906. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  23907. }
  23908. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  23909. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  23910. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  23911. }
  23912. #endif
  23913. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  23914. /************** End of mutex.c ***********************************************/
  23915. /************** Begin file mutex_noop.c **************************************/
  23916. /*
  23917. ** 2008 October 07
  23918. **
  23919. ** The author disclaims copyright to this source code. In place of
  23920. ** a legal notice, here is a blessing:
  23921. **
  23922. ** May you do good and not evil.
  23923. ** May you find forgiveness for yourself and forgive others.
  23924. ** May you share freely, never taking more than you give.
  23925. **
  23926. *************************************************************************
  23927. ** This file contains the C functions that implement mutexes.
  23928. **
  23929. ** This implementation in this file does not provide any mutual
  23930. ** exclusion and is thus suitable for use only in applications
  23931. ** that use SQLite in a single thread. The routines defined
  23932. ** here are place-holders. Applications can substitute working
  23933. ** mutex routines at start-time using the
  23934. **
  23935. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  23936. **
  23937. ** interface.
  23938. **
  23939. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  23940. ** that does error checking on mutexes to make sure they are being
  23941. ** called correctly.
  23942. */
  23943. /* #include "sqliteInt.h" */
  23944. #ifndef SQLITE_MUTEX_OMIT
  23945. #ifndef SQLITE_DEBUG
  23946. /*
  23947. ** Stub routines for all mutex methods.
  23948. **
  23949. ** This routines provide no mutual exclusion or error checking.
  23950. */
  23951. static int noopMutexInit(void){ return SQLITE_OK; }
  23952. static int noopMutexEnd(void){ return SQLITE_OK; }
  23953. static sqlite3_mutex *noopMutexAlloc(int id){
  23954. UNUSED_PARAMETER(id);
  23955. return (sqlite3_mutex*)8;
  23956. }
  23957. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  23958. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  23959. static int noopMutexTry(sqlite3_mutex *p){
  23960. UNUSED_PARAMETER(p);
  23961. return SQLITE_OK;
  23962. }
  23963. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  23964. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  23965. static const sqlite3_mutex_methods sMutex = {
  23966. noopMutexInit,
  23967. noopMutexEnd,
  23968. noopMutexAlloc,
  23969. noopMutexFree,
  23970. noopMutexEnter,
  23971. noopMutexTry,
  23972. noopMutexLeave,
  23973. 0,
  23974. 0,
  23975. };
  23976. return &sMutex;
  23977. }
  23978. #endif /* !SQLITE_DEBUG */
  23979. #ifdef SQLITE_DEBUG
  23980. /*
  23981. ** In this implementation, error checking is provided for testing
  23982. ** and debugging purposes. The mutexes still do not provide any
  23983. ** mutual exclusion.
  23984. */
  23985. /*
  23986. ** The mutex object
  23987. */
  23988. typedef struct sqlite3_debug_mutex {
  23989. int id; /* The mutex type */
  23990. int cnt; /* Number of entries without a matching leave */
  23991. } sqlite3_debug_mutex;
  23992. /*
  23993. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  23994. ** intended for use inside assert() statements.
  23995. */
  23996. static int debugMutexHeld(sqlite3_mutex *pX){
  23997. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23998. return p==0 || p->cnt>0;
  23999. }
  24000. static int debugMutexNotheld(sqlite3_mutex *pX){
  24001. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24002. return p==0 || p->cnt==0;
  24003. }
  24004. /*
  24005. ** Initialize and deinitialize the mutex subsystem.
  24006. */
  24007. static int debugMutexInit(void){ return SQLITE_OK; }
  24008. static int debugMutexEnd(void){ return SQLITE_OK; }
  24009. /*
  24010. ** The sqlite3_mutex_alloc() routine allocates a new
  24011. ** mutex and returns a pointer to it. If it returns NULL
  24012. ** that means that a mutex could not be allocated.
  24013. */
  24014. static sqlite3_mutex *debugMutexAlloc(int id){
  24015. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  24016. sqlite3_debug_mutex *pNew = 0;
  24017. switch( id ){
  24018. case SQLITE_MUTEX_FAST:
  24019. case SQLITE_MUTEX_RECURSIVE: {
  24020. pNew = sqlite3Malloc(sizeof(*pNew));
  24021. if( pNew ){
  24022. pNew->id = id;
  24023. pNew->cnt = 0;
  24024. }
  24025. break;
  24026. }
  24027. default: {
  24028. #ifdef SQLITE_ENABLE_API_ARMOR
  24029. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  24030. (void)SQLITE_MISUSE_BKPT;
  24031. return 0;
  24032. }
  24033. #endif
  24034. pNew = &aStatic[id-2];
  24035. pNew->id = id;
  24036. break;
  24037. }
  24038. }
  24039. return (sqlite3_mutex*)pNew;
  24040. }
  24041. /*
  24042. ** This routine deallocates a previously allocated mutex.
  24043. */
  24044. static void debugMutexFree(sqlite3_mutex *pX){
  24045. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24046. assert( p->cnt==0 );
  24047. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  24048. sqlite3_free(p);
  24049. }else{
  24050. #ifdef SQLITE_ENABLE_API_ARMOR
  24051. (void)SQLITE_MISUSE_BKPT;
  24052. #endif
  24053. }
  24054. }
  24055. /*
  24056. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  24057. ** to enter a mutex. If another thread is already within the mutex,
  24058. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  24059. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  24060. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  24061. ** be entered multiple times by the same thread. In such cases the,
  24062. ** mutex must be exited an equal number of times before another thread
  24063. ** can enter. If the same thread tries to enter any other kind of mutex
  24064. ** more than once, the behavior is undefined.
  24065. */
  24066. static void debugMutexEnter(sqlite3_mutex *pX){
  24067. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24068. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24069. p->cnt++;
  24070. }
  24071. static int debugMutexTry(sqlite3_mutex *pX){
  24072. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24073. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24074. p->cnt++;
  24075. return SQLITE_OK;
  24076. }
  24077. /*
  24078. ** The sqlite3_mutex_leave() routine exits a mutex that was
  24079. ** previously entered by the same thread. The behavior
  24080. ** is undefined if the mutex is not currently entered or
  24081. ** is not currently allocated. SQLite will never do either.
  24082. */
  24083. static void debugMutexLeave(sqlite3_mutex *pX){
  24084. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24085. assert( debugMutexHeld(pX) );
  24086. p->cnt--;
  24087. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24088. }
  24089. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  24090. static const sqlite3_mutex_methods sMutex = {
  24091. debugMutexInit,
  24092. debugMutexEnd,
  24093. debugMutexAlloc,
  24094. debugMutexFree,
  24095. debugMutexEnter,
  24096. debugMutexTry,
  24097. debugMutexLeave,
  24098. debugMutexHeld,
  24099. debugMutexNotheld
  24100. };
  24101. return &sMutex;
  24102. }
  24103. #endif /* SQLITE_DEBUG */
  24104. /*
  24105. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  24106. ** is used regardless of the run-time threadsafety setting.
  24107. */
  24108. #ifdef SQLITE_MUTEX_NOOP
  24109. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  24110. return sqlite3NoopMutex();
  24111. }
  24112. #endif /* defined(SQLITE_MUTEX_NOOP) */
  24113. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  24114. /************** End of mutex_noop.c ******************************************/
  24115. /************** Begin file mutex_unix.c **************************************/
  24116. /*
  24117. ** 2007 August 28
  24118. **
  24119. ** The author disclaims copyright to this source code. In place of
  24120. ** a legal notice, here is a blessing:
  24121. **
  24122. ** May you do good and not evil.
  24123. ** May you find forgiveness for yourself and forgive others.
  24124. ** May you share freely, never taking more than you give.
  24125. **
  24126. *************************************************************************
  24127. ** This file contains the C functions that implement mutexes for pthreads
  24128. */
  24129. /* #include "sqliteInt.h" */
  24130. /*
  24131. ** The code in this file is only used if we are compiling threadsafe
  24132. ** under unix with pthreads.
  24133. **
  24134. ** Note that this implementation requires a version of pthreads that
  24135. ** supports recursive mutexes.
  24136. */
  24137. #ifdef SQLITE_MUTEX_PTHREADS
  24138. #include <pthread.h>
  24139. /*
  24140. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  24141. ** are necessary under two condidtions: (1) Debug builds and (2) using
  24142. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  24143. */
  24144. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  24145. # define SQLITE_MUTEX_NREF 1
  24146. #else
  24147. # define SQLITE_MUTEX_NREF 0
  24148. #endif
  24149. /*
  24150. ** Each recursive mutex is an instance of the following structure.
  24151. */
  24152. struct sqlite3_mutex {
  24153. pthread_mutex_t mutex; /* Mutex controlling the lock */
  24154. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24155. int id; /* Mutex type */
  24156. #endif
  24157. #if SQLITE_MUTEX_NREF
  24158. volatile int nRef; /* Number of entrances */
  24159. volatile pthread_t owner; /* Thread that is within this mutex */
  24160. int trace; /* True to trace changes */
  24161. #endif
  24162. };
  24163. #if SQLITE_MUTEX_NREF
  24164. # define SQLITE3_MUTEX_INITIALIZER(id) \
  24165. {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}
  24166. #elif defined(SQLITE_ENABLE_API_ARMOR)
  24167. # define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }
  24168. #else
  24169. #define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }
  24170. #endif
  24171. /*
  24172. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24173. ** intended for use only inside assert() statements. On some platforms,
  24174. ** there might be race conditions that can cause these routines to
  24175. ** deliver incorrect results. In particular, if pthread_equal() is
  24176. ** not an atomic operation, then these routines might delivery
  24177. ** incorrect results. On most platforms, pthread_equal() is a
  24178. ** comparison of two integers and is therefore atomic. But we are
  24179. ** told that HPUX is not such a platform. If so, then these routines
  24180. ** will not always work correctly on HPUX.
  24181. **
  24182. ** On those platforms where pthread_equal() is not atomic, SQLite
  24183. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  24184. ** make sure no assert() statements are evaluated and hence these
  24185. ** routines are never called.
  24186. */
  24187. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  24188. static int pthreadMutexHeld(sqlite3_mutex *p){
  24189. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  24190. }
  24191. static int pthreadMutexNotheld(sqlite3_mutex *p){
  24192. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  24193. }
  24194. #endif
  24195. /*
  24196. ** Try to provide a memory barrier operation, needed for initialization
  24197. ** and also for the implementation of xShmBarrier in the VFS in cases
  24198. ** where SQLite is compiled without mutexes.
  24199. */
  24200. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  24201. #if defined(SQLITE_MEMORY_BARRIER)
  24202. SQLITE_MEMORY_BARRIER;
  24203. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  24204. __sync_synchronize();
  24205. #endif
  24206. }
  24207. /*
  24208. ** Initialize and deinitialize the mutex subsystem.
  24209. */
  24210. static int pthreadMutexInit(void){ return SQLITE_OK; }
  24211. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  24212. /*
  24213. ** The sqlite3_mutex_alloc() routine allocates a new
  24214. ** mutex and returns a pointer to it. If it returns NULL
  24215. ** that means that a mutex could not be allocated. SQLite
  24216. ** will unwind its stack and return an error. The argument
  24217. ** to sqlite3_mutex_alloc() is one of these integer constants:
  24218. **
  24219. ** <ul>
  24220. ** <li> SQLITE_MUTEX_FAST
  24221. ** <li> SQLITE_MUTEX_RECURSIVE
  24222. ** <li> SQLITE_MUTEX_STATIC_MASTER
  24223. ** <li> SQLITE_MUTEX_STATIC_MEM
  24224. ** <li> SQLITE_MUTEX_STATIC_OPEN
  24225. ** <li> SQLITE_MUTEX_STATIC_PRNG
  24226. ** <li> SQLITE_MUTEX_STATIC_LRU
  24227. ** <li> SQLITE_MUTEX_STATIC_PMEM
  24228. ** <li> SQLITE_MUTEX_STATIC_APP1
  24229. ** <li> SQLITE_MUTEX_STATIC_APP2
  24230. ** <li> SQLITE_MUTEX_STATIC_APP3
  24231. ** <li> SQLITE_MUTEX_STATIC_VFS1
  24232. ** <li> SQLITE_MUTEX_STATIC_VFS2
  24233. ** <li> SQLITE_MUTEX_STATIC_VFS3
  24234. ** </ul>
  24235. **
  24236. ** The first two constants cause sqlite3_mutex_alloc() to create
  24237. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  24238. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  24239. ** The mutex implementation does not need to make a distinction
  24240. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  24241. ** not want to. But SQLite will only request a recursive mutex in
  24242. ** cases where it really needs one. If a faster non-recursive mutex
  24243. ** implementation is available on the host platform, the mutex subsystem
  24244. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  24245. **
  24246. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  24247. ** a pointer to a static preexisting mutex. Six static mutexes are
  24248. ** used by the current version of SQLite. Future versions of SQLite
  24249. ** may add additional static mutexes. Static mutexes are for internal
  24250. ** use by SQLite only. Applications that use SQLite mutexes should
  24251. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  24252. ** SQLITE_MUTEX_RECURSIVE.
  24253. **
  24254. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  24255. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  24256. ** returns a different mutex on every call. But for the static
  24257. ** mutex types, the same mutex is returned on every call that has
  24258. ** the same type number.
  24259. */
  24260. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  24261. static sqlite3_mutex staticMutexes[] = {
  24262. SQLITE3_MUTEX_INITIALIZER(2),
  24263. SQLITE3_MUTEX_INITIALIZER(3),
  24264. SQLITE3_MUTEX_INITIALIZER(4),
  24265. SQLITE3_MUTEX_INITIALIZER(5),
  24266. SQLITE3_MUTEX_INITIALIZER(6),
  24267. SQLITE3_MUTEX_INITIALIZER(7),
  24268. SQLITE3_MUTEX_INITIALIZER(8),
  24269. SQLITE3_MUTEX_INITIALIZER(9),
  24270. SQLITE3_MUTEX_INITIALIZER(10),
  24271. SQLITE3_MUTEX_INITIALIZER(11),
  24272. SQLITE3_MUTEX_INITIALIZER(12),
  24273. SQLITE3_MUTEX_INITIALIZER(13)
  24274. };
  24275. sqlite3_mutex *p;
  24276. switch( iType ){
  24277. case SQLITE_MUTEX_RECURSIVE: {
  24278. p = sqlite3MallocZero( sizeof(*p) );
  24279. if( p ){
  24280. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24281. /* If recursive mutexes are not available, we will have to
  24282. ** build our own. See below. */
  24283. pthread_mutex_init(&p->mutex, 0);
  24284. #else
  24285. /* Use a recursive mutex if it is available */
  24286. pthread_mutexattr_t recursiveAttr;
  24287. pthread_mutexattr_init(&recursiveAttr);
  24288. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  24289. pthread_mutex_init(&p->mutex, &recursiveAttr);
  24290. pthread_mutexattr_destroy(&recursiveAttr);
  24291. #endif
  24292. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24293. p->id = SQLITE_MUTEX_RECURSIVE;
  24294. #endif
  24295. }
  24296. break;
  24297. }
  24298. case SQLITE_MUTEX_FAST: {
  24299. p = sqlite3MallocZero( sizeof(*p) );
  24300. if( p ){
  24301. pthread_mutex_init(&p->mutex, 0);
  24302. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24303. p->id = SQLITE_MUTEX_FAST;
  24304. #endif
  24305. }
  24306. break;
  24307. }
  24308. default: {
  24309. #ifdef SQLITE_ENABLE_API_ARMOR
  24310. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  24311. (void)SQLITE_MISUSE_BKPT;
  24312. return 0;
  24313. }
  24314. #endif
  24315. p = &staticMutexes[iType-2];
  24316. break;
  24317. }
  24318. }
  24319. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24320. assert( p==0 || p->id==iType );
  24321. #endif
  24322. return p;
  24323. }
  24324. /*
  24325. ** This routine deallocates a previously
  24326. ** allocated mutex. SQLite is careful to deallocate every
  24327. ** mutex that it allocates.
  24328. */
  24329. static void pthreadMutexFree(sqlite3_mutex *p){
  24330. assert( p->nRef==0 );
  24331. #if SQLITE_ENABLE_API_ARMOR
  24332. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  24333. #endif
  24334. {
  24335. pthread_mutex_destroy(&p->mutex);
  24336. sqlite3_free(p);
  24337. }
  24338. #ifdef SQLITE_ENABLE_API_ARMOR
  24339. else{
  24340. (void)SQLITE_MISUSE_BKPT;
  24341. }
  24342. #endif
  24343. }
  24344. /*
  24345. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  24346. ** to enter a mutex. If another thread is already within the mutex,
  24347. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  24348. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  24349. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  24350. ** be entered multiple times by the same thread. In such cases the,
  24351. ** mutex must be exited an equal number of times before another thread
  24352. ** can enter. If the same thread tries to enter any other kind of mutex
  24353. ** more than once, the behavior is undefined.
  24354. */
  24355. static void pthreadMutexEnter(sqlite3_mutex *p){
  24356. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  24357. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24358. /* If recursive mutexes are not available, then we have to grow
  24359. ** our own. This implementation assumes that pthread_equal()
  24360. ** is atomic - that it cannot be deceived into thinking self
  24361. ** and p->owner are equal if p->owner changes between two values
  24362. ** that are not equal to self while the comparison is taking place.
  24363. ** This implementation also assumes a coherent cache - that
  24364. ** separate processes cannot read different values from the same
  24365. ** address at the same time. If either of these two conditions
  24366. ** are not met, then the mutexes will fail and problems will result.
  24367. */
  24368. {
  24369. pthread_t self = pthread_self();
  24370. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  24371. p->nRef++;
  24372. }else{
  24373. pthread_mutex_lock(&p->mutex);
  24374. assert( p->nRef==0 );
  24375. p->owner = self;
  24376. p->nRef = 1;
  24377. }
  24378. }
  24379. #else
  24380. /* Use the built-in recursive mutexes if they are available.
  24381. */
  24382. pthread_mutex_lock(&p->mutex);
  24383. #if SQLITE_MUTEX_NREF
  24384. assert( p->nRef>0 || p->owner==0 );
  24385. p->owner = pthread_self();
  24386. p->nRef++;
  24387. #endif
  24388. #endif
  24389. #ifdef SQLITE_DEBUG
  24390. if( p->trace ){
  24391. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  24392. }
  24393. #endif
  24394. }
  24395. static int pthreadMutexTry(sqlite3_mutex *p){
  24396. int rc;
  24397. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  24398. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24399. /* If recursive mutexes are not available, then we have to grow
  24400. ** our own. This implementation assumes that pthread_equal()
  24401. ** is atomic - that it cannot be deceived into thinking self
  24402. ** and p->owner are equal if p->owner changes between two values
  24403. ** that are not equal to self while the comparison is taking place.
  24404. ** This implementation also assumes a coherent cache - that
  24405. ** separate processes cannot read different values from the same
  24406. ** address at the same time. If either of these two conditions
  24407. ** are not met, then the mutexes will fail and problems will result.
  24408. */
  24409. {
  24410. pthread_t self = pthread_self();
  24411. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  24412. p->nRef++;
  24413. rc = SQLITE_OK;
  24414. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  24415. assert( p->nRef==0 );
  24416. p->owner = self;
  24417. p->nRef = 1;
  24418. rc = SQLITE_OK;
  24419. }else{
  24420. rc = SQLITE_BUSY;
  24421. }
  24422. }
  24423. #else
  24424. /* Use the built-in recursive mutexes if they are available.
  24425. */
  24426. if( pthread_mutex_trylock(&p->mutex)==0 ){
  24427. #if SQLITE_MUTEX_NREF
  24428. p->owner = pthread_self();
  24429. p->nRef++;
  24430. #endif
  24431. rc = SQLITE_OK;
  24432. }else{
  24433. rc = SQLITE_BUSY;
  24434. }
  24435. #endif
  24436. #ifdef SQLITE_DEBUG
  24437. if( rc==SQLITE_OK && p->trace ){
  24438. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  24439. }
  24440. #endif
  24441. return rc;
  24442. }
  24443. /*
  24444. ** The sqlite3_mutex_leave() routine exits a mutex that was
  24445. ** previously entered by the same thread. The behavior
  24446. ** is undefined if the mutex is not currently entered or
  24447. ** is not currently allocated. SQLite will never do either.
  24448. */
  24449. static void pthreadMutexLeave(sqlite3_mutex *p){
  24450. assert( pthreadMutexHeld(p) );
  24451. #if SQLITE_MUTEX_NREF
  24452. p->nRef--;
  24453. if( p->nRef==0 ) p->owner = 0;
  24454. #endif
  24455. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  24456. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24457. if( p->nRef==0 ){
  24458. pthread_mutex_unlock(&p->mutex);
  24459. }
  24460. #else
  24461. pthread_mutex_unlock(&p->mutex);
  24462. #endif
  24463. #ifdef SQLITE_DEBUG
  24464. if( p->trace ){
  24465. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  24466. }
  24467. #endif
  24468. }
  24469. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  24470. static const sqlite3_mutex_methods sMutex = {
  24471. pthreadMutexInit,
  24472. pthreadMutexEnd,
  24473. pthreadMutexAlloc,
  24474. pthreadMutexFree,
  24475. pthreadMutexEnter,
  24476. pthreadMutexTry,
  24477. pthreadMutexLeave,
  24478. #ifdef SQLITE_DEBUG
  24479. pthreadMutexHeld,
  24480. pthreadMutexNotheld
  24481. #else
  24482. 0,
  24483. 0
  24484. #endif
  24485. };
  24486. return &sMutex;
  24487. }
  24488. #endif /* SQLITE_MUTEX_PTHREADS */
  24489. /************** End of mutex_unix.c ******************************************/
  24490. /************** Begin file mutex_w32.c ***************************************/
  24491. /*
  24492. ** 2007 August 14
  24493. **
  24494. ** The author disclaims copyright to this source code. In place of
  24495. ** a legal notice, here is a blessing:
  24496. **
  24497. ** May you do good and not evil.
  24498. ** May you find forgiveness for yourself and forgive others.
  24499. ** May you share freely, never taking more than you give.
  24500. **
  24501. *************************************************************************
  24502. ** This file contains the C functions that implement mutexes for Win32.
  24503. */
  24504. /* #include "sqliteInt.h" */
  24505. #if SQLITE_OS_WIN
  24506. /*
  24507. ** Include code that is common to all os_*.c files
  24508. */
  24509. /************** Include os_common.h in the middle of mutex_w32.c *************/
  24510. /************** Begin file os_common.h ***************************************/
  24511. /*
  24512. ** 2004 May 22
  24513. **
  24514. ** The author disclaims copyright to this source code. In place of
  24515. ** a legal notice, here is a blessing:
  24516. **
  24517. ** May you do good and not evil.
  24518. ** May you find forgiveness for yourself and forgive others.
  24519. ** May you share freely, never taking more than you give.
  24520. **
  24521. ******************************************************************************
  24522. **
  24523. ** This file contains macros and a little bit of code that is common to
  24524. ** all of the platform-specific files (os_*.c) and is #included into those
  24525. ** files.
  24526. **
  24527. ** This file should be #included by the os_*.c files only. It is not a
  24528. ** general purpose header file.
  24529. */
  24530. #ifndef _OS_COMMON_H_
  24531. #define _OS_COMMON_H_
  24532. /*
  24533. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  24534. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  24535. ** switch. The following code should catch this problem at compile-time.
  24536. */
  24537. #ifdef MEMORY_DEBUG
  24538. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  24539. #endif
  24540. /*
  24541. ** Macros for performance tracing. Normally turned off. Only works
  24542. ** on i486 hardware.
  24543. */
  24544. #ifdef SQLITE_PERFORMANCE_TRACE
  24545. /*
  24546. ** hwtime.h contains inline assembler code for implementing
  24547. ** high-performance timing routines.
  24548. */
  24549. /************** Include hwtime.h in the middle of os_common.h ****************/
  24550. /************** Begin file hwtime.h ******************************************/
  24551. /*
  24552. ** 2008 May 27
  24553. **
  24554. ** The author disclaims copyright to this source code. In place of
  24555. ** a legal notice, here is a blessing:
  24556. **
  24557. ** May you do good and not evil.
  24558. ** May you find forgiveness for yourself and forgive others.
  24559. ** May you share freely, never taking more than you give.
  24560. **
  24561. ******************************************************************************
  24562. **
  24563. ** This file contains inline asm code for retrieving "high-performance"
  24564. ** counters for x86 class CPUs.
  24565. */
  24566. #ifndef SQLITE_HWTIME_H
  24567. #define SQLITE_HWTIME_H
  24568. /*
  24569. ** The following routine only works on pentium-class (or newer) processors.
  24570. ** It uses the RDTSC opcode to read the cycle count value out of the
  24571. ** processor and returns that value. This can be used for high-res
  24572. ** profiling.
  24573. */
  24574. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  24575. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  24576. #if defined(__GNUC__)
  24577. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24578. unsigned int lo, hi;
  24579. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  24580. return (sqlite_uint64)hi << 32 | lo;
  24581. }
  24582. #elif defined(_MSC_VER)
  24583. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  24584. __asm {
  24585. rdtsc
  24586. ret ; return value at EDX:EAX
  24587. }
  24588. }
  24589. #endif
  24590. #elif (defined(__GNUC__) && defined(__x86_64__))
  24591. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24592. unsigned long val;
  24593. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  24594. return val;
  24595. }
  24596. #elif (defined(__GNUC__) && defined(__ppc__))
  24597. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24598. unsigned long long retval;
  24599. unsigned long junk;
  24600. __asm__ __volatile__ ("\n\
  24601. 1: mftbu %1\n\
  24602. mftb %L0\n\
  24603. mftbu %0\n\
  24604. cmpw %0,%1\n\
  24605. bne 1b"
  24606. : "=r" (retval), "=r" (junk));
  24607. return retval;
  24608. }
  24609. #else
  24610. #error Need implementation of sqlite3Hwtime() for your platform.
  24611. /*
  24612. ** To compile without implementing sqlite3Hwtime() for your platform,
  24613. ** you can remove the above #error and use the following
  24614. ** stub function. You will lose timing support for many
  24615. ** of the debugging and testing utilities, but it should at
  24616. ** least compile and run.
  24617. */
  24618. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  24619. #endif
  24620. #endif /* !defined(SQLITE_HWTIME_H) */
  24621. /************** End of hwtime.h **********************************************/
  24622. /************** Continuing where we left off in os_common.h ******************/
  24623. static sqlite_uint64 g_start;
  24624. static sqlite_uint64 g_elapsed;
  24625. #define TIMER_START g_start=sqlite3Hwtime()
  24626. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  24627. #define TIMER_ELAPSED g_elapsed
  24628. #else
  24629. #define TIMER_START
  24630. #define TIMER_END
  24631. #define TIMER_ELAPSED ((sqlite_uint64)0)
  24632. #endif
  24633. /*
  24634. ** If we compile with the SQLITE_TEST macro set, then the following block
  24635. ** of code will give us the ability to simulate a disk I/O error. This
  24636. ** is used for testing the I/O recovery logic.
  24637. */
  24638. #if defined(SQLITE_TEST)
  24639. SQLITE_API extern int sqlite3_io_error_hit;
  24640. SQLITE_API extern int sqlite3_io_error_hardhit;
  24641. SQLITE_API extern int sqlite3_io_error_pending;
  24642. SQLITE_API extern int sqlite3_io_error_persist;
  24643. SQLITE_API extern int sqlite3_io_error_benign;
  24644. SQLITE_API extern int sqlite3_diskfull_pending;
  24645. SQLITE_API extern int sqlite3_diskfull;
  24646. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  24647. #define SimulateIOError(CODE) \
  24648. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  24649. || sqlite3_io_error_pending-- == 1 ) \
  24650. { local_ioerr(); CODE; }
  24651. static void local_ioerr(){
  24652. IOTRACE(("IOERR\n"));
  24653. sqlite3_io_error_hit++;
  24654. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  24655. }
  24656. #define SimulateDiskfullError(CODE) \
  24657. if( sqlite3_diskfull_pending ){ \
  24658. if( sqlite3_diskfull_pending == 1 ){ \
  24659. local_ioerr(); \
  24660. sqlite3_diskfull = 1; \
  24661. sqlite3_io_error_hit = 1; \
  24662. CODE; \
  24663. }else{ \
  24664. sqlite3_diskfull_pending--; \
  24665. } \
  24666. }
  24667. #else
  24668. #define SimulateIOErrorBenign(X)
  24669. #define SimulateIOError(A)
  24670. #define SimulateDiskfullError(A)
  24671. #endif /* defined(SQLITE_TEST) */
  24672. /*
  24673. ** When testing, keep a count of the number of open files.
  24674. */
  24675. #if defined(SQLITE_TEST)
  24676. SQLITE_API extern int sqlite3_open_file_count;
  24677. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  24678. #else
  24679. #define OpenCounter(X)
  24680. #endif /* defined(SQLITE_TEST) */
  24681. #endif /* !defined(_OS_COMMON_H_) */
  24682. /************** End of os_common.h *******************************************/
  24683. /************** Continuing where we left off in mutex_w32.c ******************/
  24684. /*
  24685. ** Include the header file for the Windows VFS.
  24686. */
  24687. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  24688. /************** Begin file os_win.h ******************************************/
  24689. /*
  24690. ** 2013 November 25
  24691. **
  24692. ** The author disclaims copyright to this source code. In place of
  24693. ** a legal notice, here is a blessing:
  24694. **
  24695. ** May you do good and not evil.
  24696. ** May you find forgiveness for yourself and forgive others.
  24697. ** May you share freely, never taking more than you give.
  24698. **
  24699. ******************************************************************************
  24700. **
  24701. ** This file contains code that is specific to Windows.
  24702. */
  24703. #ifndef SQLITE_OS_WIN_H
  24704. #define SQLITE_OS_WIN_H
  24705. /*
  24706. ** Include the primary Windows SDK header file.
  24707. */
  24708. #include "windows.h"
  24709. #ifdef __CYGWIN__
  24710. # include <sys/cygwin.h>
  24711. # include <errno.h> /* amalgamator: dontcache */
  24712. #endif
  24713. /*
  24714. ** Determine if we are dealing with Windows NT.
  24715. **
  24716. ** We ought to be able to determine if we are compiling for Windows 9x or
  24717. ** Windows NT using the _WIN32_WINNT macro as follows:
  24718. **
  24719. ** #if defined(_WIN32_WINNT)
  24720. ** # define SQLITE_OS_WINNT 1
  24721. ** #else
  24722. ** # define SQLITE_OS_WINNT 0
  24723. ** #endif
  24724. **
  24725. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  24726. ** it ought to, so the above test does not work. We'll just assume that
  24727. ** everything is Windows NT unless the programmer explicitly says otherwise
  24728. ** by setting SQLITE_OS_WINNT to 0.
  24729. */
  24730. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  24731. # define SQLITE_OS_WINNT 1
  24732. #endif
  24733. /*
  24734. ** Determine if we are dealing with Windows CE - which has a much reduced
  24735. ** API.
  24736. */
  24737. #if defined(_WIN32_WCE)
  24738. # define SQLITE_OS_WINCE 1
  24739. #else
  24740. # define SQLITE_OS_WINCE 0
  24741. #endif
  24742. /*
  24743. ** Determine if we are dealing with WinRT, which provides only a subset of
  24744. ** the full Win32 API.
  24745. */
  24746. #if !defined(SQLITE_OS_WINRT)
  24747. # define SQLITE_OS_WINRT 0
  24748. #endif
  24749. /*
  24750. ** For WinCE, some API function parameters do not appear to be declared as
  24751. ** volatile.
  24752. */
  24753. #if SQLITE_OS_WINCE
  24754. # define SQLITE_WIN32_VOLATILE
  24755. #else
  24756. # define SQLITE_WIN32_VOLATILE volatile
  24757. #endif
  24758. /*
  24759. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  24760. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  24761. */
  24762. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  24763. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  24764. # define SQLITE_OS_WIN_THREADS 1
  24765. #else
  24766. # define SQLITE_OS_WIN_THREADS 0
  24767. #endif
  24768. #endif /* SQLITE_OS_WIN_H */
  24769. /************** End of os_win.h **********************************************/
  24770. /************** Continuing where we left off in mutex_w32.c ******************/
  24771. #endif
  24772. /*
  24773. ** The code in this file is only used if we are compiling multithreaded
  24774. ** on a Win32 system.
  24775. */
  24776. #ifdef SQLITE_MUTEX_W32
  24777. /*
  24778. ** Each recursive mutex is an instance of the following structure.
  24779. */
  24780. struct sqlite3_mutex {
  24781. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  24782. int id; /* Mutex type */
  24783. #ifdef SQLITE_DEBUG
  24784. volatile int nRef; /* Number of enterances */
  24785. volatile DWORD owner; /* Thread holding this mutex */
  24786. volatile LONG trace; /* True to trace changes */
  24787. #endif
  24788. };
  24789. /*
  24790. ** These are the initializer values used when declaring a "static" mutex
  24791. ** on Win32. It should be noted that all mutexes require initialization
  24792. ** on the Win32 platform.
  24793. */
  24794. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  24795. #ifdef SQLITE_DEBUG
  24796. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \
  24797. 0L, (DWORD)0, 0 }
  24798. #else
  24799. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }
  24800. #endif
  24801. #ifdef SQLITE_DEBUG
  24802. /*
  24803. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24804. ** intended for use only inside assert() statements.
  24805. */
  24806. static int winMutexHeld(sqlite3_mutex *p){
  24807. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  24808. }
  24809. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  24810. return p->nRef==0 || p->owner!=tid;
  24811. }
  24812. static int winMutexNotheld(sqlite3_mutex *p){
  24813. DWORD tid = GetCurrentThreadId();
  24814. return winMutexNotheld2(p, tid);
  24815. }
  24816. #endif
  24817. /*
  24818. ** Try to provide a memory barrier operation, needed for initialization
  24819. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  24820. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  24821. */
  24822. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  24823. #if defined(SQLITE_MEMORY_BARRIER)
  24824. SQLITE_MEMORY_BARRIER;
  24825. #elif defined(__GNUC__)
  24826. __sync_synchronize();
  24827. #elif MSVC_VERSION>=1300
  24828. _ReadWriteBarrier();
  24829. #elif defined(MemoryBarrier)
  24830. MemoryBarrier();
  24831. #endif
  24832. }
  24833. /*
  24834. ** Initialize and deinitialize the mutex subsystem.
  24835. */
  24836. static sqlite3_mutex winMutex_staticMutexes[] = {
  24837. SQLITE3_MUTEX_INITIALIZER(2),
  24838. SQLITE3_MUTEX_INITIALIZER(3),
  24839. SQLITE3_MUTEX_INITIALIZER(4),
  24840. SQLITE3_MUTEX_INITIALIZER(5),
  24841. SQLITE3_MUTEX_INITIALIZER(6),
  24842. SQLITE3_MUTEX_INITIALIZER(7),
  24843. SQLITE3_MUTEX_INITIALIZER(8),
  24844. SQLITE3_MUTEX_INITIALIZER(9),
  24845. SQLITE3_MUTEX_INITIALIZER(10),
  24846. SQLITE3_MUTEX_INITIALIZER(11),
  24847. SQLITE3_MUTEX_INITIALIZER(12),
  24848. SQLITE3_MUTEX_INITIALIZER(13)
  24849. };
  24850. static int winMutex_isInit = 0;
  24851. static int winMutex_isNt = -1; /* <0 means "need to query" */
  24852. /* As the winMutexInit() and winMutexEnd() functions are called as part
  24853. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  24854. ** "interlocked" magic used here is probably not strictly necessary.
  24855. */
  24856. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  24857. SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
  24858. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  24859. static int winMutexInit(void){
  24860. /* The first to increment to 1 does actual initialization */
  24861. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  24862. int i;
  24863. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  24864. #if SQLITE_OS_WINRT
  24865. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  24866. #else
  24867. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  24868. #endif
  24869. }
  24870. winMutex_isInit = 1;
  24871. }else{
  24872. /* Another thread is (in the process of) initializing the static
  24873. ** mutexes */
  24874. while( !winMutex_isInit ){
  24875. sqlite3_win32_sleep(1);
  24876. }
  24877. }
  24878. return SQLITE_OK;
  24879. }
  24880. static int winMutexEnd(void){
  24881. /* The first to decrement to 0 does actual shutdown
  24882. ** (which should be the last to shutdown.) */
  24883. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  24884. if( winMutex_isInit==1 ){
  24885. int i;
  24886. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  24887. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  24888. }
  24889. winMutex_isInit = 0;
  24890. }
  24891. }
  24892. return SQLITE_OK;
  24893. }
  24894. /*
  24895. ** The sqlite3_mutex_alloc() routine allocates a new
  24896. ** mutex and returns a pointer to it. If it returns NULL
  24897. ** that means that a mutex could not be allocated. SQLite
  24898. ** will unwind its stack and return an error. The argument
  24899. ** to sqlite3_mutex_alloc() is one of these integer constants:
  24900. **
  24901. ** <ul>
  24902. ** <li> SQLITE_MUTEX_FAST
  24903. ** <li> SQLITE_MUTEX_RECURSIVE
  24904. ** <li> SQLITE_MUTEX_STATIC_MASTER
  24905. ** <li> SQLITE_MUTEX_STATIC_MEM
  24906. ** <li> SQLITE_MUTEX_STATIC_OPEN
  24907. ** <li> SQLITE_MUTEX_STATIC_PRNG
  24908. ** <li> SQLITE_MUTEX_STATIC_LRU
  24909. ** <li> SQLITE_MUTEX_STATIC_PMEM
  24910. ** <li> SQLITE_MUTEX_STATIC_APP1
  24911. ** <li> SQLITE_MUTEX_STATIC_APP2
  24912. ** <li> SQLITE_MUTEX_STATIC_APP3
  24913. ** <li> SQLITE_MUTEX_STATIC_VFS1
  24914. ** <li> SQLITE_MUTEX_STATIC_VFS2
  24915. ** <li> SQLITE_MUTEX_STATIC_VFS3
  24916. ** </ul>
  24917. **
  24918. ** The first two constants cause sqlite3_mutex_alloc() to create
  24919. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  24920. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  24921. ** The mutex implementation does not need to make a distinction
  24922. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  24923. ** not want to. But SQLite will only request a recursive mutex in
  24924. ** cases where it really needs one. If a faster non-recursive mutex
  24925. ** implementation is available on the host platform, the mutex subsystem
  24926. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  24927. **
  24928. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  24929. ** a pointer to a static preexisting mutex. Six static mutexes are
  24930. ** used by the current version of SQLite. Future versions of SQLite
  24931. ** may add additional static mutexes. Static mutexes are for internal
  24932. ** use by SQLite only. Applications that use SQLite mutexes should
  24933. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  24934. ** SQLITE_MUTEX_RECURSIVE.
  24935. **
  24936. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  24937. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  24938. ** returns a different mutex on every call. But for the static
  24939. ** mutex types, the same mutex is returned on every call that has
  24940. ** the same type number.
  24941. */
  24942. static sqlite3_mutex *winMutexAlloc(int iType){
  24943. sqlite3_mutex *p;
  24944. switch( iType ){
  24945. case SQLITE_MUTEX_FAST:
  24946. case SQLITE_MUTEX_RECURSIVE: {
  24947. p = sqlite3MallocZero( sizeof(*p) );
  24948. if( p ){
  24949. p->id = iType;
  24950. #ifdef SQLITE_DEBUG
  24951. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  24952. p->trace = 1;
  24953. #endif
  24954. #endif
  24955. #if SQLITE_OS_WINRT
  24956. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  24957. #else
  24958. InitializeCriticalSection(&p->mutex);
  24959. #endif
  24960. }
  24961. break;
  24962. }
  24963. default: {
  24964. #ifdef SQLITE_ENABLE_API_ARMOR
  24965. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  24966. (void)SQLITE_MISUSE_BKPT;
  24967. return 0;
  24968. }
  24969. #endif
  24970. p = &winMutex_staticMutexes[iType-2];
  24971. #ifdef SQLITE_DEBUG
  24972. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  24973. InterlockedCompareExchange(&p->trace, 1, 0);
  24974. #endif
  24975. #endif
  24976. break;
  24977. }
  24978. }
  24979. assert( p==0 || p->id==iType );
  24980. return p;
  24981. }
  24982. /*
  24983. ** This routine deallocates a previously
  24984. ** allocated mutex. SQLite is careful to deallocate every
  24985. ** mutex that it allocates.
  24986. */
  24987. static void winMutexFree(sqlite3_mutex *p){
  24988. assert( p );
  24989. assert( p->nRef==0 && p->owner==0 );
  24990. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  24991. DeleteCriticalSection(&p->mutex);
  24992. sqlite3_free(p);
  24993. }else{
  24994. #ifdef SQLITE_ENABLE_API_ARMOR
  24995. (void)SQLITE_MISUSE_BKPT;
  24996. #endif
  24997. }
  24998. }
  24999. /*
  25000. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  25001. ** to enter a mutex. If another thread is already within the mutex,
  25002. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  25003. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  25004. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  25005. ** be entered multiple times by the same thread. In such cases the,
  25006. ** mutex must be exited an equal number of times before another thread
  25007. ** can enter. If the same thread tries to enter any other kind of mutex
  25008. ** more than once, the behavior is undefined.
  25009. */
  25010. static void winMutexEnter(sqlite3_mutex *p){
  25011. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25012. DWORD tid = GetCurrentThreadId();
  25013. #endif
  25014. #ifdef SQLITE_DEBUG
  25015. assert( p );
  25016. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  25017. #else
  25018. assert( p );
  25019. #endif
  25020. assert( winMutex_isInit==1 );
  25021. EnterCriticalSection(&p->mutex);
  25022. #ifdef SQLITE_DEBUG
  25023. assert( p->nRef>0 || p->owner==0 );
  25024. p->owner = tid;
  25025. p->nRef++;
  25026. if( p->trace ){
  25027. OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  25028. tid, p->id, p, p->trace, p->nRef));
  25029. }
  25030. #endif
  25031. }
  25032. static int winMutexTry(sqlite3_mutex *p){
  25033. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25034. DWORD tid = GetCurrentThreadId();
  25035. #endif
  25036. int rc = SQLITE_BUSY;
  25037. assert( p );
  25038. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  25039. /*
  25040. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  25041. ** is used it is merely an optimization. So it is OK for it to always
  25042. ** fail.
  25043. **
  25044. ** The TryEnterCriticalSection() interface is only available on WinNT.
  25045. ** And some windows compilers complain if you try to use it without
  25046. ** first doing some #defines that prevent SQLite from building on Win98.
  25047. ** For that reason, we will omit this optimization for now. See
  25048. ** ticket #2685.
  25049. */
  25050. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  25051. assert( winMutex_isInit==1 );
  25052. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  25053. if( winMutex_isNt<0 ){
  25054. winMutex_isNt = sqlite3_win32_is_nt();
  25055. }
  25056. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  25057. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  25058. #ifdef SQLITE_DEBUG
  25059. p->owner = tid;
  25060. p->nRef++;
  25061. #endif
  25062. rc = SQLITE_OK;
  25063. }
  25064. #else
  25065. UNUSED_PARAMETER(p);
  25066. #endif
  25067. #ifdef SQLITE_DEBUG
  25068. if( p->trace ){
  25069. OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  25070. tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  25071. }
  25072. #endif
  25073. return rc;
  25074. }
  25075. /*
  25076. ** The sqlite3_mutex_leave() routine exits a mutex that was
  25077. ** previously entered by the same thread. The behavior
  25078. ** is undefined if the mutex is not currently entered or
  25079. ** is not currently allocated. SQLite will never do either.
  25080. */
  25081. static void winMutexLeave(sqlite3_mutex *p){
  25082. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25083. DWORD tid = GetCurrentThreadId();
  25084. #endif
  25085. assert( p );
  25086. #ifdef SQLITE_DEBUG
  25087. assert( p->nRef>0 );
  25088. assert( p->owner==tid );
  25089. p->nRef--;
  25090. if( p->nRef==0 ) p->owner = 0;
  25091. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  25092. #endif
  25093. assert( winMutex_isInit==1 );
  25094. LeaveCriticalSection(&p->mutex);
  25095. #ifdef SQLITE_DEBUG
  25096. if( p->trace ){
  25097. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  25098. tid, p->id, p, p->trace, p->nRef));
  25099. }
  25100. #endif
  25101. }
  25102. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  25103. static const sqlite3_mutex_methods sMutex = {
  25104. winMutexInit,
  25105. winMutexEnd,
  25106. winMutexAlloc,
  25107. winMutexFree,
  25108. winMutexEnter,
  25109. winMutexTry,
  25110. winMutexLeave,
  25111. #ifdef SQLITE_DEBUG
  25112. winMutexHeld,
  25113. winMutexNotheld
  25114. #else
  25115. 0,
  25116. 0
  25117. #endif
  25118. };
  25119. return &sMutex;
  25120. }
  25121. #endif /* SQLITE_MUTEX_W32 */
  25122. /************** End of mutex_w32.c *******************************************/
  25123. /************** Begin file malloc.c ******************************************/
  25124. /*
  25125. ** 2001 September 15
  25126. **
  25127. ** The author disclaims copyright to this source code. In place of
  25128. ** a legal notice, here is a blessing:
  25129. **
  25130. ** May you do good and not evil.
  25131. ** May you find forgiveness for yourself and forgive others.
  25132. ** May you share freely, never taking more than you give.
  25133. **
  25134. *************************************************************************
  25135. **
  25136. ** Memory allocation functions used throughout sqlite.
  25137. */
  25138. /* #include "sqliteInt.h" */
  25139. /* #include <stdarg.h> */
  25140. /*
  25141. ** Attempt to release up to n bytes of non-essential memory currently
  25142. ** held by SQLite. An example of non-essential memory is memory used to
  25143. ** cache database pages that are not currently in use.
  25144. */
  25145. SQLITE_API int sqlite3_release_memory(int n){
  25146. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  25147. return sqlite3PcacheReleaseMemory(n);
  25148. #else
  25149. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  25150. ** is a no-op returning zero if SQLite is not compiled with
  25151. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  25152. UNUSED_PARAMETER(n);
  25153. return 0;
  25154. #endif
  25155. }
  25156. /*
  25157. ** State information local to the memory allocation subsystem.
  25158. */
  25159. static SQLITE_WSD struct Mem0Global {
  25160. sqlite3_mutex *mutex; /* Mutex to serialize access */
  25161. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  25162. /*
  25163. ** True if heap is nearly "full" where "full" is defined by the
  25164. ** sqlite3_soft_heap_limit() setting.
  25165. */
  25166. int nearlyFull;
  25167. } mem0 = { 0, 0, 0 };
  25168. #define mem0 GLOBAL(struct Mem0Global, mem0)
  25169. /*
  25170. ** Return the memory allocator mutex. sqlite3_status() needs it.
  25171. */
  25172. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  25173. return mem0.mutex;
  25174. }
  25175. #ifndef SQLITE_OMIT_DEPRECATED
  25176. /*
  25177. ** Deprecated external interface. It used to set an alarm callback
  25178. ** that was invoked when memory usage grew too large. Now it is a
  25179. ** no-op.
  25180. */
  25181. SQLITE_API int sqlite3_memory_alarm(
  25182. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  25183. void *pArg,
  25184. sqlite3_int64 iThreshold
  25185. ){
  25186. (void)xCallback;
  25187. (void)pArg;
  25188. (void)iThreshold;
  25189. return SQLITE_OK;
  25190. }
  25191. #endif
  25192. /*
  25193. ** Set the soft heap-size limit for the library. Passing a zero or
  25194. ** negative value indicates no limit.
  25195. */
  25196. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  25197. sqlite3_int64 priorLimit;
  25198. sqlite3_int64 excess;
  25199. sqlite3_int64 nUsed;
  25200. #ifndef SQLITE_OMIT_AUTOINIT
  25201. int rc = sqlite3_initialize();
  25202. if( rc ) return -1;
  25203. #endif
  25204. sqlite3_mutex_enter(mem0.mutex);
  25205. priorLimit = mem0.alarmThreshold;
  25206. if( n<0 ){
  25207. sqlite3_mutex_leave(mem0.mutex);
  25208. return priorLimit;
  25209. }
  25210. mem0.alarmThreshold = n;
  25211. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  25212. mem0.nearlyFull = (n>0 && n<=nUsed);
  25213. sqlite3_mutex_leave(mem0.mutex);
  25214. excess = sqlite3_memory_used() - n;
  25215. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  25216. return priorLimit;
  25217. }
  25218. SQLITE_API void sqlite3_soft_heap_limit(int n){
  25219. if( n<0 ) n = 0;
  25220. sqlite3_soft_heap_limit64(n);
  25221. }
  25222. /*
  25223. ** Initialize the memory allocation subsystem.
  25224. */
  25225. SQLITE_PRIVATE int sqlite3MallocInit(void){
  25226. int rc;
  25227. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  25228. sqlite3MemSetDefault();
  25229. }
  25230. memset(&mem0, 0, sizeof(mem0));
  25231. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  25232. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  25233. || sqlite3GlobalConfig.nPage<=0 ){
  25234. sqlite3GlobalConfig.pPage = 0;
  25235. sqlite3GlobalConfig.szPage = 0;
  25236. }
  25237. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  25238. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  25239. return rc;
  25240. }
  25241. /*
  25242. ** Return true if the heap is currently under memory pressure - in other
  25243. ** words if the amount of heap used is close to the limit set by
  25244. ** sqlite3_soft_heap_limit().
  25245. */
  25246. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  25247. return mem0.nearlyFull;
  25248. }
  25249. /*
  25250. ** Deinitialize the memory allocation subsystem.
  25251. */
  25252. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  25253. if( sqlite3GlobalConfig.m.xShutdown ){
  25254. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  25255. }
  25256. memset(&mem0, 0, sizeof(mem0));
  25257. }
  25258. /*
  25259. ** Return the amount of memory currently checked out.
  25260. */
  25261. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  25262. sqlite3_int64 res, mx;
  25263. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  25264. return res;
  25265. }
  25266. /*
  25267. ** Return the maximum amount of memory that has ever been
  25268. ** checked out since either the beginning of this process
  25269. ** or since the most recent reset.
  25270. */
  25271. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  25272. sqlite3_int64 res, mx;
  25273. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  25274. return mx;
  25275. }
  25276. /*
  25277. ** Trigger the alarm
  25278. */
  25279. static void sqlite3MallocAlarm(int nByte){
  25280. if( mem0.alarmThreshold<=0 ) return;
  25281. sqlite3_mutex_leave(mem0.mutex);
  25282. sqlite3_release_memory(nByte);
  25283. sqlite3_mutex_enter(mem0.mutex);
  25284. }
  25285. /*
  25286. ** Do a memory allocation with statistics and alarms. Assume the
  25287. ** lock is already held.
  25288. */
  25289. static void mallocWithAlarm(int n, void **pp){
  25290. void *p;
  25291. int nFull;
  25292. assert( sqlite3_mutex_held(mem0.mutex) );
  25293. assert( n>0 );
  25294. /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
  25295. ** implementation of malloc_good_size(), which must be called in debug
  25296. ** mode and specifically when the DMD "Dark Matter Detector" is enabled
  25297. ** or else a crash results. Hence, do not attempt to optimize out the
  25298. ** following xRoundup() call. */
  25299. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  25300. #ifdef SQLITE_MAX_MEMORY
  25301. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
  25302. *pp = 0;
  25303. return;
  25304. }
  25305. #endif
  25306. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
  25307. if( mem0.alarmThreshold>0 ){
  25308. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  25309. if( nUsed >= mem0.alarmThreshold - nFull ){
  25310. mem0.nearlyFull = 1;
  25311. sqlite3MallocAlarm(nFull);
  25312. }else{
  25313. mem0.nearlyFull = 0;
  25314. }
  25315. }
  25316. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  25317. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  25318. if( p==0 && mem0.alarmThreshold>0 ){
  25319. sqlite3MallocAlarm(nFull);
  25320. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  25321. }
  25322. #endif
  25323. if( p ){
  25324. nFull = sqlite3MallocSize(p);
  25325. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  25326. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  25327. }
  25328. *pp = p;
  25329. }
  25330. /*
  25331. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  25332. ** assumes the memory subsystem has already been initialized.
  25333. */
  25334. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  25335. void *p;
  25336. if( n==0 || n>=0x7fffff00 ){
  25337. /* A memory allocation of a number of bytes which is near the maximum
  25338. ** signed integer value might cause an integer overflow inside of the
  25339. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  25340. ** 255 bytes of overhead. SQLite itself will never use anything near
  25341. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  25342. p = 0;
  25343. }else if( sqlite3GlobalConfig.bMemstat ){
  25344. sqlite3_mutex_enter(mem0.mutex);
  25345. mallocWithAlarm((int)n, &p);
  25346. sqlite3_mutex_leave(mem0.mutex);
  25347. }else{
  25348. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  25349. }
  25350. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  25351. return p;
  25352. }
  25353. /*
  25354. ** This version of the memory allocation is for use by the application.
  25355. ** First make sure the memory subsystem is initialized, then do the
  25356. ** allocation.
  25357. */
  25358. SQLITE_API void *sqlite3_malloc(int n){
  25359. #ifndef SQLITE_OMIT_AUTOINIT
  25360. if( sqlite3_initialize() ) return 0;
  25361. #endif
  25362. return n<=0 ? 0 : sqlite3Malloc(n);
  25363. }
  25364. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
  25365. #ifndef SQLITE_OMIT_AUTOINIT
  25366. if( sqlite3_initialize() ) return 0;
  25367. #endif
  25368. return sqlite3Malloc(n);
  25369. }
  25370. /*
  25371. ** TRUE if p is a lookaside memory allocation from db
  25372. */
  25373. #ifndef SQLITE_OMIT_LOOKASIDE
  25374. static int isLookaside(sqlite3 *db, void *p){
  25375. return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
  25376. }
  25377. #else
  25378. #define isLookaside(A,B) 0
  25379. #endif
  25380. /*
  25381. ** Return the size of a memory allocation previously obtained from
  25382. ** sqlite3Malloc() or sqlite3_malloc().
  25383. */
  25384. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  25385. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25386. return sqlite3GlobalConfig.m.xSize(p);
  25387. }
  25388. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  25389. assert( p!=0 );
  25390. if( db==0 || !isLookaside(db,p) ){
  25391. #ifdef SQLITE_DEBUG
  25392. if( db==0 ){
  25393. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  25394. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25395. }else{
  25396. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25397. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25398. }
  25399. #endif
  25400. return sqlite3GlobalConfig.m.xSize(p);
  25401. }else{
  25402. assert( sqlite3_mutex_held(db->mutex) );
  25403. return db->lookaside.sz;
  25404. }
  25405. }
  25406. SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
  25407. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  25408. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25409. return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
  25410. }
  25411. /*
  25412. ** Free memory previously obtained from sqlite3Malloc().
  25413. */
  25414. SQLITE_API void sqlite3_free(void *p){
  25415. if( p==0 ) return; /* IMP: R-49053-54554 */
  25416. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25417. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  25418. if( sqlite3GlobalConfig.bMemstat ){
  25419. sqlite3_mutex_enter(mem0.mutex);
  25420. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  25421. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  25422. sqlite3GlobalConfig.m.xFree(p);
  25423. sqlite3_mutex_leave(mem0.mutex);
  25424. }else{
  25425. sqlite3GlobalConfig.m.xFree(p);
  25426. }
  25427. }
  25428. /*
  25429. ** Add the size of memory allocation "p" to the count in
  25430. ** *db->pnBytesFreed.
  25431. */
  25432. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  25433. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  25434. }
  25435. /*
  25436. ** Free memory that might be associated with a particular database
  25437. ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
  25438. ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
  25439. */
  25440. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
  25441. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  25442. assert( p!=0 );
  25443. if( db ){
  25444. if( db->pnBytesFreed ){
  25445. measureAllocationSize(db, p);
  25446. return;
  25447. }
  25448. if( isLookaside(db, p) ){
  25449. LookasideSlot *pBuf = (LookasideSlot*)p;
  25450. #ifdef SQLITE_DEBUG
  25451. /* Trash all content in the buffer being freed */
  25452. memset(p, 0xaa, db->lookaside.sz);
  25453. #endif
  25454. pBuf->pNext = db->lookaside.pFree;
  25455. db->lookaside.pFree = pBuf;
  25456. return;
  25457. }
  25458. }
  25459. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25460. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25461. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  25462. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25463. sqlite3_free(p);
  25464. }
  25465. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  25466. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  25467. if( p ) sqlite3DbFreeNN(db, p);
  25468. }
  25469. /*
  25470. ** Change the size of an existing memory allocation
  25471. */
  25472. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  25473. int nOld, nNew, nDiff;
  25474. void *pNew;
  25475. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  25476. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  25477. if( pOld==0 ){
  25478. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  25479. }
  25480. if( nBytes==0 ){
  25481. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  25482. return 0;
  25483. }
  25484. if( nBytes>=0x7fffff00 ){
  25485. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  25486. return 0;
  25487. }
  25488. nOld = sqlite3MallocSize(pOld);
  25489. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  25490. ** argument to xRealloc is always a value returned by a prior call to
  25491. ** xRoundup. */
  25492. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  25493. if( nOld==nNew ){
  25494. pNew = pOld;
  25495. }else if( sqlite3GlobalConfig.bMemstat ){
  25496. sqlite3_mutex_enter(mem0.mutex);
  25497. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  25498. nDiff = nNew - nOld;
  25499. if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  25500. mem0.alarmThreshold-nDiff ){
  25501. sqlite3MallocAlarm(nDiff);
  25502. }
  25503. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25504. if( pNew==0 && mem0.alarmThreshold>0 ){
  25505. sqlite3MallocAlarm((int)nBytes);
  25506. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25507. }
  25508. if( pNew ){
  25509. nNew = sqlite3MallocSize(pNew);
  25510. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  25511. }
  25512. sqlite3_mutex_leave(mem0.mutex);
  25513. }else{
  25514. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25515. }
  25516. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  25517. return pNew;
  25518. }
  25519. /*
  25520. ** The public interface to sqlite3Realloc. Make sure that the memory
  25521. ** subsystem is initialized prior to invoking sqliteRealloc.
  25522. */
  25523. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  25524. #ifndef SQLITE_OMIT_AUTOINIT
  25525. if( sqlite3_initialize() ) return 0;
  25526. #endif
  25527. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  25528. return sqlite3Realloc(pOld, n);
  25529. }
  25530. SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  25531. #ifndef SQLITE_OMIT_AUTOINIT
  25532. if( sqlite3_initialize() ) return 0;
  25533. #endif
  25534. return sqlite3Realloc(pOld, n);
  25535. }
  25536. /*
  25537. ** Allocate and zero memory.
  25538. */
  25539. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  25540. void *p = sqlite3Malloc(n);
  25541. if( p ){
  25542. memset(p, 0, (size_t)n);
  25543. }
  25544. return p;
  25545. }
  25546. /*
  25547. ** Allocate and zero memory. If the allocation fails, make
  25548. ** the mallocFailed flag in the connection pointer.
  25549. */
  25550. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  25551. void *p;
  25552. testcase( db==0 );
  25553. p = sqlite3DbMallocRaw(db, n);
  25554. if( p ) memset(p, 0, (size_t)n);
  25555. return p;
  25556. }
  25557. /* Finish the work of sqlite3DbMallocRawNN for the unusual and
  25558. ** slower case when the allocation cannot be fulfilled using lookaside.
  25559. */
  25560. static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
  25561. void *p;
  25562. assert( db!=0 );
  25563. p = sqlite3Malloc(n);
  25564. if( !p ) sqlite3OomFault(db);
  25565. sqlite3MemdebugSetType(p,
  25566. (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  25567. return p;
  25568. }
  25569. /*
  25570. ** Allocate memory, either lookaside (if possible) or heap.
  25571. ** If the allocation fails, set the mallocFailed flag in
  25572. ** the connection pointer.
  25573. **
  25574. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  25575. ** failure on the same database connection) then always return 0.
  25576. ** Hence for a particular database connection, once malloc starts
  25577. ** failing, it fails consistently until mallocFailed is reset.
  25578. ** This is an important assumption. There are many places in the
  25579. ** code that do things like this:
  25580. **
  25581. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  25582. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  25583. ** if( b ) a[10] = 9;
  25584. **
  25585. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  25586. ** that all prior mallocs (ex: "a") worked too.
  25587. **
  25588. ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
  25589. ** not a NULL pointer.
  25590. */
  25591. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  25592. void *p;
  25593. if( db ) return sqlite3DbMallocRawNN(db, n);
  25594. p = sqlite3Malloc(n);
  25595. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25596. return p;
  25597. }
  25598. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
  25599. #ifndef SQLITE_OMIT_LOOKASIDE
  25600. LookasideSlot *pBuf;
  25601. assert( db!=0 );
  25602. assert( sqlite3_mutex_held(db->mutex) );
  25603. assert( db->pnBytesFreed==0 );
  25604. if( db->lookaside.bDisable==0 ){
  25605. assert( db->mallocFailed==0 );
  25606. if( n>db->lookaside.sz ){
  25607. db->lookaside.anStat[1]++;
  25608. }else if( (pBuf = db->lookaside.pFree)!=0 ){
  25609. db->lookaside.pFree = pBuf->pNext;
  25610. db->lookaside.anStat[0]++;
  25611. return (void*)pBuf;
  25612. }else if( (pBuf = db->lookaside.pInit)!=0 ){
  25613. db->lookaside.pInit = pBuf->pNext;
  25614. db->lookaside.anStat[0]++;
  25615. return (void*)pBuf;
  25616. }else{
  25617. db->lookaside.anStat[2]++;
  25618. }
  25619. }else if( db->mallocFailed ){
  25620. return 0;
  25621. }
  25622. #else
  25623. assert( db!=0 );
  25624. assert( sqlite3_mutex_held(db->mutex) );
  25625. assert( db->pnBytesFreed==0 );
  25626. if( db->mallocFailed ){
  25627. return 0;
  25628. }
  25629. #endif
  25630. return dbMallocRawFinish(db, n);
  25631. }
  25632. /* Forward declaration */
  25633. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
  25634. /*
  25635. ** Resize the block of memory pointed to by p to n bytes. If the
  25636. ** resize fails, set the mallocFailed flag in the connection object.
  25637. */
  25638. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  25639. assert( db!=0 );
  25640. if( p==0 ) return sqlite3DbMallocRawNN(db, n);
  25641. assert( sqlite3_mutex_held(db->mutex) );
  25642. if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
  25643. return dbReallocFinish(db, p, n);
  25644. }
  25645. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
  25646. void *pNew = 0;
  25647. assert( db!=0 );
  25648. assert( p!=0 );
  25649. if( db->mallocFailed==0 ){
  25650. if( isLookaside(db, p) ){
  25651. pNew = sqlite3DbMallocRawNN(db, n);
  25652. if( pNew ){
  25653. memcpy(pNew, p, db->lookaside.sz);
  25654. sqlite3DbFree(db, p);
  25655. }
  25656. }else{
  25657. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25658. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25659. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25660. pNew = sqlite3_realloc64(p, n);
  25661. if( !pNew ){
  25662. sqlite3OomFault(db);
  25663. }
  25664. sqlite3MemdebugSetType(pNew,
  25665. (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  25666. }
  25667. }
  25668. return pNew;
  25669. }
  25670. /*
  25671. ** Attempt to reallocate p. If the reallocation fails, then free p
  25672. ** and set the mallocFailed flag in the database connection.
  25673. */
  25674. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  25675. void *pNew;
  25676. pNew = sqlite3DbRealloc(db, p, n);
  25677. if( !pNew ){
  25678. sqlite3DbFree(db, p);
  25679. }
  25680. return pNew;
  25681. }
  25682. /*
  25683. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  25684. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  25685. ** is because when memory debugging is turned on, these two functions are
  25686. ** called via macros that record the current file and line number in the
  25687. ** ThreadData structure.
  25688. */
  25689. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  25690. char *zNew;
  25691. size_t n;
  25692. if( z==0 ){
  25693. return 0;
  25694. }
  25695. n = strlen(z) + 1;
  25696. zNew = sqlite3DbMallocRaw(db, n);
  25697. if( zNew ){
  25698. memcpy(zNew, z, n);
  25699. }
  25700. return zNew;
  25701. }
  25702. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  25703. char *zNew;
  25704. assert( db!=0 );
  25705. if( z==0 ){
  25706. return 0;
  25707. }
  25708. assert( (n&0x7fffffff)==n );
  25709. zNew = sqlite3DbMallocRawNN(db, n+1);
  25710. if( zNew ){
  25711. memcpy(zNew, z, (size_t)n);
  25712. zNew[n] = 0;
  25713. }
  25714. return zNew;
  25715. }
  25716. /*
  25717. ** The text between zStart and zEnd represents a phrase within a larger
  25718. ** SQL statement. Make a copy of this phrase in space obtained form
  25719. ** sqlite3DbMalloc(). Omit leading and trailing whitespace.
  25720. */
  25721. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  25722. int n;
  25723. while( sqlite3Isspace(zStart[0]) ) zStart++;
  25724. n = (int)(zEnd - zStart);
  25725. while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
  25726. return sqlite3DbStrNDup(db, zStart, n);
  25727. }
  25728. /*
  25729. ** Free any prior content in *pz and replace it with a copy of zNew.
  25730. */
  25731. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  25732. sqlite3DbFree(db, *pz);
  25733. *pz = sqlite3DbStrDup(db, zNew);
  25734. }
  25735. /*
  25736. ** Call this routine to record the fact that an OOM (out-of-memory) error
  25737. ** has happened. This routine will set db->mallocFailed, and also
  25738. ** temporarily disable the lookaside memory allocator and interrupt
  25739. ** any running VDBEs.
  25740. */
  25741. SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
  25742. if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
  25743. db->mallocFailed = 1;
  25744. if( db->nVdbeExec>0 ){
  25745. db->u1.isInterrupted = 1;
  25746. }
  25747. db->lookaside.bDisable++;
  25748. }
  25749. }
  25750. /*
  25751. ** This routine reactivates the memory allocator and clears the
  25752. ** db->mallocFailed flag as necessary.
  25753. **
  25754. ** The memory allocator is not restarted if there are running
  25755. ** VDBEs.
  25756. */
  25757. SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
  25758. if( db->mallocFailed && db->nVdbeExec==0 ){
  25759. db->mallocFailed = 0;
  25760. db->u1.isInterrupted = 0;
  25761. assert( db->lookaside.bDisable>0 );
  25762. db->lookaside.bDisable--;
  25763. }
  25764. }
  25765. /*
  25766. ** Take actions at the end of an API call to indicate an OOM error
  25767. */
  25768. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  25769. sqlite3OomClear(db);
  25770. sqlite3Error(db, SQLITE_NOMEM);
  25771. return SQLITE_NOMEM_BKPT;
  25772. }
  25773. /*
  25774. ** This function must be called before exiting any API function (i.e.
  25775. ** returning control to the user) that has called sqlite3_malloc or
  25776. ** sqlite3_realloc.
  25777. **
  25778. ** The returned value is normally a copy of the second argument to this
  25779. ** function. However, if a malloc() failure has occurred since the previous
  25780. ** invocation SQLITE_NOMEM is returned instead.
  25781. **
  25782. ** If an OOM as occurred, then the connection error-code (the value
  25783. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  25784. */
  25785. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  25786. /* If the db handle must hold the connection handle mutex here.
  25787. ** Otherwise the read (and possible write) of db->mallocFailed
  25788. ** is unsafe, as is the call to sqlite3Error().
  25789. */
  25790. assert( db!=0 );
  25791. assert( sqlite3_mutex_held(db->mutex) );
  25792. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  25793. return apiOomError(db);
  25794. }
  25795. return rc & db->errMask;
  25796. }
  25797. /************** End of malloc.c **********************************************/
  25798. /************** Begin file printf.c ******************************************/
  25799. /*
  25800. ** The "printf" code that follows dates from the 1980's. It is in
  25801. ** the public domain.
  25802. **
  25803. **************************************************************************
  25804. **
  25805. ** This file contains code for a set of "printf"-like routines. These
  25806. ** routines format strings much like the printf() from the standard C
  25807. ** library, though the implementation here has enhancements to support
  25808. ** SQLite.
  25809. */
  25810. /* #include "sqliteInt.h" */
  25811. /*
  25812. ** Conversion types fall into various categories as defined by the
  25813. ** following enumeration.
  25814. */
  25815. #define etRADIX 0 /* non-decimal integer types. %x %o */
  25816. #define etFLOAT 1 /* Floating point. %f */
  25817. #define etEXP 2 /* Exponentional notation. %e and %E */
  25818. #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
  25819. #define etSIZE 4 /* Return number of characters processed so far. %n */
  25820. #define etSTRING 5 /* Strings. %s */
  25821. #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
  25822. #define etPERCENT 7 /* Percent symbol. %% */
  25823. #define etCHARX 8 /* Characters. %c */
  25824. /* The rest are extensions, not normally found in printf() */
  25825. #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
  25826. #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
  25827. NULL pointers replaced by SQL NULL. %Q */
  25828. #define etTOKEN 11 /* a pointer to a Token structure */
  25829. #define etSRCLIST 12 /* a pointer to a SrcList */
  25830. #define etPOINTER 13 /* The %p conversion */
  25831. #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
  25832. #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  25833. #define etDECIMAL 16 /* %d or %u, but not %x, %o */
  25834. #define etINVALID 17 /* Any unrecognized conversion type */
  25835. /*
  25836. ** An "etByte" is an 8-bit unsigned value.
  25837. */
  25838. typedef unsigned char etByte;
  25839. /*
  25840. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  25841. ** by an instance of the following structure
  25842. */
  25843. typedef struct et_info { /* Information about each format field */
  25844. char fmttype; /* The format field code letter */
  25845. etByte base; /* The base for radix conversion */
  25846. etByte flags; /* One or more of FLAG_ constants below */
  25847. etByte type; /* Conversion paradigm */
  25848. etByte charset; /* Offset into aDigits[] of the digits string */
  25849. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  25850. } et_info;
  25851. /*
  25852. ** Allowed values for et_info.flags
  25853. */
  25854. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  25855. #define FLAG_STRING 4 /* Allow infinite precision */
  25856. /*
  25857. ** The following table is searched linearly, so it is good to put the
  25858. ** most frequently used conversion types first.
  25859. */
  25860. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  25861. static const char aPrefix[] = "-x0\000X0";
  25862. static const et_info fmtinfo[] = {
  25863. { 'd', 10, 1, etDECIMAL, 0, 0 },
  25864. { 's', 0, 4, etSTRING, 0, 0 },
  25865. { 'g', 0, 1, etGENERIC, 30, 0 },
  25866. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  25867. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  25868. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  25869. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  25870. { 'c', 0, 0, etCHARX, 0, 0 },
  25871. { 'o', 8, 0, etRADIX, 0, 2 },
  25872. { 'u', 10, 0, etDECIMAL, 0, 0 },
  25873. { 'x', 16, 0, etRADIX, 16, 1 },
  25874. { 'X', 16, 0, etRADIX, 0, 4 },
  25875. #ifndef SQLITE_OMIT_FLOATING_POINT
  25876. { 'f', 0, 1, etFLOAT, 0, 0 },
  25877. { 'e', 0, 1, etEXP, 30, 0 },
  25878. { 'E', 0, 1, etEXP, 14, 0 },
  25879. { 'G', 0, 1, etGENERIC, 14, 0 },
  25880. #endif
  25881. { 'i', 10, 1, etDECIMAL, 0, 0 },
  25882. { 'n', 0, 0, etSIZE, 0, 0 },
  25883. { '%', 0, 0, etPERCENT, 0, 0 },
  25884. { 'p', 16, 0, etPOINTER, 0, 1 },
  25885. /* All the rest are undocumented and are for internal use only */
  25886. { 'T', 0, 0, etTOKEN, 0, 0 },
  25887. { 'S', 0, 0, etSRCLIST, 0, 0 },
  25888. { 'r', 10, 1, etORDINAL, 0, 0 },
  25889. };
  25890. /*
  25891. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  25892. ** conversions will work.
  25893. */
  25894. #ifndef SQLITE_OMIT_FLOATING_POINT
  25895. /*
  25896. ** "*val" is a double such that 0.1 <= *val < 10.0
  25897. ** Return the ascii code for the leading digit of *val, then
  25898. ** multiply "*val" by 10.0 to renormalize.
  25899. **
  25900. ** Example:
  25901. ** input: *val = 3.14159
  25902. ** output: *val = 1.4159 function return = '3'
  25903. **
  25904. ** The counter *cnt is incremented each time. After counter exceeds
  25905. ** 16 (the number of significant digits in a 64-bit float) '0' is
  25906. ** always returned.
  25907. */
  25908. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  25909. int digit;
  25910. LONGDOUBLE_TYPE d;
  25911. if( (*cnt)<=0 ) return '0';
  25912. (*cnt)--;
  25913. digit = (int)*val;
  25914. d = digit;
  25915. digit += '0';
  25916. *val = (*val - d)*10.0;
  25917. return (char)digit;
  25918. }
  25919. #endif /* SQLITE_OMIT_FLOATING_POINT */
  25920. /*
  25921. ** Set the StrAccum object to an error mode.
  25922. */
  25923. static void setStrAccumError(StrAccum *p, u8 eError){
  25924. assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
  25925. p->accError = eError;
  25926. p->nAlloc = 0;
  25927. }
  25928. /*
  25929. ** Extra argument values from a PrintfArguments object
  25930. */
  25931. static sqlite3_int64 getIntArg(PrintfArguments *p){
  25932. if( p->nArg<=p->nUsed ) return 0;
  25933. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  25934. }
  25935. static double getDoubleArg(PrintfArguments *p){
  25936. if( p->nArg<=p->nUsed ) return 0.0;
  25937. return sqlite3_value_double(p->apArg[p->nUsed++]);
  25938. }
  25939. static char *getTextArg(PrintfArguments *p){
  25940. if( p->nArg<=p->nUsed ) return 0;
  25941. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  25942. }
  25943. /*
  25944. ** On machines with a small stack size, you can redefine the
  25945. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  25946. */
  25947. #ifndef SQLITE_PRINT_BUF_SIZE
  25948. # define SQLITE_PRINT_BUF_SIZE 70
  25949. #endif
  25950. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  25951. /*
  25952. ** Render a string given by "fmt" into the StrAccum object.
  25953. */
  25954. SQLITE_API void sqlite3_str_vappendf(
  25955. sqlite3_str *pAccum, /* Accumulate results here */
  25956. const char *fmt, /* Format string */
  25957. va_list ap /* arguments */
  25958. ){
  25959. int c; /* Next character in the format string */
  25960. char *bufpt; /* Pointer to the conversion buffer */
  25961. int precision; /* Precision of the current field */
  25962. int length; /* Length of the field */
  25963. int idx; /* A general purpose loop counter */
  25964. int width; /* Width of the current field */
  25965. etByte flag_leftjustify; /* True if "-" flag is present */
  25966. etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
  25967. etByte flag_alternateform; /* True if "#" flag is present */
  25968. etByte flag_altform2; /* True if "!" flag is present */
  25969. etByte flag_zeropad; /* True if field width constant starts with zero */
  25970. etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
  25971. etByte done; /* Loop termination flag */
  25972. etByte cThousand; /* Thousands separator for %d and %u */
  25973. etByte xtype = etINVALID; /* Conversion paradigm */
  25974. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  25975. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  25976. sqlite_uint64 longvalue; /* Value for integer types */
  25977. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  25978. const et_info *infop; /* Pointer to the appropriate info structure */
  25979. char *zOut; /* Rendering buffer */
  25980. int nOut; /* Size of the rendering buffer */
  25981. char *zExtra = 0; /* Malloced memory used by some conversion */
  25982. #ifndef SQLITE_OMIT_FLOATING_POINT
  25983. int exp, e2; /* exponent of real numbers */
  25984. int nsd; /* Number of significant digits returned */
  25985. double rounder; /* Used for rounding floating point values */
  25986. etByte flag_dp; /* True if decimal point should be shown */
  25987. etByte flag_rtz; /* True if trailing zeros should be removed */
  25988. #endif
  25989. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  25990. char buf[etBUFSIZE]; /* Conversion buffer */
  25991. /* pAccum never starts out with an empty buffer that was obtained from
  25992. ** malloc(). This precondition is required by the mprintf("%z...")
  25993. ** optimization. */
  25994. assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  25995. bufpt = 0;
  25996. if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
  25997. pArgList = va_arg(ap, PrintfArguments*);
  25998. bArgList = 1;
  25999. }else{
  26000. bArgList = 0;
  26001. }
  26002. for(; (c=(*fmt))!=0; ++fmt){
  26003. if( c!='%' ){
  26004. bufpt = (char *)fmt;
  26005. #if HAVE_STRCHRNUL
  26006. fmt = strchrnul(fmt, '%');
  26007. #else
  26008. do{ fmt++; }while( *fmt && *fmt != '%' );
  26009. #endif
  26010. sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
  26011. if( *fmt==0 ) break;
  26012. }
  26013. if( (c=(*++fmt))==0 ){
  26014. sqlite3_str_append(pAccum, "%", 1);
  26015. break;
  26016. }
  26017. /* Find out what flags are present */
  26018. flag_leftjustify = flag_prefix = cThousand =
  26019. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  26020. done = 0;
  26021. do{
  26022. switch( c ){
  26023. case '-': flag_leftjustify = 1; break;
  26024. case '+': flag_prefix = '+'; break;
  26025. case ' ': flag_prefix = ' '; break;
  26026. case '#': flag_alternateform = 1; break;
  26027. case '!': flag_altform2 = 1; break;
  26028. case '0': flag_zeropad = 1; break;
  26029. case ',': cThousand = ','; break;
  26030. default: done = 1; break;
  26031. }
  26032. }while( !done && (c=(*++fmt))!=0 );
  26033. /* Get the field width */
  26034. if( c=='*' ){
  26035. if( bArgList ){
  26036. width = (int)getIntArg(pArgList);
  26037. }else{
  26038. width = va_arg(ap,int);
  26039. }
  26040. if( width<0 ){
  26041. flag_leftjustify = 1;
  26042. width = width >= -2147483647 ? -width : 0;
  26043. }
  26044. c = *++fmt;
  26045. }else{
  26046. unsigned wx = 0;
  26047. while( c>='0' && c<='9' ){
  26048. wx = wx*10 + c - '0';
  26049. c = *++fmt;
  26050. }
  26051. testcase( wx>0x7fffffff );
  26052. width = wx & 0x7fffffff;
  26053. }
  26054. assert( width>=0 );
  26055. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  26056. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  26057. width = SQLITE_PRINTF_PRECISION_LIMIT;
  26058. }
  26059. #endif
  26060. /* Get the precision */
  26061. if( c=='.' ){
  26062. c = *++fmt;
  26063. if( c=='*' ){
  26064. if( bArgList ){
  26065. precision = (int)getIntArg(pArgList);
  26066. }else{
  26067. precision = va_arg(ap,int);
  26068. }
  26069. c = *++fmt;
  26070. if( precision<0 ){
  26071. precision = precision >= -2147483647 ? -precision : -1;
  26072. }
  26073. }else{
  26074. unsigned px = 0;
  26075. while( c>='0' && c<='9' ){
  26076. px = px*10 + c - '0';
  26077. c = *++fmt;
  26078. }
  26079. testcase( px>0x7fffffff );
  26080. precision = px & 0x7fffffff;
  26081. }
  26082. }else{
  26083. precision = -1;
  26084. }
  26085. assert( precision>=(-1) );
  26086. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  26087. if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
  26088. precision = SQLITE_PRINTF_PRECISION_LIMIT;
  26089. }
  26090. #endif
  26091. /* Get the conversion type modifier */
  26092. if( c=='l' ){
  26093. flag_long = 1;
  26094. c = *++fmt;
  26095. if( c=='l' ){
  26096. flag_long = 2;
  26097. c = *++fmt;
  26098. }
  26099. }else{
  26100. flag_long = 0;
  26101. }
  26102. /* Fetch the info entry for the field */
  26103. infop = &fmtinfo[0];
  26104. xtype = etINVALID;
  26105. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  26106. if( c==fmtinfo[idx].fmttype ){
  26107. infop = &fmtinfo[idx];
  26108. xtype = infop->type;
  26109. break;
  26110. }
  26111. }
  26112. /*
  26113. ** At this point, variables are initialized as follows:
  26114. **
  26115. ** flag_alternateform TRUE if a '#' is present.
  26116. ** flag_altform2 TRUE if a '!' is present.
  26117. ** flag_prefix '+' or ' ' or zero
  26118. ** flag_leftjustify TRUE if a '-' is present or if the
  26119. ** field width was negative.
  26120. ** flag_zeropad TRUE if the width began with 0.
  26121. ** flag_long 1 for "l", 2 for "ll"
  26122. ** width The specified field width. This is
  26123. ** always non-negative. Zero is the default.
  26124. ** precision The specified precision. The default
  26125. ** is -1.
  26126. ** xtype The class of the conversion.
  26127. ** infop Pointer to the appropriate info struct.
  26128. */
  26129. switch( xtype ){
  26130. case etPOINTER:
  26131. flag_long = sizeof(char*)==sizeof(i64) ? 2 :
  26132. sizeof(char*)==sizeof(long int) ? 1 : 0;
  26133. /* Fall through into the next case */
  26134. case etORDINAL:
  26135. case etRADIX:
  26136. cThousand = 0;
  26137. /* Fall through into the next case */
  26138. case etDECIMAL:
  26139. if( infop->flags & FLAG_SIGNED ){
  26140. i64 v;
  26141. if( bArgList ){
  26142. v = getIntArg(pArgList);
  26143. }else if( flag_long ){
  26144. if( flag_long==2 ){
  26145. v = va_arg(ap,i64) ;
  26146. }else{
  26147. v = va_arg(ap,long int);
  26148. }
  26149. }else{
  26150. v = va_arg(ap,int);
  26151. }
  26152. if( v<0 ){
  26153. if( v==SMALLEST_INT64 ){
  26154. longvalue = ((u64)1)<<63;
  26155. }else{
  26156. longvalue = -v;
  26157. }
  26158. prefix = '-';
  26159. }else{
  26160. longvalue = v;
  26161. prefix = flag_prefix;
  26162. }
  26163. }else{
  26164. if( bArgList ){
  26165. longvalue = (u64)getIntArg(pArgList);
  26166. }else if( flag_long ){
  26167. if( flag_long==2 ){
  26168. longvalue = va_arg(ap,u64);
  26169. }else{
  26170. longvalue = va_arg(ap,unsigned long int);
  26171. }
  26172. }else{
  26173. longvalue = va_arg(ap,unsigned int);
  26174. }
  26175. prefix = 0;
  26176. }
  26177. if( longvalue==0 ) flag_alternateform = 0;
  26178. if( flag_zeropad && precision<width-(prefix!=0) ){
  26179. precision = width-(prefix!=0);
  26180. }
  26181. if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
  26182. nOut = etBUFSIZE;
  26183. zOut = buf;
  26184. }else{
  26185. u64 n = (u64)precision + 10 + precision/3;
  26186. zOut = zExtra = sqlite3Malloc( n );
  26187. if( zOut==0 ){
  26188. setStrAccumError(pAccum, SQLITE_NOMEM);
  26189. return;
  26190. }
  26191. nOut = (int)n;
  26192. }
  26193. bufpt = &zOut[nOut-1];
  26194. if( xtype==etORDINAL ){
  26195. static const char zOrd[] = "thstndrd";
  26196. int x = (int)(longvalue % 10);
  26197. if( x>=4 || (longvalue/10)%10==1 ){
  26198. x = 0;
  26199. }
  26200. *(--bufpt) = zOrd[x*2+1];
  26201. *(--bufpt) = zOrd[x*2];
  26202. }
  26203. {
  26204. const char *cset = &aDigits[infop->charset];
  26205. u8 base = infop->base;
  26206. do{ /* Convert to ascii */
  26207. *(--bufpt) = cset[longvalue%base];
  26208. longvalue = longvalue/base;
  26209. }while( longvalue>0 );
  26210. }
  26211. length = (int)(&zOut[nOut-1]-bufpt);
  26212. while( precision>length ){
  26213. *(--bufpt) = '0'; /* Zero pad */
  26214. length++;
  26215. }
  26216. if( cThousand ){
  26217. int nn = (length - 1)/3; /* Number of "," to insert */
  26218. int ix = (length - 1)%3 + 1;
  26219. bufpt -= nn;
  26220. for(idx=0; nn>0; idx++){
  26221. bufpt[idx] = bufpt[idx+nn];
  26222. ix--;
  26223. if( ix==0 ){
  26224. bufpt[++idx] = cThousand;
  26225. nn--;
  26226. ix = 3;
  26227. }
  26228. }
  26229. }
  26230. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  26231. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  26232. const char *pre;
  26233. char x;
  26234. pre = &aPrefix[infop->prefix];
  26235. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  26236. }
  26237. length = (int)(&zOut[nOut-1]-bufpt);
  26238. break;
  26239. case etFLOAT:
  26240. case etEXP:
  26241. case etGENERIC:
  26242. if( bArgList ){
  26243. realvalue = getDoubleArg(pArgList);
  26244. }else{
  26245. realvalue = va_arg(ap,double);
  26246. }
  26247. #ifdef SQLITE_OMIT_FLOATING_POINT
  26248. length = 0;
  26249. #else
  26250. if( precision<0 ) precision = 6; /* Set default precision */
  26251. if( realvalue<0.0 ){
  26252. realvalue = -realvalue;
  26253. prefix = '-';
  26254. }else{
  26255. prefix = flag_prefix;
  26256. }
  26257. if( xtype==etGENERIC && precision>0 ) precision--;
  26258. testcase( precision>0xfff );
  26259. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  26260. if( xtype==etFLOAT ) realvalue += rounder;
  26261. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  26262. exp = 0;
  26263. if( sqlite3IsNaN((double)realvalue) ){
  26264. bufpt = "NaN";
  26265. length = 3;
  26266. break;
  26267. }
  26268. if( realvalue>0.0 ){
  26269. LONGDOUBLE_TYPE scale = 1.0;
  26270. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  26271. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  26272. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  26273. realvalue /= scale;
  26274. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  26275. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  26276. if( exp>350 ){
  26277. bufpt = buf;
  26278. buf[0] = prefix;
  26279. memcpy(buf+(prefix!=0),"Inf",4);
  26280. length = 3+(prefix!=0);
  26281. break;
  26282. }
  26283. }
  26284. bufpt = buf;
  26285. /*
  26286. ** If the field type is etGENERIC, then convert to either etEXP
  26287. ** or etFLOAT, as appropriate.
  26288. */
  26289. if( xtype!=etFLOAT ){
  26290. realvalue += rounder;
  26291. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  26292. }
  26293. if( xtype==etGENERIC ){
  26294. flag_rtz = !flag_alternateform;
  26295. if( exp<-4 || exp>precision ){
  26296. xtype = etEXP;
  26297. }else{
  26298. precision = precision - exp;
  26299. xtype = etFLOAT;
  26300. }
  26301. }else{
  26302. flag_rtz = flag_altform2;
  26303. }
  26304. if( xtype==etEXP ){
  26305. e2 = 0;
  26306. }else{
  26307. e2 = exp;
  26308. }
  26309. if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
  26310. bufpt = zExtra
  26311. = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
  26312. if( bufpt==0 ){
  26313. setStrAccumError(pAccum, SQLITE_NOMEM);
  26314. return;
  26315. }
  26316. }
  26317. zOut = bufpt;
  26318. nsd = 16 + flag_altform2*10;
  26319. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  26320. /* The sign in front of the number */
  26321. if( prefix ){
  26322. *(bufpt++) = prefix;
  26323. }
  26324. /* Digits prior to the decimal point */
  26325. if( e2<0 ){
  26326. *(bufpt++) = '0';
  26327. }else{
  26328. for(; e2>=0; e2--){
  26329. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  26330. }
  26331. }
  26332. /* The decimal point */
  26333. if( flag_dp ){
  26334. *(bufpt++) = '.';
  26335. }
  26336. /* "0" digits after the decimal point but before the first
  26337. ** significant digit of the number */
  26338. for(e2++; e2<0; precision--, e2++){
  26339. assert( precision>0 );
  26340. *(bufpt++) = '0';
  26341. }
  26342. /* Significant digits after the decimal point */
  26343. while( (precision--)>0 ){
  26344. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  26345. }
  26346. /* Remove trailing zeros and the "." if no digits follow the "." */
  26347. if( flag_rtz && flag_dp ){
  26348. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  26349. assert( bufpt>zOut );
  26350. if( bufpt[-1]=='.' ){
  26351. if( flag_altform2 ){
  26352. *(bufpt++) = '0';
  26353. }else{
  26354. *(--bufpt) = 0;
  26355. }
  26356. }
  26357. }
  26358. /* Add the "eNNN" suffix */
  26359. if( xtype==etEXP ){
  26360. *(bufpt++) = aDigits[infop->charset];
  26361. if( exp<0 ){
  26362. *(bufpt++) = '-'; exp = -exp;
  26363. }else{
  26364. *(bufpt++) = '+';
  26365. }
  26366. if( exp>=100 ){
  26367. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  26368. exp %= 100;
  26369. }
  26370. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  26371. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  26372. }
  26373. *bufpt = 0;
  26374. /* The converted number is in buf[] and zero terminated. Output it.
  26375. ** Note that the number is in the usual order, not reversed as with
  26376. ** integer conversions. */
  26377. length = (int)(bufpt-zOut);
  26378. bufpt = zOut;
  26379. /* Special case: Add leading zeros if the flag_zeropad flag is
  26380. ** set and we are not left justified */
  26381. if( flag_zeropad && !flag_leftjustify && length < width){
  26382. int i;
  26383. int nPad = width - length;
  26384. for(i=width; i>=nPad; i--){
  26385. bufpt[i] = bufpt[i-nPad];
  26386. }
  26387. i = prefix!=0;
  26388. while( nPad-- ) bufpt[i++] = '0';
  26389. length = width;
  26390. }
  26391. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  26392. break;
  26393. case etSIZE:
  26394. if( !bArgList ){
  26395. *(va_arg(ap,int*)) = pAccum->nChar;
  26396. }
  26397. length = width = 0;
  26398. break;
  26399. case etPERCENT:
  26400. buf[0] = '%';
  26401. bufpt = buf;
  26402. length = 1;
  26403. break;
  26404. case etCHARX:
  26405. if( bArgList ){
  26406. bufpt = getTextArg(pArgList);
  26407. length = 1;
  26408. if( bufpt ){
  26409. buf[0] = c = *(bufpt++);
  26410. if( (c&0xc0)==0xc0 ){
  26411. while( length<4 && (bufpt[0]&0xc0)==0x80 ){
  26412. buf[length++] = *(bufpt++);
  26413. }
  26414. }
  26415. }else{
  26416. buf[0] = 0;
  26417. }
  26418. }else{
  26419. unsigned int ch = va_arg(ap,unsigned int);
  26420. if( ch<0x00080 ){
  26421. buf[0] = ch & 0xff;
  26422. length = 1;
  26423. }else if( ch<0x00800 ){
  26424. buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
  26425. buf[1] = 0x80 + (u8)(ch & 0x3f);
  26426. length = 2;
  26427. }else if( ch<0x10000 ){
  26428. buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
  26429. buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
  26430. buf[2] = 0x80 + (u8)(ch & 0x3f);
  26431. length = 3;
  26432. }else{
  26433. buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
  26434. buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
  26435. buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
  26436. buf[3] = 0x80 + (u8)(ch & 0x3f);
  26437. length = 4;
  26438. }
  26439. }
  26440. if( precision>1 ){
  26441. width -= precision-1;
  26442. if( width>1 && !flag_leftjustify ){
  26443. sqlite3_str_appendchar(pAccum, width-1, ' ');
  26444. width = 0;
  26445. }
  26446. while( precision-- > 1 ){
  26447. sqlite3_str_append(pAccum, buf, length);
  26448. }
  26449. }
  26450. bufpt = buf;
  26451. flag_altform2 = 1;
  26452. goto adjust_width_for_utf8;
  26453. case etSTRING:
  26454. case etDYNSTRING:
  26455. if( bArgList ){
  26456. bufpt = getTextArg(pArgList);
  26457. xtype = etSTRING;
  26458. }else{
  26459. bufpt = va_arg(ap,char*);
  26460. }
  26461. if( bufpt==0 ){
  26462. bufpt = "";
  26463. }else if( xtype==etDYNSTRING ){
  26464. if( pAccum->nChar==0
  26465. && pAccum->mxAlloc
  26466. && width==0
  26467. && precision<0
  26468. && pAccum->accError==0
  26469. ){
  26470. /* Special optimization for sqlite3_mprintf("%z..."):
  26471. ** Extend an existing memory allocation rather than creating
  26472. ** a new one. */
  26473. assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  26474. pAccum->zText = bufpt;
  26475. pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
  26476. pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
  26477. pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
  26478. length = 0;
  26479. break;
  26480. }
  26481. zExtra = bufpt;
  26482. }
  26483. if( precision>=0 ){
  26484. if( flag_altform2 ){
  26485. /* Set length to the number of bytes needed in order to display
  26486. ** precision characters */
  26487. unsigned char *z = (unsigned char*)bufpt;
  26488. while( precision-- > 0 && z[0] ){
  26489. SQLITE_SKIP_UTF8(z);
  26490. }
  26491. length = (int)(z - (unsigned char*)bufpt);
  26492. }else{
  26493. for(length=0; length<precision && bufpt[length]; length++){}
  26494. }
  26495. }else{
  26496. length = 0x7fffffff & (int)strlen(bufpt);
  26497. }
  26498. adjust_width_for_utf8:
  26499. if( flag_altform2 && width>0 ){
  26500. /* Adjust width to account for extra bytes in UTF-8 characters */
  26501. int ii = length - 1;
  26502. while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
  26503. }
  26504. break;
  26505. case etSQLESCAPE: /* %q: Escape ' characters */
  26506. case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
  26507. case etSQLESCAPE3: { /* %w: Escape " characters */
  26508. int i, j, k, n, isnull;
  26509. int needQuote;
  26510. char ch;
  26511. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  26512. char *escarg;
  26513. if( bArgList ){
  26514. escarg = getTextArg(pArgList);
  26515. }else{
  26516. escarg = va_arg(ap,char*);
  26517. }
  26518. isnull = escarg==0;
  26519. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  26520. /* For %q, %Q, and %w, the precision is the number of byte (or
  26521. ** characters if the ! flags is present) to use from the input.
  26522. ** Because of the extra quoting characters inserted, the number
  26523. ** of output characters may be larger than the precision.
  26524. */
  26525. k = precision;
  26526. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  26527. if( ch==q ) n++;
  26528. if( flag_altform2 && (ch&0xc0)==0xc0 ){
  26529. while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
  26530. }
  26531. }
  26532. needQuote = !isnull && xtype==etSQLESCAPE2;
  26533. n += i + 3;
  26534. if( n>etBUFSIZE ){
  26535. bufpt = zExtra = sqlite3Malloc( n );
  26536. if( bufpt==0 ){
  26537. setStrAccumError(pAccum, SQLITE_NOMEM);
  26538. return;
  26539. }
  26540. }else{
  26541. bufpt = buf;
  26542. }
  26543. j = 0;
  26544. if( needQuote ) bufpt[j++] = q;
  26545. k = i;
  26546. for(i=0; i<k; i++){
  26547. bufpt[j++] = ch = escarg[i];
  26548. if( ch==q ) bufpt[j++] = ch;
  26549. }
  26550. if( needQuote ) bufpt[j++] = q;
  26551. bufpt[j] = 0;
  26552. length = j;
  26553. goto adjust_width_for_utf8;
  26554. }
  26555. case etTOKEN: {
  26556. Token *pToken;
  26557. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  26558. pToken = va_arg(ap, Token*);
  26559. assert( bArgList==0 );
  26560. if( pToken && pToken->n ){
  26561. sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
  26562. }
  26563. length = width = 0;
  26564. break;
  26565. }
  26566. case etSRCLIST: {
  26567. SrcList *pSrc;
  26568. int k;
  26569. struct SrcList_item *pItem;
  26570. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  26571. pSrc = va_arg(ap, SrcList*);
  26572. k = va_arg(ap, int);
  26573. pItem = &pSrc->a[k];
  26574. assert( bArgList==0 );
  26575. assert( k>=0 && k<pSrc->nSrc );
  26576. if( pItem->zDatabase ){
  26577. sqlite3_str_appendall(pAccum, pItem->zDatabase);
  26578. sqlite3_str_append(pAccum, ".", 1);
  26579. }
  26580. sqlite3_str_appendall(pAccum, pItem->zName);
  26581. length = width = 0;
  26582. break;
  26583. }
  26584. default: {
  26585. assert( xtype==etINVALID );
  26586. return;
  26587. }
  26588. }/* End switch over the format type */
  26589. /*
  26590. ** The text of the conversion is pointed to by "bufpt" and is
  26591. ** "length" characters long. The field width is "width". Do
  26592. ** the output. Both length and width are in bytes, not characters,
  26593. ** at this point. If the "!" flag was present on string conversions
  26594. ** indicating that width and precision should be expressed in characters,
  26595. ** then the values have been translated prior to reaching this point.
  26596. */
  26597. width -= length;
  26598. if( width>0 ){
  26599. if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
  26600. sqlite3_str_append(pAccum, bufpt, length);
  26601. if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
  26602. }else{
  26603. sqlite3_str_append(pAccum, bufpt, length);
  26604. }
  26605. if( zExtra ){
  26606. sqlite3DbFree(pAccum->db, zExtra);
  26607. zExtra = 0;
  26608. }
  26609. }/* End for loop over the format string */
  26610. } /* End of function */
  26611. /*
  26612. ** Enlarge the memory allocation on a StrAccum object so that it is
  26613. ** able to accept at least N more bytes of text.
  26614. **
  26615. ** Return the number of bytes of text that StrAccum is able to accept
  26616. ** after the attempted enlargement. The value returned might be zero.
  26617. */
  26618. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  26619. char *zNew;
  26620. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  26621. if( p->accError ){
  26622. testcase(p->accError==SQLITE_TOOBIG);
  26623. testcase(p->accError==SQLITE_NOMEM);
  26624. return 0;
  26625. }
  26626. if( p->mxAlloc==0 ){
  26627. N = p->nAlloc - p->nChar - 1;
  26628. setStrAccumError(p, SQLITE_TOOBIG);
  26629. return N;
  26630. }else{
  26631. char *zOld = isMalloced(p) ? p->zText : 0;
  26632. i64 szNew = p->nChar;
  26633. szNew += N + 1;
  26634. if( szNew+p->nChar<=p->mxAlloc ){
  26635. /* Force exponential buffer size growth as long as it does not overflow,
  26636. ** to avoid having to call this routine too often */
  26637. szNew += p->nChar;
  26638. }
  26639. if( szNew > p->mxAlloc ){
  26640. sqlite3_str_reset(p);
  26641. setStrAccumError(p, SQLITE_TOOBIG);
  26642. return 0;
  26643. }else{
  26644. p->nAlloc = (int)szNew;
  26645. }
  26646. if( p->db ){
  26647. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  26648. }else{
  26649. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  26650. }
  26651. if( zNew ){
  26652. assert( p->zText!=0 || p->nChar==0 );
  26653. if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  26654. p->zText = zNew;
  26655. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  26656. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  26657. }else{
  26658. sqlite3_str_reset(p);
  26659. setStrAccumError(p, SQLITE_NOMEM);
  26660. return 0;
  26661. }
  26662. }
  26663. return N;
  26664. }
  26665. /*
  26666. ** Append N copies of character c to the given string buffer.
  26667. */
  26668. SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
  26669. testcase( p->nChar + (i64)N > 0x7fffffff );
  26670. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  26671. return;
  26672. }
  26673. while( (N--)>0 ) p->zText[p->nChar++] = c;
  26674. }
  26675. /*
  26676. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  26677. ** So enlarge if first, then do the append.
  26678. **
  26679. ** This is a helper routine to sqlite3_str_append() that does special-case
  26680. ** work (enlarging the buffer) using tail recursion, so that the
  26681. ** sqlite3_str_append() routine can use fast calling semantics.
  26682. */
  26683. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  26684. N = sqlite3StrAccumEnlarge(p, N);
  26685. if( N>0 ){
  26686. memcpy(&p->zText[p->nChar], z, N);
  26687. p->nChar += N;
  26688. }
  26689. }
  26690. /*
  26691. ** Append N bytes of text from z to the StrAccum object. Increase the
  26692. ** size of the memory allocation for StrAccum if necessary.
  26693. */
  26694. SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
  26695. assert( z!=0 || N==0 );
  26696. assert( p->zText!=0 || p->nChar==0 || p->accError );
  26697. assert( N>=0 );
  26698. assert( p->accError==0 || p->nAlloc==0 );
  26699. if( p->nChar+N >= p->nAlloc ){
  26700. enlargeAndAppend(p,z,N);
  26701. }else if( N ){
  26702. assert( p->zText );
  26703. p->nChar += N;
  26704. memcpy(&p->zText[p->nChar-N], z, N);
  26705. }
  26706. }
  26707. /*
  26708. ** Append the complete text of zero-terminated string z[] to the p string.
  26709. */
  26710. SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
  26711. sqlite3_str_append(p, z, sqlite3Strlen30(z));
  26712. }
  26713. /*
  26714. ** Finish off a string by making sure it is zero-terminated.
  26715. ** Return a pointer to the resulting string. Return a NULL
  26716. ** pointer if any kind of error was encountered.
  26717. */
  26718. static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
  26719. char *zText;
  26720. assert( p->mxAlloc>0 && !isMalloced(p) );
  26721. zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  26722. if( zText ){
  26723. memcpy(zText, p->zText, p->nChar+1);
  26724. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  26725. }else{
  26726. setStrAccumError(p, SQLITE_NOMEM);
  26727. }
  26728. p->zText = zText;
  26729. return zText;
  26730. }
  26731. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  26732. if( p->zText ){
  26733. p->zText[p->nChar] = 0;
  26734. if( p->mxAlloc>0 && !isMalloced(p) ){
  26735. return strAccumFinishRealloc(p);
  26736. }
  26737. }
  26738. return p->zText;
  26739. }
  26740. /*
  26741. ** This singleton is an sqlite3_str object that is returned if
  26742. ** sqlite3_malloc() fails to provide space for a real one. This
  26743. ** sqlite3_str object accepts no new text and always returns
  26744. ** an SQLITE_NOMEM error.
  26745. */
  26746. static sqlite3_str sqlite3OomStr = {
  26747. 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
  26748. };
  26749. /* Finalize a string created using sqlite3_str_new().
  26750. */
  26751. SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
  26752. char *z;
  26753. if( p!=0 && p!=&sqlite3OomStr ){
  26754. z = sqlite3StrAccumFinish(p);
  26755. sqlite3_free(p);
  26756. }else{
  26757. z = 0;
  26758. }
  26759. return z;
  26760. }
  26761. /* Return any error code associated with p */
  26762. SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){
  26763. return p ? p->accError : SQLITE_NOMEM;
  26764. }
  26765. /* Return the current length of p in bytes */
  26766. SQLITE_API int sqlite3_str_length(sqlite3_str *p){
  26767. return p ? p->nChar : 0;
  26768. }
  26769. /* Return the current value for p */
  26770. SQLITE_API char *sqlite3_str_value(sqlite3_str *p){
  26771. if( p==0 || p->nChar==0 ) return 0;
  26772. p->zText[p->nChar] = 0;
  26773. return p->zText;
  26774. }
  26775. /*
  26776. ** Reset an StrAccum string. Reclaim all malloced memory.
  26777. */
  26778. SQLITE_API void sqlite3_str_reset(StrAccum *p){
  26779. if( isMalloced(p) ){
  26780. sqlite3DbFree(p->db, p->zText);
  26781. p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
  26782. }
  26783. p->nAlloc = 0;
  26784. p->nChar = 0;
  26785. p->zText = 0;
  26786. }
  26787. /*
  26788. ** Initialize a string accumulator.
  26789. **
  26790. ** p: The accumulator to be initialized.
  26791. ** db: Pointer to a database connection. May be NULL. Lookaside
  26792. ** memory is used if not NULL. db->mallocFailed is set appropriately
  26793. ** when not NULL.
  26794. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  26795. ** is malloced.
  26796. ** n: Size of zBase in bytes. If total space requirements never exceed
  26797. ** n then no memory allocations ever occur.
  26798. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  26799. ** allocations will ever occur.
  26800. */
  26801. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  26802. p->zText = zBase;
  26803. p->db = db;
  26804. p->nAlloc = n;
  26805. p->mxAlloc = mx;
  26806. p->nChar = 0;
  26807. p->accError = 0;
  26808. p->printfFlags = 0;
  26809. }
  26810. /* Allocate and initialize a new dynamic string object */
  26811. SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){
  26812. sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
  26813. if( p ){
  26814. sqlite3StrAccumInit(p, 0, 0, 0,
  26815. db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
  26816. }else{
  26817. p = &sqlite3OomStr;
  26818. }
  26819. return p;
  26820. }
  26821. /*
  26822. ** Print into memory obtained from sqliteMalloc(). Use the internal
  26823. ** %-conversion extensions.
  26824. */
  26825. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  26826. char *z;
  26827. char zBase[SQLITE_PRINT_BUF_SIZE];
  26828. StrAccum acc;
  26829. assert( db!=0 );
  26830. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  26831. db->aLimit[SQLITE_LIMIT_LENGTH]);
  26832. acc.printfFlags = SQLITE_PRINTF_INTERNAL;
  26833. sqlite3_str_vappendf(&acc, zFormat, ap);
  26834. z = sqlite3StrAccumFinish(&acc);
  26835. if( acc.accError==SQLITE_NOMEM ){
  26836. sqlite3OomFault(db);
  26837. }
  26838. return z;
  26839. }
  26840. /*
  26841. ** Print into memory obtained from sqliteMalloc(). Use the internal
  26842. ** %-conversion extensions.
  26843. */
  26844. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  26845. va_list ap;
  26846. char *z;
  26847. va_start(ap, zFormat);
  26848. z = sqlite3VMPrintf(db, zFormat, ap);
  26849. va_end(ap);
  26850. return z;
  26851. }
  26852. /*
  26853. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  26854. ** %-conversion extensions.
  26855. */
  26856. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  26857. char *z;
  26858. char zBase[SQLITE_PRINT_BUF_SIZE];
  26859. StrAccum acc;
  26860. #ifdef SQLITE_ENABLE_API_ARMOR
  26861. if( zFormat==0 ){
  26862. (void)SQLITE_MISUSE_BKPT;
  26863. return 0;
  26864. }
  26865. #endif
  26866. #ifndef SQLITE_OMIT_AUTOINIT
  26867. if( sqlite3_initialize() ) return 0;
  26868. #endif
  26869. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  26870. sqlite3_str_vappendf(&acc, zFormat, ap);
  26871. z = sqlite3StrAccumFinish(&acc);
  26872. return z;
  26873. }
  26874. /*
  26875. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  26876. ** %-conversion extensions.
  26877. */
  26878. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  26879. va_list ap;
  26880. char *z;
  26881. #ifndef SQLITE_OMIT_AUTOINIT
  26882. if( sqlite3_initialize() ) return 0;
  26883. #endif
  26884. va_start(ap, zFormat);
  26885. z = sqlite3_vmprintf(zFormat, ap);
  26886. va_end(ap);
  26887. return z;
  26888. }
  26889. /*
  26890. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  26891. ** current locale settings. This is important for SQLite because we
  26892. ** are not able to use a "," as the decimal point in place of "." as
  26893. ** specified by some locales.
  26894. **
  26895. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  26896. ** from the snprintf() standard. Unfortunately, it is too late to change
  26897. ** this without breaking compatibility, so we just have to live with the
  26898. ** mistake.
  26899. **
  26900. ** sqlite3_vsnprintf() is the varargs version.
  26901. */
  26902. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  26903. StrAccum acc;
  26904. if( n<=0 ) return zBuf;
  26905. #ifdef SQLITE_ENABLE_API_ARMOR
  26906. if( zBuf==0 || zFormat==0 ) {
  26907. (void)SQLITE_MISUSE_BKPT;
  26908. if( zBuf ) zBuf[0] = 0;
  26909. return zBuf;
  26910. }
  26911. #endif
  26912. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  26913. sqlite3_str_vappendf(&acc, zFormat, ap);
  26914. zBuf[acc.nChar] = 0;
  26915. return zBuf;
  26916. }
  26917. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  26918. char *z;
  26919. va_list ap;
  26920. va_start(ap,zFormat);
  26921. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  26922. va_end(ap);
  26923. return z;
  26924. }
  26925. /*
  26926. ** This is the routine that actually formats the sqlite3_log() message.
  26927. ** We house it in a separate routine from sqlite3_log() to avoid using
  26928. ** stack space on small-stack systems when logging is disabled.
  26929. **
  26930. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  26931. ** allocate memory because it might be called while the memory allocator
  26932. ** mutex is held.
  26933. **
  26934. ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
  26935. ** certain format characters (%q) or for very large precisions or widths.
  26936. ** Care must be taken that any sqlite3_log() calls that occur while the
  26937. ** memory mutex is held do not use these mechanisms.
  26938. */
  26939. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  26940. StrAccum acc; /* String accumulator */
  26941. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  26942. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  26943. sqlite3_str_vappendf(&acc, zFormat, ap);
  26944. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  26945. sqlite3StrAccumFinish(&acc));
  26946. }
  26947. /*
  26948. ** Format and write a message to the log if logging is enabled.
  26949. */
  26950. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  26951. va_list ap; /* Vararg list */
  26952. if( sqlite3GlobalConfig.xLog ){
  26953. va_start(ap, zFormat);
  26954. renderLogMsg(iErrCode, zFormat, ap);
  26955. va_end(ap);
  26956. }
  26957. }
  26958. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  26959. /*
  26960. ** A version of printf() that understands %lld. Used for debugging.
  26961. ** The printf() built into some versions of windows does not understand %lld
  26962. ** and segfaults if you give it a long long int.
  26963. */
  26964. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  26965. va_list ap;
  26966. StrAccum acc;
  26967. char zBuf[500];
  26968. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  26969. va_start(ap,zFormat);
  26970. sqlite3_str_vappendf(&acc, zFormat, ap);
  26971. va_end(ap);
  26972. sqlite3StrAccumFinish(&acc);
  26973. #ifdef SQLITE_OS_TRACE_PROC
  26974. {
  26975. extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
  26976. SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
  26977. }
  26978. #else
  26979. fprintf(stdout,"%s", zBuf);
  26980. fflush(stdout);
  26981. #endif
  26982. }
  26983. #endif
  26984. /*
  26985. ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
  26986. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  26987. */
  26988. SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
  26989. va_list ap;
  26990. va_start(ap,zFormat);
  26991. sqlite3_str_vappendf(p, zFormat, ap);
  26992. va_end(ap);
  26993. }
  26994. /************** End of printf.c **********************************************/
  26995. /************** Begin file treeview.c ****************************************/
  26996. /*
  26997. ** 2015-06-08
  26998. **
  26999. ** The author disclaims copyright to this source code. In place of
  27000. ** a legal notice, here is a blessing:
  27001. **
  27002. ** May you do good and not evil.
  27003. ** May you find forgiveness for yourself and forgive others.
  27004. ** May you share freely, never taking more than you give.
  27005. **
  27006. *************************************************************************
  27007. **
  27008. ** This file contains C code to implement the TreeView debugging routines.
  27009. ** These routines print a parse tree to standard output for debugging and
  27010. ** analysis.
  27011. **
  27012. ** The interfaces in this file is only available when compiling
  27013. ** with SQLITE_DEBUG.
  27014. */
  27015. /* #include "sqliteInt.h" */
  27016. #ifdef SQLITE_DEBUG
  27017. /*
  27018. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  27019. ** is not the last item in the tree.
  27020. */
  27021. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  27022. if( p==0 ){
  27023. p = sqlite3_malloc64( sizeof(*p) );
  27024. if( p==0 ) return 0;
  27025. memset(p, 0, sizeof(*p));
  27026. }else{
  27027. p->iLevel++;
  27028. }
  27029. assert( moreToFollow==0 || moreToFollow==1 );
  27030. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  27031. return p;
  27032. }
  27033. /*
  27034. ** Finished with one layer of the tree
  27035. */
  27036. static void sqlite3TreeViewPop(TreeView *p){
  27037. if( p==0 ) return;
  27038. p->iLevel--;
  27039. if( p->iLevel<0 ) sqlite3_free(p);
  27040. }
  27041. /*
  27042. ** Generate a single line of output for the tree, with a prefix that contains
  27043. ** all the appropriate tree lines
  27044. */
  27045. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  27046. va_list ap;
  27047. int i;
  27048. StrAccum acc;
  27049. char zBuf[500];
  27050. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  27051. if( p ){
  27052. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  27053. sqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4);
  27054. }
  27055. sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  27056. }
  27057. if( zFormat!=0 ){
  27058. va_start(ap, zFormat);
  27059. sqlite3_str_vappendf(&acc, zFormat, ap);
  27060. va_end(ap);
  27061. assert( acc.nChar>0 );
  27062. sqlite3_str_append(&acc, "\n", 1);
  27063. }
  27064. sqlite3StrAccumFinish(&acc);
  27065. fprintf(stdout,"%s", zBuf);
  27066. fflush(stdout);
  27067. }
  27068. /*
  27069. ** Shorthand for starting a new tree item that consists of a single label
  27070. */
  27071. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  27072. p = sqlite3TreeViewPush(p, moreFollows);
  27073. sqlite3TreeViewLine(p, "%s", zLabel);
  27074. }
  27075. /*
  27076. ** Generate a human-readable description of a WITH clause.
  27077. */
  27078. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
  27079. int i;
  27080. if( pWith==0 ) return;
  27081. if( pWith->nCte==0 ) return;
  27082. if( pWith->pOuter ){
  27083. sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
  27084. }else{
  27085. sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
  27086. }
  27087. if( pWith->nCte>0 ){
  27088. pView = sqlite3TreeViewPush(pView, 1);
  27089. for(i=0; i<pWith->nCte; i++){
  27090. StrAccum x;
  27091. char zLine[1000];
  27092. const struct Cte *pCte = &pWith->a[i];
  27093. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  27094. sqlite3_str_appendf(&x, "%s", pCte->zName);
  27095. if( pCte->pCols && pCte->pCols->nExpr>0 ){
  27096. char cSep = '(';
  27097. int j;
  27098. for(j=0; j<pCte->pCols->nExpr; j++){
  27099. sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
  27100. cSep = ',';
  27101. }
  27102. sqlite3_str_appendf(&x, ")");
  27103. }
  27104. sqlite3_str_appendf(&x, " AS");
  27105. sqlite3StrAccumFinish(&x);
  27106. sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
  27107. sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
  27108. sqlite3TreeViewPop(pView);
  27109. }
  27110. sqlite3TreeViewPop(pView);
  27111. }
  27112. }
  27113. /*
  27114. ** Generate a human-readable description of a SrcList object.
  27115. */
  27116. SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){
  27117. int i;
  27118. for(i=0; i<pSrc->nSrc; i++){
  27119. const struct SrcList_item *pItem = &pSrc->a[i];
  27120. StrAccum x;
  27121. char zLine[100];
  27122. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  27123. sqlite3_str_appendf(&x, "{%d,*}", pItem->iCursor);
  27124. if( pItem->zDatabase ){
  27125. sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
  27126. }else if( pItem->zName ){
  27127. sqlite3_str_appendf(&x, " %s", pItem->zName);
  27128. }
  27129. if( pItem->pTab ){
  27130. sqlite3_str_appendf(&x, " tabname=%Q", pItem->pTab->zName);
  27131. }
  27132. if( pItem->zAlias ){
  27133. sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
  27134. }
  27135. if( pItem->fg.jointype & JT_LEFT ){
  27136. sqlite3_str_appendf(&x, " LEFT-JOIN");
  27137. }
  27138. sqlite3StrAccumFinish(&x);
  27139. sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1);
  27140. if( pItem->pSelect ){
  27141. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  27142. }
  27143. if( pItem->fg.isTabFunc ){
  27144. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  27145. }
  27146. sqlite3TreeViewPop(pView);
  27147. }
  27148. }
  27149. /*
  27150. ** Generate a human-readable description of a Select object.
  27151. */
  27152. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  27153. int n = 0;
  27154. int cnt = 0;
  27155. if( p==0 ){
  27156. sqlite3TreeViewLine(pView, "nil-SELECT");
  27157. return;
  27158. }
  27159. pView = sqlite3TreeViewPush(pView, moreToFollow);
  27160. if( p->pWith ){
  27161. sqlite3TreeViewWith(pView, p->pWith, 1);
  27162. cnt = 1;
  27163. sqlite3TreeViewPush(pView, 1);
  27164. }
  27165. do{
  27166. sqlite3TreeViewLine(pView,
  27167. "SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d",
  27168. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  27169. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
  27170. p->selId, p, p->selFlags,
  27171. (int)p->nSelectRow
  27172. );
  27173. if( cnt++ ) sqlite3TreeViewPop(pView);
  27174. if( p->pPrior ){
  27175. n = 1000;
  27176. }else{
  27177. n = 0;
  27178. if( p->pSrc && p->pSrc->nSrc ) n++;
  27179. if( p->pWhere ) n++;
  27180. if( p->pGroupBy ) n++;
  27181. if( p->pHaving ) n++;
  27182. if( p->pOrderBy ) n++;
  27183. if( p->pLimit ) n++;
  27184. #ifndef SQLITE_OMIT_WINDOWFUNC
  27185. if( p->pWin ) n++;
  27186. if( p->pWinDefn ) n++;
  27187. #endif
  27188. }
  27189. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  27190. #ifndef SQLITE_OMIT_WINDOWFUNC
  27191. if( p->pWin ){
  27192. Window *pX;
  27193. pView = sqlite3TreeViewPush(pView, (n--)>0);
  27194. sqlite3TreeViewLine(pView, "window-functions");
  27195. for(pX=p->pWin; pX; pX=pX->pNextWin){
  27196. sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);
  27197. }
  27198. sqlite3TreeViewPop(pView);
  27199. }
  27200. #endif
  27201. if( p->pSrc && p->pSrc->nSrc ){
  27202. pView = sqlite3TreeViewPush(pView, (n--)>0);
  27203. sqlite3TreeViewLine(pView, "FROM");
  27204. sqlite3TreeViewSrcList(pView, p->pSrc);
  27205. sqlite3TreeViewPop(pView);
  27206. }
  27207. if( p->pWhere ){
  27208. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  27209. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  27210. sqlite3TreeViewPop(pView);
  27211. }
  27212. if( p->pGroupBy ){
  27213. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  27214. }
  27215. if( p->pHaving ){
  27216. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  27217. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  27218. sqlite3TreeViewPop(pView);
  27219. }
  27220. #ifndef SQLITE_OMIT_WINDOWFUNC
  27221. if( p->pWinDefn ){
  27222. Window *pX;
  27223. sqlite3TreeViewItem(pView, "WINDOW", (n--)>0);
  27224. for(pX=p->pWinDefn; pX; pX=pX->pNextWin){
  27225. sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0);
  27226. }
  27227. sqlite3TreeViewPop(pView);
  27228. }
  27229. #endif
  27230. if( p->pOrderBy ){
  27231. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  27232. }
  27233. if( p->pLimit ){
  27234. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  27235. sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
  27236. if( p->pLimit->pRight ){
  27237. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  27238. sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
  27239. sqlite3TreeViewPop(pView);
  27240. }
  27241. sqlite3TreeViewPop(pView);
  27242. }
  27243. if( p->pPrior ){
  27244. const char *zOp = "UNION";
  27245. switch( p->op ){
  27246. case TK_ALL: zOp = "UNION ALL"; break;
  27247. case TK_INTERSECT: zOp = "INTERSECT"; break;
  27248. case TK_EXCEPT: zOp = "EXCEPT"; break;
  27249. }
  27250. sqlite3TreeViewItem(pView, zOp, 1);
  27251. }
  27252. p = p->pPrior;
  27253. }while( p!=0 );
  27254. sqlite3TreeViewPop(pView);
  27255. }
  27256. #ifndef SQLITE_OMIT_WINDOWFUNC
  27257. /*
  27258. ** Generate a description of starting or stopping bounds
  27259. */
  27260. SQLITE_PRIVATE void sqlite3TreeViewBound(
  27261. TreeView *pView, /* View context */
  27262. u8 eBound, /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */
  27263. Expr *pExpr, /* Value for PRECEDING or FOLLOWING */
  27264. u8 moreToFollow /* True if more to follow */
  27265. ){
  27266. switch( eBound ){
  27267. case TK_UNBOUNDED: {
  27268. sqlite3TreeViewItem(pView, "UNBOUNDED", moreToFollow);
  27269. sqlite3TreeViewPop(pView);
  27270. break;
  27271. }
  27272. case TK_CURRENT: {
  27273. sqlite3TreeViewItem(pView, "CURRENT", moreToFollow);
  27274. sqlite3TreeViewPop(pView);
  27275. break;
  27276. }
  27277. case TK_PRECEDING: {
  27278. sqlite3TreeViewItem(pView, "PRECEDING", moreToFollow);
  27279. sqlite3TreeViewExpr(pView, pExpr, 0);
  27280. sqlite3TreeViewPop(pView);
  27281. break;
  27282. }
  27283. case TK_FOLLOWING: {
  27284. sqlite3TreeViewItem(pView, "FOLLOWING", moreToFollow);
  27285. sqlite3TreeViewExpr(pView, pExpr, 0);
  27286. sqlite3TreeViewPop(pView);
  27287. break;
  27288. }
  27289. }
  27290. }
  27291. #endif /* SQLITE_OMIT_WINDOWFUNC */
  27292. #ifndef SQLITE_OMIT_WINDOWFUNC
  27293. /*
  27294. ** Generate a human-readable explanation for a Window object
  27295. */
  27296. SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){
  27297. pView = sqlite3TreeViewPush(pView, more);
  27298. if( pWin->zName ){
  27299. sqlite3TreeViewLine(pView, "OVER %s", pWin->zName);
  27300. }else{
  27301. sqlite3TreeViewLine(pView, "OVER");
  27302. }
  27303. if( pWin->pPartition ){
  27304. sqlite3TreeViewExprList(pView, pWin->pPartition, 1, "PARTITION-BY");
  27305. }
  27306. if( pWin->pOrderBy ){
  27307. sqlite3TreeViewExprList(pView, pWin->pOrderBy, 1, "ORDER-BY");
  27308. }
  27309. if( pWin->eType ){
  27310. sqlite3TreeViewItem(pView, pWin->eType==TK_RANGE ? "RANGE" : "ROWS", 0);
  27311. sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1);
  27312. sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0);
  27313. sqlite3TreeViewPop(pView);
  27314. }
  27315. sqlite3TreeViewPop(pView);
  27316. }
  27317. #endif /* SQLITE_OMIT_WINDOWFUNC */
  27318. #ifndef SQLITE_OMIT_WINDOWFUNC
  27319. /*
  27320. ** Generate a human-readable explanation for a Window Function object
  27321. */
  27322. SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){
  27323. pView = sqlite3TreeViewPush(pView, more);
  27324. sqlite3TreeViewLine(pView, "WINFUNC %s(%d)",
  27325. pWin->pFunc->zName, pWin->pFunc->nArg);
  27326. sqlite3TreeViewWindow(pView, pWin, 0);
  27327. sqlite3TreeViewPop(pView);
  27328. }
  27329. #endif /* SQLITE_OMIT_WINDOWFUNC */
  27330. /*
  27331. ** Generate a human-readable explanation of an expression tree.
  27332. */
  27333. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  27334. const char *zBinOp = 0; /* Binary operator */
  27335. const char *zUniOp = 0; /* Unary operator */
  27336. char zFlgs[60];
  27337. pView = sqlite3TreeViewPush(pView, moreToFollow);
  27338. if( pExpr==0 ){
  27339. sqlite3TreeViewLine(pView, "nil");
  27340. sqlite3TreeViewPop(pView);
  27341. return;
  27342. }
  27343. if( pExpr->flags ){
  27344. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  27345. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x iRJT=%d",
  27346. pExpr->flags, pExpr->iRightJoinTable);
  27347. }else{
  27348. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  27349. }
  27350. }else{
  27351. zFlgs[0] = 0;
  27352. }
  27353. switch( pExpr->op ){
  27354. case TK_AGG_COLUMN: {
  27355. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  27356. pExpr->iTable, pExpr->iColumn, zFlgs);
  27357. break;
  27358. }
  27359. case TK_COLUMN: {
  27360. if( pExpr->iTable<0 ){
  27361. /* This only happens when coding check constraints */
  27362. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  27363. }else{
  27364. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  27365. pExpr->iTable, pExpr->iColumn, zFlgs);
  27366. }
  27367. if( ExprHasProperty(pExpr, EP_FixedCol) ){
  27368. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27369. }
  27370. break;
  27371. }
  27372. case TK_INTEGER: {
  27373. if( pExpr->flags & EP_IntValue ){
  27374. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  27375. }else{
  27376. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  27377. }
  27378. break;
  27379. }
  27380. #ifndef SQLITE_OMIT_FLOATING_POINT
  27381. case TK_FLOAT: {
  27382. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  27383. break;
  27384. }
  27385. #endif
  27386. case TK_STRING: {
  27387. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  27388. break;
  27389. }
  27390. case TK_NULL: {
  27391. sqlite3TreeViewLine(pView,"NULL");
  27392. break;
  27393. }
  27394. case TK_TRUEFALSE: {
  27395. sqlite3TreeViewLine(pView,
  27396. sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE");
  27397. break;
  27398. }
  27399. #ifndef SQLITE_OMIT_BLOB_LITERAL
  27400. case TK_BLOB: {
  27401. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  27402. break;
  27403. }
  27404. #endif
  27405. case TK_VARIABLE: {
  27406. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  27407. pExpr->u.zToken, pExpr->iColumn);
  27408. break;
  27409. }
  27410. case TK_REGISTER: {
  27411. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  27412. break;
  27413. }
  27414. case TK_ID: {
  27415. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  27416. break;
  27417. }
  27418. #ifndef SQLITE_OMIT_CAST
  27419. case TK_CAST: {
  27420. /* Expressions of the form: CAST(pLeft AS token) */
  27421. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  27422. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27423. break;
  27424. }
  27425. #endif /* SQLITE_OMIT_CAST */
  27426. case TK_LT: zBinOp = "LT"; break;
  27427. case TK_LE: zBinOp = "LE"; break;
  27428. case TK_GT: zBinOp = "GT"; break;
  27429. case TK_GE: zBinOp = "GE"; break;
  27430. case TK_NE: zBinOp = "NE"; break;
  27431. case TK_EQ: zBinOp = "EQ"; break;
  27432. case TK_IS: zBinOp = "IS"; break;
  27433. case TK_ISNOT: zBinOp = "ISNOT"; break;
  27434. case TK_AND: zBinOp = "AND"; break;
  27435. case TK_OR: zBinOp = "OR"; break;
  27436. case TK_PLUS: zBinOp = "ADD"; break;
  27437. case TK_STAR: zBinOp = "MUL"; break;
  27438. case TK_MINUS: zBinOp = "SUB"; break;
  27439. case TK_REM: zBinOp = "REM"; break;
  27440. case TK_BITAND: zBinOp = "BITAND"; break;
  27441. case TK_BITOR: zBinOp = "BITOR"; break;
  27442. case TK_SLASH: zBinOp = "DIV"; break;
  27443. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  27444. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  27445. case TK_CONCAT: zBinOp = "CONCAT"; break;
  27446. case TK_DOT: zBinOp = "DOT"; break;
  27447. case TK_UMINUS: zUniOp = "UMINUS"; break;
  27448. case TK_UPLUS: zUniOp = "UPLUS"; break;
  27449. case TK_BITNOT: zUniOp = "BITNOT"; break;
  27450. case TK_NOT: zUniOp = "NOT"; break;
  27451. case TK_ISNULL: zUniOp = "ISNULL"; break;
  27452. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  27453. case TK_TRUTH: {
  27454. int x;
  27455. const char *azOp[] = {
  27456. "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
  27457. };
  27458. assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
  27459. assert( pExpr->pRight );
  27460. assert( pExpr->pRight->op==TK_TRUEFALSE );
  27461. x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
  27462. zUniOp = azOp[x];
  27463. break;
  27464. }
  27465. case TK_SPAN: {
  27466. sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
  27467. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27468. break;
  27469. }
  27470. case TK_COLLATE: {
  27471. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  27472. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27473. break;
  27474. }
  27475. case TK_AGG_FUNCTION:
  27476. case TK_FUNCTION: {
  27477. ExprList *pFarg; /* List of function arguments */
  27478. Window *pWin;
  27479. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  27480. pFarg = 0;
  27481. pWin = 0;
  27482. }else{
  27483. pFarg = pExpr->x.pList;
  27484. #ifndef SQLITE_OMIT_WINDOWFUNC
  27485. pWin = pExpr->y.pWin;
  27486. #else
  27487. pWin = 0;
  27488. #endif
  27489. }
  27490. if( pExpr->op==TK_AGG_FUNCTION ){
  27491. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  27492. pExpr->op2, pExpr->u.zToken);
  27493. }else{
  27494. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  27495. }
  27496. if( pFarg ){
  27497. sqlite3TreeViewExprList(pView, pFarg, pWin!=0, 0);
  27498. }
  27499. #ifndef SQLITE_OMIT_WINDOWFUNC
  27500. if( pWin ){
  27501. sqlite3TreeViewWindow(pView, pWin, 0);
  27502. }
  27503. #endif
  27504. break;
  27505. }
  27506. #ifndef SQLITE_OMIT_SUBQUERY
  27507. case TK_EXISTS: {
  27508. sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
  27509. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  27510. break;
  27511. }
  27512. case TK_SELECT: {
  27513. sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
  27514. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  27515. break;
  27516. }
  27517. case TK_IN: {
  27518. sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
  27519. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  27520. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  27521. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  27522. }else{
  27523. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  27524. }
  27525. break;
  27526. }
  27527. #endif /* SQLITE_OMIT_SUBQUERY */
  27528. /*
  27529. ** x BETWEEN y AND z
  27530. **
  27531. ** This is equivalent to
  27532. **
  27533. ** x>=y AND x<=z
  27534. **
  27535. ** X is stored in pExpr->pLeft.
  27536. ** Y is stored in pExpr->pList->a[0].pExpr.
  27537. ** Z is stored in pExpr->pList->a[1].pExpr.
  27538. */
  27539. case TK_BETWEEN: {
  27540. Expr *pX = pExpr->pLeft;
  27541. Expr *pY = pExpr->x.pList->a[0].pExpr;
  27542. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  27543. sqlite3TreeViewLine(pView, "BETWEEN");
  27544. sqlite3TreeViewExpr(pView, pX, 1);
  27545. sqlite3TreeViewExpr(pView, pY, 1);
  27546. sqlite3TreeViewExpr(pView, pZ, 0);
  27547. break;
  27548. }
  27549. case TK_TRIGGER: {
  27550. /* If the opcode is TK_TRIGGER, then the expression is a reference
  27551. ** to a column in the new.* or old.* pseudo-tables available to
  27552. ** trigger programs. In this case Expr.iTable is set to 1 for the
  27553. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  27554. ** is set to the column of the pseudo-table to read, or to -1 to
  27555. ** read the rowid field.
  27556. */
  27557. sqlite3TreeViewLine(pView, "%s(%d)",
  27558. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  27559. break;
  27560. }
  27561. case TK_CASE: {
  27562. sqlite3TreeViewLine(pView, "CASE");
  27563. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  27564. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  27565. break;
  27566. }
  27567. #ifndef SQLITE_OMIT_TRIGGER
  27568. case TK_RAISE: {
  27569. const char *zType = "unk";
  27570. switch( pExpr->affinity ){
  27571. case OE_Rollback: zType = "rollback"; break;
  27572. case OE_Abort: zType = "abort"; break;
  27573. case OE_Fail: zType = "fail"; break;
  27574. case OE_Ignore: zType = "ignore"; break;
  27575. }
  27576. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  27577. break;
  27578. }
  27579. #endif
  27580. case TK_MATCH: {
  27581. sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
  27582. pExpr->iTable, pExpr->iColumn, zFlgs);
  27583. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  27584. break;
  27585. }
  27586. case TK_VECTOR: {
  27587. sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
  27588. break;
  27589. }
  27590. case TK_SELECT_COLUMN: {
  27591. sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
  27592. sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
  27593. break;
  27594. }
  27595. case TK_IF_NULL_ROW: {
  27596. sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
  27597. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27598. break;
  27599. }
  27600. default: {
  27601. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  27602. break;
  27603. }
  27604. }
  27605. if( zBinOp ){
  27606. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  27607. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  27608. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  27609. }else if( zUniOp ){
  27610. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  27611. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27612. }
  27613. sqlite3TreeViewPop(pView);
  27614. }
  27615. /*
  27616. ** Generate a human-readable explanation of an expression list.
  27617. */
  27618. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
  27619. TreeView *pView,
  27620. const ExprList *pList,
  27621. const char *zLabel
  27622. ){
  27623. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  27624. if( pList==0 ){
  27625. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  27626. }else{
  27627. int i;
  27628. sqlite3TreeViewLine(pView, "%s", zLabel);
  27629. for(i=0; i<pList->nExpr; i++){
  27630. int j = pList->a[i].u.x.iOrderByCol;
  27631. char *zName = pList->a[i].zName;
  27632. int moreToFollow = i<pList->nExpr - 1;
  27633. if( j || zName ){
  27634. sqlite3TreeViewPush(pView, moreToFollow);
  27635. moreToFollow = 0;
  27636. sqlite3TreeViewLine(pView, 0);
  27637. if( zName ){
  27638. fprintf(stdout, "AS %s ", zName);
  27639. }
  27640. if( j ){
  27641. fprintf(stdout, "iOrderByCol=%d", j);
  27642. }
  27643. fprintf(stdout, "\n");
  27644. fflush(stdout);
  27645. }
  27646. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);
  27647. if( j || zName ){
  27648. sqlite3TreeViewPop(pView);
  27649. }
  27650. }
  27651. }
  27652. }
  27653. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  27654. TreeView *pView,
  27655. const ExprList *pList,
  27656. u8 moreToFollow,
  27657. const char *zLabel
  27658. ){
  27659. pView = sqlite3TreeViewPush(pView, moreToFollow);
  27660. sqlite3TreeViewBareExprList(pView, pList, zLabel);
  27661. sqlite3TreeViewPop(pView);
  27662. }
  27663. #endif /* SQLITE_DEBUG */
  27664. /************** End of treeview.c ********************************************/
  27665. /************** Begin file random.c ******************************************/
  27666. /*
  27667. ** 2001 September 15
  27668. **
  27669. ** The author disclaims copyright to this source code. In place of
  27670. ** a legal notice, here is a blessing:
  27671. **
  27672. ** May you do good and not evil.
  27673. ** May you find forgiveness for yourself and forgive others.
  27674. ** May you share freely, never taking more than you give.
  27675. **
  27676. *************************************************************************
  27677. ** This file contains code to implement a pseudo-random number
  27678. ** generator (PRNG) for SQLite.
  27679. **
  27680. ** Random numbers are used by some of the database backends in order
  27681. ** to generate random integer keys for tables or random filenames.
  27682. */
  27683. /* #include "sqliteInt.h" */
  27684. /* All threads share a single random number generator.
  27685. ** This structure is the current state of the generator.
  27686. */
  27687. static SQLITE_WSD struct sqlite3PrngType {
  27688. unsigned char isInit; /* True if initialized */
  27689. unsigned char i, j; /* State variables */
  27690. unsigned char s[256]; /* State variables */
  27691. } sqlite3Prng;
  27692. /*
  27693. ** Return N random bytes.
  27694. */
  27695. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  27696. unsigned char t;
  27697. unsigned char *zBuf = pBuf;
  27698. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  27699. ** state vector. If writable static data is unsupported on the target,
  27700. ** we have to locate the state vector at run-time. In the more common
  27701. ** case where writable static data is supported, wsdPrng can refer directly
  27702. ** to the "sqlite3Prng" state vector declared above.
  27703. */
  27704. #ifdef SQLITE_OMIT_WSD
  27705. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  27706. # define wsdPrng p[0]
  27707. #else
  27708. # define wsdPrng sqlite3Prng
  27709. #endif
  27710. #if SQLITE_THREADSAFE
  27711. sqlite3_mutex *mutex;
  27712. #endif
  27713. #ifndef SQLITE_OMIT_AUTOINIT
  27714. if( sqlite3_initialize() ) return;
  27715. #endif
  27716. #if SQLITE_THREADSAFE
  27717. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  27718. #endif
  27719. sqlite3_mutex_enter(mutex);
  27720. if( N<=0 || pBuf==0 ){
  27721. wsdPrng.isInit = 0;
  27722. sqlite3_mutex_leave(mutex);
  27723. return;
  27724. }
  27725. /* Initialize the state of the random number generator once,
  27726. ** the first time this routine is called. The seed value does
  27727. ** not need to contain a lot of randomness since we are not
  27728. ** trying to do secure encryption or anything like that...
  27729. **
  27730. ** Nothing in this file or anywhere else in SQLite does any kind of
  27731. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  27732. ** number generator) not as an encryption device.
  27733. */
  27734. if( !wsdPrng.isInit ){
  27735. int i;
  27736. char k[256];
  27737. wsdPrng.j = 0;
  27738. wsdPrng.i = 0;
  27739. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  27740. for(i=0; i<256; i++){
  27741. wsdPrng.s[i] = (u8)i;
  27742. }
  27743. for(i=0; i<256; i++){
  27744. wsdPrng.j += wsdPrng.s[i] + k[i];
  27745. t = wsdPrng.s[wsdPrng.j];
  27746. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  27747. wsdPrng.s[i] = t;
  27748. }
  27749. wsdPrng.isInit = 1;
  27750. }
  27751. assert( N>0 );
  27752. do{
  27753. wsdPrng.i++;
  27754. t = wsdPrng.s[wsdPrng.i];
  27755. wsdPrng.j += t;
  27756. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  27757. wsdPrng.s[wsdPrng.j] = t;
  27758. t += wsdPrng.s[wsdPrng.i];
  27759. *(zBuf++) = wsdPrng.s[t];
  27760. }while( --N );
  27761. sqlite3_mutex_leave(mutex);
  27762. }
  27763. #ifndef SQLITE_UNTESTABLE
  27764. /*
  27765. ** For testing purposes, we sometimes want to preserve the state of
  27766. ** PRNG and restore the PRNG to its saved state at a later time, or
  27767. ** to reset the PRNG to its initial state. These routines accomplish
  27768. ** those tasks.
  27769. **
  27770. ** The sqlite3_test_control() interface calls these routines to
  27771. ** control the PRNG.
  27772. */
  27773. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  27774. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  27775. memcpy(
  27776. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  27777. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  27778. sizeof(sqlite3Prng)
  27779. );
  27780. }
  27781. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  27782. memcpy(
  27783. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  27784. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  27785. sizeof(sqlite3Prng)
  27786. );
  27787. }
  27788. #endif /* SQLITE_UNTESTABLE */
  27789. /************** End of random.c **********************************************/
  27790. /************** Begin file threads.c *****************************************/
  27791. /*
  27792. ** 2012 July 21
  27793. **
  27794. ** The author disclaims copyright to this source code. In place of
  27795. ** a legal notice, here is a blessing:
  27796. **
  27797. ** May you do good and not evil.
  27798. ** May you find forgiveness for yourself and forgive others.
  27799. ** May you share freely, never taking more than you give.
  27800. **
  27801. ******************************************************************************
  27802. **
  27803. ** This file presents a simple cross-platform threading interface for
  27804. ** use internally by SQLite.
  27805. **
  27806. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  27807. ** runs independently of its creator until it is joined using
  27808. ** sqlite3ThreadJoin(), at which point it terminates.
  27809. **
  27810. ** Threads do not have to be real. It could be that the work of the
  27811. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  27812. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  27813. ** single threaded systems. Nothing in SQLite requires multiple threads.
  27814. ** This interface exists so that applications that want to take advantage
  27815. ** of multiple cores can do so, while also allowing applications to stay
  27816. ** single-threaded if desired.
  27817. */
  27818. /* #include "sqliteInt.h" */
  27819. #if SQLITE_OS_WIN
  27820. /* # include "os_win.h" */
  27821. #endif
  27822. #if SQLITE_MAX_WORKER_THREADS>0
  27823. /********************************* Unix Pthreads ****************************/
  27824. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  27825. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  27826. /* #include <pthread.h> */
  27827. /* A running thread */
  27828. struct SQLiteThread {
  27829. pthread_t tid; /* Thread ID */
  27830. int done; /* Set to true when thread finishes */
  27831. void *pOut; /* Result returned by the thread */
  27832. void *(*xTask)(void*); /* The thread routine */
  27833. void *pIn; /* Argument to the thread */
  27834. };
  27835. /* Create a new thread */
  27836. SQLITE_PRIVATE int sqlite3ThreadCreate(
  27837. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  27838. void *(*xTask)(void*), /* Routine to run in a separate thread */
  27839. void *pIn /* Argument passed into xTask() */
  27840. ){
  27841. SQLiteThread *p;
  27842. int rc;
  27843. assert( ppThread!=0 );
  27844. assert( xTask!=0 );
  27845. /* This routine is never used in single-threaded mode */
  27846. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  27847. *ppThread = 0;
  27848. p = sqlite3Malloc(sizeof(*p));
  27849. if( p==0 ) return SQLITE_NOMEM_BKPT;
  27850. memset(p, 0, sizeof(*p));
  27851. p->xTask = xTask;
  27852. p->pIn = pIn;
  27853. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  27854. ** function that returns SQLITE_ERROR when passed the argument 200, that
  27855. ** forces worker threads to run sequentially and deterministically
  27856. ** for testing purposes. */
  27857. if( sqlite3FaultSim(200) ){
  27858. rc = 1;
  27859. }else{
  27860. rc = pthread_create(&p->tid, 0, xTask, pIn);
  27861. }
  27862. if( rc ){
  27863. p->done = 1;
  27864. p->pOut = xTask(pIn);
  27865. }
  27866. *ppThread = p;
  27867. return SQLITE_OK;
  27868. }
  27869. /* Get the results of the thread */
  27870. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  27871. int rc;
  27872. assert( ppOut!=0 );
  27873. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  27874. if( p->done ){
  27875. *ppOut = p->pOut;
  27876. rc = SQLITE_OK;
  27877. }else{
  27878. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  27879. }
  27880. sqlite3_free(p);
  27881. return rc;
  27882. }
  27883. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  27884. /******************************** End Unix Pthreads *************************/
  27885. /********************************* Win32 Threads ****************************/
  27886. #if SQLITE_OS_WIN_THREADS
  27887. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  27888. #include <process.h>
  27889. /* A running thread */
  27890. struct SQLiteThread {
  27891. void *tid; /* The thread handle */
  27892. unsigned id; /* The thread identifier */
  27893. void *(*xTask)(void*); /* The routine to run as a thread */
  27894. void *pIn; /* Argument to xTask */
  27895. void *pResult; /* Result of xTask */
  27896. };
  27897. /* Thread procedure Win32 compatibility shim */
  27898. static unsigned __stdcall sqlite3ThreadProc(
  27899. void *pArg /* IN: Pointer to the SQLiteThread structure */
  27900. ){
  27901. SQLiteThread *p = (SQLiteThread *)pArg;
  27902. assert( p!=0 );
  27903. #if 0
  27904. /*
  27905. ** This assert appears to trigger spuriously on certain
  27906. ** versions of Windows, possibly due to _beginthreadex()
  27907. ** and/or CreateThread() not fully setting their thread
  27908. ** ID parameter before starting the thread.
  27909. */
  27910. assert( p->id==GetCurrentThreadId() );
  27911. #endif
  27912. assert( p->xTask!=0 );
  27913. p->pResult = p->xTask(p->pIn);
  27914. _endthreadex(0);
  27915. return 0; /* NOT REACHED */
  27916. }
  27917. /* Create a new thread */
  27918. SQLITE_PRIVATE int sqlite3ThreadCreate(
  27919. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  27920. void *(*xTask)(void*), /* Routine to run in a separate thread */
  27921. void *pIn /* Argument passed into xTask() */
  27922. ){
  27923. SQLiteThread *p;
  27924. assert( ppThread!=0 );
  27925. assert( xTask!=0 );
  27926. *ppThread = 0;
  27927. p = sqlite3Malloc(sizeof(*p));
  27928. if( p==0 ) return SQLITE_NOMEM_BKPT;
  27929. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  27930. ** function that returns SQLITE_ERROR when passed the argument 200, that
  27931. ** forces worker threads to run sequentially and deterministically
  27932. ** (via the sqlite3FaultSim() term of the conditional) for testing
  27933. ** purposes. */
  27934. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  27935. memset(p, 0, sizeof(*p));
  27936. }else{
  27937. p->xTask = xTask;
  27938. p->pIn = pIn;
  27939. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  27940. if( p->tid==0 ){
  27941. memset(p, 0, sizeof(*p));
  27942. }
  27943. }
  27944. if( p->xTask==0 ){
  27945. p->id = GetCurrentThreadId();
  27946. p->pResult = xTask(pIn);
  27947. }
  27948. *ppThread = p;
  27949. return SQLITE_OK;
  27950. }
  27951. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  27952. /* Get the results of the thread */
  27953. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  27954. DWORD rc;
  27955. BOOL bRc;
  27956. assert( ppOut!=0 );
  27957. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  27958. if( p->xTask==0 ){
  27959. /* assert( p->id==GetCurrentThreadId() ); */
  27960. rc = WAIT_OBJECT_0;
  27961. assert( p->tid==0 );
  27962. }else{
  27963. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  27964. rc = sqlite3Win32Wait((HANDLE)p->tid);
  27965. assert( rc!=WAIT_IO_COMPLETION );
  27966. bRc = CloseHandle((HANDLE)p->tid);
  27967. assert( bRc );
  27968. }
  27969. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  27970. sqlite3_free(p);
  27971. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  27972. }
  27973. #endif /* SQLITE_OS_WIN_THREADS */
  27974. /******************************** End Win32 Threads *************************/
  27975. /********************************* Single-Threaded **************************/
  27976. #ifndef SQLITE_THREADS_IMPLEMENTED
  27977. /*
  27978. ** This implementation does not actually create a new thread. It does the
  27979. ** work of the thread in the main thread, when either the thread is created
  27980. ** or when it is joined
  27981. */
  27982. /* A running thread */
  27983. struct SQLiteThread {
  27984. void *(*xTask)(void*); /* The routine to run as a thread */
  27985. void *pIn; /* Argument to xTask */
  27986. void *pResult; /* Result of xTask */
  27987. };
  27988. /* Create a new thread */
  27989. SQLITE_PRIVATE int sqlite3ThreadCreate(
  27990. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  27991. void *(*xTask)(void*), /* Routine to run in a separate thread */
  27992. void *pIn /* Argument passed into xTask() */
  27993. ){
  27994. SQLiteThread *p;
  27995. assert( ppThread!=0 );
  27996. assert( xTask!=0 );
  27997. *ppThread = 0;
  27998. p = sqlite3Malloc(sizeof(*p));
  27999. if( p==0 ) return SQLITE_NOMEM_BKPT;
  28000. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  28001. p->xTask = xTask;
  28002. p->pIn = pIn;
  28003. }else{
  28004. p->xTask = 0;
  28005. p->pResult = xTask(pIn);
  28006. }
  28007. *ppThread = p;
  28008. return SQLITE_OK;
  28009. }
  28010. /* Get the results of the thread */
  28011. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  28012. assert( ppOut!=0 );
  28013. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  28014. if( p->xTask ){
  28015. *ppOut = p->xTask(p->pIn);
  28016. }else{
  28017. *ppOut = p->pResult;
  28018. }
  28019. sqlite3_free(p);
  28020. #if defined(SQLITE_TEST)
  28021. {
  28022. void *pTstAlloc = sqlite3Malloc(10);
  28023. if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
  28024. sqlite3_free(pTstAlloc);
  28025. }
  28026. #endif
  28027. return SQLITE_OK;
  28028. }
  28029. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  28030. /****************************** End Single-Threaded *************************/
  28031. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  28032. /************** End of threads.c *********************************************/
  28033. /************** Begin file utf.c *********************************************/
  28034. /*
  28035. ** 2004 April 13
  28036. **
  28037. ** The author disclaims copyright to this source code. In place of
  28038. ** a legal notice, here is a blessing:
  28039. **
  28040. ** May you do good and not evil.
  28041. ** May you find forgiveness for yourself and forgive others.
  28042. ** May you share freely, never taking more than you give.
  28043. **
  28044. *************************************************************************
  28045. ** This file contains routines used to translate between UTF-8,
  28046. ** UTF-16, UTF-16BE, and UTF-16LE.
  28047. **
  28048. ** Notes on UTF-8:
  28049. **
  28050. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  28051. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  28052. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  28053. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  28054. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  28055. **
  28056. **
  28057. ** Notes on UTF-16: (with wwww+1==uuuuu)
  28058. **
  28059. ** Word-0 Word-1 Value
  28060. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  28061. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  28062. **
  28063. **
  28064. ** BOM or Byte Order Mark:
  28065. ** 0xff 0xfe little-endian utf-16 follows
  28066. ** 0xfe 0xff big-endian utf-16 follows
  28067. **
  28068. */
  28069. /* #include "sqliteInt.h" */
  28070. /* #include <assert.h> */
  28071. /* #include "vdbeInt.h" */
  28072. #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
  28073. /*
  28074. ** The following constant value is used by the SQLITE_BIGENDIAN and
  28075. ** SQLITE_LITTLEENDIAN macros.
  28076. */
  28077. SQLITE_PRIVATE const int sqlite3one = 1;
  28078. #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
  28079. /*
  28080. ** This lookup table is used to help decode the first byte of
  28081. ** a multi-byte UTF8 character.
  28082. */
  28083. static const unsigned char sqlite3Utf8Trans1[] = {
  28084. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  28085. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  28086. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  28087. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  28088. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  28089. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  28090. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  28091. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  28092. };
  28093. #define WRITE_UTF8(zOut, c) { \
  28094. if( c<0x00080 ){ \
  28095. *zOut++ = (u8)(c&0xFF); \
  28096. } \
  28097. else if( c<0x00800 ){ \
  28098. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  28099. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  28100. } \
  28101. else if( c<0x10000 ){ \
  28102. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  28103. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  28104. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  28105. }else{ \
  28106. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  28107. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  28108. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  28109. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  28110. } \
  28111. }
  28112. #define WRITE_UTF16LE(zOut, c) { \
  28113. if( c<=0xFFFF ){ \
  28114. *zOut++ = (u8)(c&0x00FF); \
  28115. *zOut++ = (u8)((c>>8)&0x00FF); \
  28116. }else{ \
  28117. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  28118. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  28119. *zOut++ = (u8)(c&0x00FF); \
  28120. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  28121. } \
  28122. }
  28123. #define WRITE_UTF16BE(zOut, c) { \
  28124. if( c<=0xFFFF ){ \
  28125. *zOut++ = (u8)((c>>8)&0x00FF); \
  28126. *zOut++ = (u8)(c&0x00FF); \
  28127. }else{ \
  28128. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  28129. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  28130. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  28131. *zOut++ = (u8)(c&0x00FF); \
  28132. } \
  28133. }
  28134. #define READ_UTF16LE(zIn, TERM, c){ \
  28135. c = (*zIn++); \
  28136. c += ((*zIn++)<<8); \
  28137. if( c>=0xD800 && c<0xE000 && TERM ){ \
  28138. int c2 = (*zIn++); \
  28139. c2 += ((*zIn++)<<8); \
  28140. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  28141. } \
  28142. }
  28143. #define READ_UTF16BE(zIn, TERM, c){ \
  28144. c = ((*zIn++)<<8); \
  28145. c += (*zIn++); \
  28146. if( c>=0xD800 && c<0xE000 && TERM ){ \
  28147. int c2 = ((*zIn++)<<8); \
  28148. c2 += (*zIn++); \
  28149. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  28150. } \
  28151. }
  28152. /*
  28153. ** Translate a single UTF-8 character. Return the unicode value.
  28154. **
  28155. ** During translation, assume that the byte that zTerm points
  28156. ** is a 0x00.
  28157. **
  28158. ** Write a pointer to the next unread byte back into *pzNext.
  28159. **
  28160. ** Notes On Invalid UTF-8:
  28161. **
  28162. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  28163. ** be encoded as a multi-byte character. Any multi-byte character that
  28164. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  28165. **
  28166. ** * This routine never allows a UTF16 surrogate value to be encoded.
  28167. ** If a multi-byte character attempts to encode a value between
  28168. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  28169. **
  28170. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  28171. ** byte of a character are interpreted as single-byte characters
  28172. ** and rendered as themselves even though they are technically
  28173. ** invalid characters.
  28174. **
  28175. ** * This routine accepts over-length UTF8 encodings
  28176. ** for unicode values 0x80 and greater. It does not change over-length
  28177. ** encodings to 0xfffd as some systems recommend.
  28178. */
  28179. #define READ_UTF8(zIn, zTerm, c) \
  28180. c = *(zIn++); \
  28181. if( c>=0xc0 ){ \
  28182. c = sqlite3Utf8Trans1[c-0xc0]; \
  28183. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  28184. c = (c<<6) + (0x3f & *(zIn++)); \
  28185. } \
  28186. if( c<0x80 \
  28187. || (c&0xFFFFF800)==0xD800 \
  28188. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  28189. }
  28190. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  28191. const unsigned char **pz /* Pointer to string from which to read char */
  28192. ){
  28193. unsigned int c;
  28194. /* Same as READ_UTF8() above but without the zTerm parameter.
  28195. ** For this routine, we assume the UTF8 string is always zero-terminated.
  28196. */
  28197. c = *((*pz)++);
  28198. if( c>=0xc0 ){
  28199. c = sqlite3Utf8Trans1[c-0xc0];
  28200. while( (*(*pz) & 0xc0)==0x80 ){
  28201. c = (c<<6) + (0x3f & *((*pz)++));
  28202. }
  28203. if( c<0x80
  28204. || (c&0xFFFFF800)==0xD800
  28205. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  28206. }
  28207. return c;
  28208. }
  28209. /*
  28210. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  28211. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  28212. */
  28213. /* #define TRANSLATE_TRACE 1 */
  28214. #ifndef SQLITE_OMIT_UTF16
  28215. /*
  28216. ** This routine transforms the internal text encoding used by pMem to
  28217. ** desiredEnc. It is an error if the string is already of the desired
  28218. ** encoding, or if *pMem does not contain a string value.
  28219. */
  28220. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  28221. int len; /* Maximum length of output string in bytes */
  28222. unsigned char *zOut; /* Output buffer */
  28223. unsigned char *zIn; /* Input iterator */
  28224. unsigned char *zTerm; /* End of input */
  28225. unsigned char *z; /* Output iterator */
  28226. unsigned int c;
  28227. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  28228. assert( pMem->flags&MEM_Str );
  28229. assert( pMem->enc!=desiredEnc );
  28230. assert( pMem->enc!=0 );
  28231. assert( pMem->n>=0 );
  28232. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  28233. {
  28234. char zBuf[100];
  28235. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  28236. fprintf(stderr, "INPUT: %s\n", zBuf);
  28237. }
  28238. #endif
  28239. /* If the translation is between UTF-16 little and big endian, then
  28240. ** all that is required is to swap the byte order. This case is handled
  28241. ** differently from the others.
  28242. */
  28243. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  28244. u8 temp;
  28245. int rc;
  28246. rc = sqlite3VdbeMemMakeWriteable(pMem);
  28247. if( rc!=SQLITE_OK ){
  28248. assert( rc==SQLITE_NOMEM );
  28249. return SQLITE_NOMEM_BKPT;
  28250. }
  28251. zIn = (u8*)pMem->z;
  28252. zTerm = &zIn[pMem->n&~1];
  28253. while( zIn<zTerm ){
  28254. temp = *zIn;
  28255. *zIn = *(zIn+1);
  28256. zIn++;
  28257. *zIn++ = temp;
  28258. }
  28259. pMem->enc = desiredEnc;
  28260. goto translate_out;
  28261. }
  28262. /* Set len to the maximum number of bytes required in the output buffer. */
  28263. if( desiredEnc==SQLITE_UTF8 ){
  28264. /* When converting from UTF-16, the maximum growth results from
  28265. ** translating a 2-byte character to a 4-byte UTF-8 character.
  28266. ** A single byte is required for the output string
  28267. ** nul-terminator.
  28268. */
  28269. pMem->n &= ~1;
  28270. len = pMem->n * 2 + 1;
  28271. }else{
  28272. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  28273. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  28274. ** character. Two bytes are required in the output buffer for the
  28275. ** nul-terminator.
  28276. */
  28277. len = pMem->n * 2 + 2;
  28278. }
  28279. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  28280. ** byte past the end.
  28281. **
  28282. ** Variable zOut is set to point at the output buffer, space obtained
  28283. ** from sqlite3_malloc().
  28284. */
  28285. zIn = (u8*)pMem->z;
  28286. zTerm = &zIn[pMem->n];
  28287. zOut = sqlite3DbMallocRaw(pMem->db, len);
  28288. if( !zOut ){
  28289. return SQLITE_NOMEM_BKPT;
  28290. }
  28291. z = zOut;
  28292. if( pMem->enc==SQLITE_UTF8 ){
  28293. if( desiredEnc==SQLITE_UTF16LE ){
  28294. /* UTF-8 -> UTF-16 Little-endian */
  28295. while( zIn<zTerm ){
  28296. READ_UTF8(zIn, zTerm, c);
  28297. WRITE_UTF16LE(z, c);
  28298. }
  28299. }else{
  28300. assert( desiredEnc==SQLITE_UTF16BE );
  28301. /* UTF-8 -> UTF-16 Big-endian */
  28302. while( zIn<zTerm ){
  28303. READ_UTF8(zIn, zTerm, c);
  28304. WRITE_UTF16BE(z, c);
  28305. }
  28306. }
  28307. pMem->n = (int)(z - zOut);
  28308. *z++ = 0;
  28309. }else{
  28310. assert( desiredEnc==SQLITE_UTF8 );
  28311. if( pMem->enc==SQLITE_UTF16LE ){
  28312. /* UTF-16 Little-endian -> UTF-8 */
  28313. while( zIn<zTerm ){
  28314. READ_UTF16LE(zIn, zIn<zTerm, c);
  28315. WRITE_UTF8(z, c);
  28316. }
  28317. }else{
  28318. /* UTF-16 Big-endian -> UTF-8 */
  28319. while( zIn<zTerm ){
  28320. READ_UTF16BE(zIn, zIn<zTerm, c);
  28321. WRITE_UTF8(z, c);
  28322. }
  28323. }
  28324. pMem->n = (int)(z - zOut);
  28325. }
  28326. *z = 0;
  28327. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  28328. c = pMem->flags;
  28329. sqlite3VdbeMemRelease(pMem);
  28330. pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
  28331. pMem->enc = desiredEnc;
  28332. pMem->z = (char*)zOut;
  28333. pMem->zMalloc = pMem->z;
  28334. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  28335. translate_out:
  28336. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  28337. {
  28338. char zBuf[100];
  28339. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  28340. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  28341. }
  28342. #endif
  28343. return SQLITE_OK;
  28344. }
  28345. #endif /* SQLITE_OMIT_UTF16 */
  28346. #ifndef SQLITE_OMIT_UTF16
  28347. /*
  28348. ** This routine checks for a byte-order mark at the beginning of the
  28349. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  28350. ** the encoding of the Mem adjusted. This routine does not do any
  28351. ** byte-swapping, it just sets Mem.enc appropriately.
  28352. **
  28353. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  28354. ** changed by this function.
  28355. */
  28356. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  28357. int rc = SQLITE_OK;
  28358. u8 bom = 0;
  28359. assert( pMem->n>=0 );
  28360. if( pMem->n>1 ){
  28361. u8 b1 = *(u8 *)pMem->z;
  28362. u8 b2 = *(((u8 *)pMem->z) + 1);
  28363. if( b1==0xFE && b2==0xFF ){
  28364. bom = SQLITE_UTF16BE;
  28365. }
  28366. if( b1==0xFF && b2==0xFE ){
  28367. bom = SQLITE_UTF16LE;
  28368. }
  28369. }
  28370. if( bom ){
  28371. rc = sqlite3VdbeMemMakeWriteable(pMem);
  28372. if( rc==SQLITE_OK ){
  28373. pMem->n -= 2;
  28374. memmove(pMem->z, &pMem->z[2], pMem->n);
  28375. pMem->z[pMem->n] = '\0';
  28376. pMem->z[pMem->n+1] = '\0';
  28377. pMem->flags |= MEM_Term;
  28378. pMem->enc = bom;
  28379. }
  28380. }
  28381. return rc;
  28382. }
  28383. #endif /* SQLITE_OMIT_UTF16 */
  28384. /*
  28385. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  28386. ** return the number of unicode characters in pZ up to (but not including)
  28387. ** the first 0x00 byte. If nByte is not less than zero, return the
  28388. ** number of unicode characters in the first nByte of pZ (or up to
  28389. ** the first 0x00, whichever comes first).
  28390. */
  28391. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  28392. int r = 0;
  28393. const u8 *z = (const u8*)zIn;
  28394. const u8 *zTerm;
  28395. if( nByte>=0 ){
  28396. zTerm = &z[nByte];
  28397. }else{
  28398. zTerm = (const u8*)(-1);
  28399. }
  28400. assert( z<=zTerm );
  28401. while( *z!=0 && z<zTerm ){
  28402. SQLITE_SKIP_UTF8(z);
  28403. r++;
  28404. }
  28405. return r;
  28406. }
  28407. /* This test function is not currently used by the automated test-suite.
  28408. ** Hence it is only available in debug builds.
  28409. */
  28410. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  28411. /*
  28412. ** Translate UTF-8 to UTF-8.
  28413. **
  28414. ** This has the effect of making sure that the string is well-formed
  28415. ** UTF-8. Miscoded characters are removed.
  28416. **
  28417. ** The translation is done in-place and aborted if the output
  28418. ** overruns the input.
  28419. */
  28420. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  28421. unsigned char *zOut = zIn;
  28422. unsigned char *zStart = zIn;
  28423. u32 c;
  28424. while( zIn[0] && zOut<=zIn ){
  28425. c = sqlite3Utf8Read((const u8**)&zIn);
  28426. if( c!=0xfffd ){
  28427. WRITE_UTF8(zOut, c);
  28428. }
  28429. }
  28430. *zOut = 0;
  28431. return (int)(zOut - zStart);
  28432. }
  28433. #endif
  28434. #ifndef SQLITE_OMIT_UTF16
  28435. /*
  28436. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  28437. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  28438. ** be freed by the calling function.
  28439. **
  28440. ** NULL is returned if there is an allocation error.
  28441. */
  28442. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  28443. Mem m;
  28444. memset(&m, 0, sizeof(m));
  28445. m.db = db;
  28446. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  28447. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  28448. if( db->mallocFailed ){
  28449. sqlite3VdbeMemRelease(&m);
  28450. m.z = 0;
  28451. }
  28452. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  28453. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  28454. assert( m.z || db->mallocFailed );
  28455. return m.z;
  28456. }
  28457. /*
  28458. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  28459. ** Return the number of bytes in the first nChar unicode characters
  28460. ** in pZ. nChar must be non-negative.
  28461. */
  28462. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  28463. int c;
  28464. unsigned char const *z = zIn;
  28465. int n = 0;
  28466. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  28467. while( n<nChar ){
  28468. READ_UTF16BE(z, 1, c);
  28469. n++;
  28470. }
  28471. }else{
  28472. while( n<nChar ){
  28473. READ_UTF16LE(z, 1, c);
  28474. n++;
  28475. }
  28476. }
  28477. return (int)(z-(unsigned char const *)zIn);
  28478. }
  28479. #if defined(SQLITE_TEST)
  28480. /*
  28481. ** This routine is called from the TCL test function "translate_selftest".
  28482. ** It checks that the primitives for serializing and deserializing
  28483. ** characters in each encoding are inverses of each other.
  28484. */
  28485. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  28486. unsigned int i, t;
  28487. unsigned char zBuf[20];
  28488. unsigned char *z;
  28489. int n;
  28490. unsigned int c;
  28491. for(i=0; i<0x00110000; i++){
  28492. z = zBuf;
  28493. WRITE_UTF8(z, i);
  28494. n = (int)(z-zBuf);
  28495. assert( n>0 && n<=4 );
  28496. z[0] = 0;
  28497. z = zBuf;
  28498. c = sqlite3Utf8Read((const u8**)&z);
  28499. t = i;
  28500. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  28501. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  28502. assert( c==t );
  28503. assert( (z-zBuf)==n );
  28504. }
  28505. for(i=0; i<0x00110000; i++){
  28506. if( i>=0xD800 && i<0xE000 ) continue;
  28507. z = zBuf;
  28508. WRITE_UTF16LE(z, i);
  28509. n = (int)(z-zBuf);
  28510. assert( n>0 && n<=4 );
  28511. z[0] = 0;
  28512. z = zBuf;
  28513. READ_UTF16LE(z, 1, c);
  28514. assert( c==i );
  28515. assert( (z-zBuf)==n );
  28516. }
  28517. for(i=0; i<0x00110000; i++){
  28518. if( i>=0xD800 && i<0xE000 ) continue;
  28519. z = zBuf;
  28520. WRITE_UTF16BE(z, i);
  28521. n = (int)(z-zBuf);
  28522. assert( n>0 && n<=4 );
  28523. z[0] = 0;
  28524. z = zBuf;
  28525. READ_UTF16BE(z, 1, c);
  28526. assert( c==i );
  28527. assert( (z-zBuf)==n );
  28528. }
  28529. }
  28530. #endif /* SQLITE_TEST */
  28531. #endif /* SQLITE_OMIT_UTF16 */
  28532. /************** End of utf.c *************************************************/
  28533. /************** Begin file util.c ********************************************/
  28534. /*
  28535. ** 2001 September 15
  28536. **
  28537. ** The author disclaims copyright to this source code. In place of
  28538. ** a legal notice, here is a blessing:
  28539. **
  28540. ** May you do good and not evil.
  28541. ** May you find forgiveness for yourself and forgive others.
  28542. ** May you share freely, never taking more than you give.
  28543. **
  28544. *************************************************************************
  28545. ** Utility functions used throughout sqlite.
  28546. **
  28547. ** This file contains functions for allocating memory, comparing
  28548. ** strings, and stuff like that.
  28549. **
  28550. */
  28551. /* #include "sqliteInt.h" */
  28552. /* #include <stdarg.h> */
  28553. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  28554. # include <math.h>
  28555. #endif
  28556. /*
  28557. ** Routine needed to support the testcase() macro.
  28558. */
  28559. #ifdef SQLITE_COVERAGE_TEST
  28560. SQLITE_PRIVATE void sqlite3Coverage(int x){
  28561. static unsigned dummy = 0;
  28562. dummy += (unsigned)x;
  28563. }
  28564. #endif
  28565. /*
  28566. ** Give a callback to the test harness that can be used to simulate faults
  28567. ** in places where it is difficult or expensive to do so purely by means
  28568. ** of inputs.
  28569. **
  28570. ** The intent of the integer argument is to let the fault simulator know
  28571. ** which of multiple sqlite3FaultSim() calls has been hit.
  28572. **
  28573. ** Return whatever integer value the test callback returns, or return
  28574. ** SQLITE_OK if no test callback is installed.
  28575. */
  28576. #ifndef SQLITE_UNTESTABLE
  28577. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  28578. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  28579. return xCallback ? xCallback(iTest) : SQLITE_OK;
  28580. }
  28581. #endif
  28582. #ifndef SQLITE_OMIT_FLOATING_POINT
  28583. /*
  28584. ** Return true if the floating point value is Not a Number (NaN).
  28585. **
  28586. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  28587. ** Otherwise, we have our own implementation that works on most systems.
  28588. */
  28589. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  28590. int rc; /* The value return */
  28591. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  28592. /*
  28593. ** Systems that support the isnan() library function should probably
  28594. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  28595. ** found that many systems do not have a working isnan() function so
  28596. ** this implementation is provided as an alternative.
  28597. **
  28598. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  28599. ** On the other hand, the use of -ffast-math comes with the following
  28600. ** warning:
  28601. **
  28602. ** This option [-ffast-math] should never be turned on by any
  28603. ** -O option since it can result in incorrect output for programs
  28604. ** which depend on an exact implementation of IEEE or ISO
  28605. ** rules/specifications for math functions.
  28606. **
  28607. ** Under MSVC, this NaN test may fail if compiled with a floating-
  28608. ** point precision mode other than /fp:precise. From the MSDN
  28609. ** documentation:
  28610. **
  28611. ** The compiler [with /fp:precise] will properly handle comparisons
  28612. ** involving NaN. For example, x != x evaluates to true if x is NaN
  28613. ** ...
  28614. */
  28615. #ifdef __FAST_MATH__
  28616. # error SQLite will not work correctly with the -ffast-math option of GCC.
  28617. #endif
  28618. volatile double y = x;
  28619. volatile double z = y;
  28620. rc = (y!=z);
  28621. #else /* if HAVE_ISNAN */
  28622. rc = isnan(x);
  28623. #endif /* HAVE_ISNAN */
  28624. testcase( rc );
  28625. return rc;
  28626. }
  28627. #endif /* SQLITE_OMIT_FLOATING_POINT */
  28628. /*
  28629. ** Compute a string length that is limited to what can be stored in
  28630. ** lower 30 bits of a 32-bit signed integer.
  28631. **
  28632. ** The value returned will never be negative. Nor will it ever be greater
  28633. ** than the actual length of the string. For very long strings (greater
  28634. ** than 1GiB) the value returned might be less than the true string length.
  28635. */
  28636. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  28637. if( z==0 ) return 0;
  28638. return 0x3fffffff & (int)strlen(z);
  28639. }
  28640. /*
  28641. ** Return the declared type of a column. Or return zDflt if the column
  28642. ** has no declared type.
  28643. **
  28644. ** The column type is an extra string stored after the zero-terminator on
  28645. ** the column name if and only if the COLFLAG_HASTYPE flag is set.
  28646. */
  28647. SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
  28648. if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
  28649. return pCol->zName + strlen(pCol->zName) + 1;
  28650. }
  28651. /*
  28652. ** Helper function for sqlite3Error() - called rarely. Broken out into
  28653. ** a separate routine to avoid unnecessary register saves on entry to
  28654. ** sqlite3Error().
  28655. */
  28656. static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
  28657. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  28658. sqlite3SystemError(db, err_code);
  28659. }
  28660. /*
  28661. ** Set the current error code to err_code and clear any prior error message.
  28662. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
  28663. ** that would be appropriate.
  28664. */
  28665. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  28666. assert( db!=0 );
  28667. db->errCode = err_code;
  28668. if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
  28669. }
  28670. /*
  28671. ** Load the sqlite3.iSysErrno field if that is an appropriate thing
  28672. ** to do based on the SQLite error code in rc.
  28673. */
  28674. SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
  28675. if( rc==SQLITE_IOERR_NOMEM ) return;
  28676. rc &= 0xff;
  28677. if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
  28678. db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
  28679. }
  28680. }
  28681. /*
  28682. ** Set the most recent error code and error string for the sqlite
  28683. ** handle "db". The error code is set to "err_code".
  28684. **
  28685. ** If it is not NULL, string zFormat specifies the format of the
  28686. ** error string in the style of the printf functions: The following
  28687. ** format characters are allowed:
  28688. **
  28689. ** %s Insert a string
  28690. ** %z A string that should be freed after use
  28691. ** %d Insert an integer
  28692. ** %T Insert a token
  28693. ** %S Insert the first element of a SrcList
  28694. **
  28695. ** zFormat and any string tokens that follow it are assumed to be
  28696. ** encoded in UTF-8.
  28697. **
  28698. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  28699. ** should be called with err_code set to SQLITE_OK and zFormat set
  28700. ** to NULL.
  28701. */
  28702. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  28703. assert( db!=0 );
  28704. db->errCode = err_code;
  28705. sqlite3SystemError(db, err_code);
  28706. if( zFormat==0 ){
  28707. sqlite3Error(db, err_code);
  28708. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  28709. char *z;
  28710. va_list ap;
  28711. va_start(ap, zFormat);
  28712. z = sqlite3VMPrintf(db, zFormat, ap);
  28713. va_end(ap);
  28714. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  28715. }
  28716. }
  28717. /*
  28718. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  28719. ** The following formatting characters are allowed:
  28720. **
  28721. ** %s Insert a string
  28722. ** %z A string that should be freed after use
  28723. ** %d Insert an integer
  28724. ** %T Insert a token
  28725. ** %S Insert the first element of a SrcList
  28726. **
  28727. ** This function should be used to report any error that occurs while
  28728. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  28729. ** last thing the sqlite3_prepare() function does is copy the error
  28730. ** stored by this function into the database handle using sqlite3Error().
  28731. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  28732. ** during statement execution (sqlite3_step() etc.).
  28733. */
  28734. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  28735. char *zMsg;
  28736. va_list ap;
  28737. sqlite3 *db = pParse->db;
  28738. va_start(ap, zFormat);
  28739. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  28740. va_end(ap);
  28741. if( db->suppressErr ){
  28742. sqlite3DbFree(db, zMsg);
  28743. }else{
  28744. pParse->nErr++;
  28745. sqlite3DbFree(db, pParse->zErrMsg);
  28746. pParse->zErrMsg = zMsg;
  28747. pParse->rc = SQLITE_ERROR;
  28748. }
  28749. }
  28750. /*
  28751. ** Convert an SQL-style quoted string into a normal string by removing
  28752. ** the quote characters. The conversion is done in-place. If the
  28753. ** input does not begin with a quote character, then this routine
  28754. ** is a no-op.
  28755. **
  28756. ** The input string must be zero-terminated. A new zero-terminator
  28757. ** is added to the dequoted string.
  28758. **
  28759. ** The return value is -1 if no dequoting occurs or the length of the
  28760. ** dequoted string, exclusive of the zero terminator, if dequoting does
  28761. ** occur.
  28762. **
  28763. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  28764. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  28765. ** "a-b-c".
  28766. */
  28767. SQLITE_PRIVATE void sqlite3Dequote(char *z){
  28768. char quote;
  28769. int i, j;
  28770. if( z==0 ) return;
  28771. quote = z[0];
  28772. if( !sqlite3Isquote(quote) ) return;
  28773. if( quote=='[' ) quote = ']';
  28774. for(i=1, j=0;; i++){
  28775. assert( z[i] );
  28776. if( z[i]==quote ){
  28777. if( z[i+1]==quote ){
  28778. z[j++] = quote;
  28779. i++;
  28780. }else{
  28781. break;
  28782. }
  28783. }else{
  28784. z[j++] = z[i];
  28785. }
  28786. }
  28787. z[j] = 0;
  28788. }
  28789. /*
  28790. ** Generate a Token object from a string
  28791. */
  28792. SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
  28793. p->z = z;
  28794. p->n = sqlite3Strlen30(z);
  28795. }
  28796. /* Convenient short-hand */
  28797. #define UpperToLower sqlite3UpperToLower
  28798. /*
  28799. ** Some systems have stricmp(). Others have strcasecmp(). Because
  28800. ** there is no consistency, we will define our own.
  28801. **
  28802. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  28803. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  28804. ** the contents of two buffers containing UTF-8 strings in a
  28805. ** case-independent fashion, using the same definition of "case
  28806. ** independence" that SQLite uses internally when comparing identifiers.
  28807. */
  28808. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  28809. if( zLeft==0 ){
  28810. return zRight ? -1 : 0;
  28811. }else if( zRight==0 ){
  28812. return 1;
  28813. }
  28814. return sqlite3StrICmp(zLeft, zRight);
  28815. }
  28816. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  28817. unsigned char *a, *b;
  28818. int c;
  28819. a = (unsigned char *)zLeft;
  28820. b = (unsigned char *)zRight;
  28821. for(;;){
  28822. c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
  28823. if( c || *a==0 ) break;
  28824. a++;
  28825. b++;
  28826. }
  28827. return c;
  28828. }
  28829. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  28830. register unsigned char *a, *b;
  28831. if( zLeft==0 ){
  28832. return zRight ? -1 : 0;
  28833. }else if( zRight==0 ){
  28834. return 1;
  28835. }
  28836. a = (unsigned char *)zLeft;
  28837. b = (unsigned char *)zRight;
  28838. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  28839. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  28840. }
  28841. /*
  28842. ** Compute 10 to the E-th power. Examples: E==1 results in 10.
  28843. ** E==2 results in 100. E==50 results in 1.0e50.
  28844. **
  28845. ** This routine only works for values of E between 1 and 341.
  28846. */
  28847. static LONGDOUBLE_TYPE sqlite3Pow10(int E){
  28848. #if defined(_MSC_VER)
  28849. static const LONGDOUBLE_TYPE x[] = {
  28850. 1.0e+001,
  28851. 1.0e+002,
  28852. 1.0e+004,
  28853. 1.0e+008,
  28854. 1.0e+016,
  28855. 1.0e+032,
  28856. 1.0e+064,
  28857. 1.0e+128,
  28858. 1.0e+256
  28859. };
  28860. LONGDOUBLE_TYPE r = 1.0;
  28861. int i;
  28862. assert( E>=0 && E<=307 );
  28863. for(i=0; E!=0; i++, E >>=1){
  28864. if( E & 1 ) r *= x[i];
  28865. }
  28866. return r;
  28867. #else
  28868. LONGDOUBLE_TYPE x = 10.0;
  28869. LONGDOUBLE_TYPE r = 1.0;
  28870. while(1){
  28871. if( E & 1 ) r *= x;
  28872. E >>= 1;
  28873. if( E==0 ) break;
  28874. x *= x;
  28875. }
  28876. return r;
  28877. #endif
  28878. }
  28879. /*
  28880. ** The string z[] is an text representation of a real number.
  28881. ** Convert this string to a double and write it into *pResult.
  28882. **
  28883. ** The string z[] is length bytes in length (bytes, not characters) and
  28884. ** uses the encoding enc. The string is not necessarily zero-terminated.
  28885. **
  28886. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  28887. ** if the string is empty or contains extraneous text. Valid numbers
  28888. ** are in one of these formats:
  28889. **
  28890. ** [+-]digits[E[+-]digits]
  28891. ** [+-]digits.[digits][E[+-]digits]
  28892. ** [+-].digits[E[+-]digits]
  28893. **
  28894. ** Leading and trailing whitespace is ignored for the purpose of determining
  28895. ** validity.
  28896. **
  28897. ** If some prefix of the input string is a valid number, this routine
  28898. ** returns FALSE but it still converts the prefix and writes the result
  28899. ** into *pResult.
  28900. */
  28901. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  28902. #ifndef SQLITE_OMIT_FLOATING_POINT
  28903. int incr;
  28904. const char *zEnd = z + length;
  28905. /* sign * significand * (10 ^ (esign * exponent)) */
  28906. int sign = 1; /* sign of significand */
  28907. i64 s = 0; /* significand */
  28908. int d = 0; /* adjust exponent for shifting decimal point */
  28909. int esign = 1; /* sign of exponent */
  28910. int e = 0; /* exponent */
  28911. int eValid = 1; /* True exponent is either not used or is well-formed */
  28912. double result;
  28913. int nDigits = 0;
  28914. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  28915. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  28916. *pResult = 0.0; /* Default return value, in case of an error */
  28917. if( enc==SQLITE_UTF8 ){
  28918. incr = 1;
  28919. }else{
  28920. int i;
  28921. incr = 2;
  28922. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  28923. for(i=3-enc; i<length && z[i]==0; i+=2){}
  28924. nonNum = i<length;
  28925. zEnd = &z[i^1];
  28926. z += (enc&1);
  28927. }
  28928. /* skip leading spaces */
  28929. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  28930. if( z>=zEnd ) return 0;
  28931. /* get sign of significand */
  28932. if( *z=='-' ){
  28933. sign = -1;
  28934. z+=incr;
  28935. }else if( *z=='+' ){
  28936. z+=incr;
  28937. }
  28938. /* copy max significant digits to significand */
  28939. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  28940. s = s*10 + (*z - '0');
  28941. z+=incr; nDigits++;
  28942. }
  28943. /* skip non-significant significand digits
  28944. ** (increase exponent by d to shift decimal left) */
  28945. while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; nDigits++; d++; }
  28946. if( z>=zEnd ) goto do_atof_calc;
  28947. /* if decimal point is present */
  28948. if( *z=='.' ){
  28949. z+=incr;
  28950. /* copy digits from after decimal to significand
  28951. ** (decrease exponent by d to shift decimal right) */
  28952. while( z<zEnd && sqlite3Isdigit(*z) ){
  28953. if( s<((LARGEST_INT64-9)/10) ){
  28954. s = s*10 + (*z - '0');
  28955. d--;
  28956. }
  28957. z+=incr; nDigits++;
  28958. }
  28959. }
  28960. if( z>=zEnd ) goto do_atof_calc;
  28961. /* if exponent is present */
  28962. if( *z=='e' || *z=='E' ){
  28963. z+=incr;
  28964. eValid = 0;
  28965. /* This branch is needed to avoid a (harmless) buffer overread. The
  28966. ** special comment alerts the mutation tester that the correct answer
  28967. ** is obtained even if the branch is omitted */
  28968. if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
  28969. /* get sign of exponent */
  28970. if( *z=='-' ){
  28971. esign = -1;
  28972. z+=incr;
  28973. }else if( *z=='+' ){
  28974. z+=incr;
  28975. }
  28976. /* copy digits to exponent */
  28977. while( z<zEnd && sqlite3Isdigit(*z) ){
  28978. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  28979. z+=incr;
  28980. eValid = 1;
  28981. }
  28982. }
  28983. /* skip trailing spaces */
  28984. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  28985. do_atof_calc:
  28986. /* adjust exponent by d, and update sign */
  28987. e = (e*esign) + d;
  28988. if( e<0 ) {
  28989. esign = -1;
  28990. e *= -1;
  28991. } else {
  28992. esign = 1;
  28993. }
  28994. if( s==0 ) {
  28995. /* In the IEEE 754 standard, zero is signed. */
  28996. result = sign<0 ? -(double)0 : (double)0;
  28997. } else {
  28998. /* Attempt to reduce exponent.
  28999. **
  29000. ** Branches that are not required for the correct answer but which only
  29001. ** help to obtain the correct answer faster are marked with special
  29002. ** comments, as a hint to the mutation tester.
  29003. */
  29004. while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
  29005. if( esign>0 ){
  29006. if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
  29007. s *= 10;
  29008. }else{
  29009. if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
  29010. s /= 10;
  29011. }
  29012. e--;
  29013. }
  29014. /* adjust the sign of significand */
  29015. s = sign<0 ? -s : s;
  29016. if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
  29017. result = (double)s;
  29018. }else{
  29019. /* attempt to handle extremely small/large numbers better */
  29020. if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
  29021. if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
  29022. LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
  29023. if( esign<0 ){
  29024. result = s / scale;
  29025. result /= 1.0e+308;
  29026. }else{
  29027. result = s * scale;
  29028. result *= 1.0e+308;
  29029. }
  29030. }else{ assert( e>=342 );
  29031. if( esign<0 ){
  29032. result = 0.0*s;
  29033. }else{
  29034. #ifdef INFINITY
  29035. result = INFINITY*s;
  29036. #else
  29037. result = 1e308*1e308*s; /* Infinity */
  29038. #endif
  29039. }
  29040. }
  29041. }else{
  29042. LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
  29043. if( esign<0 ){
  29044. result = s / scale;
  29045. }else{
  29046. result = s * scale;
  29047. }
  29048. }
  29049. }
  29050. }
  29051. /* store the result */
  29052. *pResult = result;
  29053. /* return true if number and no extra non-whitespace chracters after */
  29054. return z==zEnd && nDigits>0 && eValid && nonNum==0;
  29055. #else
  29056. return !sqlite3Atoi64(z, pResult, length, enc);
  29057. #endif /* SQLITE_OMIT_FLOATING_POINT */
  29058. }
  29059. /*
  29060. ** Compare the 19-character string zNum against the text representation
  29061. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  29062. ** if zNum is less than, equal to, or greater than the string.
  29063. ** Note that zNum must contain exactly 19 characters.
  29064. **
  29065. ** Unlike memcmp() this routine is guaranteed to return the difference
  29066. ** in the values of the last digit if the only difference is in the
  29067. ** last digit. So, for example,
  29068. **
  29069. ** compare2pow63("9223372036854775800", 1)
  29070. **
  29071. ** will return -8.
  29072. */
  29073. static int compare2pow63(const char *zNum, int incr){
  29074. int c = 0;
  29075. int i;
  29076. /* 012345678901234567 */
  29077. const char *pow63 = "922337203685477580";
  29078. for(i=0; c==0 && i<18; i++){
  29079. c = (zNum[i*incr]-pow63[i])*10;
  29080. }
  29081. if( c==0 ){
  29082. c = zNum[18*incr] - '8';
  29083. testcase( c==(-1) );
  29084. testcase( c==0 );
  29085. testcase( c==(+1) );
  29086. }
  29087. return c;
  29088. }
  29089. /*
  29090. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  29091. ** routine does *not* accept hexadecimal notation.
  29092. **
  29093. ** Returns:
  29094. **
  29095. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  29096. ** 1 Excess non-space text after the integer value
  29097. ** 2 Integer too large for a 64-bit signed integer or is malformed
  29098. ** 3 Special case of 9223372036854775808
  29099. **
  29100. ** length is the number of bytes in the string (bytes, not characters).
  29101. ** The string is not necessarily zero-terminated. The encoding is
  29102. ** given by enc.
  29103. */
  29104. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  29105. int incr;
  29106. u64 u = 0;
  29107. int neg = 0; /* assume positive */
  29108. int i;
  29109. int c = 0;
  29110. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  29111. int rc; /* Baseline return code */
  29112. const char *zStart;
  29113. const char *zEnd = zNum + length;
  29114. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  29115. if( enc==SQLITE_UTF8 ){
  29116. incr = 1;
  29117. }else{
  29118. incr = 2;
  29119. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  29120. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  29121. nonNum = i<length;
  29122. zEnd = &zNum[i^1];
  29123. zNum += (enc&1);
  29124. }
  29125. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  29126. if( zNum<zEnd ){
  29127. if( *zNum=='-' ){
  29128. neg = 1;
  29129. zNum+=incr;
  29130. }else if( *zNum=='+' ){
  29131. zNum+=incr;
  29132. }
  29133. }
  29134. zStart = zNum;
  29135. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  29136. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  29137. u = u*10 + c - '0';
  29138. }
  29139. testcase( i==18*incr );
  29140. testcase( i==19*incr );
  29141. testcase( i==20*incr );
  29142. if( u>LARGEST_INT64 ){
  29143. /* This test and assignment is needed only to suppress UB warnings
  29144. ** from clang and -fsanitize=undefined. This test and assignment make
  29145. ** the code a little larger and slower, and no harm comes from omitting
  29146. ** them, but we must appaise the undefined-behavior pharisees. */
  29147. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  29148. }else if( neg ){
  29149. *pNum = -(i64)u;
  29150. }else{
  29151. *pNum = (i64)u;
  29152. }
  29153. rc = 0;
  29154. if( (i==0 && zStart==zNum) /* No digits */
  29155. || nonNum /* UTF16 with high-order bytes non-zero */
  29156. ){
  29157. rc = 1;
  29158. }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */
  29159. int jj = i;
  29160. do{
  29161. if( !sqlite3Isspace(zNum[jj]) ){
  29162. rc = 1; /* Extra non-space text after the integer */
  29163. break;
  29164. }
  29165. jj += incr;
  29166. }while( &zNum[jj]<zEnd );
  29167. }
  29168. if( i<19*incr ){
  29169. /* Less than 19 digits, so we know that it fits in 64 bits */
  29170. assert( u<=LARGEST_INT64 );
  29171. return rc;
  29172. }else{
  29173. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  29174. c = i>19*incr ? 1 : compare2pow63(zNum, incr);
  29175. if( c<0 ){
  29176. /* zNum is less than 9223372036854775808 so it fits */
  29177. assert( u<=LARGEST_INT64 );
  29178. return rc;
  29179. }else{
  29180. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  29181. if( c>0 ){
  29182. /* zNum is greater than 9223372036854775808 so it overflows */
  29183. return 2;
  29184. }else{
  29185. /* zNum is exactly 9223372036854775808. Fits if negative. The
  29186. ** special case 2 overflow if positive */
  29187. assert( u-1==LARGEST_INT64 );
  29188. return neg ? rc : 3;
  29189. }
  29190. }
  29191. }
  29192. }
  29193. /*
  29194. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  29195. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  29196. ** whereas sqlite3Atoi64() does not.
  29197. **
  29198. ** Returns:
  29199. **
  29200. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  29201. ** 1 Excess text after the integer value
  29202. ** 2 Integer too large for a 64-bit signed integer or is malformed
  29203. ** 3 Special case of 9223372036854775808
  29204. */
  29205. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  29206. #ifndef SQLITE_OMIT_HEX_INTEGER
  29207. if( z[0]=='0'
  29208. && (z[1]=='x' || z[1]=='X')
  29209. ){
  29210. u64 u = 0;
  29211. int i, k;
  29212. for(i=2; z[i]=='0'; i++){}
  29213. for(k=i; sqlite3Isxdigit(z[k]); k++){
  29214. u = u*16 + sqlite3HexToInt(z[k]);
  29215. }
  29216. memcpy(pOut, &u, 8);
  29217. return (z[k]==0 && k-i<=16) ? 0 : 2;
  29218. }else
  29219. #endif /* SQLITE_OMIT_HEX_INTEGER */
  29220. {
  29221. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  29222. }
  29223. }
  29224. /*
  29225. ** If zNum represents an integer that will fit in 32-bits, then set
  29226. ** *pValue to that integer and return true. Otherwise return false.
  29227. **
  29228. ** This routine accepts both decimal and hexadecimal notation for integers.
  29229. **
  29230. ** Any non-numeric characters that following zNum are ignored.
  29231. ** This is different from sqlite3Atoi64() which requires the
  29232. ** input number to be zero-terminated.
  29233. */
  29234. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  29235. sqlite_int64 v = 0;
  29236. int i, c;
  29237. int neg = 0;
  29238. if( zNum[0]=='-' ){
  29239. neg = 1;
  29240. zNum++;
  29241. }else if( zNum[0]=='+' ){
  29242. zNum++;
  29243. }
  29244. #ifndef SQLITE_OMIT_HEX_INTEGER
  29245. else if( zNum[0]=='0'
  29246. && (zNum[1]=='x' || zNum[1]=='X')
  29247. && sqlite3Isxdigit(zNum[2])
  29248. ){
  29249. u32 u = 0;
  29250. zNum += 2;
  29251. while( zNum[0]=='0' ) zNum++;
  29252. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  29253. u = u*16 + sqlite3HexToInt(zNum[i]);
  29254. }
  29255. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  29256. memcpy(pValue, &u, 4);
  29257. return 1;
  29258. }else{
  29259. return 0;
  29260. }
  29261. }
  29262. #endif
  29263. if( !sqlite3Isdigit(zNum[0]) ) return 0;
  29264. while( zNum[0]=='0' ) zNum++;
  29265. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  29266. v = v*10 + c;
  29267. }
  29268. /* The longest decimal representation of a 32 bit integer is 10 digits:
  29269. **
  29270. ** 1234567890
  29271. ** 2^31 -> 2147483648
  29272. */
  29273. testcase( i==10 );
  29274. if( i>10 ){
  29275. return 0;
  29276. }
  29277. testcase( v-neg==2147483647 );
  29278. if( v-neg>2147483647 ){
  29279. return 0;
  29280. }
  29281. if( neg ){
  29282. v = -v;
  29283. }
  29284. *pValue = (int)v;
  29285. return 1;
  29286. }
  29287. /*
  29288. ** Return a 32-bit integer value extracted from a string. If the
  29289. ** string is not an integer, just return 0.
  29290. */
  29291. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  29292. int x = 0;
  29293. if( z ) sqlite3GetInt32(z, &x);
  29294. return x;
  29295. }
  29296. /*
  29297. ** The variable-length integer encoding is as follows:
  29298. **
  29299. ** KEY:
  29300. ** A = 0xxxxxxx 7 bits of data and one flag bit
  29301. ** B = 1xxxxxxx 7 bits of data and one flag bit
  29302. ** C = xxxxxxxx 8 bits of data
  29303. **
  29304. ** 7 bits - A
  29305. ** 14 bits - BA
  29306. ** 21 bits - BBA
  29307. ** 28 bits - BBBA
  29308. ** 35 bits - BBBBA
  29309. ** 42 bits - BBBBBA
  29310. ** 49 bits - BBBBBBA
  29311. ** 56 bits - BBBBBBBA
  29312. ** 64 bits - BBBBBBBBC
  29313. */
  29314. /*
  29315. ** Write a 64-bit variable-length integer to memory starting at p[0].
  29316. ** The length of data write will be between 1 and 9 bytes. The number
  29317. ** of bytes written is returned.
  29318. **
  29319. ** A variable-length integer consists of the lower 7 bits of each byte
  29320. ** for all bytes that have the 8th bit set and one byte with the 8th
  29321. ** bit clear. Except, if we get to the 9th byte, it stores the full
  29322. ** 8 bits and is the last byte.
  29323. */
  29324. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  29325. int i, j, n;
  29326. u8 buf[10];
  29327. if( v & (((u64)0xff000000)<<32) ){
  29328. p[8] = (u8)v;
  29329. v >>= 8;
  29330. for(i=7; i>=0; i--){
  29331. p[i] = (u8)((v & 0x7f) | 0x80);
  29332. v >>= 7;
  29333. }
  29334. return 9;
  29335. }
  29336. n = 0;
  29337. do{
  29338. buf[n++] = (u8)((v & 0x7f) | 0x80);
  29339. v >>= 7;
  29340. }while( v!=0 );
  29341. buf[0] &= 0x7f;
  29342. assert( n<=9 );
  29343. for(i=0, j=n-1; j>=0; j--, i++){
  29344. p[i] = buf[j];
  29345. }
  29346. return n;
  29347. }
  29348. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  29349. if( v<=0x7f ){
  29350. p[0] = v&0x7f;
  29351. return 1;
  29352. }
  29353. if( v<=0x3fff ){
  29354. p[0] = ((v>>7)&0x7f)|0x80;
  29355. p[1] = v&0x7f;
  29356. return 2;
  29357. }
  29358. return putVarint64(p,v);
  29359. }
  29360. /*
  29361. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  29362. ** are defined here rather than simply putting the constant expressions
  29363. ** inline in order to work around bugs in the RVT compiler.
  29364. **
  29365. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  29366. **
  29367. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  29368. */
  29369. #define SLOT_2_0 0x001fc07f
  29370. #define SLOT_4_2_0 0xf01fc07f
  29371. /*
  29372. ** Read a 64-bit variable-length integer from memory starting at p[0].
  29373. ** Return the number of bytes read. The value is stored in *v.
  29374. */
  29375. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  29376. u32 a,b,s;
  29377. a = *p;
  29378. /* a: p0 (unmasked) */
  29379. if (!(a&0x80))
  29380. {
  29381. *v = a;
  29382. return 1;
  29383. }
  29384. p++;
  29385. b = *p;
  29386. /* b: p1 (unmasked) */
  29387. if (!(b&0x80))
  29388. {
  29389. a &= 0x7f;
  29390. a = a<<7;
  29391. a |= b;
  29392. *v = a;
  29393. return 2;
  29394. }
  29395. /* Verify that constants are precomputed correctly */
  29396. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  29397. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  29398. p++;
  29399. a = a<<14;
  29400. a |= *p;
  29401. /* a: p0<<14 | p2 (unmasked) */
  29402. if (!(a&0x80))
  29403. {
  29404. a &= SLOT_2_0;
  29405. b &= 0x7f;
  29406. b = b<<7;
  29407. a |= b;
  29408. *v = a;
  29409. return 3;
  29410. }
  29411. /* CSE1 from below */
  29412. a &= SLOT_2_0;
  29413. p++;
  29414. b = b<<14;
  29415. b |= *p;
  29416. /* b: p1<<14 | p3 (unmasked) */
  29417. if (!(b&0x80))
  29418. {
  29419. b &= SLOT_2_0;
  29420. /* moved CSE1 up */
  29421. /* a &= (0x7f<<14)|(0x7f); */
  29422. a = a<<7;
  29423. a |= b;
  29424. *v = a;
  29425. return 4;
  29426. }
  29427. /* a: p0<<14 | p2 (masked) */
  29428. /* b: p1<<14 | p3 (unmasked) */
  29429. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  29430. /* moved CSE1 up */
  29431. /* a &= (0x7f<<14)|(0x7f); */
  29432. b &= SLOT_2_0;
  29433. s = a;
  29434. /* s: p0<<14 | p2 (masked) */
  29435. p++;
  29436. a = a<<14;
  29437. a |= *p;
  29438. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  29439. if (!(a&0x80))
  29440. {
  29441. /* we can skip these cause they were (effectively) done above
  29442. ** while calculating s */
  29443. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  29444. /* b &= (0x7f<<14)|(0x7f); */
  29445. b = b<<7;
  29446. a |= b;
  29447. s = s>>18;
  29448. *v = ((u64)s)<<32 | a;
  29449. return 5;
  29450. }
  29451. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  29452. s = s<<7;
  29453. s |= b;
  29454. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  29455. p++;
  29456. b = b<<14;
  29457. b |= *p;
  29458. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  29459. if (!(b&0x80))
  29460. {
  29461. /* we can skip this cause it was (effectively) done above in calc'ing s */
  29462. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  29463. a &= SLOT_2_0;
  29464. a = a<<7;
  29465. a |= b;
  29466. s = s>>18;
  29467. *v = ((u64)s)<<32 | a;
  29468. return 6;
  29469. }
  29470. p++;
  29471. a = a<<14;
  29472. a |= *p;
  29473. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  29474. if (!(a&0x80))
  29475. {
  29476. a &= SLOT_4_2_0;
  29477. b &= SLOT_2_0;
  29478. b = b<<7;
  29479. a |= b;
  29480. s = s>>11;
  29481. *v = ((u64)s)<<32 | a;
  29482. return 7;
  29483. }
  29484. /* CSE2 from below */
  29485. a &= SLOT_2_0;
  29486. p++;
  29487. b = b<<14;
  29488. b |= *p;
  29489. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  29490. if (!(b&0x80))
  29491. {
  29492. b &= SLOT_4_2_0;
  29493. /* moved CSE2 up */
  29494. /* a &= (0x7f<<14)|(0x7f); */
  29495. a = a<<7;
  29496. a |= b;
  29497. s = s>>4;
  29498. *v = ((u64)s)<<32 | a;
  29499. return 8;
  29500. }
  29501. p++;
  29502. a = a<<15;
  29503. a |= *p;
  29504. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  29505. /* moved CSE2 up */
  29506. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  29507. b &= SLOT_2_0;
  29508. b = b<<8;
  29509. a |= b;
  29510. s = s<<4;
  29511. b = p[-4];
  29512. b &= 0x7f;
  29513. b = b>>3;
  29514. s |= b;
  29515. *v = ((u64)s)<<32 | a;
  29516. return 9;
  29517. }
  29518. /*
  29519. ** Read a 32-bit variable-length integer from memory starting at p[0].
  29520. ** Return the number of bytes read. The value is stored in *v.
  29521. **
  29522. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  29523. ** integer, then set *v to 0xffffffff.
  29524. **
  29525. ** A MACRO version, getVarint32, is provided which inlines the
  29526. ** single-byte case. All code should use the MACRO version as
  29527. ** this function assumes the single-byte case has already been handled.
  29528. */
  29529. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  29530. u32 a,b;
  29531. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  29532. ** by the getVarin32() macro */
  29533. a = *p;
  29534. /* a: p0 (unmasked) */
  29535. #ifndef getVarint32
  29536. if (!(a&0x80))
  29537. {
  29538. /* Values between 0 and 127 */
  29539. *v = a;
  29540. return 1;
  29541. }
  29542. #endif
  29543. /* The 2-byte case */
  29544. p++;
  29545. b = *p;
  29546. /* b: p1 (unmasked) */
  29547. if (!(b&0x80))
  29548. {
  29549. /* Values between 128 and 16383 */
  29550. a &= 0x7f;
  29551. a = a<<7;
  29552. *v = a | b;
  29553. return 2;
  29554. }
  29555. /* The 3-byte case */
  29556. p++;
  29557. a = a<<14;
  29558. a |= *p;
  29559. /* a: p0<<14 | p2 (unmasked) */
  29560. if (!(a&0x80))
  29561. {
  29562. /* Values between 16384 and 2097151 */
  29563. a &= (0x7f<<14)|(0x7f);
  29564. b &= 0x7f;
  29565. b = b<<7;
  29566. *v = a | b;
  29567. return 3;
  29568. }
  29569. /* A 32-bit varint is used to store size information in btrees.
  29570. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  29571. ** A 3-byte varint is sufficient, for example, to record the size
  29572. ** of a 1048569-byte BLOB or string.
  29573. **
  29574. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  29575. ** rare larger cases can be handled by the slower 64-bit varint
  29576. ** routine.
  29577. */
  29578. #if 1
  29579. {
  29580. u64 v64;
  29581. u8 n;
  29582. p -= 2;
  29583. n = sqlite3GetVarint(p, &v64);
  29584. assert( n>3 && n<=9 );
  29585. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  29586. *v = 0xffffffff;
  29587. }else{
  29588. *v = (u32)v64;
  29589. }
  29590. return n;
  29591. }
  29592. #else
  29593. /* For following code (kept for historical record only) shows an
  29594. ** unrolling for the 3- and 4-byte varint cases. This code is
  29595. ** slightly faster, but it is also larger and much harder to test.
  29596. */
  29597. p++;
  29598. b = b<<14;
  29599. b |= *p;
  29600. /* b: p1<<14 | p3 (unmasked) */
  29601. if (!(b&0x80))
  29602. {
  29603. /* Values between 2097152 and 268435455 */
  29604. b &= (0x7f<<14)|(0x7f);
  29605. a &= (0x7f<<14)|(0x7f);
  29606. a = a<<7;
  29607. *v = a | b;
  29608. return 4;
  29609. }
  29610. p++;
  29611. a = a<<14;
  29612. a |= *p;
  29613. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  29614. if (!(a&0x80))
  29615. {
  29616. /* Values between 268435456 and 34359738367 */
  29617. a &= SLOT_4_2_0;
  29618. b &= SLOT_4_2_0;
  29619. b = b<<7;
  29620. *v = a | b;
  29621. return 5;
  29622. }
  29623. /* We can only reach this point when reading a corrupt database
  29624. ** file. In that case we are not in any hurry. Use the (relatively
  29625. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  29626. ** value. */
  29627. {
  29628. u64 v64;
  29629. u8 n;
  29630. p -= 4;
  29631. n = sqlite3GetVarint(p, &v64);
  29632. assert( n>5 && n<=9 );
  29633. *v = (u32)v64;
  29634. return n;
  29635. }
  29636. #endif
  29637. }
  29638. /*
  29639. ** Return the number of bytes that will be needed to store the given
  29640. ** 64-bit integer.
  29641. */
  29642. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  29643. int i;
  29644. for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
  29645. return i;
  29646. }
  29647. /*
  29648. ** Read or write a four-byte big-endian integer value.
  29649. */
  29650. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  29651. #if SQLITE_BYTEORDER==4321
  29652. u32 x;
  29653. memcpy(&x,p,4);
  29654. return x;
  29655. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  29656. u32 x;
  29657. memcpy(&x,p,4);
  29658. return __builtin_bswap32(x);
  29659. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  29660. u32 x;
  29661. memcpy(&x,p,4);
  29662. return _byteswap_ulong(x);
  29663. #else
  29664. testcase( p[0]&0x80 );
  29665. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  29666. #endif
  29667. }
  29668. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  29669. #if SQLITE_BYTEORDER==4321
  29670. memcpy(p,&v,4);
  29671. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  29672. u32 x = __builtin_bswap32(v);
  29673. memcpy(p,&x,4);
  29674. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  29675. u32 x = _byteswap_ulong(v);
  29676. memcpy(p,&x,4);
  29677. #else
  29678. p[0] = (u8)(v>>24);
  29679. p[1] = (u8)(v>>16);
  29680. p[2] = (u8)(v>>8);
  29681. p[3] = (u8)v;
  29682. #endif
  29683. }
  29684. /*
  29685. ** Translate a single byte of Hex into an integer.
  29686. ** This routine only works if h really is a valid hexadecimal
  29687. ** character: 0..9a..fA..F
  29688. */
  29689. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  29690. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  29691. #ifdef SQLITE_ASCII
  29692. h += 9*(1&(h>>6));
  29693. #endif
  29694. #ifdef SQLITE_EBCDIC
  29695. h += 9*(1&~(h>>4));
  29696. #endif
  29697. return (u8)(h & 0xf);
  29698. }
  29699. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  29700. /*
  29701. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  29702. ** value. Return a pointer to its binary value. Space to hold the
  29703. ** binary value has been obtained from malloc and must be freed by
  29704. ** the calling routine.
  29705. */
  29706. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  29707. char *zBlob;
  29708. int i;
  29709. zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
  29710. n--;
  29711. if( zBlob ){
  29712. for(i=0; i<n; i+=2){
  29713. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  29714. }
  29715. zBlob[i/2] = 0;
  29716. }
  29717. return zBlob;
  29718. }
  29719. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  29720. /*
  29721. ** Log an error that is an API call on a connection pointer that should
  29722. ** not have been used. The "type" of connection pointer is given as the
  29723. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  29724. */
  29725. static void logBadConnection(const char *zType){
  29726. sqlite3_log(SQLITE_MISUSE,
  29727. "API call with %s database connection pointer",
  29728. zType
  29729. );
  29730. }
  29731. /*
  29732. ** Check to make sure we have a valid db pointer. This test is not
  29733. ** foolproof but it does provide some measure of protection against
  29734. ** misuse of the interface such as passing in db pointers that are
  29735. ** NULL or which have been previously closed. If this routine returns
  29736. ** 1 it means that the db pointer is valid and 0 if it should not be
  29737. ** dereferenced for any reason. The calling function should invoke
  29738. ** SQLITE_MISUSE immediately.
  29739. **
  29740. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  29741. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  29742. ** open properly and is not fit for general use but which can be
  29743. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  29744. */
  29745. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  29746. u32 magic;
  29747. if( db==0 ){
  29748. logBadConnection("NULL");
  29749. return 0;
  29750. }
  29751. magic = db->magic;
  29752. if( magic!=SQLITE_MAGIC_OPEN ){
  29753. if( sqlite3SafetyCheckSickOrOk(db) ){
  29754. testcase( sqlite3GlobalConfig.xLog!=0 );
  29755. logBadConnection("unopened");
  29756. }
  29757. return 0;
  29758. }else{
  29759. return 1;
  29760. }
  29761. }
  29762. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  29763. u32 magic;
  29764. magic = db->magic;
  29765. if( magic!=SQLITE_MAGIC_SICK &&
  29766. magic!=SQLITE_MAGIC_OPEN &&
  29767. magic!=SQLITE_MAGIC_BUSY ){
  29768. testcase( sqlite3GlobalConfig.xLog!=0 );
  29769. logBadConnection("invalid");
  29770. return 0;
  29771. }else{
  29772. return 1;
  29773. }
  29774. }
  29775. /*
  29776. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  29777. ** the other 64-bit signed integer at *pA and store the result in *pA.
  29778. ** Return 0 on success. Or if the operation would have resulted in an
  29779. ** overflow, leave *pA unchanged and return 1.
  29780. */
  29781. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  29782. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  29783. return __builtin_add_overflow(*pA, iB, pA);
  29784. #else
  29785. i64 iA = *pA;
  29786. testcase( iA==0 ); testcase( iA==1 );
  29787. testcase( iB==-1 ); testcase( iB==0 );
  29788. if( iB>=0 ){
  29789. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  29790. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  29791. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  29792. }else{
  29793. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  29794. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  29795. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  29796. }
  29797. *pA += iB;
  29798. return 0;
  29799. #endif
  29800. }
  29801. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  29802. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  29803. return __builtin_sub_overflow(*pA, iB, pA);
  29804. #else
  29805. testcase( iB==SMALLEST_INT64+1 );
  29806. if( iB==SMALLEST_INT64 ){
  29807. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  29808. if( (*pA)>=0 ) return 1;
  29809. *pA -= iB;
  29810. return 0;
  29811. }else{
  29812. return sqlite3AddInt64(pA, -iB);
  29813. }
  29814. #endif
  29815. }
  29816. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  29817. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  29818. return __builtin_mul_overflow(*pA, iB, pA);
  29819. #else
  29820. i64 iA = *pA;
  29821. if( iB>0 ){
  29822. if( iA>LARGEST_INT64/iB ) return 1;
  29823. if( iA<SMALLEST_INT64/iB ) return 1;
  29824. }else if( iB<0 ){
  29825. if( iA>0 ){
  29826. if( iB<SMALLEST_INT64/iA ) return 1;
  29827. }else if( iA<0 ){
  29828. if( iB==SMALLEST_INT64 ) return 1;
  29829. if( iA==SMALLEST_INT64 ) return 1;
  29830. if( -iA>LARGEST_INT64/-iB ) return 1;
  29831. }
  29832. }
  29833. *pA = iA*iB;
  29834. return 0;
  29835. #endif
  29836. }
  29837. /*
  29838. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  29839. ** if the integer has a value of -2147483648, return +2147483647
  29840. */
  29841. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  29842. if( x>=0 ) return x;
  29843. if( x==(int)0x80000000 ) return 0x7fffffff;
  29844. return -x;
  29845. }
  29846. #ifdef SQLITE_ENABLE_8_3_NAMES
  29847. /*
  29848. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  29849. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  29850. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  29851. ** three characters, then shorten the suffix on z[] to be the last three
  29852. ** characters of the original suffix.
  29853. **
  29854. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  29855. ** do the suffix shortening regardless of URI parameter.
  29856. **
  29857. ** Examples:
  29858. **
  29859. ** test.db-journal => test.nal
  29860. ** test.db-wal => test.wal
  29861. ** test.db-shm => test.shm
  29862. ** test.db-mj7f3319fa => test.9fa
  29863. */
  29864. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  29865. #if SQLITE_ENABLE_8_3_NAMES<2
  29866. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  29867. #endif
  29868. {
  29869. int i, sz;
  29870. sz = sqlite3Strlen30(z);
  29871. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  29872. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  29873. }
  29874. }
  29875. #endif
  29876. /*
  29877. ** Find (an approximate) sum of two LogEst values. This computation is
  29878. ** not a simple "+" operator because LogEst is stored as a logarithmic
  29879. ** value.
  29880. **
  29881. */
  29882. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  29883. static const unsigned char x[] = {
  29884. 10, 10, /* 0,1 */
  29885. 9, 9, /* 2,3 */
  29886. 8, 8, /* 4,5 */
  29887. 7, 7, 7, /* 6,7,8 */
  29888. 6, 6, 6, /* 9,10,11 */
  29889. 5, 5, 5, /* 12-14 */
  29890. 4, 4, 4, 4, /* 15-18 */
  29891. 3, 3, 3, 3, 3, 3, /* 19-24 */
  29892. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  29893. };
  29894. if( a>=b ){
  29895. if( a>b+49 ) return a;
  29896. if( a>b+31 ) return a+1;
  29897. return a+x[a-b];
  29898. }else{
  29899. if( b>a+49 ) return b;
  29900. if( b>a+31 ) return b+1;
  29901. return b+x[b-a];
  29902. }
  29903. }
  29904. /*
  29905. ** Convert an integer into a LogEst. In other words, compute an
  29906. ** approximation for 10*log2(x).
  29907. */
  29908. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  29909. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  29910. LogEst y = 40;
  29911. if( x<8 ){
  29912. if( x<2 ) return 0;
  29913. while( x<8 ){ y -= 10; x <<= 1; }
  29914. }else{
  29915. #if GCC_VERSION>=5004000
  29916. int i = 60 - __builtin_clzll(x);
  29917. y += i*10;
  29918. x >>= i;
  29919. #else
  29920. while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
  29921. while( x>15 ){ y += 10; x >>= 1; }
  29922. #endif
  29923. }
  29924. return a[x&7] + y - 10;
  29925. }
  29926. #ifndef SQLITE_OMIT_VIRTUALTABLE
  29927. /*
  29928. ** Convert a double into a LogEst
  29929. ** In other words, compute an approximation for 10*log2(x).
  29930. */
  29931. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  29932. u64 a;
  29933. LogEst e;
  29934. assert( sizeof(x)==8 && sizeof(a)==8 );
  29935. if( x<=1 ) return 0;
  29936. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  29937. memcpy(&a, &x, 8);
  29938. e = (a>>52) - 1022;
  29939. return e*10;
  29940. }
  29941. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  29942. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  29943. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  29944. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  29945. /*
  29946. ** Convert a LogEst into an integer.
  29947. **
  29948. ** Note that this routine is only used when one or more of various
  29949. ** non-standard compile-time options is enabled.
  29950. */
  29951. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  29952. u64 n;
  29953. n = x%10;
  29954. x /= 10;
  29955. if( n>=5 ) n -= 2;
  29956. else if( n>=1 ) n -= 1;
  29957. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  29958. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  29959. if( x>60 ) return (u64)LARGEST_INT64;
  29960. #else
  29961. /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
  29962. ** possible to this routine is 310, resulting in a maximum x of 31 */
  29963. assert( x<=60 );
  29964. #endif
  29965. return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
  29966. }
  29967. #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
  29968. /*
  29969. ** Add a new name/number pair to a VList. This might require that the
  29970. ** VList object be reallocated, so return the new VList. If an OOM
  29971. ** error occurs, the original VList returned and the
  29972. ** db->mallocFailed flag is set.
  29973. **
  29974. ** A VList is really just an array of integers. To destroy a VList,
  29975. ** simply pass it to sqlite3DbFree().
  29976. **
  29977. ** The first integer is the number of integers allocated for the whole
  29978. ** VList. The second integer is the number of integers actually used.
  29979. ** Each name/number pair is encoded by subsequent groups of 3 or more
  29980. ** integers.
  29981. **
  29982. ** Each name/number pair starts with two integers which are the numeric
  29983. ** value for the pair and the size of the name/number pair, respectively.
  29984. ** The text name overlays one or more following integers. The text name
  29985. ** is always zero-terminated.
  29986. **
  29987. ** Conceptually:
  29988. **
  29989. ** struct VList {
  29990. ** int nAlloc; // Number of allocated slots
  29991. ** int nUsed; // Number of used slots
  29992. ** struct VListEntry {
  29993. ** int iValue; // Value for this entry
  29994. ** int nSlot; // Slots used by this entry
  29995. ** // ... variable name goes here
  29996. ** } a[0];
  29997. ** }
  29998. **
  29999. ** During code generation, pointers to the variable names within the
  30000. ** VList are taken. When that happens, nAlloc is set to zero as an
  30001. ** indication that the VList may never again be enlarged, since the
  30002. ** accompanying realloc() would invalidate the pointers.
  30003. */
  30004. SQLITE_PRIVATE VList *sqlite3VListAdd(
  30005. sqlite3 *db, /* The database connection used for malloc() */
  30006. VList *pIn, /* The input VList. Might be NULL */
  30007. const char *zName, /* Name of symbol to add */
  30008. int nName, /* Bytes of text in zName */
  30009. int iVal /* Value to associate with zName */
  30010. ){
  30011. int nInt; /* number of sizeof(int) objects needed for zName */
  30012. char *z; /* Pointer to where zName will be stored */
  30013. int i; /* Index in pIn[] where zName is stored */
  30014. nInt = nName/4 + 3;
  30015. assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
  30016. if( pIn==0 || pIn[1]+nInt > pIn[0] ){
  30017. /* Enlarge the allocation */
  30018. int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
  30019. VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
  30020. if( pOut==0 ) return pIn;
  30021. if( pIn==0 ) pOut[1] = 2;
  30022. pIn = pOut;
  30023. pIn[0] = nAlloc;
  30024. }
  30025. i = pIn[1];
  30026. pIn[i] = iVal;
  30027. pIn[i+1] = nInt;
  30028. z = (char*)&pIn[i+2];
  30029. pIn[1] = i+nInt;
  30030. assert( pIn[1]<=pIn[0] );
  30031. memcpy(z, zName, nName);
  30032. z[nName] = 0;
  30033. return pIn;
  30034. }
  30035. /*
  30036. ** Return a pointer to the name of a variable in the given VList that
  30037. ** has the value iVal. Or return a NULL if there is no such variable in
  30038. ** the list
  30039. */
  30040. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
  30041. int i, mx;
  30042. if( pIn==0 ) return 0;
  30043. mx = pIn[1];
  30044. i = 2;
  30045. do{
  30046. if( pIn[i]==iVal ) return (char*)&pIn[i+2];
  30047. i += pIn[i+1];
  30048. }while( i<mx );
  30049. return 0;
  30050. }
  30051. /*
  30052. ** Return the number of the variable named zName, if it is in VList.
  30053. ** or return 0 if there is no such variable.
  30054. */
  30055. SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
  30056. int i, mx;
  30057. if( pIn==0 ) return 0;
  30058. mx = pIn[1];
  30059. i = 2;
  30060. do{
  30061. const char *z = (const char*)&pIn[i+2];
  30062. if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
  30063. i += pIn[i+1];
  30064. }while( i<mx );
  30065. return 0;
  30066. }
  30067. /************** End of util.c ************************************************/
  30068. /************** Begin file hash.c ********************************************/
  30069. /*
  30070. ** 2001 September 22
  30071. **
  30072. ** The author disclaims copyright to this source code. In place of
  30073. ** a legal notice, here is a blessing:
  30074. **
  30075. ** May you do good and not evil.
  30076. ** May you find forgiveness for yourself and forgive others.
  30077. ** May you share freely, never taking more than you give.
  30078. **
  30079. *************************************************************************
  30080. ** This is the implementation of generic hash-tables
  30081. ** used in SQLite.
  30082. */
  30083. /* #include "sqliteInt.h" */
  30084. /* #include <assert.h> */
  30085. /* Turn bulk memory into a hash table object by initializing the
  30086. ** fields of the Hash structure.
  30087. **
  30088. ** "pNew" is a pointer to the hash table that is to be initialized.
  30089. */
  30090. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  30091. assert( pNew!=0 );
  30092. pNew->first = 0;
  30093. pNew->count = 0;
  30094. pNew->htsize = 0;
  30095. pNew->ht = 0;
  30096. }
  30097. /* Remove all entries from a hash table. Reclaim all memory.
  30098. ** Call this routine to delete a hash table or to reset a hash table
  30099. ** to the empty state.
  30100. */
  30101. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  30102. HashElem *elem; /* For looping over all elements of the table */
  30103. assert( pH!=0 );
  30104. elem = pH->first;
  30105. pH->first = 0;
  30106. sqlite3_free(pH->ht);
  30107. pH->ht = 0;
  30108. pH->htsize = 0;
  30109. while( elem ){
  30110. HashElem *next_elem = elem->next;
  30111. sqlite3_free(elem);
  30112. elem = next_elem;
  30113. }
  30114. pH->count = 0;
  30115. }
  30116. /*
  30117. ** The hashing function.
  30118. */
  30119. static unsigned int strHash(const char *z){
  30120. unsigned int h = 0;
  30121. unsigned char c;
  30122. while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
  30123. /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
  30124. ** 0x9e3779b1 is 2654435761 which is the closest prime number to
  30125. ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
  30126. h += sqlite3UpperToLower[c];
  30127. h *= 0x9e3779b1;
  30128. }
  30129. return h;
  30130. }
  30131. #ifdef SQLITE_ENABLE_NORMALIZE
  30132. static unsigned int strHashN(const char *z, int n){
  30133. unsigned int h = 0;
  30134. int i;
  30135. for(i=0; i<n; i++){
  30136. /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
  30137. ** 0x9e3779b1 is 2654435761 which is the closest prime number to
  30138. ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
  30139. h += sqlite3UpperToLower[z[i]];
  30140. h *= 0x9e3779b1;
  30141. }
  30142. return h;
  30143. }
  30144. #endif /* SQLITE_ENABLE_NORMALIZE */
  30145. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  30146. ** insert pNew into the pEntry hash bucket.
  30147. */
  30148. static void insertElement(
  30149. Hash *pH, /* The complete hash table */
  30150. struct _ht *pEntry, /* The entry into which pNew is inserted */
  30151. HashElem *pNew /* The element to be inserted */
  30152. ){
  30153. HashElem *pHead; /* First element already in pEntry */
  30154. if( pEntry ){
  30155. pHead = pEntry->count ? pEntry->chain : 0;
  30156. pEntry->count++;
  30157. pEntry->chain = pNew;
  30158. }else{
  30159. pHead = 0;
  30160. }
  30161. if( pHead ){
  30162. pNew->next = pHead;
  30163. pNew->prev = pHead->prev;
  30164. if( pHead->prev ){ pHead->prev->next = pNew; }
  30165. else { pH->first = pNew; }
  30166. pHead->prev = pNew;
  30167. }else{
  30168. pNew->next = pH->first;
  30169. if( pH->first ){ pH->first->prev = pNew; }
  30170. pNew->prev = 0;
  30171. pH->first = pNew;
  30172. }
  30173. }
  30174. /* Resize the hash table so that it cantains "new_size" buckets.
  30175. **
  30176. ** The hash table might fail to resize if sqlite3_malloc() fails or
  30177. ** if the new size is the same as the prior size.
  30178. ** Return TRUE if the resize occurs and false if not.
  30179. */
  30180. static int rehash(Hash *pH, unsigned int new_size){
  30181. struct _ht *new_ht; /* The new hash table */
  30182. HashElem *elem, *next_elem; /* For looping over existing elements */
  30183. #if SQLITE_MALLOC_SOFT_LIMIT>0
  30184. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  30185. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  30186. }
  30187. if( new_size==pH->htsize ) return 0;
  30188. #endif
  30189. /* The inability to allocates space for a larger hash table is
  30190. ** a performance hit but it is not a fatal error. So mark the
  30191. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  30192. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  30193. ** only zeroes the requested number of bytes whereas this module will
  30194. ** use the actual amount of space allocated for the hash table (which
  30195. ** may be larger than the requested amount).
  30196. */
  30197. sqlite3BeginBenignMalloc();
  30198. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  30199. sqlite3EndBenignMalloc();
  30200. if( new_ht==0 ) return 0;
  30201. sqlite3_free(pH->ht);
  30202. pH->ht = new_ht;
  30203. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  30204. memset(new_ht, 0, new_size*sizeof(struct _ht));
  30205. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  30206. unsigned int h = strHash(elem->pKey) % new_size;
  30207. next_elem = elem->next;
  30208. insertElement(pH, &new_ht[h], elem);
  30209. }
  30210. return 1;
  30211. }
  30212. /* This function (for internal use only) locates an element in an
  30213. ** hash table that matches the given key. If no element is found,
  30214. ** a pointer to a static null element with HashElem.data==0 is returned.
  30215. ** If pH is not NULL, then the hash for this key is written to *pH.
  30216. */
  30217. static HashElem *findElementWithHash(
  30218. const Hash *pH, /* The pH to be searched */
  30219. const char *pKey, /* The key we are searching for */
  30220. unsigned int *pHash /* Write the hash value here */
  30221. ){
  30222. HashElem *elem; /* Used to loop thru the element list */
  30223. int count; /* Number of elements left to test */
  30224. unsigned int h; /* The computed hash */
  30225. static HashElem nullElement = { 0, 0, 0, 0 };
  30226. if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
  30227. struct _ht *pEntry;
  30228. h = strHash(pKey) % pH->htsize;
  30229. pEntry = &pH->ht[h];
  30230. elem = pEntry->chain;
  30231. count = pEntry->count;
  30232. }else{
  30233. h = 0;
  30234. elem = pH->first;
  30235. count = pH->count;
  30236. }
  30237. if( pHash ) *pHash = h;
  30238. while( count-- ){
  30239. assert( elem!=0 );
  30240. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  30241. return elem;
  30242. }
  30243. elem = elem->next;
  30244. }
  30245. return &nullElement;
  30246. }
  30247. #ifdef SQLITE_ENABLE_NORMALIZE
  30248. static HashElem *findElementWithHashN(
  30249. const Hash *pH, /* The pH to be searched */
  30250. const char *pKey, /* The key we are searching for */
  30251. int nKey, /* Number of key bytes to use */
  30252. unsigned int *pHash /* Write the hash value here */
  30253. ){
  30254. HashElem *elem; /* Used to loop thru the element list */
  30255. int count; /* Number of elements left to test */
  30256. unsigned int h; /* The computed hash */
  30257. static HashElem nullElement = { 0, 0, 0, 0 };
  30258. if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
  30259. struct _ht *pEntry;
  30260. h = strHashN(pKey, nKey) % pH->htsize;
  30261. pEntry = &pH->ht[h];
  30262. elem = pEntry->chain;
  30263. count = pEntry->count;
  30264. }else{
  30265. h = 0;
  30266. elem = pH->first;
  30267. count = pH->count;
  30268. }
  30269. if( pHash ) *pHash = h;
  30270. while( count-- ){
  30271. assert( elem!=0 );
  30272. if( sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
  30273. return elem;
  30274. }
  30275. elem = elem->next;
  30276. }
  30277. return &nullElement;
  30278. }
  30279. #endif /* SQLITE_ENABLE_NORMALIZE */
  30280. /* Remove a single entry from the hash table given a pointer to that
  30281. ** element and a hash on the element's key.
  30282. */
  30283. static void removeElementGivenHash(
  30284. Hash *pH, /* The pH containing "elem" */
  30285. HashElem* elem, /* The element to be removed from the pH */
  30286. unsigned int h /* Hash value for the element */
  30287. ){
  30288. struct _ht *pEntry;
  30289. if( elem->prev ){
  30290. elem->prev->next = elem->next;
  30291. }else{
  30292. pH->first = elem->next;
  30293. }
  30294. if( elem->next ){
  30295. elem->next->prev = elem->prev;
  30296. }
  30297. if( pH->ht ){
  30298. pEntry = &pH->ht[h];
  30299. if( pEntry->chain==elem ){
  30300. pEntry->chain = elem->next;
  30301. }
  30302. pEntry->count--;
  30303. assert( pEntry->count>=0 );
  30304. }
  30305. sqlite3_free( elem );
  30306. pH->count--;
  30307. if( pH->count==0 ){
  30308. assert( pH->first==0 );
  30309. assert( pH->count==0 );
  30310. sqlite3HashClear(pH);
  30311. }
  30312. }
  30313. /* Attempt to locate an element of the hash table pH with a key
  30314. ** that matches pKey. Return the data for this element if it is
  30315. ** found, or NULL if there is no match.
  30316. */
  30317. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  30318. assert( pH!=0 );
  30319. assert( pKey!=0 );
  30320. return findElementWithHash(pH, pKey, 0)->data;
  30321. }
  30322. #ifdef SQLITE_ENABLE_NORMALIZE
  30323. SQLITE_PRIVATE void *sqlite3HashFindN(const Hash *pH, const char *pKey, int nKey){
  30324. assert( pH!=0 );
  30325. assert( pKey!=0 );
  30326. assert( nKey>=0 );
  30327. return findElementWithHashN(pH, pKey, nKey, 0)->data;
  30328. }
  30329. #endif /* SQLITE_ENABLE_NORMALIZE */
  30330. /* Insert an element into the hash table pH. The key is pKey
  30331. ** and the data is "data".
  30332. **
  30333. ** If no element exists with a matching key, then a new
  30334. ** element is created and NULL is returned.
  30335. **
  30336. ** If another element already exists with the same key, then the
  30337. ** new data replaces the old data and the old data is returned.
  30338. ** The key is not copied in this instance. If a malloc fails, then
  30339. ** the new data is returned and the hash table is unchanged.
  30340. **
  30341. ** If the "data" parameter to this function is NULL, then the
  30342. ** element corresponding to "key" is removed from the hash table.
  30343. */
  30344. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  30345. unsigned int h; /* the hash of the key modulo hash table size */
  30346. HashElem *elem; /* Used to loop thru the element list */
  30347. HashElem *new_elem; /* New element added to the pH */
  30348. assert( pH!=0 );
  30349. assert( pKey!=0 );
  30350. elem = findElementWithHash(pH,pKey,&h);
  30351. if( elem->data ){
  30352. void *old_data = elem->data;
  30353. if( data==0 ){
  30354. removeElementGivenHash(pH,elem,h);
  30355. }else{
  30356. elem->data = data;
  30357. elem->pKey = pKey;
  30358. }
  30359. return old_data;
  30360. }
  30361. if( data==0 ) return 0;
  30362. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  30363. if( new_elem==0 ) return data;
  30364. new_elem->pKey = pKey;
  30365. new_elem->data = data;
  30366. pH->count++;
  30367. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  30368. if( rehash(pH, pH->count*2) ){
  30369. assert( pH->htsize>0 );
  30370. h = strHash(pKey) % pH->htsize;
  30371. }
  30372. }
  30373. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  30374. return 0;
  30375. }
  30376. /************** End of hash.c ************************************************/
  30377. /************** Begin file opcodes.c *****************************************/
  30378. /* Automatically generated. Do not edit */
  30379. /* See the tool/mkopcodec.tcl script for details. */
  30380. #if !defined(SQLITE_OMIT_EXPLAIN) \
  30381. || defined(VDBE_PROFILE) \
  30382. || defined(SQLITE_DEBUG)
  30383. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  30384. # define OpHelp(X) "\0" X
  30385. #else
  30386. # define OpHelp(X)
  30387. #endif
  30388. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  30389. static const char *const azName[] = {
  30390. /* 0 */ "Savepoint" OpHelp(""),
  30391. /* 1 */ "AutoCommit" OpHelp(""),
  30392. /* 2 */ "Transaction" OpHelp(""),
  30393. /* 3 */ "SorterNext" OpHelp(""),
  30394. /* 4 */ "Prev" OpHelp(""),
  30395. /* 5 */ "Next" OpHelp(""),
  30396. /* 6 */ "Checkpoint" OpHelp(""),
  30397. /* 7 */ "JournalMode" OpHelp(""),
  30398. /* 8 */ "Vacuum" OpHelp(""),
  30399. /* 9 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  30400. /* 10 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  30401. /* 11 */ "Goto" OpHelp(""),
  30402. /* 12 */ "Gosub" OpHelp(""),
  30403. /* 13 */ "InitCoroutine" OpHelp(""),
  30404. /* 14 */ "Yield" OpHelp(""),
  30405. /* 15 */ "MustBeInt" OpHelp(""),
  30406. /* 16 */ "Jump" OpHelp(""),
  30407. /* 17 */ "Once" OpHelp(""),
  30408. /* 18 */ "If" OpHelp(""),
  30409. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  30410. /* 20 */ "IfNot" OpHelp(""),
  30411. /* 21 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
  30412. /* 22 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  30413. /* 23 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  30414. /* 24 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  30415. /* 25 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  30416. /* 26 */ "IfNoHope" OpHelp("key=r[P3@P4]"),
  30417. /* 27 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  30418. /* 28 */ "NotFound" OpHelp("key=r[P3@P4]"),
  30419. /* 29 */ "Found" OpHelp("key=r[P3@P4]"),
  30420. /* 30 */ "SeekRowid" OpHelp("intkey=r[P3]"),
  30421. /* 31 */ "NotExists" OpHelp("intkey=r[P3]"),
  30422. /* 32 */ "Last" OpHelp(""),
  30423. /* 33 */ "IfSmaller" OpHelp(""),
  30424. /* 34 */ "SorterSort" OpHelp(""),
  30425. /* 35 */ "Sort" OpHelp(""),
  30426. /* 36 */ "Rewind" OpHelp(""),
  30427. /* 37 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  30428. /* 38 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  30429. /* 39 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  30430. /* 40 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  30431. /* 41 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  30432. /* 42 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  30433. /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  30434. /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  30435. /* 45 */ "Program" OpHelp(""),
  30436. /* 46 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  30437. /* 47 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  30438. /* 48 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
  30439. /* 49 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  30440. /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  30441. /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  30442. /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
  30443. /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
  30444. /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
  30445. /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
  30446. /* 56 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
  30447. /* 57 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
  30448. /* 58 */ "ElseNotEq" OpHelp(""),
  30449. /* 59 */ "IncrVacuum" OpHelp(""),
  30450. /* 60 */ "VNext" OpHelp(""),
  30451. /* 61 */ "Init" OpHelp("Start at P2"),
  30452. /* 62 */ "PureFunc0" OpHelp(""),
  30453. /* 63 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  30454. /* 64 */ "PureFunc" OpHelp(""),
  30455. /* 65 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  30456. /* 66 */ "Return" OpHelp(""),
  30457. /* 67 */ "EndCoroutine" OpHelp(""),
  30458. /* 68 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  30459. /* 69 */ "Halt" OpHelp(""),
  30460. /* 70 */ "Integer" OpHelp("r[P2]=P1"),
  30461. /* 71 */ "Int64" OpHelp("r[P2]=P4"),
  30462. /* 72 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  30463. /* 73 */ "Null" OpHelp("r[P2..P3]=NULL"),
  30464. /* 74 */ "SoftNull" OpHelp("r[P1]=NULL"),
  30465. /* 75 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  30466. /* 76 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  30467. /* 77 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  30468. /* 78 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  30469. /* 79 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  30470. /* 80 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
  30471. /* 81 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  30472. /* 82 */ "CollSeq" OpHelp(""),
  30473. /* 83 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  30474. /* 84 */ "RealAffinity" OpHelp(""),
  30475. /* 85 */ "Cast" OpHelp("affinity(r[P1])"),
  30476. /* 86 */ "Permutation" OpHelp(""),
  30477. /* 87 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  30478. /* 88 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
  30479. /* 89 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"),
  30480. /* 90 */ "Column" OpHelp("r[P3]=PX"),
  30481. /* 91 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  30482. /* 92 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  30483. /* 93 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  30484. /* 94 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  30485. /* 95 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  30486. /* 96 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  30487. /* 97 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  30488. /* 98 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  30489. /* 99 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  30490. /* 100 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  30491. /* 101 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  30492. /* 102 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  30493. /* 103 */ "BitNot" OpHelp("r[P2]= ~r[P1]"),
  30494. /* 104 */ "Count" OpHelp("r[P2]=count()"),
  30495. /* 105 */ "ReadCookie" OpHelp(""),
  30496. /* 106 */ "String8" OpHelp("r[P2]='P4'"),
  30497. /* 107 */ "SetCookie" OpHelp(""),
  30498. /* 108 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  30499. /* 109 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  30500. /* 110 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  30501. /* 111 */ "OpenDup" OpHelp(""),
  30502. /* 112 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  30503. /* 113 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  30504. /* 114 */ "SorterOpen" OpHelp(""),
  30505. /* 115 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  30506. /* 116 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  30507. /* 117 */ "Close" OpHelp(""),
  30508. /* 118 */ "ColumnsUsed" OpHelp(""),
  30509. /* 119 */ "SeekHit" OpHelp("seekHit=P2"),
  30510. /* 120 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  30511. /* 121 */ "NewRowid" OpHelp("r[P2]=rowid"),
  30512. /* 122 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  30513. /* 123 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  30514. /* 124 */ "Delete" OpHelp(""),
  30515. /* 125 */ "ResetCount" OpHelp(""),
  30516. /* 126 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  30517. /* 127 */ "SorterData" OpHelp("r[P2]=data"),
  30518. /* 128 */ "RowData" OpHelp("r[P2]=data"),
  30519. /* 129 */ "Rowid" OpHelp("r[P2]=rowid"),
  30520. /* 130 */ "NullRow" OpHelp(""),
  30521. /* 131 */ "SeekEnd" OpHelp(""),
  30522. /* 132 */ "SorterInsert" OpHelp("key=r[P2]"),
  30523. /* 133 */ "IdxInsert" OpHelp("key=r[P2]"),
  30524. /* 134 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  30525. /* 135 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
  30526. /* 136 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  30527. /* 137 */ "Destroy" OpHelp(""),
  30528. /* 138 */ "Clear" OpHelp(""),
  30529. /* 139 */ "ResetSorter" OpHelp(""),
  30530. /* 140 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
  30531. /* 141 */ "Real" OpHelp("r[P2]=P4"),
  30532. /* 142 */ "SqlExec" OpHelp(""),
  30533. /* 143 */ "ParseSchema" OpHelp(""),
  30534. /* 144 */ "LoadAnalysis" OpHelp(""),
  30535. /* 145 */ "DropTable" OpHelp(""),
  30536. /* 146 */ "DropIndex" OpHelp(""),
  30537. /* 147 */ "DropTrigger" OpHelp(""),
  30538. /* 148 */ "IntegrityCk" OpHelp(""),
  30539. /* 149 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  30540. /* 150 */ "Param" OpHelp(""),
  30541. /* 151 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  30542. /* 152 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  30543. /* 153 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
  30544. /* 154 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),
  30545. /* 155 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  30546. /* 156 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),
  30547. /* 157 */ "AggValue" OpHelp("r[P3]=value N=P2"),
  30548. /* 158 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  30549. /* 159 */ "Expire" OpHelp(""),
  30550. /* 160 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  30551. /* 161 */ "VBegin" OpHelp(""),
  30552. /* 162 */ "VCreate" OpHelp(""),
  30553. /* 163 */ "VDestroy" OpHelp(""),
  30554. /* 164 */ "VOpen" OpHelp(""),
  30555. /* 165 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  30556. /* 166 */ "VRename" OpHelp(""),
  30557. /* 167 */ "Pagecount" OpHelp(""),
  30558. /* 168 */ "MaxPgcnt" OpHelp(""),
  30559. /* 169 */ "Trace" OpHelp(""),
  30560. /* 170 */ "CursorHint" OpHelp(""),
  30561. /* 171 */ "Noop" OpHelp(""),
  30562. /* 172 */ "Explain" OpHelp(""),
  30563. /* 173 */ "Abortable" OpHelp(""),
  30564. };
  30565. return azName[i];
  30566. }
  30567. #endif
  30568. /************** End of opcodes.c *********************************************/
  30569. /************** Begin file os_unix.c *****************************************/
  30570. /*
  30571. ** 2004 May 22
  30572. **
  30573. ** The author disclaims copyright to this source code. In place of
  30574. ** a legal notice, here is a blessing:
  30575. **
  30576. ** May you do good and not evil.
  30577. ** May you find forgiveness for yourself and forgive others.
  30578. ** May you share freely, never taking more than you give.
  30579. **
  30580. ******************************************************************************
  30581. **
  30582. ** This file contains the VFS implementation for unix-like operating systems
  30583. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  30584. **
  30585. ** There are actually several different VFS implementations in this file.
  30586. ** The differences are in the way that file locking is done. The default
  30587. ** implementation uses Posix Advisory Locks. Alternative implementations
  30588. ** use flock(), dot-files, various proprietary locking schemas, or simply
  30589. ** skip locking all together.
  30590. **
  30591. ** This source file is organized into divisions where the logic for various
  30592. ** subfunctions is contained within the appropriate division. PLEASE
  30593. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  30594. ** in the correct division and should be clearly labeled.
  30595. **
  30596. ** The layout of divisions is as follows:
  30597. **
  30598. ** * General-purpose declarations and utility functions.
  30599. ** * Unique file ID logic used by VxWorks.
  30600. ** * Various locking primitive implementations (all except proxy locking):
  30601. ** + for Posix Advisory Locks
  30602. ** + for no-op locks
  30603. ** + for dot-file locks
  30604. ** + for flock() locking
  30605. ** + for named semaphore locks (VxWorks only)
  30606. ** + for AFP filesystem locks (MacOSX only)
  30607. ** * sqlite3_file methods not associated with locking.
  30608. ** * Definitions of sqlite3_io_methods objects for all locking
  30609. ** methods plus "finder" functions for each locking method.
  30610. ** * sqlite3_vfs method implementations.
  30611. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  30612. ** * Definitions of sqlite3_vfs objects for all locking methods
  30613. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  30614. */
  30615. /* #include "sqliteInt.h" */
  30616. #if SQLITE_OS_UNIX /* This file is used on unix only */
  30617. /*
  30618. ** There are various methods for file locking used for concurrency
  30619. ** control:
  30620. **
  30621. ** 1. POSIX locking (the default),
  30622. ** 2. No locking,
  30623. ** 3. Dot-file locking,
  30624. ** 4. flock() locking,
  30625. ** 5. AFP locking (OSX only),
  30626. ** 6. Named POSIX semaphores (VXWorks only),
  30627. ** 7. proxy locking. (OSX only)
  30628. **
  30629. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  30630. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  30631. ** selection of the appropriate locking style based on the filesystem
  30632. ** where the database is located.
  30633. */
  30634. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  30635. # if defined(__APPLE__)
  30636. # define SQLITE_ENABLE_LOCKING_STYLE 1
  30637. # else
  30638. # define SQLITE_ENABLE_LOCKING_STYLE 0
  30639. # endif
  30640. #endif
  30641. /* Use pread() and pwrite() if they are available */
  30642. #if defined(__APPLE__)
  30643. # define HAVE_PREAD 1
  30644. # define HAVE_PWRITE 1
  30645. #endif
  30646. #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
  30647. # undef USE_PREAD
  30648. # define USE_PREAD64 1
  30649. #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
  30650. # undef USE_PREAD64
  30651. # define USE_PREAD 1
  30652. #endif
  30653. /*
  30654. ** standard include files.
  30655. */
  30656. #include <sys/types.h>
  30657. #include <sys/stat.h>
  30658. #include <fcntl.h>
  30659. #include <sys/ioctl.h>
  30660. #include <unistd.h>
  30661. /* #include <time.h> */
  30662. #include <sys/time.h>
  30663. #include <errno.h>
  30664. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  30665. # include <sys/mman.h>
  30666. #endif
  30667. #if SQLITE_ENABLE_LOCKING_STYLE
  30668. /* # include <sys/ioctl.h> */
  30669. # include <sys/file.h>
  30670. # include <sys/param.h>
  30671. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  30672. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  30673. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  30674. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  30675. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  30676. # define HAVE_GETHOSTUUID 1
  30677. # else
  30678. # warning "gethostuuid() is disabled."
  30679. # endif
  30680. #endif
  30681. #if OS_VXWORKS
  30682. /* # include <sys/ioctl.h> */
  30683. # include <semaphore.h>
  30684. # include <limits.h>
  30685. #endif /* OS_VXWORKS */
  30686. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  30687. # include <sys/mount.h>
  30688. #endif
  30689. #ifdef HAVE_UTIME
  30690. # include <utime.h>
  30691. #endif
  30692. /*
  30693. ** Allowed values of unixFile.fsFlags
  30694. */
  30695. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  30696. /*
  30697. ** If we are to be thread-safe, include the pthreads header.
  30698. */
  30699. #if SQLITE_THREADSAFE
  30700. /* # include <pthread.h> */
  30701. #endif
  30702. /*
  30703. ** Default permissions when creating a new file
  30704. */
  30705. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  30706. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  30707. #endif
  30708. /*
  30709. ** Default permissions when creating auto proxy dir
  30710. */
  30711. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  30712. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  30713. #endif
  30714. /*
  30715. ** Maximum supported path-length.
  30716. */
  30717. #define MAX_PATHNAME 512
  30718. /*
  30719. ** Maximum supported symbolic links
  30720. */
  30721. #define SQLITE_MAX_SYMLINKS 100
  30722. /* Always cast the getpid() return type for compatibility with
  30723. ** kernel modules in VxWorks. */
  30724. #define osGetpid(X) (pid_t)getpid()
  30725. /*
  30726. ** Only set the lastErrno if the error code is a real error and not
  30727. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  30728. */
  30729. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  30730. /* Forward references */
  30731. typedef struct unixShm unixShm; /* Connection shared memory */
  30732. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  30733. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  30734. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  30735. /*
  30736. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  30737. ** cannot be closed immediately. In these cases, instances of the following
  30738. ** structure are used to store the file descriptor while waiting for an
  30739. ** opportunity to either close or reuse it.
  30740. */
  30741. struct UnixUnusedFd {
  30742. int fd; /* File descriptor to close */
  30743. int flags; /* Flags this file descriptor was opened with */
  30744. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  30745. };
  30746. /*
  30747. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  30748. ** VFS implementations.
  30749. */
  30750. typedef struct unixFile unixFile;
  30751. struct unixFile {
  30752. sqlite3_io_methods const *pMethod; /* Always the first entry */
  30753. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  30754. unixInodeInfo *pInode; /* Info about locks on this inode */
  30755. int h; /* The file descriptor */
  30756. unsigned char eFileLock; /* The type of lock held on this fd */
  30757. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  30758. int lastErrno; /* The unix errno from last I/O error */
  30759. void *lockingContext; /* Locking style specific state */
  30760. UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
  30761. const char *zPath; /* Name of the file */
  30762. unixShm *pShm; /* Shared memory segment information */
  30763. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  30764. #if SQLITE_MAX_MMAP_SIZE>0
  30765. int nFetchOut; /* Number of outstanding xFetch refs */
  30766. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  30767. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  30768. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  30769. void *pMapRegion; /* Memory mapped region */
  30770. #endif
  30771. int sectorSize; /* Device sector size */
  30772. int deviceCharacteristics; /* Precomputed device characteristics */
  30773. #if SQLITE_ENABLE_LOCKING_STYLE
  30774. int openFlags; /* The flags specified at open() */
  30775. #endif
  30776. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  30777. unsigned fsFlags; /* cached details from statfs() */
  30778. #endif
  30779. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  30780. unsigned iBusyTimeout; /* Wait this many millisec on locks */
  30781. #endif
  30782. #if OS_VXWORKS
  30783. struct vxworksFileId *pId; /* Unique file ID */
  30784. #endif
  30785. #ifdef SQLITE_DEBUG
  30786. /* The next group of variables are used to track whether or not the
  30787. ** transaction counter in bytes 24-27 of database files are updated
  30788. ** whenever any part of the database changes. An assertion fault will
  30789. ** occur if a file is updated without also updating the transaction
  30790. ** counter. This test is made to avoid new problems similar to the
  30791. ** one described by ticket #3584.
  30792. */
  30793. unsigned char transCntrChng; /* True if the transaction counter changed */
  30794. unsigned char dbUpdate; /* True if any part of database file changed */
  30795. unsigned char inNormalWrite; /* True if in a normal write operation */
  30796. #endif
  30797. #ifdef SQLITE_TEST
  30798. /* In test mode, increase the size of this structure a bit so that
  30799. ** it is larger than the struct CrashFile defined in test6.c.
  30800. */
  30801. char aPadding[32];
  30802. #endif
  30803. };
  30804. /* This variable holds the process id (pid) from when the xRandomness()
  30805. ** method was called. If xOpen() is called from a different process id,
  30806. ** indicating that a fork() has occurred, the PRNG will be reset.
  30807. */
  30808. static pid_t randomnessPid = 0;
  30809. /*
  30810. ** Allowed values for the unixFile.ctrlFlags bitmask:
  30811. */
  30812. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  30813. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  30814. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  30815. #ifndef SQLITE_DISABLE_DIRSYNC
  30816. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  30817. #else
  30818. # define UNIXFILE_DIRSYNC 0x00
  30819. #endif
  30820. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  30821. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  30822. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  30823. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  30824. /*
  30825. ** Include code that is common to all os_*.c files
  30826. */
  30827. /************** Include os_common.h in the middle of os_unix.c ***************/
  30828. /************** Begin file os_common.h ***************************************/
  30829. /*
  30830. ** 2004 May 22
  30831. **
  30832. ** The author disclaims copyright to this source code. In place of
  30833. ** a legal notice, here is a blessing:
  30834. **
  30835. ** May you do good and not evil.
  30836. ** May you find forgiveness for yourself and forgive others.
  30837. ** May you share freely, never taking more than you give.
  30838. **
  30839. ******************************************************************************
  30840. **
  30841. ** This file contains macros and a little bit of code that is common to
  30842. ** all of the platform-specific files (os_*.c) and is #included into those
  30843. ** files.
  30844. **
  30845. ** This file should be #included by the os_*.c files only. It is not a
  30846. ** general purpose header file.
  30847. */
  30848. #ifndef _OS_COMMON_H_
  30849. #define _OS_COMMON_H_
  30850. /*
  30851. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  30852. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  30853. ** switch. The following code should catch this problem at compile-time.
  30854. */
  30855. #ifdef MEMORY_DEBUG
  30856. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  30857. #endif
  30858. /*
  30859. ** Macros for performance tracing. Normally turned off. Only works
  30860. ** on i486 hardware.
  30861. */
  30862. #ifdef SQLITE_PERFORMANCE_TRACE
  30863. /*
  30864. ** hwtime.h contains inline assembler code for implementing
  30865. ** high-performance timing routines.
  30866. */
  30867. /************** Include hwtime.h in the middle of os_common.h ****************/
  30868. /************** Begin file hwtime.h ******************************************/
  30869. /*
  30870. ** 2008 May 27
  30871. **
  30872. ** The author disclaims copyright to this source code. In place of
  30873. ** a legal notice, here is a blessing:
  30874. **
  30875. ** May you do good and not evil.
  30876. ** May you find forgiveness for yourself and forgive others.
  30877. ** May you share freely, never taking more than you give.
  30878. **
  30879. ******************************************************************************
  30880. **
  30881. ** This file contains inline asm code for retrieving "high-performance"
  30882. ** counters for x86 class CPUs.
  30883. */
  30884. #ifndef SQLITE_HWTIME_H
  30885. #define SQLITE_HWTIME_H
  30886. /*
  30887. ** The following routine only works on pentium-class (or newer) processors.
  30888. ** It uses the RDTSC opcode to read the cycle count value out of the
  30889. ** processor and returns that value. This can be used for high-res
  30890. ** profiling.
  30891. */
  30892. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  30893. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  30894. #if defined(__GNUC__)
  30895. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30896. unsigned int lo, hi;
  30897. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  30898. return (sqlite_uint64)hi << 32 | lo;
  30899. }
  30900. #elif defined(_MSC_VER)
  30901. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  30902. __asm {
  30903. rdtsc
  30904. ret ; return value at EDX:EAX
  30905. }
  30906. }
  30907. #endif
  30908. #elif (defined(__GNUC__) && defined(__x86_64__))
  30909. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30910. unsigned long val;
  30911. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  30912. return val;
  30913. }
  30914. #elif (defined(__GNUC__) && defined(__ppc__))
  30915. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30916. unsigned long long retval;
  30917. unsigned long junk;
  30918. __asm__ __volatile__ ("\n\
  30919. 1: mftbu %1\n\
  30920. mftb %L0\n\
  30921. mftbu %0\n\
  30922. cmpw %0,%1\n\
  30923. bne 1b"
  30924. : "=r" (retval), "=r" (junk));
  30925. return retval;
  30926. }
  30927. #else
  30928. #error Need implementation of sqlite3Hwtime() for your platform.
  30929. /*
  30930. ** To compile without implementing sqlite3Hwtime() for your platform,
  30931. ** you can remove the above #error and use the following
  30932. ** stub function. You will lose timing support for many
  30933. ** of the debugging and testing utilities, but it should at
  30934. ** least compile and run.
  30935. */
  30936. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  30937. #endif
  30938. #endif /* !defined(SQLITE_HWTIME_H) */
  30939. /************** End of hwtime.h **********************************************/
  30940. /************** Continuing where we left off in os_common.h ******************/
  30941. static sqlite_uint64 g_start;
  30942. static sqlite_uint64 g_elapsed;
  30943. #define TIMER_START g_start=sqlite3Hwtime()
  30944. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  30945. #define TIMER_ELAPSED g_elapsed
  30946. #else
  30947. #define TIMER_START
  30948. #define TIMER_END
  30949. #define TIMER_ELAPSED ((sqlite_uint64)0)
  30950. #endif
  30951. /*
  30952. ** If we compile with the SQLITE_TEST macro set, then the following block
  30953. ** of code will give us the ability to simulate a disk I/O error. This
  30954. ** is used for testing the I/O recovery logic.
  30955. */
  30956. #if defined(SQLITE_TEST)
  30957. SQLITE_API extern int sqlite3_io_error_hit;
  30958. SQLITE_API extern int sqlite3_io_error_hardhit;
  30959. SQLITE_API extern int sqlite3_io_error_pending;
  30960. SQLITE_API extern int sqlite3_io_error_persist;
  30961. SQLITE_API extern int sqlite3_io_error_benign;
  30962. SQLITE_API extern int sqlite3_diskfull_pending;
  30963. SQLITE_API extern int sqlite3_diskfull;
  30964. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  30965. #define SimulateIOError(CODE) \
  30966. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  30967. || sqlite3_io_error_pending-- == 1 ) \
  30968. { local_ioerr(); CODE; }
  30969. static void local_ioerr(){
  30970. IOTRACE(("IOERR\n"));
  30971. sqlite3_io_error_hit++;
  30972. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  30973. }
  30974. #define SimulateDiskfullError(CODE) \
  30975. if( sqlite3_diskfull_pending ){ \
  30976. if( sqlite3_diskfull_pending == 1 ){ \
  30977. local_ioerr(); \
  30978. sqlite3_diskfull = 1; \
  30979. sqlite3_io_error_hit = 1; \
  30980. CODE; \
  30981. }else{ \
  30982. sqlite3_diskfull_pending--; \
  30983. } \
  30984. }
  30985. #else
  30986. #define SimulateIOErrorBenign(X)
  30987. #define SimulateIOError(A)
  30988. #define SimulateDiskfullError(A)
  30989. #endif /* defined(SQLITE_TEST) */
  30990. /*
  30991. ** When testing, keep a count of the number of open files.
  30992. */
  30993. #if defined(SQLITE_TEST)
  30994. SQLITE_API extern int sqlite3_open_file_count;
  30995. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  30996. #else
  30997. #define OpenCounter(X)
  30998. #endif /* defined(SQLITE_TEST) */
  30999. #endif /* !defined(_OS_COMMON_H_) */
  31000. /************** End of os_common.h *******************************************/
  31001. /************** Continuing where we left off in os_unix.c ********************/
  31002. /*
  31003. ** Define various macros that are missing from some systems.
  31004. */
  31005. #ifndef O_LARGEFILE
  31006. # define O_LARGEFILE 0
  31007. #endif
  31008. #ifdef SQLITE_DISABLE_LFS
  31009. # undef O_LARGEFILE
  31010. # define O_LARGEFILE 0
  31011. #endif
  31012. #ifndef O_NOFOLLOW
  31013. # define O_NOFOLLOW 0
  31014. #endif
  31015. #ifndef O_BINARY
  31016. # define O_BINARY 0
  31017. #endif
  31018. /*
  31019. ** The threadid macro resolves to the thread-id or to 0. Used for
  31020. ** testing and debugging only.
  31021. */
  31022. #if SQLITE_THREADSAFE
  31023. #define threadid pthread_self()
  31024. #else
  31025. #define threadid 0
  31026. #endif
  31027. /*
  31028. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  31029. */
  31030. #if !defined(HAVE_MREMAP)
  31031. # if defined(__linux__) && defined(_GNU_SOURCE)
  31032. # define HAVE_MREMAP 1
  31033. # else
  31034. # define HAVE_MREMAP 0
  31035. # endif
  31036. #endif
  31037. /*
  31038. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  31039. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  31040. */
  31041. #ifdef __ANDROID__
  31042. # define lseek lseek64
  31043. #endif
  31044. #ifdef __linux__
  31045. /*
  31046. ** Linux-specific IOCTL magic numbers used for controlling F2FS
  31047. */
  31048. #define F2FS_IOCTL_MAGIC 0xf5
  31049. #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
  31050. #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
  31051. #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
  31052. #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
  31053. #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
  31054. #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
  31055. #endif /* __linux__ */
  31056. /*
  31057. ** Different Unix systems declare open() in different ways. Same use
  31058. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  31059. ** The difference is important when using a pointer to the function.
  31060. **
  31061. ** The safest way to deal with the problem is to always use this wrapper
  31062. ** which always has the same well-defined interface.
  31063. */
  31064. static int posixOpen(const char *zFile, int flags, int mode){
  31065. return open(zFile, flags, mode);
  31066. }
  31067. /* Forward reference */
  31068. static int openDirectory(const char*, int*);
  31069. static int unixGetpagesize(void);
  31070. /*
  31071. ** Many system calls are accessed through pointer-to-functions so that
  31072. ** they may be overridden at runtime to facilitate fault injection during
  31073. ** testing and sandboxing. The following array holds the names and pointers
  31074. ** to all overrideable system calls.
  31075. */
  31076. static struct unix_syscall {
  31077. const char *zName; /* Name of the system call */
  31078. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  31079. sqlite3_syscall_ptr pDefault; /* Default value */
  31080. } aSyscall[] = {
  31081. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  31082. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  31083. { "close", (sqlite3_syscall_ptr)close, 0 },
  31084. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  31085. { "access", (sqlite3_syscall_ptr)access, 0 },
  31086. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  31087. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  31088. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  31089. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  31090. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  31091. /*
  31092. ** The DJGPP compiler environment looks mostly like Unix, but it
  31093. ** lacks the fcntl() system call. So redefine fcntl() to be something
  31094. ** that always succeeds. This means that locking does not occur under
  31095. ** DJGPP. But it is DOS - what did you expect?
  31096. */
  31097. #ifdef __DJGPP__
  31098. { "fstat", 0, 0 },
  31099. #define osFstat(a,b,c) 0
  31100. #else
  31101. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  31102. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  31103. #endif
  31104. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  31105. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  31106. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  31107. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  31108. { "read", (sqlite3_syscall_ptr)read, 0 },
  31109. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  31110. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  31111. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  31112. #else
  31113. { "pread", (sqlite3_syscall_ptr)0, 0 },
  31114. #endif
  31115. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  31116. #if defined(USE_PREAD64)
  31117. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  31118. #else
  31119. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  31120. #endif
  31121. #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
  31122. { "write", (sqlite3_syscall_ptr)write, 0 },
  31123. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  31124. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  31125. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  31126. #else
  31127. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  31128. #endif
  31129. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  31130. aSyscall[12].pCurrent)
  31131. #if defined(USE_PREAD64)
  31132. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  31133. #else
  31134. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  31135. #endif
  31136. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
  31137. aSyscall[13].pCurrent)
  31138. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  31139. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  31140. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  31141. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  31142. #else
  31143. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  31144. #endif
  31145. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  31146. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  31147. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  31148. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  31149. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  31150. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  31151. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  31152. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  31153. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  31154. #if defined(HAVE_FCHOWN)
  31155. { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
  31156. #else
  31157. { "fchown", (sqlite3_syscall_ptr)0, 0 },
  31158. #endif
  31159. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  31160. #if defined(HAVE_FCHOWN)
  31161. { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
  31162. #else
  31163. { "geteuid", (sqlite3_syscall_ptr)0, 0 },
  31164. #endif
  31165. #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
  31166. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  31167. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  31168. #else
  31169. { "mmap", (sqlite3_syscall_ptr)0, 0 },
  31170. #endif
  31171. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
  31172. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  31173. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  31174. #else
  31175. { "munmap", (sqlite3_syscall_ptr)0, 0 },
  31176. #endif
  31177. #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
  31178. #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  31179. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  31180. #else
  31181. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  31182. #endif
  31183. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
  31184. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  31185. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  31186. #else
  31187. { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
  31188. #endif
  31189. #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
  31190. #if defined(HAVE_READLINK)
  31191. { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
  31192. #else
  31193. { "readlink", (sqlite3_syscall_ptr)0, 0 },
  31194. #endif
  31195. #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
  31196. #if defined(HAVE_LSTAT)
  31197. { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
  31198. #else
  31199. { "lstat", (sqlite3_syscall_ptr)0, 0 },
  31200. #endif
  31201. #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
  31202. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  31203. # ifdef __ANDROID__
  31204. { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
  31205. # else
  31206. { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
  31207. # endif
  31208. #else
  31209. { "ioctl", (sqlite3_syscall_ptr)0, 0 },
  31210. #endif
  31211. #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
  31212. }; /* End of the overrideable system calls */
  31213. /*
  31214. ** On some systems, calls to fchown() will trigger a message in a security
  31215. ** log if they come from non-root processes. So avoid calling fchown() if
  31216. ** we are not running as root.
  31217. */
  31218. static int robustFchown(int fd, uid_t uid, gid_t gid){
  31219. #if defined(HAVE_FCHOWN)
  31220. return osGeteuid() ? 0 : osFchown(fd,uid,gid);
  31221. #else
  31222. return 0;
  31223. #endif
  31224. }
  31225. /*
  31226. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  31227. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  31228. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  31229. ** system call named zName.
  31230. */
  31231. static int unixSetSystemCall(
  31232. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  31233. const char *zName, /* Name of system call to override */
  31234. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  31235. ){
  31236. unsigned int i;
  31237. int rc = SQLITE_NOTFOUND;
  31238. UNUSED_PARAMETER(pNotUsed);
  31239. if( zName==0 ){
  31240. /* If no zName is given, restore all system calls to their default
  31241. ** settings and return NULL
  31242. */
  31243. rc = SQLITE_OK;
  31244. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31245. if( aSyscall[i].pDefault ){
  31246. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  31247. }
  31248. }
  31249. }else{
  31250. /* If zName is specified, operate on only the one system call
  31251. ** specified.
  31252. */
  31253. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31254. if( strcmp(zName, aSyscall[i].zName)==0 ){
  31255. if( aSyscall[i].pDefault==0 ){
  31256. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  31257. }
  31258. rc = SQLITE_OK;
  31259. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  31260. aSyscall[i].pCurrent = pNewFunc;
  31261. break;
  31262. }
  31263. }
  31264. }
  31265. return rc;
  31266. }
  31267. /*
  31268. ** Return the value of a system call. Return NULL if zName is not a
  31269. ** recognized system call name. NULL is also returned if the system call
  31270. ** is currently undefined.
  31271. */
  31272. static sqlite3_syscall_ptr unixGetSystemCall(
  31273. sqlite3_vfs *pNotUsed,
  31274. const char *zName
  31275. ){
  31276. unsigned int i;
  31277. UNUSED_PARAMETER(pNotUsed);
  31278. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31279. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  31280. }
  31281. return 0;
  31282. }
  31283. /*
  31284. ** Return the name of the first system call after zName. If zName==NULL
  31285. ** then return the name of the first system call. Return NULL if zName
  31286. ** is the last system call or if zName is not the name of a valid
  31287. ** system call.
  31288. */
  31289. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  31290. int i = -1;
  31291. UNUSED_PARAMETER(p);
  31292. if( zName ){
  31293. for(i=0; i<ArraySize(aSyscall)-1; i++){
  31294. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  31295. }
  31296. }
  31297. for(i++; i<ArraySize(aSyscall); i++){
  31298. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  31299. }
  31300. return 0;
  31301. }
  31302. /*
  31303. ** Do not accept any file descriptor less than this value, in order to avoid
  31304. ** opening database file using file descriptors that are commonly used for
  31305. ** standard input, output, and error.
  31306. */
  31307. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  31308. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  31309. #endif
  31310. /*
  31311. ** Invoke open(). Do so multiple times, until it either succeeds or
  31312. ** fails for some reason other than EINTR.
  31313. **
  31314. ** If the file creation mode "m" is 0 then set it to the default for
  31315. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  31316. ** 0644) as modified by the system umask. If m is not 0, then
  31317. ** make the file creation mode be exactly m ignoring the umask.
  31318. **
  31319. ** The m parameter will be non-zero only when creating -wal, -journal,
  31320. ** and -shm files. We want those files to have *exactly* the same
  31321. ** permissions as their original database, unadulterated by the umask.
  31322. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  31323. ** transaction crashes and leaves behind hot journals, then any
  31324. ** process that is able to write to the database will also be able to
  31325. ** recover the hot journals.
  31326. */
  31327. static int robust_open(const char *z, int f, mode_t m){
  31328. int fd;
  31329. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  31330. while(1){
  31331. #if defined(O_CLOEXEC)
  31332. fd = osOpen(z,f|O_CLOEXEC,m2);
  31333. #else
  31334. fd = osOpen(z,f,m2);
  31335. #endif
  31336. if( fd<0 ){
  31337. if( errno==EINTR ) continue;
  31338. break;
  31339. }
  31340. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  31341. osClose(fd);
  31342. sqlite3_log(SQLITE_WARNING,
  31343. "attempt to open \"%s\" as file descriptor %d", z, fd);
  31344. fd = -1;
  31345. if( osOpen("/dev/null", f, m)<0 ) break;
  31346. }
  31347. if( fd>=0 ){
  31348. if( m!=0 ){
  31349. struct stat statbuf;
  31350. if( osFstat(fd, &statbuf)==0
  31351. && statbuf.st_size==0
  31352. && (statbuf.st_mode&0777)!=m
  31353. ){
  31354. osFchmod(fd, m);
  31355. }
  31356. }
  31357. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  31358. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  31359. #endif
  31360. }
  31361. return fd;
  31362. }
  31363. /*
  31364. ** Helper functions to obtain and relinquish the global mutex. The
  31365. ** global mutex is used to protect the unixInodeInfo and
  31366. ** vxworksFileId objects used by this file, all of which may be
  31367. ** shared by multiple threads.
  31368. **
  31369. ** Function unixMutexHeld() is used to assert() that the global mutex
  31370. ** is held when required. This function is only used as part of assert()
  31371. ** statements. e.g.
  31372. **
  31373. ** unixEnterMutex()
  31374. ** assert( unixMutexHeld() );
  31375. ** unixEnterLeave()
  31376. **
  31377. ** To prevent deadlock, the global unixBigLock must must be acquired
  31378. ** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
  31379. ** OK to get the pLockMutex without holding unixBigLock first, but if
  31380. ** that happens, the unixBigLock mutex must not be acquired until after
  31381. ** pLockMutex is released.
  31382. **
  31383. ** OK: enter(unixBigLock), enter(pLockInfo)
  31384. ** OK: enter(unixBigLock)
  31385. ** OK: enter(pLockInfo)
  31386. ** ERROR: enter(pLockInfo), enter(unixBigLock)
  31387. */
  31388. static sqlite3_mutex *unixBigLock = 0;
  31389. static void unixEnterMutex(void){
  31390. assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
  31391. sqlite3_mutex_enter(unixBigLock);
  31392. }
  31393. static void unixLeaveMutex(void){
  31394. assert( sqlite3_mutex_held(unixBigLock) );
  31395. sqlite3_mutex_leave(unixBigLock);
  31396. }
  31397. #ifdef SQLITE_DEBUG
  31398. static int unixMutexHeld(void) {
  31399. return sqlite3_mutex_held(unixBigLock);
  31400. }
  31401. #endif
  31402. #ifdef SQLITE_HAVE_OS_TRACE
  31403. /*
  31404. ** Helper function for printing out trace information from debugging
  31405. ** binaries. This returns the string representation of the supplied
  31406. ** integer lock-type.
  31407. */
  31408. static const char *azFileLock(int eFileLock){
  31409. switch( eFileLock ){
  31410. case NO_LOCK: return "NONE";
  31411. case SHARED_LOCK: return "SHARED";
  31412. case RESERVED_LOCK: return "RESERVED";
  31413. case PENDING_LOCK: return "PENDING";
  31414. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  31415. }
  31416. return "ERROR";
  31417. }
  31418. #endif
  31419. #ifdef SQLITE_LOCK_TRACE
  31420. /*
  31421. ** Print out information about all locking operations.
  31422. **
  31423. ** This routine is used for troubleshooting locks on multithreaded
  31424. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  31425. ** command-line option on the compiler. This code is normally
  31426. ** turned off.
  31427. */
  31428. static int lockTrace(int fd, int op, struct flock *p){
  31429. char *zOpName, *zType;
  31430. int s;
  31431. int savedErrno;
  31432. if( op==F_GETLK ){
  31433. zOpName = "GETLK";
  31434. }else if( op==F_SETLK ){
  31435. zOpName = "SETLK";
  31436. }else{
  31437. s = osFcntl(fd, op, p);
  31438. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  31439. return s;
  31440. }
  31441. if( p->l_type==F_RDLCK ){
  31442. zType = "RDLCK";
  31443. }else if( p->l_type==F_WRLCK ){
  31444. zType = "WRLCK";
  31445. }else if( p->l_type==F_UNLCK ){
  31446. zType = "UNLCK";
  31447. }else{
  31448. assert( 0 );
  31449. }
  31450. assert( p->l_whence==SEEK_SET );
  31451. s = osFcntl(fd, op, p);
  31452. savedErrno = errno;
  31453. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  31454. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  31455. (int)p->l_pid, s);
  31456. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  31457. struct flock l2;
  31458. l2 = *p;
  31459. osFcntl(fd, F_GETLK, &l2);
  31460. if( l2.l_type==F_RDLCK ){
  31461. zType = "RDLCK";
  31462. }else if( l2.l_type==F_WRLCK ){
  31463. zType = "WRLCK";
  31464. }else if( l2.l_type==F_UNLCK ){
  31465. zType = "UNLCK";
  31466. }else{
  31467. assert( 0 );
  31468. }
  31469. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  31470. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  31471. }
  31472. errno = savedErrno;
  31473. return s;
  31474. }
  31475. #undef osFcntl
  31476. #define osFcntl lockTrace
  31477. #endif /* SQLITE_LOCK_TRACE */
  31478. /*
  31479. ** Retry ftruncate() calls that fail due to EINTR
  31480. **
  31481. ** All calls to ftruncate() within this file should be made through
  31482. ** this wrapper. On the Android platform, bypassing the logic below
  31483. ** could lead to a corrupt database.
  31484. */
  31485. static int robust_ftruncate(int h, sqlite3_int64 sz){
  31486. int rc;
  31487. #ifdef __ANDROID__
  31488. /* On Android, ftruncate() always uses 32-bit offsets, even if
  31489. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  31490. ** truncate a file to any size larger than 2GiB. Silently ignore any
  31491. ** such attempts. */
  31492. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  31493. rc = SQLITE_OK;
  31494. }else
  31495. #endif
  31496. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  31497. return rc;
  31498. }
  31499. /*
  31500. ** This routine translates a standard POSIX errno code into something
  31501. ** useful to the clients of the sqlite3 functions. Specifically, it is
  31502. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  31503. ** and a variety of "please close the file descriptor NOW" errors into
  31504. ** SQLITE_IOERR
  31505. **
  31506. ** Errors during initialization of locks, or file system support for locks,
  31507. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  31508. */
  31509. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  31510. assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  31511. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  31512. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  31513. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
  31514. switch (posixError) {
  31515. case EACCES:
  31516. case EAGAIN:
  31517. case ETIMEDOUT:
  31518. case EBUSY:
  31519. case EINTR:
  31520. case ENOLCK:
  31521. /* random NFS retry error, unless during file system support
  31522. * introspection, in which it actually means what it says */
  31523. return SQLITE_BUSY;
  31524. case EPERM:
  31525. return SQLITE_PERM;
  31526. default:
  31527. return sqliteIOErr;
  31528. }
  31529. }
  31530. /******************************************************************************
  31531. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  31532. **
  31533. ** On most versions of unix, we can get a unique ID for a file by concatenating
  31534. ** the device number and the inode number. But this does not work on VxWorks.
  31535. ** On VxWorks, a unique file id must be based on the canonical filename.
  31536. **
  31537. ** A pointer to an instance of the following structure can be used as a
  31538. ** unique file ID in VxWorks. Each instance of this structure contains
  31539. ** a copy of the canonical filename. There is also a reference count.
  31540. ** The structure is reclaimed when the number of pointers to it drops to
  31541. ** zero.
  31542. **
  31543. ** There are never very many files open at one time and lookups are not
  31544. ** a performance-critical path, so it is sufficient to put these
  31545. ** structures on a linked list.
  31546. */
  31547. struct vxworksFileId {
  31548. struct vxworksFileId *pNext; /* Next in a list of them all */
  31549. int nRef; /* Number of references to this one */
  31550. int nName; /* Length of the zCanonicalName[] string */
  31551. char *zCanonicalName; /* Canonical filename */
  31552. };
  31553. #if OS_VXWORKS
  31554. /*
  31555. ** All unique filenames are held on a linked list headed by this
  31556. ** variable:
  31557. */
  31558. static struct vxworksFileId *vxworksFileList = 0;
  31559. /*
  31560. ** Simplify a filename into its canonical form
  31561. ** by making the following changes:
  31562. **
  31563. ** * removing any trailing and duplicate /
  31564. ** * convert /./ into just /
  31565. ** * convert /A/../ where A is any simple name into just /
  31566. **
  31567. ** Changes are made in-place. Return the new name length.
  31568. **
  31569. ** The original filename is in z[0..n-1]. Return the number of
  31570. ** characters in the simplified name.
  31571. */
  31572. static int vxworksSimplifyName(char *z, int n){
  31573. int i, j;
  31574. while( n>1 && z[n-1]=='/' ){ n--; }
  31575. for(i=j=0; i<n; i++){
  31576. if( z[i]=='/' ){
  31577. if( z[i+1]=='/' ) continue;
  31578. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  31579. i += 1;
  31580. continue;
  31581. }
  31582. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  31583. while( j>0 && z[j-1]!='/' ){ j--; }
  31584. if( j>0 ){ j--; }
  31585. i += 2;
  31586. continue;
  31587. }
  31588. }
  31589. z[j++] = z[i];
  31590. }
  31591. z[j] = 0;
  31592. return j;
  31593. }
  31594. /*
  31595. ** Find a unique file ID for the given absolute pathname. Return
  31596. ** a pointer to the vxworksFileId object. This pointer is the unique
  31597. ** file ID.
  31598. **
  31599. ** The nRef field of the vxworksFileId object is incremented before
  31600. ** the object is returned. A new vxworksFileId object is created
  31601. ** and added to the global list if necessary.
  31602. **
  31603. ** If a memory allocation error occurs, return NULL.
  31604. */
  31605. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  31606. struct vxworksFileId *pNew; /* search key and new file ID */
  31607. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  31608. int n; /* Length of zAbsoluteName string */
  31609. assert( zAbsoluteName[0]=='/' );
  31610. n = (int)strlen(zAbsoluteName);
  31611. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  31612. if( pNew==0 ) return 0;
  31613. pNew->zCanonicalName = (char*)&pNew[1];
  31614. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  31615. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  31616. /* Search for an existing entry that matching the canonical name.
  31617. ** If found, increment the reference count and return a pointer to
  31618. ** the existing file ID.
  31619. */
  31620. unixEnterMutex();
  31621. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  31622. if( pCandidate->nName==n
  31623. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  31624. ){
  31625. sqlite3_free(pNew);
  31626. pCandidate->nRef++;
  31627. unixLeaveMutex();
  31628. return pCandidate;
  31629. }
  31630. }
  31631. /* No match was found. We will make a new file ID */
  31632. pNew->nRef = 1;
  31633. pNew->nName = n;
  31634. pNew->pNext = vxworksFileList;
  31635. vxworksFileList = pNew;
  31636. unixLeaveMutex();
  31637. return pNew;
  31638. }
  31639. /*
  31640. ** Decrement the reference count on a vxworksFileId object. Free
  31641. ** the object when the reference count reaches zero.
  31642. */
  31643. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  31644. unixEnterMutex();
  31645. assert( pId->nRef>0 );
  31646. pId->nRef--;
  31647. if( pId->nRef==0 ){
  31648. struct vxworksFileId **pp;
  31649. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  31650. assert( *pp==pId );
  31651. *pp = pId->pNext;
  31652. sqlite3_free(pId);
  31653. }
  31654. unixLeaveMutex();
  31655. }
  31656. #endif /* OS_VXWORKS */
  31657. /*************** End of Unique File ID Utility Used By VxWorks ****************
  31658. ******************************************************************************/
  31659. /******************************************************************************
  31660. *************************** Posix Advisory Locking ****************************
  31661. **
  31662. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  31663. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  31664. ** sets or clears a lock, that operation overrides any prior locks set
  31665. ** by the same process. It does not explicitly say so, but this implies
  31666. ** that it overrides locks set by the same process using a different
  31667. ** file descriptor. Consider this test case:
  31668. **
  31669. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  31670. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  31671. **
  31672. ** Suppose ./file1 and ./file2 are really the same file (because
  31673. ** one is a hard or symbolic link to the other) then if you set
  31674. ** an exclusive lock on fd1, then try to get an exclusive lock
  31675. ** on fd2, it works. I would have expected the second lock to
  31676. ** fail since there was already a lock on the file due to fd1.
  31677. ** But not so. Since both locks came from the same process, the
  31678. ** second overrides the first, even though they were on different
  31679. ** file descriptors opened on different file names.
  31680. **
  31681. ** This means that we cannot use POSIX locks to synchronize file access
  31682. ** among competing threads of the same process. POSIX locks will work fine
  31683. ** to synchronize access for threads in separate processes, but not
  31684. ** threads within the same process.
  31685. **
  31686. ** To work around the problem, SQLite has to manage file locks internally
  31687. ** on its own. Whenever a new database is opened, we have to find the
  31688. ** specific inode of the database file (the inode is determined by the
  31689. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  31690. ** and check for locks already existing on that inode. When locks are
  31691. ** created or removed, we have to look at our own internal record of the
  31692. ** locks to see if another thread has previously set a lock on that same
  31693. ** inode.
  31694. **
  31695. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  31696. ** For VxWorks, we have to use the alternative unique ID system based on
  31697. ** canonical filename and implemented in the previous division.)
  31698. **
  31699. ** The sqlite3_file structure for POSIX is no longer just an integer file
  31700. ** descriptor. It is now a structure that holds the integer file
  31701. ** descriptor and a pointer to a structure that describes the internal
  31702. ** locks on the corresponding inode. There is one locking structure
  31703. ** per inode, so if the same inode is opened twice, both unixFile structures
  31704. ** point to the same locking structure. The locking structure keeps
  31705. ** a reference count (so we will know when to delete it) and a "cnt"
  31706. ** field that tells us its internal lock status. cnt==0 means the
  31707. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  31708. ** cnt>0 means there are cnt shared locks on the file.
  31709. **
  31710. ** Any attempt to lock or unlock a file first checks the locking
  31711. ** structure. The fcntl() system call is only invoked to set a
  31712. ** POSIX lock if the internal lock structure transitions between
  31713. ** a locked and an unlocked state.
  31714. **
  31715. ** But wait: there are yet more problems with POSIX advisory locks.
  31716. **
  31717. ** If you close a file descriptor that points to a file that has locks,
  31718. ** all locks on that file that are owned by the current process are
  31719. ** released. To work around this problem, each unixInodeInfo object
  31720. ** maintains a count of the number of pending locks on tha inode.
  31721. ** When an attempt is made to close an unixFile, if there are
  31722. ** other unixFile open on the same inode that are holding locks, the call
  31723. ** to close() the file descriptor is deferred until all of the locks clear.
  31724. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  31725. ** be closed and that list is walked (and cleared) when the last lock
  31726. ** clears.
  31727. **
  31728. ** Yet another problem: LinuxThreads do not play well with posix locks.
  31729. **
  31730. ** Many older versions of linux use the LinuxThreads library which is
  31731. ** not posix compliant. Under LinuxThreads, a lock created by thread
  31732. ** A cannot be modified or overridden by a different thread B.
  31733. ** Only thread A can modify the lock. Locking behavior is correct
  31734. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  31735. ** on linux - with NPTL a lock created by thread A can override locks
  31736. ** in thread B. But there is no way to know at compile-time which
  31737. ** threading library is being used. So there is no way to know at
  31738. ** compile-time whether or not thread A can override locks on thread B.
  31739. ** One has to do a run-time check to discover the behavior of the
  31740. ** current process.
  31741. **
  31742. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  31743. ** was dropped beginning with version 3.7.0. SQLite will still work with
  31744. ** LinuxThreads provided that (1) there is no more than one connection
  31745. ** per database file in the same process and (2) database connections
  31746. ** do not move across threads.
  31747. */
  31748. /*
  31749. ** An instance of the following structure serves as the key used
  31750. ** to locate a particular unixInodeInfo object.
  31751. */
  31752. struct unixFileId {
  31753. dev_t dev; /* Device number */
  31754. #if OS_VXWORKS
  31755. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  31756. #else
  31757. /* We are told that some versions of Android contain a bug that
  31758. ** sizes ino_t at only 32-bits instead of 64-bits. (See
  31759. ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
  31760. ** To work around this, always allocate 64-bits for the inode number.
  31761. ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
  31762. ** but that should not be a big deal. */
  31763. /* WAS: ino_t ino; */
  31764. u64 ino; /* Inode number */
  31765. #endif
  31766. };
  31767. /*
  31768. ** An instance of the following structure is allocated for each open
  31769. ** inode.
  31770. **
  31771. ** A single inode can have multiple file descriptors, so each unixFile
  31772. ** structure contains a pointer to an instance of this object and this
  31773. ** object keeps a count of the number of unixFile pointing to it.
  31774. **
  31775. ** Mutex rules:
  31776. **
  31777. ** (1) Only the pLockMutex mutex must be held in order to read or write
  31778. ** any of the locking fields:
  31779. ** nShared, nLock, eFileLock, bProcessLock, pUnused
  31780. **
  31781. ** (2) When nRef>0, then the following fields are unchanging and can
  31782. ** be read (but not written) without holding any mutex:
  31783. ** fileId, pLockMutex
  31784. **
  31785. ** (3) With the exceptions above, all the fields may only be read
  31786. ** or written while holding the global unixBigLock mutex.
  31787. **
  31788. ** Deadlock prevention: The global unixBigLock mutex may not
  31789. ** be acquired while holding the pLockMutex mutex. If both unixBigLock
  31790. ** and pLockMutex are needed, then unixBigLock must be acquired first.
  31791. */
  31792. struct unixInodeInfo {
  31793. struct unixFileId fileId; /* The lookup key */
  31794. sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
  31795. int nShared; /* Number of SHARED locks held */
  31796. int nLock; /* Number of outstanding file locks */
  31797. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  31798. unsigned char bProcessLock; /* An exclusive process lock is held */
  31799. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  31800. int nRef; /* Number of pointers to this structure */
  31801. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  31802. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  31803. unixInodeInfo *pPrev; /* .... doubly linked */
  31804. #if SQLITE_ENABLE_LOCKING_STYLE
  31805. unsigned long long sharedByte; /* for AFP simulated shared lock */
  31806. #endif
  31807. #if OS_VXWORKS
  31808. sem_t *pSem; /* Named POSIX semaphore */
  31809. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  31810. #endif
  31811. };
  31812. /*
  31813. ** A lists of all unixInodeInfo objects.
  31814. **
  31815. ** Must hold unixBigLock in order to read or write this variable.
  31816. */
  31817. static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
  31818. #ifdef SQLITE_DEBUG
  31819. /*
  31820. ** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
  31821. ** This routine is used only within assert() to help verify correct mutex
  31822. ** usage.
  31823. */
  31824. int unixFileMutexHeld(unixFile *pFile){
  31825. assert( pFile->pInode );
  31826. return sqlite3_mutex_held(pFile->pInode->pLockMutex);
  31827. }
  31828. int unixFileMutexNotheld(unixFile *pFile){
  31829. assert( pFile->pInode );
  31830. return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
  31831. }
  31832. #endif
  31833. /*
  31834. **
  31835. ** This function - unixLogErrorAtLine(), is only ever called via the macro
  31836. ** unixLogError().
  31837. **
  31838. ** It is invoked after an error occurs in an OS function and errno has been
  31839. ** set. It logs a message using sqlite3_log() containing the current value of
  31840. ** errno and, if possible, the human-readable equivalent from strerror() or
  31841. ** strerror_r().
  31842. **
  31843. ** The first argument passed to the macro should be the error code that
  31844. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  31845. ** The two subsequent arguments should be the name of the OS function that
  31846. ** failed (e.g. "unlink", "open") and the associated file-system path,
  31847. ** if any.
  31848. */
  31849. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  31850. static int unixLogErrorAtLine(
  31851. int errcode, /* SQLite error code */
  31852. const char *zFunc, /* Name of OS function that failed */
  31853. const char *zPath, /* File path associated with error */
  31854. int iLine /* Source line number where error occurred */
  31855. ){
  31856. char *zErr; /* Message from strerror() or equivalent */
  31857. int iErrno = errno; /* Saved syscall error number */
  31858. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  31859. ** the strerror() function to obtain the human-readable error message
  31860. ** equivalent to errno. Otherwise, use strerror_r().
  31861. */
  31862. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  31863. char aErr[80];
  31864. memset(aErr, 0, sizeof(aErr));
  31865. zErr = aErr;
  31866. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  31867. ** assume that the system provides the GNU version of strerror_r() that
  31868. ** returns a pointer to a buffer containing the error message. That pointer
  31869. ** may point to aErr[], or it may point to some static storage somewhere.
  31870. ** Otherwise, assume that the system provides the POSIX version of
  31871. ** strerror_r(), which always writes an error message into aErr[].
  31872. **
  31873. ** If the code incorrectly assumes that it is the POSIX version that is
  31874. ** available, the error message will often be an empty string. Not a
  31875. ** huge problem. Incorrectly concluding that the GNU version is available
  31876. ** could lead to a segfault though.
  31877. */
  31878. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  31879. zErr =
  31880. # endif
  31881. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  31882. #elif SQLITE_THREADSAFE
  31883. /* This is a threadsafe build, but strerror_r() is not available. */
  31884. zErr = "";
  31885. #else
  31886. /* Non-threadsafe build, use strerror(). */
  31887. zErr = strerror(iErrno);
  31888. #endif
  31889. if( zPath==0 ) zPath = "";
  31890. sqlite3_log(errcode,
  31891. "os_unix.c:%d: (%d) %s(%s) - %s",
  31892. iLine, iErrno, zFunc, zPath, zErr
  31893. );
  31894. return errcode;
  31895. }
  31896. /*
  31897. ** Close a file descriptor.
  31898. **
  31899. ** We assume that close() almost always works, since it is only in a
  31900. ** very sick application or on a very sick platform that it might fail.
  31901. ** If it does fail, simply leak the file descriptor, but do log the
  31902. ** error.
  31903. **
  31904. ** Note that it is not safe to retry close() after EINTR since the
  31905. ** file descriptor might have already been reused by another thread.
  31906. ** So we don't even try to recover from an EINTR. Just log the error
  31907. ** and move on.
  31908. */
  31909. static void robust_close(unixFile *pFile, int h, int lineno){
  31910. if( osClose(h) ){
  31911. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  31912. pFile ? pFile->zPath : 0, lineno);
  31913. }
  31914. }
  31915. /*
  31916. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  31917. ** a convenient place to set a breakpoint.
  31918. */
  31919. static void storeLastErrno(unixFile *pFile, int error){
  31920. pFile->lastErrno = error;
  31921. }
  31922. /*
  31923. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  31924. */
  31925. static void closePendingFds(unixFile *pFile){
  31926. unixInodeInfo *pInode = pFile->pInode;
  31927. UnixUnusedFd *p;
  31928. UnixUnusedFd *pNext;
  31929. assert( unixFileMutexHeld(pFile) );
  31930. for(p=pInode->pUnused; p; p=pNext){
  31931. pNext = p->pNext;
  31932. robust_close(pFile, p->fd, __LINE__);
  31933. sqlite3_free(p);
  31934. }
  31935. pInode->pUnused = 0;
  31936. }
  31937. /*
  31938. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  31939. **
  31940. ** The global mutex must be held when this routine is called, but the mutex
  31941. ** on the inode being deleted must NOT be held.
  31942. */
  31943. static void releaseInodeInfo(unixFile *pFile){
  31944. unixInodeInfo *pInode = pFile->pInode;
  31945. assert( unixMutexHeld() );
  31946. assert( unixFileMutexNotheld(pFile) );
  31947. if( ALWAYS(pInode) ){
  31948. pInode->nRef--;
  31949. if( pInode->nRef==0 ){
  31950. assert( pInode->pShmNode==0 );
  31951. sqlite3_mutex_enter(pInode->pLockMutex);
  31952. closePendingFds(pFile);
  31953. sqlite3_mutex_leave(pInode->pLockMutex);
  31954. if( pInode->pPrev ){
  31955. assert( pInode->pPrev->pNext==pInode );
  31956. pInode->pPrev->pNext = pInode->pNext;
  31957. }else{
  31958. assert( inodeList==pInode );
  31959. inodeList = pInode->pNext;
  31960. }
  31961. if( pInode->pNext ){
  31962. assert( pInode->pNext->pPrev==pInode );
  31963. pInode->pNext->pPrev = pInode->pPrev;
  31964. }
  31965. sqlite3_mutex_free(pInode->pLockMutex);
  31966. sqlite3_free(pInode);
  31967. }
  31968. }
  31969. }
  31970. /*
  31971. ** Given a file descriptor, locate the unixInodeInfo object that
  31972. ** describes that file descriptor. Create a new one if necessary. The
  31973. ** return value might be uninitialized if an error occurs.
  31974. **
  31975. ** The global mutex must held when calling this routine.
  31976. **
  31977. ** Return an appropriate error code.
  31978. */
  31979. static int findInodeInfo(
  31980. unixFile *pFile, /* Unix file with file desc used in the key */
  31981. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  31982. ){
  31983. int rc; /* System call return code */
  31984. int fd; /* The file descriptor for pFile */
  31985. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  31986. struct stat statbuf; /* Low-level file information */
  31987. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  31988. assert( unixMutexHeld() );
  31989. /* Get low-level information about the file that we can used to
  31990. ** create a unique name for the file.
  31991. */
  31992. fd = pFile->h;
  31993. rc = osFstat(fd, &statbuf);
  31994. if( rc!=0 ){
  31995. storeLastErrno(pFile, errno);
  31996. #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
  31997. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  31998. #endif
  31999. return SQLITE_IOERR;
  32000. }
  32001. #ifdef __APPLE__
  32002. /* On OS X on an msdos filesystem, the inode number is reported
  32003. ** incorrectly for zero-size files. See ticket #3260. To work
  32004. ** around this problem (we consider it a bug in OS X, not SQLite)
  32005. ** we always increase the file size to 1 by writing a single byte
  32006. ** prior to accessing the inode number. The one byte written is
  32007. ** an ASCII 'S' character which also happens to be the first byte
  32008. ** in the header of every SQLite database. In this way, if there
  32009. ** is a race condition such that another thread has already populated
  32010. ** the first page of the database, no damage is done.
  32011. */
  32012. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  32013. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  32014. if( rc!=1 ){
  32015. storeLastErrno(pFile, errno);
  32016. return SQLITE_IOERR;
  32017. }
  32018. rc = osFstat(fd, &statbuf);
  32019. if( rc!=0 ){
  32020. storeLastErrno(pFile, errno);
  32021. return SQLITE_IOERR;
  32022. }
  32023. }
  32024. #endif
  32025. memset(&fileId, 0, sizeof(fileId));
  32026. fileId.dev = statbuf.st_dev;
  32027. #if OS_VXWORKS
  32028. fileId.pId = pFile->pId;
  32029. #else
  32030. fileId.ino = (u64)statbuf.st_ino;
  32031. #endif
  32032. assert( unixMutexHeld() );
  32033. pInode = inodeList;
  32034. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  32035. pInode = pInode->pNext;
  32036. }
  32037. if( pInode==0 ){
  32038. pInode = sqlite3_malloc64( sizeof(*pInode) );
  32039. if( pInode==0 ){
  32040. return SQLITE_NOMEM_BKPT;
  32041. }
  32042. memset(pInode, 0, sizeof(*pInode));
  32043. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  32044. if( sqlite3GlobalConfig.bCoreMutex ){
  32045. pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  32046. if( pInode->pLockMutex==0 ){
  32047. sqlite3_free(pInode);
  32048. return SQLITE_NOMEM_BKPT;
  32049. }
  32050. }
  32051. pInode->nRef = 1;
  32052. assert( unixMutexHeld() );
  32053. pInode->pNext = inodeList;
  32054. pInode->pPrev = 0;
  32055. if( inodeList ) inodeList->pPrev = pInode;
  32056. inodeList = pInode;
  32057. }else{
  32058. pInode->nRef++;
  32059. }
  32060. *ppInode = pInode;
  32061. return SQLITE_OK;
  32062. }
  32063. /*
  32064. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  32065. */
  32066. static int fileHasMoved(unixFile *pFile){
  32067. #if OS_VXWORKS
  32068. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  32069. #else
  32070. struct stat buf;
  32071. return pFile->pInode!=0 &&
  32072. (osStat(pFile->zPath, &buf)!=0
  32073. || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
  32074. #endif
  32075. }
  32076. /*
  32077. ** Check a unixFile that is a database. Verify the following:
  32078. **
  32079. ** (1) There is exactly one hard link on the file
  32080. ** (2) The file is not a symbolic link
  32081. ** (3) The file has not been renamed or unlinked
  32082. **
  32083. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  32084. */
  32085. static void verifyDbFile(unixFile *pFile){
  32086. struct stat buf;
  32087. int rc;
  32088. /* These verifications occurs for the main database only */
  32089. if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
  32090. rc = osFstat(pFile->h, &buf);
  32091. if( rc!=0 ){
  32092. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  32093. return;
  32094. }
  32095. if( buf.st_nlink==0 ){
  32096. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  32097. return;
  32098. }
  32099. if( buf.st_nlink>1 ){
  32100. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  32101. return;
  32102. }
  32103. if( fileHasMoved(pFile) ){
  32104. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  32105. return;
  32106. }
  32107. }
  32108. /*
  32109. ** This routine checks if there is a RESERVED lock held on the specified
  32110. ** file by this or any other process. If such a lock is held, set *pResOut
  32111. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32112. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32113. */
  32114. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  32115. int rc = SQLITE_OK;
  32116. int reserved = 0;
  32117. unixFile *pFile = (unixFile*)id;
  32118. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32119. assert( pFile );
  32120. assert( pFile->eFileLock<=SHARED_LOCK );
  32121. sqlite3_mutex_enter(pFile->pInode->pLockMutex);
  32122. /* Check if a thread in this process holds such a lock */
  32123. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  32124. reserved = 1;
  32125. }
  32126. /* Otherwise see if some other process holds it.
  32127. */
  32128. #ifndef __DJGPP__
  32129. if( !reserved && !pFile->pInode->bProcessLock ){
  32130. struct flock lock;
  32131. lock.l_whence = SEEK_SET;
  32132. lock.l_start = RESERVED_BYTE;
  32133. lock.l_len = 1;
  32134. lock.l_type = F_WRLCK;
  32135. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  32136. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  32137. storeLastErrno(pFile, errno);
  32138. } else if( lock.l_type!=F_UNLCK ){
  32139. reserved = 1;
  32140. }
  32141. }
  32142. #endif
  32143. sqlite3_mutex_leave(pFile->pInode->pLockMutex);
  32144. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  32145. *pResOut = reserved;
  32146. return rc;
  32147. }
  32148. /*
  32149. ** Set a posix-advisory-lock.
  32150. **
  32151. ** There are two versions of this routine. If compiled with
  32152. ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
  32153. ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
  32154. ** value is set, then it is the number of milliseconds to wait before
  32155. ** failing the lock. The iBusyTimeout value is always reset back to
  32156. ** zero on each call.
  32157. **
  32158. ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
  32159. ** attempt to set the lock.
  32160. */
  32161. #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
  32162. # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
  32163. #else
  32164. static int osSetPosixAdvisoryLock(
  32165. int h, /* The file descriptor on which to take the lock */
  32166. struct flock *pLock, /* The description of the lock */
  32167. unixFile *pFile /* Structure holding timeout value */
  32168. ){
  32169. int rc = osFcntl(h,F_SETLK,pLock);
  32170. while( rc<0 && pFile->iBusyTimeout>0 ){
  32171. /* On systems that support some kind of blocking file lock with a timeout,
  32172. ** make appropriate changes here to invoke that blocking file lock. On
  32173. ** generic posix, however, there is no such API. So we simply try the
  32174. ** lock once every millisecond until either the timeout expires, or until
  32175. ** the lock is obtained. */
  32176. usleep(1000);
  32177. rc = osFcntl(h,F_SETLK,pLock);
  32178. pFile->iBusyTimeout--;
  32179. }
  32180. return rc;
  32181. }
  32182. #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
  32183. /*
  32184. ** Attempt to set a system-lock on the file pFile. The lock is
  32185. ** described by pLock.
  32186. **
  32187. ** If the pFile was opened read/write from unix-excl, then the only lock
  32188. ** ever obtained is an exclusive lock, and it is obtained exactly once
  32189. ** the first time any lock is attempted. All subsequent system locking
  32190. ** operations become no-ops. Locking operations still happen internally,
  32191. ** in order to coordinate access between separate database connections
  32192. ** within this process, but all of that is handled in memory and the
  32193. ** operating system does not participate.
  32194. **
  32195. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  32196. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  32197. ** and is read-only.
  32198. **
  32199. ** Zero is returned if the call completes successfully, or -1 if a call
  32200. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  32201. */
  32202. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  32203. int rc;
  32204. unixInodeInfo *pInode = pFile->pInode;
  32205. assert( pInode!=0 );
  32206. assert( sqlite3_mutex_held(pInode->pLockMutex) );
  32207. if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
  32208. if( pInode->bProcessLock==0 ){
  32209. struct flock lock;
  32210. assert( pInode->nLock==0 );
  32211. lock.l_whence = SEEK_SET;
  32212. lock.l_start = SHARED_FIRST;
  32213. lock.l_len = SHARED_SIZE;
  32214. lock.l_type = F_WRLCK;
  32215. rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
  32216. if( rc<0 ) return rc;
  32217. pInode->bProcessLock = 1;
  32218. pInode->nLock++;
  32219. }else{
  32220. rc = 0;
  32221. }
  32222. }else{
  32223. rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
  32224. }
  32225. return rc;
  32226. }
  32227. /*
  32228. ** Lock the file with the lock specified by parameter eFileLock - one
  32229. ** of the following:
  32230. **
  32231. ** (1) SHARED_LOCK
  32232. ** (2) RESERVED_LOCK
  32233. ** (3) PENDING_LOCK
  32234. ** (4) EXCLUSIVE_LOCK
  32235. **
  32236. ** Sometimes when requesting one lock state, additional lock states
  32237. ** are inserted in between. The locking might fail on one of the later
  32238. ** transitions leaving the lock state different from what it started but
  32239. ** still short of its goal. The following chart shows the allowed
  32240. ** transitions and the inserted intermediate states:
  32241. **
  32242. ** UNLOCKED -> SHARED
  32243. ** SHARED -> RESERVED
  32244. ** SHARED -> (PENDING) -> EXCLUSIVE
  32245. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32246. ** PENDING -> EXCLUSIVE
  32247. **
  32248. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32249. ** routine to lower a locking level.
  32250. */
  32251. static int unixLock(sqlite3_file *id, int eFileLock){
  32252. /* The following describes the implementation of the various locks and
  32253. ** lock transitions in terms of the POSIX advisory shared and exclusive
  32254. ** lock primitives (called read-locks and write-locks below, to avoid
  32255. ** confusion with SQLite lock names). The algorithms are complicated
  32256. ** slightly in order to be compatible with Windows95 systems simultaneously
  32257. ** accessing the same database file, in case that is ever required.
  32258. **
  32259. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  32260. ** byte', each single bytes at well known offsets, and the 'shared byte
  32261. ** range', a range of 510 bytes at a well known offset.
  32262. **
  32263. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  32264. ** byte'. If this is successful, 'shared byte range' is read-locked
  32265. ** and the lock on the 'pending byte' released. (Legacy note: When
  32266. ** SQLite was first developed, Windows95 systems were still very common,
  32267. ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
  32268. ** single randomly selected by from the 'shared byte range' is locked.
  32269. ** Windows95 is now pretty much extinct, but this work-around for the
  32270. ** lack of shared-locks on Windows95 lives on, for backwards
  32271. ** compatibility.)
  32272. **
  32273. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  32274. ** A RESERVED lock is implemented by grabbing a write-lock on the
  32275. ** 'reserved byte'.
  32276. **
  32277. ** A process may only obtain a PENDING lock after it has obtained a
  32278. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  32279. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  32280. ** obtained, but existing SHARED locks are allowed to persist. A process
  32281. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  32282. ** This property is used by the algorithm for rolling back a journal file
  32283. ** after a crash.
  32284. **
  32285. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  32286. ** implemented by obtaining a write-lock on the entire 'shared byte
  32287. ** range'. Since all other locks require a read-lock on one of the bytes
  32288. ** within this range, this ensures that no other locks are held on the
  32289. ** database.
  32290. */
  32291. int rc = SQLITE_OK;
  32292. unixFile *pFile = (unixFile*)id;
  32293. unixInodeInfo *pInode;
  32294. struct flock lock;
  32295. int tErrno = 0;
  32296. assert( pFile );
  32297. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  32298. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  32299. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  32300. osGetpid(0)));
  32301. /* If there is already a lock of this type or more restrictive on the
  32302. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  32303. ** unixEnterMutex() hasn't been called yet.
  32304. */
  32305. if( pFile->eFileLock>=eFileLock ){
  32306. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  32307. azFileLock(eFileLock)));
  32308. return SQLITE_OK;
  32309. }
  32310. /* Make sure the locking sequence is correct.
  32311. ** (1) We never move from unlocked to anything higher than shared lock.
  32312. ** (2) SQLite never explicitly requests a pendig lock.
  32313. ** (3) A shared lock is always held when a reserve lock is requested.
  32314. */
  32315. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  32316. assert( eFileLock!=PENDING_LOCK );
  32317. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  32318. /* This mutex is needed because pFile->pInode is shared across threads
  32319. */
  32320. pInode = pFile->pInode;
  32321. sqlite3_mutex_enter(pInode->pLockMutex);
  32322. /* If some thread using this PID has a lock via a different unixFile*
  32323. ** handle that precludes the requested lock, return BUSY.
  32324. */
  32325. if( (pFile->eFileLock!=pInode->eFileLock &&
  32326. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  32327. ){
  32328. rc = SQLITE_BUSY;
  32329. goto end_lock;
  32330. }
  32331. /* If a SHARED lock is requested, and some thread using this PID already
  32332. ** has a SHARED or RESERVED lock, then increment reference counts and
  32333. ** return SQLITE_OK.
  32334. */
  32335. if( eFileLock==SHARED_LOCK &&
  32336. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  32337. assert( eFileLock==SHARED_LOCK );
  32338. assert( pFile->eFileLock==0 );
  32339. assert( pInode->nShared>0 );
  32340. pFile->eFileLock = SHARED_LOCK;
  32341. pInode->nShared++;
  32342. pInode->nLock++;
  32343. goto end_lock;
  32344. }
  32345. /* A PENDING lock is needed before acquiring a SHARED lock and before
  32346. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  32347. ** be released.
  32348. */
  32349. lock.l_len = 1L;
  32350. lock.l_whence = SEEK_SET;
  32351. if( eFileLock==SHARED_LOCK
  32352. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  32353. ){
  32354. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  32355. lock.l_start = PENDING_BYTE;
  32356. if( unixFileLock(pFile, &lock) ){
  32357. tErrno = errno;
  32358. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32359. if( rc!=SQLITE_BUSY ){
  32360. storeLastErrno(pFile, tErrno);
  32361. }
  32362. goto end_lock;
  32363. }
  32364. }
  32365. /* If control gets to this point, then actually go ahead and make
  32366. ** operating system calls for the specified lock.
  32367. */
  32368. if( eFileLock==SHARED_LOCK ){
  32369. assert( pInode->nShared==0 );
  32370. assert( pInode->eFileLock==0 );
  32371. assert( rc==SQLITE_OK );
  32372. /* Now get the read-lock */
  32373. lock.l_start = SHARED_FIRST;
  32374. lock.l_len = SHARED_SIZE;
  32375. if( unixFileLock(pFile, &lock) ){
  32376. tErrno = errno;
  32377. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32378. }
  32379. /* Drop the temporary PENDING lock */
  32380. lock.l_start = PENDING_BYTE;
  32381. lock.l_len = 1L;
  32382. lock.l_type = F_UNLCK;
  32383. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  32384. /* This could happen with a network mount */
  32385. tErrno = errno;
  32386. rc = SQLITE_IOERR_UNLOCK;
  32387. }
  32388. if( rc ){
  32389. if( rc!=SQLITE_BUSY ){
  32390. storeLastErrno(pFile, tErrno);
  32391. }
  32392. goto end_lock;
  32393. }else{
  32394. pFile->eFileLock = SHARED_LOCK;
  32395. pInode->nLock++;
  32396. pInode->nShared = 1;
  32397. }
  32398. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  32399. /* We are trying for an exclusive lock but another thread in this
  32400. ** same process is still holding a shared lock. */
  32401. rc = SQLITE_BUSY;
  32402. }else{
  32403. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  32404. ** assumed that there is a SHARED or greater lock on the file
  32405. ** already.
  32406. */
  32407. assert( 0!=pFile->eFileLock );
  32408. lock.l_type = F_WRLCK;
  32409. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  32410. if( eFileLock==RESERVED_LOCK ){
  32411. lock.l_start = RESERVED_BYTE;
  32412. lock.l_len = 1L;
  32413. }else{
  32414. lock.l_start = SHARED_FIRST;
  32415. lock.l_len = SHARED_SIZE;
  32416. }
  32417. if( unixFileLock(pFile, &lock) ){
  32418. tErrno = errno;
  32419. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32420. if( rc!=SQLITE_BUSY ){
  32421. storeLastErrno(pFile, tErrno);
  32422. }
  32423. }
  32424. }
  32425. #ifdef SQLITE_DEBUG
  32426. /* Set up the transaction-counter change checking flags when
  32427. ** transitioning from a SHARED to a RESERVED lock. The change
  32428. ** from SHARED to RESERVED marks the beginning of a normal
  32429. ** write operation (not a hot journal rollback).
  32430. */
  32431. if( rc==SQLITE_OK
  32432. && pFile->eFileLock<=SHARED_LOCK
  32433. && eFileLock==RESERVED_LOCK
  32434. ){
  32435. pFile->transCntrChng = 0;
  32436. pFile->dbUpdate = 0;
  32437. pFile->inNormalWrite = 1;
  32438. }
  32439. #endif
  32440. if( rc==SQLITE_OK ){
  32441. pFile->eFileLock = eFileLock;
  32442. pInode->eFileLock = eFileLock;
  32443. }else if( eFileLock==EXCLUSIVE_LOCK ){
  32444. pFile->eFileLock = PENDING_LOCK;
  32445. pInode->eFileLock = PENDING_LOCK;
  32446. }
  32447. end_lock:
  32448. sqlite3_mutex_leave(pInode->pLockMutex);
  32449. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  32450. rc==SQLITE_OK ? "ok" : "failed"));
  32451. return rc;
  32452. }
  32453. /*
  32454. ** Add the file descriptor used by file handle pFile to the corresponding
  32455. ** pUnused list.
  32456. */
  32457. static void setPendingFd(unixFile *pFile){
  32458. unixInodeInfo *pInode = pFile->pInode;
  32459. UnixUnusedFd *p = pFile->pPreallocatedUnused;
  32460. assert( unixFileMutexHeld(pFile) );
  32461. p->pNext = pInode->pUnused;
  32462. pInode->pUnused = p;
  32463. pFile->h = -1;
  32464. pFile->pPreallocatedUnused = 0;
  32465. }
  32466. /*
  32467. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32468. ** must be either NO_LOCK or SHARED_LOCK.
  32469. **
  32470. ** If the locking level of the file descriptor is already at or below
  32471. ** the requested locking level, this routine is a no-op.
  32472. **
  32473. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  32474. ** the byte range is divided into 2 parts and the first part is unlocked then
  32475. ** set to a read lock, then the other part is simply unlocked. This works
  32476. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  32477. ** remove the write lock on a region when a read lock is set.
  32478. */
  32479. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  32480. unixFile *pFile = (unixFile*)id;
  32481. unixInodeInfo *pInode;
  32482. struct flock lock;
  32483. int rc = SQLITE_OK;
  32484. assert( pFile );
  32485. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  32486. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  32487. osGetpid(0)));
  32488. assert( eFileLock<=SHARED_LOCK );
  32489. if( pFile->eFileLock<=eFileLock ){
  32490. return SQLITE_OK;
  32491. }
  32492. pInode = pFile->pInode;
  32493. sqlite3_mutex_enter(pInode->pLockMutex);
  32494. assert( pInode->nShared!=0 );
  32495. if( pFile->eFileLock>SHARED_LOCK ){
  32496. assert( pInode->eFileLock==pFile->eFileLock );
  32497. #ifdef SQLITE_DEBUG
  32498. /* When reducing a lock such that other processes can start
  32499. ** reading the database file again, make sure that the
  32500. ** transaction counter was updated if any part of the database
  32501. ** file changed. If the transaction counter is not updated,
  32502. ** other connections to the same file might not realize that
  32503. ** the file has changed and hence might not know to flush their
  32504. ** cache. The use of a stale cache can lead to database corruption.
  32505. */
  32506. pFile->inNormalWrite = 0;
  32507. #endif
  32508. /* downgrading to a shared lock on NFS involves clearing the write lock
  32509. ** before establishing the readlock - to avoid a race condition we downgrade
  32510. ** the lock in 2 blocks, so that part of the range will be covered by a
  32511. ** write lock until the rest is covered by a read lock:
  32512. ** 1: [WWWWW]
  32513. ** 2: [....W]
  32514. ** 3: [RRRRW]
  32515. ** 4: [RRRR.]
  32516. */
  32517. if( eFileLock==SHARED_LOCK ){
  32518. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  32519. (void)handleNFSUnlock;
  32520. assert( handleNFSUnlock==0 );
  32521. #endif
  32522. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  32523. if( handleNFSUnlock ){
  32524. int tErrno; /* Error code from system call errors */
  32525. off_t divSize = SHARED_SIZE - 1;
  32526. lock.l_type = F_UNLCK;
  32527. lock.l_whence = SEEK_SET;
  32528. lock.l_start = SHARED_FIRST;
  32529. lock.l_len = divSize;
  32530. if( unixFileLock(pFile, &lock)==(-1) ){
  32531. tErrno = errno;
  32532. rc = SQLITE_IOERR_UNLOCK;
  32533. storeLastErrno(pFile, tErrno);
  32534. goto end_unlock;
  32535. }
  32536. lock.l_type = F_RDLCK;
  32537. lock.l_whence = SEEK_SET;
  32538. lock.l_start = SHARED_FIRST;
  32539. lock.l_len = divSize;
  32540. if( unixFileLock(pFile, &lock)==(-1) ){
  32541. tErrno = errno;
  32542. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  32543. if( IS_LOCK_ERROR(rc) ){
  32544. storeLastErrno(pFile, tErrno);
  32545. }
  32546. goto end_unlock;
  32547. }
  32548. lock.l_type = F_UNLCK;
  32549. lock.l_whence = SEEK_SET;
  32550. lock.l_start = SHARED_FIRST+divSize;
  32551. lock.l_len = SHARED_SIZE-divSize;
  32552. if( unixFileLock(pFile, &lock)==(-1) ){
  32553. tErrno = errno;
  32554. rc = SQLITE_IOERR_UNLOCK;
  32555. storeLastErrno(pFile, tErrno);
  32556. goto end_unlock;
  32557. }
  32558. }else
  32559. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  32560. {
  32561. lock.l_type = F_RDLCK;
  32562. lock.l_whence = SEEK_SET;
  32563. lock.l_start = SHARED_FIRST;
  32564. lock.l_len = SHARED_SIZE;
  32565. if( unixFileLock(pFile, &lock) ){
  32566. /* In theory, the call to unixFileLock() cannot fail because another
  32567. ** process is holding an incompatible lock. If it does, this
  32568. ** indicates that the other process is not following the locking
  32569. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  32570. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  32571. ** an assert to fail). */
  32572. rc = SQLITE_IOERR_RDLOCK;
  32573. storeLastErrno(pFile, errno);
  32574. goto end_unlock;
  32575. }
  32576. }
  32577. }
  32578. lock.l_type = F_UNLCK;
  32579. lock.l_whence = SEEK_SET;
  32580. lock.l_start = PENDING_BYTE;
  32581. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  32582. if( unixFileLock(pFile, &lock)==0 ){
  32583. pInode->eFileLock = SHARED_LOCK;
  32584. }else{
  32585. rc = SQLITE_IOERR_UNLOCK;
  32586. storeLastErrno(pFile, errno);
  32587. goto end_unlock;
  32588. }
  32589. }
  32590. if( eFileLock==NO_LOCK ){
  32591. /* Decrement the shared lock counter. Release the lock using an
  32592. ** OS call only when all threads in this same process have released
  32593. ** the lock.
  32594. */
  32595. pInode->nShared--;
  32596. if( pInode->nShared==0 ){
  32597. lock.l_type = F_UNLCK;
  32598. lock.l_whence = SEEK_SET;
  32599. lock.l_start = lock.l_len = 0L;
  32600. if( unixFileLock(pFile, &lock)==0 ){
  32601. pInode->eFileLock = NO_LOCK;
  32602. }else{
  32603. rc = SQLITE_IOERR_UNLOCK;
  32604. storeLastErrno(pFile, errno);
  32605. pInode->eFileLock = NO_LOCK;
  32606. pFile->eFileLock = NO_LOCK;
  32607. }
  32608. }
  32609. /* Decrement the count of locks against this same file. When the
  32610. ** count reaches zero, close any other file descriptors whose close
  32611. ** was deferred because of outstanding locks.
  32612. */
  32613. pInode->nLock--;
  32614. assert( pInode->nLock>=0 );
  32615. if( pInode->nLock==0 ) closePendingFds(pFile);
  32616. }
  32617. end_unlock:
  32618. sqlite3_mutex_leave(pInode->pLockMutex);
  32619. if( rc==SQLITE_OK ){
  32620. pFile->eFileLock = eFileLock;
  32621. }
  32622. return rc;
  32623. }
  32624. /*
  32625. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32626. ** must be either NO_LOCK or SHARED_LOCK.
  32627. **
  32628. ** If the locking level of the file descriptor is already at or below
  32629. ** the requested locking level, this routine is a no-op.
  32630. */
  32631. static int unixUnlock(sqlite3_file *id, int eFileLock){
  32632. #if SQLITE_MAX_MMAP_SIZE>0
  32633. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  32634. #endif
  32635. return posixUnlock(id, eFileLock, 0);
  32636. }
  32637. #if SQLITE_MAX_MMAP_SIZE>0
  32638. static int unixMapfile(unixFile *pFd, i64 nByte);
  32639. static void unixUnmapfile(unixFile *pFd);
  32640. #endif
  32641. /*
  32642. ** This function performs the parts of the "close file" operation
  32643. ** common to all locking schemes. It closes the directory and file
  32644. ** handles, if they are valid, and sets all fields of the unixFile
  32645. ** structure to 0.
  32646. **
  32647. ** It is *not* necessary to hold the mutex when this routine is called,
  32648. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  32649. ** vxworksReleaseFileId() routine.
  32650. */
  32651. static int closeUnixFile(sqlite3_file *id){
  32652. unixFile *pFile = (unixFile*)id;
  32653. #if SQLITE_MAX_MMAP_SIZE>0
  32654. unixUnmapfile(pFile);
  32655. #endif
  32656. if( pFile->h>=0 ){
  32657. robust_close(pFile, pFile->h, __LINE__);
  32658. pFile->h = -1;
  32659. }
  32660. #if OS_VXWORKS
  32661. if( pFile->pId ){
  32662. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  32663. osUnlink(pFile->pId->zCanonicalName);
  32664. }
  32665. vxworksReleaseFileId(pFile->pId);
  32666. pFile->pId = 0;
  32667. }
  32668. #endif
  32669. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  32670. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  32671. osUnlink(pFile->zPath);
  32672. sqlite3_free(*(char**)&pFile->zPath);
  32673. pFile->zPath = 0;
  32674. }
  32675. #endif
  32676. OSTRACE(("CLOSE %-3d\n", pFile->h));
  32677. OpenCounter(-1);
  32678. sqlite3_free(pFile->pPreallocatedUnused);
  32679. memset(pFile, 0, sizeof(unixFile));
  32680. return SQLITE_OK;
  32681. }
  32682. /*
  32683. ** Close a file.
  32684. */
  32685. static int unixClose(sqlite3_file *id){
  32686. int rc = SQLITE_OK;
  32687. unixFile *pFile = (unixFile *)id;
  32688. unixInodeInfo *pInode = pFile->pInode;
  32689. assert( pInode!=0 );
  32690. verifyDbFile(pFile);
  32691. unixUnlock(id, NO_LOCK);
  32692. assert( unixFileMutexNotheld(pFile) );
  32693. unixEnterMutex();
  32694. /* unixFile.pInode is always valid here. Otherwise, a different close
  32695. ** routine (e.g. nolockClose()) would be called instead.
  32696. */
  32697. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  32698. sqlite3_mutex_enter(pInode->pLockMutex);
  32699. if( pInode->nLock ){
  32700. /* If there are outstanding locks, do not actually close the file just
  32701. ** yet because that would clear those locks. Instead, add the file
  32702. ** descriptor to pInode->pUnused list. It will be automatically closed
  32703. ** when the last lock is cleared.
  32704. */
  32705. setPendingFd(pFile);
  32706. }
  32707. sqlite3_mutex_leave(pInode->pLockMutex);
  32708. releaseInodeInfo(pFile);
  32709. rc = closeUnixFile(id);
  32710. unixLeaveMutex();
  32711. return rc;
  32712. }
  32713. /************** End of the posix advisory lock implementation *****************
  32714. ******************************************************************************/
  32715. /******************************************************************************
  32716. ****************************** No-op Locking **********************************
  32717. **
  32718. ** Of the various locking implementations available, this is by far the
  32719. ** simplest: locking is ignored. No attempt is made to lock the database
  32720. ** file for reading or writing.
  32721. **
  32722. ** This locking mode is appropriate for use on read-only databases
  32723. ** (ex: databases that are burned into CD-ROM, for example.) It can
  32724. ** also be used if the application employs some external mechanism to
  32725. ** prevent simultaneous access of the same database by two or more
  32726. ** database connections. But there is a serious risk of database
  32727. ** corruption if this locking mode is used in situations where multiple
  32728. ** database connections are accessing the same database file at the same
  32729. ** time and one or more of those connections are writing.
  32730. */
  32731. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  32732. UNUSED_PARAMETER(NotUsed);
  32733. *pResOut = 0;
  32734. return SQLITE_OK;
  32735. }
  32736. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  32737. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  32738. return SQLITE_OK;
  32739. }
  32740. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  32741. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  32742. return SQLITE_OK;
  32743. }
  32744. /*
  32745. ** Close the file.
  32746. */
  32747. static int nolockClose(sqlite3_file *id) {
  32748. return closeUnixFile(id);
  32749. }
  32750. /******************* End of the no-op lock implementation *********************
  32751. ******************************************************************************/
  32752. /******************************************************************************
  32753. ************************* Begin dot-file Locking ******************************
  32754. **
  32755. ** The dotfile locking implementation uses the existence of separate lock
  32756. ** files (really a directory) to control access to the database. This works
  32757. ** on just about every filesystem imaginable. But there are serious downsides:
  32758. **
  32759. ** (1) There is zero concurrency. A single reader blocks all other
  32760. ** connections from reading or writing the database.
  32761. **
  32762. ** (2) An application crash or power loss can leave stale lock files
  32763. ** sitting around that need to be cleared manually.
  32764. **
  32765. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  32766. ** other locking strategy is available.
  32767. **
  32768. ** Dotfile locking works by creating a subdirectory in the same directory as
  32769. ** the database and with the same name but with a ".lock" extension added.
  32770. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  32771. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  32772. */
  32773. /*
  32774. ** The file suffix added to the data base filename in order to create the
  32775. ** lock directory.
  32776. */
  32777. #define DOTLOCK_SUFFIX ".lock"
  32778. /*
  32779. ** This routine checks if there is a RESERVED lock held on the specified
  32780. ** file by this or any other process. If such a lock is held, set *pResOut
  32781. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32782. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32783. **
  32784. ** In dotfile locking, either a lock exists or it does not. So in this
  32785. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  32786. ** is held on the file and false if the file is unlocked.
  32787. */
  32788. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  32789. int rc = SQLITE_OK;
  32790. int reserved = 0;
  32791. unixFile *pFile = (unixFile*)id;
  32792. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32793. assert( pFile );
  32794. reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
  32795. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  32796. *pResOut = reserved;
  32797. return rc;
  32798. }
  32799. /*
  32800. ** Lock the file with the lock specified by parameter eFileLock - one
  32801. ** of the following:
  32802. **
  32803. ** (1) SHARED_LOCK
  32804. ** (2) RESERVED_LOCK
  32805. ** (3) PENDING_LOCK
  32806. ** (4) EXCLUSIVE_LOCK
  32807. **
  32808. ** Sometimes when requesting one lock state, additional lock states
  32809. ** are inserted in between. The locking might fail on one of the later
  32810. ** transitions leaving the lock state different from what it started but
  32811. ** still short of its goal. The following chart shows the allowed
  32812. ** transitions and the inserted intermediate states:
  32813. **
  32814. ** UNLOCKED -> SHARED
  32815. ** SHARED -> RESERVED
  32816. ** SHARED -> (PENDING) -> EXCLUSIVE
  32817. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32818. ** PENDING -> EXCLUSIVE
  32819. **
  32820. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32821. ** routine to lower a locking level.
  32822. **
  32823. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  32824. ** But we track the other locking levels internally.
  32825. */
  32826. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  32827. unixFile *pFile = (unixFile*)id;
  32828. char *zLockFile = (char *)pFile->lockingContext;
  32829. int rc = SQLITE_OK;
  32830. /* If we have any lock, then the lock file already exists. All we have
  32831. ** to do is adjust our internal record of the lock level.
  32832. */
  32833. if( pFile->eFileLock > NO_LOCK ){
  32834. pFile->eFileLock = eFileLock;
  32835. /* Always update the timestamp on the old file */
  32836. #ifdef HAVE_UTIME
  32837. utime(zLockFile, NULL);
  32838. #else
  32839. utimes(zLockFile, NULL);
  32840. #endif
  32841. return SQLITE_OK;
  32842. }
  32843. /* grab an exclusive lock */
  32844. rc = osMkdir(zLockFile, 0777);
  32845. if( rc<0 ){
  32846. /* failed to open/create the lock directory */
  32847. int tErrno = errno;
  32848. if( EEXIST == tErrno ){
  32849. rc = SQLITE_BUSY;
  32850. } else {
  32851. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32852. if( rc!=SQLITE_BUSY ){
  32853. storeLastErrno(pFile, tErrno);
  32854. }
  32855. }
  32856. return rc;
  32857. }
  32858. /* got it, set the type and return ok */
  32859. pFile->eFileLock = eFileLock;
  32860. return rc;
  32861. }
  32862. /*
  32863. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32864. ** must be either NO_LOCK or SHARED_LOCK.
  32865. **
  32866. ** If the locking level of the file descriptor is already at or below
  32867. ** the requested locking level, this routine is a no-op.
  32868. **
  32869. ** When the locking level reaches NO_LOCK, delete the lock file.
  32870. */
  32871. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  32872. unixFile *pFile = (unixFile*)id;
  32873. char *zLockFile = (char *)pFile->lockingContext;
  32874. int rc;
  32875. assert( pFile );
  32876. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  32877. pFile->eFileLock, osGetpid(0)));
  32878. assert( eFileLock<=SHARED_LOCK );
  32879. /* no-op if possible */
  32880. if( pFile->eFileLock==eFileLock ){
  32881. return SQLITE_OK;
  32882. }
  32883. /* To downgrade to shared, simply update our internal notion of the
  32884. ** lock state. No need to mess with the file on disk.
  32885. */
  32886. if( eFileLock==SHARED_LOCK ){
  32887. pFile->eFileLock = SHARED_LOCK;
  32888. return SQLITE_OK;
  32889. }
  32890. /* To fully unlock the database, delete the lock file */
  32891. assert( eFileLock==NO_LOCK );
  32892. rc = osRmdir(zLockFile);
  32893. if( rc<0 ){
  32894. int tErrno = errno;
  32895. if( tErrno==ENOENT ){
  32896. rc = SQLITE_OK;
  32897. }else{
  32898. rc = SQLITE_IOERR_UNLOCK;
  32899. storeLastErrno(pFile, tErrno);
  32900. }
  32901. return rc;
  32902. }
  32903. pFile->eFileLock = NO_LOCK;
  32904. return SQLITE_OK;
  32905. }
  32906. /*
  32907. ** Close a file. Make sure the lock has been released before closing.
  32908. */
  32909. static int dotlockClose(sqlite3_file *id) {
  32910. unixFile *pFile = (unixFile*)id;
  32911. assert( id!=0 );
  32912. dotlockUnlock(id, NO_LOCK);
  32913. sqlite3_free(pFile->lockingContext);
  32914. return closeUnixFile(id);
  32915. }
  32916. /****************** End of the dot-file lock implementation *******************
  32917. ******************************************************************************/
  32918. /******************************************************************************
  32919. ************************** Begin flock Locking ********************************
  32920. **
  32921. ** Use the flock() system call to do file locking.
  32922. **
  32923. ** flock() locking is like dot-file locking in that the various
  32924. ** fine-grain locking levels supported by SQLite are collapsed into
  32925. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  32926. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  32927. ** still works when you do this, but concurrency is reduced since
  32928. ** only a single process can be reading the database at a time.
  32929. **
  32930. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  32931. */
  32932. #if SQLITE_ENABLE_LOCKING_STYLE
  32933. /*
  32934. ** Retry flock() calls that fail with EINTR
  32935. */
  32936. #ifdef EINTR
  32937. static int robust_flock(int fd, int op){
  32938. int rc;
  32939. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  32940. return rc;
  32941. }
  32942. #else
  32943. # define robust_flock(a,b) flock(a,b)
  32944. #endif
  32945. /*
  32946. ** This routine checks if there is a RESERVED lock held on the specified
  32947. ** file by this or any other process. If such a lock is held, set *pResOut
  32948. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32949. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32950. */
  32951. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  32952. int rc = SQLITE_OK;
  32953. int reserved = 0;
  32954. unixFile *pFile = (unixFile*)id;
  32955. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32956. assert( pFile );
  32957. /* Check if a thread in this process holds such a lock */
  32958. if( pFile->eFileLock>SHARED_LOCK ){
  32959. reserved = 1;
  32960. }
  32961. /* Otherwise see if some other process holds it. */
  32962. if( !reserved ){
  32963. /* attempt to get the lock */
  32964. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  32965. if( !lrc ){
  32966. /* got the lock, unlock it */
  32967. lrc = robust_flock(pFile->h, LOCK_UN);
  32968. if ( lrc ) {
  32969. int tErrno = errno;
  32970. /* unlock failed with an error */
  32971. lrc = SQLITE_IOERR_UNLOCK;
  32972. storeLastErrno(pFile, tErrno);
  32973. rc = lrc;
  32974. }
  32975. } else {
  32976. int tErrno = errno;
  32977. reserved = 1;
  32978. /* someone else might have it reserved */
  32979. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32980. if( IS_LOCK_ERROR(lrc) ){
  32981. storeLastErrno(pFile, tErrno);
  32982. rc = lrc;
  32983. }
  32984. }
  32985. }
  32986. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  32987. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  32988. if( (rc & 0xff) == SQLITE_IOERR ){
  32989. rc = SQLITE_OK;
  32990. reserved=1;
  32991. }
  32992. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  32993. *pResOut = reserved;
  32994. return rc;
  32995. }
  32996. /*
  32997. ** Lock the file with the lock specified by parameter eFileLock - one
  32998. ** of the following:
  32999. **
  33000. ** (1) SHARED_LOCK
  33001. ** (2) RESERVED_LOCK
  33002. ** (3) PENDING_LOCK
  33003. ** (4) EXCLUSIVE_LOCK
  33004. **
  33005. ** Sometimes when requesting one lock state, additional lock states
  33006. ** are inserted in between. The locking might fail on one of the later
  33007. ** transitions leaving the lock state different from what it started but
  33008. ** still short of its goal. The following chart shows the allowed
  33009. ** transitions and the inserted intermediate states:
  33010. **
  33011. ** UNLOCKED -> SHARED
  33012. ** SHARED -> RESERVED
  33013. ** SHARED -> (PENDING) -> EXCLUSIVE
  33014. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33015. ** PENDING -> EXCLUSIVE
  33016. **
  33017. ** flock() only really support EXCLUSIVE locks. We track intermediate
  33018. ** lock states in the sqlite3_file structure, but all locks SHARED or
  33019. ** above are really EXCLUSIVE locks and exclude all other processes from
  33020. ** access the file.
  33021. **
  33022. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33023. ** routine to lower a locking level.
  33024. */
  33025. static int flockLock(sqlite3_file *id, int eFileLock) {
  33026. int rc = SQLITE_OK;
  33027. unixFile *pFile = (unixFile*)id;
  33028. assert( pFile );
  33029. /* if we already have a lock, it is exclusive.
  33030. ** Just adjust level and punt on outta here. */
  33031. if (pFile->eFileLock > NO_LOCK) {
  33032. pFile->eFileLock = eFileLock;
  33033. return SQLITE_OK;
  33034. }
  33035. /* grab an exclusive lock */
  33036. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  33037. int tErrno = errno;
  33038. /* didn't get, must be busy */
  33039. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  33040. if( IS_LOCK_ERROR(rc) ){
  33041. storeLastErrno(pFile, tErrno);
  33042. }
  33043. } else {
  33044. /* got it, set the type and return ok */
  33045. pFile->eFileLock = eFileLock;
  33046. }
  33047. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  33048. rc==SQLITE_OK ? "ok" : "failed"));
  33049. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  33050. if( (rc & 0xff) == SQLITE_IOERR ){
  33051. rc = SQLITE_BUSY;
  33052. }
  33053. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  33054. return rc;
  33055. }
  33056. /*
  33057. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33058. ** must be either NO_LOCK or SHARED_LOCK.
  33059. **
  33060. ** If the locking level of the file descriptor is already at or below
  33061. ** the requested locking level, this routine is a no-op.
  33062. */
  33063. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  33064. unixFile *pFile = (unixFile*)id;
  33065. assert( pFile );
  33066. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  33067. pFile->eFileLock, osGetpid(0)));
  33068. assert( eFileLock<=SHARED_LOCK );
  33069. /* no-op if possible */
  33070. if( pFile->eFileLock==eFileLock ){
  33071. return SQLITE_OK;
  33072. }
  33073. /* shared can just be set because we always have an exclusive */
  33074. if (eFileLock==SHARED_LOCK) {
  33075. pFile->eFileLock = eFileLock;
  33076. return SQLITE_OK;
  33077. }
  33078. /* no, really, unlock. */
  33079. if( robust_flock(pFile->h, LOCK_UN) ){
  33080. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  33081. return SQLITE_OK;
  33082. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  33083. return SQLITE_IOERR_UNLOCK;
  33084. }else{
  33085. pFile->eFileLock = NO_LOCK;
  33086. return SQLITE_OK;
  33087. }
  33088. }
  33089. /*
  33090. ** Close a file.
  33091. */
  33092. static int flockClose(sqlite3_file *id) {
  33093. assert( id!=0 );
  33094. flockUnlock(id, NO_LOCK);
  33095. return closeUnixFile(id);
  33096. }
  33097. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  33098. /******************* End of the flock lock implementation *********************
  33099. ******************************************************************************/
  33100. /******************************************************************************
  33101. ************************ Begin Named Semaphore Locking ************************
  33102. **
  33103. ** Named semaphore locking is only supported on VxWorks.
  33104. **
  33105. ** Semaphore locking is like dot-lock and flock in that it really only
  33106. ** supports EXCLUSIVE locking. Only a single process can read or write
  33107. ** the database file at a time. This reduces potential concurrency, but
  33108. ** makes the lock implementation much easier.
  33109. */
  33110. #if OS_VXWORKS
  33111. /*
  33112. ** This routine checks if there is a RESERVED lock held on the specified
  33113. ** file by this or any other process. If such a lock is held, set *pResOut
  33114. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  33115. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  33116. */
  33117. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  33118. int rc = SQLITE_OK;
  33119. int reserved = 0;
  33120. unixFile *pFile = (unixFile*)id;
  33121. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33122. assert( pFile );
  33123. /* Check if a thread in this process holds such a lock */
  33124. if( pFile->eFileLock>SHARED_LOCK ){
  33125. reserved = 1;
  33126. }
  33127. /* Otherwise see if some other process holds it. */
  33128. if( !reserved ){
  33129. sem_t *pSem = pFile->pInode->pSem;
  33130. if( sem_trywait(pSem)==-1 ){
  33131. int tErrno = errno;
  33132. if( EAGAIN != tErrno ){
  33133. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  33134. storeLastErrno(pFile, tErrno);
  33135. } else {
  33136. /* someone else has the lock when we are in NO_LOCK */
  33137. reserved = (pFile->eFileLock < SHARED_LOCK);
  33138. }
  33139. }else{
  33140. /* we could have it if we want it */
  33141. sem_post(pSem);
  33142. }
  33143. }
  33144. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  33145. *pResOut = reserved;
  33146. return rc;
  33147. }
  33148. /*
  33149. ** Lock the file with the lock specified by parameter eFileLock - one
  33150. ** of the following:
  33151. **
  33152. ** (1) SHARED_LOCK
  33153. ** (2) RESERVED_LOCK
  33154. ** (3) PENDING_LOCK
  33155. ** (4) EXCLUSIVE_LOCK
  33156. **
  33157. ** Sometimes when requesting one lock state, additional lock states
  33158. ** are inserted in between. The locking might fail on one of the later
  33159. ** transitions leaving the lock state different from what it started but
  33160. ** still short of its goal. The following chart shows the allowed
  33161. ** transitions and the inserted intermediate states:
  33162. **
  33163. ** UNLOCKED -> SHARED
  33164. ** SHARED -> RESERVED
  33165. ** SHARED -> (PENDING) -> EXCLUSIVE
  33166. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33167. ** PENDING -> EXCLUSIVE
  33168. **
  33169. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  33170. ** lock states in the sqlite3_file structure, but all locks SHARED or
  33171. ** above are really EXCLUSIVE locks and exclude all other processes from
  33172. ** access the file.
  33173. **
  33174. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33175. ** routine to lower a locking level.
  33176. */
  33177. static int semXLock(sqlite3_file *id, int eFileLock) {
  33178. unixFile *pFile = (unixFile*)id;
  33179. sem_t *pSem = pFile->pInode->pSem;
  33180. int rc = SQLITE_OK;
  33181. /* if we already have a lock, it is exclusive.
  33182. ** Just adjust level and punt on outta here. */
  33183. if (pFile->eFileLock > NO_LOCK) {
  33184. pFile->eFileLock = eFileLock;
  33185. rc = SQLITE_OK;
  33186. goto sem_end_lock;
  33187. }
  33188. /* lock semaphore now but bail out when already locked. */
  33189. if( sem_trywait(pSem)==-1 ){
  33190. rc = SQLITE_BUSY;
  33191. goto sem_end_lock;
  33192. }
  33193. /* got it, set the type and return ok */
  33194. pFile->eFileLock = eFileLock;
  33195. sem_end_lock:
  33196. return rc;
  33197. }
  33198. /*
  33199. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33200. ** must be either NO_LOCK or SHARED_LOCK.
  33201. **
  33202. ** If the locking level of the file descriptor is already at or below
  33203. ** the requested locking level, this routine is a no-op.
  33204. */
  33205. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  33206. unixFile *pFile = (unixFile*)id;
  33207. sem_t *pSem = pFile->pInode->pSem;
  33208. assert( pFile );
  33209. assert( pSem );
  33210. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  33211. pFile->eFileLock, osGetpid(0)));
  33212. assert( eFileLock<=SHARED_LOCK );
  33213. /* no-op if possible */
  33214. if( pFile->eFileLock==eFileLock ){
  33215. return SQLITE_OK;
  33216. }
  33217. /* shared can just be set because we always have an exclusive */
  33218. if (eFileLock==SHARED_LOCK) {
  33219. pFile->eFileLock = eFileLock;
  33220. return SQLITE_OK;
  33221. }
  33222. /* no, really unlock. */
  33223. if ( sem_post(pSem)==-1 ) {
  33224. int rc, tErrno = errno;
  33225. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  33226. if( IS_LOCK_ERROR(rc) ){
  33227. storeLastErrno(pFile, tErrno);
  33228. }
  33229. return rc;
  33230. }
  33231. pFile->eFileLock = NO_LOCK;
  33232. return SQLITE_OK;
  33233. }
  33234. /*
  33235. ** Close a file.
  33236. */
  33237. static int semXClose(sqlite3_file *id) {
  33238. if( id ){
  33239. unixFile *pFile = (unixFile*)id;
  33240. semXUnlock(id, NO_LOCK);
  33241. assert( pFile );
  33242. assert( unixFileMutexNotheld(pFile) );
  33243. unixEnterMutex();
  33244. releaseInodeInfo(pFile);
  33245. unixLeaveMutex();
  33246. closeUnixFile(id);
  33247. }
  33248. return SQLITE_OK;
  33249. }
  33250. #endif /* OS_VXWORKS */
  33251. /*
  33252. ** Named semaphore locking is only available on VxWorks.
  33253. **
  33254. *************** End of the named semaphore lock implementation ****************
  33255. ******************************************************************************/
  33256. /******************************************************************************
  33257. *************************** Begin AFP Locking *********************************
  33258. **
  33259. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  33260. ** on Apple Macintosh computers - both OS9 and OSX.
  33261. **
  33262. ** Third-party implementations of AFP are available. But this code here
  33263. ** only works on OSX.
  33264. */
  33265. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33266. /*
  33267. ** The afpLockingContext structure contains all afp lock specific state
  33268. */
  33269. typedef struct afpLockingContext afpLockingContext;
  33270. struct afpLockingContext {
  33271. int reserved;
  33272. const char *dbPath; /* Name of the open file */
  33273. };
  33274. struct ByteRangeLockPB2
  33275. {
  33276. unsigned long long offset; /* offset to first byte to lock */
  33277. unsigned long long length; /* nbr of bytes to lock */
  33278. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  33279. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  33280. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  33281. int fd; /* file desc to assoc this lock with */
  33282. };
  33283. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  33284. /*
  33285. ** This is a utility for setting or clearing a bit-range lock on an
  33286. ** AFP filesystem.
  33287. **
  33288. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  33289. */
  33290. static int afpSetLock(
  33291. const char *path, /* Name of the file to be locked or unlocked */
  33292. unixFile *pFile, /* Open file descriptor on path */
  33293. unsigned long long offset, /* First byte to be locked */
  33294. unsigned long long length, /* Number of bytes to lock */
  33295. int setLockFlag /* True to set lock. False to clear lock */
  33296. ){
  33297. struct ByteRangeLockPB2 pb;
  33298. int err;
  33299. pb.unLockFlag = setLockFlag ? 0 : 1;
  33300. pb.startEndFlag = 0;
  33301. pb.offset = offset;
  33302. pb.length = length;
  33303. pb.fd = pFile->h;
  33304. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  33305. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  33306. offset, length));
  33307. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  33308. if ( err==-1 ) {
  33309. int rc;
  33310. int tErrno = errno;
  33311. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  33312. path, tErrno, strerror(tErrno)));
  33313. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  33314. rc = SQLITE_BUSY;
  33315. #else
  33316. rc = sqliteErrorFromPosixError(tErrno,
  33317. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  33318. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  33319. if( IS_LOCK_ERROR(rc) ){
  33320. storeLastErrno(pFile, tErrno);
  33321. }
  33322. return rc;
  33323. } else {
  33324. return SQLITE_OK;
  33325. }
  33326. }
  33327. /*
  33328. ** This routine checks if there is a RESERVED lock held on the specified
  33329. ** file by this or any other process. If such a lock is held, set *pResOut
  33330. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  33331. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  33332. */
  33333. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  33334. int rc = SQLITE_OK;
  33335. int reserved = 0;
  33336. unixFile *pFile = (unixFile*)id;
  33337. afpLockingContext *context;
  33338. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33339. assert( pFile );
  33340. context = (afpLockingContext *) pFile->lockingContext;
  33341. if( context->reserved ){
  33342. *pResOut = 1;
  33343. return SQLITE_OK;
  33344. }
  33345. sqlite3_mutex_enter(pFile->pInode->pLockMutex);
  33346. /* Check if a thread in this process holds such a lock */
  33347. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  33348. reserved = 1;
  33349. }
  33350. /* Otherwise see if some other process holds it.
  33351. */
  33352. if( !reserved ){
  33353. /* lock the RESERVED byte */
  33354. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  33355. if( SQLITE_OK==lrc ){
  33356. /* if we succeeded in taking the reserved lock, unlock it to restore
  33357. ** the original state */
  33358. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  33359. } else {
  33360. /* if we failed to get the lock then someone else must have it */
  33361. reserved = 1;
  33362. }
  33363. if( IS_LOCK_ERROR(lrc) ){
  33364. rc=lrc;
  33365. }
  33366. }
  33367. sqlite3_mutex_leave(pFile->pInode->pLockMutex);
  33368. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  33369. *pResOut = reserved;
  33370. return rc;
  33371. }
  33372. /*
  33373. ** Lock the file with the lock specified by parameter eFileLock - one
  33374. ** of the following:
  33375. **
  33376. ** (1) SHARED_LOCK
  33377. ** (2) RESERVED_LOCK
  33378. ** (3) PENDING_LOCK
  33379. ** (4) EXCLUSIVE_LOCK
  33380. **
  33381. ** Sometimes when requesting one lock state, additional lock states
  33382. ** are inserted in between. The locking might fail on one of the later
  33383. ** transitions leaving the lock state different from what it started but
  33384. ** still short of its goal. The following chart shows the allowed
  33385. ** transitions and the inserted intermediate states:
  33386. **
  33387. ** UNLOCKED -> SHARED
  33388. ** SHARED -> RESERVED
  33389. ** SHARED -> (PENDING) -> EXCLUSIVE
  33390. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33391. ** PENDING -> EXCLUSIVE
  33392. **
  33393. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33394. ** routine to lower a locking level.
  33395. */
  33396. static int afpLock(sqlite3_file *id, int eFileLock){
  33397. int rc = SQLITE_OK;
  33398. unixFile *pFile = (unixFile*)id;
  33399. unixInodeInfo *pInode = pFile->pInode;
  33400. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  33401. assert( pFile );
  33402. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  33403. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  33404. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  33405. /* If there is already a lock of this type or more restrictive on the
  33406. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  33407. ** unixEnterMutex() hasn't been called yet.
  33408. */
  33409. if( pFile->eFileLock>=eFileLock ){
  33410. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  33411. azFileLock(eFileLock)));
  33412. return SQLITE_OK;
  33413. }
  33414. /* Make sure the locking sequence is correct
  33415. ** (1) We never move from unlocked to anything higher than shared lock.
  33416. ** (2) SQLite never explicitly requests a pendig lock.
  33417. ** (3) A shared lock is always held when a reserve lock is requested.
  33418. */
  33419. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  33420. assert( eFileLock!=PENDING_LOCK );
  33421. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  33422. /* This mutex is needed because pFile->pInode is shared across threads
  33423. */
  33424. pInode = pFile->pInode;
  33425. sqlite3_mutex_enter(pInode->pLockMutex);
  33426. /* If some thread using this PID has a lock via a different unixFile*
  33427. ** handle that precludes the requested lock, return BUSY.
  33428. */
  33429. if( (pFile->eFileLock!=pInode->eFileLock &&
  33430. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  33431. ){
  33432. rc = SQLITE_BUSY;
  33433. goto afp_end_lock;
  33434. }
  33435. /* If a SHARED lock is requested, and some thread using this PID already
  33436. ** has a SHARED or RESERVED lock, then increment reference counts and
  33437. ** return SQLITE_OK.
  33438. */
  33439. if( eFileLock==SHARED_LOCK &&
  33440. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  33441. assert( eFileLock==SHARED_LOCK );
  33442. assert( pFile->eFileLock==0 );
  33443. assert( pInode->nShared>0 );
  33444. pFile->eFileLock = SHARED_LOCK;
  33445. pInode->nShared++;
  33446. pInode->nLock++;
  33447. goto afp_end_lock;
  33448. }
  33449. /* A PENDING lock is needed before acquiring a SHARED lock and before
  33450. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  33451. ** be released.
  33452. */
  33453. if( eFileLock==SHARED_LOCK
  33454. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  33455. ){
  33456. int failed;
  33457. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  33458. if (failed) {
  33459. rc = failed;
  33460. goto afp_end_lock;
  33461. }
  33462. }
  33463. /* If control gets to this point, then actually go ahead and make
  33464. ** operating system calls for the specified lock.
  33465. */
  33466. if( eFileLock==SHARED_LOCK ){
  33467. int lrc1, lrc2, lrc1Errno = 0;
  33468. long lk, mask;
  33469. assert( pInode->nShared==0 );
  33470. assert( pInode->eFileLock==0 );
  33471. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  33472. /* Now get the read-lock SHARED_LOCK */
  33473. /* note that the quality of the randomness doesn't matter that much */
  33474. lk = random();
  33475. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  33476. lrc1 = afpSetLock(context->dbPath, pFile,
  33477. SHARED_FIRST+pInode->sharedByte, 1, 1);
  33478. if( IS_LOCK_ERROR(lrc1) ){
  33479. lrc1Errno = pFile->lastErrno;
  33480. }
  33481. /* Drop the temporary PENDING lock */
  33482. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  33483. if( IS_LOCK_ERROR(lrc1) ) {
  33484. storeLastErrno(pFile, lrc1Errno);
  33485. rc = lrc1;
  33486. goto afp_end_lock;
  33487. } else if( IS_LOCK_ERROR(lrc2) ){
  33488. rc = lrc2;
  33489. goto afp_end_lock;
  33490. } else if( lrc1 != SQLITE_OK ) {
  33491. rc = lrc1;
  33492. } else {
  33493. pFile->eFileLock = SHARED_LOCK;
  33494. pInode->nLock++;
  33495. pInode->nShared = 1;
  33496. }
  33497. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  33498. /* We are trying for an exclusive lock but another thread in this
  33499. ** same process is still holding a shared lock. */
  33500. rc = SQLITE_BUSY;
  33501. }else{
  33502. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  33503. ** assumed that there is a SHARED or greater lock on the file
  33504. ** already.
  33505. */
  33506. int failed = 0;
  33507. assert( 0!=pFile->eFileLock );
  33508. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  33509. /* Acquire a RESERVED lock */
  33510. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  33511. if( !failed ){
  33512. context->reserved = 1;
  33513. }
  33514. }
  33515. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  33516. /* Acquire an EXCLUSIVE lock */
  33517. /* Remove the shared lock before trying the range. we'll need to
  33518. ** reestablish the shared lock if we can't get the afpUnlock
  33519. */
  33520. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  33521. pInode->sharedByte, 1, 0)) ){
  33522. int failed2 = SQLITE_OK;
  33523. /* now attemmpt to get the exclusive lock range */
  33524. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  33525. SHARED_SIZE, 1);
  33526. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  33527. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  33528. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  33529. ** a critical I/O error
  33530. */
  33531. rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
  33532. SQLITE_IOERR_LOCK;
  33533. goto afp_end_lock;
  33534. }
  33535. }else{
  33536. rc = failed;
  33537. }
  33538. }
  33539. if( failed ){
  33540. rc = failed;
  33541. }
  33542. }
  33543. if( rc==SQLITE_OK ){
  33544. pFile->eFileLock = eFileLock;
  33545. pInode->eFileLock = eFileLock;
  33546. }else if( eFileLock==EXCLUSIVE_LOCK ){
  33547. pFile->eFileLock = PENDING_LOCK;
  33548. pInode->eFileLock = PENDING_LOCK;
  33549. }
  33550. afp_end_lock:
  33551. sqlite3_mutex_leave(pInode->pLockMutex);
  33552. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  33553. rc==SQLITE_OK ? "ok" : "failed"));
  33554. return rc;
  33555. }
  33556. /*
  33557. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33558. ** must be either NO_LOCK or SHARED_LOCK.
  33559. **
  33560. ** If the locking level of the file descriptor is already at or below
  33561. ** the requested locking level, this routine is a no-op.
  33562. */
  33563. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  33564. int rc = SQLITE_OK;
  33565. unixFile *pFile = (unixFile*)id;
  33566. unixInodeInfo *pInode;
  33567. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  33568. int skipShared = 0;
  33569. #ifdef SQLITE_TEST
  33570. int h = pFile->h;
  33571. #endif
  33572. assert( pFile );
  33573. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  33574. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  33575. osGetpid(0)));
  33576. assert( eFileLock<=SHARED_LOCK );
  33577. if( pFile->eFileLock<=eFileLock ){
  33578. return SQLITE_OK;
  33579. }
  33580. pInode = pFile->pInode;
  33581. sqlite3_mutex_enter(pInode->pLockMutex);
  33582. assert( pInode->nShared!=0 );
  33583. if( pFile->eFileLock>SHARED_LOCK ){
  33584. assert( pInode->eFileLock==pFile->eFileLock );
  33585. SimulateIOErrorBenign(1);
  33586. SimulateIOError( h=(-1) )
  33587. SimulateIOErrorBenign(0);
  33588. #ifdef SQLITE_DEBUG
  33589. /* When reducing a lock such that other processes can start
  33590. ** reading the database file again, make sure that the
  33591. ** transaction counter was updated if any part of the database
  33592. ** file changed. If the transaction counter is not updated,
  33593. ** other connections to the same file might not realize that
  33594. ** the file has changed and hence might not know to flush their
  33595. ** cache. The use of a stale cache can lead to database corruption.
  33596. */
  33597. assert( pFile->inNormalWrite==0
  33598. || pFile->dbUpdate==0
  33599. || pFile->transCntrChng==1 );
  33600. pFile->inNormalWrite = 0;
  33601. #endif
  33602. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  33603. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  33604. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  33605. /* only re-establish the shared lock if necessary */
  33606. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  33607. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  33608. } else {
  33609. skipShared = 1;
  33610. }
  33611. }
  33612. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  33613. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  33614. }
  33615. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  33616. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  33617. if( !rc ){
  33618. context->reserved = 0;
  33619. }
  33620. }
  33621. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  33622. pInode->eFileLock = SHARED_LOCK;
  33623. }
  33624. }
  33625. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  33626. /* Decrement the shared lock counter. Release the lock using an
  33627. ** OS call only when all threads in this same process have released
  33628. ** the lock.
  33629. */
  33630. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  33631. pInode->nShared--;
  33632. if( pInode->nShared==0 ){
  33633. SimulateIOErrorBenign(1);
  33634. SimulateIOError( h=(-1) )
  33635. SimulateIOErrorBenign(0);
  33636. if( !skipShared ){
  33637. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  33638. }
  33639. if( !rc ){
  33640. pInode->eFileLock = NO_LOCK;
  33641. pFile->eFileLock = NO_LOCK;
  33642. }
  33643. }
  33644. if( rc==SQLITE_OK ){
  33645. pInode->nLock--;
  33646. assert( pInode->nLock>=0 );
  33647. if( pInode->nLock==0 ) closePendingFds(pFile);
  33648. }
  33649. }
  33650. sqlite3_mutex_leave(pInode->pLockMutex);
  33651. if( rc==SQLITE_OK ){
  33652. pFile->eFileLock = eFileLock;
  33653. }
  33654. return rc;
  33655. }
  33656. /*
  33657. ** Close a file & cleanup AFP specific locking context
  33658. */
  33659. static int afpClose(sqlite3_file *id) {
  33660. int rc = SQLITE_OK;
  33661. unixFile *pFile = (unixFile*)id;
  33662. assert( id!=0 );
  33663. afpUnlock(id, NO_LOCK);
  33664. assert( unixFileMutexNotheld(pFile) );
  33665. unixEnterMutex();
  33666. if( pFile->pInode ){
  33667. unixInodeInfo *pInode = pFile->pInode;
  33668. sqlite3_mutex_enter(pInode->pLockMutex);
  33669. if( pInode->nLock ){
  33670. /* If there are outstanding locks, do not actually close the file just
  33671. ** yet because that would clear those locks. Instead, add the file
  33672. ** descriptor to pInode->aPending. It will be automatically closed when
  33673. ** the last lock is cleared.
  33674. */
  33675. setPendingFd(pFile);
  33676. }
  33677. sqlite3_mutex_leave(pInode->pLockMutex);
  33678. }
  33679. releaseInodeInfo(pFile);
  33680. sqlite3_free(pFile->lockingContext);
  33681. rc = closeUnixFile(id);
  33682. unixLeaveMutex();
  33683. return rc;
  33684. }
  33685. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  33686. /*
  33687. ** The code above is the AFP lock implementation. The code is specific
  33688. ** to MacOSX and does not work on other unix platforms. No alternative
  33689. ** is available. If you don't compile for a mac, then the "unix-afp"
  33690. ** VFS is not available.
  33691. **
  33692. ********************* End of the AFP lock implementation **********************
  33693. ******************************************************************************/
  33694. /******************************************************************************
  33695. *************************** Begin NFS Locking ********************************/
  33696. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33697. /*
  33698. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33699. ** must be either NO_LOCK or SHARED_LOCK.
  33700. **
  33701. ** If the locking level of the file descriptor is already at or below
  33702. ** the requested locking level, this routine is a no-op.
  33703. */
  33704. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  33705. return posixUnlock(id, eFileLock, 1);
  33706. }
  33707. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  33708. /*
  33709. ** The code above is the NFS lock implementation. The code is specific
  33710. ** to MacOSX and does not work on other unix platforms. No alternative
  33711. ** is available.
  33712. **
  33713. ********************* End of the NFS lock implementation **********************
  33714. ******************************************************************************/
  33715. /******************************************************************************
  33716. **************** Non-locking sqlite3_file methods *****************************
  33717. **
  33718. ** The next division contains implementations for all methods of the
  33719. ** sqlite3_file object other than the locking methods. The locking
  33720. ** methods were defined in divisions above (one locking method per
  33721. ** division). Those methods that are common to all locking modes
  33722. ** are gather together into this division.
  33723. */
  33724. /*
  33725. ** Seek to the offset passed as the second argument, then read cnt
  33726. ** bytes into pBuf. Return the number of bytes actually read.
  33727. **
  33728. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  33729. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  33730. ** one system to another. Since SQLite does not define USE_PREAD
  33731. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  33732. ** See tickets #2741 and #2681.
  33733. **
  33734. ** To avoid stomping the errno value on a failed read the lastErrno value
  33735. ** is set before returning.
  33736. */
  33737. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  33738. int got;
  33739. int prior = 0;
  33740. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  33741. i64 newOffset;
  33742. #endif
  33743. TIMER_START;
  33744. assert( cnt==(cnt&0x1ffff) );
  33745. assert( id->h>2 );
  33746. do{
  33747. #if defined(USE_PREAD)
  33748. got = osPread(id->h, pBuf, cnt, offset);
  33749. SimulateIOError( got = -1 );
  33750. #elif defined(USE_PREAD64)
  33751. got = osPread64(id->h, pBuf, cnt, offset);
  33752. SimulateIOError( got = -1 );
  33753. #else
  33754. newOffset = lseek(id->h, offset, SEEK_SET);
  33755. SimulateIOError( newOffset = -1 );
  33756. if( newOffset<0 ){
  33757. storeLastErrno((unixFile*)id, errno);
  33758. return -1;
  33759. }
  33760. got = osRead(id->h, pBuf, cnt);
  33761. #endif
  33762. if( got==cnt ) break;
  33763. if( got<0 ){
  33764. if( errno==EINTR ){ got = 1; continue; }
  33765. prior = 0;
  33766. storeLastErrno((unixFile*)id, errno);
  33767. break;
  33768. }else if( got>0 ){
  33769. cnt -= got;
  33770. offset += got;
  33771. prior += got;
  33772. pBuf = (void*)(got + (char*)pBuf);
  33773. }
  33774. }while( got>0 );
  33775. TIMER_END;
  33776. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  33777. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  33778. return got+prior;
  33779. }
  33780. /*
  33781. ** Read data from a file into a buffer. Return SQLITE_OK if all
  33782. ** bytes were read successfully and SQLITE_IOERR if anything goes
  33783. ** wrong.
  33784. */
  33785. static int unixRead(
  33786. sqlite3_file *id,
  33787. void *pBuf,
  33788. int amt,
  33789. sqlite3_int64 offset
  33790. ){
  33791. unixFile *pFile = (unixFile *)id;
  33792. int got;
  33793. assert( id );
  33794. assert( offset>=0 );
  33795. assert( amt>0 );
  33796. /* If this is a database file (not a journal, master-journal or temp
  33797. ** file), the bytes in the locking range should never be read or written. */
  33798. #if 0
  33799. assert( pFile->pPreallocatedUnused==0
  33800. || offset>=PENDING_BYTE+512
  33801. || offset+amt<=PENDING_BYTE
  33802. );
  33803. #endif
  33804. #if SQLITE_MAX_MMAP_SIZE>0
  33805. /* Deal with as much of this read request as possible by transfering
  33806. ** data from the memory mapping using memcpy(). */
  33807. if( offset<pFile->mmapSize ){
  33808. if( offset+amt <= pFile->mmapSize ){
  33809. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  33810. return SQLITE_OK;
  33811. }else{
  33812. int nCopy = pFile->mmapSize - offset;
  33813. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  33814. pBuf = &((u8 *)pBuf)[nCopy];
  33815. amt -= nCopy;
  33816. offset += nCopy;
  33817. }
  33818. }
  33819. #endif
  33820. got = seekAndRead(pFile, offset, pBuf, amt);
  33821. if( got==amt ){
  33822. return SQLITE_OK;
  33823. }else if( got<0 ){
  33824. /* lastErrno set by seekAndRead */
  33825. return SQLITE_IOERR_READ;
  33826. }else{
  33827. storeLastErrno(pFile, 0); /* not a system error */
  33828. /* Unread parts of the buffer must be zero-filled */
  33829. memset(&((char*)pBuf)[got], 0, amt-got);
  33830. return SQLITE_IOERR_SHORT_READ;
  33831. }
  33832. }
  33833. /*
  33834. ** Attempt to seek the file-descriptor passed as the first argument to
  33835. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  33836. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  33837. ** return the actual number of bytes written (which may be less than
  33838. ** nBuf).
  33839. */
  33840. static int seekAndWriteFd(
  33841. int fd, /* File descriptor to write to */
  33842. i64 iOff, /* File offset to begin writing at */
  33843. const void *pBuf, /* Copy data from this buffer to the file */
  33844. int nBuf, /* Size of buffer pBuf in bytes */
  33845. int *piErrno /* OUT: Error number if error occurs */
  33846. ){
  33847. int rc = 0; /* Value returned by system call */
  33848. assert( nBuf==(nBuf&0x1ffff) );
  33849. assert( fd>2 );
  33850. assert( piErrno!=0 );
  33851. nBuf &= 0x1ffff;
  33852. TIMER_START;
  33853. #if defined(USE_PREAD)
  33854. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  33855. #elif defined(USE_PREAD64)
  33856. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  33857. #else
  33858. do{
  33859. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  33860. SimulateIOError( iSeek = -1 );
  33861. if( iSeek<0 ){
  33862. rc = -1;
  33863. break;
  33864. }
  33865. rc = osWrite(fd, pBuf, nBuf);
  33866. }while( rc<0 && errno==EINTR );
  33867. #endif
  33868. TIMER_END;
  33869. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  33870. if( rc<0 ) *piErrno = errno;
  33871. return rc;
  33872. }
  33873. /*
  33874. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  33875. ** Return the number of bytes actually read. Update the offset.
  33876. **
  33877. ** To avoid stomping the errno value on a failed write the lastErrno value
  33878. ** is set before returning.
  33879. */
  33880. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  33881. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  33882. }
  33883. /*
  33884. ** Write data from a buffer into a file. Return SQLITE_OK on success
  33885. ** or some other error code on failure.
  33886. */
  33887. static int unixWrite(
  33888. sqlite3_file *id,
  33889. const void *pBuf,
  33890. int amt,
  33891. sqlite3_int64 offset
  33892. ){
  33893. unixFile *pFile = (unixFile*)id;
  33894. int wrote = 0;
  33895. assert( id );
  33896. assert( amt>0 );
  33897. /* If this is a database file (not a journal, master-journal or temp
  33898. ** file), the bytes in the locking range should never be read or written. */
  33899. #if 0
  33900. assert( pFile->pPreallocatedUnused==0
  33901. || offset>=PENDING_BYTE+512
  33902. || offset+amt<=PENDING_BYTE
  33903. );
  33904. #endif
  33905. #ifdef SQLITE_DEBUG
  33906. /* If we are doing a normal write to a database file (as opposed to
  33907. ** doing a hot-journal rollback or a write to some file other than a
  33908. ** normal database file) then record the fact that the database
  33909. ** has changed. If the transaction counter is modified, record that
  33910. ** fact too.
  33911. */
  33912. if( pFile->inNormalWrite ){
  33913. pFile->dbUpdate = 1; /* The database has been modified */
  33914. if( offset<=24 && offset+amt>=27 ){
  33915. int rc;
  33916. char oldCntr[4];
  33917. SimulateIOErrorBenign(1);
  33918. rc = seekAndRead(pFile, 24, oldCntr, 4);
  33919. SimulateIOErrorBenign(0);
  33920. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  33921. pFile->transCntrChng = 1; /* The transaction counter has changed */
  33922. }
  33923. }
  33924. }
  33925. #endif
  33926. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  33927. /* Deal with as much of this write request as possible by transfering
  33928. ** data from the memory mapping using memcpy(). */
  33929. if( offset<pFile->mmapSize ){
  33930. if( offset+amt <= pFile->mmapSize ){
  33931. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  33932. return SQLITE_OK;
  33933. }else{
  33934. int nCopy = pFile->mmapSize - offset;
  33935. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  33936. pBuf = &((u8 *)pBuf)[nCopy];
  33937. amt -= nCopy;
  33938. offset += nCopy;
  33939. }
  33940. }
  33941. #endif
  33942. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  33943. amt -= wrote;
  33944. offset += wrote;
  33945. pBuf = &((char*)pBuf)[wrote];
  33946. }
  33947. SimulateIOError(( wrote=(-1), amt=1 ));
  33948. SimulateDiskfullError(( wrote=0, amt=1 ));
  33949. if( amt>wrote ){
  33950. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  33951. /* lastErrno set by seekAndWrite */
  33952. return SQLITE_IOERR_WRITE;
  33953. }else{
  33954. storeLastErrno(pFile, 0); /* not a system error */
  33955. return SQLITE_FULL;
  33956. }
  33957. }
  33958. return SQLITE_OK;
  33959. }
  33960. #ifdef SQLITE_TEST
  33961. /*
  33962. ** Count the number of fullsyncs and normal syncs. This is used to test
  33963. ** that syncs and fullsyncs are occurring at the right times.
  33964. */
  33965. SQLITE_API int sqlite3_sync_count = 0;
  33966. SQLITE_API int sqlite3_fullsync_count = 0;
  33967. #endif
  33968. /*
  33969. ** We do not trust systems to provide a working fdatasync(). Some do.
  33970. ** Others do no. To be safe, we will stick with the (slightly slower)
  33971. ** fsync(). If you know that your system does support fdatasync() correctly,
  33972. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  33973. */
  33974. #if !defined(fdatasync) && !HAVE_FDATASYNC
  33975. # define fdatasync fsync
  33976. #endif
  33977. /*
  33978. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  33979. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  33980. ** only available on Mac OS X. But that could change.
  33981. */
  33982. #ifdef F_FULLFSYNC
  33983. # define HAVE_FULLFSYNC 1
  33984. #else
  33985. # define HAVE_FULLFSYNC 0
  33986. #endif
  33987. /*
  33988. ** The fsync() system call does not work as advertised on many
  33989. ** unix systems. The following procedure is an attempt to make
  33990. ** it work better.
  33991. **
  33992. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  33993. ** for testing when we want to run through the test suite quickly.
  33994. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  33995. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  33996. ** or power failure will likely corrupt the database file.
  33997. **
  33998. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  33999. ** The idea behind dataOnly is that it should only write the file content
  34000. ** to disk, not the inode. We only set dataOnly if the file size is
  34001. ** unchanged since the file size is part of the inode. However,
  34002. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  34003. ** file size has changed. The only real difference between fdatasync()
  34004. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  34005. ** inode if the mtime or owner or other inode attributes have changed.
  34006. ** We only care about the file size, not the other file attributes, so
  34007. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  34008. ** So, we always use fdatasync() if it is available, regardless of
  34009. ** the value of the dataOnly flag.
  34010. */
  34011. static int full_fsync(int fd, int fullSync, int dataOnly){
  34012. int rc;
  34013. /* The following "ifdef/elif/else/" block has the same structure as
  34014. ** the one below. It is replicated here solely to avoid cluttering
  34015. ** up the real code with the UNUSED_PARAMETER() macros.
  34016. */
  34017. #ifdef SQLITE_NO_SYNC
  34018. UNUSED_PARAMETER(fd);
  34019. UNUSED_PARAMETER(fullSync);
  34020. UNUSED_PARAMETER(dataOnly);
  34021. #elif HAVE_FULLFSYNC
  34022. UNUSED_PARAMETER(dataOnly);
  34023. #else
  34024. UNUSED_PARAMETER(fullSync);
  34025. UNUSED_PARAMETER(dataOnly);
  34026. #endif
  34027. /* Record the number of times that we do a normal fsync() and
  34028. ** FULLSYNC. This is used during testing to verify that this procedure
  34029. ** gets called with the correct arguments.
  34030. */
  34031. #ifdef SQLITE_TEST
  34032. if( fullSync ) sqlite3_fullsync_count++;
  34033. sqlite3_sync_count++;
  34034. #endif
  34035. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  34036. ** no-op. But go ahead and call fstat() to validate the file
  34037. ** descriptor as we need a method to provoke a failure during
  34038. ** coverate testing.
  34039. */
  34040. #ifdef SQLITE_NO_SYNC
  34041. {
  34042. struct stat buf;
  34043. rc = osFstat(fd, &buf);
  34044. }
  34045. #elif HAVE_FULLFSYNC
  34046. if( fullSync ){
  34047. rc = osFcntl(fd, F_FULLFSYNC, 0);
  34048. }else{
  34049. rc = 1;
  34050. }
  34051. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  34052. ** It shouldn't be possible for fullfsync to fail on the local
  34053. ** file system (on OSX), so failure indicates that FULLFSYNC
  34054. ** isn't supported for this file system. So, attempt an fsync
  34055. ** and (for now) ignore the overhead of a superfluous fcntl call.
  34056. ** It'd be better to detect fullfsync support once and avoid
  34057. ** the fcntl call every time sync is called.
  34058. */
  34059. if( rc ) rc = fsync(fd);
  34060. #elif defined(__APPLE__)
  34061. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  34062. ** so currently we default to the macro that redefines fdatasync to fsync
  34063. */
  34064. rc = fsync(fd);
  34065. #else
  34066. rc = fdatasync(fd);
  34067. #if OS_VXWORKS
  34068. if( rc==-1 && errno==ENOTSUP ){
  34069. rc = fsync(fd);
  34070. }
  34071. #endif /* OS_VXWORKS */
  34072. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  34073. if( OS_VXWORKS && rc!= -1 ){
  34074. rc = 0;
  34075. }
  34076. return rc;
  34077. }
  34078. /*
  34079. ** Open a file descriptor to the directory containing file zFilename.
  34080. ** If successful, *pFd is set to the opened file descriptor and
  34081. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  34082. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  34083. ** value.
  34084. **
  34085. ** The directory file descriptor is used for only one thing - to
  34086. ** fsync() a directory to make sure file creation and deletion events
  34087. ** are flushed to disk. Such fsyncs are not needed on newer
  34088. ** journaling filesystems, but are required on older filesystems.
  34089. **
  34090. ** This routine can be overridden using the xSetSysCall interface.
  34091. ** The ability to override this routine was added in support of the
  34092. ** chromium sandbox. Opening a directory is a security risk (we are
  34093. ** told) so making it overrideable allows the chromium sandbox to
  34094. ** replace this routine with a harmless no-op. To make this routine
  34095. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  34096. ** *pFd set to a negative number.
  34097. **
  34098. ** If SQLITE_OK is returned, the caller is responsible for closing
  34099. ** the file descriptor *pFd using close().
  34100. */
  34101. static int openDirectory(const char *zFilename, int *pFd){
  34102. int ii;
  34103. int fd = -1;
  34104. char zDirname[MAX_PATHNAME+1];
  34105. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  34106. for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
  34107. if( ii>0 ){
  34108. zDirname[ii] = '\0';
  34109. }else{
  34110. if( zDirname[0]!='/' ) zDirname[0] = '.';
  34111. zDirname[1] = 0;
  34112. }
  34113. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  34114. if( fd>=0 ){
  34115. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  34116. }
  34117. *pFd = fd;
  34118. if( fd>=0 ) return SQLITE_OK;
  34119. return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
  34120. }
  34121. /*
  34122. ** Make sure all writes to a particular file are committed to disk.
  34123. **
  34124. ** If dataOnly==0 then both the file itself and its metadata (file
  34125. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  34126. ** file data is synced.
  34127. **
  34128. ** Under Unix, also make sure that the directory entry for the file
  34129. ** has been created by fsync-ing the directory that contains the file.
  34130. ** If we do not do this and we encounter a power failure, the directory
  34131. ** entry for the journal might not exist after we reboot. The next
  34132. ** SQLite to access the file will not know that the journal exists (because
  34133. ** the directory entry for the journal was never created) and the transaction
  34134. ** will not roll back - possibly leading to database corruption.
  34135. */
  34136. static int unixSync(sqlite3_file *id, int flags){
  34137. int rc;
  34138. unixFile *pFile = (unixFile*)id;
  34139. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  34140. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  34141. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  34142. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  34143. || (flags&0x0F)==SQLITE_SYNC_FULL
  34144. );
  34145. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  34146. ** line is to test that doing so does not cause any problems.
  34147. */
  34148. SimulateDiskfullError( return SQLITE_FULL );
  34149. assert( pFile );
  34150. OSTRACE(("SYNC %-3d\n", pFile->h));
  34151. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  34152. SimulateIOError( rc=1 );
  34153. if( rc ){
  34154. storeLastErrno(pFile, errno);
  34155. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  34156. }
  34157. /* Also fsync the directory containing the file if the DIRSYNC flag
  34158. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  34159. ** are unable to fsync a directory, so ignore errors on the fsync.
  34160. */
  34161. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  34162. int dirfd;
  34163. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  34164. HAVE_FULLFSYNC, isFullsync));
  34165. rc = osOpenDirectory(pFile->zPath, &dirfd);
  34166. if( rc==SQLITE_OK ){
  34167. full_fsync(dirfd, 0, 0);
  34168. robust_close(pFile, dirfd, __LINE__);
  34169. }else{
  34170. assert( rc==SQLITE_CANTOPEN );
  34171. rc = SQLITE_OK;
  34172. }
  34173. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  34174. }
  34175. return rc;
  34176. }
  34177. /*
  34178. ** Truncate an open file to a specified size
  34179. */
  34180. static int unixTruncate(sqlite3_file *id, i64 nByte){
  34181. unixFile *pFile = (unixFile *)id;
  34182. int rc;
  34183. assert( pFile );
  34184. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  34185. /* If the user has configured a chunk-size for this file, truncate the
  34186. ** file so that it consists of an integer number of chunks (i.e. the
  34187. ** actual file size after the operation may be larger than the requested
  34188. ** size).
  34189. */
  34190. if( pFile->szChunk>0 ){
  34191. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  34192. }
  34193. rc = robust_ftruncate(pFile->h, nByte);
  34194. if( rc ){
  34195. storeLastErrno(pFile, errno);
  34196. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  34197. }else{
  34198. #ifdef SQLITE_DEBUG
  34199. /* If we are doing a normal write to a database file (as opposed to
  34200. ** doing a hot-journal rollback or a write to some file other than a
  34201. ** normal database file) and we truncate the file to zero length,
  34202. ** that effectively updates the change counter. This might happen
  34203. ** when restoring a database using the backup API from a zero-length
  34204. ** source.
  34205. */
  34206. if( pFile->inNormalWrite && nByte==0 ){
  34207. pFile->transCntrChng = 1;
  34208. }
  34209. #endif
  34210. #if SQLITE_MAX_MMAP_SIZE>0
  34211. /* If the file was just truncated to a size smaller than the currently
  34212. ** mapped region, reduce the effective mapping size as well. SQLite will
  34213. ** use read() and write() to access data beyond this point from now on.
  34214. */
  34215. if( nByte<pFile->mmapSize ){
  34216. pFile->mmapSize = nByte;
  34217. }
  34218. #endif
  34219. return SQLITE_OK;
  34220. }
  34221. }
  34222. /*
  34223. ** Determine the current size of a file in bytes
  34224. */
  34225. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  34226. int rc;
  34227. struct stat buf;
  34228. assert( id );
  34229. rc = osFstat(((unixFile*)id)->h, &buf);
  34230. SimulateIOError( rc=1 );
  34231. if( rc!=0 ){
  34232. storeLastErrno((unixFile*)id, errno);
  34233. return SQLITE_IOERR_FSTAT;
  34234. }
  34235. *pSize = buf.st_size;
  34236. /* When opening a zero-size database, the findInodeInfo() procedure
  34237. ** writes a single byte into that file in order to work around a bug
  34238. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  34239. ** layers, we need to report this file size as zero even though it is
  34240. ** really 1. Ticket #3260.
  34241. */
  34242. if( *pSize==1 ) *pSize = 0;
  34243. return SQLITE_OK;
  34244. }
  34245. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  34246. /*
  34247. ** Handler for proxy-locking file-control verbs. Defined below in the
  34248. ** proxying locking division.
  34249. */
  34250. static int proxyFileControl(sqlite3_file*,int,void*);
  34251. #endif
  34252. /*
  34253. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  34254. ** file-control operation. Enlarge the database to nBytes in size
  34255. ** (rounded up to the next chunk-size). If the database is already
  34256. ** nBytes or larger, this routine is a no-op.
  34257. */
  34258. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  34259. if( pFile->szChunk>0 ){
  34260. i64 nSize; /* Required file size */
  34261. struct stat buf; /* Used to hold return values of fstat() */
  34262. if( osFstat(pFile->h, &buf) ){
  34263. return SQLITE_IOERR_FSTAT;
  34264. }
  34265. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  34266. if( nSize>(i64)buf.st_size ){
  34267. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  34268. /* The code below is handling the return value of osFallocate()
  34269. ** correctly. posix_fallocate() is defined to "returns zero on success,
  34270. ** or an error number on failure". See the manpage for details. */
  34271. int err;
  34272. do{
  34273. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  34274. }while( err==EINTR );
  34275. if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
  34276. #else
  34277. /* If the OS does not have posix_fallocate(), fake it. Write a
  34278. ** single byte to the last byte in each block that falls entirely
  34279. ** within the extended region. Then, if required, a single byte
  34280. ** at offset (nSize-1), to set the size of the file correctly.
  34281. ** This is a similar technique to that used by glibc on systems
  34282. ** that do not have a real fallocate() call.
  34283. */
  34284. int nBlk = buf.st_blksize; /* File-system block size */
  34285. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  34286. i64 iWrite; /* Next offset to write to */
  34287. iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
  34288. assert( iWrite>=buf.st_size );
  34289. assert( ((iWrite+1)%nBlk)==0 );
  34290. for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
  34291. if( iWrite>=nSize ) iWrite = nSize - 1;
  34292. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  34293. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  34294. }
  34295. #endif
  34296. }
  34297. }
  34298. #if SQLITE_MAX_MMAP_SIZE>0
  34299. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  34300. int rc;
  34301. if( pFile->szChunk<=0 ){
  34302. if( robust_ftruncate(pFile->h, nByte) ){
  34303. storeLastErrno(pFile, errno);
  34304. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  34305. }
  34306. }
  34307. rc = unixMapfile(pFile, nByte);
  34308. return rc;
  34309. }
  34310. #endif
  34311. return SQLITE_OK;
  34312. }
  34313. /*
  34314. ** If *pArg is initially negative then this is a query. Set *pArg to
  34315. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  34316. **
  34317. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  34318. */
  34319. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  34320. if( *pArg<0 ){
  34321. *pArg = (pFile->ctrlFlags & mask)!=0;
  34322. }else if( (*pArg)==0 ){
  34323. pFile->ctrlFlags &= ~mask;
  34324. }else{
  34325. pFile->ctrlFlags |= mask;
  34326. }
  34327. }
  34328. /* Forward declaration */
  34329. static int unixGetTempname(int nBuf, char *zBuf);
  34330. /*
  34331. ** Information and control of an open file handle.
  34332. */
  34333. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  34334. unixFile *pFile = (unixFile*)id;
  34335. switch( op ){
  34336. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  34337. case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
  34338. int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
  34339. return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
  34340. }
  34341. case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
  34342. int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
  34343. return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
  34344. }
  34345. case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
  34346. int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
  34347. return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
  34348. }
  34349. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  34350. case SQLITE_FCNTL_LOCKSTATE: {
  34351. *(int*)pArg = pFile->eFileLock;
  34352. return SQLITE_OK;
  34353. }
  34354. case SQLITE_FCNTL_LAST_ERRNO: {
  34355. *(int*)pArg = pFile->lastErrno;
  34356. return SQLITE_OK;
  34357. }
  34358. case SQLITE_FCNTL_CHUNK_SIZE: {
  34359. pFile->szChunk = *(int *)pArg;
  34360. return SQLITE_OK;
  34361. }
  34362. case SQLITE_FCNTL_SIZE_HINT: {
  34363. int rc;
  34364. SimulateIOErrorBenign(1);
  34365. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  34366. SimulateIOErrorBenign(0);
  34367. return rc;
  34368. }
  34369. case SQLITE_FCNTL_PERSIST_WAL: {
  34370. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  34371. return SQLITE_OK;
  34372. }
  34373. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  34374. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  34375. return SQLITE_OK;
  34376. }
  34377. case SQLITE_FCNTL_VFSNAME: {
  34378. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  34379. return SQLITE_OK;
  34380. }
  34381. case SQLITE_FCNTL_TEMPFILENAME: {
  34382. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  34383. if( zTFile ){
  34384. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  34385. *(char**)pArg = zTFile;
  34386. }
  34387. return SQLITE_OK;
  34388. }
  34389. case SQLITE_FCNTL_HAS_MOVED: {
  34390. *(int*)pArg = fileHasMoved(pFile);
  34391. return SQLITE_OK;
  34392. }
  34393. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  34394. case SQLITE_FCNTL_LOCK_TIMEOUT: {
  34395. pFile->iBusyTimeout = *(int*)pArg;
  34396. return SQLITE_OK;
  34397. }
  34398. #endif
  34399. #if SQLITE_MAX_MMAP_SIZE>0
  34400. case SQLITE_FCNTL_MMAP_SIZE: {
  34401. i64 newLimit = *(i64*)pArg;
  34402. int rc = SQLITE_OK;
  34403. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  34404. newLimit = sqlite3GlobalConfig.mxMmap;
  34405. }
  34406. /* The value of newLimit may be eventually cast to (size_t) and passed
  34407. ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
  34408. ** 64-bit type. */
  34409. if( newLimit>0 && sizeof(size_t)<8 ){
  34410. newLimit = (newLimit & 0x7FFFFFFF);
  34411. }
  34412. *(i64*)pArg = pFile->mmapSizeMax;
  34413. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  34414. pFile->mmapSizeMax = newLimit;
  34415. if( pFile->mmapSize>0 ){
  34416. unixUnmapfile(pFile);
  34417. rc = unixMapfile(pFile, -1);
  34418. }
  34419. }
  34420. return rc;
  34421. }
  34422. #endif
  34423. #ifdef SQLITE_DEBUG
  34424. /* The pager calls this method to signal that it has done
  34425. ** a rollback and that the database is therefore unchanged and
  34426. ** it hence it is OK for the transaction change counter to be
  34427. ** unchanged.
  34428. */
  34429. case SQLITE_FCNTL_DB_UNCHANGED: {
  34430. ((unixFile*)id)->dbUpdate = 0;
  34431. return SQLITE_OK;
  34432. }
  34433. #endif
  34434. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  34435. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  34436. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  34437. return proxyFileControl(id,op,pArg);
  34438. }
  34439. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  34440. }
  34441. return SQLITE_NOTFOUND;
  34442. }
  34443. /*
  34444. ** If pFd->sectorSize is non-zero when this function is called, it is a
  34445. ** no-op. Otherwise, the values of pFd->sectorSize and
  34446. ** pFd->deviceCharacteristics are set according to the file-system
  34447. ** characteristics.
  34448. **
  34449. ** There are two versions of this function. One for QNX and one for all
  34450. ** other systems.
  34451. */
  34452. #ifndef __QNXNTO__
  34453. static void setDeviceCharacteristics(unixFile *pFd){
  34454. assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
  34455. if( pFd->sectorSize==0 ){
  34456. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  34457. int res;
  34458. u32 f = 0;
  34459. /* Check for support for F2FS atomic batch writes. */
  34460. res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
  34461. if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
  34462. pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
  34463. }
  34464. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  34465. /* Set the POWERSAFE_OVERWRITE flag if requested. */
  34466. if( pFd->ctrlFlags & UNIXFILE_PSOW ){
  34467. pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  34468. }
  34469. pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  34470. }
  34471. }
  34472. #else
  34473. #include <sys/dcmd_blk.h>
  34474. #include <sys/statvfs.h>
  34475. static void setDeviceCharacteristics(unixFile *pFile){
  34476. if( pFile->sectorSize == 0 ){
  34477. struct statvfs fsInfo;
  34478. /* Set defaults for non-supported filesystems */
  34479. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  34480. pFile->deviceCharacteristics = 0;
  34481. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  34482. return;
  34483. }
  34484. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  34485. pFile->sectorSize = fsInfo.f_bsize;
  34486. pFile->deviceCharacteristics =
  34487. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  34488. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34489. ** the write succeeds */
  34490. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34491. ** so it is ordered */
  34492. 0;
  34493. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  34494. pFile->sectorSize = fsInfo.f_bsize;
  34495. pFile->deviceCharacteristics =
  34496. /* etfs cluster size writes are atomic */
  34497. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  34498. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34499. ** the write succeeds */
  34500. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34501. ** so it is ordered */
  34502. 0;
  34503. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  34504. pFile->sectorSize = fsInfo.f_bsize;
  34505. pFile->deviceCharacteristics =
  34506. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  34507. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34508. ** the write succeeds */
  34509. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34510. ** so it is ordered */
  34511. 0;
  34512. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  34513. pFile->sectorSize = fsInfo.f_bsize;
  34514. pFile->deviceCharacteristics =
  34515. /* full bitset of atomics from max sector size and smaller */
  34516. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  34517. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34518. ** so it is ordered */
  34519. 0;
  34520. }else if( strstr(fsInfo.f_basetype, "dos") ){
  34521. pFile->sectorSize = fsInfo.f_bsize;
  34522. pFile->deviceCharacteristics =
  34523. /* full bitset of atomics from max sector size and smaller */
  34524. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  34525. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34526. ** so it is ordered */
  34527. 0;
  34528. }else{
  34529. pFile->deviceCharacteristics =
  34530. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  34531. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34532. ** the write succeeds */
  34533. 0;
  34534. }
  34535. }
  34536. /* Last chance verification. If the sector size isn't a multiple of 512
  34537. ** then it isn't valid.*/
  34538. if( pFile->sectorSize % 512 != 0 ){
  34539. pFile->deviceCharacteristics = 0;
  34540. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  34541. }
  34542. }
  34543. #endif
  34544. /*
  34545. ** Return the sector size in bytes of the underlying block device for
  34546. ** the specified file. This is almost always 512 bytes, but may be
  34547. ** larger for some devices.
  34548. **
  34549. ** SQLite code assumes this function cannot fail. It also assumes that
  34550. ** if two files are created in the same file-system directory (i.e.
  34551. ** a database and its journal file) that the sector size will be the
  34552. ** same for both.
  34553. */
  34554. static int unixSectorSize(sqlite3_file *id){
  34555. unixFile *pFd = (unixFile*)id;
  34556. setDeviceCharacteristics(pFd);
  34557. return pFd->sectorSize;
  34558. }
  34559. /*
  34560. ** Return the device characteristics for the file.
  34561. **
  34562. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  34563. ** However, that choice is controversial since technically the underlying
  34564. ** file system does not always provide powersafe overwrites. (In other
  34565. ** words, after a power-loss event, parts of the file that were never
  34566. ** written might end up being altered.) However, non-PSOW behavior is very,
  34567. ** very rare. And asserting PSOW makes a large reduction in the amount
  34568. ** of required I/O for journaling, since a lot of padding is eliminated.
  34569. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  34570. ** available to turn it off and URI query parameter available to turn it off.
  34571. */
  34572. static int unixDeviceCharacteristics(sqlite3_file *id){
  34573. unixFile *pFd = (unixFile*)id;
  34574. setDeviceCharacteristics(pFd);
  34575. return pFd->deviceCharacteristics;
  34576. }
  34577. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  34578. /*
  34579. ** Return the system page size.
  34580. **
  34581. ** This function should not be called directly by other code in this file.
  34582. ** Instead, it should be called via macro osGetpagesize().
  34583. */
  34584. static int unixGetpagesize(void){
  34585. #if OS_VXWORKS
  34586. return 1024;
  34587. #elif defined(_BSD_SOURCE)
  34588. return getpagesize();
  34589. #else
  34590. return (int)sysconf(_SC_PAGESIZE);
  34591. #endif
  34592. }
  34593. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  34594. #ifndef SQLITE_OMIT_WAL
  34595. /*
  34596. ** Object used to represent an shared memory buffer.
  34597. **
  34598. ** When multiple threads all reference the same wal-index, each thread
  34599. ** has its own unixShm object, but they all point to a single instance
  34600. ** of this unixShmNode object. In other words, each wal-index is opened
  34601. ** only once per process.
  34602. **
  34603. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  34604. ** We could coalesce this object into unixInodeInfo, but that would mean
  34605. ** every open file that does not use shared memory (in other words, most
  34606. ** open files) would have to carry around this extra information. So
  34607. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  34608. ** and the unixShmNode object is created only when needed.
  34609. **
  34610. ** unixMutexHeld() must be true when creating or destroying
  34611. ** this object or while reading or writing the following fields:
  34612. **
  34613. ** nRef
  34614. **
  34615. ** The following fields are read-only after the object is created:
  34616. **
  34617. ** hShm
  34618. ** zFilename
  34619. **
  34620. ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
  34621. ** unixMutexHeld() is true when reading or writing any other field
  34622. ** in this structure.
  34623. */
  34624. struct unixShmNode {
  34625. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  34626. sqlite3_mutex *pShmMutex; /* Mutex to access this object */
  34627. char *zFilename; /* Name of the mmapped file */
  34628. int hShm; /* Open file descriptor */
  34629. int szRegion; /* Size of shared-memory regions */
  34630. u16 nRegion; /* Size of array apRegion */
  34631. u8 isReadonly; /* True if read-only */
  34632. u8 isUnlocked; /* True if no DMS lock held */
  34633. char **apRegion; /* Array of mapped shared-memory regions */
  34634. int nRef; /* Number of unixShm objects pointing to this */
  34635. unixShm *pFirst; /* All unixShm objects pointing to this */
  34636. #ifdef SQLITE_DEBUG
  34637. u8 exclMask; /* Mask of exclusive locks held */
  34638. u8 sharedMask; /* Mask of shared locks held */
  34639. u8 nextShmId; /* Next available unixShm.id value */
  34640. #endif
  34641. };
  34642. /*
  34643. ** Structure used internally by this VFS to record the state of an
  34644. ** open shared memory connection.
  34645. **
  34646. ** The following fields are initialized when this object is created and
  34647. ** are read-only thereafter:
  34648. **
  34649. ** unixShm.pShmNode
  34650. ** unixShm.id
  34651. **
  34652. ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
  34653. ** be held while accessing any read/write fields.
  34654. */
  34655. struct unixShm {
  34656. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  34657. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  34658. u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
  34659. u8 id; /* Id of this connection within its unixShmNode */
  34660. u16 sharedMask; /* Mask of shared locks held */
  34661. u16 exclMask; /* Mask of exclusive locks held */
  34662. };
  34663. /*
  34664. ** Constants used for locking
  34665. */
  34666. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  34667. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  34668. /*
  34669. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  34670. **
  34671. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  34672. ** otherwise.
  34673. */
  34674. static int unixShmSystemLock(
  34675. unixFile *pFile, /* Open connection to the WAL file */
  34676. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  34677. int ofst, /* First byte of the locking range */
  34678. int n /* Number of bytes to lock */
  34679. ){
  34680. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  34681. struct flock f; /* The posix advisory locking structure */
  34682. int rc = SQLITE_OK; /* Result code form fcntl() */
  34683. /* Access to the unixShmNode object is serialized by the caller */
  34684. pShmNode = pFile->pInode->pShmNode;
  34685. assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
  34686. assert( pShmNode->nRef>0 || unixMutexHeld() );
  34687. /* Shared locks never span more than one byte */
  34688. assert( n==1 || lockType!=F_RDLCK );
  34689. /* Locks are within range */
  34690. assert( n>=1 && n<=SQLITE_SHM_NLOCK );
  34691. if( pShmNode->hShm>=0 ){
  34692. /* Initialize the locking parameters */
  34693. f.l_type = lockType;
  34694. f.l_whence = SEEK_SET;
  34695. f.l_start = ofst;
  34696. f.l_len = n;
  34697. rc = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
  34698. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  34699. }
  34700. /* Update the global lock state and do debug tracing */
  34701. #ifdef SQLITE_DEBUG
  34702. { u16 mask;
  34703. OSTRACE(("SHM-LOCK "));
  34704. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  34705. if( rc==SQLITE_OK ){
  34706. if( lockType==F_UNLCK ){
  34707. OSTRACE(("unlock %d ok", ofst));
  34708. pShmNode->exclMask &= ~mask;
  34709. pShmNode->sharedMask &= ~mask;
  34710. }else if( lockType==F_RDLCK ){
  34711. OSTRACE(("read-lock %d ok", ofst));
  34712. pShmNode->exclMask &= ~mask;
  34713. pShmNode->sharedMask |= mask;
  34714. }else{
  34715. assert( lockType==F_WRLCK );
  34716. OSTRACE(("write-lock %d ok", ofst));
  34717. pShmNode->exclMask |= mask;
  34718. pShmNode->sharedMask &= ~mask;
  34719. }
  34720. }else{
  34721. if( lockType==F_UNLCK ){
  34722. OSTRACE(("unlock %d failed", ofst));
  34723. }else if( lockType==F_RDLCK ){
  34724. OSTRACE(("read-lock failed"));
  34725. }else{
  34726. assert( lockType==F_WRLCK );
  34727. OSTRACE(("write-lock %d failed", ofst));
  34728. }
  34729. }
  34730. OSTRACE((" - afterwards %03x,%03x\n",
  34731. pShmNode->sharedMask, pShmNode->exclMask));
  34732. }
  34733. #endif
  34734. return rc;
  34735. }
  34736. /*
  34737. ** Return the minimum number of 32KB shm regions that should be mapped at
  34738. ** a time, assuming that each mapping must be an integer multiple of the
  34739. ** current system page-size.
  34740. **
  34741. ** Usually, this is 1. The exception seems to be systems that are configured
  34742. ** to use 64KB pages - in this case each mapping must cover at least two
  34743. ** shm regions.
  34744. */
  34745. static int unixShmRegionPerMap(void){
  34746. int shmsz = 32*1024; /* SHM region size */
  34747. int pgsz = osGetpagesize(); /* System page size */
  34748. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  34749. if( pgsz<shmsz ) return 1;
  34750. return pgsz/shmsz;
  34751. }
  34752. /*
  34753. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  34754. **
  34755. ** This is not a VFS shared-memory method; it is a utility function called
  34756. ** by VFS shared-memory methods.
  34757. */
  34758. static void unixShmPurge(unixFile *pFd){
  34759. unixShmNode *p = pFd->pInode->pShmNode;
  34760. assert( unixMutexHeld() );
  34761. if( p && ALWAYS(p->nRef==0) ){
  34762. int nShmPerMap = unixShmRegionPerMap();
  34763. int i;
  34764. assert( p->pInode==pFd->pInode );
  34765. sqlite3_mutex_free(p->pShmMutex);
  34766. for(i=0; i<p->nRegion; i+=nShmPerMap){
  34767. if( p->hShm>=0 ){
  34768. osMunmap(p->apRegion[i], p->szRegion);
  34769. }else{
  34770. sqlite3_free(p->apRegion[i]);
  34771. }
  34772. }
  34773. sqlite3_free(p->apRegion);
  34774. if( p->hShm>=0 ){
  34775. robust_close(pFd, p->hShm, __LINE__);
  34776. p->hShm = -1;
  34777. }
  34778. p->pInode->pShmNode = 0;
  34779. sqlite3_free(p);
  34780. }
  34781. }
  34782. /*
  34783. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  34784. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  34785. ** code otherwise.
  34786. **
  34787. ** If the DMS cannot be locked because this is a readonly_shm=1
  34788. ** connection and no other process already holds a lock, return
  34789. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  34790. */
  34791. static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
  34792. struct flock lock;
  34793. int rc = SQLITE_OK;
  34794. /* Use F_GETLK to determine the locks other processes are holding
  34795. ** on the DMS byte. If it indicates that another process is holding
  34796. ** a SHARED lock, then this process may also take a SHARED lock
  34797. ** and proceed with opening the *-shm file.
  34798. **
  34799. ** Or, if no other process is holding any lock, then this process
  34800. ** is the first to open it. In this case take an EXCLUSIVE lock on the
  34801. ** DMS byte and truncate the *-shm file to zero bytes in size. Then
  34802. ** downgrade to a SHARED lock on the DMS byte.
  34803. **
  34804. ** If another process is holding an EXCLUSIVE lock on the DMS byte,
  34805. ** return SQLITE_BUSY to the caller (it will try again). An earlier
  34806. ** version of this code attempted the SHARED lock at this point. But
  34807. ** this introduced a subtle race condition: if the process holding
  34808. ** EXCLUSIVE failed just before truncating the *-shm file, then this
  34809. ** process might open and use the *-shm file without truncating it.
  34810. ** And if the *-shm file has been corrupted by a power failure or
  34811. ** system crash, the database itself may also become corrupt. */
  34812. lock.l_whence = SEEK_SET;
  34813. lock.l_start = UNIX_SHM_DMS;
  34814. lock.l_len = 1;
  34815. lock.l_type = F_WRLCK;
  34816. if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
  34817. rc = SQLITE_IOERR_LOCK;
  34818. }else if( lock.l_type==F_UNLCK ){
  34819. if( pShmNode->isReadonly ){
  34820. pShmNode->isUnlocked = 1;
  34821. rc = SQLITE_READONLY_CANTINIT;
  34822. }else{
  34823. rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
  34824. /* The first connection to attach must truncate the -shm file. We
  34825. ** truncate to 3 bytes (an arbitrary small number, less than the
  34826. ** -shm header size) rather than 0 as a system debugging aid, to
  34827. ** help detect if a -shm file truncation is legitimate or is the work
  34828. ** or a rogue process. */
  34829. if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
  34830. rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
  34831. }
  34832. }
  34833. }else if( lock.l_type==F_WRLCK ){
  34834. rc = SQLITE_BUSY;
  34835. }
  34836. if( rc==SQLITE_OK ){
  34837. assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
  34838. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  34839. }
  34840. return rc;
  34841. }
  34842. /*
  34843. ** Open a shared-memory area associated with open database file pDbFd.
  34844. ** This particular implementation uses mmapped files.
  34845. **
  34846. ** The file used to implement shared-memory is in the same directory
  34847. ** as the open database file and has the same name as the open database
  34848. ** file with the "-shm" suffix added. For example, if the database file
  34849. ** is "/home/user1/config.db" then the file that is created and mmapped
  34850. ** for shared memory will be called "/home/user1/config.db-shm".
  34851. **
  34852. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  34853. ** some other tmpfs mount. But if a file in a different directory
  34854. ** from the database file is used, then differing access permissions
  34855. ** or a chroot() might cause two different processes on the same
  34856. ** database to end up using different files for shared memory -
  34857. ** meaning that their memory would not really be shared - resulting
  34858. ** in database corruption. Nevertheless, this tmpfs file usage
  34859. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  34860. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  34861. ** option results in an incompatible build of SQLite; builds of SQLite
  34862. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  34863. ** same database file at the same time, database corruption will likely
  34864. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  34865. ** "unsupported" and may go away in a future SQLite release.
  34866. **
  34867. ** When opening a new shared-memory file, if no other instances of that
  34868. ** file are currently open, in this process or in other processes, then
  34869. ** the file must be truncated to zero length or have its header cleared.
  34870. **
  34871. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  34872. ** that means that an exclusive lock is held on the database file and
  34873. ** that no other processes are able to read or write the database. In
  34874. ** that case, we do not really need shared memory. No shared memory
  34875. ** file is created. The shared memory will be simulated with heap memory.
  34876. */
  34877. static int unixOpenSharedMemory(unixFile *pDbFd){
  34878. struct unixShm *p = 0; /* The connection to be opened */
  34879. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  34880. int rc = SQLITE_OK; /* Result code */
  34881. unixInodeInfo *pInode; /* The inode of fd */
  34882. char *zShm; /* Name of the file used for SHM */
  34883. int nShmFilename; /* Size of the SHM filename in bytes */
  34884. /* Allocate space for the new unixShm object. */
  34885. p = sqlite3_malloc64( sizeof(*p) );
  34886. if( p==0 ) return SQLITE_NOMEM_BKPT;
  34887. memset(p, 0, sizeof(*p));
  34888. assert( pDbFd->pShm==0 );
  34889. /* Check to see if a unixShmNode object already exists. Reuse an existing
  34890. ** one if present. Create a new one if necessary.
  34891. */
  34892. assert( unixFileMutexNotheld(pDbFd) );
  34893. unixEnterMutex();
  34894. pInode = pDbFd->pInode;
  34895. pShmNode = pInode->pShmNode;
  34896. if( pShmNode==0 ){
  34897. struct stat sStat; /* fstat() info for database file */
  34898. #ifndef SQLITE_SHM_DIRECTORY
  34899. const char *zBasePath = pDbFd->zPath;
  34900. #endif
  34901. /* Call fstat() to figure out the permissions on the database file. If
  34902. ** a new *-shm file is created, an attempt will be made to create it
  34903. ** with the same permissions.
  34904. */
  34905. if( osFstat(pDbFd->h, &sStat) ){
  34906. rc = SQLITE_IOERR_FSTAT;
  34907. goto shm_open_err;
  34908. }
  34909. #ifdef SQLITE_SHM_DIRECTORY
  34910. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  34911. #else
  34912. nShmFilename = 6 + (int)strlen(zBasePath);
  34913. #endif
  34914. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  34915. if( pShmNode==0 ){
  34916. rc = SQLITE_NOMEM_BKPT;
  34917. goto shm_open_err;
  34918. }
  34919. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  34920. zShm = pShmNode->zFilename = (char*)&pShmNode[1];
  34921. #ifdef SQLITE_SHM_DIRECTORY
  34922. sqlite3_snprintf(nShmFilename, zShm,
  34923. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  34924. (u32)sStat.st_ino, (u32)sStat.st_dev);
  34925. #else
  34926. sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
  34927. sqlite3FileSuffix3(pDbFd->zPath, zShm);
  34928. #endif
  34929. pShmNode->hShm = -1;
  34930. pDbFd->pInode->pShmNode = pShmNode;
  34931. pShmNode->pInode = pDbFd->pInode;
  34932. if( sqlite3GlobalConfig.bCoreMutex ){
  34933. pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  34934. if( pShmNode->pShmMutex==0 ){
  34935. rc = SQLITE_NOMEM_BKPT;
  34936. goto shm_open_err;
  34937. }
  34938. }
  34939. if( pInode->bProcessLock==0 ){
  34940. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  34941. pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT,(sStat.st_mode&0777));
  34942. }
  34943. if( pShmNode->hShm<0 ){
  34944. pShmNode->hShm = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
  34945. if( pShmNode->hShm<0 ){
  34946. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
  34947. goto shm_open_err;
  34948. }
  34949. pShmNode->isReadonly = 1;
  34950. }
  34951. /* If this process is running as root, make sure that the SHM file
  34952. ** is owned by the same user that owns the original database. Otherwise,
  34953. ** the original owner will not be able to connect.
  34954. */
  34955. robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
  34956. rc = unixLockSharedMemory(pDbFd, pShmNode);
  34957. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  34958. }
  34959. }
  34960. /* Make the new connection a child of the unixShmNode */
  34961. p->pShmNode = pShmNode;
  34962. #ifdef SQLITE_DEBUG
  34963. p->id = pShmNode->nextShmId++;
  34964. #endif
  34965. pShmNode->nRef++;
  34966. pDbFd->pShm = p;
  34967. unixLeaveMutex();
  34968. /* The reference count on pShmNode has already been incremented under
  34969. ** the cover of the unixEnterMutex() mutex and the pointer from the
  34970. ** new (struct unixShm) object to the pShmNode has been set. All that is
  34971. ** left to do is to link the new object into the linked list starting
  34972. ** at pShmNode->pFirst. This must be done while holding the
  34973. ** pShmNode->pShmMutex.
  34974. */
  34975. sqlite3_mutex_enter(pShmNode->pShmMutex);
  34976. p->pNext = pShmNode->pFirst;
  34977. pShmNode->pFirst = p;
  34978. sqlite3_mutex_leave(pShmNode->pShmMutex);
  34979. return rc;
  34980. /* Jump here on any error */
  34981. shm_open_err:
  34982. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  34983. sqlite3_free(p);
  34984. unixLeaveMutex();
  34985. return rc;
  34986. }
  34987. /*
  34988. ** This function is called to obtain a pointer to region iRegion of the
  34989. ** shared-memory associated with the database file fd. Shared-memory regions
  34990. ** are numbered starting from zero. Each shared-memory region is szRegion
  34991. ** bytes in size.
  34992. **
  34993. ** If an error occurs, an error code is returned and *pp is set to NULL.
  34994. **
  34995. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  34996. ** region has not been allocated (by any client, including one running in a
  34997. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  34998. ** bExtend is non-zero and the requested shared-memory region has not yet
  34999. ** been allocated, it is allocated by this function.
  35000. **
  35001. ** If the shared-memory region has already been allocated or is allocated by
  35002. ** this call as described above, then it is mapped into this processes
  35003. ** address space (if it is not already), *pp is set to point to the mapped
  35004. ** memory and SQLITE_OK returned.
  35005. */
  35006. static int unixShmMap(
  35007. sqlite3_file *fd, /* Handle open on database file */
  35008. int iRegion, /* Region to retrieve */
  35009. int szRegion, /* Size of regions */
  35010. int bExtend, /* True to extend file if necessary */
  35011. void volatile **pp /* OUT: Mapped memory */
  35012. ){
  35013. unixFile *pDbFd = (unixFile*)fd;
  35014. unixShm *p;
  35015. unixShmNode *pShmNode;
  35016. int rc = SQLITE_OK;
  35017. int nShmPerMap = unixShmRegionPerMap();
  35018. int nReqRegion;
  35019. /* If the shared-memory file has not yet been opened, open it now. */
  35020. if( pDbFd->pShm==0 ){
  35021. rc = unixOpenSharedMemory(pDbFd);
  35022. if( rc!=SQLITE_OK ) return rc;
  35023. }
  35024. p = pDbFd->pShm;
  35025. pShmNode = p->pShmNode;
  35026. sqlite3_mutex_enter(pShmNode->pShmMutex);
  35027. if( pShmNode->isUnlocked ){
  35028. rc = unixLockSharedMemory(pDbFd, pShmNode);
  35029. if( rc!=SQLITE_OK ) goto shmpage_out;
  35030. pShmNode->isUnlocked = 0;
  35031. }
  35032. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  35033. assert( pShmNode->pInode==pDbFd->pInode );
  35034. assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
  35035. assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
  35036. /* Minimum number of regions required to be mapped. */
  35037. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  35038. if( pShmNode->nRegion<nReqRegion ){
  35039. char **apNew; /* New apRegion[] array */
  35040. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  35041. struct stat sStat; /* Used by fstat() */
  35042. pShmNode->szRegion = szRegion;
  35043. if( pShmNode->hShm>=0 ){
  35044. /* The requested region is not mapped into this processes address space.
  35045. ** Check to see if it has been allocated (i.e. if the wal-index file is
  35046. ** large enough to contain the requested region).
  35047. */
  35048. if( osFstat(pShmNode->hShm, &sStat) ){
  35049. rc = SQLITE_IOERR_SHMSIZE;
  35050. goto shmpage_out;
  35051. }
  35052. if( sStat.st_size<nByte ){
  35053. /* The requested memory region does not exist. If bExtend is set to
  35054. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  35055. */
  35056. if( !bExtend ){
  35057. goto shmpage_out;
  35058. }
  35059. /* Alternatively, if bExtend is true, extend the file. Do this by
  35060. ** writing a single byte to the end of each (OS) page being
  35061. ** allocated or extended. Technically, we need only write to the
  35062. ** last page in order to extend the file. But writing to all new
  35063. ** pages forces the OS to allocate them immediately, which reduces
  35064. ** the chances of SIGBUS while accessing the mapped region later on.
  35065. */
  35066. else{
  35067. static const int pgsz = 4096;
  35068. int iPg;
  35069. /* Write to the last byte of each newly allocated or extended page */
  35070. assert( (nByte % pgsz)==0 );
  35071. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  35072. int x = 0;
  35073. if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
  35074. const char *zFile = pShmNode->zFilename;
  35075. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  35076. goto shmpage_out;
  35077. }
  35078. }
  35079. }
  35080. }
  35081. }
  35082. /* Map the requested memory region into this processes address space. */
  35083. apNew = (char **)sqlite3_realloc(
  35084. pShmNode->apRegion, nReqRegion*sizeof(char *)
  35085. );
  35086. if( !apNew ){
  35087. rc = SQLITE_IOERR_NOMEM_BKPT;
  35088. goto shmpage_out;
  35089. }
  35090. pShmNode->apRegion = apNew;
  35091. while( pShmNode->nRegion<nReqRegion ){
  35092. int nMap = szRegion*nShmPerMap;
  35093. int i;
  35094. void *pMem;
  35095. if( pShmNode->hShm>=0 ){
  35096. pMem = osMmap(0, nMap,
  35097. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  35098. MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
  35099. );
  35100. if( pMem==MAP_FAILED ){
  35101. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  35102. goto shmpage_out;
  35103. }
  35104. }else{
  35105. pMem = sqlite3_malloc64(nMap);
  35106. if( pMem==0 ){
  35107. rc = SQLITE_NOMEM_BKPT;
  35108. goto shmpage_out;
  35109. }
  35110. memset(pMem, 0, nMap);
  35111. }
  35112. for(i=0; i<nShmPerMap; i++){
  35113. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  35114. }
  35115. pShmNode->nRegion += nShmPerMap;
  35116. }
  35117. }
  35118. shmpage_out:
  35119. if( pShmNode->nRegion>iRegion ){
  35120. *pp = pShmNode->apRegion[iRegion];
  35121. }else{
  35122. *pp = 0;
  35123. }
  35124. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  35125. sqlite3_mutex_leave(pShmNode->pShmMutex);
  35126. return rc;
  35127. }
  35128. /*
  35129. ** Change the lock state for a shared-memory segment.
  35130. **
  35131. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  35132. ** different here than in posix. In xShmLock(), one can go from unlocked
  35133. ** to shared and back or from unlocked to exclusive and back. But one may
  35134. ** not go from shared to exclusive or from exclusive to shared.
  35135. */
  35136. static int unixShmLock(
  35137. sqlite3_file *fd, /* Database file holding the shared memory */
  35138. int ofst, /* First lock to acquire or release */
  35139. int n, /* Number of locks to acquire or release */
  35140. int flags /* What to do with the lock */
  35141. ){
  35142. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  35143. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  35144. unixShm *pX; /* For looping over all siblings */
  35145. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  35146. int rc = SQLITE_OK; /* Result code */
  35147. u16 mask; /* Mask of locks to take or release */
  35148. assert( pShmNode==pDbFd->pInode->pShmNode );
  35149. assert( pShmNode->pInode==pDbFd->pInode );
  35150. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  35151. assert( n>=1 );
  35152. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  35153. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  35154. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  35155. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  35156. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  35157. assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
  35158. assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
  35159. mask = (1<<(ofst+n)) - (1<<ofst);
  35160. assert( n>1 || mask==(1<<ofst) );
  35161. sqlite3_mutex_enter(pShmNode->pShmMutex);
  35162. if( flags & SQLITE_SHM_UNLOCK ){
  35163. u16 allMask = 0; /* Mask of locks held by siblings */
  35164. /* See if any siblings hold this same lock */
  35165. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35166. if( pX==p ) continue;
  35167. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  35168. allMask |= pX->sharedMask;
  35169. }
  35170. /* Unlock the system-level locks */
  35171. if( (mask & allMask)==0 ){
  35172. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  35173. }else{
  35174. rc = SQLITE_OK;
  35175. }
  35176. /* Undo the local locks */
  35177. if( rc==SQLITE_OK ){
  35178. p->exclMask &= ~mask;
  35179. p->sharedMask &= ~mask;
  35180. }
  35181. }else if( flags & SQLITE_SHM_SHARED ){
  35182. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  35183. /* Find out which shared locks are already held by sibling connections.
  35184. ** If any sibling already holds an exclusive lock, go ahead and return
  35185. ** SQLITE_BUSY.
  35186. */
  35187. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35188. if( (pX->exclMask & mask)!=0 ){
  35189. rc = SQLITE_BUSY;
  35190. break;
  35191. }
  35192. allShared |= pX->sharedMask;
  35193. }
  35194. /* Get shared locks at the system level, if necessary */
  35195. if( rc==SQLITE_OK ){
  35196. if( (allShared & mask)==0 ){
  35197. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  35198. }else{
  35199. rc = SQLITE_OK;
  35200. }
  35201. }
  35202. /* Get the local shared locks */
  35203. if( rc==SQLITE_OK ){
  35204. p->sharedMask |= mask;
  35205. }
  35206. }else{
  35207. /* Make sure no sibling connections hold locks that will block this
  35208. ** lock. If any do, return SQLITE_BUSY right away.
  35209. */
  35210. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35211. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  35212. rc = SQLITE_BUSY;
  35213. break;
  35214. }
  35215. }
  35216. /* Get the exclusive locks at the system level. Then if successful
  35217. ** also mark the local connection as being locked.
  35218. */
  35219. if( rc==SQLITE_OK ){
  35220. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  35221. if( rc==SQLITE_OK ){
  35222. assert( (p->sharedMask & mask)==0 );
  35223. p->exclMask |= mask;
  35224. }
  35225. }
  35226. }
  35227. sqlite3_mutex_leave(pShmNode->pShmMutex);
  35228. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  35229. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  35230. return rc;
  35231. }
  35232. /*
  35233. ** Implement a memory barrier or memory fence on shared memory.
  35234. **
  35235. ** All loads and stores begun before the barrier must complete before
  35236. ** any load or store begun after the barrier.
  35237. */
  35238. static void unixShmBarrier(
  35239. sqlite3_file *fd /* Database file holding the shared memory */
  35240. ){
  35241. UNUSED_PARAMETER(fd);
  35242. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  35243. assert( fd->pMethods->xLock==nolockLock
  35244. || unixFileMutexNotheld((unixFile*)fd)
  35245. );
  35246. unixEnterMutex(); /* Also mutex, for redundancy */
  35247. unixLeaveMutex();
  35248. }
  35249. /*
  35250. ** Close a connection to shared-memory. Delete the underlying
  35251. ** storage if deleteFlag is true.
  35252. **
  35253. ** If there is no shared memory associated with the connection then this
  35254. ** routine is a harmless no-op.
  35255. */
  35256. static int unixShmUnmap(
  35257. sqlite3_file *fd, /* The underlying database file */
  35258. int deleteFlag /* Delete shared-memory if true */
  35259. ){
  35260. unixShm *p; /* The connection to be closed */
  35261. unixShmNode *pShmNode; /* The underlying shared-memory file */
  35262. unixShm **pp; /* For looping over sibling connections */
  35263. unixFile *pDbFd; /* The underlying database file */
  35264. pDbFd = (unixFile*)fd;
  35265. p = pDbFd->pShm;
  35266. if( p==0 ) return SQLITE_OK;
  35267. pShmNode = p->pShmNode;
  35268. assert( pShmNode==pDbFd->pInode->pShmNode );
  35269. assert( pShmNode->pInode==pDbFd->pInode );
  35270. /* Remove connection p from the set of connections associated
  35271. ** with pShmNode */
  35272. sqlite3_mutex_enter(pShmNode->pShmMutex);
  35273. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  35274. *pp = p->pNext;
  35275. /* Free the connection p */
  35276. sqlite3_free(p);
  35277. pDbFd->pShm = 0;
  35278. sqlite3_mutex_leave(pShmNode->pShmMutex);
  35279. /* If pShmNode->nRef has reached 0, then close the underlying
  35280. ** shared-memory file, too */
  35281. assert( unixFileMutexNotheld(pDbFd) );
  35282. unixEnterMutex();
  35283. assert( pShmNode->nRef>0 );
  35284. pShmNode->nRef--;
  35285. if( pShmNode->nRef==0 ){
  35286. if( deleteFlag && pShmNode->hShm>=0 ){
  35287. osUnlink(pShmNode->zFilename);
  35288. }
  35289. unixShmPurge(pDbFd);
  35290. }
  35291. unixLeaveMutex();
  35292. return SQLITE_OK;
  35293. }
  35294. #else
  35295. # define unixShmMap 0
  35296. # define unixShmLock 0
  35297. # define unixShmBarrier 0
  35298. # define unixShmUnmap 0
  35299. #endif /* #ifndef SQLITE_OMIT_WAL */
  35300. #if SQLITE_MAX_MMAP_SIZE>0
  35301. /*
  35302. ** If it is currently memory mapped, unmap file pFd.
  35303. */
  35304. static void unixUnmapfile(unixFile *pFd){
  35305. assert( pFd->nFetchOut==0 );
  35306. if( pFd->pMapRegion ){
  35307. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  35308. pFd->pMapRegion = 0;
  35309. pFd->mmapSize = 0;
  35310. pFd->mmapSizeActual = 0;
  35311. }
  35312. }
  35313. /*
  35314. ** Attempt to set the size of the memory mapping maintained by file
  35315. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  35316. **
  35317. ** If successful, this function sets the following variables:
  35318. **
  35319. ** unixFile.pMapRegion
  35320. ** unixFile.mmapSize
  35321. ** unixFile.mmapSizeActual
  35322. **
  35323. ** If unsuccessful, an error message is logged via sqlite3_log() and
  35324. ** the three variables above are zeroed. In this case SQLite should
  35325. ** continue accessing the database using the xRead() and xWrite()
  35326. ** methods.
  35327. */
  35328. static void unixRemapfile(
  35329. unixFile *pFd, /* File descriptor object */
  35330. i64 nNew /* Required mapping size */
  35331. ){
  35332. const char *zErr = "mmap";
  35333. int h = pFd->h; /* File descriptor open on db file */
  35334. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  35335. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  35336. u8 *pNew = 0; /* Location of new mapping */
  35337. int flags = PROT_READ; /* Flags to pass to mmap() */
  35338. assert( pFd->nFetchOut==0 );
  35339. assert( nNew>pFd->mmapSize );
  35340. assert( nNew<=pFd->mmapSizeMax );
  35341. assert( nNew>0 );
  35342. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  35343. assert( MAP_FAILED!=0 );
  35344. #ifdef SQLITE_MMAP_READWRITE
  35345. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  35346. #endif
  35347. if( pOrig ){
  35348. #if HAVE_MREMAP
  35349. i64 nReuse = pFd->mmapSize;
  35350. #else
  35351. const int szSyspage = osGetpagesize();
  35352. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  35353. #endif
  35354. u8 *pReq = &pOrig[nReuse];
  35355. /* Unmap any pages of the existing mapping that cannot be reused. */
  35356. if( nReuse!=nOrig ){
  35357. osMunmap(pReq, nOrig-nReuse);
  35358. }
  35359. #if HAVE_MREMAP
  35360. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  35361. zErr = "mremap";
  35362. #else
  35363. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  35364. if( pNew!=MAP_FAILED ){
  35365. if( pNew!=pReq ){
  35366. osMunmap(pNew, nNew - nReuse);
  35367. pNew = 0;
  35368. }else{
  35369. pNew = pOrig;
  35370. }
  35371. }
  35372. #endif
  35373. /* The attempt to extend the existing mapping failed. Free it. */
  35374. if( pNew==MAP_FAILED || pNew==0 ){
  35375. osMunmap(pOrig, nReuse);
  35376. }
  35377. }
  35378. /* If pNew is still NULL, try to create an entirely new mapping. */
  35379. if( pNew==0 ){
  35380. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  35381. }
  35382. if( pNew==MAP_FAILED ){
  35383. pNew = 0;
  35384. nNew = 0;
  35385. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  35386. /* If the mmap() above failed, assume that all subsequent mmap() calls
  35387. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  35388. ** in this case. */
  35389. pFd->mmapSizeMax = 0;
  35390. }
  35391. pFd->pMapRegion = (void *)pNew;
  35392. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  35393. }
  35394. /*
  35395. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  35396. ** is already mapped, the existing mapping is replaced by the new). Or, if
  35397. ** there already exists a mapping for this file, and there are still
  35398. ** outstanding xFetch() references to it, this function is a no-op.
  35399. **
  35400. ** If parameter nByte is non-negative, then it is the requested size of
  35401. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  35402. ** requested size is the size of the file on disk. The actual size of the
  35403. ** created mapping is either the requested size or the value configured
  35404. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  35405. **
  35406. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  35407. ** recreated as a result of outstanding references) or an SQLite error
  35408. ** code otherwise.
  35409. */
  35410. static int unixMapfile(unixFile *pFd, i64 nMap){
  35411. assert( nMap>=0 || pFd->nFetchOut==0 );
  35412. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  35413. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  35414. if( nMap<0 ){
  35415. struct stat statbuf; /* Low-level file information */
  35416. if( osFstat(pFd->h, &statbuf) ){
  35417. return SQLITE_IOERR_FSTAT;
  35418. }
  35419. nMap = statbuf.st_size;
  35420. }
  35421. if( nMap>pFd->mmapSizeMax ){
  35422. nMap = pFd->mmapSizeMax;
  35423. }
  35424. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  35425. if( nMap!=pFd->mmapSize ){
  35426. unixRemapfile(pFd, nMap);
  35427. }
  35428. return SQLITE_OK;
  35429. }
  35430. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  35431. /*
  35432. ** If possible, return a pointer to a mapping of file fd starting at offset
  35433. ** iOff. The mapping must be valid for at least nAmt bytes.
  35434. **
  35435. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  35436. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  35437. ** Finally, if an error does occur, return an SQLite error code. The final
  35438. ** value of *pp is undefined in this case.
  35439. **
  35440. ** If this function does return a pointer, the caller must eventually
  35441. ** release the reference by calling unixUnfetch().
  35442. */
  35443. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  35444. #if SQLITE_MAX_MMAP_SIZE>0
  35445. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  35446. #endif
  35447. *pp = 0;
  35448. #if SQLITE_MAX_MMAP_SIZE>0
  35449. if( pFd->mmapSizeMax>0 ){
  35450. if( pFd->pMapRegion==0 ){
  35451. int rc = unixMapfile(pFd, -1);
  35452. if( rc!=SQLITE_OK ) return rc;
  35453. }
  35454. if( pFd->mmapSize >= iOff+nAmt ){
  35455. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  35456. pFd->nFetchOut++;
  35457. }
  35458. }
  35459. #endif
  35460. return SQLITE_OK;
  35461. }
  35462. /*
  35463. ** If the third argument is non-NULL, then this function releases a
  35464. ** reference obtained by an earlier call to unixFetch(). The second
  35465. ** argument passed to this function must be the same as the corresponding
  35466. ** argument that was passed to the unixFetch() invocation.
  35467. **
  35468. ** Or, if the third argument is NULL, then this function is being called
  35469. ** to inform the VFS layer that, according to POSIX, any existing mapping
  35470. ** may now be invalid and should be unmapped.
  35471. */
  35472. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  35473. #if SQLITE_MAX_MMAP_SIZE>0
  35474. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  35475. UNUSED_PARAMETER(iOff);
  35476. /* If p==0 (unmap the entire file) then there must be no outstanding
  35477. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  35478. ** then there must be at least one outstanding. */
  35479. assert( (p==0)==(pFd->nFetchOut==0) );
  35480. /* If p!=0, it must match the iOff value. */
  35481. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  35482. if( p ){
  35483. pFd->nFetchOut--;
  35484. }else{
  35485. unixUnmapfile(pFd);
  35486. }
  35487. assert( pFd->nFetchOut>=0 );
  35488. #else
  35489. UNUSED_PARAMETER(fd);
  35490. UNUSED_PARAMETER(p);
  35491. UNUSED_PARAMETER(iOff);
  35492. #endif
  35493. return SQLITE_OK;
  35494. }
  35495. /*
  35496. ** Here ends the implementation of all sqlite3_file methods.
  35497. **
  35498. ********************** End sqlite3_file Methods *******************************
  35499. ******************************************************************************/
  35500. /*
  35501. ** This division contains definitions of sqlite3_io_methods objects that
  35502. ** implement various file locking strategies. It also contains definitions
  35503. ** of "finder" functions. A finder-function is used to locate the appropriate
  35504. ** sqlite3_io_methods object for a particular database file. The pAppData
  35505. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  35506. ** the correct finder-function for that VFS.
  35507. **
  35508. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  35509. ** object. The only interesting finder-function is autolockIoFinder, which
  35510. ** looks at the filesystem type and tries to guess the best locking
  35511. ** strategy from that.
  35512. **
  35513. ** For finder-function F, two objects are created:
  35514. **
  35515. ** (1) The real finder-function named "FImpt()".
  35516. **
  35517. ** (2) A constant pointer to this function named just "F".
  35518. **
  35519. **
  35520. ** A pointer to the F pointer is used as the pAppData value for VFS
  35521. ** objects. We have to do this instead of letting pAppData point
  35522. ** directly at the finder-function since C90 rules prevent a void*
  35523. ** from be cast into a function pointer.
  35524. **
  35525. **
  35526. ** Each instance of this macro generates two objects:
  35527. **
  35528. ** * A constant sqlite3_io_methods object call METHOD that has locking
  35529. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  35530. **
  35531. ** * An I/O method finder function called FINDER that returns a pointer
  35532. ** to the METHOD object in the previous bullet.
  35533. */
  35534. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  35535. static const sqlite3_io_methods METHOD = { \
  35536. VERSION, /* iVersion */ \
  35537. CLOSE, /* xClose */ \
  35538. unixRead, /* xRead */ \
  35539. unixWrite, /* xWrite */ \
  35540. unixTruncate, /* xTruncate */ \
  35541. unixSync, /* xSync */ \
  35542. unixFileSize, /* xFileSize */ \
  35543. LOCK, /* xLock */ \
  35544. UNLOCK, /* xUnlock */ \
  35545. CKLOCK, /* xCheckReservedLock */ \
  35546. unixFileControl, /* xFileControl */ \
  35547. unixSectorSize, /* xSectorSize */ \
  35548. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  35549. SHMMAP, /* xShmMap */ \
  35550. unixShmLock, /* xShmLock */ \
  35551. unixShmBarrier, /* xShmBarrier */ \
  35552. unixShmUnmap, /* xShmUnmap */ \
  35553. unixFetch, /* xFetch */ \
  35554. unixUnfetch, /* xUnfetch */ \
  35555. }; \
  35556. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  35557. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  35558. return &METHOD; \
  35559. } \
  35560. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  35561. = FINDER##Impl;
  35562. /*
  35563. ** Here are all of the sqlite3_io_methods objects for each of the
  35564. ** locking strategies. Functions that return pointers to these methods
  35565. ** are also created.
  35566. */
  35567. IOMETHODS(
  35568. posixIoFinder, /* Finder function name */
  35569. posixIoMethods, /* sqlite3_io_methods object name */
  35570. 3, /* shared memory and mmap are enabled */
  35571. unixClose, /* xClose method */
  35572. unixLock, /* xLock method */
  35573. unixUnlock, /* xUnlock method */
  35574. unixCheckReservedLock, /* xCheckReservedLock method */
  35575. unixShmMap /* xShmMap method */
  35576. )
  35577. IOMETHODS(
  35578. nolockIoFinder, /* Finder function name */
  35579. nolockIoMethods, /* sqlite3_io_methods object name */
  35580. 3, /* shared memory and mmap are enabled */
  35581. nolockClose, /* xClose method */
  35582. nolockLock, /* xLock method */
  35583. nolockUnlock, /* xUnlock method */
  35584. nolockCheckReservedLock, /* xCheckReservedLock method */
  35585. 0 /* xShmMap method */
  35586. )
  35587. IOMETHODS(
  35588. dotlockIoFinder, /* Finder function name */
  35589. dotlockIoMethods, /* sqlite3_io_methods object name */
  35590. 1, /* shared memory is disabled */
  35591. dotlockClose, /* xClose method */
  35592. dotlockLock, /* xLock method */
  35593. dotlockUnlock, /* xUnlock method */
  35594. dotlockCheckReservedLock, /* xCheckReservedLock method */
  35595. 0 /* xShmMap method */
  35596. )
  35597. #if SQLITE_ENABLE_LOCKING_STYLE
  35598. IOMETHODS(
  35599. flockIoFinder, /* Finder function name */
  35600. flockIoMethods, /* sqlite3_io_methods object name */
  35601. 1, /* shared memory is disabled */
  35602. flockClose, /* xClose method */
  35603. flockLock, /* xLock method */
  35604. flockUnlock, /* xUnlock method */
  35605. flockCheckReservedLock, /* xCheckReservedLock method */
  35606. 0 /* xShmMap method */
  35607. )
  35608. #endif
  35609. #if OS_VXWORKS
  35610. IOMETHODS(
  35611. semIoFinder, /* Finder function name */
  35612. semIoMethods, /* sqlite3_io_methods object name */
  35613. 1, /* shared memory is disabled */
  35614. semXClose, /* xClose method */
  35615. semXLock, /* xLock method */
  35616. semXUnlock, /* xUnlock method */
  35617. semXCheckReservedLock, /* xCheckReservedLock method */
  35618. 0 /* xShmMap method */
  35619. )
  35620. #endif
  35621. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35622. IOMETHODS(
  35623. afpIoFinder, /* Finder function name */
  35624. afpIoMethods, /* sqlite3_io_methods object name */
  35625. 1, /* shared memory is disabled */
  35626. afpClose, /* xClose method */
  35627. afpLock, /* xLock method */
  35628. afpUnlock, /* xUnlock method */
  35629. afpCheckReservedLock, /* xCheckReservedLock method */
  35630. 0 /* xShmMap method */
  35631. )
  35632. #endif
  35633. /*
  35634. ** The proxy locking method is a "super-method" in the sense that it
  35635. ** opens secondary file descriptors for the conch and lock files and
  35636. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  35637. ** secondary files. For this reason, the division that implements
  35638. ** proxy locking is located much further down in the file. But we need
  35639. ** to go ahead and define the sqlite3_io_methods and finder function
  35640. ** for proxy locking here. So we forward declare the I/O methods.
  35641. */
  35642. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35643. static int proxyClose(sqlite3_file*);
  35644. static int proxyLock(sqlite3_file*, int);
  35645. static int proxyUnlock(sqlite3_file*, int);
  35646. static int proxyCheckReservedLock(sqlite3_file*, int*);
  35647. IOMETHODS(
  35648. proxyIoFinder, /* Finder function name */
  35649. proxyIoMethods, /* sqlite3_io_methods object name */
  35650. 1, /* shared memory is disabled */
  35651. proxyClose, /* xClose method */
  35652. proxyLock, /* xLock method */
  35653. proxyUnlock, /* xUnlock method */
  35654. proxyCheckReservedLock, /* xCheckReservedLock method */
  35655. 0 /* xShmMap method */
  35656. )
  35657. #endif
  35658. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  35659. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35660. IOMETHODS(
  35661. nfsIoFinder, /* Finder function name */
  35662. nfsIoMethods, /* sqlite3_io_methods object name */
  35663. 1, /* shared memory is disabled */
  35664. unixClose, /* xClose method */
  35665. unixLock, /* xLock method */
  35666. nfsUnlock, /* xUnlock method */
  35667. unixCheckReservedLock, /* xCheckReservedLock method */
  35668. 0 /* xShmMap method */
  35669. )
  35670. #endif
  35671. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35672. /*
  35673. ** This "finder" function attempts to determine the best locking strategy
  35674. ** for the database file "filePath". It then returns the sqlite3_io_methods
  35675. ** object that implements that strategy.
  35676. **
  35677. ** This is for MacOSX only.
  35678. */
  35679. static const sqlite3_io_methods *autolockIoFinderImpl(
  35680. const char *filePath, /* name of the database file */
  35681. unixFile *pNew /* open file object for the database file */
  35682. ){
  35683. static const struct Mapping {
  35684. const char *zFilesystem; /* Filesystem type name */
  35685. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  35686. } aMap[] = {
  35687. { "hfs", &posixIoMethods },
  35688. { "ufs", &posixIoMethods },
  35689. { "afpfs", &afpIoMethods },
  35690. { "smbfs", &afpIoMethods },
  35691. { "webdav", &nolockIoMethods },
  35692. { 0, 0 }
  35693. };
  35694. int i;
  35695. struct statfs fsInfo;
  35696. struct flock lockInfo;
  35697. if( !filePath ){
  35698. /* If filePath==NULL that means we are dealing with a transient file
  35699. ** that does not need to be locked. */
  35700. return &nolockIoMethods;
  35701. }
  35702. if( statfs(filePath, &fsInfo) != -1 ){
  35703. if( fsInfo.f_flags & MNT_RDONLY ){
  35704. return &nolockIoMethods;
  35705. }
  35706. for(i=0; aMap[i].zFilesystem; i++){
  35707. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  35708. return aMap[i].pMethods;
  35709. }
  35710. }
  35711. }
  35712. /* Default case. Handles, amongst others, "nfs".
  35713. ** Test byte-range lock using fcntl(). If the call succeeds,
  35714. ** assume that the file-system supports POSIX style locks.
  35715. */
  35716. lockInfo.l_len = 1;
  35717. lockInfo.l_start = 0;
  35718. lockInfo.l_whence = SEEK_SET;
  35719. lockInfo.l_type = F_RDLCK;
  35720. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  35721. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  35722. return &nfsIoMethods;
  35723. } else {
  35724. return &posixIoMethods;
  35725. }
  35726. }else{
  35727. return &dotlockIoMethods;
  35728. }
  35729. }
  35730. static const sqlite3_io_methods
  35731. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  35732. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  35733. #if OS_VXWORKS
  35734. /*
  35735. ** This "finder" function for VxWorks checks to see if posix advisory
  35736. ** locking works. If it does, then that is what is used. If it does not
  35737. ** work, then fallback to named semaphore locking.
  35738. */
  35739. static const sqlite3_io_methods *vxworksIoFinderImpl(
  35740. const char *filePath, /* name of the database file */
  35741. unixFile *pNew /* the open file object */
  35742. ){
  35743. struct flock lockInfo;
  35744. if( !filePath ){
  35745. /* If filePath==NULL that means we are dealing with a transient file
  35746. ** that does not need to be locked. */
  35747. return &nolockIoMethods;
  35748. }
  35749. /* Test if fcntl() is supported and use POSIX style locks.
  35750. ** Otherwise fall back to the named semaphore method.
  35751. */
  35752. lockInfo.l_len = 1;
  35753. lockInfo.l_start = 0;
  35754. lockInfo.l_whence = SEEK_SET;
  35755. lockInfo.l_type = F_RDLCK;
  35756. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  35757. return &posixIoMethods;
  35758. }else{
  35759. return &semIoMethods;
  35760. }
  35761. }
  35762. static const sqlite3_io_methods
  35763. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  35764. #endif /* OS_VXWORKS */
  35765. /*
  35766. ** An abstract type for a pointer to an IO method finder function:
  35767. */
  35768. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  35769. /****************************************************************************
  35770. **************************** sqlite3_vfs methods ****************************
  35771. **
  35772. ** This division contains the implementation of methods on the
  35773. ** sqlite3_vfs object.
  35774. */
  35775. /*
  35776. ** Initialize the contents of the unixFile structure pointed to by pId.
  35777. */
  35778. static int fillInUnixFile(
  35779. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  35780. int h, /* Open file descriptor of file being opened */
  35781. sqlite3_file *pId, /* Write to the unixFile structure here */
  35782. const char *zFilename, /* Name of the file being opened */
  35783. int ctrlFlags /* Zero or more UNIXFILE_* values */
  35784. ){
  35785. const sqlite3_io_methods *pLockingStyle;
  35786. unixFile *pNew = (unixFile *)pId;
  35787. int rc = SQLITE_OK;
  35788. assert( pNew->pInode==NULL );
  35789. /* No locking occurs in temporary files */
  35790. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  35791. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  35792. pNew->h = h;
  35793. pNew->pVfs = pVfs;
  35794. pNew->zPath = zFilename;
  35795. pNew->ctrlFlags = (u8)ctrlFlags;
  35796. #if SQLITE_MAX_MMAP_SIZE>0
  35797. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  35798. #endif
  35799. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  35800. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  35801. pNew->ctrlFlags |= UNIXFILE_PSOW;
  35802. }
  35803. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  35804. pNew->ctrlFlags |= UNIXFILE_EXCL;
  35805. }
  35806. #if OS_VXWORKS
  35807. pNew->pId = vxworksFindFileId(zFilename);
  35808. if( pNew->pId==0 ){
  35809. ctrlFlags |= UNIXFILE_NOLOCK;
  35810. rc = SQLITE_NOMEM_BKPT;
  35811. }
  35812. #endif
  35813. if( ctrlFlags & UNIXFILE_NOLOCK ){
  35814. pLockingStyle = &nolockIoMethods;
  35815. }else{
  35816. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  35817. #if SQLITE_ENABLE_LOCKING_STYLE
  35818. /* Cache zFilename in the locking context (AFP and dotlock override) for
  35819. ** proxyLock activation is possible (remote proxy is based on db name)
  35820. ** zFilename remains valid until file is closed, to support */
  35821. pNew->lockingContext = (void*)zFilename;
  35822. #endif
  35823. }
  35824. if( pLockingStyle == &posixIoMethods
  35825. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35826. || pLockingStyle == &nfsIoMethods
  35827. #endif
  35828. ){
  35829. unixEnterMutex();
  35830. rc = findInodeInfo(pNew, &pNew->pInode);
  35831. if( rc!=SQLITE_OK ){
  35832. /* If an error occurred in findInodeInfo(), close the file descriptor
  35833. ** immediately, before releasing the mutex. findInodeInfo() may fail
  35834. ** in two scenarios:
  35835. **
  35836. ** (a) A call to fstat() failed.
  35837. ** (b) A malloc failed.
  35838. **
  35839. ** Scenario (b) may only occur if the process is holding no other
  35840. ** file descriptors open on the same file. If there were other file
  35841. ** descriptors on this file, then no malloc would be required by
  35842. ** findInodeInfo(). If this is the case, it is quite safe to close
  35843. ** handle h - as it is guaranteed that no posix locks will be released
  35844. ** by doing so.
  35845. **
  35846. ** If scenario (a) caused the error then things are not so safe. The
  35847. ** implicit assumption here is that if fstat() fails, things are in
  35848. ** such bad shape that dropping a lock or two doesn't matter much.
  35849. */
  35850. robust_close(pNew, h, __LINE__);
  35851. h = -1;
  35852. }
  35853. unixLeaveMutex();
  35854. }
  35855. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35856. else if( pLockingStyle == &afpIoMethods ){
  35857. /* AFP locking uses the file path so it needs to be included in
  35858. ** the afpLockingContext.
  35859. */
  35860. afpLockingContext *pCtx;
  35861. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  35862. if( pCtx==0 ){
  35863. rc = SQLITE_NOMEM_BKPT;
  35864. }else{
  35865. /* NB: zFilename exists and remains valid until the file is closed
  35866. ** according to requirement F11141. So we do not need to make a
  35867. ** copy of the filename. */
  35868. pCtx->dbPath = zFilename;
  35869. pCtx->reserved = 0;
  35870. srandomdev();
  35871. unixEnterMutex();
  35872. rc = findInodeInfo(pNew, &pNew->pInode);
  35873. if( rc!=SQLITE_OK ){
  35874. sqlite3_free(pNew->lockingContext);
  35875. robust_close(pNew, h, __LINE__);
  35876. h = -1;
  35877. }
  35878. unixLeaveMutex();
  35879. }
  35880. }
  35881. #endif
  35882. else if( pLockingStyle == &dotlockIoMethods ){
  35883. /* Dotfile locking uses the file path so it needs to be included in
  35884. ** the dotlockLockingContext
  35885. */
  35886. char *zLockFile;
  35887. int nFilename;
  35888. assert( zFilename!=0 );
  35889. nFilename = (int)strlen(zFilename) + 6;
  35890. zLockFile = (char *)sqlite3_malloc64(nFilename);
  35891. if( zLockFile==0 ){
  35892. rc = SQLITE_NOMEM_BKPT;
  35893. }else{
  35894. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  35895. }
  35896. pNew->lockingContext = zLockFile;
  35897. }
  35898. #if OS_VXWORKS
  35899. else if( pLockingStyle == &semIoMethods ){
  35900. /* Named semaphore locking uses the file path so it needs to be
  35901. ** included in the semLockingContext
  35902. */
  35903. unixEnterMutex();
  35904. rc = findInodeInfo(pNew, &pNew->pInode);
  35905. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  35906. char *zSemName = pNew->pInode->aSemName;
  35907. int n;
  35908. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  35909. pNew->pId->zCanonicalName);
  35910. for( n=1; zSemName[n]; n++ )
  35911. if( zSemName[n]=='/' ) zSemName[n] = '_';
  35912. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  35913. if( pNew->pInode->pSem == SEM_FAILED ){
  35914. rc = SQLITE_NOMEM_BKPT;
  35915. pNew->pInode->aSemName[0] = '\0';
  35916. }
  35917. }
  35918. unixLeaveMutex();
  35919. }
  35920. #endif
  35921. storeLastErrno(pNew, 0);
  35922. #if OS_VXWORKS
  35923. if( rc!=SQLITE_OK ){
  35924. if( h>=0 ) robust_close(pNew, h, __LINE__);
  35925. h = -1;
  35926. osUnlink(zFilename);
  35927. pNew->ctrlFlags |= UNIXFILE_DELETE;
  35928. }
  35929. #endif
  35930. if( rc!=SQLITE_OK ){
  35931. if( h>=0 ) robust_close(pNew, h, __LINE__);
  35932. }else{
  35933. pNew->pMethod = pLockingStyle;
  35934. OpenCounter(+1);
  35935. verifyDbFile(pNew);
  35936. }
  35937. return rc;
  35938. }
  35939. /*
  35940. ** Return the name of a directory in which to put temporary files.
  35941. ** If no suitable temporary file directory can be found, return NULL.
  35942. */
  35943. static const char *unixTempFileDir(void){
  35944. static const char *azDirs[] = {
  35945. 0,
  35946. 0,
  35947. "/var/tmp",
  35948. "/usr/tmp",
  35949. "/tmp",
  35950. "."
  35951. };
  35952. unsigned int i = 0;
  35953. struct stat buf;
  35954. const char *zDir = sqlite3_temp_directory;
  35955. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  35956. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  35957. while(1){
  35958. if( zDir!=0
  35959. && osStat(zDir, &buf)==0
  35960. && S_ISDIR(buf.st_mode)
  35961. && osAccess(zDir, 03)==0
  35962. ){
  35963. return zDir;
  35964. }
  35965. if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
  35966. zDir = azDirs[i++];
  35967. }
  35968. return 0;
  35969. }
  35970. /*
  35971. ** Create a temporary file name in zBuf. zBuf must be allocated
  35972. ** by the calling process and must be big enough to hold at least
  35973. ** pVfs->mxPathname bytes.
  35974. */
  35975. static int unixGetTempname(int nBuf, char *zBuf){
  35976. const char *zDir;
  35977. int iLimit = 0;
  35978. /* It's odd to simulate an io-error here, but really this is just
  35979. ** using the io-error infrastructure to test that SQLite handles this
  35980. ** function failing.
  35981. */
  35982. zBuf[0] = 0;
  35983. SimulateIOError( return SQLITE_IOERR );
  35984. zDir = unixTempFileDir();
  35985. if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
  35986. do{
  35987. u64 r;
  35988. sqlite3_randomness(sizeof(r), &r);
  35989. assert( nBuf>2 );
  35990. zBuf[nBuf-2] = 0;
  35991. sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
  35992. zDir, r, 0);
  35993. if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
  35994. }while( osAccess(zBuf,0)==0 );
  35995. return SQLITE_OK;
  35996. }
  35997. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35998. /*
  35999. ** Routine to transform a unixFile into a proxy-locking unixFile.
  36000. ** Implementation in the proxy-lock division, but used by unixOpen()
  36001. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  36002. */
  36003. static int proxyTransformUnixFile(unixFile*, const char*);
  36004. #endif
  36005. /*
  36006. ** Search for an unused file descriptor that was opened on the database
  36007. ** file (not a journal or master-journal file) identified by pathname
  36008. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  36009. ** argument to this function.
  36010. **
  36011. ** Such a file descriptor may exist if a database connection was closed
  36012. ** but the associated file descriptor could not be closed because some
  36013. ** other file descriptor open on the same file is holding a file-lock.
  36014. ** Refer to comments in the unixClose() function and the lengthy comment
  36015. ** describing "Posix Advisory Locking" at the start of this file for
  36016. ** further details. Also, ticket #4018.
  36017. **
  36018. ** If a suitable file descriptor is found, then it is returned. If no
  36019. ** such file descriptor is located, -1 is returned.
  36020. */
  36021. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  36022. UnixUnusedFd *pUnused = 0;
  36023. /* Do not search for an unused file descriptor on vxworks. Not because
  36024. ** vxworks would not benefit from the change (it might, we're not sure),
  36025. ** but because no way to test it is currently available. It is better
  36026. ** not to risk breaking vxworks support for the sake of such an obscure
  36027. ** feature. */
  36028. #if !OS_VXWORKS
  36029. struct stat sStat; /* Results of stat() call */
  36030. unixEnterMutex();
  36031. /* A stat() call may fail for various reasons. If this happens, it is
  36032. ** almost certain that an open() call on the same path will also fail.
  36033. ** For this reason, if an error occurs in the stat() call here, it is
  36034. ** ignored and -1 is returned. The caller will try to open a new file
  36035. ** descriptor on the same path, fail, and return an error to SQLite.
  36036. **
  36037. ** Even if a subsequent open() call does succeed, the consequences of
  36038. ** not searching for a reusable file descriptor are not dire. */
  36039. if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
  36040. unixInodeInfo *pInode;
  36041. pInode = inodeList;
  36042. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  36043. || pInode->fileId.ino!=(u64)sStat.st_ino) ){
  36044. pInode = pInode->pNext;
  36045. }
  36046. if( pInode ){
  36047. UnixUnusedFd **pp;
  36048. assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
  36049. sqlite3_mutex_enter(pInode->pLockMutex);
  36050. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  36051. pUnused = *pp;
  36052. if( pUnused ){
  36053. *pp = pUnused->pNext;
  36054. }
  36055. sqlite3_mutex_leave(pInode->pLockMutex);
  36056. }
  36057. }
  36058. unixLeaveMutex();
  36059. #endif /* if !OS_VXWORKS */
  36060. return pUnused;
  36061. }
  36062. /*
  36063. ** Find the mode, uid and gid of file zFile.
  36064. */
  36065. static int getFileMode(
  36066. const char *zFile, /* File name */
  36067. mode_t *pMode, /* OUT: Permissions of zFile */
  36068. uid_t *pUid, /* OUT: uid of zFile. */
  36069. gid_t *pGid /* OUT: gid of zFile. */
  36070. ){
  36071. struct stat sStat; /* Output of stat() on database file */
  36072. int rc = SQLITE_OK;
  36073. if( 0==osStat(zFile, &sStat) ){
  36074. *pMode = sStat.st_mode & 0777;
  36075. *pUid = sStat.st_uid;
  36076. *pGid = sStat.st_gid;
  36077. }else{
  36078. rc = SQLITE_IOERR_FSTAT;
  36079. }
  36080. return rc;
  36081. }
  36082. /*
  36083. ** This function is called by unixOpen() to determine the unix permissions
  36084. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  36085. ** and a value suitable for passing as the third argument to open(2) is
  36086. ** written to *pMode. If an IO error occurs, an SQLite error code is
  36087. ** returned and the value of *pMode is not modified.
  36088. **
  36089. ** In most cases, this routine sets *pMode to 0, which will become
  36090. ** an indication to robust_open() to create the file using
  36091. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  36092. ** But if the file being opened is a WAL or regular journal file, then
  36093. ** this function queries the file-system for the permissions on the
  36094. ** corresponding database file and sets *pMode to this value. Whenever
  36095. ** possible, WAL and journal files are created using the same permissions
  36096. ** as the associated database file.
  36097. **
  36098. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  36099. ** original filename is unavailable. But 8_3_NAMES is only used for
  36100. ** FAT filesystems and permissions do not matter there, so just use
  36101. ** the default permissions.
  36102. */
  36103. static int findCreateFileMode(
  36104. const char *zPath, /* Path of file (possibly) being created */
  36105. int flags, /* Flags passed as 4th argument to xOpen() */
  36106. mode_t *pMode, /* OUT: Permissions to open file with */
  36107. uid_t *pUid, /* OUT: uid to set on the file */
  36108. gid_t *pGid /* OUT: gid to set on the file */
  36109. ){
  36110. int rc = SQLITE_OK; /* Return Code */
  36111. *pMode = 0;
  36112. *pUid = 0;
  36113. *pGid = 0;
  36114. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  36115. char zDb[MAX_PATHNAME+1]; /* Database file path */
  36116. int nDb; /* Number of valid bytes in zDb */
  36117. /* zPath is a path to a WAL or journal file. The following block derives
  36118. ** the path to the associated database file from zPath. This block handles
  36119. ** the following naming conventions:
  36120. **
  36121. ** "<path to db>-journal"
  36122. ** "<path to db>-wal"
  36123. ** "<path to db>-journalNN"
  36124. ** "<path to db>-walNN"
  36125. **
  36126. ** where NN is a decimal number. The NN naming schemes are
  36127. ** used by the test_multiplex.c module.
  36128. */
  36129. nDb = sqlite3Strlen30(zPath) - 1;
  36130. while( zPath[nDb]!='-' ){
  36131. /* In normal operation, the journal file name will always contain
  36132. ** a '-' character. However in 8+3 filename mode, or if a corrupt
  36133. ** rollback journal specifies a master journal with a goofy name, then
  36134. ** the '-' might be missing. */
  36135. if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  36136. nDb--;
  36137. }
  36138. memcpy(zDb, zPath, nDb);
  36139. zDb[nDb] = '\0';
  36140. rc = getFileMode(zDb, pMode, pUid, pGid);
  36141. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  36142. *pMode = 0600;
  36143. }else if( flags & SQLITE_OPEN_URI ){
  36144. /* If this is a main database file and the file was opened using a URI
  36145. ** filename, check for the "modeof" parameter. If present, interpret
  36146. ** its value as a filename and try to copy the mode, uid and gid from
  36147. ** that file. */
  36148. const char *z = sqlite3_uri_parameter(zPath, "modeof");
  36149. if( z ){
  36150. rc = getFileMode(z, pMode, pUid, pGid);
  36151. }
  36152. }
  36153. return rc;
  36154. }
  36155. /*
  36156. ** Open the file zPath.
  36157. **
  36158. ** Previously, the SQLite OS layer used three functions in place of this
  36159. ** one:
  36160. **
  36161. ** sqlite3OsOpenReadWrite();
  36162. ** sqlite3OsOpenReadOnly();
  36163. ** sqlite3OsOpenExclusive();
  36164. **
  36165. ** These calls correspond to the following combinations of flags:
  36166. **
  36167. ** ReadWrite() -> (READWRITE | CREATE)
  36168. ** ReadOnly() -> (READONLY)
  36169. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  36170. **
  36171. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  36172. ** true, the file was configured to be automatically deleted when the
  36173. ** file handle closed. To achieve the same effect using this new
  36174. ** interface, add the DELETEONCLOSE flag to those specified above for
  36175. ** OpenExclusive().
  36176. */
  36177. static int unixOpen(
  36178. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  36179. const char *zPath, /* Pathname of file to be opened */
  36180. sqlite3_file *pFile, /* The file descriptor to be filled in */
  36181. int flags, /* Input flags to control the opening */
  36182. int *pOutFlags /* Output flags returned to SQLite core */
  36183. ){
  36184. unixFile *p = (unixFile *)pFile;
  36185. int fd = -1; /* File descriptor returned by open() */
  36186. int openFlags = 0; /* Flags to pass to open() */
  36187. int eType = flags&0xFFFFFF00; /* Type of file to open */
  36188. int noLock; /* True to omit locking primitives */
  36189. int rc = SQLITE_OK; /* Function Return Code */
  36190. int ctrlFlags = 0; /* UNIXFILE_* flags */
  36191. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  36192. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  36193. int isCreate = (flags & SQLITE_OPEN_CREATE);
  36194. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  36195. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  36196. #if SQLITE_ENABLE_LOCKING_STYLE
  36197. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  36198. #endif
  36199. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  36200. struct statfs fsInfo;
  36201. #endif
  36202. /* If creating a master or main-file journal, this function will open
  36203. ** a file-descriptor on the directory too. The first time unixSync()
  36204. ** is called the directory file descriptor will be fsync()ed and close()d.
  36205. */
  36206. int isNewJrnl = (isCreate && (
  36207. eType==SQLITE_OPEN_MASTER_JOURNAL
  36208. || eType==SQLITE_OPEN_MAIN_JOURNAL
  36209. || eType==SQLITE_OPEN_WAL
  36210. ));
  36211. /* If argument zPath is a NULL pointer, this function is required to open
  36212. ** a temporary file. Use this buffer to store the file name in.
  36213. */
  36214. char zTmpname[MAX_PATHNAME+2];
  36215. const char *zName = zPath;
  36216. /* Check the following statements are true:
  36217. **
  36218. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  36219. ** (b) if CREATE is set, then READWRITE must also be set, and
  36220. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  36221. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  36222. */
  36223. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  36224. assert(isCreate==0 || isReadWrite);
  36225. assert(isExclusive==0 || isCreate);
  36226. assert(isDelete==0 || isCreate);
  36227. /* The main DB, main journal, WAL file and master journal are never
  36228. ** automatically deleted. Nor are they ever temporary files. */
  36229. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  36230. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  36231. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  36232. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  36233. /* Assert that the upper layer has set one of the "file-type" flags. */
  36234. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  36235. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  36236. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  36237. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  36238. );
  36239. /* Detect a pid change and reset the PRNG. There is a race condition
  36240. ** here such that two or more threads all trying to open databases at
  36241. ** the same instant might all reset the PRNG. But multiple resets
  36242. ** are harmless.
  36243. */
  36244. if( randomnessPid!=osGetpid(0) ){
  36245. randomnessPid = osGetpid(0);
  36246. sqlite3_randomness(0,0);
  36247. }
  36248. memset(p, 0, sizeof(unixFile));
  36249. if( eType==SQLITE_OPEN_MAIN_DB ){
  36250. UnixUnusedFd *pUnused;
  36251. pUnused = findReusableFd(zName, flags);
  36252. if( pUnused ){
  36253. fd = pUnused->fd;
  36254. }else{
  36255. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  36256. if( !pUnused ){
  36257. return SQLITE_NOMEM_BKPT;
  36258. }
  36259. }
  36260. p->pPreallocatedUnused = pUnused;
  36261. /* Database filenames are double-zero terminated if they are not
  36262. ** URIs with parameters. Hence, they can always be passed into
  36263. ** sqlite3_uri_parameter(). */
  36264. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  36265. }else if( !zName ){
  36266. /* If zName is NULL, the upper layer is requesting a temp file. */
  36267. assert(isDelete && !isNewJrnl);
  36268. rc = unixGetTempname(pVfs->mxPathname, zTmpname);
  36269. if( rc!=SQLITE_OK ){
  36270. return rc;
  36271. }
  36272. zName = zTmpname;
  36273. /* Generated temporary filenames are always double-zero terminated
  36274. ** for use by sqlite3_uri_parameter(). */
  36275. assert( zName[strlen(zName)+1]==0 );
  36276. }
  36277. /* Determine the value of the flags parameter passed to POSIX function
  36278. ** open(). These must be calculated even if open() is not called, as
  36279. ** they may be stored as part of the file handle and used by the
  36280. ** 'conch file' locking functions later on. */
  36281. if( isReadonly ) openFlags |= O_RDONLY;
  36282. if( isReadWrite ) openFlags |= O_RDWR;
  36283. if( isCreate ) openFlags |= O_CREAT;
  36284. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  36285. openFlags |= (O_LARGEFILE|O_BINARY);
  36286. if( fd<0 ){
  36287. mode_t openMode; /* Permissions to create file with */
  36288. uid_t uid; /* Userid for the file */
  36289. gid_t gid; /* Groupid for the file */
  36290. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  36291. if( rc!=SQLITE_OK ){
  36292. assert( !p->pPreallocatedUnused );
  36293. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  36294. return rc;
  36295. }
  36296. fd = robust_open(zName, openFlags, openMode);
  36297. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  36298. assert( !isExclusive || (openFlags & O_CREAT)!=0 );
  36299. if( fd<0 ){
  36300. if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
  36301. /* If unable to create a journal because the directory is not
  36302. ** writable, change the error code to indicate that. */
  36303. rc = SQLITE_READONLY_DIRECTORY;
  36304. }else if( errno!=EISDIR && isReadWrite ){
  36305. /* Failed to open the file for read/write access. Try read-only. */
  36306. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  36307. openFlags &= ~(O_RDWR|O_CREAT);
  36308. flags |= SQLITE_OPEN_READONLY;
  36309. openFlags |= O_RDONLY;
  36310. isReadonly = 1;
  36311. fd = robust_open(zName, openFlags, openMode);
  36312. }
  36313. }
  36314. if( fd<0 ){
  36315. int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  36316. if( rc==SQLITE_OK ) rc = rc2;
  36317. goto open_finished;
  36318. }
  36319. /* If this process is running as root and if creating a new rollback
  36320. ** journal or WAL file, set the ownership of the journal or WAL to be
  36321. ** the same as the original database.
  36322. */
  36323. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  36324. robustFchown(fd, uid, gid);
  36325. }
  36326. }
  36327. assert( fd>=0 );
  36328. if( pOutFlags ){
  36329. *pOutFlags = flags;
  36330. }
  36331. if( p->pPreallocatedUnused ){
  36332. p->pPreallocatedUnused->fd = fd;
  36333. p->pPreallocatedUnused->flags = flags;
  36334. }
  36335. if( isDelete ){
  36336. #if OS_VXWORKS
  36337. zPath = zName;
  36338. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  36339. zPath = sqlite3_mprintf("%s", zName);
  36340. if( zPath==0 ){
  36341. robust_close(p, fd, __LINE__);
  36342. return SQLITE_NOMEM_BKPT;
  36343. }
  36344. #else
  36345. osUnlink(zName);
  36346. #endif
  36347. }
  36348. #if SQLITE_ENABLE_LOCKING_STYLE
  36349. else{
  36350. p->openFlags = openFlags;
  36351. }
  36352. #endif
  36353. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  36354. if( fstatfs(fd, &fsInfo) == -1 ){
  36355. storeLastErrno(p, errno);
  36356. robust_close(p, fd, __LINE__);
  36357. return SQLITE_IOERR_ACCESS;
  36358. }
  36359. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  36360. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  36361. }
  36362. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  36363. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  36364. }
  36365. #endif
  36366. /* Set up appropriate ctrlFlags */
  36367. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  36368. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  36369. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  36370. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  36371. if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
  36372. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  36373. #if SQLITE_ENABLE_LOCKING_STYLE
  36374. #if SQLITE_PREFER_PROXY_LOCKING
  36375. isAutoProxy = 1;
  36376. #endif
  36377. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  36378. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  36379. int useProxy = 0;
  36380. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  36381. ** never use proxy, NULL means use proxy for non-local files only. */
  36382. if( envforce!=NULL ){
  36383. useProxy = atoi(envforce)>0;
  36384. }else{
  36385. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  36386. }
  36387. if( useProxy ){
  36388. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  36389. if( rc==SQLITE_OK ){
  36390. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  36391. if( rc!=SQLITE_OK ){
  36392. /* Use unixClose to clean up the resources added in fillInUnixFile
  36393. ** and clear all the structure's references. Specifically,
  36394. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  36395. */
  36396. unixClose(pFile);
  36397. return rc;
  36398. }
  36399. }
  36400. goto open_finished;
  36401. }
  36402. }
  36403. #endif
  36404. assert( zPath==0 || zPath[0]=='/'
  36405. || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
  36406. );
  36407. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  36408. open_finished:
  36409. if( rc!=SQLITE_OK ){
  36410. sqlite3_free(p->pPreallocatedUnused);
  36411. }
  36412. return rc;
  36413. }
  36414. /*
  36415. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  36416. ** the directory after deleting the file.
  36417. */
  36418. static int unixDelete(
  36419. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  36420. const char *zPath, /* Name of file to be deleted */
  36421. int dirSync /* If true, fsync() directory after deleting file */
  36422. ){
  36423. int rc = SQLITE_OK;
  36424. UNUSED_PARAMETER(NotUsed);
  36425. SimulateIOError(return SQLITE_IOERR_DELETE);
  36426. if( osUnlink(zPath)==(-1) ){
  36427. if( errno==ENOENT
  36428. #if OS_VXWORKS
  36429. || osAccess(zPath,0)!=0
  36430. #endif
  36431. ){
  36432. rc = SQLITE_IOERR_DELETE_NOENT;
  36433. }else{
  36434. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  36435. }
  36436. return rc;
  36437. }
  36438. #ifndef SQLITE_DISABLE_DIRSYNC
  36439. if( (dirSync & 1)!=0 ){
  36440. int fd;
  36441. rc = osOpenDirectory(zPath, &fd);
  36442. if( rc==SQLITE_OK ){
  36443. if( full_fsync(fd,0,0) ){
  36444. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  36445. }
  36446. robust_close(0, fd, __LINE__);
  36447. }else{
  36448. assert( rc==SQLITE_CANTOPEN );
  36449. rc = SQLITE_OK;
  36450. }
  36451. }
  36452. #endif
  36453. return rc;
  36454. }
  36455. /*
  36456. ** Test the existence of or access permissions of file zPath. The
  36457. ** test performed depends on the value of flags:
  36458. **
  36459. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  36460. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  36461. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  36462. **
  36463. ** Otherwise return 0.
  36464. */
  36465. static int unixAccess(
  36466. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  36467. const char *zPath, /* Path of the file to examine */
  36468. int flags, /* What do we want to learn about the zPath file? */
  36469. int *pResOut /* Write result boolean here */
  36470. ){
  36471. UNUSED_PARAMETER(NotUsed);
  36472. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  36473. assert( pResOut!=0 );
  36474. /* The spec says there are three possible values for flags. But only
  36475. ** two of them are actually used */
  36476. assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
  36477. if( flags==SQLITE_ACCESS_EXISTS ){
  36478. struct stat buf;
  36479. *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
  36480. }else{
  36481. *pResOut = osAccess(zPath, W_OK|R_OK)==0;
  36482. }
  36483. return SQLITE_OK;
  36484. }
  36485. /*
  36486. **
  36487. */
  36488. static int mkFullPathname(
  36489. const char *zPath, /* Input path */
  36490. char *zOut, /* Output buffer */
  36491. int nOut /* Allocated size of buffer zOut */
  36492. ){
  36493. int nPath = sqlite3Strlen30(zPath);
  36494. int iOff = 0;
  36495. if( zPath[0]!='/' ){
  36496. if( osGetcwd(zOut, nOut-2)==0 ){
  36497. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  36498. }
  36499. iOff = sqlite3Strlen30(zOut);
  36500. zOut[iOff++] = '/';
  36501. }
  36502. if( (iOff+nPath+1)>nOut ){
  36503. /* SQLite assumes that xFullPathname() nul-terminates the output buffer
  36504. ** even if it returns an error. */
  36505. zOut[iOff] = '\0';
  36506. return SQLITE_CANTOPEN_BKPT;
  36507. }
  36508. sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
  36509. return SQLITE_OK;
  36510. }
  36511. /*
  36512. ** Turn a relative pathname into a full pathname. The relative path
  36513. ** is stored as a nul-terminated string in the buffer pointed to by
  36514. ** zPath.
  36515. **
  36516. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  36517. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  36518. ** this buffer before returning.
  36519. */
  36520. static int unixFullPathname(
  36521. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  36522. const char *zPath, /* Possibly relative input path */
  36523. int nOut, /* Size of output buffer in bytes */
  36524. char *zOut /* Output buffer */
  36525. ){
  36526. #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
  36527. return mkFullPathname(zPath, zOut, nOut);
  36528. #else
  36529. int rc = SQLITE_OK;
  36530. int nByte;
  36531. int nLink = 1; /* Number of symbolic links followed so far */
  36532. const char *zIn = zPath; /* Input path for each iteration of loop */
  36533. char *zDel = 0;
  36534. assert( pVfs->mxPathname==MAX_PATHNAME );
  36535. UNUSED_PARAMETER(pVfs);
  36536. /* It's odd to simulate an io-error here, but really this is just
  36537. ** using the io-error infrastructure to test that SQLite handles this
  36538. ** function failing. This function could fail if, for example, the
  36539. ** current working directory has been unlinked.
  36540. */
  36541. SimulateIOError( return SQLITE_ERROR );
  36542. do {
  36543. /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
  36544. ** link, or false otherwise. */
  36545. int bLink = 0;
  36546. struct stat buf;
  36547. if( osLstat(zIn, &buf)!=0 ){
  36548. if( errno!=ENOENT ){
  36549. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
  36550. }
  36551. }else{
  36552. bLink = S_ISLNK(buf.st_mode);
  36553. }
  36554. if( bLink ){
  36555. if( zDel==0 ){
  36556. zDel = sqlite3_malloc(nOut);
  36557. if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
  36558. }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
  36559. rc = SQLITE_CANTOPEN_BKPT;
  36560. }
  36561. if( rc==SQLITE_OK ){
  36562. nByte = osReadlink(zIn, zDel, nOut-1);
  36563. if( nByte<0 ){
  36564. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
  36565. }else{
  36566. if( zDel[0]!='/' ){
  36567. int n;
  36568. for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
  36569. if( nByte+n+1>nOut ){
  36570. rc = SQLITE_CANTOPEN_BKPT;
  36571. }else{
  36572. memmove(&zDel[n], zDel, nByte+1);
  36573. memcpy(zDel, zIn, n);
  36574. nByte += n;
  36575. }
  36576. }
  36577. zDel[nByte] = '\0';
  36578. }
  36579. }
  36580. zIn = zDel;
  36581. }
  36582. assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
  36583. if( rc==SQLITE_OK && zIn!=zOut ){
  36584. rc = mkFullPathname(zIn, zOut, nOut);
  36585. }
  36586. if( bLink==0 ) break;
  36587. zIn = zOut;
  36588. }while( rc==SQLITE_OK );
  36589. sqlite3_free(zDel);
  36590. return rc;
  36591. #endif /* HAVE_READLINK && HAVE_LSTAT */
  36592. }
  36593. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  36594. /*
  36595. ** Interfaces for opening a shared library, finding entry points
  36596. ** within the shared library, and closing the shared library.
  36597. */
  36598. #include <dlfcn.h>
  36599. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  36600. UNUSED_PARAMETER(NotUsed);
  36601. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  36602. }
  36603. /*
  36604. ** SQLite calls this function immediately after a call to unixDlSym() or
  36605. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  36606. ** message is available, it is written to zBufOut. If no error message
  36607. ** is available, zBufOut is left unmodified and SQLite uses a default
  36608. ** error message.
  36609. */
  36610. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  36611. const char *zErr;
  36612. UNUSED_PARAMETER(NotUsed);
  36613. unixEnterMutex();
  36614. zErr = dlerror();
  36615. if( zErr ){
  36616. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  36617. }
  36618. unixLeaveMutex();
  36619. }
  36620. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  36621. /*
  36622. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  36623. ** cast into a pointer to a function. And yet the library dlsym() routine
  36624. ** returns a void* which is really a pointer to a function. So how do we
  36625. ** use dlsym() with -pedantic-errors?
  36626. **
  36627. ** Variable x below is defined to be a pointer to a function taking
  36628. ** parameters void* and const char* and returning a pointer to a function.
  36629. ** We initialize x by assigning it a pointer to the dlsym() function.
  36630. ** (That assignment requires a cast.) Then we call the function that
  36631. ** x points to.
  36632. **
  36633. ** This work-around is unlikely to work correctly on any system where
  36634. ** you really cannot cast a function pointer into void*. But then, on the
  36635. ** other hand, dlsym() will not work on such a system either, so we have
  36636. ** not really lost anything.
  36637. */
  36638. void (*(*x)(void*,const char*))(void);
  36639. UNUSED_PARAMETER(NotUsed);
  36640. x = (void(*(*)(void*,const char*))(void))dlsym;
  36641. return (*x)(p, zSym);
  36642. }
  36643. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  36644. UNUSED_PARAMETER(NotUsed);
  36645. dlclose(pHandle);
  36646. }
  36647. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  36648. #define unixDlOpen 0
  36649. #define unixDlError 0
  36650. #define unixDlSym 0
  36651. #define unixDlClose 0
  36652. #endif
  36653. /*
  36654. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  36655. */
  36656. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  36657. UNUSED_PARAMETER(NotUsed);
  36658. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  36659. /* We have to initialize zBuf to prevent valgrind from reporting
  36660. ** errors. The reports issued by valgrind are incorrect - we would
  36661. ** prefer that the randomness be increased by making use of the
  36662. ** uninitialized space in zBuf - but valgrind errors tend to worry
  36663. ** some users. Rather than argue, it seems easier just to initialize
  36664. ** the whole array and silence valgrind, even if that means less randomness
  36665. ** in the random seed.
  36666. **
  36667. ** When testing, initializing zBuf[] to zero is all we do. That means
  36668. ** that we always use the same random number sequence. This makes the
  36669. ** tests repeatable.
  36670. */
  36671. memset(zBuf, 0, nBuf);
  36672. randomnessPid = osGetpid(0);
  36673. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  36674. {
  36675. int fd, got;
  36676. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  36677. if( fd<0 ){
  36678. time_t t;
  36679. time(&t);
  36680. memcpy(zBuf, &t, sizeof(t));
  36681. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  36682. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  36683. nBuf = sizeof(t) + sizeof(randomnessPid);
  36684. }else{
  36685. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  36686. robust_close(0, fd, __LINE__);
  36687. }
  36688. }
  36689. #endif
  36690. return nBuf;
  36691. }
  36692. /*
  36693. ** Sleep for a little while. Return the amount of time slept.
  36694. ** The argument is the number of microseconds we want to sleep.
  36695. ** The return value is the number of microseconds of sleep actually
  36696. ** requested from the underlying operating system, a number which
  36697. ** might be greater than or equal to the argument, but not less
  36698. ** than the argument.
  36699. */
  36700. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  36701. #if OS_VXWORKS
  36702. struct timespec sp;
  36703. sp.tv_sec = microseconds / 1000000;
  36704. sp.tv_nsec = (microseconds % 1000000) * 1000;
  36705. nanosleep(&sp, NULL);
  36706. UNUSED_PARAMETER(NotUsed);
  36707. return microseconds;
  36708. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  36709. usleep(microseconds);
  36710. UNUSED_PARAMETER(NotUsed);
  36711. return microseconds;
  36712. #else
  36713. int seconds = (microseconds+999999)/1000000;
  36714. sleep(seconds);
  36715. UNUSED_PARAMETER(NotUsed);
  36716. return seconds*1000000;
  36717. #endif
  36718. }
  36719. /*
  36720. ** The following variable, if set to a non-zero value, is interpreted as
  36721. ** the number of seconds since 1970 and is used to set the result of
  36722. ** sqlite3OsCurrentTime() during testing.
  36723. */
  36724. #ifdef SQLITE_TEST
  36725. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  36726. #endif
  36727. /*
  36728. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  36729. ** the current time and date as a Julian Day number times 86_400_000. In
  36730. ** other words, write into *piNow the number of milliseconds since the Julian
  36731. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  36732. ** proleptic Gregorian calendar.
  36733. **
  36734. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  36735. ** cannot be found.
  36736. */
  36737. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  36738. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  36739. int rc = SQLITE_OK;
  36740. #if defined(NO_GETTOD)
  36741. time_t t;
  36742. time(&t);
  36743. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  36744. #elif OS_VXWORKS
  36745. struct timespec sNow;
  36746. clock_gettime(CLOCK_REALTIME, &sNow);
  36747. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  36748. #else
  36749. struct timeval sNow;
  36750. (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
  36751. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  36752. #endif
  36753. #ifdef SQLITE_TEST
  36754. if( sqlite3_current_time ){
  36755. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  36756. }
  36757. #endif
  36758. UNUSED_PARAMETER(NotUsed);
  36759. return rc;
  36760. }
  36761. #ifndef SQLITE_OMIT_DEPRECATED
  36762. /*
  36763. ** Find the current time (in Universal Coordinated Time). Write the
  36764. ** current time and date as a Julian Day number into *prNow and
  36765. ** return 0. Return 1 if the time and date cannot be found.
  36766. */
  36767. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  36768. sqlite3_int64 i = 0;
  36769. int rc;
  36770. UNUSED_PARAMETER(NotUsed);
  36771. rc = unixCurrentTimeInt64(0, &i);
  36772. *prNow = i/86400000.0;
  36773. return rc;
  36774. }
  36775. #else
  36776. # define unixCurrentTime 0
  36777. #endif
  36778. /*
  36779. ** The xGetLastError() method is designed to return a better
  36780. ** low-level error message when operating-system problems come up
  36781. ** during SQLite operation. Only the integer return code is currently
  36782. ** used.
  36783. */
  36784. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  36785. UNUSED_PARAMETER(NotUsed);
  36786. UNUSED_PARAMETER(NotUsed2);
  36787. UNUSED_PARAMETER(NotUsed3);
  36788. return errno;
  36789. }
  36790. /*
  36791. ************************ End of sqlite3_vfs methods ***************************
  36792. ******************************************************************************/
  36793. /******************************************************************************
  36794. ************************** Begin Proxy Locking ********************************
  36795. **
  36796. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  36797. ** other locking methods on secondary lock files. Proxy locking is a
  36798. ** meta-layer over top of the primitive locking implemented above. For
  36799. ** this reason, the division that implements of proxy locking is deferred
  36800. ** until late in the file (here) after all of the other I/O methods have
  36801. ** been defined - so that the primitive locking methods are available
  36802. ** as services to help with the implementation of proxy locking.
  36803. **
  36804. ****
  36805. **
  36806. ** The default locking schemes in SQLite use byte-range locks on the
  36807. ** database file to coordinate safe, concurrent access by multiple readers
  36808. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  36809. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  36810. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  36811. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  36812. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  36813. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  36814. ** address in the shared range is taken for a SHARED lock, the entire
  36815. ** shared range is taken for an EXCLUSIVE lock):
  36816. **
  36817. ** PENDING_BYTE 0x40000000
  36818. ** RESERVED_BYTE 0x40000001
  36819. ** SHARED_RANGE 0x40000002 -> 0x40000200
  36820. **
  36821. ** This works well on the local file system, but shows a nearly 100x
  36822. ** slowdown in read performance on AFP because the AFP client disables
  36823. ** the read cache when byte-range locks are present. Enabling the read
  36824. ** cache exposes a cache coherency problem that is present on all OS X
  36825. ** supported network file systems. NFS and AFP both observe the
  36826. ** close-to-open semantics for ensuring cache coherency
  36827. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  36828. ** address the requirements for concurrent database access by multiple
  36829. ** readers and writers
  36830. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  36831. **
  36832. ** To address the performance and cache coherency issues, proxy file locking
  36833. ** changes the way database access is controlled by limiting access to a
  36834. ** single host at a time and moving file locks off of the database file
  36835. ** and onto a proxy file on the local file system.
  36836. **
  36837. **
  36838. ** Using proxy locks
  36839. ** -----------------
  36840. **
  36841. ** C APIs
  36842. **
  36843. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  36844. ** <proxy_path> | ":auto:");
  36845. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  36846. ** &<proxy_path>);
  36847. **
  36848. **
  36849. ** SQL pragmas
  36850. **
  36851. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  36852. ** PRAGMA [database.]lock_proxy_file
  36853. **
  36854. ** Specifying ":auto:" means that if there is a conch file with a matching
  36855. ** host ID in it, the proxy path in the conch file will be used, otherwise
  36856. ** a proxy path based on the user's temp dir
  36857. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  36858. ** actual proxy file name is generated from the name and path of the
  36859. ** database file. For example:
  36860. **
  36861. ** For database path "/Users/me/foo.db"
  36862. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  36863. **
  36864. ** Once a lock proxy is configured for a database connection, it can not
  36865. ** be removed, however it may be switched to a different proxy path via
  36866. ** the above APIs (assuming the conch file is not being held by another
  36867. ** connection or process).
  36868. **
  36869. **
  36870. ** How proxy locking works
  36871. ** -----------------------
  36872. **
  36873. ** Proxy file locking relies primarily on two new supporting files:
  36874. **
  36875. ** * conch file to limit access to the database file to a single host
  36876. ** at a time
  36877. **
  36878. ** * proxy file to act as a proxy for the advisory locks normally
  36879. ** taken on the database
  36880. **
  36881. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  36882. ** by taking an sqlite-style shared lock on the conch file, reading the
  36883. ** contents and comparing the host's unique host ID (see below) and lock
  36884. ** proxy path against the values stored in the conch. The conch file is
  36885. ** stored in the same directory as the database file and the file name
  36886. ** is patterned after the database file name as ".<databasename>-conch".
  36887. ** If the conch file does not exist, or its contents do not match the
  36888. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  36889. ** lock and the conch file contents is updated with the host ID and proxy
  36890. ** path and the lock is downgraded to a shared lock again. If the conch
  36891. ** is held by another process (with a shared lock), the exclusive lock
  36892. ** will fail and SQLITE_BUSY is returned.
  36893. **
  36894. ** The proxy file - a single-byte file used for all advisory file locks
  36895. ** normally taken on the database file. This allows for safe sharing
  36896. ** of the database file for multiple readers and writers on the same
  36897. ** host (the conch ensures that they all use the same local lock file).
  36898. **
  36899. ** Requesting the lock proxy does not immediately take the conch, it is
  36900. ** only taken when the first request to lock database file is made.
  36901. ** This matches the semantics of the traditional locking behavior, where
  36902. ** opening a connection to a database file does not take a lock on it.
  36903. ** The shared lock and an open file descriptor are maintained until
  36904. ** the connection to the database is closed.
  36905. **
  36906. ** The proxy file and the lock file are never deleted so they only need
  36907. ** to be created the first time they are used.
  36908. **
  36909. ** Configuration options
  36910. ** ---------------------
  36911. **
  36912. ** SQLITE_PREFER_PROXY_LOCKING
  36913. **
  36914. ** Database files accessed on non-local file systems are
  36915. ** automatically configured for proxy locking, lock files are
  36916. ** named automatically using the same logic as
  36917. ** PRAGMA lock_proxy_file=":auto:"
  36918. **
  36919. ** SQLITE_PROXY_DEBUG
  36920. **
  36921. ** Enables the logging of error messages during host id file
  36922. ** retrieval and creation
  36923. **
  36924. ** LOCKPROXYDIR
  36925. **
  36926. ** Overrides the default directory used for lock proxy files that
  36927. ** are named automatically via the ":auto:" setting
  36928. **
  36929. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  36930. **
  36931. ** Permissions to use when creating a directory for storing the
  36932. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  36933. **
  36934. **
  36935. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  36936. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  36937. ** force proxy locking to be used for every database file opened, and 0
  36938. ** will force automatic proxy locking to be disabled for all database
  36939. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  36940. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  36941. */
  36942. /*
  36943. ** Proxy locking is only available on MacOSX
  36944. */
  36945. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  36946. /*
  36947. ** The proxyLockingContext has the path and file structures for the remote
  36948. ** and local proxy files in it
  36949. */
  36950. typedef struct proxyLockingContext proxyLockingContext;
  36951. struct proxyLockingContext {
  36952. unixFile *conchFile; /* Open conch file */
  36953. char *conchFilePath; /* Name of the conch file */
  36954. unixFile *lockProxy; /* Open proxy lock file */
  36955. char *lockProxyPath; /* Name of the proxy lock file */
  36956. char *dbPath; /* Name of the open file */
  36957. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  36958. int nFails; /* Number of conch taking failures */
  36959. void *oldLockingContext; /* Original lockingcontext to restore on close */
  36960. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  36961. };
  36962. /*
  36963. ** The proxy lock file path for the database at dbPath is written into lPath,
  36964. ** which must point to valid, writable memory large enough for a maxLen length
  36965. ** file path.
  36966. */
  36967. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  36968. int len;
  36969. int dbLen;
  36970. int i;
  36971. #ifdef LOCKPROXYDIR
  36972. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  36973. #else
  36974. # ifdef _CS_DARWIN_USER_TEMP_DIR
  36975. {
  36976. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  36977. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  36978. lPath, errno, osGetpid(0)));
  36979. return SQLITE_IOERR_LOCK;
  36980. }
  36981. len = strlcat(lPath, "sqliteplocks", maxLen);
  36982. }
  36983. # else
  36984. len = strlcpy(lPath, "/tmp/", maxLen);
  36985. # endif
  36986. #endif
  36987. if( lPath[len-1]!='/' ){
  36988. len = strlcat(lPath, "/", maxLen);
  36989. }
  36990. /* transform the db path to a unique cache name */
  36991. dbLen = (int)strlen(dbPath);
  36992. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  36993. char c = dbPath[i];
  36994. lPath[i+len] = (c=='/')?'_':c;
  36995. }
  36996. lPath[i+len]='\0';
  36997. strlcat(lPath, ":auto:", maxLen);
  36998. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  36999. return SQLITE_OK;
  37000. }
  37001. /*
  37002. ** Creates the lock file and any missing directories in lockPath
  37003. */
  37004. static int proxyCreateLockPath(const char *lockPath){
  37005. int i, len;
  37006. char buf[MAXPATHLEN];
  37007. int start = 0;
  37008. assert(lockPath!=NULL);
  37009. /* try to create all the intermediate directories */
  37010. len = (int)strlen(lockPath);
  37011. buf[0] = lockPath[0];
  37012. for( i=1; i<len; i++ ){
  37013. if( lockPath[i] == '/' && (i - start > 0) ){
  37014. /* only mkdir if leaf dir != "." or "/" or ".." */
  37015. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  37016. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  37017. buf[i]='\0';
  37018. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  37019. int err=errno;
  37020. if( err!=EEXIST ) {
  37021. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  37022. "'%s' proxy lock path=%s pid=%d\n",
  37023. buf, strerror(err), lockPath, osGetpid(0)));
  37024. return err;
  37025. }
  37026. }
  37027. }
  37028. start=i+1;
  37029. }
  37030. buf[i] = lockPath[i];
  37031. }
  37032. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
  37033. return 0;
  37034. }
  37035. /*
  37036. ** Create a new VFS file descriptor (stored in memory obtained from
  37037. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  37038. **
  37039. ** The caller is responsible not only for closing the file descriptor
  37040. ** but also for freeing the memory associated with the file descriptor.
  37041. */
  37042. static int proxyCreateUnixFile(
  37043. const char *path, /* path for the new unixFile */
  37044. unixFile **ppFile, /* unixFile created and returned by ref */
  37045. int islockfile /* if non zero missing dirs will be created */
  37046. ) {
  37047. int fd = -1;
  37048. unixFile *pNew;
  37049. int rc = SQLITE_OK;
  37050. int openFlags = O_RDWR | O_CREAT;
  37051. sqlite3_vfs dummyVfs;
  37052. int terrno = 0;
  37053. UnixUnusedFd *pUnused = NULL;
  37054. /* 1. first try to open/create the file
  37055. ** 2. if that fails, and this is a lock file (not-conch), try creating
  37056. ** the parent directories and then try again.
  37057. ** 3. if that fails, try to open the file read-only
  37058. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  37059. */
  37060. pUnused = findReusableFd(path, openFlags);
  37061. if( pUnused ){
  37062. fd = pUnused->fd;
  37063. }else{
  37064. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  37065. if( !pUnused ){
  37066. return SQLITE_NOMEM_BKPT;
  37067. }
  37068. }
  37069. if( fd<0 ){
  37070. fd = robust_open(path, openFlags, 0);
  37071. terrno = errno;
  37072. if( fd<0 && errno==ENOENT && islockfile ){
  37073. if( proxyCreateLockPath(path) == SQLITE_OK ){
  37074. fd = robust_open(path, openFlags, 0);
  37075. }
  37076. }
  37077. }
  37078. if( fd<0 ){
  37079. openFlags = O_RDONLY;
  37080. fd = robust_open(path, openFlags, 0);
  37081. terrno = errno;
  37082. }
  37083. if( fd<0 ){
  37084. if( islockfile ){
  37085. return SQLITE_BUSY;
  37086. }
  37087. switch (terrno) {
  37088. case EACCES:
  37089. return SQLITE_PERM;
  37090. case EIO:
  37091. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  37092. default:
  37093. return SQLITE_CANTOPEN_BKPT;
  37094. }
  37095. }
  37096. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  37097. if( pNew==NULL ){
  37098. rc = SQLITE_NOMEM_BKPT;
  37099. goto end_create_proxy;
  37100. }
  37101. memset(pNew, 0, sizeof(unixFile));
  37102. pNew->openFlags = openFlags;
  37103. memset(&dummyVfs, 0, sizeof(dummyVfs));
  37104. dummyVfs.pAppData = (void*)&autolockIoFinder;
  37105. dummyVfs.zName = "dummy";
  37106. pUnused->fd = fd;
  37107. pUnused->flags = openFlags;
  37108. pNew->pPreallocatedUnused = pUnused;
  37109. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  37110. if( rc==SQLITE_OK ){
  37111. *ppFile = pNew;
  37112. return SQLITE_OK;
  37113. }
  37114. end_create_proxy:
  37115. robust_close(pNew, fd, __LINE__);
  37116. sqlite3_free(pNew);
  37117. sqlite3_free(pUnused);
  37118. return rc;
  37119. }
  37120. #ifdef SQLITE_TEST
  37121. /* simulate multiple hosts by creating unique hostid file paths */
  37122. SQLITE_API int sqlite3_hostid_num = 0;
  37123. #endif
  37124. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  37125. #ifdef HAVE_GETHOSTUUID
  37126. /* Not always defined in the headers as it ought to be */
  37127. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  37128. #endif
  37129. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  37130. ** bytes of writable memory.
  37131. */
  37132. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  37133. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  37134. memset(pHostID, 0, PROXY_HOSTIDLEN);
  37135. #ifdef HAVE_GETHOSTUUID
  37136. {
  37137. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  37138. if( gethostuuid(pHostID, &timeout) ){
  37139. int err = errno;
  37140. if( pError ){
  37141. *pError = err;
  37142. }
  37143. return SQLITE_IOERR;
  37144. }
  37145. }
  37146. #else
  37147. UNUSED_PARAMETER(pError);
  37148. #endif
  37149. #ifdef SQLITE_TEST
  37150. /* simulate multiple hosts by creating unique hostid file paths */
  37151. if( sqlite3_hostid_num != 0){
  37152. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  37153. }
  37154. #endif
  37155. return SQLITE_OK;
  37156. }
  37157. /* The conch file contains the header, host id and lock file path
  37158. */
  37159. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  37160. #define PROXY_HEADERLEN 1 /* conch file header length */
  37161. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  37162. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  37163. /*
  37164. ** Takes an open conch file, copies the contents to a new path and then moves
  37165. ** it back. The newly created file's file descriptor is assigned to the
  37166. ** conch file structure and finally the original conch file descriptor is
  37167. ** closed. Returns zero if successful.
  37168. */
  37169. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  37170. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37171. unixFile *conchFile = pCtx->conchFile;
  37172. char tPath[MAXPATHLEN];
  37173. char buf[PROXY_MAXCONCHLEN];
  37174. char *cPath = pCtx->conchFilePath;
  37175. size_t readLen = 0;
  37176. size_t pathLen = 0;
  37177. char errmsg[64] = "";
  37178. int fd = -1;
  37179. int rc = -1;
  37180. UNUSED_PARAMETER(myHostID);
  37181. /* create a new path by replace the trailing '-conch' with '-break' */
  37182. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  37183. if( pathLen>MAXPATHLEN || pathLen<6 ||
  37184. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  37185. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  37186. goto end_breaklock;
  37187. }
  37188. /* read the conch content */
  37189. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  37190. if( readLen<PROXY_PATHINDEX ){
  37191. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  37192. goto end_breaklock;
  37193. }
  37194. /* write it out to the temporary break file */
  37195. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  37196. if( fd<0 ){
  37197. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  37198. goto end_breaklock;
  37199. }
  37200. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  37201. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  37202. goto end_breaklock;
  37203. }
  37204. if( rename(tPath, cPath) ){
  37205. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  37206. goto end_breaklock;
  37207. }
  37208. rc = 0;
  37209. fprintf(stderr, "broke stale lock on %s\n", cPath);
  37210. robust_close(pFile, conchFile->h, __LINE__);
  37211. conchFile->h = fd;
  37212. conchFile->openFlags = O_RDWR | O_CREAT;
  37213. end_breaklock:
  37214. if( rc ){
  37215. if( fd>=0 ){
  37216. osUnlink(tPath);
  37217. robust_close(pFile, fd, __LINE__);
  37218. }
  37219. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  37220. }
  37221. return rc;
  37222. }
  37223. /* Take the requested lock on the conch file and break a stale lock if the
  37224. ** host id matches.
  37225. */
  37226. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  37227. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37228. unixFile *conchFile = pCtx->conchFile;
  37229. int rc = SQLITE_OK;
  37230. int nTries = 0;
  37231. struct timespec conchModTime;
  37232. memset(&conchModTime, 0, sizeof(conchModTime));
  37233. do {
  37234. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  37235. nTries ++;
  37236. if( rc==SQLITE_BUSY ){
  37237. /* If the lock failed (busy):
  37238. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  37239. * 2nd try: fail if the mod time changed or host id is different, wait
  37240. * 10 sec and try again
  37241. * 3rd try: break the lock unless the mod time has changed.
  37242. */
  37243. struct stat buf;
  37244. if( osFstat(conchFile->h, &buf) ){
  37245. storeLastErrno(pFile, errno);
  37246. return SQLITE_IOERR_LOCK;
  37247. }
  37248. if( nTries==1 ){
  37249. conchModTime = buf.st_mtimespec;
  37250. usleep(500000); /* wait 0.5 sec and try the lock again*/
  37251. continue;
  37252. }
  37253. assert( nTries>1 );
  37254. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  37255. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  37256. return SQLITE_BUSY;
  37257. }
  37258. if( nTries==2 ){
  37259. char tBuf[PROXY_MAXCONCHLEN];
  37260. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  37261. if( len<0 ){
  37262. storeLastErrno(pFile, errno);
  37263. return SQLITE_IOERR_LOCK;
  37264. }
  37265. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  37266. /* don't break the lock if the host id doesn't match */
  37267. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  37268. return SQLITE_BUSY;
  37269. }
  37270. }else{
  37271. /* don't break the lock on short read or a version mismatch */
  37272. return SQLITE_BUSY;
  37273. }
  37274. usleep(10000000); /* wait 10 sec and try the lock again */
  37275. continue;
  37276. }
  37277. assert( nTries==3 );
  37278. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  37279. rc = SQLITE_OK;
  37280. if( lockType==EXCLUSIVE_LOCK ){
  37281. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  37282. }
  37283. if( !rc ){
  37284. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  37285. }
  37286. }
  37287. }
  37288. } while( rc==SQLITE_BUSY && nTries<3 );
  37289. return rc;
  37290. }
  37291. /* Takes the conch by taking a shared lock and read the contents conch, if
  37292. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  37293. ** lockPath means that the lockPath in the conch file will be used if the
  37294. ** host IDs match, or a new lock path will be generated automatically
  37295. ** and written to the conch file.
  37296. */
  37297. static int proxyTakeConch(unixFile *pFile){
  37298. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37299. if( pCtx->conchHeld!=0 ){
  37300. return SQLITE_OK;
  37301. }else{
  37302. unixFile *conchFile = pCtx->conchFile;
  37303. uuid_t myHostID;
  37304. int pError = 0;
  37305. char readBuf[PROXY_MAXCONCHLEN];
  37306. char lockPath[MAXPATHLEN];
  37307. char *tempLockPath = NULL;
  37308. int rc = SQLITE_OK;
  37309. int createConch = 0;
  37310. int hostIdMatch = 0;
  37311. int readLen = 0;
  37312. int tryOldLockPath = 0;
  37313. int forceNewLockPath = 0;
  37314. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  37315. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  37316. osGetpid(0)));
  37317. rc = proxyGetHostID(myHostID, &pError);
  37318. if( (rc&0xff)==SQLITE_IOERR ){
  37319. storeLastErrno(pFile, pError);
  37320. goto end_takeconch;
  37321. }
  37322. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  37323. if( rc!=SQLITE_OK ){
  37324. goto end_takeconch;
  37325. }
  37326. /* read the existing conch file */
  37327. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  37328. if( readLen<0 ){
  37329. /* I/O error: lastErrno set by seekAndRead */
  37330. storeLastErrno(pFile, conchFile->lastErrno);
  37331. rc = SQLITE_IOERR_READ;
  37332. goto end_takeconch;
  37333. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  37334. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  37335. /* a short read or version format mismatch means we need to create a new
  37336. ** conch file.
  37337. */
  37338. createConch = 1;
  37339. }
  37340. /* if the host id matches and the lock path already exists in the conch
  37341. ** we'll try to use the path there, if we can't open that path, we'll
  37342. ** retry with a new auto-generated path
  37343. */
  37344. do { /* in case we need to try again for an :auto: named lock file */
  37345. if( !createConch && !forceNewLockPath ){
  37346. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  37347. PROXY_HOSTIDLEN);
  37348. /* if the conch has data compare the contents */
  37349. if( !pCtx->lockProxyPath ){
  37350. /* for auto-named local lock file, just check the host ID and we'll
  37351. ** use the local lock file path that's already in there
  37352. */
  37353. if( hostIdMatch ){
  37354. size_t pathLen = (readLen - PROXY_PATHINDEX);
  37355. if( pathLen>=MAXPATHLEN ){
  37356. pathLen=MAXPATHLEN-1;
  37357. }
  37358. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  37359. lockPath[pathLen] = 0;
  37360. tempLockPath = lockPath;
  37361. tryOldLockPath = 1;
  37362. /* create a copy of the lock path if the conch is taken */
  37363. goto end_takeconch;
  37364. }
  37365. }else if( hostIdMatch
  37366. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  37367. readLen-PROXY_PATHINDEX)
  37368. ){
  37369. /* conch host and lock path match */
  37370. goto end_takeconch;
  37371. }
  37372. }
  37373. /* if the conch isn't writable and doesn't match, we can't take it */
  37374. if( (conchFile->openFlags&O_RDWR) == 0 ){
  37375. rc = SQLITE_BUSY;
  37376. goto end_takeconch;
  37377. }
  37378. /* either the conch didn't match or we need to create a new one */
  37379. if( !pCtx->lockProxyPath ){
  37380. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  37381. tempLockPath = lockPath;
  37382. /* create a copy of the lock path _only_ if the conch is taken */
  37383. }
  37384. /* update conch with host and path (this will fail if other process
  37385. ** has a shared lock already), if the host id matches, use the big
  37386. ** stick.
  37387. */
  37388. futimes(conchFile->h, NULL);
  37389. if( hostIdMatch && !createConch ){
  37390. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  37391. /* We are trying for an exclusive lock but another thread in this
  37392. ** same process is still holding a shared lock. */
  37393. rc = SQLITE_BUSY;
  37394. } else {
  37395. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  37396. }
  37397. }else{
  37398. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  37399. }
  37400. if( rc==SQLITE_OK ){
  37401. char writeBuffer[PROXY_MAXCONCHLEN];
  37402. int writeSize = 0;
  37403. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  37404. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  37405. if( pCtx->lockProxyPath!=NULL ){
  37406. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  37407. MAXPATHLEN);
  37408. }else{
  37409. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  37410. }
  37411. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  37412. robust_ftruncate(conchFile->h, writeSize);
  37413. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  37414. full_fsync(conchFile->h,0,0);
  37415. /* If we created a new conch file (not just updated the contents of a
  37416. ** valid conch file), try to match the permissions of the database
  37417. */
  37418. if( rc==SQLITE_OK && createConch ){
  37419. struct stat buf;
  37420. int err = osFstat(pFile->h, &buf);
  37421. if( err==0 ){
  37422. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  37423. S_IROTH|S_IWOTH);
  37424. /* try to match the database file R/W permissions, ignore failure */
  37425. #ifndef SQLITE_PROXY_DEBUG
  37426. osFchmod(conchFile->h, cmode);
  37427. #else
  37428. do{
  37429. rc = osFchmod(conchFile->h, cmode);
  37430. }while( rc==(-1) && errno==EINTR );
  37431. if( rc!=0 ){
  37432. int code = errno;
  37433. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  37434. cmode, code, strerror(code));
  37435. } else {
  37436. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  37437. }
  37438. }else{
  37439. int code = errno;
  37440. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  37441. err, code, strerror(code));
  37442. #endif
  37443. }
  37444. }
  37445. }
  37446. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  37447. end_takeconch:
  37448. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  37449. if( rc==SQLITE_OK && pFile->openFlags ){
  37450. int fd;
  37451. if( pFile->h>=0 ){
  37452. robust_close(pFile, pFile->h, __LINE__);
  37453. }
  37454. pFile->h = -1;
  37455. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  37456. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  37457. if( fd>=0 ){
  37458. pFile->h = fd;
  37459. }else{
  37460. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  37461. during locking */
  37462. }
  37463. }
  37464. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  37465. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  37466. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  37467. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  37468. /* we couldn't create the proxy lock file with the old lock file path
  37469. ** so try again via auto-naming
  37470. */
  37471. forceNewLockPath = 1;
  37472. tryOldLockPath = 0;
  37473. continue; /* go back to the do {} while start point, try again */
  37474. }
  37475. }
  37476. if( rc==SQLITE_OK ){
  37477. /* Need to make a copy of path if we extracted the value
  37478. ** from the conch file or the path was allocated on the stack
  37479. */
  37480. if( tempLockPath ){
  37481. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  37482. if( !pCtx->lockProxyPath ){
  37483. rc = SQLITE_NOMEM_BKPT;
  37484. }
  37485. }
  37486. }
  37487. if( rc==SQLITE_OK ){
  37488. pCtx->conchHeld = 1;
  37489. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  37490. afpLockingContext *afpCtx;
  37491. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  37492. afpCtx->dbPath = pCtx->lockProxyPath;
  37493. }
  37494. } else {
  37495. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  37496. }
  37497. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  37498. rc==SQLITE_OK?"ok":"failed"));
  37499. return rc;
  37500. } while (1); /* in case we need to retry the :auto: lock file -
  37501. ** we should never get here except via the 'continue' call. */
  37502. }
  37503. }
  37504. /*
  37505. ** If pFile holds a lock on a conch file, then release that lock.
  37506. */
  37507. static int proxyReleaseConch(unixFile *pFile){
  37508. int rc = SQLITE_OK; /* Subroutine return code */
  37509. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  37510. unixFile *conchFile; /* Name of the conch file */
  37511. pCtx = (proxyLockingContext *)pFile->lockingContext;
  37512. conchFile = pCtx->conchFile;
  37513. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  37514. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  37515. osGetpid(0)));
  37516. if( pCtx->conchHeld>0 ){
  37517. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  37518. }
  37519. pCtx->conchHeld = 0;
  37520. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  37521. (rc==SQLITE_OK ? "ok" : "failed")));
  37522. return rc;
  37523. }
  37524. /*
  37525. ** Given the name of a database file, compute the name of its conch file.
  37526. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  37527. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  37528. ** or SQLITE_NOMEM if unable to obtain memory.
  37529. **
  37530. ** The caller is responsible for ensuring that the allocated memory
  37531. ** space is eventually freed.
  37532. **
  37533. ** *pConchPath is set to NULL if a memory allocation error occurs.
  37534. */
  37535. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  37536. int i; /* Loop counter */
  37537. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  37538. char *conchPath; /* buffer in which to construct conch name */
  37539. /* Allocate space for the conch filename and initialize the name to
  37540. ** the name of the original database file. */
  37541. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  37542. if( conchPath==0 ){
  37543. return SQLITE_NOMEM_BKPT;
  37544. }
  37545. memcpy(conchPath, dbPath, len+1);
  37546. /* now insert a "." before the last / character */
  37547. for( i=(len-1); i>=0; i-- ){
  37548. if( conchPath[i]=='/' ){
  37549. i++;
  37550. break;
  37551. }
  37552. }
  37553. conchPath[i]='.';
  37554. while ( i<len ){
  37555. conchPath[i+1]=dbPath[i];
  37556. i++;
  37557. }
  37558. /* append the "-conch" suffix to the file */
  37559. memcpy(&conchPath[i+1], "-conch", 7);
  37560. assert( (int)strlen(conchPath) == len+7 );
  37561. return SQLITE_OK;
  37562. }
  37563. /* Takes a fully configured proxy locking-style unix file and switches
  37564. ** the local lock file path
  37565. */
  37566. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  37567. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  37568. char *oldPath = pCtx->lockProxyPath;
  37569. int rc = SQLITE_OK;
  37570. if( pFile->eFileLock!=NO_LOCK ){
  37571. return SQLITE_BUSY;
  37572. }
  37573. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  37574. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  37575. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  37576. return SQLITE_OK;
  37577. }else{
  37578. unixFile *lockProxy = pCtx->lockProxy;
  37579. pCtx->lockProxy=NULL;
  37580. pCtx->conchHeld = 0;
  37581. if( lockProxy!=NULL ){
  37582. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  37583. if( rc ) return rc;
  37584. sqlite3_free(lockProxy);
  37585. }
  37586. sqlite3_free(oldPath);
  37587. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  37588. }
  37589. return rc;
  37590. }
  37591. /*
  37592. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  37593. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  37594. **
  37595. ** This routine find the filename associated with pFile and writes it
  37596. ** int dbPath.
  37597. */
  37598. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  37599. #if defined(__APPLE__)
  37600. if( pFile->pMethod == &afpIoMethods ){
  37601. /* afp style keeps a reference to the db path in the filePath field
  37602. ** of the struct */
  37603. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  37604. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  37605. MAXPATHLEN);
  37606. } else
  37607. #endif
  37608. if( pFile->pMethod == &dotlockIoMethods ){
  37609. /* dot lock style uses the locking context to store the dot lock
  37610. ** file path */
  37611. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  37612. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  37613. }else{
  37614. /* all other styles use the locking context to store the db file path */
  37615. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  37616. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  37617. }
  37618. return SQLITE_OK;
  37619. }
  37620. /*
  37621. ** Takes an already filled in unix file and alters it so all file locking
  37622. ** will be performed on the local proxy lock file. The following fields
  37623. ** are preserved in the locking context so that they can be restored and
  37624. ** the unix structure properly cleaned up at close time:
  37625. ** ->lockingContext
  37626. ** ->pMethod
  37627. */
  37628. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  37629. proxyLockingContext *pCtx;
  37630. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  37631. char *lockPath=NULL;
  37632. int rc = SQLITE_OK;
  37633. if( pFile->eFileLock!=NO_LOCK ){
  37634. return SQLITE_BUSY;
  37635. }
  37636. proxyGetDbPathForUnixFile(pFile, dbPath);
  37637. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  37638. lockPath=NULL;
  37639. }else{
  37640. lockPath=(char *)path;
  37641. }
  37642. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  37643. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  37644. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  37645. if( pCtx==0 ){
  37646. return SQLITE_NOMEM_BKPT;
  37647. }
  37648. memset(pCtx, 0, sizeof(*pCtx));
  37649. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  37650. if( rc==SQLITE_OK ){
  37651. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  37652. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  37653. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  37654. ** (c) the file system is read-only, then enable no-locking access.
  37655. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  37656. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  37657. */
  37658. struct statfs fsInfo;
  37659. struct stat conchInfo;
  37660. int goLockless = 0;
  37661. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  37662. int err = errno;
  37663. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  37664. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  37665. }
  37666. }
  37667. if( goLockless ){
  37668. pCtx->conchHeld = -1; /* read only FS/ lockless */
  37669. rc = SQLITE_OK;
  37670. }
  37671. }
  37672. }
  37673. if( rc==SQLITE_OK && lockPath ){
  37674. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  37675. }
  37676. if( rc==SQLITE_OK ){
  37677. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  37678. if( pCtx->dbPath==NULL ){
  37679. rc = SQLITE_NOMEM_BKPT;
  37680. }
  37681. }
  37682. if( rc==SQLITE_OK ){
  37683. /* all memory is allocated, proxys are created and assigned,
  37684. ** switch the locking context and pMethod then return.
  37685. */
  37686. pCtx->oldLockingContext = pFile->lockingContext;
  37687. pFile->lockingContext = pCtx;
  37688. pCtx->pOldMethod = pFile->pMethod;
  37689. pFile->pMethod = &proxyIoMethods;
  37690. }else{
  37691. if( pCtx->conchFile ){
  37692. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  37693. sqlite3_free(pCtx->conchFile);
  37694. }
  37695. sqlite3DbFree(0, pCtx->lockProxyPath);
  37696. sqlite3_free(pCtx->conchFilePath);
  37697. sqlite3_free(pCtx);
  37698. }
  37699. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  37700. (rc==SQLITE_OK ? "ok" : "failed")));
  37701. return rc;
  37702. }
  37703. /*
  37704. ** This routine handles sqlite3_file_control() calls that are specific
  37705. ** to proxy locking.
  37706. */
  37707. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  37708. switch( op ){
  37709. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  37710. unixFile *pFile = (unixFile*)id;
  37711. if( pFile->pMethod == &proxyIoMethods ){
  37712. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  37713. proxyTakeConch(pFile);
  37714. if( pCtx->lockProxyPath ){
  37715. *(const char **)pArg = pCtx->lockProxyPath;
  37716. }else{
  37717. *(const char **)pArg = ":auto: (not held)";
  37718. }
  37719. } else {
  37720. *(const char **)pArg = NULL;
  37721. }
  37722. return SQLITE_OK;
  37723. }
  37724. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  37725. unixFile *pFile = (unixFile*)id;
  37726. int rc = SQLITE_OK;
  37727. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  37728. if( pArg==NULL || (const char *)pArg==0 ){
  37729. if( isProxyStyle ){
  37730. /* turn off proxy locking - not supported. If support is added for
  37731. ** switching proxy locking mode off then it will need to fail if
  37732. ** the journal mode is WAL mode.
  37733. */
  37734. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  37735. }else{
  37736. /* turn off proxy locking - already off - NOOP */
  37737. rc = SQLITE_OK;
  37738. }
  37739. }else{
  37740. const char *proxyPath = (const char *)pArg;
  37741. if( isProxyStyle ){
  37742. proxyLockingContext *pCtx =
  37743. (proxyLockingContext*)pFile->lockingContext;
  37744. if( !strcmp(pArg, ":auto:")
  37745. || (pCtx->lockProxyPath &&
  37746. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  37747. ){
  37748. rc = SQLITE_OK;
  37749. }else{
  37750. rc = switchLockProxyPath(pFile, proxyPath);
  37751. }
  37752. }else{
  37753. /* turn on proxy file locking */
  37754. rc = proxyTransformUnixFile(pFile, proxyPath);
  37755. }
  37756. }
  37757. return rc;
  37758. }
  37759. default: {
  37760. assert( 0 ); /* The call assures that only valid opcodes are sent */
  37761. }
  37762. }
  37763. /*NOTREACHED*/
  37764. return SQLITE_ERROR;
  37765. }
  37766. /*
  37767. ** Within this division (the proxying locking implementation) the procedures
  37768. ** above this point are all utilities. The lock-related methods of the
  37769. ** proxy-locking sqlite3_io_method object follow.
  37770. */
  37771. /*
  37772. ** This routine checks if there is a RESERVED lock held on the specified
  37773. ** file by this or any other process. If such a lock is held, set *pResOut
  37774. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  37775. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  37776. */
  37777. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  37778. unixFile *pFile = (unixFile*)id;
  37779. int rc = proxyTakeConch(pFile);
  37780. if( rc==SQLITE_OK ){
  37781. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37782. if( pCtx->conchHeld>0 ){
  37783. unixFile *proxy = pCtx->lockProxy;
  37784. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  37785. }else{ /* conchHeld < 0 is lockless */
  37786. pResOut=0;
  37787. }
  37788. }
  37789. return rc;
  37790. }
  37791. /*
  37792. ** Lock the file with the lock specified by parameter eFileLock - one
  37793. ** of the following:
  37794. **
  37795. ** (1) SHARED_LOCK
  37796. ** (2) RESERVED_LOCK
  37797. ** (3) PENDING_LOCK
  37798. ** (4) EXCLUSIVE_LOCK
  37799. **
  37800. ** Sometimes when requesting one lock state, additional lock states
  37801. ** are inserted in between. The locking might fail on one of the later
  37802. ** transitions leaving the lock state different from what it started but
  37803. ** still short of its goal. The following chart shows the allowed
  37804. ** transitions and the inserted intermediate states:
  37805. **
  37806. ** UNLOCKED -> SHARED
  37807. ** SHARED -> RESERVED
  37808. ** SHARED -> (PENDING) -> EXCLUSIVE
  37809. ** RESERVED -> (PENDING) -> EXCLUSIVE
  37810. ** PENDING -> EXCLUSIVE
  37811. **
  37812. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  37813. ** routine to lower a locking level.
  37814. */
  37815. static int proxyLock(sqlite3_file *id, int eFileLock) {
  37816. unixFile *pFile = (unixFile*)id;
  37817. int rc = proxyTakeConch(pFile);
  37818. if( rc==SQLITE_OK ){
  37819. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37820. if( pCtx->conchHeld>0 ){
  37821. unixFile *proxy = pCtx->lockProxy;
  37822. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  37823. pFile->eFileLock = proxy->eFileLock;
  37824. }else{
  37825. /* conchHeld < 0 is lockless */
  37826. }
  37827. }
  37828. return rc;
  37829. }
  37830. /*
  37831. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  37832. ** must be either NO_LOCK or SHARED_LOCK.
  37833. **
  37834. ** If the locking level of the file descriptor is already at or below
  37835. ** the requested locking level, this routine is a no-op.
  37836. */
  37837. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  37838. unixFile *pFile = (unixFile*)id;
  37839. int rc = proxyTakeConch(pFile);
  37840. if( rc==SQLITE_OK ){
  37841. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37842. if( pCtx->conchHeld>0 ){
  37843. unixFile *proxy = pCtx->lockProxy;
  37844. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  37845. pFile->eFileLock = proxy->eFileLock;
  37846. }else{
  37847. /* conchHeld < 0 is lockless */
  37848. }
  37849. }
  37850. return rc;
  37851. }
  37852. /*
  37853. ** Close a file that uses proxy locks.
  37854. */
  37855. static int proxyClose(sqlite3_file *id) {
  37856. if( ALWAYS(id) ){
  37857. unixFile *pFile = (unixFile*)id;
  37858. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37859. unixFile *lockProxy = pCtx->lockProxy;
  37860. unixFile *conchFile = pCtx->conchFile;
  37861. int rc = SQLITE_OK;
  37862. if( lockProxy ){
  37863. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  37864. if( rc ) return rc;
  37865. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  37866. if( rc ) return rc;
  37867. sqlite3_free(lockProxy);
  37868. pCtx->lockProxy = 0;
  37869. }
  37870. if( conchFile ){
  37871. if( pCtx->conchHeld ){
  37872. rc = proxyReleaseConch(pFile);
  37873. if( rc ) return rc;
  37874. }
  37875. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  37876. if( rc ) return rc;
  37877. sqlite3_free(conchFile);
  37878. }
  37879. sqlite3DbFree(0, pCtx->lockProxyPath);
  37880. sqlite3_free(pCtx->conchFilePath);
  37881. sqlite3DbFree(0, pCtx->dbPath);
  37882. /* restore the original locking context and pMethod then close it */
  37883. pFile->lockingContext = pCtx->oldLockingContext;
  37884. pFile->pMethod = pCtx->pOldMethod;
  37885. sqlite3_free(pCtx);
  37886. return pFile->pMethod->xClose(id);
  37887. }
  37888. return SQLITE_OK;
  37889. }
  37890. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  37891. /*
  37892. ** The proxy locking style is intended for use with AFP filesystems.
  37893. ** And since AFP is only supported on MacOSX, the proxy locking is also
  37894. ** restricted to MacOSX.
  37895. **
  37896. **
  37897. ******************* End of the proxy lock implementation **********************
  37898. ******************************************************************************/
  37899. /*
  37900. ** Initialize the operating system interface.
  37901. **
  37902. ** This routine registers all VFS implementations for unix-like operating
  37903. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  37904. ** should be the only routines in this file that are visible from other
  37905. ** files.
  37906. **
  37907. ** This routine is called once during SQLite initialization and by a
  37908. ** single thread. The memory allocation and mutex subsystems have not
  37909. ** necessarily been initialized when this routine is called, and so they
  37910. ** should not be used.
  37911. */
  37912. SQLITE_API int sqlite3_os_init(void){
  37913. /*
  37914. ** The following macro defines an initializer for an sqlite3_vfs object.
  37915. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  37916. ** to the "finder" function. (pAppData is a pointer to a pointer because
  37917. ** silly C90 rules prohibit a void* from being cast to a function pointer
  37918. ** and so we have to go through the intermediate pointer to avoid problems
  37919. ** when compiling with -pedantic-errors on GCC.)
  37920. **
  37921. ** The FINDER parameter to this macro is the name of the pointer to the
  37922. ** finder-function. The finder-function returns a pointer to the
  37923. ** sqlite_io_methods object that implements the desired locking
  37924. ** behaviors. See the division above that contains the IOMETHODS
  37925. ** macro for addition information on finder-functions.
  37926. **
  37927. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  37928. ** object. But the "autolockIoFinder" available on MacOSX does a little
  37929. ** more than that; it looks at the filesystem type that hosts the
  37930. ** database file and tries to choose an locking method appropriate for
  37931. ** that filesystem time.
  37932. */
  37933. #define UNIXVFS(VFSNAME, FINDER) { \
  37934. 3, /* iVersion */ \
  37935. sizeof(unixFile), /* szOsFile */ \
  37936. MAX_PATHNAME, /* mxPathname */ \
  37937. 0, /* pNext */ \
  37938. VFSNAME, /* zName */ \
  37939. (void*)&FINDER, /* pAppData */ \
  37940. unixOpen, /* xOpen */ \
  37941. unixDelete, /* xDelete */ \
  37942. unixAccess, /* xAccess */ \
  37943. unixFullPathname, /* xFullPathname */ \
  37944. unixDlOpen, /* xDlOpen */ \
  37945. unixDlError, /* xDlError */ \
  37946. unixDlSym, /* xDlSym */ \
  37947. unixDlClose, /* xDlClose */ \
  37948. unixRandomness, /* xRandomness */ \
  37949. unixSleep, /* xSleep */ \
  37950. unixCurrentTime, /* xCurrentTime */ \
  37951. unixGetLastError, /* xGetLastError */ \
  37952. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  37953. unixSetSystemCall, /* xSetSystemCall */ \
  37954. unixGetSystemCall, /* xGetSystemCall */ \
  37955. unixNextSystemCall, /* xNextSystemCall */ \
  37956. }
  37957. /*
  37958. ** All default VFSes for unix are contained in the following array.
  37959. **
  37960. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  37961. ** by the SQLite core when the VFS is registered. So the following
  37962. ** array cannot be const.
  37963. */
  37964. static sqlite3_vfs aVfs[] = {
  37965. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  37966. UNIXVFS("unix", autolockIoFinder ),
  37967. #elif OS_VXWORKS
  37968. UNIXVFS("unix", vxworksIoFinder ),
  37969. #else
  37970. UNIXVFS("unix", posixIoFinder ),
  37971. #endif
  37972. UNIXVFS("unix-none", nolockIoFinder ),
  37973. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  37974. UNIXVFS("unix-excl", posixIoFinder ),
  37975. #if OS_VXWORKS
  37976. UNIXVFS("unix-namedsem", semIoFinder ),
  37977. #endif
  37978. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  37979. UNIXVFS("unix-posix", posixIoFinder ),
  37980. #endif
  37981. #if SQLITE_ENABLE_LOCKING_STYLE
  37982. UNIXVFS("unix-flock", flockIoFinder ),
  37983. #endif
  37984. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  37985. UNIXVFS("unix-afp", afpIoFinder ),
  37986. UNIXVFS("unix-nfs", nfsIoFinder ),
  37987. UNIXVFS("unix-proxy", proxyIoFinder ),
  37988. #endif
  37989. };
  37990. unsigned int i; /* Loop counter */
  37991. /* Double-check that the aSyscall[] array has been constructed
  37992. ** correctly. See ticket [bb3a86e890c8e96ab] */
  37993. assert( ArraySize(aSyscall)==29 );
  37994. /* Register all VFSes defined in the aVfs[] array */
  37995. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  37996. sqlite3_vfs_register(&aVfs[i], i==0);
  37997. }
  37998. unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  37999. return SQLITE_OK;
  38000. }
  38001. /*
  38002. ** Shutdown the operating system interface.
  38003. **
  38004. ** Some operating systems might need to do some cleanup in this routine,
  38005. ** to release dynamically allocated objects. But not on unix.
  38006. ** This routine is a no-op for unix.
  38007. */
  38008. SQLITE_API int sqlite3_os_end(void){
  38009. unixBigLock = 0;
  38010. return SQLITE_OK;
  38011. }
  38012. #endif /* SQLITE_OS_UNIX */
  38013. /************** End of os_unix.c *********************************************/
  38014. /************** Begin file os_win.c ******************************************/
  38015. /*
  38016. ** 2004 May 22
  38017. **
  38018. ** The author disclaims copyright to this source code. In place of
  38019. ** a legal notice, here is a blessing:
  38020. **
  38021. ** May you do good and not evil.
  38022. ** May you find forgiveness for yourself and forgive others.
  38023. ** May you share freely, never taking more than you give.
  38024. **
  38025. ******************************************************************************
  38026. **
  38027. ** This file contains code that is specific to Windows.
  38028. */
  38029. /* #include "sqliteInt.h" */
  38030. #if SQLITE_OS_WIN /* This file is used for Windows only */
  38031. /*
  38032. ** Include code that is common to all os_*.c files
  38033. */
  38034. /************** Include os_common.h in the middle of os_win.c ****************/
  38035. /************** Begin file os_common.h ***************************************/
  38036. /*
  38037. ** 2004 May 22
  38038. **
  38039. ** The author disclaims copyright to this source code. In place of
  38040. ** a legal notice, here is a blessing:
  38041. **
  38042. ** May you do good and not evil.
  38043. ** May you find forgiveness for yourself and forgive others.
  38044. ** May you share freely, never taking more than you give.
  38045. **
  38046. ******************************************************************************
  38047. **
  38048. ** This file contains macros and a little bit of code that is common to
  38049. ** all of the platform-specific files (os_*.c) and is #included into those
  38050. ** files.
  38051. **
  38052. ** This file should be #included by the os_*.c files only. It is not a
  38053. ** general purpose header file.
  38054. */
  38055. #ifndef _OS_COMMON_H_
  38056. #define _OS_COMMON_H_
  38057. /*
  38058. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  38059. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  38060. ** switch. The following code should catch this problem at compile-time.
  38061. */
  38062. #ifdef MEMORY_DEBUG
  38063. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  38064. #endif
  38065. /*
  38066. ** Macros for performance tracing. Normally turned off. Only works
  38067. ** on i486 hardware.
  38068. */
  38069. #ifdef SQLITE_PERFORMANCE_TRACE
  38070. /*
  38071. ** hwtime.h contains inline assembler code for implementing
  38072. ** high-performance timing routines.
  38073. */
  38074. /************** Include hwtime.h in the middle of os_common.h ****************/
  38075. /************** Begin file hwtime.h ******************************************/
  38076. /*
  38077. ** 2008 May 27
  38078. **
  38079. ** The author disclaims copyright to this source code. In place of
  38080. ** a legal notice, here is a blessing:
  38081. **
  38082. ** May you do good and not evil.
  38083. ** May you find forgiveness for yourself and forgive others.
  38084. ** May you share freely, never taking more than you give.
  38085. **
  38086. ******************************************************************************
  38087. **
  38088. ** This file contains inline asm code for retrieving "high-performance"
  38089. ** counters for x86 class CPUs.
  38090. */
  38091. #ifndef SQLITE_HWTIME_H
  38092. #define SQLITE_HWTIME_H
  38093. /*
  38094. ** The following routine only works on pentium-class (or newer) processors.
  38095. ** It uses the RDTSC opcode to read the cycle count value out of the
  38096. ** processor and returns that value. This can be used for high-res
  38097. ** profiling.
  38098. */
  38099. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  38100. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  38101. #if defined(__GNUC__)
  38102. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  38103. unsigned int lo, hi;
  38104. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  38105. return (sqlite_uint64)hi << 32 | lo;
  38106. }
  38107. #elif defined(_MSC_VER)
  38108. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  38109. __asm {
  38110. rdtsc
  38111. ret ; return value at EDX:EAX
  38112. }
  38113. }
  38114. #endif
  38115. #elif (defined(__GNUC__) && defined(__x86_64__))
  38116. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  38117. unsigned long val;
  38118. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  38119. return val;
  38120. }
  38121. #elif (defined(__GNUC__) && defined(__ppc__))
  38122. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  38123. unsigned long long retval;
  38124. unsigned long junk;
  38125. __asm__ __volatile__ ("\n\
  38126. 1: mftbu %1\n\
  38127. mftb %L0\n\
  38128. mftbu %0\n\
  38129. cmpw %0,%1\n\
  38130. bne 1b"
  38131. : "=r" (retval), "=r" (junk));
  38132. return retval;
  38133. }
  38134. #else
  38135. #error Need implementation of sqlite3Hwtime() for your platform.
  38136. /*
  38137. ** To compile without implementing sqlite3Hwtime() for your platform,
  38138. ** you can remove the above #error and use the following
  38139. ** stub function. You will lose timing support for many
  38140. ** of the debugging and testing utilities, but it should at
  38141. ** least compile and run.
  38142. */
  38143. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  38144. #endif
  38145. #endif /* !defined(SQLITE_HWTIME_H) */
  38146. /************** End of hwtime.h **********************************************/
  38147. /************** Continuing where we left off in os_common.h ******************/
  38148. static sqlite_uint64 g_start;
  38149. static sqlite_uint64 g_elapsed;
  38150. #define TIMER_START g_start=sqlite3Hwtime()
  38151. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  38152. #define TIMER_ELAPSED g_elapsed
  38153. #else
  38154. #define TIMER_START
  38155. #define TIMER_END
  38156. #define TIMER_ELAPSED ((sqlite_uint64)0)
  38157. #endif
  38158. /*
  38159. ** If we compile with the SQLITE_TEST macro set, then the following block
  38160. ** of code will give us the ability to simulate a disk I/O error. This
  38161. ** is used for testing the I/O recovery logic.
  38162. */
  38163. #if defined(SQLITE_TEST)
  38164. SQLITE_API extern int sqlite3_io_error_hit;
  38165. SQLITE_API extern int sqlite3_io_error_hardhit;
  38166. SQLITE_API extern int sqlite3_io_error_pending;
  38167. SQLITE_API extern int sqlite3_io_error_persist;
  38168. SQLITE_API extern int sqlite3_io_error_benign;
  38169. SQLITE_API extern int sqlite3_diskfull_pending;
  38170. SQLITE_API extern int sqlite3_diskfull;
  38171. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  38172. #define SimulateIOError(CODE) \
  38173. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  38174. || sqlite3_io_error_pending-- == 1 ) \
  38175. { local_ioerr(); CODE; }
  38176. static void local_ioerr(){
  38177. IOTRACE(("IOERR\n"));
  38178. sqlite3_io_error_hit++;
  38179. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  38180. }
  38181. #define SimulateDiskfullError(CODE) \
  38182. if( sqlite3_diskfull_pending ){ \
  38183. if( sqlite3_diskfull_pending == 1 ){ \
  38184. local_ioerr(); \
  38185. sqlite3_diskfull = 1; \
  38186. sqlite3_io_error_hit = 1; \
  38187. CODE; \
  38188. }else{ \
  38189. sqlite3_diskfull_pending--; \
  38190. } \
  38191. }
  38192. #else
  38193. #define SimulateIOErrorBenign(X)
  38194. #define SimulateIOError(A)
  38195. #define SimulateDiskfullError(A)
  38196. #endif /* defined(SQLITE_TEST) */
  38197. /*
  38198. ** When testing, keep a count of the number of open files.
  38199. */
  38200. #if defined(SQLITE_TEST)
  38201. SQLITE_API extern int sqlite3_open_file_count;
  38202. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  38203. #else
  38204. #define OpenCounter(X)
  38205. #endif /* defined(SQLITE_TEST) */
  38206. #endif /* !defined(_OS_COMMON_H_) */
  38207. /************** End of os_common.h *******************************************/
  38208. /************** Continuing where we left off in os_win.c *********************/
  38209. /*
  38210. ** Include the header file for the Windows VFS.
  38211. */
  38212. /* #include "os_win.h" */
  38213. /*
  38214. ** Compiling and using WAL mode requires several APIs that are only
  38215. ** available in Windows platforms based on the NT kernel.
  38216. */
  38217. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  38218. # error "WAL mode requires support from the Windows NT kernel, compile\
  38219. with SQLITE_OMIT_WAL."
  38220. #endif
  38221. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  38222. # error "Memory mapped files require support from the Windows NT kernel,\
  38223. compile with SQLITE_MAX_MMAP_SIZE=0."
  38224. #endif
  38225. /*
  38226. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  38227. ** based on the sub-platform)?
  38228. */
  38229. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  38230. # define SQLITE_WIN32_HAS_ANSI
  38231. #endif
  38232. /*
  38233. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  38234. ** based on the sub-platform)?
  38235. */
  38236. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  38237. !defined(SQLITE_WIN32_NO_WIDE)
  38238. # define SQLITE_WIN32_HAS_WIDE
  38239. #endif
  38240. /*
  38241. ** Make sure at least one set of Win32 APIs is available.
  38242. */
  38243. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  38244. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  38245. must be defined."
  38246. #endif
  38247. /*
  38248. ** Define the required Windows SDK version constants if they are not
  38249. ** already available.
  38250. */
  38251. #ifndef NTDDI_WIN8
  38252. # define NTDDI_WIN8 0x06020000
  38253. #endif
  38254. #ifndef NTDDI_WINBLUE
  38255. # define NTDDI_WINBLUE 0x06030000
  38256. #endif
  38257. #ifndef NTDDI_WINTHRESHOLD
  38258. # define NTDDI_WINTHRESHOLD 0x06040000
  38259. #endif
  38260. /*
  38261. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  38262. ** target system. GetVersionEx was first deprecated in Win8.1.
  38263. */
  38264. #ifndef SQLITE_WIN32_GETVERSIONEX
  38265. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  38266. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  38267. # else
  38268. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  38269. # endif
  38270. #endif
  38271. /*
  38272. ** Check to see if the CreateFileMappingA function is supported on the
  38273. ** target system. It is unavailable when using "mincore.lib" on Win10.
  38274. ** When compiling for Windows 10, always assume "mincore.lib" is in use.
  38275. */
  38276. #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
  38277. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
  38278. # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
  38279. # else
  38280. # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
  38281. # endif
  38282. #endif
  38283. /*
  38284. ** This constant should already be defined (in the "WinDef.h" SDK file).
  38285. */
  38286. #ifndef MAX_PATH
  38287. # define MAX_PATH (260)
  38288. #endif
  38289. /*
  38290. ** Maximum pathname length (in chars) for Win32. This should normally be
  38291. ** MAX_PATH.
  38292. */
  38293. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  38294. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  38295. #endif
  38296. /*
  38297. ** This constant should already be defined (in the "WinNT.h" SDK file).
  38298. */
  38299. #ifndef UNICODE_STRING_MAX_CHARS
  38300. # define UNICODE_STRING_MAX_CHARS (32767)
  38301. #endif
  38302. /*
  38303. ** Maximum pathname length (in chars) for WinNT. This should normally be
  38304. ** UNICODE_STRING_MAX_CHARS.
  38305. */
  38306. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  38307. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  38308. #endif
  38309. /*
  38310. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  38311. ** characters, so we allocate 4 bytes per character assuming worst-case of
  38312. ** 4-bytes-per-character for UTF8.
  38313. */
  38314. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  38315. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  38316. #endif
  38317. /*
  38318. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  38319. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  38320. */
  38321. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  38322. # define SQLITE_WINNT_MAX_PATH_BYTES \
  38323. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  38324. #endif
  38325. /*
  38326. ** Maximum error message length (in chars) for WinRT.
  38327. */
  38328. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  38329. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  38330. #endif
  38331. /*
  38332. ** Returns non-zero if the character should be treated as a directory
  38333. ** separator.
  38334. */
  38335. #ifndef winIsDirSep
  38336. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  38337. #endif
  38338. /*
  38339. ** This macro is used when a local variable is set to a value that is
  38340. ** [sometimes] not used by the code (e.g. via conditional compilation).
  38341. */
  38342. #ifndef UNUSED_VARIABLE_VALUE
  38343. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  38344. #endif
  38345. /*
  38346. ** Returns the character that should be used as the directory separator.
  38347. */
  38348. #ifndef winGetDirSep
  38349. # define winGetDirSep() '\\'
  38350. #endif
  38351. /*
  38352. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  38353. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  38354. ** CE SDK; however, they are not present in the header file)?
  38355. */
  38356. #if SQLITE_WIN32_FILEMAPPING_API && \
  38357. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  38358. /*
  38359. ** Two of the file mapping APIs are different under WinRT. Figure out which
  38360. ** set we need.
  38361. */
  38362. #if SQLITE_OS_WINRT
  38363. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  38364. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  38365. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  38366. #else
  38367. #if defined(SQLITE_WIN32_HAS_ANSI)
  38368. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  38369. DWORD, DWORD, DWORD, LPCSTR);
  38370. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  38371. #if defined(SQLITE_WIN32_HAS_WIDE)
  38372. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  38373. DWORD, DWORD, DWORD, LPCWSTR);
  38374. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  38375. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  38376. #endif /* SQLITE_OS_WINRT */
  38377. /*
  38378. ** These file mapping APIs are common to both Win32 and WinRT.
  38379. */
  38380. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  38381. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  38382. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  38383. /*
  38384. ** Some Microsoft compilers lack this definition.
  38385. */
  38386. #ifndef INVALID_FILE_ATTRIBUTES
  38387. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  38388. #endif
  38389. #ifndef FILE_FLAG_MASK
  38390. # define FILE_FLAG_MASK (0xFF3C0000)
  38391. #endif
  38392. #ifndef FILE_ATTRIBUTE_MASK
  38393. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  38394. #endif
  38395. #ifndef SQLITE_OMIT_WAL
  38396. /* Forward references to structures used for WAL */
  38397. typedef struct winShm winShm; /* A connection to shared-memory */
  38398. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  38399. #endif
  38400. /*
  38401. ** WinCE lacks native support for file locking so we have to fake it
  38402. ** with some code of our own.
  38403. */
  38404. #if SQLITE_OS_WINCE
  38405. typedef struct winceLock {
  38406. int nReaders; /* Number of reader locks obtained */
  38407. BOOL bPending; /* Indicates a pending lock has been obtained */
  38408. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  38409. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  38410. } winceLock;
  38411. #endif
  38412. /*
  38413. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  38414. ** portability layer.
  38415. */
  38416. typedef struct winFile winFile;
  38417. struct winFile {
  38418. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  38419. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  38420. HANDLE h; /* Handle for accessing the file */
  38421. u8 locktype; /* Type of lock currently held on this file */
  38422. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  38423. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  38424. DWORD lastErrno; /* The Windows errno from the last I/O error */
  38425. #ifndef SQLITE_OMIT_WAL
  38426. winShm *pShm; /* Instance of shared memory on this file */
  38427. #endif
  38428. const char *zPath; /* Full pathname of this file */
  38429. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  38430. #if SQLITE_OS_WINCE
  38431. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  38432. HANDLE hMutex; /* Mutex used to control access to shared lock */
  38433. HANDLE hShared; /* Shared memory segment used for locking */
  38434. winceLock local; /* Locks obtained by this instance of winFile */
  38435. winceLock *shared; /* Global shared lock memory for the file */
  38436. #endif
  38437. #if SQLITE_MAX_MMAP_SIZE>0
  38438. int nFetchOut; /* Number of outstanding xFetch references */
  38439. HANDLE hMap; /* Handle for accessing memory mapping */
  38440. void *pMapRegion; /* Area memory mapped */
  38441. sqlite3_int64 mmapSize; /* Size of mapped region */
  38442. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  38443. #endif
  38444. };
  38445. /*
  38446. ** The winVfsAppData structure is used for the pAppData member for all of the
  38447. ** Win32 VFS variants.
  38448. */
  38449. typedef struct winVfsAppData winVfsAppData;
  38450. struct winVfsAppData {
  38451. const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
  38452. void *pAppData; /* The extra pAppData, if any. */
  38453. BOOL bNoLock; /* Non-zero if locking is disabled. */
  38454. };
  38455. /*
  38456. ** Allowed values for winFile.ctrlFlags
  38457. */
  38458. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  38459. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  38460. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  38461. /*
  38462. * The size of the buffer used by sqlite3_win32_write_debug().
  38463. */
  38464. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  38465. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  38466. #endif
  38467. /*
  38468. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  38469. * various Win32 API heap functions instead of our own.
  38470. */
  38471. #ifdef SQLITE_WIN32_MALLOC
  38472. /*
  38473. * If this is non-zero, an isolated heap will be created by the native Win32
  38474. * allocator subsystem; otherwise, the default process heap will be used. This
  38475. * setting has no effect when compiling for WinRT. By default, this is enabled
  38476. * and an isolated heap will be created to store all allocated data.
  38477. *
  38478. ******************************************************************************
  38479. * WARNING: It is important to note that when this setting is non-zero and the
  38480. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  38481. * function), all data that was allocated using the isolated heap will
  38482. * be freed immediately and any attempt to access any of that freed
  38483. * data will almost certainly result in an immediate access violation.
  38484. ******************************************************************************
  38485. */
  38486. #ifndef SQLITE_WIN32_HEAP_CREATE
  38487. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  38488. #endif
  38489. /*
  38490. * This is the maximum possible initial size of the Win32-specific heap, in
  38491. * bytes.
  38492. */
  38493. #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
  38494. # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
  38495. #endif
  38496. /*
  38497. * This is the extra space for the initial size of the Win32-specific heap,
  38498. * in bytes. This value may be zero.
  38499. */
  38500. #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
  38501. # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
  38502. #endif
  38503. /*
  38504. * Calculate the maximum legal cache size, in pages, based on the maximum
  38505. * possible initial heap size and the default page size, setting aside the
  38506. * needed extra space.
  38507. */
  38508. #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
  38509. # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
  38510. (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
  38511. (SQLITE_DEFAULT_PAGE_SIZE))
  38512. #endif
  38513. /*
  38514. * This is cache size used in the calculation of the initial size of the
  38515. * Win32-specific heap. It cannot be negative.
  38516. */
  38517. #ifndef SQLITE_WIN32_CACHE_SIZE
  38518. # if SQLITE_DEFAULT_CACHE_SIZE>=0
  38519. # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
  38520. # else
  38521. # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
  38522. # endif
  38523. #endif
  38524. /*
  38525. * Make sure that the calculated cache size, in pages, cannot cause the
  38526. * initial size of the Win32-specific heap to exceed the maximum amount
  38527. * of memory that can be specified in the call to HeapCreate.
  38528. */
  38529. #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
  38530. # undef SQLITE_WIN32_CACHE_SIZE
  38531. # define SQLITE_WIN32_CACHE_SIZE (2000)
  38532. #endif
  38533. /*
  38534. * The initial size of the Win32-specific heap. This value may be zero.
  38535. */
  38536. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  38537. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
  38538. (SQLITE_DEFAULT_PAGE_SIZE) + \
  38539. (SQLITE_WIN32_HEAP_INIT_EXTRA))
  38540. #endif
  38541. /*
  38542. * The maximum size of the Win32-specific heap. This value may be zero.
  38543. */
  38544. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  38545. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  38546. #endif
  38547. /*
  38548. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  38549. * zero for the default behavior.
  38550. */
  38551. #ifndef SQLITE_WIN32_HEAP_FLAGS
  38552. # define SQLITE_WIN32_HEAP_FLAGS (0)
  38553. #endif
  38554. /*
  38555. ** The winMemData structure stores information required by the Win32-specific
  38556. ** sqlite3_mem_methods implementation.
  38557. */
  38558. typedef struct winMemData winMemData;
  38559. struct winMemData {
  38560. #ifndef NDEBUG
  38561. u32 magic1; /* Magic number to detect structure corruption. */
  38562. #endif
  38563. HANDLE hHeap; /* The handle to our heap. */
  38564. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  38565. #ifndef NDEBUG
  38566. u32 magic2; /* Magic number to detect structure corruption. */
  38567. #endif
  38568. };
  38569. #ifndef NDEBUG
  38570. #define WINMEM_MAGIC1 0x42b2830b
  38571. #define WINMEM_MAGIC2 0xbd4d7cf4
  38572. #endif
  38573. static struct winMemData win_mem_data = {
  38574. #ifndef NDEBUG
  38575. WINMEM_MAGIC1,
  38576. #endif
  38577. NULL, FALSE
  38578. #ifndef NDEBUG
  38579. ,WINMEM_MAGIC2
  38580. #endif
  38581. };
  38582. #ifndef NDEBUG
  38583. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  38584. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  38585. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  38586. #else
  38587. #define winMemAssertMagic()
  38588. #endif
  38589. #define winMemGetDataPtr() &win_mem_data
  38590. #define winMemGetHeap() win_mem_data.hHeap
  38591. #define winMemGetOwned() win_mem_data.bOwned
  38592. static void *winMemMalloc(int nBytes);
  38593. static void winMemFree(void *pPrior);
  38594. static void *winMemRealloc(void *pPrior, int nBytes);
  38595. static int winMemSize(void *p);
  38596. static int winMemRoundup(int n);
  38597. static int winMemInit(void *pAppData);
  38598. static void winMemShutdown(void *pAppData);
  38599. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  38600. #endif /* SQLITE_WIN32_MALLOC */
  38601. /*
  38602. ** The following variable is (normally) set once and never changes
  38603. ** thereafter. It records whether the operating system is Win9x
  38604. ** or WinNT.
  38605. **
  38606. ** 0: Operating system unknown.
  38607. ** 1: Operating system is Win9x.
  38608. ** 2: Operating system is WinNT.
  38609. **
  38610. ** In order to facilitate testing on a WinNT system, the test fixture
  38611. ** can manually set this value to 1 to emulate Win98 behavior.
  38612. */
  38613. #ifdef SQLITE_TEST
  38614. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  38615. #else
  38616. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  38617. #endif
  38618. #ifndef SYSCALL
  38619. # define SYSCALL sqlite3_syscall_ptr
  38620. #endif
  38621. /*
  38622. ** This function is not available on Windows CE or WinRT.
  38623. */
  38624. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  38625. # define osAreFileApisANSI() 1
  38626. #endif
  38627. /*
  38628. ** Many system calls are accessed through pointer-to-functions so that
  38629. ** they may be overridden at runtime to facilitate fault injection during
  38630. ** testing and sandboxing. The following array holds the names and pointers
  38631. ** to all overrideable system calls.
  38632. */
  38633. static struct win_syscall {
  38634. const char *zName; /* Name of the system call */
  38635. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  38636. sqlite3_syscall_ptr pDefault; /* Default value */
  38637. } aSyscall[] = {
  38638. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  38639. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  38640. #else
  38641. { "AreFileApisANSI", (SYSCALL)0, 0 },
  38642. #endif
  38643. #ifndef osAreFileApisANSI
  38644. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  38645. #endif
  38646. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  38647. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  38648. #else
  38649. { "CharLowerW", (SYSCALL)0, 0 },
  38650. #endif
  38651. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  38652. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  38653. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  38654. #else
  38655. { "CharUpperW", (SYSCALL)0, 0 },
  38656. #endif
  38657. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  38658. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  38659. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  38660. #if defined(SQLITE_WIN32_HAS_ANSI)
  38661. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  38662. #else
  38663. { "CreateFileA", (SYSCALL)0, 0 },
  38664. #endif
  38665. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  38666. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  38667. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38668. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  38669. #else
  38670. { "CreateFileW", (SYSCALL)0, 0 },
  38671. #endif
  38672. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  38673. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  38674. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  38675. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
  38676. SQLITE_WIN32_CREATEFILEMAPPINGA
  38677. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  38678. #else
  38679. { "CreateFileMappingA", (SYSCALL)0, 0 },
  38680. #endif
  38681. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  38682. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  38683. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  38684. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  38685. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  38686. #else
  38687. { "CreateFileMappingW", (SYSCALL)0, 0 },
  38688. #endif
  38689. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  38690. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  38691. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38692. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  38693. #else
  38694. { "CreateMutexW", (SYSCALL)0, 0 },
  38695. #endif
  38696. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  38697. LPCWSTR))aSyscall[8].pCurrent)
  38698. #if defined(SQLITE_WIN32_HAS_ANSI)
  38699. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  38700. #else
  38701. { "DeleteFileA", (SYSCALL)0, 0 },
  38702. #endif
  38703. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  38704. #if defined(SQLITE_WIN32_HAS_WIDE)
  38705. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  38706. #else
  38707. { "DeleteFileW", (SYSCALL)0, 0 },
  38708. #endif
  38709. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  38710. #if SQLITE_OS_WINCE
  38711. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  38712. #else
  38713. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  38714. #endif
  38715. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  38716. LPFILETIME))aSyscall[11].pCurrent)
  38717. #if SQLITE_OS_WINCE
  38718. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  38719. #else
  38720. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  38721. #endif
  38722. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  38723. LPSYSTEMTIME))aSyscall[12].pCurrent)
  38724. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  38725. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  38726. #if defined(SQLITE_WIN32_HAS_ANSI)
  38727. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  38728. #else
  38729. { "FormatMessageA", (SYSCALL)0, 0 },
  38730. #endif
  38731. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  38732. DWORD,va_list*))aSyscall[14].pCurrent)
  38733. #if defined(SQLITE_WIN32_HAS_WIDE)
  38734. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  38735. #else
  38736. { "FormatMessageW", (SYSCALL)0, 0 },
  38737. #endif
  38738. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  38739. DWORD,va_list*))aSyscall[15].pCurrent)
  38740. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38741. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  38742. #else
  38743. { "FreeLibrary", (SYSCALL)0, 0 },
  38744. #endif
  38745. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  38746. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  38747. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  38748. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  38749. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  38750. #else
  38751. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  38752. #endif
  38753. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  38754. LPDWORD))aSyscall[18].pCurrent)
  38755. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38756. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  38757. #else
  38758. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  38759. #endif
  38760. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  38761. LPDWORD))aSyscall[19].pCurrent)
  38762. #if defined(SQLITE_WIN32_HAS_ANSI)
  38763. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  38764. #else
  38765. { "GetFileAttributesA", (SYSCALL)0, 0 },
  38766. #endif
  38767. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  38768. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38769. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  38770. #else
  38771. { "GetFileAttributesW", (SYSCALL)0, 0 },
  38772. #endif
  38773. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  38774. #if defined(SQLITE_WIN32_HAS_WIDE)
  38775. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  38776. #else
  38777. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  38778. #endif
  38779. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  38780. LPVOID))aSyscall[22].pCurrent)
  38781. #if !SQLITE_OS_WINRT
  38782. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  38783. #else
  38784. { "GetFileSize", (SYSCALL)0, 0 },
  38785. #endif
  38786. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  38787. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  38788. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  38789. #else
  38790. { "GetFullPathNameA", (SYSCALL)0, 0 },
  38791. #endif
  38792. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  38793. LPSTR*))aSyscall[24].pCurrent)
  38794. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38795. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  38796. #else
  38797. { "GetFullPathNameW", (SYSCALL)0, 0 },
  38798. #endif
  38799. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  38800. LPWSTR*))aSyscall[25].pCurrent)
  38801. { "GetLastError", (SYSCALL)GetLastError, 0 },
  38802. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  38803. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38804. #if SQLITE_OS_WINCE
  38805. /* The GetProcAddressA() routine is only available on Windows CE. */
  38806. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  38807. #else
  38808. /* All other Windows platforms expect GetProcAddress() to take
  38809. ** an ANSI string regardless of the _UNICODE setting */
  38810. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  38811. #endif
  38812. #else
  38813. { "GetProcAddressA", (SYSCALL)0, 0 },
  38814. #endif
  38815. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  38816. LPCSTR))aSyscall[27].pCurrent)
  38817. #if !SQLITE_OS_WINRT
  38818. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  38819. #else
  38820. { "GetSystemInfo", (SYSCALL)0, 0 },
  38821. #endif
  38822. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  38823. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  38824. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  38825. #if !SQLITE_OS_WINCE
  38826. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  38827. #else
  38828. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  38829. #endif
  38830. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  38831. LPFILETIME))aSyscall[30].pCurrent)
  38832. #if defined(SQLITE_WIN32_HAS_ANSI)
  38833. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  38834. #else
  38835. { "GetTempPathA", (SYSCALL)0, 0 },
  38836. #endif
  38837. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  38838. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38839. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  38840. #else
  38841. { "GetTempPathW", (SYSCALL)0, 0 },
  38842. #endif
  38843. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  38844. #if !SQLITE_OS_WINRT
  38845. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  38846. #else
  38847. { "GetTickCount", (SYSCALL)0, 0 },
  38848. #endif
  38849. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  38850. #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
  38851. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  38852. #else
  38853. { "GetVersionExA", (SYSCALL)0, 0 },
  38854. #endif
  38855. #define osGetVersionExA ((BOOL(WINAPI*)( \
  38856. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  38857. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  38858. SQLITE_WIN32_GETVERSIONEX
  38859. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  38860. #else
  38861. { "GetVersionExW", (SYSCALL)0, 0 },
  38862. #endif
  38863. #define osGetVersionExW ((BOOL(WINAPI*)( \
  38864. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  38865. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  38866. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  38867. SIZE_T))aSyscall[36].pCurrent)
  38868. #if !SQLITE_OS_WINRT
  38869. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  38870. #else
  38871. { "HeapCreate", (SYSCALL)0, 0 },
  38872. #endif
  38873. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  38874. SIZE_T))aSyscall[37].pCurrent)
  38875. #if !SQLITE_OS_WINRT
  38876. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  38877. #else
  38878. { "HeapDestroy", (SYSCALL)0, 0 },
  38879. #endif
  38880. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  38881. { "HeapFree", (SYSCALL)HeapFree, 0 },
  38882. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  38883. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  38884. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  38885. SIZE_T))aSyscall[40].pCurrent)
  38886. { "HeapSize", (SYSCALL)HeapSize, 0 },
  38887. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  38888. LPCVOID))aSyscall[41].pCurrent)
  38889. #if !SQLITE_OS_WINRT
  38890. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  38891. #else
  38892. { "HeapValidate", (SYSCALL)0, 0 },
  38893. #endif
  38894. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  38895. LPCVOID))aSyscall[42].pCurrent)
  38896. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  38897. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  38898. #else
  38899. { "HeapCompact", (SYSCALL)0, 0 },
  38900. #endif
  38901. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  38902. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38903. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  38904. #else
  38905. { "LoadLibraryA", (SYSCALL)0, 0 },
  38906. #endif
  38907. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  38908. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  38909. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38910. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  38911. #else
  38912. { "LoadLibraryW", (SYSCALL)0, 0 },
  38913. #endif
  38914. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  38915. #if !SQLITE_OS_WINRT
  38916. { "LocalFree", (SYSCALL)LocalFree, 0 },
  38917. #else
  38918. { "LocalFree", (SYSCALL)0, 0 },
  38919. #endif
  38920. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  38921. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  38922. { "LockFile", (SYSCALL)LockFile, 0 },
  38923. #else
  38924. { "LockFile", (SYSCALL)0, 0 },
  38925. #endif
  38926. #ifndef osLockFile
  38927. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  38928. DWORD))aSyscall[47].pCurrent)
  38929. #endif
  38930. #if !SQLITE_OS_WINCE
  38931. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  38932. #else
  38933. { "LockFileEx", (SYSCALL)0, 0 },
  38934. #endif
  38935. #ifndef osLockFileEx
  38936. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  38937. LPOVERLAPPED))aSyscall[48].pCurrent)
  38938. #endif
  38939. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  38940. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  38941. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  38942. #else
  38943. { "MapViewOfFile", (SYSCALL)0, 0 },
  38944. #endif
  38945. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  38946. SIZE_T))aSyscall[49].pCurrent)
  38947. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  38948. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  38949. int))aSyscall[50].pCurrent)
  38950. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  38951. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  38952. LARGE_INTEGER*))aSyscall[51].pCurrent)
  38953. { "ReadFile", (SYSCALL)ReadFile, 0 },
  38954. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  38955. LPOVERLAPPED))aSyscall[52].pCurrent)
  38956. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  38957. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  38958. #if !SQLITE_OS_WINRT
  38959. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  38960. #else
  38961. { "SetFilePointer", (SYSCALL)0, 0 },
  38962. #endif
  38963. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  38964. DWORD))aSyscall[54].pCurrent)
  38965. #if !SQLITE_OS_WINRT
  38966. { "Sleep", (SYSCALL)Sleep, 0 },
  38967. #else
  38968. { "Sleep", (SYSCALL)0, 0 },
  38969. #endif
  38970. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  38971. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  38972. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  38973. LPFILETIME))aSyscall[56].pCurrent)
  38974. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  38975. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  38976. #else
  38977. { "UnlockFile", (SYSCALL)0, 0 },
  38978. #endif
  38979. #ifndef osUnlockFile
  38980. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  38981. DWORD))aSyscall[57].pCurrent)
  38982. #endif
  38983. #if !SQLITE_OS_WINCE
  38984. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  38985. #else
  38986. { "UnlockFileEx", (SYSCALL)0, 0 },
  38987. #endif
  38988. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  38989. LPOVERLAPPED))aSyscall[58].pCurrent)
  38990. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  38991. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  38992. #else
  38993. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  38994. #endif
  38995. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  38996. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  38997. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  38998. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  38999. { "WriteFile", (SYSCALL)WriteFile, 0 },
  39000. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  39001. LPOVERLAPPED))aSyscall[61].pCurrent)
  39002. #if SQLITE_OS_WINRT
  39003. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  39004. #else
  39005. { "CreateEventExW", (SYSCALL)0, 0 },
  39006. #endif
  39007. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  39008. DWORD,DWORD))aSyscall[62].pCurrent)
  39009. #if !SQLITE_OS_WINRT
  39010. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  39011. #else
  39012. { "WaitForSingleObject", (SYSCALL)0, 0 },
  39013. #endif
  39014. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  39015. DWORD))aSyscall[63].pCurrent)
  39016. #if !SQLITE_OS_WINCE
  39017. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  39018. #else
  39019. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  39020. #endif
  39021. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  39022. BOOL))aSyscall[64].pCurrent)
  39023. #if SQLITE_OS_WINRT
  39024. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  39025. #else
  39026. { "SetFilePointerEx", (SYSCALL)0, 0 },
  39027. #endif
  39028. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  39029. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  39030. #if SQLITE_OS_WINRT
  39031. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  39032. #else
  39033. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  39034. #endif
  39035. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  39036. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  39037. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  39038. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  39039. #else
  39040. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  39041. #endif
  39042. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  39043. SIZE_T))aSyscall[67].pCurrent)
  39044. #if SQLITE_OS_WINRT
  39045. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  39046. #else
  39047. { "CreateFile2", (SYSCALL)0, 0 },
  39048. #endif
  39049. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  39050. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  39051. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  39052. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  39053. #else
  39054. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  39055. #endif
  39056. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  39057. DWORD))aSyscall[69].pCurrent)
  39058. #if SQLITE_OS_WINRT
  39059. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  39060. #else
  39061. { "GetTickCount64", (SYSCALL)0, 0 },
  39062. #endif
  39063. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  39064. #if SQLITE_OS_WINRT
  39065. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  39066. #else
  39067. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  39068. #endif
  39069. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  39070. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  39071. #if defined(SQLITE_WIN32_HAS_ANSI)
  39072. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  39073. #else
  39074. { "OutputDebugStringA", (SYSCALL)0, 0 },
  39075. #endif
  39076. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  39077. #if defined(SQLITE_WIN32_HAS_WIDE)
  39078. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  39079. #else
  39080. { "OutputDebugStringW", (SYSCALL)0, 0 },
  39081. #endif
  39082. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  39083. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  39084. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  39085. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  39086. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  39087. #else
  39088. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  39089. #endif
  39090. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  39091. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  39092. /*
  39093. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  39094. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  39095. ** So do not try to make this is into a redefinable interface.
  39096. */
  39097. #if defined(InterlockedCompareExchange)
  39098. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  39099. #define osInterlockedCompareExchange InterlockedCompareExchange
  39100. #else
  39101. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  39102. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  39103. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  39104. #endif /* defined(InterlockedCompareExchange) */
  39105. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  39106. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  39107. #else
  39108. { "UuidCreate", (SYSCALL)0, 0 },
  39109. #endif
  39110. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  39111. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  39112. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  39113. #else
  39114. { "UuidCreateSequential", (SYSCALL)0, 0 },
  39115. #endif
  39116. #define osUuidCreateSequential \
  39117. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  39118. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  39119. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  39120. #else
  39121. { "FlushViewOfFile", (SYSCALL)0, 0 },
  39122. #endif
  39123. #define osFlushViewOfFile \
  39124. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  39125. }; /* End of the overrideable system calls */
  39126. /*
  39127. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  39128. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  39129. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  39130. ** system call named zName.
  39131. */
  39132. static int winSetSystemCall(
  39133. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  39134. const char *zName, /* Name of system call to override */
  39135. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  39136. ){
  39137. unsigned int i;
  39138. int rc = SQLITE_NOTFOUND;
  39139. UNUSED_PARAMETER(pNotUsed);
  39140. if( zName==0 ){
  39141. /* If no zName is given, restore all system calls to their default
  39142. ** settings and return NULL
  39143. */
  39144. rc = SQLITE_OK;
  39145. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  39146. if( aSyscall[i].pDefault ){
  39147. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  39148. }
  39149. }
  39150. }else{
  39151. /* If zName is specified, operate on only the one system call
  39152. ** specified.
  39153. */
  39154. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  39155. if( strcmp(zName, aSyscall[i].zName)==0 ){
  39156. if( aSyscall[i].pDefault==0 ){
  39157. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  39158. }
  39159. rc = SQLITE_OK;
  39160. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  39161. aSyscall[i].pCurrent = pNewFunc;
  39162. break;
  39163. }
  39164. }
  39165. }
  39166. return rc;
  39167. }
  39168. /*
  39169. ** Return the value of a system call. Return NULL if zName is not a
  39170. ** recognized system call name. NULL is also returned if the system call
  39171. ** is currently undefined.
  39172. */
  39173. static sqlite3_syscall_ptr winGetSystemCall(
  39174. sqlite3_vfs *pNotUsed,
  39175. const char *zName
  39176. ){
  39177. unsigned int i;
  39178. UNUSED_PARAMETER(pNotUsed);
  39179. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  39180. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  39181. }
  39182. return 0;
  39183. }
  39184. /*
  39185. ** Return the name of the first system call after zName. If zName==NULL
  39186. ** then return the name of the first system call. Return NULL if zName
  39187. ** is the last system call or if zName is not the name of a valid
  39188. ** system call.
  39189. */
  39190. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  39191. int i = -1;
  39192. UNUSED_PARAMETER(p);
  39193. if( zName ){
  39194. for(i=0; i<ArraySize(aSyscall)-1; i++){
  39195. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  39196. }
  39197. }
  39198. for(i++; i<ArraySize(aSyscall); i++){
  39199. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  39200. }
  39201. return 0;
  39202. }
  39203. #ifdef SQLITE_WIN32_MALLOC
  39204. /*
  39205. ** If a Win32 native heap has been configured, this function will attempt to
  39206. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  39207. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  39208. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  39209. ** largest committed free block in the heap, in bytes.
  39210. */
  39211. SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
  39212. int rc = SQLITE_OK;
  39213. UINT nLargest = 0;
  39214. HANDLE hHeap;
  39215. winMemAssertMagic();
  39216. hHeap = winMemGetHeap();
  39217. assert( hHeap!=0 );
  39218. assert( hHeap!=INVALID_HANDLE_VALUE );
  39219. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39220. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39221. #endif
  39222. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  39223. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  39224. DWORD lastErrno = osGetLastError();
  39225. if( lastErrno==NO_ERROR ){
  39226. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  39227. (void*)hHeap);
  39228. rc = SQLITE_NOMEM_BKPT;
  39229. }else{
  39230. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  39231. osGetLastError(), (void*)hHeap);
  39232. rc = SQLITE_ERROR;
  39233. }
  39234. }
  39235. #else
  39236. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  39237. (void*)hHeap);
  39238. rc = SQLITE_NOTFOUND;
  39239. #endif
  39240. if( pnLargest ) *pnLargest = nLargest;
  39241. return rc;
  39242. }
  39243. /*
  39244. ** If a Win32 native heap has been configured, this function will attempt to
  39245. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  39246. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  39247. ** be returned and no changes will be made to the Win32 native heap.
  39248. */
  39249. SQLITE_API int sqlite3_win32_reset_heap(){
  39250. int rc;
  39251. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  39252. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  39253. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  39254. MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
  39255. sqlite3_mutex_enter(pMaster);
  39256. sqlite3_mutex_enter(pMem);
  39257. winMemAssertMagic();
  39258. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  39259. /*
  39260. ** At this point, there should be no outstanding memory allocations on
  39261. ** the heap. Also, since both the master and memsys locks are currently
  39262. ** being held by us, no other function (i.e. from another thread) should
  39263. ** be able to even access the heap. Attempt to destroy and recreate our
  39264. ** isolated Win32 native heap now.
  39265. */
  39266. assert( winMemGetHeap()!=NULL );
  39267. assert( winMemGetOwned() );
  39268. assert( sqlite3_memory_used()==0 );
  39269. winMemShutdown(winMemGetDataPtr());
  39270. assert( winMemGetHeap()==NULL );
  39271. assert( !winMemGetOwned() );
  39272. assert( sqlite3_memory_used()==0 );
  39273. rc = winMemInit(winMemGetDataPtr());
  39274. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  39275. assert( rc!=SQLITE_OK || winMemGetOwned() );
  39276. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  39277. }else{
  39278. /*
  39279. ** The Win32 native heap cannot be modified because it may be in use.
  39280. */
  39281. rc = SQLITE_BUSY;
  39282. }
  39283. sqlite3_mutex_leave(pMem);
  39284. sqlite3_mutex_leave(pMaster);
  39285. return rc;
  39286. }
  39287. #endif /* SQLITE_WIN32_MALLOC */
  39288. /*
  39289. ** This function outputs the specified (ANSI) string to the Win32 debugger
  39290. ** (if available).
  39291. */
  39292. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  39293. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  39294. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  39295. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  39296. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  39297. #ifdef SQLITE_ENABLE_API_ARMOR
  39298. if( !zBuf ){
  39299. (void)SQLITE_MISUSE_BKPT;
  39300. return;
  39301. }
  39302. #endif
  39303. #if defined(SQLITE_WIN32_HAS_ANSI)
  39304. if( nMin>0 ){
  39305. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  39306. memcpy(zDbgBuf, zBuf, nMin);
  39307. osOutputDebugStringA(zDbgBuf);
  39308. }else{
  39309. osOutputDebugStringA(zBuf);
  39310. }
  39311. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39312. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  39313. if ( osMultiByteToWideChar(
  39314. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  39315. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  39316. return;
  39317. }
  39318. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  39319. #else
  39320. if( nMin>0 ){
  39321. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  39322. memcpy(zDbgBuf, zBuf, nMin);
  39323. fprintf(stderr, "%s", zDbgBuf);
  39324. }else{
  39325. fprintf(stderr, "%s", zBuf);
  39326. }
  39327. #endif
  39328. }
  39329. /*
  39330. ** The following routine suspends the current thread for at least ms
  39331. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  39332. */
  39333. #if SQLITE_OS_WINRT
  39334. static HANDLE sleepObj = NULL;
  39335. #endif
  39336. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  39337. #if SQLITE_OS_WINRT
  39338. if ( sleepObj==NULL ){
  39339. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  39340. SYNCHRONIZE);
  39341. }
  39342. assert( sleepObj!=NULL );
  39343. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  39344. #else
  39345. osSleep(milliseconds);
  39346. #endif
  39347. }
  39348. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  39349. SQLITE_THREADSAFE>0
  39350. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  39351. DWORD rc;
  39352. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  39353. TRUE))==WAIT_IO_COMPLETION ){}
  39354. return rc;
  39355. }
  39356. #endif
  39357. /*
  39358. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  39359. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  39360. **
  39361. ** Here is an interesting observation: Win95, Win98, and WinME lack
  39362. ** the LockFileEx() API. But we can still statically link against that
  39363. ** API as long as we don't call it when running Win95/98/ME. A call to
  39364. ** this routine is used to determine if the host is Win95/98/ME or
  39365. ** WinNT/2K/XP so that we will know whether or not we can safely call
  39366. ** the LockFileEx() API.
  39367. */
  39368. #if !SQLITE_WIN32_GETVERSIONEX
  39369. # define osIsNT() (1)
  39370. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  39371. # define osIsNT() (1)
  39372. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  39373. # define osIsNT() (0)
  39374. #else
  39375. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  39376. #endif
  39377. /*
  39378. ** This function determines if the machine is running a version of Windows
  39379. ** based on the NT kernel.
  39380. */
  39381. SQLITE_API int sqlite3_win32_is_nt(void){
  39382. #if SQLITE_OS_WINRT
  39383. /*
  39384. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  39385. ** kernel.
  39386. */
  39387. return 1;
  39388. #elif SQLITE_WIN32_GETVERSIONEX
  39389. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  39390. #if defined(SQLITE_WIN32_HAS_ANSI)
  39391. OSVERSIONINFOA sInfo;
  39392. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  39393. osGetVersionExA(&sInfo);
  39394. osInterlockedCompareExchange(&sqlite3_os_type,
  39395. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  39396. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39397. OSVERSIONINFOW sInfo;
  39398. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  39399. osGetVersionExW(&sInfo);
  39400. osInterlockedCompareExchange(&sqlite3_os_type,
  39401. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  39402. #endif
  39403. }
  39404. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  39405. #elif SQLITE_TEST
  39406. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  39407. #else
  39408. /*
  39409. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  39410. ** deprecated are always assumed to be based on the NT kernel.
  39411. */
  39412. return 1;
  39413. #endif
  39414. }
  39415. #ifdef SQLITE_WIN32_MALLOC
  39416. /*
  39417. ** Allocate nBytes of memory.
  39418. */
  39419. static void *winMemMalloc(int nBytes){
  39420. HANDLE hHeap;
  39421. void *p;
  39422. winMemAssertMagic();
  39423. hHeap = winMemGetHeap();
  39424. assert( hHeap!=0 );
  39425. assert( hHeap!=INVALID_HANDLE_VALUE );
  39426. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39427. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39428. #endif
  39429. assert( nBytes>=0 );
  39430. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  39431. if( !p ){
  39432. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  39433. nBytes, osGetLastError(), (void*)hHeap);
  39434. }
  39435. return p;
  39436. }
  39437. /*
  39438. ** Free memory.
  39439. */
  39440. static void winMemFree(void *pPrior){
  39441. HANDLE hHeap;
  39442. winMemAssertMagic();
  39443. hHeap = winMemGetHeap();
  39444. assert( hHeap!=0 );
  39445. assert( hHeap!=INVALID_HANDLE_VALUE );
  39446. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39447. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  39448. #endif
  39449. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  39450. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  39451. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  39452. pPrior, osGetLastError(), (void*)hHeap);
  39453. }
  39454. }
  39455. /*
  39456. ** Change the size of an existing memory allocation
  39457. */
  39458. static void *winMemRealloc(void *pPrior, int nBytes){
  39459. HANDLE hHeap;
  39460. void *p;
  39461. winMemAssertMagic();
  39462. hHeap = winMemGetHeap();
  39463. assert( hHeap!=0 );
  39464. assert( hHeap!=INVALID_HANDLE_VALUE );
  39465. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39466. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  39467. #endif
  39468. assert( nBytes>=0 );
  39469. if( !pPrior ){
  39470. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  39471. }else{
  39472. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  39473. }
  39474. if( !p ){
  39475. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  39476. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  39477. (void*)hHeap);
  39478. }
  39479. return p;
  39480. }
  39481. /*
  39482. ** Return the size of an outstanding allocation, in bytes.
  39483. */
  39484. static int winMemSize(void *p){
  39485. HANDLE hHeap;
  39486. SIZE_T n;
  39487. winMemAssertMagic();
  39488. hHeap = winMemGetHeap();
  39489. assert( hHeap!=0 );
  39490. assert( hHeap!=INVALID_HANDLE_VALUE );
  39491. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39492. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  39493. #endif
  39494. if( !p ) return 0;
  39495. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  39496. if( n==(SIZE_T)-1 ){
  39497. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  39498. p, osGetLastError(), (void*)hHeap);
  39499. return 0;
  39500. }
  39501. return (int)n;
  39502. }
  39503. /*
  39504. ** Round up a request size to the next valid allocation size.
  39505. */
  39506. static int winMemRoundup(int n){
  39507. return n;
  39508. }
  39509. /*
  39510. ** Initialize this module.
  39511. */
  39512. static int winMemInit(void *pAppData){
  39513. winMemData *pWinMemData = (winMemData *)pAppData;
  39514. if( !pWinMemData ) return SQLITE_ERROR;
  39515. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  39516. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  39517. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  39518. if( !pWinMemData->hHeap ){
  39519. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  39520. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  39521. if( dwMaximumSize==0 ){
  39522. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  39523. }else if( dwInitialSize>dwMaximumSize ){
  39524. dwInitialSize = dwMaximumSize;
  39525. }
  39526. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  39527. dwInitialSize, dwMaximumSize);
  39528. if( !pWinMemData->hHeap ){
  39529. sqlite3_log(SQLITE_NOMEM,
  39530. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  39531. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  39532. dwMaximumSize);
  39533. return SQLITE_NOMEM_BKPT;
  39534. }
  39535. pWinMemData->bOwned = TRUE;
  39536. assert( pWinMemData->bOwned );
  39537. }
  39538. #else
  39539. pWinMemData->hHeap = osGetProcessHeap();
  39540. if( !pWinMemData->hHeap ){
  39541. sqlite3_log(SQLITE_NOMEM,
  39542. "failed to GetProcessHeap (%lu)", osGetLastError());
  39543. return SQLITE_NOMEM_BKPT;
  39544. }
  39545. pWinMemData->bOwned = FALSE;
  39546. assert( !pWinMemData->bOwned );
  39547. #endif
  39548. assert( pWinMemData->hHeap!=0 );
  39549. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  39550. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39551. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39552. #endif
  39553. return SQLITE_OK;
  39554. }
  39555. /*
  39556. ** Deinitialize this module.
  39557. */
  39558. static void winMemShutdown(void *pAppData){
  39559. winMemData *pWinMemData = (winMemData *)pAppData;
  39560. if( !pWinMemData ) return;
  39561. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  39562. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  39563. if( pWinMemData->hHeap ){
  39564. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  39565. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39566. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39567. #endif
  39568. if( pWinMemData->bOwned ){
  39569. if( !osHeapDestroy(pWinMemData->hHeap) ){
  39570. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  39571. osGetLastError(), (void*)pWinMemData->hHeap);
  39572. }
  39573. pWinMemData->bOwned = FALSE;
  39574. }
  39575. pWinMemData->hHeap = NULL;
  39576. }
  39577. }
  39578. /*
  39579. ** Populate the low-level memory allocation function pointers in
  39580. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  39581. ** arguments specify the block of memory to manage.
  39582. **
  39583. ** This routine is only called by sqlite3_config(), and therefore
  39584. ** is not required to be threadsafe (it is not).
  39585. */
  39586. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  39587. static const sqlite3_mem_methods winMemMethods = {
  39588. winMemMalloc,
  39589. winMemFree,
  39590. winMemRealloc,
  39591. winMemSize,
  39592. winMemRoundup,
  39593. winMemInit,
  39594. winMemShutdown,
  39595. &win_mem_data
  39596. };
  39597. return &winMemMethods;
  39598. }
  39599. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  39600. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  39601. }
  39602. #endif /* SQLITE_WIN32_MALLOC */
  39603. /*
  39604. ** Convert a UTF-8 string to Microsoft Unicode.
  39605. **
  39606. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39607. */
  39608. static LPWSTR winUtf8ToUnicode(const char *zText){
  39609. int nChar;
  39610. LPWSTR zWideText;
  39611. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
  39612. if( nChar==0 ){
  39613. return 0;
  39614. }
  39615. zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
  39616. if( zWideText==0 ){
  39617. return 0;
  39618. }
  39619. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
  39620. nChar);
  39621. if( nChar==0 ){
  39622. sqlite3_free(zWideText);
  39623. zWideText = 0;
  39624. }
  39625. return zWideText;
  39626. }
  39627. /*
  39628. ** Convert a Microsoft Unicode string to UTF-8.
  39629. **
  39630. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39631. */
  39632. static char *winUnicodeToUtf8(LPCWSTR zWideText){
  39633. int nByte;
  39634. char *zText;
  39635. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
  39636. if( nByte == 0 ){
  39637. return 0;
  39638. }
  39639. zText = sqlite3MallocZero( nByte );
  39640. if( zText==0 ){
  39641. return 0;
  39642. }
  39643. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
  39644. 0, 0);
  39645. if( nByte == 0 ){
  39646. sqlite3_free(zText);
  39647. zText = 0;
  39648. }
  39649. return zText;
  39650. }
  39651. /*
  39652. ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
  39653. ** code page.
  39654. **
  39655. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39656. */
  39657. static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
  39658. int nByte;
  39659. LPWSTR zMbcsText;
  39660. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  39661. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
  39662. 0)*sizeof(WCHAR);
  39663. if( nByte==0 ){
  39664. return 0;
  39665. }
  39666. zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
  39667. if( zMbcsText==0 ){
  39668. return 0;
  39669. }
  39670. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
  39671. nByte);
  39672. if( nByte==0 ){
  39673. sqlite3_free(zMbcsText);
  39674. zMbcsText = 0;
  39675. }
  39676. return zMbcsText;
  39677. }
  39678. /*
  39679. ** Convert a Microsoft Unicode string to a multi-byte character string,
  39680. ** using the ANSI or OEM code page.
  39681. **
  39682. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39683. */
  39684. static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
  39685. int nByte;
  39686. char *zText;
  39687. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  39688. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
  39689. if( nByte == 0 ){
  39690. return 0;
  39691. }
  39692. zText = sqlite3MallocZero( nByte );
  39693. if( zText==0 ){
  39694. return 0;
  39695. }
  39696. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
  39697. nByte, 0, 0);
  39698. if( nByte == 0 ){
  39699. sqlite3_free(zText);
  39700. zText = 0;
  39701. }
  39702. return zText;
  39703. }
  39704. /*
  39705. ** Convert a multi-byte character string to UTF-8.
  39706. **
  39707. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39708. */
  39709. static char *winMbcsToUtf8(const char *zText, int useAnsi){
  39710. char *zTextUtf8;
  39711. LPWSTR zTmpWide;
  39712. zTmpWide = winMbcsToUnicode(zText, useAnsi);
  39713. if( zTmpWide==0 ){
  39714. return 0;
  39715. }
  39716. zTextUtf8 = winUnicodeToUtf8(zTmpWide);
  39717. sqlite3_free(zTmpWide);
  39718. return zTextUtf8;
  39719. }
  39720. /*
  39721. ** Convert a UTF-8 string to a multi-byte character string.
  39722. **
  39723. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39724. */
  39725. static char *winUtf8ToMbcs(const char *zText, int useAnsi){
  39726. char *zTextMbcs;
  39727. LPWSTR zTmpWide;
  39728. zTmpWide = winUtf8ToUnicode(zText);
  39729. if( zTmpWide==0 ){
  39730. return 0;
  39731. }
  39732. zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
  39733. sqlite3_free(zTmpWide);
  39734. return zTextMbcs;
  39735. }
  39736. /*
  39737. ** This is a public wrapper for the winUtf8ToUnicode() function.
  39738. */
  39739. SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
  39740. #ifdef SQLITE_ENABLE_API_ARMOR
  39741. if( !zText ){
  39742. (void)SQLITE_MISUSE_BKPT;
  39743. return 0;
  39744. }
  39745. #endif
  39746. #ifndef SQLITE_OMIT_AUTOINIT
  39747. if( sqlite3_initialize() ) return 0;
  39748. #endif
  39749. return winUtf8ToUnicode(zText);
  39750. }
  39751. /*
  39752. ** This is a public wrapper for the winUnicodeToUtf8() function.
  39753. */
  39754. SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
  39755. #ifdef SQLITE_ENABLE_API_ARMOR
  39756. if( !zWideText ){
  39757. (void)SQLITE_MISUSE_BKPT;
  39758. return 0;
  39759. }
  39760. #endif
  39761. #ifndef SQLITE_OMIT_AUTOINIT
  39762. if( sqlite3_initialize() ) return 0;
  39763. #endif
  39764. return winUnicodeToUtf8(zWideText);
  39765. }
  39766. /*
  39767. ** This is a public wrapper for the winMbcsToUtf8() function.
  39768. */
  39769. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
  39770. #ifdef SQLITE_ENABLE_API_ARMOR
  39771. if( !zText ){
  39772. (void)SQLITE_MISUSE_BKPT;
  39773. return 0;
  39774. }
  39775. #endif
  39776. #ifndef SQLITE_OMIT_AUTOINIT
  39777. if( sqlite3_initialize() ) return 0;
  39778. #endif
  39779. return winMbcsToUtf8(zText, osAreFileApisANSI());
  39780. }
  39781. /*
  39782. ** This is a public wrapper for the winMbcsToUtf8() function.
  39783. */
  39784. SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
  39785. #ifdef SQLITE_ENABLE_API_ARMOR
  39786. if( !zText ){
  39787. (void)SQLITE_MISUSE_BKPT;
  39788. return 0;
  39789. }
  39790. #endif
  39791. #ifndef SQLITE_OMIT_AUTOINIT
  39792. if( sqlite3_initialize() ) return 0;
  39793. #endif
  39794. return winMbcsToUtf8(zText, useAnsi);
  39795. }
  39796. /*
  39797. ** This is a public wrapper for the winUtf8ToMbcs() function.
  39798. */
  39799. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
  39800. #ifdef SQLITE_ENABLE_API_ARMOR
  39801. if( !zText ){
  39802. (void)SQLITE_MISUSE_BKPT;
  39803. return 0;
  39804. }
  39805. #endif
  39806. #ifndef SQLITE_OMIT_AUTOINIT
  39807. if( sqlite3_initialize() ) return 0;
  39808. #endif
  39809. return winUtf8ToMbcs(zText, osAreFileApisANSI());
  39810. }
  39811. /*
  39812. ** This is a public wrapper for the winUtf8ToMbcs() function.
  39813. */
  39814. SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
  39815. #ifdef SQLITE_ENABLE_API_ARMOR
  39816. if( !zText ){
  39817. (void)SQLITE_MISUSE_BKPT;
  39818. return 0;
  39819. }
  39820. #endif
  39821. #ifndef SQLITE_OMIT_AUTOINIT
  39822. if( sqlite3_initialize() ) return 0;
  39823. #endif
  39824. return winUtf8ToMbcs(zText, useAnsi);
  39825. }
  39826. /*
  39827. ** This function is the same as sqlite3_win32_set_directory (below); however,
  39828. ** it accepts a UTF-8 string.
  39829. */
  39830. SQLITE_API int sqlite3_win32_set_directory8(
  39831. unsigned long type, /* Identifier for directory being set or reset */
  39832. const char *zValue /* New value for directory being set or reset */
  39833. ){
  39834. char **ppDirectory = 0;
  39835. #ifndef SQLITE_OMIT_AUTOINIT
  39836. int rc = sqlite3_initialize();
  39837. if( rc ) return rc;
  39838. #endif
  39839. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  39840. ppDirectory = &sqlite3_data_directory;
  39841. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  39842. ppDirectory = &sqlite3_temp_directory;
  39843. }
  39844. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  39845. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  39846. );
  39847. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  39848. if( ppDirectory ){
  39849. char *zCopy = 0;
  39850. if( zValue && zValue[0] ){
  39851. zCopy = sqlite3_mprintf("%s", zValue);
  39852. if ( zCopy==0 ){
  39853. return SQLITE_NOMEM_BKPT;
  39854. }
  39855. }
  39856. sqlite3_free(*ppDirectory);
  39857. *ppDirectory = zCopy;
  39858. return SQLITE_OK;
  39859. }
  39860. return SQLITE_ERROR;
  39861. }
  39862. /*
  39863. ** This function is the same as sqlite3_win32_set_directory (below); however,
  39864. ** it accepts a UTF-16 string.
  39865. */
  39866. SQLITE_API int sqlite3_win32_set_directory16(
  39867. unsigned long type, /* Identifier for directory being set or reset */
  39868. const void *zValue /* New value for directory being set or reset */
  39869. ){
  39870. int rc;
  39871. char *zUtf8 = 0;
  39872. if( zValue ){
  39873. zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
  39874. if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
  39875. }
  39876. rc = sqlite3_win32_set_directory8(type, zUtf8);
  39877. if( zUtf8 ) sqlite3_free(zUtf8);
  39878. return rc;
  39879. }
  39880. /*
  39881. ** This function sets the data directory or the temporary directory based on
  39882. ** the provided arguments. The type argument must be 1 in order to set the
  39883. ** data directory or 2 in order to set the temporary directory. The zValue
  39884. ** argument is the name of the directory to use. The return value will be
  39885. ** SQLITE_OK if successful.
  39886. */
  39887. SQLITE_API int sqlite3_win32_set_directory(
  39888. unsigned long type, /* Identifier for directory being set or reset */
  39889. void *zValue /* New value for directory being set or reset */
  39890. ){
  39891. return sqlite3_win32_set_directory16(type, zValue);
  39892. }
  39893. /*
  39894. ** The return value of winGetLastErrorMsg
  39895. ** is zero if the error message fits in the buffer, or non-zero
  39896. ** otherwise (if the message was truncated).
  39897. */
  39898. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  39899. /* FormatMessage returns 0 on failure. Otherwise it
  39900. ** returns the number of TCHARs written to the output
  39901. ** buffer, excluding the terminating null char.
  39902. */
  39903. DWORD dwLen = 0;
  39904. char *zOut = 0;
  39905. if( osIsNT() ){
  39906. #if SQLITE_OS_WINRT
  39907. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  39908. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  39909. FORMAT_MESSAGE_IGNORE_INSERTS,
  39910. NULL,
  39911. lastErrno,
  39912. 0,
  39913. zTempWide,
  39914. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  39915. 0);
  39916. #else
  39917. LPWSTR zTempWide = NULL;
  39918. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  39919. FORMAT_MESSAGE_FROM_SYSTEM |
  39920. FORMAT_MESSAGE_IGNORE_INSERTS,
  39921. NULL,
  39922. lastErrno,
  39923. 0,
  39924. (LPWSTR) &zTempWide,
  39925. 0,
  39926. 0);
  39927. #endif
  39928. if( dwLen > 0 ){
  39929. /* allocate a buffer and convert to UTF8 */
  39930. sqlite3BeginBenignMalloc();
  39931. zOut = winUnicodeToUtf8(zTempWide);
  39932. sqlite3EndBenignMalloc();
  39933. #if !SQLITE_OS_WINRT
  39934. /* free the system buffer allocated by FormatMessage */
  39935. osLocalFree(zTempWide);
  39936. #endif
  39937. }
  39938. }
  39939. #ifdef SQLITE_WIN32_HAS_ANSI
  39940. else{
  39941. char *zTemp = NULL;
  39942. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  39943. FORMAT_MESSAGE_FROM_SYSTEM |
  39944. FORMAT_MESSAGE_IGNORE_INSERTS,
  39945. NULL,
  39946. lastErrno,
  39947. 0,
  39948. (LPSTR) &zTemp,
  39949. 0,
  39950. 0);
  39951. if( dwLen > 0 ){
  39952. /* allocate a buffer and convert to UTF8 */
  39953. sqlite3BeginBenignMalloc();
  39954. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  39955. sqlite3EndBenignMalloc();
  39956. /* free the system buffer allocated by FormatMessage */
  39957. osLocalFree(zTemp);
  39958. }
  39959. }
  39960. #endif
  39961. if( 0 == dwLen ){
  39962. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  39963. }else{
  39964. /* copy a maximum of nBuf chars to output buffer */
  39965. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  39966. /* free the UTF8 buffer */
  39967. sqlite3_free(zOut);
  39968. }
  39969. return 0;
  39970. }
  39971. /*
  39972. **
  39973. ** This function - winLogErrorAtLine() - is only ever called via the macro
  39974. ** winLogError().
  39975. **
  39976. ** This routine is invoked after an error occurs in an OS function.
  39977. ** It logs a message using sqlite3_log() containing the current value of
  39978. ** error code and, if possible, the human-readable equivalent from
  39979. ** FormatMessage.
  39980. **
  39981. ** The first argument passed to the macro should be the error code that
  39982. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  39983. ** The two subsequent arguments should be the name of the OS function that
  39984. ** failed and the associated file-system path, if any.
  39985. */
  39986. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  39987. static int winLogErrorAtLine(
  39988. int errcode, /* SQLite error code */
  39989. DWORD lastErrno, /* Win32 last error */
  39990. const char *zFunc, /* Name of OS function that failed */
  39991. const char *zPath, /* File path associated with error */
  39992. int iLine /* Source line number where error occurred */
  39993. ){
  39994. char zMsg[500]; /* Human readable error text */
  39995. int i; /* Loop counter */
  39996. zMsg[0] = 0;
  39997. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  39998. assert( errcode!=SQLITE_OK );
  39999. if( zPath==0 ) zPath = "";
  40000. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  40001. zMsg[i] = 0;
  40002. sqlite3_log(errcode,
  40003. "os_win.c:%d: (%lu) %s(%s) - %s",
  40004. iLine, lastErrno, zFunc, zPath, zMsg
  40005. );
  40006. return errcode;
  40007. }
  40008. /*
  40009. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  40010. ** will be retried following a locking error - probably caused by
  40011. ** antivirus software. Also the initial delay before the first retry.
  40012. ** The delay increases linearly with each retry.
  40013. */
  40014. #ifndef SQLITE_WIN32_IOERR_RETRY
  40015. # define SQLITE_WIN32_IOERR_RETRY 10
  40016. #endif
  40017. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  40018. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  40019. #endif
  40020. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  40021. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  40022. /*
  40023. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  40024. ** error code obtained via GetLastError() is eligible to be retried. It
  40025. ** must accept the error code DWORD as its only argument and should return
  40026. ** non-zero if the error code is transient in nature and the operation
  40027. ** responsible for generating the original error might succeed upon being
  40028. ** retried. The argument to this macro should be a variable.
  40029. **
  40030. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  40031. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  40032. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  40033. ** may be used to include additional error codes in the set that should
  40034. ** result in the failing I/O operation being retried by the caller. If
  40035. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  40036. ** identical to those of the "winIoerrCanRetry1" macro.
  40037. */
  40038. #if !defined(winIoerrCanRetry1)
  40039. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  40040. ((a)==ERROR_SHARING_VIOLATION) || \
  40041. ((a)==ERROR_LOCK_VIOLATION) || \
  40042. ((a)==ERROR_DEV_NOT_EXIST) || \
  40043. ((a)==ERROR_NETNAME_DELETED) || \
  40044. ((a)==ERROR_SEM_TIMEOUT) || \
  40045. ((a)==ERROR_NETWORK_UNREACHABLE))
  40046. #endif
  40047. /*
  40048. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  40049. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  40050. ** to give up with an error.
  40051. */
  40052. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  40053. DWORD e = osGetLastError();
  40054. if( *pnRetry>=winIoerrRetry ){
  40055. if( pError ){
  40056. *pError = e;
  40057. }
  40058. return 0;
  40059. }
  40060. if( winIoerrCanRetry1(e) ){
  40061. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  40062. ++*pnRetry;
  40063. return 1;
  40064. }
  40065. #if defined(winIoerrCanRetry2)
  40066. else if( winIoerrCanRetry2(e) ){
  40067. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  40068. ++*pnRetry;
  40069. return 1;
  40070. }
  40071. #endif
  40072. if( pError ){
  40073. *pError = e;
  40074. }
  40075. return 0;
  40076. }
  40077. /*
  40078. ** Log a I/O error retry episode.
  40079. */
  40080. static void winLogIoerr(int nRetry, int lineno){
  40081. if( nRetry ){
  40082. sqlite3_log(SQLITE_NOTICE,
  40083. "delayed %dms for lock/sharing conflict at line %d",
  40084. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  40085. );
  40086. }
  40087. }
  40088. /*
  40089. ** This #if does not rely on the SQLITE_OS_WINCE define because the
  40090. ** corresponding section in "date.c" cannot use it.
  40091. */
  40092. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  40093. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  40094. /*
  40095. ** The MSVC CRT on Windows CE may not have a localtime() function.
  40096. ** So define a substitute.
  40097. */
  40098. /* # include <time.h> */
  40099. struct tm *__cdecl localtime(const time_t *t)
  40100. {
  40101. static struct tm y;
  40102. FILETIME uTm, lTm;
  40103. SYSTEMTIME pTm;
  40104. sqlite3_int64 t64;
  40105. t64 = *t;
  40106. t64 = (t64 + 11644473600)*10000000;
  40107. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  40108. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  40109. osFileTimeToLocalFileTime(&uTm,&lTm);
  40110. osFileTimeToSystemTime(&lTm,&pTm);
  40111. y.tm_year = pTm.wYear - 1900;
  40112. y.tm_mon = pTm.wMonth - 1;
  40113. y.tm_wday = pTm.wDayOfWeek;
  40114. y.tm_mday = pTm.wDay;
  40115. y.tm_hour = pTm.wHour;
  40116. y.tm_min = pTm.wMinute;
  40117. y.tm_sec = pTm.wSecond;
  40118. return &y;
  40119. }
  40120. #endif
  40121. #if SQLITE_OS_WINCE
  40122. /*************************************************************************
  40123. ** This section contains code for WinCE only.
  40124. */
  40125. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  40126. /*
  40127. ** Acquire a lock on the handle h
  40128. */
  40129. static void winceMutexAcquire(HANDLE h){
  40130. DWORD dwErr;
  40131. do {
  40132. dwErr = osWaitForSingleObject(h, INFINITE);
  40133. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  40134. }
  40135. /*
  40136. ** Release a lock acquired by winceMutexAcquire()
  40137. */
  40138. #define winceMutexRelease(h) ReleaseMutex(h)
  40139. /*
  40140. ** Create the mutex and shared memory used for locking in the file
  40141. ** descriptor pFile
  40142. */
  40143. static int winceCreateLock(const char *zFilename, winFile *pFile){
  40144. LPWSTR zTok;
  40145. LPWSTR zName;
  40146. DWORD lastErrno;
  40147. BOOL bLogged = FALSE;
  40148. BOOL bInit = TRUE;
  40149. zName = winUtf8ToUnicode(zFilename);
  40150. if( zName==0 ){
  40151. /* out of memory */
  40152. return SQLITE_IOERR_NOMEM_BKPT;
  40153. }
  40154. /* Initialize the local lockdata */
  40155. memset(&pFile->local, 0, sizeof(pFile->local));
  40156. /* Replace the backslashes from the filename and lowercase it
  40157. ** to derive a mutex name. */
  40158. zTok = osCharLowerW(zName);
  40159. for (;*zTok;zTok++){
  40160. if (*zTok == '\\') *zTok = '_';
  40161. }
  40162. /* Create/open the named mutex */
  40163. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  40164. if (!pFile->hMutex){
  40165. pFile->lastErrno = osGetLastError();
  40166. sqlite3_free(zName);
  40167. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  40168. "winceCreateLock1", zFilename);
  40169. }
  40170. /* Acquire the mutex before continuing */
  40171. winceMutexAcquire(pFile->hMutex);
  40172. /* Since the names of named mutexes, semaphores, file mappings etc are
  40173. ** case-sensitive, take advantage of that by uppercasing the mutex name
  40174. ** and using that as the shared filemapping name.
  40175. */
  40176. osCharUpperW(zName);
  40177. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  40178. PAGE_READWRITE, 0, sizeof(winceLock),
  40179. zName);
  40180. /* Set a flag that indicates we're the first to create the memory so it
  40181. ** must be zero-initialized */
  40182. lastErrno = osGetLastError();
  40183. if (lastErrno == ERROR_ALREADY_EXISTS){
  40184. bInit = FALSE;
  40185. }
  40186. sqlite3_free(zName);
  40187. /* If we succeeded in making the shared memory handle, map it. */
  40188. if( pFile->hShared ){
  40189. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  40190. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  40191. /* If mapping failed, close the shared memory handle and erase it */
  40192. if( !pFile->shared ){
  40193. pFile->lastErrno = osGetLastError();
  40194. winLogError(SQLITE_IOERR, pFile->lastErrno,
  40195. "winceCreateLock2", zFilename);
  40196. bLogged = TRUE;
  40197. osCloseHandle(pFile->hShared);
  40198. pFile->hShared = NULL;
  40199. }
  40200. }
  40201. /* If shared memory could not be created, then close the mutex and fail */
  40202. if( pFile->hShared==NULL ){
  40203. if( !bLogged ){
  40204. pFile->lastErrno = lastErrno;
  40205. winLogError(SQLITE_IOERR, pFile->lastErrno,
  40206. "winceCreateLock3", zFilename);
  40207. bLogged = TRUE;
  40208. }
  40209. winceMutexRelease(pFile->hMutex);
  40210. osCloseHandle(pFile->hMutex);
  40211. pFile->hMutex = NULL;
  40212. return SQLITE_IOERR;
  40213. }
  40214. /* Initialize the shared memory if we're supposed to */
  40215. if( bInit ){
  40216. memset(pFile->shared, 0, sizeof(winceLock));
  40217. }
  40218. winceMutexRelease(pFile->hMutex);
  40219. return SQLITE_OK;
  40220. }
  40221. /*
  40222. ** Destroy the part of winFile that deals with wince locks
  40223. */
  40224. static void winceDestroyLock(winFile *pFile){
  40225. if (pFile->hMutex){
  40226. /* Acquire the mutex */
  40227. winceMutexAcquire(pFile->hMutex);
  40228. /* The following blocks should probably assert in debug mode, but they
  40229. are to cleanup in case any locks remained open */
  40230. if (pFile->local.nReaders){
  40231. pFile->shared->nReaders --;
  40232. }
  40233. if (pFile->local.bReserved){
  40234. pFile->shared->bReserved = FALSE;
  40235. }
  40236. if (pFile->local.bPending){
  40237. pFile->shared->bPending = FALSE;
  40238. }
  40239. if (pFile->local.bExclusive){
  40240. pFile->shared->bExclusive = FALSE;
  40241. }
  40242. /* De-reference and close our copy of the shared memory handle */
  40243. osUnmapViewOfFile(pFile->shared);
  40244. osCloseHandle(pFile->hShared);
  40245. /* Done with the mutex */
  40246. winceMutexRelease(pFile->hMutex);
  40247. osCloseHandle(pFile->hMutex);
  40248. pFile->hMutex = NULL;
  40249. }
  40250. }
  40251. /*
  40252. ** An implementation of the LockFile() API of Windows for CE
  40253. */
  40254. static BOOL winceLockFile(
  40255. LPHANDLE phFile,
  40256. DWORD dwFileOffsetLow,
  40257. DWORD dwFileOffsetHigh,
  40258. DWORD nNumberOfBytesToLockLow,
  40259. DWORD nNumberOfBytesToLockHigh
  40260. ){
  40261. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  40262. BOOL bReturn = FALSE;
  40263. UNUSED_PARAMETER(dwFileOffsetHigh);
  40264. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  40265. if (!pFile->hMutex) return TRUE;
  40266. winceMutexAcquire(pFile->hMutex);
  40267. /* Wanting an exclusive lock? */
  40268. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  40269. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  40270. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  40271. pFile->shared->bExclusive = TRUE;
  40272. pFile->local.bExclusive = TRUE;
  40273. bReturn = TRUE;
  40274. }
  40275. }
  40276. /* Want a read-only lock? */
  40277. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  40278. nNumberOfBytesToLockLow == 1){
  40279. if (pFile->shared->bExclusive == 0){
  40280. pFile->local.nReaders ++;
  40281. if (pFile->local.nReaders == 1){
  40282. pFile->shared->nReaders ++;
  40283. }
  40284. bReturn = TRUE;
  40285. }
  40286. }
  40287. /* Want a pending lock? */
  40288. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  40289. && nNumberOfBytesToLockLow == 1){
  40290. /* If no pending lock has been acquired, then acquire it */
  40291. if (pFile->shared->bPending == 0) {
  40292. pFile->shared->bPending = TRUE;
  40293. pFile->local.bPending = TRUE;
  40294. bReturn = TRUE;
  40295. }
  40296. }
  40297. /* Want a reserved lock? */
  40298. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  40299. && nNumberOfBytesToLockLow == 1){
  40300. if (pFile->shared->bReserved == 0) {
  40301. pFile->shared->bReserved = TRUE;
  40302. pFile->local.bReserved = TRUE;
  40303. bReturn = TRUE;
  40304. }
  40305. }
  40306. winceMutexRelease(pFile->hMutex);
  40307. return bReturn;
  40308. }
  40309. /*
  40310. ** An implementation of the UnlockFile API of Windows for CE
  40311. */
  40312. static BOOL winceUnlockFile(
  40313. LPHANDLE phFile,
  40314. DWORD dwFileOffsetLow,
  40315. DWORD dwFileOffsetHigh,
  40316. DWORD nNumberOfBytesToUnlockLow,
  40317. DWORD nNumberOfBytesToUnlockHigh
  40318. ){
  40319. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  40320. BOOL bReturn = FALSE;
  40321. UNUSED_PARAMETER(dwFileOffsetHigh);
  40322. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  40323. if (!pFile->hMutex) return TRUE;
  40324. winceMutexAcquire(pFile->hMutex);
  40325. /* Releasing a reader lock or an exclusive lock */
  40326. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  40327. /* Did we have an exclusive lock? */
  40328. if (pFile->local.bExclusive){
  40329. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  40330. pFile->local.bExclusive = FALSE;
  40331. pFile->shared->bExclusive = FALSE;
  40332. bReturn = TRUE;
  40333. }
  40334. /* Did we just have a reader lock? */
  40335. else if (pFile->local.nReaders){
  40336. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  40337. || nNumberOfBytesToUnlockLow == 1);
  40338. pFile->local.nReaders --;
  40339. if (pFile->local.nReaders == 0)
  40340. {
  40341. pFile->shared->nReaders --;
  40342. }
  40343. bReturn = TRUE;
  40344. }
  40345. }
  40346. /* Releasing a pending lock */
  40347. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  40348. && nNumberOfBytesToUnlockLow == 1){
  40349. if (pFile->local.bPending){
  40350. pFile->local.bPending = FALSE;
  40351. pFile->shared->bPending = FALSE;
  40352. bReturn = TRUE;
  40353. }
  40354. }
  40355. /* Releasing a reserved lock */
  40356. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  40357. && nNumberOfBytesToUnlockLow == 1){
  40358. if (pFile->local.bReserved) {
  40359. pFile->local.bReserved = FALSE;
  40360. pFile->shared->bReserved = FALSE;
  40361. bReturn = TRUE;
  40362. }
  40363. }
  40364. winceMutexRelease(pFile->hMutex);
  40365. return bReturn;
  40366. }
  40367. /*
  40368. ** End of the special code for wince
  40369. *****************************************************************************/
  40370. #endif /* SQLITE_OS_WINCE */
  40371. /*
  40372. ** Lock a file region.
  40373. */
  40374. static BOOL winLockFile(
  40375. LPHANDLE phFile,
  40376. DWORD flags,
  40377. DWORD offsetLow,
  40378. DWORD offsetHigh,
  40379. DWORD numBytesLow,
  40380. DWORD numBytesHigh
  40381. ){
  40382. #if SQLITE_OS_WINCE
  40383. /*
  40384. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  40385. ** API LockFile.
  40386. */
  40387. return winceLockFile(phFile, offsetLow, offsetHigh,
  40388. numBytesLow, numBytesHigh);
  40389. #else
  40390. if( osIsNT() ){
  40391. OVERLAPPED ovlp;
  40392. memset(&ovlp, 0, sizeof(OVERLAPPED));
  40393. ovlp.Offset = offsetLow;
  40394. ovlp.OffsetHigh = offsetHigh;
  40395. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  40396. }else{
  40397. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  40398. numBytesHigh);
  40399. }
  40400. #endif
  40401. }
  40402. /*
  40403. ** Unlock a file region.
  40404. */
  40405. static BOOL winUnlockFile(
  40406. LPHANDLE phFile,
  40407. DWORD offsetLow,
  40408. DWORD offsetHigh,
  40409. DWORD numBytesLow,
  40410. DWORD numBytesHigh
  40411. ){
  40412. #if SQLITE_OS_WINCE
  40413. /*
  40414. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  40415. ** API UnlockFile.
  40416. */
  40417. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  40418. numBytesLow, numBytesHigh);
  40419. #else
  40420. if( osIsNT() ){
  40421. OVERLAPPED ovlp;
  40422. memset(&ovlp, 0, sizeof(OVERLAPPED));
  40423. ovlp.Offset = offsetLow;
  40424. ovlp.OffsetHigh = offsetHigh;
  40425. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  40426. }else{
  40427. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  40428. numBytesHigh);
  40429. }
  40430. #endif
  40431. }
  40432. /*****************************************************************************
  40433. ** The next group of routines implement the I/O methods specified
  40434. ** by the sqlite3_io_methods object.
  40435. ******************************************************************************/
  40436. /*
  40437. ** Some Microsoft compilers lack this definition.
  40438. */
  40439. #ifndef INVALID_SET_FILE_POINTER
  40440. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  40441. #endif
  40442. /*
  40443. ** Move the current position of the file handle passed as the first
  40444. ** argument to offset iOffset within the file. If successful, return 0.
  40445. ** Otherwise, set pFile->lastErrno and return non-zero.
  40446. */
  40447. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  40448. #if !SQLITE_OS_WINRT
  40449. LONG upperBits; /* Most sig. 32 bits of new offset */
  40450. LONG lowerBits; /* Least sig. 32 bits of new offset */
  40451. DWORD dwRet; /* Value returned by SetFilePointer() */
  40452. DWORD lastErrno; /* Value returned by GetLastError() */
  40453. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  40454. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  40455. lowerBits = (LONG)(iOffset & 0xffffffff);
  40456. /* API oddity: If successful, SetFilePointer() returns a dword
  40457. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  40458. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  40459. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  40460. ** whether an error has actually occurred, it is also necessary to call
  40461. ** GetLastError().
  40462. */
  40463. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  40464. if( (dwRet==INVALID_SET_FILE_POINTER
  40465. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  40466. pFile->lastErrno = lastErrno;
  40467. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  40468. "winSeekFile", pFile->zPath);
  40469. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  40470. return 1;
  40471. }
  40472. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  40473. return 0;
  40474. #else
  40475. /*
  40476. ** Same as above, except that this implementation works for WinRT.
  40477. */
  40478. LARGE_INTEGER x; /* The new offset */
  40479. BOOL bRet; /* Value returned by SetFilePointerEx() */
  40480. x.QuadPart = iOffset;
  40481. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  40482. if(!bRet){
  40483. pFile->lastErrno = osGetLastError();
  40484. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  40485. "winSeekFile", pFile->zPath);
  40486. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  40487. return 1;
  40488. }
  40489. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  40490. return 0;
  40491. #endif
  40492. }
  40493. #if SQLITE_MAX_MMAP_SIZE>0
  40494. /* Forward references to VFS helper methods used for memory mapped files */
  40495. static int winMapfile(winFile*, sqlite3_int64);
  40496. static int winUnmapfile(winFile*);
  40497. #endif
  40498. /*
  40499. ** Close a file.
  40500. **
  40501. ** It is reported that an attempt to close a handle might sometimes
  40502. ** fail. This is a very unreasonable result, but Windows is notorious
  40503. ** for being unreasonable so I do not doubt that it might happen. If
  40504. ** the close fails, we pause for 100 milliseconds and try again. As
  40505. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  40506. ** giving up and returning an error.
  40507. */
  40508. #define MX_CLOSE_ATTEMPT 3
  40509. static int winClose(sqlite3_file *id){
  40510. int rc, cnt = 0;
  40511. winFile *pFile = (winFile*)id;
  40512. assert( id!=0 );
  40513. #ifndef SQLITE_OMIT_WAL
  40514. assert( pFile->pShm==0 );
  40515. #endif
  40516. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  40517. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  40518. osGetCurrentProcessId(), pFile, pFile->h));
  40519. #if SQLITE_MAX_MMAP_SIZE>0
  40520. winUnmapfile(pFile);
  40521. #endif
  40522. do{
  40523. rc = osCloseHandle(pFile->h);
  40524. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  40525. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  40526. #if SQLITE_OS_WINCE
  40527. #define WINCE_DELETION_ATTEMPTS 3
  40528. {
  40529. winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
  40530. if( pAppData==NULL || !pAppData->bNoLock ){
  40531. winceDestroyLock(pFile);
  40532. }
  40533. }
  40534. if( pFile->zDeleteOnClose ){
  40535. int cnt = 0;
  40536. while(
  40537. osDeleteFileW(pFile->zDeleteOnClose)==0
  40538. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  40539. && cnt++ < WINCE_DELETION_ATTEMPTS
  40540. ){
  40541. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  40542. }
  40543. sqlite3_free(pFile->zDeleteOnClose);
  40544. }
  40545. #endif
  40546. if( rc ){
  40547. pFile->h = NULL;
  40548. }
  40549. OpenCounter(-1);
  40550. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  40551. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  40552. return rc ? SQLITE_OK
  40553. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  40554. "winClose", pFile->zPath);
  40555. }
  40556. /*
  40557. ** Read data from a file into a buffer. Return SQLITE_OK if all
  40558. ** bytes were read successfully and SQLITE_IOERR if anything goes
  40559. ** wrong.
  40560. */
  40561. static int winRead(
  40562. sqlite3_file *id, /* File to read from */
  40563. void *pBuf, /* Write content into this buffer */
  40564. int amt, /* Number of bytes to read */
  40565. sqlite3_int64 offset /* Begin reading at this offset */
  40566. ){
  40567. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40568. OVERLAPPED overlapped; /* The offset for ReadFile. */
  40569. #endif
  40570. winFile *pFile = (winFile*)id; /* file handle */
  40571. DWORD nRead; /* Number of bytes actually read from file */
  40572. int nRetry = 0; /* Number of retrys */
  40573. assert( id!=0 );
  40574. assert( amt>0 );
  40575. assert( offset>=0 );
  40576. SimulateIOError(return SQLITE_IOERR_READ);
  40577. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  40578. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  40579. pFile->h, pBuf, amt, offset, pFile->locktype));
  40580. #if SQLITE_MAX_MMAP_SIZE>0
  40581. /* Deal with as much of this read request as possible by transfering
  40582. ** data from the memory mapping using memcpy(). */
  40583. if( offset<pFile->mmapSize ){
  40584. if( offset+amt <= pFile->mmapSize ){
  40585. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  40586. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40587. osGetCurrentProcessId(), pFile, pFile->h));
  40588. return SQLITE_OK;
  40589. }else{
  40590. int nCopy = (int)(pFile->mmapSize - offset);
  40591. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  40592. pBuf = &((u8 *)pBuf)[nCopy];
  40593. amt -= nCopy;
  40594. offset += nCopy;
  40595. }
  40596. }
  40597. #endif
  40598. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  40599. if( winSeekFile(pFile, offset) ){
  40600. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  40601. osGetCurrentProcessId(), pFile, pFile->h));
  40602. return SQLITE_FULL;
  40603. }
  40604. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  40605. #else
  40606. memset(&overlapped, 0, sizeof(OVERLAPPED));
  40607. overlapped.Offset = (LONG)(offset & 0xffffffff);
  40608. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  40609. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  40610. osGetLastError()!=ERROR_HANDLE_EOF ){
  40611. #endif
  40612. DWORD lastErrno;
  40613. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  40614. pFile->lastErrno = lastErrno;
  40615. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  40616. osGetCurrentProcessId(), pFile, pFile->h));
  40617. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  40618. "winRead", pFile->zPath);
  40619. }
  40620. winLogIoerr(nRetry, __LINE__);
  40621. if( nRead<(DWORD)amt ){
  40622. /* Unread parts of the buffer must be zero-filled */
  40623. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  40624. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  40625. osGetCurrentProcessId(), pFile, pFile->h));
  40626. return SQLITE_IOERR_SHORT_READ;
  40627. }
  40628. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40629. osGetCurrentProcessId(), pFile, pFile->h));
  40630. return SQLITE_OK;
  40631. }
  40632. /*
  40633. ** Write data from a buffer into a file. Return SQLITE_OK on success
  40634. ** or some other error code on failure.
  40635. */
  40636. static int winWrite(
  40637. sqlite3_file *id, /* File to write into */
  40638. const void *pBuf, /* The bytes to be written */
  40639. int amt, /* Number of bytes to write */
  40640. sqlite3_int64 offset /* Offset into the file to begin writing at */
  40641. ){
  40642. int rc = 0; /* True if error has occurred, else false */
  40643. winFile *pFile = (winFile*)id; /* File handle */
  40644. int nRetry = 0; /* Number of retries */
  40645. assert( amt>0 );
  40646. assert( pFile );
  40647. SimulateIOError(return SQLITE_IOERR_WRITE);
  40648. SimulateDiskfullError(return SQLITE_FULL);
  40649. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  40650. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  40651. pFile->h, pBuf, amt, offset, pFile->locktype));
  40652. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  40653. /* Deal with as much of this write request as possible by transfering
  40654. ** data from the memory mapping using memcpy(). */
  40655. if( offset<pFile->mmapSize ){
  40656. if( offset+amt <= pFile->mmapSize ){
  40657. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  40658. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40659. osGetCurrentProcessId(), pFile, pFile->h));
  40660. return SQLITE_OK;
  40661. }else{
  40662. int nCopy = (int)(pFile->mmapSize - offset);
  40663. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  40664. pBuf = &((u8 *)pBuf)[nCopy];
  40665. amt -= nCopy;
  40666. offset += nCopy;
  40667. }
  40668. }
  40669. #endif
  40670. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  40671. rc = winSeekFile(pFile, offset);
  40672. if( rc==0 ){
  40673. #else
  40674. {
  40675. #endif
  40676. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40677. OVERLAPPED overlapped; /* The offset for WriteFile. */
  40678. #endif
  40679. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  40680. int nRem = amt; /* Number of bytes yet to be written */
  40681. DWORD nWrite; /* Bytes written by each WriteFile() call */
  40682. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  40683. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40684. memset(&overlapped, 0, sizeof(OVERLAPPED));
  40685. overlapped.Offset = (LONG)(offset & 0xffffffff);
  40686. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  40687. #endif
  40688. while( nRem>0 ){
  40689. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  40690. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  40691. #else
  40692. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  40693. #endif
  40694. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  40695. break;
  40696. }
  40697. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  40698. if( nWrite==0 || nWrite>(DWORD)nRem ){
  40699. lastErrno = osGetLastError();
  40700. break;
  40701. }
  40702. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40703. offset += nWrite;
  40704. overlapped.Offset = (LONG)(offset & 0xffffffff);
  40705. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  40706. #endif
  40707. aRem += nWrite;
  40708. nRem -= nWrite;
  40709. }
  40710. if( nRem>0 ){
  40711. pFile->lastErrno = lastErrno;
  40712. rc = 1;
  40713. }
  40714. }
  40715. if( rc ){
  40716. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  40717. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  40718. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  40719. osGetCurrentProcessId(), pFile, pFile->h));
  40720. return winLogError(SQLITE_FULL, pFile->lastErrno,
  40721. "winWrite1", pFile->zPath);
  40722. }
  40723. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  40724. osGetCurrentProcessId(), pFile, pFile->h));
  40725. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  40726. "winWrite2", pFile->zPath);
  40727. }else{
  40728. winLogIoerr(nRetry, __LINE__);
  40729. }
  40730. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40731. osGetCurrentProcessId(), pFile, pFile->h));
  40732. return SQLITE_OK;
  40733. }
  40734. /*
  40735. ** Truncate an open file to a specified size
  40736. */
  40737. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  40738. winFile *pFile = (winFile*)id; /* File handle object */
  40739. int rc = SQLITE_OK; /* Return code for this function */
  40740. DWORD lastErrno;
  40741. #if SQLITE_MAX_MMAP_SIZE>0
  40742. sqlite3_int64 oldMmapSize;
  40743. if( pFile->nFetchOut>0 ){
  40744. /* File truncation is a no-op if there are outstanding memory mapped
  40745. ** pages. This is because truncating the file means temporarily unmapping
  40746. ** the file, and that might delete memory out from under existing cursors.
  40747. **
  40748. ** This can result in incremental vacuum not truncating the file,
  40749. ** if there is an active read cursor when the incremental vacuum occurs.
  40750. ** No real harm comes of this - the database file is not corrupted,
  40751. ** though some folks might complain that the file is bigger than it
  40752. ** needs to be.
  40753. **
  40754. ** The only feasible work-around is to defer the truncation until after
  40755. ** all references to memory-mapped content are closed. That is doable,
  40756. ** but involves adding a few branches in the common write code path which
  40757. ** could slow down normal operations slightly. Hence, we have decided for
  40758. ** now to simply make trancations a no-op if there are pending reads. We
  40759. ** can maybe revisit this decision in the future.
  40760. */
  40761. return SQLITE_OK;
  40762. }
  40763. #endif
  40764. assert( pFile );
  40765. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  40766. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  40767. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  40768. /* If the user has configured a chunk-size for this file, truncate the
  40769. ** file so that it consists of an integer number of chunks (i.e. the
  40770. ** actual file size after the operation may be larger than the requested
  40771. ** size).
  40772. */
  40773. if( pFile->szChunk>0 ){
  40774. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  40775. }
  40776. #if SQLITE_MAX_MMAP_SIZE>0
  40777. if( pFile->pMapRegion ){
  40778. oldMmapSize = pFile->mmapSize;
  40779. }else{
  40780. oldMmapSize = 0;
  40781. }
  40782. winUnmapfile(pFile);
  40783. #endif
  40784. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  40785. if( winSeekFile(pFile, nByte) ){
  40786. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  40787. "winTruncate1", pFile->zPath);
  40788. }else if( 0==osSetEndOfFile(pFile->h) &&
  40789. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  40790. pFile->lastErrno = lastErrno;
  40791. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  40792. "winTruncate2", pFile->zPath);
  40793. }
  40794. #if SQLITE_MAX_MMAP_SIZE>0
  40795. if( rc==SQLITE_OK && oldMmapSize>0 ){
  40796. if( oldMmapSize>nByte ){
  40797. winMapfile(pFile, -1);
  40798. }else{
  40799. winMapfile(pFile, oldMmapSize);
  40800. }
  40801. }
  40802. #endif
  40803. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  40804. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  40805. return rc;
  40806. }
  40807. #ifdef SQLITE_TEST
  40808. /*
  40809. ** Count the number of fullsyncs and normal syncs. This is used to test
  40810. ** that syncs and fullsyncs are occuring at the right times.
  40811. */
  40812. SQLITE_API int sqlite3_sync_count = 0;
  40813. SQLITE_API int sqlite3_fullsync_count = 0;
  40814. #endif
  40815. /*
  40816. ** Make sure all writes to a particular file are committed to disk.
  40817. */
  40818. static int winSync(sqlite3_file *id, int flags){
  40819. #ifndef SQLITE_NO_SYNC
  40820. /*
  40821. ** Used only when SQLITE_NO_SYNC is not defined.
  40822. */
  40823. BOOL rc;
  40824. #endif
  40825. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  40826. defined(SQLITE_HAVE_OS_TRACE)
  40827. /*
  40828. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  40829. ** OSTRACE() macros.
  40830. */
  40831. winFile *pFile = (winFile*)id;
  40832. #else
  40833. UNUSED_PARAMETER(id);
  40834. #endif
  40835. assert( pFile );
  40836. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  40837. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  40838. || (flags&0x0F)==SQLITE_SYNC_FULL
  40839. );
  40840. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  40841. ** line is to test that doing so does not cause any problems.
  40842. */
  40843. SimulateDiskfullError( return SQLITE_FULL );
  40844. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  40845. osGetCurrentProcessId(), pFile, pFile->h, flags,
  40846. pFile->locktype));
  40847. #ifndef SQLITE_TEST
  40848. UNUSED_PARAMETER(flags);
  40849. #else
  40850. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  40851. sqlite3_fullsync_count++;
  40852. }
  40853. sqlite3_sync_count++;
  40854. #endif
  40855. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  40856. ** no-op
  40857. */
  40858. #ifdef SQLITE_NO_SYNC
  40859. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40860. osGetCurrentProcessId(), pFile, pFile->h));
  40861. return SQLITE_OK;
  40862. #else
  40863. #if SQLITE_MAX_MMAP_SIZE>0
  40864. if( pFile->pMapRegion ){
  40865. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  40866. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  40867. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  40868. pFile, pFile->pMapRegion));
  40869. }else{
  40870. pFile->lastErrno = osGetLastError();
  40871. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  40872. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  40873. pFile, pFile->pMapRegion));
  40874. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  40875. "winSync1", pFile->zPath);
  40876. }
  40877. }
  40878. #endif
  40879. rc = osFlushFileBuffers(pFile->h);
  40880. SimulateIOError( rc=FALSE );
  40881. if( rc ){
  40882. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40883. osGetCurrentProcessId(), pFile, pFile->h));
  40884. return SQLITE_OK;
  40885. }else{
  40886. pFile->lastErrno = osGetLastError();
  40887. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  40888. osGetCurrentProcessId(), pFile, pFile->h));
  40889. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  40890. "winSync2", pFile->zPath);
  40891. }
  40892. #endif
  40893. }
  40894. /*
  40895. ** Determine the current size of a file in bytes
  40896. */
  40897. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  40898. winFile *pFile = (winFile*)id;
  40899. int rc = SQLITE_OK;
  40900. assert( id!=0 );
  40901. assert( pSize!=0 );
  40902. SimulateIOError(return SQLITE_IOERR_FSTAT);
  40903. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  40904. #if SQLITE_OS_WINRT
  40905. {
  40906. FILE_STANDARD_INFO info;
  40907. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  40908. &info, sizeof(info)) ){
  40909. *pSize = info.EndOfFile.QuadPart;
  40910. }else{
  40911. pFile->lastErrno = osGetLastError();
  40912. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  40913. "winFileSize", pFile->zPath);
  40914. }
  40915. }
  40916. #else
  40917. {
  40918. DWORD upperBits;
  40919. DWORD lowerBits;
  40920. DWORD lastErrno;
  40921. lowerBits = osGetFileSize(pFile->h, &upperBits);
  40922. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  40923. if( (lowerBits == INVALID_FILE_SIZE)
  40924. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  40925. pFile->lastErrno = lastErrno;
  40926. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  40927. "winFileSize", pFile->zPath);
  40928. }
  40929. }
  40930. #endif
  40931. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  40932. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  40933. return rc;
  40934. }
  40935. /*
  40936. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  40937. */
  40938. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  40939. # define LOCKFILE_FAIL_IMMEDIATELY 1
  40940. #endif
  40941. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  40942. # define LOCKFILE_EXCLUSIVE_LOCK 2
  40943. #endif
  40944. /*
  40945. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  40946. ** When the LockFile function was used, it was always expected to fail
  40947. ** immediately if the lock could not be obtained. Also, it always expected to
  40948. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  40949. ** and reflect those expectations; therefore, they should not be changed.
  40950. */
  40951. #ifndef SQLITE_LOCKFILE_FLAGS
  40952. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  40953. LOCKFILE_EXCLUSIVE_LOCK)
  40954. #endif
  40955. /*
  40956. ** Currently, SQLite never calls the LockFileEx function without wanting the
  40957. ** call to fail immediately if the lock cannot be obtained.
  40958. */
  40959. #ifndef SQLITE_LOCKFILEEX_FLAGS
  40960. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  40961. #endif
  40962. /*
  40963. ** Acquire a reader lock.
  40964. ** Different API routines are called depending on whether or not this
  40965. ** is Win9x or WinNT.
  40966. */
  40967. static int winGetReadLock(winFile *pFile){
  40968. int res;
  40969. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  40970. if( osIsNT() ){
  40971. #if SQLITE_OS_WINCE
  40972. /*
  40973. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  40974. ** API LockFileEx.
  40975. */
  40976. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  40977. #else
  40978. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  40979. SHARED_SIZE, 0);
  40980. #endif
  40981. }
  40982. #ifdef SQLITE_WIN32_HAS_ANSI
  40983. else{
  40984. int lk;
  40985. sqlite3_randomness(sizeof(lk), &lk);
  40986. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  40987. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  40988. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  40989. }
  40990. #endif
  40991. if( res == 0 ){
  40992. pFile->lastErrno = osGetLastError();
  40993. /* No need to log a failure to lock */
  40994. }
  40995. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  40996. return res;
  40997. }
  40998. /*
  40999. ** Undo a readlock
  41000. */
  41001. static int winUnlockReadLock(winFile *pFile){
  41002. int res;
  41003. DWORD lastErrno;
  41004. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  41005. if( osIsNT() ){
  41006. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  41007. }
  41008. #ifdef SQLITE_WIN32_HAS_ANSI
  41009. else{
  41010. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  41011. }
  41012. #endif
  41013. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  41014. pFile->lastErrno = lastErrno;
  41015. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  41016. "winUnlockReadLock", pFile->zPath);
  41017. }
  41018. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  41019. return res;
  41020. }
  41021. /*
  41022. ** Lock the file with the lock specified by parameter locktype - one
  41023. ** of the following:
  41024. **
  41025. ** (1) SHARED_LOCK
  41026. ** (2) RESERVED_LOCK
  41027. ** (3) PENDING_LOCK
  41028. ** (4) EXCLUSIVE_LOCK
  41029. **
  41030. ** Sometimes when requesting one lock state, additional lock states
  41031. ** are inserted in between. The locking might fail on one of the later
  41032. ** transitions leaving the lock state different from what it started but
  41033. ** still short of its goal. The following chart shows the allowed
  41034. ** transitions and the inserted intermediate states:
  41035. **
  41036. ** UNLOCKED -> SHARED
  41037. ** SHARED -> RESERVED
  41038. ** SHARED -> (PENDING) -> EXCLUSIVE
  41039. ** RESERVED -> (PENDING) -> EXCLUSIVE
  41040. ** PENDING -> EXCLUSIVE
  41041. **
  41042. ** This routine will only increase a lock. The winUnlock() routine
  41043. ** erases all locks at once and returns us immediately to locking level 0.
  41044. ** It is not possible to lower the locking level one step at a time. You
  41045. ** must go straight to locking level 0.
  41046. */
  41047. static int winLock(sqlite3_file *id, int locktype){
  41048. int rc = SQLITE_OK; /* Return code from subroutines */
  41049. int res = 1; /* Result of a Windows lock call */
  41050. int newLocktype; /* Set pFile->locktype to this value before exiting */
  41051. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  41052. winFile *pFile = (winFile*)id;
  41053. DWORD lastErrno = NO_ERROR;
  41054. assert( id!=0 );
  41055. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  41056. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  41057. /* If there is already a lock of this type or more restrictive on the
  41058. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  41059. ** sqlite3OsEnterMutex() hasn't been called yet.
  41060. */
  41061. if( pFile->locktype>=locktype ){
  41062. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  41063. return SQLITE_OK;
  41064. }
  41065. /* Do not allow any kind of write-lock on a read-only database
  41066. */
  41067. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  41068. return SQLITE_IOERR_LOCK;
  41069. }
  41070. /* Make sure the locking sequence is correct
  41071. */
  41072. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  41073. assert( locktype!=PENDING_LOCK );
  41074. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  41075. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  41076. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  41077. ** the PENDING_LOCK byte is temporary.
  41078. */
  41079. newLocktype = pFile->locktype;
  41080. if( pFile->locktype==NO_LOCK
  41081. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
  41082. ){
  41083. int cnt = 3;
  41084. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  41085. PENDING_BYTE, 0, 1, 0))==0 ){
  41086. /* Try 3 times to get the pending lock. This is needed to work
  41087. ** around problems caused by indexing and/or anti-virus software on
  41088. ** Windows systems.
  41089. ** If you are using this code as a model for alternative VFSes, do not
  41090. ** copy this retry logic. It is a hack intended for Windows only.
  41091. */
  41092. lastErrno = osGetLastError();
  41093. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  41094. pFile->h, cnt, res));
  41095. if( lastErrno==ERROR_INVALID_HANDLE ){
  41096. pFile->lastErrno = lastErrno;
  41097. rc = SQLITE_IOERR_LOCK;
  41098. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  41099. pFile->h, cnt, sqlite3ErrName(rc)));
  41100. return rc;
  41101. }
  41102. if( cnt ) sqlite3_win32_sleep(1);
  41103. }
  41104. gotPendingLock = res;
  41105. if( !res ){
  41106. lastErrno = osGetLastError();
  41107. }
  41108. }
  41109. /* Acquire a shared lock
  41110. */
  41111. if( locktype==SHARED_LOCK && res ){
  41112. assert( pFile->locktype==NO_LOCK );
  41113. res = winGetReadLock(pFile);
  41114. if( res ){
  41115. newLocktype = SHARED_LOCK;
  41116. }else{
  41117. lastErrno = osGetLastError();
  41118. }
  41119. }
  41120. /* Acquire a RESERVED lock
  41121. */
  41122. if( locktype==RESERVED_LOCK && res ){
  41123. assert( pFile->locktype==SHARED_LOCK );
  41124. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  41125. if( res ){
  41126. newLocktype = RESERVED_LOCK;
  41127. }else{
  41128. lastErrno = osGetLastError();
  41129. }
  41130. }
  41131. /* Acquire a PENDING lock
  41132. */
  41133. if( locktype==EXCLUSIVE_LOCK && res ){
  41134. newLocktype = PENDING_LOCK;
  41135. gotPendingLock = 0;
  41136. }
  41137. /* Acquire an EXCLUSIVE lock
  41138. */
  41139. if( locktype==EXCLUSIVE_LOCK && res ){
  41140. assert( pFile->locktype>=SHARED_LOCK );
  41141. res = winUnlockReadLock(pFile);
  41142. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  41143. SHARED_SIZE, 0);
  41144. if( res ){
  41145. newLocktype = EXCLUSIVE_LOCK;
  41146. }else{
  41147. lastErrno = osGetLastError();
  41148. winGetReadLock(pFile);
  41149. }
  41150. }
  41151. /* If we are holding a PENDING lock that ought to be released, then
  41152. ** release it now.
  41153. */
  41154. if( gotPendingLock && locktype==SHARED_LOCK ){
  41155. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  41156. }
  41157. /* Update the state of the lock has held in the file descriptor then
  41158. ** return the appropriate result code.
  41159. */
  41160. if( res ){
  41161. rc = SQLITE_OK;
  41162. }else{
  41163. pFile->lastErrno = lastErrno;
  41164. rc = SQLITE_BUSY;
  41165. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  41166. pFile->h, locktype, newLocktype));
  41167. }
  41168. pFile->locktype = (u8)newLocktype;
  41169. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  41170. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  41171. return rc;
  41172. }
  41173. /*
  41174. ** This routine checks if there is a RESERVED lock held on the specified
  41175. ** file by this or any other process. If such a lock is held, return
  41176. ** non-zero, otherwise zero.
  41177. */
  41178. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  41179. int res;
  41180. winFile *pFile = (winFile*)id;
  41181. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  41182. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  41183. assert( id!=0 );
  41184. if( pFile->locktype>=RESERVED_LOCK ){
  41185. res = 1;
  41186. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  41187. }else{
  41188. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
  41189. if( res ){
  41190. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  41191. }
  41192. res = !res;
  41193. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  41194. }
  41195. *pResOut = res;
  41196. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  41197. pFile->h, pResOut, *pResOut));
  41198. return SQLITE_OK;
  41199. }
  41200. /*
  41201. ** Lower the locking level on file descriptor id to locktype. locktype
  41202. ** must be either NO_LOCK or SHARED_LOCK.
  41203. **
  41204. ** If the locking level of the file descriptor is already at or below
  41205. ** the requested locking level, this routine is a no-op.
  41206. **
  41207. ** It is not possible for this routine to fail if the second argument
  41208. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  41209. ** might return SQLITE_IOERR;
  41210. */
  41211. static int winUnlock(sqlite3_file *id, int locktype){
  41212. int type;
  41213. winFile *pFile = (winFile*)id;
  41214. int rc = SQLITE_OK;
  41215. assert( pFile!=0 );
  41216. assert( locktype<=SHARED_LOCK );
  41217. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  41218. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  41219. type = pFile->locktype;
  41220. if( type>=EXCLUSIVE_LOCK ){
  41221. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  41222. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  41223. /* This should never happen. We should always be able to
  41224. ** reacquire the read lock */
  41225. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  41226. "winUnlock", pFile->zPath);
  41227. }
  41228. }
  41229. if( type>=RESERVED_LOCK ){
  41230. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  41231. }
  41232. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  41233. winUnlockReadLock(pFile);
  41234. }
  41235. if( type>=PENDING_LOCK ){
  41236. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  41237. }
  41238. pFile->locktype = (u8)locktype;
  41239. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  41240. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  41241. return rc;
  41242. }
  41243. /******************************************************************************
  41244. ****************************** No-op Locking **********************************
  41245. **
  41246. ** Of the various locking implementations available, this is by far the
  41247. ** simplest: locking is ignored. No attempt is made to lock the database
  41248. ** file for reading or writing.
  41249. **
  41250. ** This locking mode is appropriate for use on read-only databases
  41251. ** (ex: databases that are burned into CD-ROM, for example.) It can
  41252. ** also be used if the application employs some external mechanism to
  41253. ** prevent simultaneous access of the same database by two or more
  41254. ** database connections. But there is a serious risk of database
  41255. ** corruption if this locking mode is used in situations where multiple
  41256. ** database connections are accessing the same database file at the same
  41257. ** time and one or more of those connections are writing.
  41258. */
  41259. static int winNolockLock(sqlite3_file *id, int locktype){
  41260. UNUSED_PARAMETER(id);
  41261. UNUSED_PARAMETER(locktype);
  41262. return SQLITE_OK;
  41263. }
  41264. static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
  41265. UNUSED_PARAMETER(id);
  41266. UNUSED_PARAMETER(pResOut);
  41267. return SQLITE_OK;
  41268. }
  41269. static int winNolockUnlock(sqlite3_file *id, int locktype){
  41270. UNUSED_PARAMETER(id);
  41271. UNUSED_PARAMETER(locktype);
  41272. return SQLITE_OK;
  41273. }
  41274. /******************* End of the no-op lock implementation *********************
  41275. ******************************************************************************/
  41276. /*
  41277. ** If *pArg is initially negative then this is a query. Set *pArg to
  41278. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  41279. **
  41280. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  41281. */
  41282. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  41283. if( *pArg<0 ){
  41284. *pArg = (pFile->ctrlFlags & mask)!=0;
  41285. }else if( (*pArg)==0 ){
  41286. pFile->ctrlFlags &= ~mask;
  41287. }else{
  41288. pFile->ctrlFlags |= mask;
  41289. }
  41290. }
  41291. /* Forward references to VFS helper methods used for temporary files */
  41292. static int winGetTempname(sqlite3_vfs *, char **);
  41293. static int winIsDir(const void *);
  41294. static BOOL winIsDriveLetterAndColon(const char *);
  41295. /*
  41296. ** Control and query of the open file handle.
  41297. */
  41298. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  41299. winFile *pFile = (winFile*)id;
  41300. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  41301. switch( op ){
  41302. case SQLITE_FCNTL_LOCKSTATE: {
  41303. *(int*)pArg = pFile->locktype;
  41304. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41305. return SQLITE_OK;
  41306. }
  41307. case SQLITE_FCNTL_LAST_ERRNO: {
  41308. *(int*)pArg = (int)pFile->lastErrno;
  41309. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41310. return SQLITE_OK;
  41311. }
  41312. case SQLITE_FCNTL_CHUNK_SIZE: {
  41313. pFile->szChunk = *(int *)pArg;
  41314. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41315. return SQLITE_OK;
  41316. }
  41317. case SQLITE_FCNTL_SIZE_HINT: {
  41318. if( pFile->szChunk>0 ){
  41319. sqlite3_int64 oldSz;
  41320. int rc = winFileSize(id, &oldSz);
  41321. if( rc==SQLITE_OK ){
  41322. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  41323. if( newSz>oldSz ){
  41324. SimulateIOErrorBenign(1);
  41325. rc = winTruncate(id, newSz);
  41326. SimulateIOErrorBenign(0);
  41327. }
  41328. }
  41329. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  41330. return rc;
  41331. }
  41332. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41333. return SQLITE_OK;
  41334. }
  41335. case SQLITE_FCNTL_PERSIST_WAL: {
  41336. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  41337. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41338. return SQLITE_OK;
  41339. }
  41340. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  41341. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  41342. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41343. return SQLITE_OK;
  41344. }
  41345. case SQLITE_FCNTL_VFSNAME: {
  41346. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  41347. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41348. return SQLITE_OK;
  41349. }
  41350. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  41351. int *a = (int*)pArg;
  41352. if( a[0]>0 ){
  41353. winIoerrRetry = a[0];
  41354. }else{
  41355. a[0] = winIoerrRetry;
  41356. }
  41357. if( a[1]>0 ){
  41358. winIoerrRetryDelay = a[1];
  41359. }else{
  41360. a[1] = winIoerrRetryDelay;
  41361. }
  41362. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41363. return SQLITE_OK;
  41364. }
  41365. case SQLITE_FCNTL_WIN32_GET_HANDLE: {
  41366. LPHANDLE phFile = (LPHANDLE)pArg;
  41367. *phFile = pFile->h;
  41368. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41369. return SQLITE_OK;
  41370. }
  41371. #ifdef SQLITE_TEST
  41372. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  41373. LPHANDLE phFile = (LPHANDLE)pArg;
  41374. HANDLE hOldFile = pFile->h;
  41375. pFile->h = *phFile;
  41376. *phFile = hOldFile;
  41377. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  41378. hOldFile, pFile->h));
  41379. return SQLITE_OK;
  41380. }
  41381. #endif
  41382. case SQLITE_FCNTL_TEMPFILENAME: {
  41383. char *zTFile = 0;
  41384. int rc = winGetTempname(pFile->pVfs, &zTFile);
  41385. if( rc==SQLITE_OK ){
  41386. *(char**)pArg = zTFile;
  41387. }
  41388. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  41389. return rc;
  41390. }
  41391. #if SQLITE_MAX_MMAP_SIZE>0
  41392. case SQLITE_FCNTL_MMAP_SIZE: {
  41393. i64 newLimit = *(i64*)pArg;
  41394. int rc = SQLITE_OK;
  41395. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  41396. newLimit = sqlite3GlobalConfig.mxMmap;
  41397. }
  41398. /* The value of newLimit may be eventually cast to (SIZE_T) and passed
  41399. ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
  41400. ** least a 64-bit type. */
  41401. if( newLimit>0 && sizeof(SIZE_T)<8 ){
  41402. newLimit = (newLimit & 0x7FFFFFFF);
  41403. }
  41404. *(i64*)pArg = pFile->mmapSizeMax;
  41405. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  41406. pFile->mmapSizeMax = newLimit;
  41407. if( pFile->mmapSize>0 ){
  41408. winUnmapfile(pFile);
  41409. rc = winMapfile(pFile, -1);
  41410. }
  41411. }
  41412. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  41413. return rc;
  41414. }
  41415. #endif
  41416. }
  41417. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  41418. return SQLITE_NOTFOUND;
  41419. }
  41420. /*
  41421. ** Return the sector size in bytes of the underlying block device for
  41422. ** the specified file. This is almost always 512 bytes, but may be
  41423. ** larger for some devices.
  41424. **
  41425. ** SQLite code assumes this function cannot fail. It also assumes that
  41426. ** if two files are created in the same file-system directory (i.e.
  41427. ** a database and its journal file) that the sector size will be the
  41428. ** same for both.
  41429. */
  41430. static int winSectorSize(sqlite3_file *id){
  41431. (void)id;
  41432. return SQLITE_DEFAULT_SECTOR_SIZE;
  41433. }
  41434. /*
  41435. ** Return a vector of device characteristics.
  41436. */
  41437. static int winDeviceCharacteristics(sqlite3_file *id){
  41438. winFile *p = (winFile*)id;
  41439. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  41440. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  41441. }
  41442. /*
  41443. ** Windows will only let you create file view mappings
  41444. ** on allocation size granularity boundaries.
  41445. ** During sqlite3_os_init() we do a GetSystemInfo()
  41446. ** to get the granularity size.
  41447. */
  41448. static SYSTEM_INFO winSysInfo;
  41449. #ifndef SQLITE_OMIT_WAL
  41450. /*
  41451. ** Helper functions to obtain and relinquish the global mutex. The
  41452. ** global mutex is used to protect the winLockInfo objects used by
  41453. ** this file, all of which may be shared by multiple threads.
  41454. **
  41455. ** Function winShmMutexHeld() is used to assert() that the global mutex
  41456. ** is held when required. This function is only used as part of assert()
  41457. ** statements. e.g.
  41458. **
  41459. ** winShmEnterMutex()
  41460. ** assert( winShmMutexHeld() );
  41461. ** winShmLeaveMutex()
  41462. */
  41463. static sqlite3_mutex *winBigLock = 0;
  41464. static void winShmEnterMutex(void){
  41465. sqlite3_mutex_enter(winBigLock);
  41466. }
  41467. static void winShmLeaveMutex(void){
  41468. sqlite3_mutex_leave(winBigLock);
  41469. }
  41470. #ifndef NDEBUG
  41471. static int winShmMutexHeld(void) {
  41472. return sqlite3_mutex_held(winBigLock);
  41473. }
  41474. #endif
  41475. /*
  41476. ** Object used to represent a single file opened and mmapped to provide
  41477. ** shared memory. When multiple threads all reference the same
  41478. ** log-summary, each thread has its own winFile object, but they all
  41479. ** point to a single instance of this object. In other words, each
  41480. ** log-summary is opened only once per process.
  41481. **
  41482. ** winShmMutexHeld() must be true when creating or destroying
  41483. ** this object or while reading or writing the following fields:
  41484. **
  41485. ** nRef
  41486. ** pNext
  41487. **
  41488. ** The following fields are read-only after the object is created:
  41489. **
  41490. ** fid
  41491. ** zFilename
  41492. **
  41493. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  41494. ** winShmMutexHeld() is true when reading or writing any other field
  41495. ** in this structure.
  41496. **
  41497. */
  41498. struct winShmNode {
  41499. sqlite3_mutex *mutex; /* Mutex to access this object */
  41500. char *zFilename; /* Name of the file */
  41501. winFile hFile; /* File handle from winOpen */
  41502. int szRegion; /* Size of shared-memory regions */
  41503. int nRegion; /* Size of array apRegion */
  41504. u8 isReadonly; /* True if read-only */
  41505. u8 isUnlocked; /* True if no DMS lock held */
  41506. struct ShmRegion {
  41507. HANDLE hMap; /* File handle from CreateFileMapping */
  41508. void *pMap;
  41509. } *aRegion;
  41510. DWORD lastErrno; /* The Windows errno from the last I/O error */
  41511. int nRef; /* Number of winShm objects pointing to this */
  41512. winShm *pFirst; /* All winShm objects pointing to this */
  41513. winShmNode *pNext; /* Next in list of all winShmNode objects */
  41514. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  41515. u8 nextShmId; /* Next available winShm.id value */
  41516. #endif
  41517. };
  41518. /*
  41519. ** A global array of all winShmNode objects.
  41520. **
  41521. ** The winShmMutexHeld() must be true while reading or writing this list.
  41522. */
  41523. static winShmNode *winShmNodeList = 0;
  41524. /*
  41525. ** Structure used internally by this VFS to record the state of an
  41526. ** open shared memory connection.
  41527. **
  41528. ** The following fields are initialized when this object is created and
  41529. ** are read-only thereafter:
  41530. **
  41531. ** winShm.pShmNode
  41532. ** winShm.id
  41533. **
  41534. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  41535. ** while accessing any read/write fields.
  41536. */
  41537. struct winShm {
  41538. winShmNode *pShmNode; /* The underlying winShmNode object */
  41539. winShm *pNext; /* Next winShm with the same winShmNode */
  41540. u8 hasMutex; /* True if holding the winShmNode mutex */
  41541. u16 sharedMask; /* Mask of shared locks held */
  41542. u16 exclMask; /* Mask of exclusive locks held */
  41543. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  41544. u8 id; /* Id of this connection with its winShmNode */
  41545. #endif
  41546. };
  41547. /*
  41548. ** Constants used for locking
  41549. */
  41550. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  41551. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  41552. /*
  41553. ** Apply advisory locks for all n bytes beginning at ofst.
  41554. */
  41555. #define WINSHM_UNLCK 1
  41556. #define WINSHM_RDLCK 2
  41557. #define WINSHM_WRLCK 3
  41558. static int winShmSystemLock(
  41559. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  41560. int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
  41561. int ofst, /* Offset to first byte to be locked/unlocked */
  41562. int nByte /* Number of bytes to lock or unlock */
  41563. ){
  41564. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  41565. /* Access to the winShmNode object is serialized by the caller */
  41566. assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
  41567. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  41568. pFile->hFile.h, lockType, ofst, nByte));
  41569. /* Release/Acquire the system-level lock */
  41570. if( lockType==WINSHM_UNLCK ){
  41571. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  41572. }else{
  41573. /* Initialize the locking parameters */
  41574. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  41575. if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  41576. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  41577. }
  41578. if( rc!= 0 ){
  41579. rc = SQLITE_OK;
  41580. }else{
  41581. pFile->lastErrno = osGetLastError();
  41582. rc = SQLITE_BUSY;
  41583. }
  41584. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  41585. pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
  41586. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  41587. return rc;
  41588. }
  41589. /* Forward references to VFS methods */
  41590. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  41591. static int winDelete(sqlite3_vfs *,const char*,int);
  41592. /*
  41593. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  41594. **
  41595. ** This is not a VFS shared-memory method; it is a utility function called
  41596. ** by VFS shared-memory methods.
  41597. */
  41598. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  41599. winShmNode **pp;
  41600. winShmNode *p;
  41601. assert( winShmMutexHeld() );
  41602. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  41603. osGetCurrentProcessId(), deleteFlag));
  41604. pp = &winShmNodeList;
  41605. while( (p = *pp)!=0 ){
  41606. if( p->nRef==0 ){
  41607. int i;
  41608. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  41609. for(i=0; i<p->nRegion; i++){
  41610. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  41611. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  41612. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  41613. UNUSED_VARIABLE_VALUE(bRc);
  41614. bRc = osCloseHandle(p->aRegion[i].hMap);
  41615. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  41616. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  41617. UNUSED_VARIABLE_VALUE(bRc);
  41618. }
  41619. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  41620. SimulateIOErrorBenign(1);
  41621. winClose((sqlite3_file *)&p->hFile);
  41622. SimulateIOErrorBenign(0);
  41623. }
  41624. if( deleteFlag ){
  41625. SimulateIOErrorBenign(1);
  41626. sqlite3BeginBenignMalloc();
  41627. winDelete(pVfs, p->zFilename, 0);
  41628. sqlite3EndBenignMalloc();
  41629. SimulateIOErrorBenign(0);
  41630. }
  41631. *pp = p->pNext;
  41632. sqlite3_free(p->aRegion);
  41633. sqlite3_free(p);
  41634. }else{
  41635. pp = &p->pNext;
  41636. }
  41637. }
  41638. }
  41639. /*
  41640. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  41641. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  41642. ** code otherwise.
  41643. **
  41644. ** If the DMS cannot be locked because this is a readonly_shm=1
  41645. ** connection and no other process already holds a lock, return
  41646. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  41647. */
  41648. static int winLockSharedMemory(winShmNode *pShmNode){
  41649. int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
  41650. if( rc==SQLITE_OK ){
  41651. if( pShmNode->isReadonly ){
  41652. pShmNode->isUnlocked = 1;
  41653. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  41654. return SQLITE_READONLY_CANTINIT;
  41655. }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
  41656. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  41657. return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  41658. "winLockSharedMemory", pShmNode->zFilename);
  41659. }
  41660. }
  41661. if( rc==SQLITE_OK ){
  41662. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  41663. }
  41664. return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
  41665. }
  41666. /*
  41667. ** Open the shared-memory area associated with database file pDbFd.
  41668. **
  41669. ** When opening a new shared-memory file, if no other instances of that
  41670. ** file are currently open, in this process or in other processes, then
  41671. ** the file must be truncated to zero length or have its header cleared.
  41672. */
  41673. static int winOpenSharedMemory(winFile *pDbFd){
  41674. struct winShm *p; /* The connection to be opened */
  41675. winShmNode *pShmNode = 0; /* The underlying mmapped file */
  41676. int rc = SQLITE_OK; /* Result code */
  41677. winShmNode *pNew; /* Newly allocated winShmNode */
  41678. int nName; /* Size of zName in bytes */
  41679. assert( pDbFd->pShm==0 ); /* Not previously opened */
  41680. /* Allocate space for the new sqlite3_shm object. Also speculatively
  41681. ** allocate space for a new winShmNode and filename.
  41682. */
  41683. p = sqlite3MallocZero( sizeof(*p) );
  41684. if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
  41685. nName = sqlite3Strlen30(pDbFd->zPath);
  41686. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  41687. if( pNew==0 ){
  41688. sqlite3_free(p);
  41689. return SQLITE_IOERR_NOMEM_BKPT;
  41690. }
  41691. pNew->zFilename = (char*)&pNew[1];
  41692. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  41693. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  41694. /* Look to see if there is an existing winShmNode that can be used.
  41695. ** If no matching winShmNode currently exists, create a new one.
  41696. */
  41697. winShmEnterMutex();
  41698. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  41699. /* TBD need to come up with better match here. Perhaps
  41700. ** use FILE_ID_BOTH_DIR_INFO Structure.
  41701. */
  41702. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  41703. }
  41704. if( pShmNode ){
  41705. sqlite3_free(pNew);
  41706. }else{
  41707. int inFlags = SQLITE_OPEN_WAL;
  41708. int outFlags = 0;
  41709. pShmNode = pNew;
  41710. pNew = 0;
  41711. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  41712. pShmNode->pNext = winShmNodeList;
  41713. winShmNodeList = pShmNode;
  41714. if( sqlite3GlobalConfig.bCoreMutex ){
  41715. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  41716. if( pShmNode->mutex==0 ){
  41717. rc = SQLITE_IOERR_NOMEM_BKPT;
  41718. goto shm_open_err;
  41719. }
  41720. }
  41721. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  41722. inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
  41723. }else{
  41724. inFlags |= SQLITE_OPEN_READONLY;
  41725. }
  41726. rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
  41727. (sqlite3_file*)&pShmNode->hFile,
  41728. inFlags, &outFlags);
  41729. if( rc!=SQLITE_OK ){
  41730. rc = winLogError(rc, osGetLastError(), "winOpenShm",
  41731. pShmNode->zFilename);
  41732. goto shm_open_err;
  41733. }
  41734. if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
  41735. rc = winLockSharedMemory(pShmNode);
  41736. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  41737. }
  41738. /* Make the new connection a child of the winShmNode */
  41739. p->pShmNode = pShmNode;
  41740. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  41741. p->id = pShmNode->nextShmId++;
  41742. #endif
  41743. pShmNode->nRef++;
  41744. pDbFd->pShm = p;
  41745. winShmLeaveMutex();
  41746. /* The reference count on pShmNode has already been incremented under
  41747. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  41748. ** new (struct winShm) object to the pShmNode has been set. All that is
  41749. ** left to do is to link the new object into the linked list starting
  41750. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  41751. ** mutex.
  41752. */
  41753. sqlite3_mutex_enter(pShmNode->mutex);
  41754. p->pNext = pShmNode->pFirst;
  41755. pShmNode->pFirst = p;
  41756. sqlite3_mutex_leave(pShmNode->mutex);
  41757. return rc;
  41758. /* Jump here on any error */
  41759. shm_open_err:
  41760. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  41761. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  41762. sqlite3_free(p);
  41763. sqlite3_free(pNew);
  41764. winShmLeaveMutex();
  41765. return rc;
  41766. }
  41767. /*
  41768. ** Close a connection to shared-memory. Delete the underlying
  41769. ** storage if deleteFlag is true.
  41770. */
  41771. static int winShmUnmap(
  41772. sqlite3_file *fd, /* Database holding shared memory */
  41773. int deleteFlag /* Delete after closing if true */
  41774. ){
  41775. winFile *pDbFd; /* Database holding shared-memory */
  41776. winShm *p; /* The connection to be closed */
  41777. winShmNode *pShmNode; /* The underlying shared-memory file */
  41778. winShm **pp; /* For looping over sibling connections */
  41779. pDbFd = (winFile*)fd;
  41780. p = pDbFd->pShm;
  41781. if( p==0 ) return SQLITE_OK;
  41782. pShmNode = p->pShmNode;
  41783. /* Remove connection p from the set of connections associated
  41784. ** with pShmNode */
  41785. sqlite3_mutex_enter(pShmNode->mutex);
  41786. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  41787. *pp = p->pNext;
  41788. /* Free the connection p */
  41789. sqlite3_free(p);
  41790. pDbFd->pShm = 0;
  41791. sqlite3_mutex_leave(pShmNode->mutex);
  41792. /* If pShmNode->nRef has reached 0, then close the underlying
  41793. ** shared-memory file, too */
  41794. winShmEnterMutex();
  41795. assert( pShmNode->nRef>0 );
  41796. pShmNode->nRef--;
  41797. if( pShmNode->nRef==0 ){
  41798. winShmPurge(pDbFd->pVfs, deleteFlag);
  41799. }
  41800. winShmLeaveMutex();
  41801. return SQLITE_OK;
  41802. }
  41803. /*
  41804. ** Change the lock state for a shared-memory segment.
  41805. */
  41806. static int winShmLock(
  41807. sqlite3_file *fd, /* Database file holding the shared memory */
  41808. int ofst, /* First lock to acquire or release */
  41809. int n, /* Number of locks to acquire or release */
  41810. int flags /* What to do with the lock */
  41811. ){
  41812. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  41813. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  41814. winShm *pX; /* For looping over all siblings */
  41815. winShmNode *pShmNode = p->pShmNode;
  41816. int rc = SQLITE_OK; /* Result code */
  41817. u16 mask; /* Mask of locks to take or release */
  41818. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  41819. assert( n>=1 );
  41820. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  41821. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  41822. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  41823. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  41824. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  41825. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  41826. assert( n>1 || mask==(1<<ofst) );
  41827. sqlite3_mutex_enter(pShmNode->mutex);
  41828. if( flags & SQLITE_SHM_UNLOCK ){
  41829. u16 allMask = 0; /* Mask of locks held by siblings */
  41830. /* See if any siblings hold this same lock */
  41831. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  41832. if( pX==p ) continue;
  41833. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  41834. allMask |= pX->sharedMask;
  41835. }
  41836. /* Unlock the system-level locks */
  41837. if( (mask & allMask)==0 ){
  41838. rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
  41839. }else{
  41840. rc = SQLITE_OK;
  41841. }
  41842. /* Undo the local locks */
  41843. if( rc==SQLITE_OK ){
  41844. p->exclMask &= ~mask;
  41845. p->sharedMask &= ~mask;
  41846. }
  41847. }else if( flags & SQLITE_SHM_SHARED ){
  41848. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  41849. /* Find out which shared locks are already held by sibling connections.
  41850. ** If any sibling already holds an exclusive lock, go ahead and return
  41851. ** SQLITE_BUSY.
  41852. */
  41853. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  41854. if( (pX->exclMask & mask)!=0 ){
  41855. rc = SQLITE_BUSY;
  41856. break;
  41857. }
  41858. allShared |= pX->sharedMask;
  41859. }
  41860. /* Get shared locks at the system level, if necessary */
  41861. if( rc==SQLITE_OK ){
  41862. if( (allShared & mask)==0 ){
  41863. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
  41864. }else{
  41865. rc = SQLITE_OK;
  41866. }
  41867. }
  41868. /* Get the local shared locks */
  41869. if( rc==SQLITE_OK ){
  41870. p->sharedMask |= mask;
  41871. }
  41872. }else{
  41873. /* Make sure no sibling connections hold locks that will block this
  41874. ** lock. If any do, return SQLITE_BUSY right away.
  41875. */
  41876. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  41877. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  41878. rc = SQLITE_BUSY;
  41879. break;
  41880. }
  41881. }
  41882. /* Get the exclusive locks at the system level. Then if successful
  41883. ** also mark the local connection as being locked.
  41884. */
  41885. if( rc==SQLITE_OK ){
  41886. rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
  41887. if( rc==SQLITE_OK ){
  41888. assert( (p->sharedMask & mask)==0 );
  41889. p->exclMask |= mask;
  41890. }
  41891. }
  41892. }
  41893. sqlite3_mutex_leave(pShmNode->mutex);
  41894. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  41895. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  41896. sqlite3ErrName(rc)));
  41897. return rc;
  41898. }
  41899. /*
  41900. ** Implement a memory barrier or memory fence on shared memory.
  41901. **
  41902. ** All loads and stores begun before the barrier must complete before
  41903. ** any load or store begun after the barrier.
  41904. */
  41905. static void winShmBarrier(
  41906. sqlite3_file *fd /* Database holding the shared memory */
  41907. ){
  41908. UNUSED_PARAMETER(fd);
  41909. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  41910. winShmEnterMutex(); /* Also mutex, for redundancy */
  41911. winShmLeaveMutex();
  41912. }
  41913. /*
  41914. ** This function is called to obtain a pointer to region iRegion of the
  41915. ** shared-memory associated with the database file fd. Shared-memory regions
  41916. ** are numbered starting from zero. Each shared-memory region is szRegion
  41917. ** bytes in size.
  41918. **
  41919. ** If an error occurs, an error code is returned and *pp is set to NULL.
  41920. **
  41921. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  41922. ** region has not been allocated (by any client, including one running in a
  41923. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  41924. ** isWrite is non-zero and the requested shared-memory region has not yet
  41925. ** been allocated, it is allocated by this function.
  41926. **
  41927. ** If the shared-memory region has already been allocated or is allocated by
  41928. ** this call as described above, then it is mapped into this processes
  41929. ** address space (if it is not already), *pp is set to point to the mapped
  41930. ** memory and SQLITE_OK returned.
  41931. */
  41932. static int winShmMap(
  41933. sqlite3_file *fd, /* Handle open on database file */
  41934. int iRegion, /* Region to retrieve */
  41935. int szRegion, /* Size of regions */
  41936. int isWrite, /* True to extend file if necessary */
  41937. void volatile **pp /* OUT: Mapped memory */
  41938. ){
  41939. winFile *pDbFd = (winFile*)fd;
  41940. winShm *pShm = pDbFd->pShm;
  41941. winShmNode *pShmNode;
  41942. DWORD protect = PAGE_READWRITE;
  41943. DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
  41944. int rc = SQLITE_OK;
  41945. if( !pShm ){
  41946. rc = winOpenSharedMemory(pDbFd);
  41947. if( rc!=SQLITE_OK ) return rc;
  41948. pShm = pDbFd->pShm;
  41949. }
  41950. pShmNode = pShm->pShmNode;
  41951. sqlite3_mutex_enter(pShmNode->mutex);
  41952. if( pShmNode->isUnlocked ){
  41953. rc = winLockSharedMemory(pShmNode);
  41954. if( rc!=SQLITE_OK ) goto shmpage_out;
  41955. pShmNode->isUnlocked = 0;
  41956. }
  41957. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  41958. if( pShmNode->nRegion<=iRegion ){
  41959. struct ShmRegion *apNew; /* New aRegion[] array */
  41960. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  41961. sqlite3_int64 sz; /* Current size of wal-index file */
  41962. pShmNode->szRegion = szRegion;
  41963. /* The requested region is not mapped into this processes address space.
  41964. ** Check to see if it has been allocated (i.e. if the wal-index file is
  41965. ** large enough to contain the requested region).
  41966. */
  41967. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  41968. if( rc!=SQLITE_OK ){
  41969. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  41970. "winShmMap1", pDbFd->zPath);
  41971. goto shmpage_out;
  41972. }
  41973. if( sz<nByte ){
  41974. /* The requested memory region does not exist. If isWrite is set to
  41975. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  41976. **
  41977. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  41978. ** the requested memory region.
  41979. */
  41980. if( !isWrite ) goto shmpage_out;
  41981. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  41982. if( rc!=SQLITE_OK ){
  41983. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  41984. "winShmMap2", pDbFd->zPath);
  41985. goto shmpage_out;
  41986. }
  41987. }
  41988. /* Map the requested memory region into this processes address space. */
  41989. apNew = (struct ShmRegion *)sqlite3_realloc64(
  41990. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  41991. );
  41992. if( !apNew ){
  41993. rc = SQLITE_IOERR_NOMEM_BKPT;
  41994. goto shmpage_out;
  41995. }
  41996. pShmNode->aRegion = apNew;
  41997. if( pShmNode->isReadonly ){
  41998. protect = PAGE_READONLY;
  41999. flags = FILE_MAP_READ;
  42000. }
  42001. while( pShmNode->nRegion<=iRegion ){
  42002. HANDLE hMap = NULL; /* file-mapping handle */
  42003. void *pMap = 0; /* Mapped memory region */
  42004. #if SQLITE_OS_WINRT
  42005. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  42006. NULL, protect, nByte, NULL
  42007. );
  42008. #elif defined(SQLITE_WIN32_HAS_WIDE)
  42009. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  42010. NULL, protect, 0, nByte, NULL
  42011. );
  42012. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  42013. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  42014. NULL, protect, 0, nByte, NULL
  42015. );
  42016. #endif
  42017. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  42018. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  42019. hMap ? "ok" : "failed"));
  42020. if( hMap ){
  42021. int iOffset = pShmNode->nRegion*szRegion;
  42022. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  42023. #if SQLITE_OS_WINRT
  42024. pMap = osMapViewOfFileFromApp(hMap, flags,
  42025. iOffset - iOffsetShift, szRegion + iOffsetShift
  42026. );
  42027. #else
  42028. pMap = osMapViewOfFile(hMap, flags,
  42029. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  42030. );
  42031. #endif
  42032. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  42033. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  42034. szRegion, pMap ? "ok" : "failed"));
  42035. }
  42036. if( !pMap ){
  42037. pShmNode->lastErrno = osGetLastError();
  42038. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  42039. "winShmMap3", pDbFd->zPath);
  42040. if( hMap ) osCloseHandle(hMap);
  42041. goto shmpage_out;
  42042. }
  42043. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  42044. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  42045. pShmNode->nRegion++;
  42046. }
  42047. }
  42048. shmpage_out:
  42049. if( pShmNode->nRegion>iRegion ){
  42050. int iOffset = iRegion*szRegion;
  42051. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  42052. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  42053. *pp = (void *)&p[iOffsetShift];
  42054. }else{
  42055. *pp = 0;
  42056. }
  42057. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  42058. sqlite3_mutex_leave(pShmNode->mutex);
  42059. return rc;
  42060. }
  42061. #else
  42062. # define winShmMap 0
  42063. # define winShmLock 0
  42064. # define winShmBarrier 0
  42065. # define winShmUnmap 0
  42066. #endif /* #ifndef SQLITE_OMIT_WAL */
  42067. /*
  42068. ** Cleans up the mapped region of the specified file, if any.
  42069. */
  42070. #if SQLITE_MAX_MMAP_SIZE>0
  42071. static int winUnmapfile(winFile *pFile){
  42072. assert( pFile!=0 );
  42073. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  42074. "mmapSize=%lld, mmapSizeMax=%lld\n",
  42075. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  42076. pFile->mmapSize, pFile->mmapSizeMax));
  42077. if( pFile->pMapRegion ){
  42078. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  42079. pFile->lastErrno = osGetLastError();
  42080. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  42081. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  42082. pFile->pMapRegion));
  42083. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  42084. "winUnmapfile1", pFile->zPath);
  42085. }
  42086. pFile->pMapRegion = 0;
  42087. pFile->mmapSize = 0;
  42088. }
  42089. if( pFile->hMap!=NULL ){
  42090. if( !osCloseHandle(pFile->hMap) ){
  42091. pFile->lastErrno = osGetLastError();
  42092. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  42093. osGetCurrentProcessId(), pFile, pFile->hMap));
  42094. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  42095. "winUnmapfile2", pFile->zPath);
  42096. }
  42097. pFile->hMap = NULL;
  42098. }
  42099. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  42100. osGetCurrentProcessId(), pFile));
  42101. return SQLITE_OK;
  42102. }
  42103. /*
  42104. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  42105. ** is already mapped, the existing mapping is replaced by the new). Or, if
  42106. ** there already exists a mapping for this file, and there are still
  42107. ** outstanding xFetch() references to it, this function is a no-op.
  42108. **
  42109. ** If parameter nByte is non-negative, then it is the requested size of
  42110. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  42111. ** requested size is the size of the file on disk. The actual size of the
  42112. ** created mapping is either the requested size or the value configured
  42113. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  42114. **
  42115. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  42116. ** recreated as a result of outstanding references) or an SQLite error
  42117. ** code otherwise.
  42118. */
  42119. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  42120. sqlite3_int64 nMap = nByte;
  42121. int rc;
  42122. assert( nMap>=0 || pFd->nFetchOut==0 );
  42123. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  42124. osGetCurrentProcessId(), pFd, nByte));
  42125. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  42126. if( nMap<0 ){
  42127. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  42128. if( rc ){
  42129. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  42130. osGetCurrentProcessId(), pFd));
  42131. return SQLITE_IOERR_FSTAT;
  42132. }
  42133. }
  42134. if( nMap>pFd->mmapSizeMax ){
  42135. nMap = pFd->mmapSizeMax;
  42136. }
  42137. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  42138. if( nMap==0 && pFd->mmapSize>0 ){
  42139. winUnmapfile(pFd);
  42140. }
  42141. if( nMap!=pFd->mmapSize ){
  42142. void *pNew = 0;
  42143. DWORD protect = PAGE_READONLY;
  42144. DWORD flags = FILE_MAP_READ;
  42145. winUnmapfile(pFd);
  42146. #ifdef SQLITE_MMAP_READWRITE
  42147. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  42148. protect = PAGE_READWRITE;
  42149. flags |= FILE_MAP_WRITE;
  42150. }
  42151. #endif
  42152. #if SQLITE_OS_WINRT
  42153. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  42154. #elif defined(SQLITE_WIN32_HAS_WIDE)
  42155. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  42156. (DWORD)((nMap>>32) & 0xffffffff),
  42157. (DWORD)(nMap & 0xffffffff), NULL);
  42158. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  42159. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  42160. (DWORD)((nMap>>32) & 0xffffffff),
  42161. (DWORD)(nMap & 0xffffffff), NULL);
  42162. #endif
  42163. if( pFd->hMap==NULL ){
  42164. pFd->lastErrno = osGetLastError();
  42165. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  42166. "winMapfile1", pFd->zPath);
  42167. /* Log the error, but continue normal operation using xRead/xWrite */
  42168. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  42169. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  42170. return SQLITE_OK;
  42171. }
  42172. assert( (nMap % winSysInfo.dwPageSize)==0 );
  42173. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  42174. #if SQLITE_OS_WINRT
  42175. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  42176. #else
  42177. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  42178. #endif
  42179. if( pNew==NULL ){
  42180. osCloseHandle(pFd->hMap);
  42181. pFd->hMap = NULL;
  42182. pFd->lastErrno = osGetLastError();
  42183. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  42184. "winMapfile2", pFd->zPath);
  42185. /* Log the error, but continue normal operation using xRead/xWrite */
  42186. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  42187. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  42188. return SQLITE_OK;
  42189. }
  42190. pFd->pMapRegion = pNew;
  42191. pFd->mmapSize = nMap;
  42192. }
  42193. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  42194. osGetCurrentProcessId(), pFd));
  42195. return SQLITE_OK;
  42196. }
  42197. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  42198. /*
  42199. ** If possible, return a pointer to a mapping of file fd starting at offset
  42200. ** iOff. The mapping must be valid for at least nAmt bytes.
  42201. **
  42202. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  42203. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  42204. ** Finally, if an error does occur, return an SQLite error code. The final
  42205. ** value of *pp is undefined in this case.
  42206. **
  42207. ** If this function does return a pointer, the caller must eventually
  42208. ** release the reference by calling winUnfetch().
  42209. */
  42210. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  42211. #if SQLITE_MAX_MMAP_SIZE>0
  42212. winFile *pFd = (winFile*)fd; /* The underlying database file */
  42213. #endif
  42214. *pp = 0;
  42215. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  42216. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  42217. #if SQLITE_MAX_MMAP_SIZE>0
  42218. if( pFd->mmapSizeMax>0 ){
  42219. if( pFd->pMapRegion==0 ){
  42220. int rc = winMapfile(pFd, -1);
  42221. if( rc!=SQLITE_OK ){
  42222. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  42223. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  42224. return rc;
  42225. }
  42226. }
  42227. if( pFd->mmapSize >= iOff+nAmt ){
  42228. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  42229. pFd->nFetchOut++;
  42230. }
  42231. }
  42232. #endif
  42233. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  42234. osGetCurrentProcessId(), fd, pp, *pp));
  42235. return SQLITE_OK;
  42236. }
  42237. /*
  42238. ** If the third argument is non-NULL, then this function releases a
  42239. ** reference obtained by an earlier call to winFetch(). The second
  42240. ** argument passed to this function must be the same as the corresponding
  42241. ** argument that was passed to the winFetch() invocation.
  42242. **
  42243. ** Or, if the third argument is NULL, then this function is being called
  42244. ** to inform the VFS layer that, according to POSIX, any existing mapping
  42245. ** may now be invalid and should be unmapped.
  42246. */
  42247. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  42248. #if SQLITE_MAX_MMAP_SIZE>0
  42249. winFile *pFd = (winFile*)fd; /* The underlying database file */
  42250. /* If p==0 (unmap the entire file) then there must be no outstanding
  42251. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  42252. ** then there must be at least one outstanding. */
  42253. assert( (p==0)==(pFd->nFetchOut==0) );
  42254. /* If p!=0, it must match the iOff value. */
  42255. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  42256. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  42257. osGetCurrentProcessId(), pFd, iOff, p));
  42258. if( p ){
  42259. pFd->nFetchOut--;
  42260. }else{
  42261. /* FIXME: If Windows truly always prevents truncating or deleting a
  42262. ** file while a mapping is held, then the following winUnmapfile() call
  42263. ** is unnecessary can be omitted - potentially improving
  42264. ** performance. */
  42265. winUnmapfile(pFd);
  42266. }
  42267. assert( pFd->nFetchOut>=0 );
  42268. #endif
  42269. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  42270. osGetCurrentProcessId(), fd));
  42271. return SQLITE_OK;
  42272. }
  42273. /*
  42274. ** Here ends the implementation of all sqlite3_file methods.
  42275. **
  42276. ********************** End sqlite3_file Methods *******************************
  42277. ******************************************************************************/
  42278. /*
  42279. ** This vector defines all the methods that can operate on an
  42280. ** sqlite3_file for win32.
  42281. */
  42282. static const sqlite3_io_methods winIoMethod = {
  42283. 3, /* iVersion */
  42284. winClose, /* xClose */
  42285. winRead, /* xRead */
  42286. winWrite, /* xWrite */
  42287. winTruncate, /* xTruncate */
  42288. winSync, /* xSync */
  42289. winFileSize, /* xFileSize */
  42290. winLock, /* xLock */
  42291. winUnlock, /* xUnlock */
  42292. winCheckReservedLock, /* xCheckReservedLock */
  42293. winFileControl, /* xFileControl */
  42294. winSectorSize, /* xSectorSize */
  42295. winDeviceCharacteristics, /* xDeviceCharacteristics */
  42296. winShmMap, /* xShmMap */
  42297. winShmLock, /* xShmLock */
  42298. winShmBarrier, /* xShmBarrier */
  42299. winShmUnmap, /* xShmUnmap */
  42300. winFetch, /* xFetch */
  42301. winUnfetch /* xUnfetch */
  42302. };
  42303. /*
  42304. ** This vector defines all the methods that can operate on an
  42305. ** sqlite3_file for win32 without performing any locking.
  42306. */
  42307. static const sqlite3_io_methods winIoNolockMethod = {
  42308. 3, /* iVersion */
  42309. winClose, /* xClose */
  42310. winRead, /* xRead */
  42311. winWrite, /* xWrite */
  42312. winTruncate, /* xTruncate */
  42313. winSync, /* xSync */
  42314. winFileSize, /* xFileSize */
  42315. winNolockLock, /* xLock */
  42316. winNolockUnlock, /* xUnlock */
  42317. winNolockCheckReservedLock, /* xCheckReservedLock */
  42318. winFileControl, /* xFileControl */
  42319. winSectorSize, /* xSectorSize */
  42320. winDeviceCharacteristics, /* xDeviceCharacteristics */
  42321. winShmMap, /* xShmMap */
  42322. winShmLock, /* xShmLock */
  42323. winShmBarrier, /* xShmBarrier */
  42324. winShmUnmap, /* xShmUnmap */
  42325. winFetch, /* xFetch */
  42326. winUnfetch /* xUnfetch */
  42327. };
  42328. static winVfsAppData winAppData = {
  42329. &winIoMethod, /* pMethod */
  42330. 0, /* pAppData */
  42331. 0 /* bNoLock */
  42332. };
  42333. static winVfsAppData winNolockAppData = {
  42334. &winIoNolockMethod, /* pMethod */
  42335. 0, /* pAppData */
  42336. 1 /* bNoLock */
  42337. };
  42338. /****************************************************************************
  42339. **************************** sqlite3_vfs methods ****************************
  42340. **
  42341. ** This division contains the implementation of methods on the
  42342. ** sqlite3_vfs object.
  42343. */
  42344. #if defined(__CYGWIN__)
  42345. /*
  42346. ** Convert a filename from whatever the underlying operating system
  42347. ** supports for filenames into UTF-8. Space to hold the result is
  42348. ** obtained from malloc and must be freed by the calling function.
  42349. */
  42350. static char *winConvertToUtf8Filename(const void *zFilename){
  42351. char *zConverted = 0;
  42352. if( osIsNT() ){
  42353. zConverted = winUnicodeToUtf8(zFilename);
  42354. }
  42355. #ifdef SQLITE_WIN32_HAS_ANSI
  42356. else{
  42357. zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
  42358. }
  42359. #endif
  42360. /* caller will handle out of memory */
  42361. return zConverted;
  42362. }
  42363. #endif
  42364. /*
  42365. ** Convert a UTF-8 filename into whatever form the underlying
  42366. ** operating system wants filenames in. Space to hold the result
  42367. ** is obtained from malloc and must be freed by the calling
  42368. ** function.
  42369. */
  42370. static void *winConvertFromUtf8Filename(const char *zFilename){
  42371. void *zConverted = 0;
  42372. if( osIsNT() ){
  42373. zConverted = winUtf8ToUnicode(zFilename);
  42374. }
  42375. #ifdef SQLITE_WIN32_HAS_ANSI
  42376. else{
  42377. zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
  42378. }
  42379. #endif
  42380. /* caller will handle out of memory */
  42381. return zConverted;
  42382. }
  42383. /*
  42384. ** This function returns non-zero if the specified UTF-8 string buffer
  42385. ** ends with a directory separator character or one was successfully
  42386. ** added to it.
  42387. */
  42388. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  42389. if( zBuf ){
  42390. int nLen = sqlite3Strlen30(zBuf);
  42391. if( nLen>0 ){
  42392. if( winIsDirSep(zBuf[nLen-1]) ){
  42393. return 1;
  42394. }else if( nLen+1<nBuf ){
  42395. zBuf[nLen] = winGetDirSep();
  42396. zBuf[nLen+1] = '\0';
  42397. return 1;
  42398. }
  42399. }
  42400. }
  42401. return 0;
  42402. }
  42403. /*
  42404. ** Create a temporary file name and store the resulting pointer into pzBuf.
  42405. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  42406. */
  42407. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  42408. static char zChars[] =
  42409. "abcdefghijklmnopqrstuvwxyz"
  42410. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  42411. "0123456789";
  42412. size_t i, j;
  42413. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  42414. int nMax, nBuf, nDir, nLen;
  42415. char *zBuf;
  42416. /* It's odd to simulate an io-error here, but really this is just
  42417. ** using the io-error infrastructure to test that SQLite handles this
  42418. ** function failing.
  42419. */
  42420. SimulateIOError( return SQLITE_IOERR );
  42421. /* Allocate a temporary buffer to store the fully qualified file
  42422. ** name for the temporary file. If this fails, we cannot continue.
  42423. */
  42424. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  42425. zBuf = sqlite3MallocZero( nBuf );
  42426. if( !zBuf ){
  42427. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42428. return SQLITE_IOERR_NOMEM_BKPT;
  42429. }
  42430. /* Figure out the effective temporary directory. First, check if one
  42431. ** has been explicitly set by the application; otherwise, use the one
  42432. ** configured by the operating system.
  42433. */
  42434. nDir = nMax - (nPre + 15);
  42435. assert( nDir>0 );
  42436. if( sqlite3_temp_directory ){
  42437. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  42438. if( nDirLen>0 ){
  42439. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  42440. nDirLen++;
  42441. }
  42442. if( nDirLen>nDir ){
  42443. sqlite3_free(zBuf);
  42444. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  42445. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  42446. }
  42447. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  42448. }
  42449. }
  42450. #if defined(__CYGWIN__)
  42451. else{
  42452. static const char *azDirs[] = {
  42453. 0, /* getenv("SQLITE_TMPDIR") */
  42454. 0, /* getenv("TMPDIR") */
  42455. 0, /* getenv("TMP") */
  42456. 0, /* getenv("TEMP") */
  42457. 0, /* getenv("USERPROFILE") */
  42458. "/var/tmp",
  42459. "/usr/tmp",
  42460. "/tmp",
  42461. ".",
  42462. 0 /* List terminator */
  42463. };
  42464. unsigned int i;
  42465. const char *zDir = 0;
  42466. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  42467. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  42468. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  42469. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  42470. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  42471. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  42472. void *zConverted;
  42473. if( zDir==0 ) continue;
  42474. /* If the path starts with a drive letter followed by the colon
  42475. ** character, assume it is already a native Win32 path; otherwise,
  42476. ** it must be converted to a native Win32 path via the Cygwin API
  42477. ** prior to using it.
  42478. */
  42479. if( winIsDriveLetterAndColon(zDir) ){
  42480. zConverted = winConvertFromUtf8Filename(zDir);
  42481. if( !zConverted ){
  42482. sqlite3_free(zBuf);
  42483. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42484. return SQLITE_IOERR_NOMEM_BKPT;
  42485. }
  42486. if( winIsDir(zConverted) ){
  42487. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  42488. sqlite3_free(zConverted);
  42489. break;
  42490. }
  42491. sqlite3_free(zConverted);
  42492. }else{
  42493. zConverted = sqlite3MallocZero( nMax+1 );
  42494. if( !zConverted ){
  42495. sqlite3_free(zBuf);
  42496. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42497. return SQLITE_IOERR_NOMEM_BKPT;
  42498. }
  42499. if( cygwin_conv_path(
  42500. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  42501. zConverted, nMax+1)<0 ){
  42502. sqlite3_free(zConverted);
  42503. sqlite3_free(zBuf);
  42504. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  42505. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  42506. "winGetTempname2", zDir);
  42507. }
  42508. if( winIsDir(zConverted) ){
  42509. /* At this point, we know the candidate directory exists and should
  42510. ** be used. However, we may need to convert the string containing
  42511. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  42512. */
  42513. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  42514. if( !zUtf8 ){
  42515. sqlite3_free(zConverted);
  42516. sqlite3_free(zBuf);
  42517. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42518. return SQLITE_IOERR_NOMEM_BKPT;
  42519. }
  42520. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  42521. sqlite3_free(zUtf8);
  42522. sqlite3_free(zConverted);
  42523. break;
  42524. }
  42525. sqlite3_free(zConverted);
  42526. }
  42527. }
  42528. }
  42529. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  42530. else if( osIsNT() ){
  42531. char *zMulti;
  42532. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  42533. if( !zWidePath ){
  42534. sqlite3_free(zBuf);
  42535. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42536. return SQLITE_IOERR_NOMEM_BKPT;
  42537. }
  42538. if( osGetTempPathW(nMax, zWidePath)==0 ){
  42539. sqlite3_free(zWidePath);
  42540. sqlite3_free(zBuf);
  42541. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  42542. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  42543. "winGetTempname2", 0);
  42544. }
  42545. zMulti = winUnicodeToUtf8(zWidePath);
  42546. if( zMulti ){
  42547. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  42548. sqlite3_free(zMulti);
  42549. sqlite3_free(zWidePath);
  42550. }else{
  42551. sqlite3_free(zWidePath);
  42552. sqlite3_free(zBuf);
  42553. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42554. return SQLITE_IOERR_NOMEM_BKPT;
  42555. }
  42556. }
  42557. #ifdef SQLITE_WIN32_HAS_ANSI
  42558. else{
  42559. char *zUtf8;
  42560. char *zMbcsPath = sqlite3MallocZero( nMax );
  42561. if( !zMbcsPath ){
  42562. sqlite3_free(zBuf);
  42563. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42564. return SQLITE_IOERR_NOMEM_BKPT;
  42565. }
  42566. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  42567. sqlite3_free(zBuf);
  42568. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  42569. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  42570. "winGetTempname3", 0);
  42571. }
  42572. zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
  42573. if( zUtf8 ){
  42574. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  42575. sqlite3_free(zUtf8);
  42576. }else{
  42577. sqlite3_free(zBuf);
  42578. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42579. return SQLITE_IOERR_NOMEM_BKPT;
  42580. }
  42581. }
  42582. #endif /* SQLITE_WIN32_HAS_ANSI */
  42583. #endif /* !SQLITE_OS_WINRT */
  42584. /*
  42585. ** Check to make sure the temporary directory ends with an appropriate
  42586. ** separator. If it does not and there is not enough space left to add
  42587. ** one, fail.
  42588. */
  42589. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  42590. sqlite3_free(zBuf);
  42591. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  42592. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  42593. }
  42594. /*
  42595. ** Check that the output buffer is large enough for the temporary file
  42596. ** name in the following format:
  42597. **
  42598. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  42599. **
  42600. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  42601. ** account for the space used by the 15 character random suffix and the
  42602. ** two trailing NUL characters. The final directory separator character
  42603. ** has already added if it was not already present.
  42604. */
  42605. nLen = sqlite3Strlen30(zBuf);
  42606. if( (nLen + nPre + 17) > nBuf ){
  42607. sqlite3_free(zBuf);
  42608. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  42609. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  42610. }
  42611. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  42612. j = sqlite3Strlen30(zBuf);
  42613. sqlite3_randomness(15, &zBuf[j]);
  42614. for(i=0; i<15; i++, j++){
  42615. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  42616. }
  42617. zBuf[j] = 0;
  42618. zBuf[j+1] = 0;
  42619. *pzBuf = zBuf;
  42620. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  42621. return SQLITE_OK;
  42622. }
  42623. /*
  42624. ** Return TRUE if the named file is really a directory. Return false if
  42625. ** it is something other than a directory, or if there is any kind of memory
  42626. ** allocation failure.
  42627. */
  42628. static int winIsDir(const void *zConverted){
  42629. DWORD attr;
  42630. int rc = 0;
  42631. DWORD lastErrno;
  42632. if( osIsNT() ){
  42633. int cnt = 0;
  42634. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  42635. memset(&sAttrData, 0, sizeof(sAttrData));
  42636. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  42637. GetFileExInfoStandard,
  42638. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  42639. if( !rc ){
  42640. return 0; /* Invalid name? */
  42641. }
  42642. attr = sAttrData.dwFileAttributes;
  42643. #if SQLITE_OS_WINCE==0
  42644. }else{
  42645. attr = osGetFileAttributesA((char*)zConverted);
  42646. #endif
  42647. }
  42648. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  42649. }
  42650. /* forward reference */
  42651. static int winAccess(
  42652. sqlite3_vfs *pVfs, /* Not used on win32 */
  42653. const char *zFilename, /* Name of file to check */
  42654. int flags, /* Type of test to make on this file */
  42655. int *pResOut /* OUT: Result */
  42656. );
  42657. /*
  42658. ** Open a file.
  42659. */
  42660. static int winOpen(
  42661. sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
  42662. const char *zName, /* Name of the file (UTF-8) */
  42663. sqlite3_file *id, /* Write the SQLite file handle here */
  42664. int flags, /* Open mode flags */
  42665. int *pOutFlags /* Status return flags */
  42666. ){
  42667. HANDLE h;
  42668. DWORD lastErrno = 0;
  42669. DWORD dwDesiredAccess;
  42670. DWORD dwShareMode;
  42671. DWORD dwCreationDisposition;
  42672. DWORD dwFlagsAndAttributes = 0;
  42673. #if SQLITE_OS_WINCE
  42674. int isTemp = 0;
  42675. #endif
  42676. winVfsAppData *pAppData;
  42677. winFile *pFile = (winFile*)id;
  42678. void *zConverted; /* Filename in OS encoding */
  42679. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  42680. int cnt = 0;
  42681. /* If argument zPath is a NULL pointer, this function is required to open
  42682. ** a temporary file. Use this buffer to store the file name in.
  42683. */
  42684. char *zTmpname = 0; /* For temporary filename, if necessary. */
  42685. int rc = SQLITE_OK; /* Function Return Code */
  42686. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  42687. int eType = flags&0xFFFFFF00; /* Type of file to open */
  42688. #endif
  42689. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  42690. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  42691. int isCreate = (flags & SQLITE_OPEN_CREATE);
  42692. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  42693. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  42694. #ifndef NDEBUG
  42695. int isOpenJournal = (isCreate && (
  42696. eType==SQLITE_OPEN_MASTER_JOURNAL
  42697. || eType==SQLITE_OPEN_MAIN_JOURNAL
  42698. || eType==SQLITE_OPEN_WAL
  42699. ));
  42700. #endif
  42701. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  42702. zUtf8Name, id, flags, pOutFlags));
  42703. /* Check the following statements are true:
  42704. **
  42705. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  42706. ** (b) if CREATE is set, then READWRITE must also be set, and
  42707. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  42708. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  42709. */
  42710. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  42711. assert(isCreate==0 || isReadWrite);
  42712. assert(isExclusive==0 || isCreate);
  42713. assert(isDelete==0 || isCreate);
  42714. /* The main DB, main journal, WAL file and master journal are never
  42715. ** automatically deleted. Nor are they ever temporary files. */
  42716. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  42717. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  42718. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  42719. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  42720. /* Assert that the upper layer has set one of the "file-type" flags. */
  42721. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  42722. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  42723. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  42724. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  42725. );
  42726. assert( pFile!=0 );
  42727. memset(pFile, 0, sizeof(winFile));
  42728. pFile->h = INVALID_HANDLE_VALUE;
  42729. #if SQLITE_OS_WINRT
  42730. if( !zUtf8Name && !sqlite3_temp_directory ){
  42731. sqlite3_log(SQLITE_ERROR,
  42732. "sqlite3_temp_directory variable should be set for WinRT");
  42733. }
  42734. #endif
  42735. /* If the second argument to this function is NULL, generate a
  42736. ** temporary file name to use
  42737. */
  42738. if( !zUtf8Name ){
  42739. assert( isDelete && !isOpenJournal );
  42740. rc = winGetTempname(pVfs, &zTmpname);
  42741. if( rc!=SQLITE_OK ){
  42742. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  42743. return rc;
  42744. }
  42745. zUtf8Name = zTmpname;
  42746. }
  42747. /* Database filenames are double-zero terminated if they are not
  42748. ** URIs with parameters. Hence, they can always be passed into
  42749. ** sqlite3_uri_parameter().
  42750. */
  42751. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  42752. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  42753. /* Convert the filename to the system encoding. */
  42754. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  42755. if( zConverted==0 ){
  42756. sqlite3_free(zTmpname);
  42757. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  42758. return SQLITE_IOERR_NOMEM_BKPT;
  42759. }
  42760. if( winIsDir(zConverted) ){
  42761. sqlite3_free(zConverted);
  42762. sqlite3_free(zTmpname);
  42763. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  42764. return SQLITE_CANTOPEN_ISDIR;
  42765. }
  42766. if( isReadWrite ){
  42767. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  42768. }else{
  42769. dwDesiredAccess = GENERIC_READ;
  42770. }
  42771. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  42772. ** created. SQLite doesn't use it to indicate "exclusive access"
  42773. ** as it is usually understood.
  42774. */
  42775. if( isExclusive ){
  42776. /* Creates a new file, only if it does not already exist. */
  42777. /* If the file exists, it fails. */
  42778. dwCreationDisposition = CREATE_NEW;
  42779. }else if( isCreate ){
  42780. /* Open existing file, or create if it doesn't exist */
  42781. dwCreationDisposition = OPEN_ALWAYS;
  42782. }else{
  42783. /* Opens a file, only if it exists. */
  42784. dwCreationDisposition = OPEN_EXISTING;
  42785. }
  42786. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  42787. if( isDelete ){
  42788. #if SQLITE_OS_WINCE
  42789. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  42790. isTemp = 1;
  42791. #else
  42792. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  42793. | FILE_ATTRIBUTE_HIDDEN
  42794. | FILE_FLAG_DELETE_ON_CLOSE;
  42795. #endif
  42796. }else{
  42797. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  42798. }
  42799. /* Reports from the internet are that performance is always
  42800. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  42801. #if SQLITE_OS_WINCE
  42802. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  42803. #endif
  42804. if( osIsNT() ){
  42805. #if SQLITE_OS_WINRT
  42806. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  42807. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  42808. extendedParameters.dwFileAttributes =
  42809. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  42810. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  42811. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  42812. extendedParameters.lpSecurityAttributes = NULL;
  42813. extendedParameters.hTemplateFile = NULL;
  42814. do{
  42815. h = osCreateFile2((LPCWSTR)zConverted,
  42816. dwDesiredAccess,
  42817. dwShareMode,
  42818. dwCreationDisposition,
  42819. &extendedParameters);
  42820. if( h!=INVALID_HANDLE_VALUE ) break;
  42821. if( isReadWrite ){
  42822. int rc2, isRO = 0;
  42823. sqlite3BeginBenignMalloc();
  42824. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  42825. sqlite3EndBenignMalloc();
  42826. if( rc2==SQLITE_OK && isRO ) break;
  42827. }
  42828. }while( winRetryIoerr(&cnt, &lastErrno) );
  42829. #else
  42830. do{
  42831. h = osCreateFileW((LPCWSTR)zConverted,
  42832. dwDesiredAccess,
  42833. dwShareMode, NULL,
  42834. dwCreationDisposition,
  42835. dwFlagsAndAttributes,
  42836. NULL);
  42837. if( h!=INVALID_HANDLE_VALUE ) break;
  42838. if( isReadWrite ){
  42839. int rc2, isRO = 0;
  42840. sqlite3BeginBenignMalloc();
  42841. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  42842. sqlite3EndBenignMalloc();
  42843. if( rc2==SQLITE_OK && isRO ) break;
  42844. }
  42845. }while( winRetryIoerr(&cnt, &lastErrno) );
  42846. #endif
  42847. }
  42848. #ifdef SQLITE_WIN32_HAS_ANSI
  42849. else{
  42850. do{
  42851. h = osCreateFileA((LPCSTR)zConverted,
  42852. dwDesiredAccess,
  42853. dwShareMode, NULL,
  42854. dwCreationDisposition,
  42855. dwFlagsAndAttributes,
  42856. NULL);
  42857. if( h!=INVALID_HANDLE_VALUE ) break;
  42858. if( isReadWrite ){
  42859. int rc2, isRO = 0;
  42860. sqlite3BeginBenignMalloc();
  42861. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  42862. sqlite3EndBenignMalloc();
  42863. if( rc2==SQLITE_OK && isRO ) break;
  42864. }
  42865. }while( winRetryIoerr(&cnt, &lastErrno) );
  42866. }
  42867. #endif
  42868. winLogIoerr(cnt, __LINE__);
  42869. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  42870. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  42871. if( h==INVALID_HANDLE_VALUE ){
  42872. sqlite3_free(zConverted);
  42873. sqlite3_free(zTmpname);
  42874. if( isReadWrite && !isExclusive ){
  42875. return winOpen(pVfs, zName, id,
  42876. ((flags|SQLITE_OPEN_READONLY) &
  42877. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  42878. pOutFlags);
  42879. }else{
  42880. pFile->lastErrno = lastErrno;
  42881. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  42882. return SQLITE_CANTOPEN_BKPT;
  42883. }
  42884. }
  42885. if( pOutFlags ){
  42886. if( isReadWrite ){
  42887. *pOutFlags = SQLITE_OPEN_READWRITE;
  42888. }else{
  42889. *pOutFlags = SQLITE_OPEN_READONLY;
  42890. }
  42891. }
  42892. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  42893. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  42894. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  42895. pAppData = (winVfsAppData*)pVfs->pAppData;
  42896. #if SQLITE_OS_WINCE
  42897. {
  42898. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  42899. && ((pAppData==NULL) || !pAppData->bNoLock)
  42900. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  42901. ){
  42902. osCloseHandle(h);
  42903. sqlite3_free(zConverted);
  42904. sqlite3_free(zTmpname);
  42905. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  42906. return rc;
  42907. }
  42908. }
  42909. if( isTemp ){
  42910. pFile->zDeleteOnClose = zConverted;
  42911. }else
  42912. #endif
  42913. {
  42914. sqlite3_free(zConverted);
  42915. }
  42916. sqlite3_free(zTmpname);
  42917. pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
  42918. pFile->pVfs = pVfs;
  42919. pFile->h = h;
  42920. if( isReadonly ){
  42921. pFile->ctrlFlags |= WINFILE_RDONLY;
  42922. }
  42923. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  42924. pFile->ctrlFlags |= WINFILE_PSOW;
  42925. }
  42926. pFile->lastErrno = NO_ERROR;
  42927. pFile->zPath = zName;
  42928. #if SQLITE_MAX_MMAP_SIZE>0
  42929. pFile->hMap = NULL;
  42930. pFile->pMapRegion = 0;
  42931. pFile->mmapSize = 0;
  42932. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  42933. #endif
  42934. OpenCounter(+1);
  42935. return rc;
  42936. }
  42937. /*
  42938. ** Delete the named file.
  42939. **
  42940. ** Note that Windows does not allow a file to be deleted if some other
  42941. ** process has it open. Sometimes a virus scanner or indexing program
  42942. ** will open a journal file shortly after it is created in order to do
  42943. ** whatever it does. While this other process is holding the
  42944. ** file open, we will be unable to delete it. To work around this
  42945. ** problem, we delay 100 milliseconds and try to delete again. Up
  42946. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  42947. ** up and returning an error.
  42948. */
  42949. static int winDelete(
  42950. sqlite3_vfs *pVfs, /* Not used on win32 */
  42951. const char *zFilename, /* Name of file to delete */
  42952. int syncDir /* Not used on win32 */
  42953. ){
  42954. int cnt = 0;
  42955. int rc;
  42956. DWORD attr;
  42957. DWORD lastErrno = 0;
  42958. void *zConverted;
  42959. UNUSED_PARAMETER(pVfs);
  42960. UNUSED_PARAMETER(syncDir);
  42961. SimulateIOError(return SQLITE_IOERR_DELETE);
  42962. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  42963. zConverted = winConvertFromUtf8Filename(zFilename);
  42964. if( zConverted==0 ){
  42965. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  42966. return SQLITE_IOERR_NOMEM_BKPT;
  42967. }
  42968. if( osIsNT() ){
  42969. do {
  42970. #if SQLITE_OS_WINRT
  42971. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  42972. memset(&sAttrData, 0, sizeof(sAttrData));
  42973. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  42974. &sAttrData) ){
  42975. attr = sAttrData.dwFileAttributes;
  42976. }else{
  42977. lastErrno = osGetLastError();
  42978. if( lastErrno==ERROR_FILE_NOT_FOUND
  42979. || lastErrno==ERROR_PATH_NOT_FOUND ){
  42980. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  42981. }else{
  42982. rc = SQLITE_ERROR;
  42983. }
  42984. break;
  42985. }
  42986. #else
  42987. attr = osGetFileAttributesW(zConverted);
  42988. #endif
  42989. if ( attr==INVALID_FILE_ATTRIBUTES ){
  42990. lastErrno = osGetLastError();
  42991. if( lastErrno==ERROR_FILE_NOT_FOUND
  42992. || lastErrno==ERROR_PATH_NOT_FOUND ){
  42993. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  42994. }else{
  42995. rc = SQLITE_ERROR;
  42996. }
  42997. break;
  42998. }
  42999. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  43000. rc = SQLITE_ERROR; /* Files only. */
  43001. break;
  43002. }
  43003. if ( osDeleteFileW(zConverted) ){
  43004. rc = SQLITE_OK; /* Deleted OK. */
  43005. break;
  43006. }
  43007. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  43008. rc = SQLITE_ERROR; /* No more retries. */
  43009. break;
  43010. }
  43011. } while(1);
  43012. }
  43013. #ifdef SQLITE_WIN32_HAS_ANSI
  43014. else{
  43015. do {
  43016. attr = osGetFileAttributesA(zConverted);
  43017. if ( attr==INVALID_FILE_ATTRIBUTES ){
  43018. lastErrno = osGetLastError();
  43019. if( lastErrno==ERROR_FILE_NOT_FOUND
  43020. || lastErrno==ERROR_PATH_NOT_FOUND ){
  43021. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  43022. }else{
  43023. rc = SQLITE_ERROR;
  43024. }
  43025. break;
  43026. }
  43027. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  43028. rc = SQLITE_ERROR; /* Files only. */
  43029. break;
  43030. }
  43031. if ( osDeleteFileA(zConverted) ){
  43032. rc = SQLITE_OK; /* Deleted OK. */
  43033. break;
  43034. }
  43035. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  43036. rc = SQLITE_ERROR; /* No more retries. */
  43037. break;
  43038. }
  43039. } while(1);
  43040. }
  43041. #endif
  43042. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  43043. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  43044. }else{
  43045. winLogIoerr(cnt, __LINE__);
  43046. }
  43047. sqlite3_free(zConverted);
  43048. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  43049. return rc;
  43050. }
  43051. /*
  43052. ** Check the existence and status of a file.
  43053. */
  43054. static int winAccess(
  43055. sqlite3_vfs *pVfs, /* Not used on win32 */
  43056. const char *zFilename, /* Name of file to check */
  43057. int flags, /* Type of test to make on this file */
  43058. int *pResOut /* OUT: Result */
  43059. ){
  43060. DWORD attr;
  43061. int rc = 0;
  43062. DWORD lastErrno = 0;
  43063. void *zConverted;
  43064. UNUSED_PARAMETER(pVfs);
  43065. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  43066. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  43067. zFilename, flags, pResOut));
  43068. zConverted = winConvertFromUtf8Filename(zFilename);
  43069. if( zConverted==0 ){
  43070. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  43071. return SQLITE_IOERR_NOMEM_BKPT;
  43072. }
  43073. if( osIsNT() ){
  43074. int cnt = 0;
  43075. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  43076. memset(&sAttrData, 0, sizeof(sAttrData));
  43077. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  43078. GetFileExInfoStandard,
  43079. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  43080. if( rc ){
  43081. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  43082. ** as if it does not exist.
  43083. */
  43084. if( flags==SQLITE_ACCESS_EXISTS
  43085. && sAttrData.nFileSizeHigh==0
  43086. && sAttrData.nFileSizeLow==0 ){
  43087. attr = INVALID_FILE_ATTRIBUTES;
  43088. }else{
  43089. attr = sAttrData.dwFileAttributes;
  43090. }
  43091. }else{
  43092. winLogIoerr(cnt, __LINE__);
  43093. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  43094. sqlite3_free(zConverted);
  43095. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  43096. zFilename);
  43097. }else{
  43098. attr = INVALID_FILE_ATTRIBUTES;
  43099. }
  43100. }
  43101. }
  43102. #ifdef SQLITE_WIN32_HAS_ANSI
  43103. else{
  43104. attr = osGetFileAttributesA((char*)zConverted);
  43105. }
  43106. #endif
  43107. sqlite3_free(zConverted);
  43108. switch( flags ){
  43109. case SQLITE_ACCESS_READ:
  43110. case SQLITE_ACCESS_EXISTS:
  43111. rc = attr!=INVALID_FILE_ATTRIBUTES;
  43112. break;
  43113. case SQLITE_ACCESS_READWRITE:
  43114. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  43115. (attr & FILE_ATTRIBUTE_READONLY)==0;
  43116. break;
  43117. default:
  43118. assert(!"Invalid flags argument");
  43119. }
  43120. *pResOut = rc;
  43121. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  43122. zFilename, pResOut, *pResOut));
  43123. return SQLITE_OK;
  43124. }
  43125. /*
  43126. ** Returns non-zero if the specified path name starts with a drive letter
  43127. ** followed by a colon character.
  43128. */
  43129. static BOOL winIsDriveLetterAndColon(
  43130. const char *zPathname
  43131. ){
  43132. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  43133. }
  43134. /*
  43135. ** Returns non-zero if the specified path name should be used verbatim. If
  43136. ** non-zero is returned from this function, the calling function must simply
  43137. ** use the provided path name verbatim -OR- resolve it into a full path name
  43138. ** using the GetFullPathName Win32 API function (if available).
  43139. */
  43140. static BOOL winIsVerbatimPathname(
  43141. const char *zPathname
  43142. ){
  43143. /*
  43144. ** If the path name starts with a forward slash or a backslash, it is either
  43145. ** a legal UNC name, a volume relative path, or an absolute path name in the
  43146. ** "Unix" format on Windows. There is no easy way to differentiate between
  43147. ** the final two cases; therefore, we return the safer return value of TRUE
  43148. ** so that callers of this function will simply use it verbatim.
  43149. */
  43150. if ( winIsDirSep(zPathname[0]) ){
  43151. return TRUE;
  43152. }
  43153. /*
  43154. ** If the path name starts with a letter and a colon it is either a volume
  43155. ** relative path or an absolute path. Callers of this function must not
  43156. ** attempt to treat it as a relative path name (i.e. they should simply use
  43157. ** it verbatim).
  43158. */
  43159. if ( winIsDriveLetterAndColon(zPathname) ){
  43160. return TRUE;
  43161. }
  43162. /*
  43163. ** If we get to this point, the path name should almost certainly be a purely
  43164. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  43165. */
  43166. return FALSE;
  43167. }
  43168. /*
  43169. ** Turn a relative pathname into a full pathname. Write the full
  43170. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  43171. ** bytes in size.
  43172. */
  43173. static int winFullPathname(
  43174. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  43175. const char *zRelative, /* Possibly relative input path */
  43176. int nFull, /* Size of output buffer in bytes */
  43177. char *zFull /* Output buffer */
  43178. ){
  43179. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  43180. DWORD nByte;
  43181. void *zConverted;
  43182. char *zOut;
  43183. #endif
  43184. /* If this path name begins with "/X:", where "X" is any alphabetic
  43185. ** character, discard the initial "/" from the pathname.
  43186. */
  43187. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  43188. zRelative++;
  43189. }
  43190. #if defined(__CYGWIN__)
  43191. SimulateIOError( return SQLITE_ERROR );
  43192. UNUSED_PARAMETER(nFull);
  43193. assert( nFull>=pVfs->mxPathname );
  43194. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  43195. /*
  43196. ** NOTE: We are dealing with a relative path name and the data
  43197. ** directory has been set. Therefore, use it as the basis
  43198. ** for converting the relative path name to an absolute
  43199. ** one by prepending the data directory and a slash.
  43200. */
  43201. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  43202. if( !zOut ){
  43203. return SQLITE_IOERR_NOMEM_BKPT;
  43204. }
  43205. if( cygwin_conv_path(
  43206. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  43207. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  43208. sqlite3_free(zOut);
  43209. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  43210. "winFullPathname1", zRelative);
  43211. }else{
  43212. char *zUtf8 = winConvertToUtf8Filename(zOut);
  43213. if( !zUtf8 ){
  43214. sqlite3_free(zOut);
  43215. return SQLITE_IOERR_NOMEM_BKPT;
  43216. }
  43217. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  43218. sqlite3_data_directory, winGetDirSep(), zUtf8);
  43219. sqlite3_free(zUtf8);
  43220. sqlite3_free(zOut);
  43221. }
  43222. }else{
  43223. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  43224. if( !zOut ){
  43225. return SQLITE_IOERR_NOMEM_BKPT;
  43226. }
  43227. if( cygwin_conv_path(
  43228. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  43229. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  43230. sqlite3_free(zOut);
  43231. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  43232. "winFullPathname2", zRelative);
  43233. }else{
  43234. char *zUtf8 = winConvertToUtf8Filename(zOut);
  43235. if( !zUtf8 ){
  43236. sqlite3_free(zOut);
  43237. return SQLITE_IOERR_NOMEM_BKPT;
  43238. }
  43239. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  43240. sqlite3_free(zUtf8);
  43241. sqlite3_free(zOut);
  43242. }
  43243. }
  43244. return SQLITE_OK;
  43245. #endif
  43246. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  43247. SimulateIOError( return SQLITE_ERROR );
  43248. /* WinCE has no concept of a relative pathname, or so I am told. */
  43249. /* WinRT has no way to convert a relative path to an absolute one. */
  43250. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  43251. /*
  43252. ** NOTE: We are dealing with a relative path name and the data
  43253. ** directory has been set. Therefore, use it as the basis
  43254. ** for converting the relative path name to an absolute
  43255. ** one by prepending the data directory and a backslash.
  43256. */
  43257. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  43258. sqlite3_data_directory, winGetDirSep(), zRelative);
  43259. }else{
  43260. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  43261. }
  43262. return SQLITE_OK;
  43263. #endif
  43264. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  43265. /* It's odd to simulate an io-error here, but really this is just
  43266. ** using the io-error infrastructure to test that SQLite handles this
  43267. ** function failing. This function could fail if, for example, the
  43268. ** current working directory has been unlinked.
  43269. */
  43270. SimulateIOError( return SQLITE_ERROR );
  43271. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  43272. /*
  43273. ** NOTE: We are dealing with a relative path name and the data
  43274. ** directory has been set. Therefore, use it as the basis
  43275. ** for converting the relative path name to an absolute
  43276. ** one by prepending the data directory and a backslash.
  43277. */
  43278. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  43279. sqlite3_data_directory, winGetDirSep(), zRelative);
  43280. return SQLITE_OK;
  43281. }
  43282. zConverted = winConvertFromUtf8Filename(zRelative);
  43283. if( zConverted==0 ){
  43284. return SQLITE_IOERR_NOMEM_BKPT;
  43285. }
  43286. if( osIsNT() ){
  43287. LPWSTR zTemp;
  43288. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  43289. if( nByte==0 ){
  43290. sqlite3_free(zConverted);
  43291. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43292. "winFullPathname1", zRelative);
  43293. }
  43294. nByte += 3;
  43295. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  43296. if( zTemp==0 ){
  43297. sqlite3_free(zConverted);
  43298. return SQLITE_IOERR_NOMEM_BKPT;
  43299. }
  43300. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  43301. if( nByte==0 ){
  43302. sqlite3_free(zConverted);
  43303. sqlite3_free(zTemp);
  43304. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43305. "winFullPathname2", zRelative);
  43306. }
  43307. sqlite3_free(zConverted);
  43308. zOut = winUnicodeToUtf8(zTemp);
  43309. sqlite3_free(zTemp);
  43310. }
  43311. #ifdef SQLITE_WIN32_HAS_ANSI
  43312. else{
  43313. char *zTemp;
  43314. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  43315. if( nByte==0 ){
  43316. sqlite3_free(zConverted);
  43317. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43318. "winFullPathname3", zRelative);
  43319. }
  43320. nByte += 3;
  43321. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  43322. if( zTemp==0 ){
  43323. sqlite3_free(zConverted);
  43324. return SQLITE_IOERR_NOMEM_BKPT;
  43325. }
  43326. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  43327. if( nByte==0 ){
  43328. sqlite3_free(zConverted);
  43329. sqlite3_free(zTemp);
  43330. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43331. "winFullPathname4", zRelative);
  43332. }
  43333. sqlite3_free(zConverted);
  43334. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  43335. sqlite3_free(zTemp);
  43336. }
  43337. #endif
  43338. if( zOut ){
  43339. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  43340. sqlite3_free(zOut);
  43341. return SQLITE_OK;
  43342. }else{
  43343. return SQLITE_IOERR_NOMEM_BKPT;
  43344. }
  43345. #endif
  43346. }
  43347. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  43348. /*
  43349. ** Interfaces for opening a shared library, finding entry points
  43350. ** within the shared library, and closing the shared library.
  43351. */
  43352. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  43353. HANDLE h;
  43354. #if defined(__CYGWIN__)
  43355. int nFull = pVfs->mxPathname+1;
  43356. char *zFull = sqlite3MallocZero( nFull );
  43357. void *zConverted = 0;
  43358. if( zFull==0 ){
  43359. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  43360. return 0;
  43361. }
  43362. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  43363. sqlite3_free(zFull);
  43364. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  43365. return 0;
  43366. }
  43367. zConverted = winConvertFromUtf8Filename(zFull);
  43368. sqlite3_free(zFull);
  43369. #else
  43370. void *zConverted = winConvertFromUtf8Filename(zFilename);
  43371. UNUSED_PARAMETER(pVfs);
  43372. #endif
  43373. if( zConverted==0 ){
  43374. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  43375. return 0;
  43376. }
  43377. if( osIsNT() ){
  43378. #if SQLITE_OS_WINRT
  43379. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  43380. #else
  43381. h = osLoadLibraryW((LPCWSTR)zConverted);
  43382. #endif
  43383. }
  43384. #ifdef SQLITE_WIN32_HAS_ANSI
  43385. else{
  43386. h = osLoadLibraryA((char*)zConverted);
  43387. }
  43388. #endif
  43389. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  43390. sqlite3_free(zConverted);
  43391. return (void*)h;
  43392. }
  43393. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  43394. UNUSED_PARAMETER(pVfs);
  43395. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  43396. }
  43397. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  43398. FARPROC proc;
  43399. UNUSED_PARAMETER(pVfs);
  43400. proc = osGetProcAddressA((HANDLE)pH, zSym);
  43401. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  43402. (void*)pH, zSym, (void*)proc));
  43403. return (void(*)(void))proc;
  43404. }
  43405. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  43406. UNUSED_PARAMETER(pVfs);
  43407. osFreeLibrary((HANDLE)pHandle);
  43408. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  43409. }
  43410. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  43411. #define winDlOpen 0
  43412. #define winDlError 0
  43413. #define winDlSym 0
  43414. #define winDlClose 0
  43415. #endif
  43416. /* State information for the randomness gatherer. */
  43417. typedef struct EntropyGatherer EntropyGatherer;
  43418. struct EntropyGatherer {
  43419. unsigned char *a; /* Gather entropy into this buffer */
  43420. int na; /* Size of a[] in bytes */
  43421. int i; /* XOR next input into a[i] */
  43422. int nXor; /* Number of XOR operations done */
  43423. };
  43424. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  43425. /* Mix sz bytes of entropy into p. */
  43426. static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
  43427. int j, k;
  43428. for(j=0, k=p->i; j<sz; j++){
  43429. p->a[k++] ^= x[j];
  43430. if( k>=p->na ) k = 0;
  43431. }
  43432. p->i = k;
  43433. p->nXor += sz;
  43434. }
  43435. #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
  43436. /*
  43437. ** Write up to nBuf bytes of randomness into zBuf.
  43438. */
  43439. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  43440. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  43441. UNUSED_PARAMETER(pVfs);
  43442. memset(zBuf, 0, nBuf);
  43443. return nBuf;
  43444. #else
  43445. EntropyGatherer e;
  43446. UNUSED_PARAMETER(pVfs);
  43447. memset(zBuf, 0, nBuf);
  43448. e.a = (unsigned char*)zBuf;
  43449. e.na = nBuf;
  43450. e.nXor = 0;
  43451. e.i = 0;
  43452. {
  43453. SYSTEMTIME x;
  43454. osGetSystemTime(&x);
  43455. xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
  43456. }
  43457. {
  43458. DWORD pid = osGetCurrentProcessId();
  43459. xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
  43460. }
  43461. #if SQLITE_OS_WINRT
  43462. {
  43463. ULONGLONG cnt = osGetTickCount64();
  43464. xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
  43465. }
  43466. #else
  43467. {
  43468. DWORD cnt = osGetTickCount();
  43469. xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
  43470. }
  43471. #endif /* SQLITE_OS_WINRT */
  43472. {
  43473. LARGE_INTEGER i;
  43474. osQueryPerformanceCounter(&i);
  43475. xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
  43476. }
  43477. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  43478. {
  43479. UUID id;
  43480. memset(&id, 0, sizeof(UUID));
  43481. osUuidCreate(&id);
  43482. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  43483. memset(&id, 0, sizeof(UUID));
  43484. osUuidCreateSequential(&id);
  43485. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  43486. }
  43487. #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
  43488. return e.nXor>nBuf ? nBuf : e.nXor;
  43489. #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
  43490. }
  43491. /*
  43492. ** Sleep for a little while. Return the amount of time slept.
  43493. */
  43494. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  43495. sqlite3_win32_sleep((microsec+999)/1000);
  43496. UNUSED_PARAMETER(pVfs);
  43497. return ((microsec+999)/1000)*1000;
  43498. }
  43499. /*
  43500. ** The following variable, if set to a non-zero value, is interpreted as
  43501. ** the number of seconds since 1970 and is used to set the result of
  43502. ** sqlite3OsCurrentTime() during testing.
  43503. */
  43504. #ifdef SQLITE_TEST
  43505. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  43506. #endif
  43507. /*
  43508. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  43509. ** the current time and date as a Julian Day number times 86_400_000. In
  43510. ** other words, write into *piNow the number of milliseconds since the Julian
  43511. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  43512. ** proleptic Gregorian calendar.
  43513. **
  43514. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  43515. ** cannot be found.
  43516. */
  43517. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  43518. /* FILETIME structure is a 64-bit value representing the number of
  43519. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  43520. */
  43521. FILETIME ft;
  43522. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  43523. #ifdef SQLITE_TEST
  43524. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  43525. #endif
  43526. /* 2^32 - to avoid use of LL and warnings in gcc */
  43527. static const sqlite3_int64 max32BitValue =
  43528. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  43529. (sqlite3_int64)294967296;
  43530. #if SQLITE_OS_WINCE
  43531. SYSTEMTIME time;
  43532. osGetSystemTime(&time);
  43533. /* if SystemTimeToFileTime() fails, it returns zero. */
  43534. if (!osSystemTimeToFileTime(&time,&ft)){
  43535. return SQLITE_ERROR;
  43536. }
  43537. #else
  43538. osGetSystemTimeAsFileTime( &ft );
  43539. #endif
  43540. *piNow = winFiletimeEpoch +
  43541. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  43542. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  43543. #ifdef SQLITE_TEST
  43544. if( sqlite3_current_time ){
  43545. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  43546. }
  43547. #endif
  43548. UNUSED_PARAMETER(pVfs);
  43549. return SQLITE_OK;
  43550. }
  43551. /*
  43552. ** Find the current time (in Universal Coordinated Time). Write the
  43553. ** current time and date as a Julian Day number into *prNow and
  43554. ** return 0. Return 1 if the time and date cannot be found.
  43555. */
  43556. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  43557. int rc;
  43558. sqlite3_int64 i;
  43559. rc = winCurrentTimeInt64(pVfs, &i);
  43560. if( !rc ){
  43561. *prNow = i/86400000.0;
  43562. }
  43563. return rc;
  43564. }
  43565. /*
  43566. ** The idea is that this function works like a combination of
  43567. ** GetLastError() and FormatMessage() on Windows (or errno and
  43568. ** strerror_r() on Unix). After an error is returned by an OS
  43569. ** function, SQLite calls this function with zBuf pointing to
  43570. ** a buffer of nBuf bytes. The OS layer should populate the
  43571. ** buffer with a nul-terminated UTF-8 encoded error message
  43572. ** describing the last IO error to have occurred within the calling
  43573. ** thread.
  43574. **
  43575. ** If the error message is too large for the supplied buffer,
  43576. ** it should be truncated. The return value of xGetLastError
  43577. ** is zero if the error message fits in the buffer, or non-zero
  43578. ** otherwise (if the message was truncated). If non-zero is returned,
  43579. ** then it is not necessary to include the nul-terminator character
  43580. ** in the output buffer.
  43581. **
  43582. ** Not supplying an error message will have no adverse effect
  43583. ** on SQLite. It is fine to have an implementation that never
  43584. ** returns an error message:
  43585. **
  43586. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  43587. ** assert(zBuf[0]=='\0');
  43588. ** return 0;
  43589. ** }
  43590. **
  43591. ** However if an error message is supplied, it will be incorporated
  43592. ** by sqlite into the error message available to the user using
  43593. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  43594. */
  43595. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  43596. DWORD e = osGetLastError();
  43597. UNUSED_PARAMETER(pVfs);
  43598. if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
  43599. return e;
  43600. }
  43601. /*
  43602. ** Initialize and deinitialize the operating system interface.
  43603. */
  43604. SQLITE_API int sqlite3_os_init(void){
  43605. static sqlite3_vfs winVfs = {
  43606. 3, /* iVersion */
  43607. sizeof(winFile), /* szOsFile */
  43608. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  43609. 0, /* pNext */
  43610. "win32", /* zName */
  43611. &winAppData, /* pAppData */
  43612. winOpen, /* xOpen */
  43613. winDelete, /* xDelete */
  43614. winAccess, /* xAccess */
  43615. winFullPathname, /* xFullPathname */
  43616. winDlOpen, /* xDlOpen */
  43617. winDlError, /* xDlError */
  43618. winDlSym, /* xDlSym */
  43619. winDlClose, /* xDlClose */
  43620. winRandomness, /* xRandomness */
  43621. winSleep, /* xSleep */
  43622. winCurrentTime, /* xCurrentTime */
  43623. winGetLastError, /* xGetLastError */
  43624. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43625. winSetSystemCall, /* xSetSystemCall */
  43626. winGetSystemCall, /* xGetSystemCall */
  43627. winNextSystemCall, /* xNextSystemCall */
  43628. };
  43629. #if defined(SQLITE_WIN32_HAS_WIDE)
  43630. static sqlite3_vfs winLongPathVfs = {
  43631. 3, /* iVersion */
  43632. sizeof(winFile), /* szOsFile */
  43633. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  43634. 0, /* pNext */
  43635. "win32-longpath", /* zName */
  43636. &winAppData, /* pAppData */
  43637. winOpen, /* xOpen */
  43638. winDelete, /* xDelete */
  43639. winAccess, /* xAccess */
  43640. winFullPathname, /* xFullPathname */
  43641. winDlOpen, /* xDlOpen */
  43642. winDlError, /* xDlError */
  43643. winDlSym, /* xDlSym */
  43644. winDlClose, /* xDlClose */
  43645. winRandomness, /* xRandomness */
  43646. winSleep, /* xSleep */
  43647. winCurrentTime, /* xCurrentTime */
  43648. winGetLastError, /* xGetLastError */
  43649. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43650. winSetSystemCall, /* xSetSystemCall */
  43651. winGetSystemCall, /* xGetSystemCall */
  43652. winNextSystemCall, /* xNextSystemCall */
  43653. };
  43654. #endif
  43655. static sqlite3_vfs winNolockVfs = {
  43656. 3, /* iVersion */
  43657. sizeof(winFile), /* szOsFile */
  43658. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  43659. 0, /* pNext */
  43660. "win32-none", /* zName */
  43661. &winNolockAppData, /* pAppData */
  43662. winOpen, /* xOpen */
  43663. winDelete, /* xDelete */
  43664. winAccess, /* xAccess */
  43665. winFullPathname, /* xFullPathname */
  43666. winDlOpen, /* xDlOpen */
  43667. winDlError, /* xDlError */
  43668. winDlSym, /* xDlSym */
  43669. winDlClose, /* xDlClose */
  43670. winRandomness, /* xRandomness */
  43671. winSleep, /* xSleep */
  43672. winCurrentTime, /* xCurrentTime */
  43673. winGetLastError, /* xGetLastError */
  43674. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43675. winSetSystemCall, /* xSetSystemCall */
  43676. winGetSystemCall, /* xGetSystemCall */
  43677. winNextSystemCall, /* xNextSystemCall */
  43678. };
  43679. #if defined(SQLITE_WIN32_HAS_WIDE)
  43680. static sqlite3_vfs winLongPathNolockVfs = {
  43681. 3, /* iVersion */
  43682. sizeof(winFile), /* szOsFile */
  43683. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  43684. 0, /* pNext */
  43685. "win32-longpath-none", /* zName */
  43686. &winNolockAppData, /* pAppData */
  43687. winOpen, /* xOpen */
  43688. winDelete, /* xDelete */
  43689. winAccess, /* xAccess */
  43690. winFullPathname, /* xFullPathname */
  43691. winDlOpen, /* xDlOpen */
  43692. winDlError, /* xDlError */
  43693. winDlSym, /* xDlSym */
  43694. winDlClose, /* xDlClose */
  43695. winRandomness, /* xRandomness */
  43696. winSleep, /* xSleep */
  43697. winCurrentTime, /* xCurrentTime */
  43698. winGetLastError, /* xGetLastError */
  43699. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43700. winSetSystemCall, /* xSetSystemCall */
  43701. winGetSystemCall, /* xGetSystemCall */
  43702. winNextSystemCall, /* xNextSystemCall */
  43703. };
  43704. #endif
  43705. /* Double-check that the aSyscall[] array has been constructed
  43706. ** correctly. See ticket [bb3a86e890c8e96ab] */
  43707. assert( ArraySize(aSyscall)==80 );
  43708. /* get memory map allocation granularity */
  43709. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  43710. #if SQLITE_OS_WINRT
  43711. osGetNativeSystemInfo(&winSysInfo);
  43712. #else
  43713. osGetSystemInfo(&winSysInfo);
  43714. #endif
  43715. assert( winSysInfo.dwAllocationGranularity>0 );
  43716. assert( winSysInfo.dwPageSize>0 );
  43717. sqlite3_vfs_register(&winVfs, 1);
  43718. #if defined(SQLITE_WIN32_HAS_WIDE)
  43719. sqlite3_vfs_register(&winLongPathVfs, 0);
  43720. #endif
  43721. sqlite3_vfs_register(&winNolockVfs, 0);
  43722. #if defined(SQLITE_WIN32_HAS_WIDE)
  43723. sqlite3_vfs_register(&winLongPathNolockVfs, 0);
  43724. #endif
  43725. #ifndef SQLITE_OMIT_WAL
  43726. winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  43727. #endif
  43728. return SQLITE_OK;
  43729. }
  43730. SQLITE_API int sqlite3_os_end(void){
  43731. #if SQLITE_OS_WINRT
  43732. if( sleepObj!=NULL ){
  43733. osCloseHandle(sleepObj);
  43734. sleepObj = NULL;
  43735. }
  43736. #endif
  43737. #ifndef SQLITE_OMIT_WAL
  43738. winBigLock = 0;
  43739. #endif
  43740. return SQLITE_OK;
  43741. }
  43742. #endif /* SQLITE_OS_WIN */
  43743. /************** End of os_win.c **********************************************/
  43744. /************** Begin file memdb.c *******************************************/
  43745. /*
  43746. ** 2016-09-07
  43747. **
  43748. ** The author disclaims copyright to this source code. In place of
  43749. ** a legal notice, here is a blessing:
  43750. **
  43751. ** May you do good and not evil.
  43752. ** May you find forgiveness for yourself and forgive others.
  43753. ** May you share freely, never taking more than you give.
  43754. **
  43755. ******************************************************************************
  43756. **
  43757. ** This file implements an in-memory VFS. A database is held as a contiguous
  43758. ** block of memory.
  43759. **
  43760. ** This file also implements interface sqlite3_serialize() and
  43761. ** sqlite3_deserialize().
  43762. */
  43763. /* #include "sqliteInt.h" */
  43764. #ifdef SQLITE_ENABLE_DESERIALIZE
  43765. /*
  43766. ** Forward declaration of objects used by this utility
  43767. */
  43768. typedef struct sqlite3_vfs MemVfs;
  43769. typedef struct MemFile MemFile;
  43770. /* Access to a lower-level VFS that (might) implement dynamic loading,
  43771. ** access to randomness, etc.
  43772. */
  43773. #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
  43774. /* An open file */
  43775. struct MemFile {
  43776. sqlite3_file base; /* IO methods */
  43777. sqlite3_int64 sz; /* Size of the file */
  43778. sqlite3_int64 szMax; /* Space allocated to aData */
  43779. unsigned char *aData; /* content of the file */
  43780. int nMmap; /* Number of memory mapped pages */
  43781. unsigned mFlags; /* Flags */
  43782. int eLock; /* Most recent lock against this file */
  43783. };
  43784. /*
  43785. ** Methods for MemFile
  43786. */
  43787. static int memdbClose(sqlite3_file*);
  43788. static int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  43789. static int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
  43790. static int memdbTruncate(sqlite3_file*, sqlite3_int64 size);
  43791. static int memdbSync(sqlite3_file*, int flags);
  43792. static int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  43793. static int memdbLock(sqlite3_file*, int);
  43794. /* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */
  43795. static int memdbFileControl(sqlite3_file*, int op, void *pArg);
  43796. /* static int memdbSectorSize(sqlite3_file*); // not used */
  43797. static int memdbDeviceCharacteristics(sqlite3_file*);
  43798. static int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  43799. static int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  43800. /*
  43801. ** Methods for MemVfs
  43802. */
  43803. static int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
  43804. /* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */
  43805. static int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *);
  43806. static int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
  43807. static void *memdbDlOpen(sqlite3_vfs*, const char *zFilename);
  43808. static void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
  43809. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
  43810. static void memdbDlClose(sqlite3_vfs*, void*);
  43811. static int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut);
  43812. static int memdbSleep(sqlite3_vfs*, int microseconds);
  43813. /* static int memdbCurrentTime(sqlite3_vfs*, double*); */
  43814. static int memdbGetLastError(sqlite3_vfs*, int, char *);
  43815. static int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
  43816. static sqlite3_vfs memdb_vfs = {
  43817. 2, /* iVersion */
  43818. 0, /* szOsFile (set when registered) */
  43819. 1024, /* mxPathname */
  43820. 0, /* pNext */
  43821. "memdb", /* zName */
  43822. 0, /* pAppData (set when registered) */
  43823. memdbOpen, /* xOpen */
  43824. 0, /* memdbDelete, */ /* xDelete */
  43825. memdbAccess, /* xAccess */
  43826. memdbFullPathname, /* xFullPathname */
  43827. memdbDlOpen, /* xDlOpen */
  43828. memdbDlError, /* xDlError */
  43829. memdbDlSym, /* xDlSym */
  43830. memdbDlClose, /* xDlClose */
  43831. memdbRandomness, /* xRandomness */
  43832. memdbSleep, /* xSleep */
  43833. 0, /* memdbCurrentTime, */ /* xCurrentTime */
  43834. memdbGetLastError, /* xGetLastError */
  43835. memdbCurrentTimeInt64 /* xCurrentTimeInt64 */
  43836. };
  43837. static const sqlite3_io_methods memdb_io_methods = {
  43838. 3, /* iVersion */
  43839. memdbClose, /* xClose */
  43840. memdbRead, /* xRead */
  43841. memdbWrite, /* xWrite */
  43842. memdbTruncate, /* xTruncate */
  43843. memdbSync, /* xSync */
  43844. memdbFileSize, /* xFileSize */
  43845. memdbLock, /* xLock */
  43846. memdbLock, /* xUnlock - same as xLock in this case */
  43847. 0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */
  43848. memdbFileControl, /* xFileControl */
  43849. 0, /* memdbSectorSize,*/ /* xSectorSize */
  43850. memdbDeviceCharacteristics, /* xDeviceCharacteristics */
  43851. 0, /* xShmMap */
  43852. 0, /* xShmLock */
  43853. 0, /* xShmBarrier */
  43854. 0, /* xShmUnmap */
  43855. memdbFetch, /* xFetch */
  43856. memdbUnfetch /* xUnfetch */
  43857. };
  43858. /*
  43859. ** Close an memdb-file.
  43860. **
  43861. ** The pData pointer is owned by the application, so there is nothing
  43862. ** to free.
  43863. */
  43864. static int memdbClose(sqlite3_file *pFile){
  43865. MemFile *p = (MemFile *)pFile;
  43866. if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) sqlite3_free(p->aData);
  43867. return SQLITE_OK;
  43868. }
  43869. /*
  43870. ** Read data from an memdb-file.
  43871. */
  43872. static int memdbRead(
  43873. sqlite3_file *pFile,
  43874. void *zBuf,
  43875. int iAmt,
  43876. sqlite_int64 iOfst
  43877. ){
  43878. MemFile *p = (MemFile *)pFile;
  43879. if( iOfst+iAmt>p->sz ){
  43880. memset(zBuf, 0, iAmt);
  43881. if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
  43882. return SQLITE_IOERR_SHORT_READ;
  43883. }
  43884. memcpy(zBuf, p->aData+iOfst, iAmt);
  43885. return SQLITE_OK;
  43886. }
  43887. /*
  43888. ** Try to enlarge the memory allocation to hold at least sz bytes
  43889. */
  43890. static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
  43891. unsigned char *pNew;
  43892. if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){
  43893. return SQLITE_FULL;
  43894. }
  43895. pNew = sqlite3_realloc64(p->aData, newSz);
  43896. if( pNew==0 ) return SQLITE_NOMEM;
  43897. p->aData = pNew;
  43898. p->szMax = newSz;
  43899. return SQLITE_OK;
  43900. }
  43901. /*
  43902. ** Write data to an memdb-file.
  43903. */
  43904. static int memdbWrite(
  43905. sqlite3_file *pFile,
  43906. const void *z,
  43907. int iAmt,
  43908. sqlite_int64 iOfst
  43909. ){
  43910. MemFile *p = (MemFile *)pFile;
  43911. if( iOfst+iAmt>p->sz ){
  43912. int rc;
  43913. if( iOfst+iAmt>p->szMax
  43914. && (rc = memdbEnlarge(p, (iOfst+iAmt)*2))!=SQLITE_OK
  43915. ){
  43916. return rc;
  43917. }
  43918. if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
  43919. p->sz = iOfst+iAmt;
  43920. }
  43921. memcpy(p->aData+iOfst, z, iAmt);
  43922. return SQLITE_OK;
  43923. }
  43924. /*
  43925. ** Truncate an memdb-file.
  43926. **
  43927. ** In rollback mode (which is always the case for memdb, as it does not
  43928. ** support WAL mode) the truncate() method is only used to reduce
  43929. ** the size of a file, never to increase the size.
  43930. */
  43931. static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
  43932. MemFile *p = (MemFile *)pFile;
  43933. if( NEVER(size>p->sz) ) return SQLITE_FULL;
  43934. p->sz = size;
  43935. return SQLITE_OK;
  43936. }
  43937. /*
  43938. ** Sync an memdb-file.
  43939. */
  43940. static int memdbSync(sqlite3_file *pFile, int flags){
  43941. return SQLITE_OK;
  43942. }
  43943. /*
  43944. ** Return the current file-size of an memdb-file.
  43945. */
  43946. static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  43947. MemFile *p = (MemFile *)pFile;
  43948. *pSize = p->sz;
  43949. return SQLITE_OK;
  43950. }
  43951. /*
  43952. ** Lock an memdb-file.
  43953. */
  43954. static int memdbLock(sqlite3_file *pFile, int eLock){
  43955. MemFile *p = (MemFile *)pFile;
  43956. p->eLock = eLock;
  43957. return SQLITE_OK;
  43958. }
  43959. #if 0 /* Never used because memdbAccess() always returns false */
  43960. /*
  43961. ** Check if another file-handle holds a RESERVED lock on an memdb-file.
  43962. */
  43963. static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  43964. *pResOut = 0;
  43965. return SQLITE_OK;
  43966. }
  43967. #endif
  43968. /*
  43969. ** File control method. For custom operations on an memdb-file.
  43970. */
  43971. static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
  43972. MemFile *p = (MemFile *)pFile;
  43973. int rc = SQLITE_NOTFOUND;
  43974. if( op==SQLITE_FCNTL_VFSNAME ){
  43975. *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
  43976. rc = SQLITE_OK;
  43977. }
  43978. return rc;
  43979. }
  43980. #if 0 /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  43981. /*
  43982. ** Return the sector-size in bytes for an memdb-file.
  43983. */
  43984. static int memdbSectorSize(sqlite3_file *pFile){
  43985. return 1024;
  43986. }
  43987. #endif
  43988. /*
  43989. ** Return the device characteristic flags supported by an memdb-file.
  43990. */
  43991. static int memdbDeviceCharacteristics(sqlite3_file *pFile){
  43992. return SQLITE_IOCAP_ATOMIC |
  43993. SQLITE_IOCAP_POWERSAFE_OVERWRITE |
  43994. SQLITE_IOCAP_SAFE_APPEND |
  43995. SQLITE_IOCAP_SEQUENTIAL;
  43996. }
  43997. /* Fetch a page of a memory-mapped file */
  43998. static int memdbFetch(
  43999. sqlite3_file *pFile,
  44000. sqlite3_int64 iOfst,
  44001. int iAmt,
  44002. void **pp
  44003. ){
  44004. MemFile *p = (MemFile *)pFile;
  44005. p->nMmap++;
  44006. *pp = (void*)(p->aData + iOfst);
  44007. return SQLITE_OK;
  44008. }
  44009. /* Release a memory-mapped page */
  44010. static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
  44011. MemFile *p = (MemFile *)pFile;
  44012. p->nMmap--;
  44013. return SQLITE_OK;
  44014. }
  44015. /*
  44016. ** Open an mem file handle.
  44017. */
  44018. static int memdbOpen(
  44019. sqlite3_vfs *pVfs,
  44020. const char *zName,
  44021. sqlite3_file *pFile,
  44022. int flags,
  44023. int *pOutFlags
  44024. ){
  44025. MemFile *p = (MemFile*)pFile;
  44026. if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
  44027. return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags);
  44028. }
  44029. memset(p, 0, sizeof(*p));
  44030. p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
  44031. assert( pOutFlags!=0 ); /* True because flags==SQLITE_OPEN_MAIN_DB */
  44032. *pOutFlags = flags | SQLITE_OPEN_MEMORY;
  44033. p->base.pMethods = &memdb_io_methods;
  44034. return SQLITE_OK;
  44035. }
  44036. #if 0 /* Only used to delete rollback journals, master journals, and WAL
  44037. ** files, none of which exist in memdb. So this routine is never used */
  44038. /*
  44039. ** Delete the file located at zPath. If the dirSync argument is true,
  44040. ** ensure the file-system modifications are synced to disk before
  44041. ** returning.
  44042. */
  44043. static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  44044. return SQLITE_IOERR_DELETE;
  44045. }
  44046. #endif
  44047. /*
  44048. ** Test for access permissions. Return true if the requested permission
  44049. ** is available, or false otherwise.
  44050. **
  44051. ** With memdb, no files ever exist on disk. So always return false.
  44052. */
  44053. static int memdbAccess(
  44054. sqlite3_vfs *pVfs,
  44055. const char *zPath,
  44056. int flags,
  44057. int *pResOut
  44058. ){
  44059. *pResOut = 0;
  44060. return SQLITE_OK;
  44061. }
  44062. /*
  44063. ** Populate buffer zOut with the full canonical pathname corresponding
  44064. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  44065. ** of at least (INST_MAX_PATHNAME+1) bytes.
  44066. */
  44067. static int memdbFullPathname(
  44068. sqlite3_vfs *pVfs,
  44069. const char *zPath,
  44070. int nOut,
  44071. char *zOut
  44072. ){
  44073. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  44074. return SQLITE_OK;
  44075. }
  44076. /*
  44077. ** Open the dynamic library located at zPath and return a handle.
  44078. */
  44079. static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  44080. return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
  44081. }
  44082. /*
  44083. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  44084. ** utf-8 string describing the most recent error encountered associated
  44085. ** with dynamic libraries.
  44086. */
  44087. static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  44088. ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
  44089. }
  44090. /*
  44091. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  44092. */
  44093. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  44094. return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
  44095. }
  44096. /*
  44097. ** Close the dynamic library handle pHandle.
  44098. */
  44099. static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){
  44100. ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
  44101. }
  44102. /*
  44103. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  44104. ** random data.
  44105. */
  44106. static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  44107. return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
  44108. }
  44109. /*
  44110. ** Sleep for nMicro microseconds. Return the number of microseconds
  44111. ** actually slept.
  44112. */
  44113. static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){
  44114. return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
  44115. }
  44116. #if 0 /* Never used. Modern cores only call xCurrentTimeInt64() */
  44117. /*
  44118. ** Return the current time as a Julian Day number in *pTimeOut.
  44119. */
  44120. static int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  44121. return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
  44122. }
  44123. #endif
  44124. static int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  44125. return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
  44126. }
  44127. static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
  44128. return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
  44129. }
  44130. /*
  44131. ** Translate a database connection pointer and schema name into a
  44132. ** MemFile pointer.
  44133. */
  44134. static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){
  44135. MemFile *p = 0;
  44136. int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);
  44137. if( rc ) return 0;
  44138. if( p->base.pMethods!=&memdb_io_methods ) return 0;
  44139. return p;
  44140. }
  44141. /*
  44142. ** Return the serialization of a database
  44143. */
  44144. SQLITE_API unsigned char *sqlite3_serialize(
  44145. sqlite3 *db, /* The database connection */
  44146. const char *zSchema, /* Which database within the connection */
  44147. sqlite3_int64 *piSize, /* Write size here, if not NULL */
  44148. unsigned int mFlags /* Maybe SQLITE_SERIALIZE_NOCOPY */
  44149. ){
  44150. MemFile *p;
  44151. int iDb;
  44152. Btree *pBt;
  44153. sqlite3_int64 sz;
  44154. int szPage = 0;
  44155. sqlite3_stmt *pStmt = 0;
  44156. unsigned char *pOut;
  44157. char *zSql;
  44158. int rc;
  44159. #ifdef SQLITE_ENABLE_API_ARMOR
  44160. if( !sqlite3SafetyCheckOk(db) ){
  44161. (void)SQLITE_MISUSE_BKPT;
  44162. return 0;
  44163. }
  44164. #endif
  44165. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  44166. p = memdbFromDbSchema(db, zSchema);
  44167. iDb = sqlite3FindDbName(db, zSchema);
  44168. if( piSize ) *piSize = -1;
  44169. if( iDb<0 ) return 0;
  44170. if( p ){
  44171. if( piSize ) *piSize = p->sz;
  44172. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  44173. pOut = p->aData;
  44174. }else{
  44175. pOut = sqlite3_malloc64( p->sz );
  44176. if( pOut ) memcpy(pOut, p->aData, p->sz);
  44177. }
  44178. return pOut;
  44179. }
  44180. pBt = db->aDb[iDb].pBt;
  44181. if( pBt==0 ) return 0;
  44182. szPage = sqlite3BtreeGetPageSize(pBt);
  44183. zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
  44184. rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
  44185. sqlite3_free(zSql);
  44186. if( rc ) return 0;
  44187. rc = sqlite3_step(pStmt);
  44188. if( rc!=SQLITE_ROW ){
  44189. pOut = 0;
  44190. }else{
  44191. sz = sqlite3_column_int64(pStmt, 0)*szPage;
  44192. if( piSize ) *piSize = sz;
  44193. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  44194. pOut = 0;
  44195. }else{
  44196. pOut = sqlite3_malloc64( sz );
  44197. if( pOut ){
  44198. int nPage = sqlite3_column_int(pStmt, 0);
  44199. Pager *pPager = sqlite3BtreePager(pBt);
  44200. int pgno;
  44201. for(pgno=1; pgno<=nPage; pgno++){
  44202. DbPage *pPage = 0;
  44203. unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
  44204. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0);
  44205. if( rc==SQLITE_OK ){
  44206. memcpy(pTo, sqlite3PagerGetData(pPage), szPage);
  44207. }else{
  44208. memset(pTo, 0, szPage);
  44209. }
  44210. sqlite3PagerUnref(pPage);
  44211. }
  44212. }
  44213. }
  44214. }
  44215. sqlite3_finalize(pStmt);
  44216. return pOut;
  44217. }
  44218. /* Convert zSchema to a MemDB and initialize its content.
  44219. */
  44220. SQLITE_API int sqlite3_deserialize(
  44221. sqlite3 *db, /* The database connection */
  44222. const char *zSchema, /* Which DB to reopen with the deserialization */
  44223. unsigned char *pData, /* The serialized database content */
  44224. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  44225. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  44226. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  44227. ){
  44228. MemFile *p;
  44229. char *zSql;
  44230. sqlite3_stmt *pStmt = 0;
  44231. int rc;
  44232. int iDb;
  44233. #ifdef SQLITE_ENABLE_API_ARMOR
  44234. if( !sqlite3SafetyCheckOk(db) ){
  44235. return SQLITE_MISUSE_BKPT;
  44236. }
  44237. if( szDb<0 ) return SQLITE_MISUSE_BKPT;
  44238. if( szBuf<0 ) return SQLITE_MISUSE_BKPT;
  44239. #endif
  44240. sqlite3_mutex_enter(db->mutex);
  44241. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  44242. iDb = sqlite3FindDbName(db, zSchema);
  44243. if( iDb<0 ){
  44244. rc = SQLITE_ERROR;
  44245. goto end_deserialize;
  44246. }
  44247. zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema);
  44248. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  44249. sqlite3_free(zSql);
  44250. if( rc ) goto end_deserialize;
  44251. db->init.iDb = (u8)iDb;
  44252. db->init.reopenMemdb = 1;
  44253. rc = sqlite3_step(pStmt);
  44254. db->init.reopenMemdb = 0;
  44255. if( rc!=SQLITE_DONE ){
  44256. rc = SQLITE_ERROR;
  44257. goto end_deserialize;
  44258. }
  44259. p = memdbFromDbSchema(db, zSchema);
  44260. if( p==0 ){
  44261. rc = SQLITE_ERROR;
  44262. }else{
  44263. p->aData = pData;
  44264. p->sz = szDb;
  44265. p->szMax = szBuf;
  44266. p->mFlags = mFlags;
  44267. rc = SQLITE_OK;
  44268. }
  44269. end_deserialize:
  44270. sqlite3_finalize(pStmt);
  44271. sqlite3_mutex_leave(db->mutex);
  44272. return rc;
  44273. }
  44274. /*
  44275. ** This routine is called when the extension is loaded.
  44276. ** Register the new VFS.
  44277. */
  44278. SQLITE_PRIVATE int sqlite3MemdbInit(void){
  44279. sqlite3_vfs *pLower = sqlite3_vfs_find(0);
  44280. int sz = pLower->szOsFile;
  44281. memdb_vfs.pAppData = pLower;
  44282. /* In all known configurations of SQLite, the size of a default
  44283. ** sqlite3_file is greater than the size of a memdb sqlite3_file.
  44284. ** Should that ever change, remove the following NEVER() */
  44285. if( NEVER(sz<sizeof(MemFile)) ) sz = sizeof(MemFile);
  44286. memdb_vfs.szOsFile = sz;
  44287. return sqlite3_vfs_register(&memdb_vfs, 0);
  44288. }
  44289. #endif /* SQLITE_ENABLE_DESERIALIZE */
  44290. /************** End of memdb.c ***********************************************/
  44291. /************** Begin file bitvec.c ******************************************/
  44292. /*
  44293. ** 2008 February 16
  44294. **
  44295. ** The author disclaims copyright to this source code. In place of
  44296. ** a legal notice, here is a blessing:
  44297. **
  44298. ** May you do good and not evil.
  44299. ** May you find forgiveness for yourself and forgive others.
  44300. ** May you share freely, never taking more than you give.
  44301. **
  44302. *************************************************************************
  44303. ** This file implements an object that represents a fixed-length
  44304. ** bitmap. Bits are numbered starting with 1.
  44305. **
  44306. ** A bitmap is used to record which pages of a database file have been
  44307. ** journalled during a transaction, or which pages have the "dont-write"
  44308. ** property. Usually only a few pages are meet either condition.
  44309. ** So the bitmap is usually sparse and has low cardinality.
  44310. ** But sometimes (for example when during a DROP of a large table) most
  44311. ** or all of the pages in a database can get journalled. In those cases,
  44312. ** the bitmap becomes dense with high cardinality. The algorithm needs
  44313. ** to handle both cases well.
  44314. **
  44315. ** The size of the bitmap is fixed when the object is created.
  44316. **
  44317. ** All bits are clear when the bitmap is created. Individual bits
  44318. ** may be set or cleared one at a time.
  44319. **
  44320. ** Test operations are about 100 times more common that set operations.
  44321. ** Clear operations are exceedingly rare. There are usually between
  44322. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  44323. ** sometimes grow into tens of thousands or larger. The size of the
  44324. ** Bitvec object is the number of pages in the database file at the
  44325. ** start of a transaction, and is thus usually less than a few thousand,
  44326. ** but can be as large as 2 billion for a really big database.
  44327. */
  44328. /* #include "sqliteInt.h" */
  44329. /* Size of the Bitvec structure in bytes. */
  44330. #define BITVEC_SZ 512
  44331. /* Round the union size down to the nearest pointer boundary, since that's how
  44332. ** it will be aligned within the Bitvec struct. */
  44333. #define BITVEC_USIZE \
  44334. (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  44335. /* Type of the array "element" for the bitmap representation.
  44336. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  44337. ** Setting this to the "natural word" size of your CPU may improve
  44338. ** performance. */
  44339. #define BITVEC_TELEM u8
  44340. /* Size, in bits, of the bitmap element. */
  44341. #define BITVEC_SZELEM 8
  44342. /* Number of elements in a bitmap array. */
  44343. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  44344. /* Number of bits in the bitmap array. */
  44345. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  44346. /* Number of u32 values in hash table. */
  44347. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  44348. /* Maximum number of entries in hash table before
  44349. ** sub-dividing and re-hashing. */
  44350. #define BITVEC_MXHASH (BITVEC_NINT/2)
  44351. /* Hashing function for the aHash representation.
  44352. ** Empirical testing showed that the *37 multiplier
  44353. ** (an arbitrary prime)in the hash function provided
  44354. ** no fewer collisions than the no-op *1. */
  44355. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  44356. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  44357. /*
  44358. ** A bitmap is an instance of the following structure.
  44359. **
  44360. ** This bitmap records the existence of zero or more bits
  44361. ** with values between 1 and iSize, inclusive.
  44362. **
  44363. ** There are three possible representations of the bitmap.
  44364. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  44365. ** bitmap. The least significant bit is bit 1.
  44366. **
  44367. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  44368. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  44369. **
  44370. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  44371. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  44372. ** handles up to iDivisor separate values of i. apSub[0] holds
  44373. ** values between 1 and iDivisor. apSub[1] holds values between
  44374. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  44375. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  44376. ** to hold deal with values between 1 and iDivisor.
  44377. */
  44378. struct Bitvec {
  44379. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  44380. u32 nSet; /* Number of bits that are set - only valid for aHash
  44381. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  44382. ** this would be 125. */
  44383. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  44384. /* Should >=0 for apSub element. */
  44385. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  44386. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  44387. union {
  44388. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  44389. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  44390. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  44391. } u;
  44392. };
  44393. /*
  44394. ** Create a new bitmap object able to handle bits between 0 and iSize,
  44395. ** inclusive. Return a pointer to the new object. Return NULL if
  44396. ** malloc fails.
  44397. */
  44398. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  44399. Bitvec *p;
  44400. assert( sizeof(*p)==BITVEC_SZ );
  44401. p = sqlite3MallocZero( sizeof(*p) );
  44402. if( p ){
  44403. p->iSize = iSize;
  44404. }
  44405. return p;
  44406. }
  44407. /*
  44408. ** Check to see if the i-th bit is set. Return true or false.
  44409. ** If p is NULL (if the bitmap has not been created) or if
  44410. ** i is out of range, then return false.
  44411. */
  44412. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  44413. assert( p!=0 );
  44414. i--;
  44415. if( i>=p->iSize ) return 0;
  44416. while( p->iDivisor ){
  44417. u32 bin = i/p->iDivisor;
  44418. i = i%p->iDivisor;
  44419. p = p->u.apSub[bin];
  44420. if (!p) {
  44421. return 0;
  44422. }
  44423. }
  44424. if( p->iSize<=BITVEC_NBIT ){
  44425. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  44426. } else{
  44427. u32 h = BITVEC_HASH(i++);
  44428. while( p->u.aHash[h] ){
  44429. if( p->u.aHash[h]==i ) return 1;
  44430. h = (h+1) % BITVEC_NINT;
  44431. }
  44432. return 0;
  44433. }
  44434. }
  44435. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  44436. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  44437. }
  44438. /*
  44439. ** Set the i-th bit. Return 0 on success and an error code if
  44440. ** anything goes wrong.
  44441. **
  44442. ** This routine might cause sub-bitmaps to be allocated. Failing
  44443. ** to get the memory needed to hold the sub-bitmap is the only
  44444. ** that can go wrong with an insert, assuming p and i are valid.
  44445. **
  44446. ** The calling function must ensure that p is a valid Bitvec object
  44447. ** and that the value for "i" is within range of the Bitvec object.
  44448. ** Otherwise the behavior is undefined.
  44449. */
  44450. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  44451. u32 h;
  44452. if( p==0 ) return SQLITE_OK;
  44453. assert( i>0 );
  44454. assert( i<=p->iSize );
  44455. i--;
  44456. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  44457. u32 bin = i/p->iDivisor;
  44458. i = i%p->iDivisor;
  44459. if( p->u.apSub[bin]==0 ){
  44460. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  44461. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
  44462. }
  44463. p = p->u.apSub[bin];
  44464. }
  44465. if( p->iSize<=BITVEC_NBIT ){
  44466. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  44467. return SQLITE_OK;
  44468. }
  44469. h = BITVEC_HASH(i++);
  44470. /* if there wasn't a hash collision, and this doesn't */
  44471. /* completely fill the hash, then just add it without */
  44472. /* worring about sub-dividing and re-hashing. */
  44473. if( !p->u.aHash[h] ){
  44474. if (p->nSet<(BITVEC_NINT-1)) {
  44475. goto bitvec_set_end;
  44476. } else {
  44477. goto bitvec_set_rehash;
  44478. }
  44479. }
  44480. /* there was a collision, check to see if it's already */
  44481. /* in hash, if not, try to find a spot for it */
  44482. do {
  44483. if( p->u.aHash[h]==i ) return SQLITE_OK;
  44484. h++;
  44485. if( h>=BITVEC_NINT ) h = 0;
  44486. } while( p->u.aHash[h] );
  44487. /* we didn't find it in the hash. h points to the first */
  44488. /* available free spot. check to see if this is going to */
  44489. /* make our hash too "full". */
  44490. bitvec_set_rehash:
  44491. if( p->nSet>=BITVEC_MXHASH ){
  44492. unsigned int j;
  44493. int rc;
  44494. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  44495. if( aiValues==0 ){
  44496. return SQLITE_NOMEM_BKPT;
  44497. }else{
  44498. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  44499. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  44500. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  44501. rc = sqlite3BitvecSet(p, i);
  44502. for(j=0; j<BITVEC_NINT; j++){
  44503. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  44504. }
  44505. sqlite3StackFree(0, aiValues);
  44506. return rc;
  44507. }
  44508. }
  44509. bitvec_set_end:
  44510. p->nSet++;
  44511. p->u.aHash[h] = i;
  44512. return SQLITE_OK;
  44513. }
  44514. /*
  44515. ** Clear the i-th bit.
  44516. **
  44517. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  44518. ** that BitvecClear can use to rebuilt its hash table.
  44519. */
  44520. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  44521. if( p==0 ) return;
  44522. assert( i>0 );
  44523. i--;
  44524. while( p->iDivisor ){
  44525. u32 bin = i/p->iDivisor;
  44526. i = i%p->iDivisor;
  44527. p = p->u.apSub[bin];
  44528. if (!p) {
  44529. return;
  44530. }
  44531. }
  44532. if( p->iSize<=BITVEC_NBIT ){
  44533. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  44534. }else{
  44535. unsigned int j;
  44536. u32 *aiValues = pBuf;
  44537. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  44538. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  44539. p->nSet = 0;
  44540. for(j=0; j<BITVEC_NINT; j++){
  44541. if( aiValues[j] && aiValues[j]!=(i+1) ){
  44542. u32 h = BITVEC_HASH(aiValues[j]-1);
  44543. p->nSet++;
  44544. while( p->u.aHash[h] ){
  44545. h++;
  44546. if( h>=BITVEC_NINT ) h = 0;
  44547. }
  44548. p->u.aHash[h] = aiValues[j];
  44549. }
  44550. }
  44551. }
  44552. }
  44553. /*
  44554. ** Destroy a bitmap object. Reclaim all memory used.
  44555. */
  44556. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  44557. if( p==0 ) return;
  44558. if( p->iDivisor ){
  44559. unsigned int i;
  44560. for(i=0; i<BITVEC_NPTR; i++){
  44561. sqlite3BitvecDestroy(p->u.apSub[i]);
  44562. }
  44563. }
  44564. sqlite3_free(p);
  44565. }
  44566. /*
  44567. ** Return the value of the iSize parameter specified when Bitvec *p
  44568. ** was created.
  44569. */
  44570. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  44571. return p->iSize;
  44572. }
  44573. #ifndef SQLITE_UNTESTABLE
  44574. /*
  44575. ** Let V[] be an array of unsigned characters sufficient to hold
  44576. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  44577. ** Then the following macros can be used to set, clear, or test
  44578. ** individual bits within V.
  44579. */
  44580. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  44581. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  44582. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  44583. /*
  44584. ** This routine runs an extensive test of the Bitvec code.
  44585. **
  44586. ** The input is an array of integers that acts as a program
  44587. ** to test the Bitvec. The integers are opcodes followed
  44588. ** by 0, 1, or 3 operands, depending on the opcode. Another
  44589. ** opcode follows immediately after the last operand.
  44590. **
  44591. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  44592. ** "halt" opcode and causes the test to end.
  44593. **
  44594. ** 0 Halt and return the number of errors
  44595. ** 1 N S X Set N bits beginning with S and incrementing by X
  44596. ** 2 N S X Clear N bits beginning with S and incrementing by X
  44597. ** 3 N Set N randomly chosen bits
  44598. ** 4 N Clear N randomly chosen bits
  44599. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  44600. **
  44601. ** The opcodes 1 through 4 perform set and clear operations are performed
  44602. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  44603. ** Opcode 5 works on the linear array only, not on the Bitvec.
  44604. ** Opcode 5 is used to deliberately induce a fault in order to
  44605. ** confirm that error detection works.
  44606. **
  44607. ** At the conclusion of the test the linear array is compared
  44608. ** against the Bitvec object. If there are any differences,
  44609. ** an error is returned. If they are the same, zero is returned.
  44610. **
  44611. ** If a memory allocation error occurs, return -1.
  44612. */
  44613. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  44614. Bitvec *pBitvec = 0;
  44615. unsigned char *pV = 0;
  44616. int rc = -1;
  44617. int i, nx, pc, op;
  44618. void *pTmpSpace;
  44619. /* Allocate the Bitvec to be tested and a linear array of
  44620. ** bits to act as the reference */
  44621. pBitvec = sqlite3BitvecCreate( sz );
  44622. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  44623. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  44624. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  44625. /* NULL pBitvec tests */
  44626. sqlite3BitvecSet(0, 1);
  44627. sqlite3BitvecClear(0, 1, pTmpSpace);
  44628. /* Run the program */
  44629. pc = 0;
  44630. while( (op = aOp[pc])!=0 ){
  44631. switch( op ){
  44632. case 1:
  44633. case 2:
  44634. case 5: {
  44635. nx = 4;
  44636. i = aOp[pc+2] - 1;
  44637. aOp[pc+2] += aOp[pc+3];
  44638. break;
  44639. }
  44640. case 3:
  44641. case 4:
  44642. default: {
  44643. nx = 2;
  44644. sqlite3_randomness(sizeof(i), &i);
  44645. break;
  44646. }
  44647. }
  44648. if( (--aOp[pc+1]) > 0 ) nx = 0;
  44649. pc += nx;
  44650. i = (i & 0x7fffffff)%sz;
  44651. if( (op & 1)!=0 ){
  44652. SETBIT(pV, (i+1));
  44653. if( op!=5 ){
  44654. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  44655. }
  44656. }else{
  44657. CLEARBIT(pV, (i+1));
  44658. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  44659. }
  44660. }
  44661. /* Test to make sure the linear array exactly matches the
  44662. ** Bitvec object. Start with the assumption that they do
  44663. ** match (rc==0). Change rc to non-zero if a discrepancy
  44664. ** is found.
  44665. */
  44666. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  44667. + sqlite3BitvecTest(pBitvec, 0)
  44668. + (sqlite3BitvecSize(pBitvec) - sz);
  44669. for(i=1; i<=sz; i++){
  44670. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  44671. rc = i;
  44672. break;
  44673. }
  44674. }
  44675. /* Free allocated structure */
  44676. bitvec_end:
  44677. sqlite3_free(pTmpSpace);
  44678. sqlite3_free(pV);
  44679. sqlite3BitvecDestroy(pBitvec);
  44680. return rc;
  44681. }
  44682. #endif /* SQLITE_UNTESTABLE */
  44683. /************** End of bitvec.c **********************************************/
  44684. /************** Begin file pcache.c ******************************************/
  44685. /*
  44686. ** 2008 August 05
  44687. **
  44688. ** The author disclaims copyright to this source code. In place of
  44689. ** a legal notice, here is a blessing:
  44690. **
  44691. ** May you do good and not evil.
  44692. ** May you find forgiveness for yourself and forgive others.
  44693. ** May you share freely, never taking more than you give.
  44694. **
  44695. *************************************************************************
  44696. ** This file implements that page cache.
  44697. */
  44698. /* #include "sqliteInt.h" */
  44699. /*
  44700. ** A complete page cache is an instance of this structure. Every
  44701. ** entry in the cache holds a single page of the database file. The
  44702. ** btree layer only operates on the cached copy of the database pages.
  44703. **
  44704. ** A page cache entry is "clean" if it exactly matches what is currently
  44705. ** on disk. A page is "dirty" if it has been modified and needs to be
  44706. ** persisted to disk.
  44707. **
  44708. ** pDirty, pDirtyTail, pSynced:
  44709. ** All dirty pages are linked into the doubly linked list using
  44710. ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
  44711. ** such that p was added to the list more recently than p->pDirtyNext.
  44712. ** PCache.pDirty points to the first (newest) element in the list and
  44713. ** pDirtyTail to the last (oldest).
  44714. **
  44715. ** The PCache.pSynced variable is used to optimize searching for a dirty
  44716. ** page to eject from the cache mid-transaction. It is better to eject
  44717. ** a page that does not require a journal sync than one that does.
  44718. ** Therefore, pSynced is maintained so that it *almost* always points
  44719. ** to either the oldest page in the pDirty/pDirtyTail list that has a
  44720. ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
  44721. ** (so that the right page to eject can be found by following pDirtyPrev
  44722. ** pointers).
  44723. */
  44724. struct PCache {
  44725. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  44726. PgHdr *pSynced; /* Last synced page in dirty page list */
  44727. int nRefSum; /* Sum of ref counts over all pages */
  44728. int szCache; /* Configured cache size */
  44729. int szSpill; /* Size before spilling occurs */
  44730. int szPage; /* Size of every page in this cache */
  44731. int szExtra; /* Size of extra space for each page */
  44732. u8 bPurgeable; /* True if pages are on backing store */
  44733. u8 eCreate; /* eCreate value for for xFetch() */
  44734. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  44735. void *pStress; /* Argument to xStress */
  44736. sqlite3_pcache *pCache; /* Pluggable cache module */
  44737. };
  44738. /********************************** Test and Debug Logic **********************/
  44739. /*
  44740. ** Debug tracing macros. Enable by by changing the "0" to "1" and
  44741. ** recompiling.
  44742. **
  44743. ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
  44744. ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
  44745. ** is displayed for many operations, resulting in a lot of output.
  44746. */
  44747. #if defined(SQLITE_DEBUG) && 0
  44748. int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
  44749. int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
  44750. # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
  44751. void pcacheDump(PCache *pCache){
  44752. int N;
  44753. int i, j;
  44754. sqlite3_pcache_page *pLower;
  44755. PgHdr *pPg;
  44756. unsigned char *a;
  44757. if( sqlite3PcacheTrace<2 ) return;
  44758. if( pCache->pCache==0 ) return;
  44759. N = sqlite3PcachePagecount(pCache);
  44760. if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
  44761. for(i=1; i<=N; i++){
  44762. pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
  44763. if( pLower==0 ) continue;
  44764. pPg = (PgHdr*)pLower->pExtra;
  44765. printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
  44766. a = (unsigned char *)pLower->pBuf;
  44767. for(j=0; j<12; j++) printf("%02x", a[j]);
  44768. printf("\n");
  44769. if( pPg->pPage==0 ){
  44770. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
  44771. }
  44772. }
  44773. }
  44774. #else
  44775. # define pcacheTrace(X)
  44776. # define pcacheDump(X)
  44777. #endif
  44778. /*
  44779. ** Check invariants on a PgHdr entry. Return true if everything is OK.
  44780. ** Return false if any invariant is violated.
  44781. **
  44782. ** This routine is for use inside of assert() statements only. For
  44783. ** example:
  44784. **
  44785. ** assert( sqlite3PcachePageSanity(pPg) );
  44786. */
  44787. #ifdef SQLITE_DEBUG
  44788. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
  44789. PCache *pCache;
  44790. assert( pPg!=0 );
  44791. assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
  44792. pCache = pPg->pCache;
  44793. assert( pCache!=0 ); /* Every page has an associated PCache */
  44794. if( pPg->flags & PGHDR_CLEAN ){
  44795. assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
  44796. assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
  44797. assert( pCache->pDirtyTail!=pPg );
  44798. }
  44799. /* WRITEABLE pages must also be DIRTY */
  44800. if( pPg->flags & PGHDR_WRITEABLE ){
  44801. assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
  44802. }
  44803. /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
  44804. ** for example, when using the sqlite3PagerDontWrite() optimization:
  44805. ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
  44806. ** (2) Page X moved to freelist, WRITEABLE is cleared
  44807. ** (3) Page X reused, WRITEABLE is set again
  44808. ** If NEED_SYNC had been cleared in step 2, then it would not be reset
  44809. ** in step 3, and page might be written into the database without first
  44810. ** syncing the rollback journal, which might cause corruption on a power
  44811. ** loss.
  44812. **
  44813. ** Another example is when the database page size is smaller than the
  44814. ** disk sector size. When any page of a sector is journalled, all pages
  44815. ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
  44816. ** in case they are later modified, since all pages in the same sector
  44817. ** must be journalled and synced before any of those pages can be safely
  44818. ** written.
  44819. */
  44820. return 1;
  44821. }
  44822. #endif /* SQLITE_DEBUG */
  44823. /********************************** Linked List Management ********************/
  44824. /* Allowed values for second argument to pcacheManageDirtyList() */
  44825. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  44826. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  44827. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  44828. /*
  44829. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  44830. ** argument determines what operation to do. The 0x01 bit means first
  44831. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  44832. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  44833. */
  44834. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  44835. PCache *p = pPage->pCache;
  44836. pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
  44837. addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
  44838. pPage->pgno));
  44839. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  44840. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  44841. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  44842. /* Update the PCache1.pSynced variable if necessary. */
  44843. if( p->pSynced==pPage ){
  44844. p->pSynced = pPage->pDirtyPrev;
  44845. }
  44846. if( pPage->pDirtyNext ){
  44847. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  44848. }else{
  44849. assert( pPage==p->pDirtyTail );
  44850. p->pDirtyTail = pPage->pDirtyPrev;
  44851. }
  44852. if( pPage->pDirtyPrev ){
  44853. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  44854. }else{
  44855. /* If there are now no dirty pages in the cache, set eCreate to 2.
  44856. ** This is an optimization that allows sqlite3PcacheFetch() to skip
  44857. ** searching for a dirty page to eject from the cache when it might
  44858. ** otherwise have to. */
  44859. assert( pPage==p->pDirty );
  44860. p->pDirty = pPage->pDirtyNext;
  44861. assert( p->bPurgeable || p->eCreate==2 );
  44862. if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
  44863. assert( p->bPurgeable==0 || p->eCreate==1 );
  44864. p->eCreate = 2;
  44865. }
  44866. }
  44867. }
  44868. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  44869. pPage->pDirtyPrev = 0;
  44870. pPage->pDirtyNext = p->pDirty;
  44871. if( pPage->pDirtyNext ){
  44872. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  44873. pPage->pDirtyNext->pDirtyPrev = pPage;
  44874. }else{
  44875. p->pDirtyTail = pPage;
  44876. if( p->bPurgeable ){
  44877. assert( p->eCreate==2 );
  44878. p->eCreate = 1;
  44879. }
  44880. }
  44881. p->pDirty = pPage;
  44882. /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
  44883. ** pSynced to point to it. Checking the NEED_SYNC flag is an
  44884. ** optimization, as if pSynced points to a page with the NEED_SYNC
  44885. ** flag set sqlite3PcacheFetchStress() searches through all newer
  44886. ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
  44887. if( !p->pSynced
  44888. && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
  44889. ){
  44890. p->pSynced = pPage;
  44891. }
  44892. }
  44893. pcacheDump(p);
  44894. }
  44895. /*
  44896. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  44897. ** being used for an in-memory database, this function is a no-op.
  44898. */
  44899. static void pcacheUnpin(PgHdr *p){
  44900. if( p->pCache->bPurgeable ){
  44901. pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
  44902. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  44903. pcacheDump(p->pCache);
  44904. }
  44905. }
  44906. /*
  44907. ** Compute the number of pages of cache requested. p->szCache is the
  44908. ** cache size requested by the "PRAGMA cache_size" statement.
  44909. */
  44910. static int numberOfCachePages(PCache *p){
  44911. if( p->szCache>=0 ){
  44912. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  44913. ** suggested cache size is set to N. */
  44914. return p->szCache;
  44915. }else{
  44916. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  44917. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  44918. ** bytes of memory. */
  44919. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  44920. }
  44921. }
  44922. /*************************************************** General Interfaces ******
  44923. **
  44924. ** Initialize and shutdown the page cache subsystem. Neither of these
  44925. ** functions are threadsafe.
  44926. */
  44927. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  44928. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  44929. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  44930. ** built-in default page cache is used instead of the application defined
  44931. ** page cache. */
  44932. sqlite3PCacheSetDefault();
  44933. }
  44934. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  44935. }
  44936. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  44937. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  44938. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  44939. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  44940. }
  44941. }
  44942. /*
  44943. ** Return the size in bytes of a PCache object.
  44944. */
  44945. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  44946. /*
  44947. ** Create a new PCache object. Storage space to hold the object
  44948. ** has already been allocated and is passed in as the p pointer.
  44949. ** The caller discovers how much space needs to be allocated by
  44950. ** calling sqlite3PcacheSize().
  44951. **
  44952. ** szExtra is some extra space allocated for each page. The first
  44953. ** 8 bytes of the extra space will be zeroed as the page is allocated,
  44954. ** but remaining content will be uninitialized. Though it is opaque
  44955. ** to this module, the extra space really ends up being the MemPage
  44956. ** structure in the pager.
  44957. */
  44958. SQLITE_PRIVATE int sqlite3PcacheOpen(
  44959. int szPage, /* Size of every page */
  44960. int szExtra, /* Extra space associated with each page */
  44961. int bPurgeable, /* True if pages are on backing store */
  44962. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  44963. void *pStress, /* Argument to xStress */
  44964. PCache *p /* Preallocated space for the PCache */
  44965. ){
  44966. memset(p, 0, sizeof(PCache));
  44967. p->szPage = 1;
  44968. p->szExtra = szExtra;
  44969. assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
  44970. p->bPurgeable = bPurgeable;
  44971. p->eCreate = 2;
  44972. p->xStress = xStress;
  44973. p->pStress = pStress;
  44974. p->szCache = 100;
  44975. p->szSpill = 1;
  44976. pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
  44977. return sqlite3PcacheSetPageSize(p, szPage);
  44978. }
  44979. /*
  44980. ** Change the page size for PCache object. The caller must ensure that there
  44981. ** are no outstanding page references when this function is called.
  44982. */
  44983. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  44984. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  44985. if( pCache->szPage ){
  44986. sqlite3_pcache *pNew;
  44987. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  44988. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  44989. pCache->bPurgeable
  44990. );
  44991. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  44992. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  44993. if( pCache->pCache ){
  44994. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  44995. }
  44996. pCache->pCache = pNew;
  44997. pCache->szPage = szPage;
  44998. pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
  44999. }
  45000. return SQLITE_OK;
  45001. }
  45002. /*
  45003. ** Try to obtain a page from the cache.
  45004. **
  45005. ** This routine returns a pointer to an sqlite3_pcache_page object if
  45006. ** such an object is already in cache, or if a new one is created.
  45007. ** This routine returns a NULL pointer if the object was not in cache
  45008. ** and could not be created.
  45009. **
  45010. ** The createFlags should be 0 to check for existing pages and should
  45011. ** be 3 (not 1, but 3) to try to create a new page.
  45012. **
  45013. ** If the createFlag is 0, then NULL is always returned if the page
  45014. ** is not already in the cache. If createFlag is 1, then a new page
  45015. ** is created only if that can be done without spilling dirty pages
  45016. ** and without exceeding the cache size limit.
  45017. **
  45018. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  45019. ** initialize the sqlite3_pcache_page object and convert it into a
  45020. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  45021. ** routines are split this way for performance reasons. When separated
  45022. ** they can both (usually) operate without having to push values to
  45023. ** the stack on entry and pop them back off on exit, which saves a
  45024. ** lot of pushing and popping.
  45025. */
  45026. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  45027. PCache *pCache, /* Obtain the page from this cache */
  45028. Pgno pgno, /* Page number to obtain */
  45029. int createFlag /* If true, create page if it does not exist already */
  45030. ){
  45031. int eCreate;
  45032. sqlite3_pcache_page *pRes;
  45033. assert( pCache!=0 );
  45034. assert( pCache->pCache!=0 );
  45035. assert( createFlag==3 || createFlag==0 );
  45036. assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
  45037. /* eCreate defines what to do if the page does not exist.
  45038. ** 0 Do not allocate a new page. (createFlag==0)
  45039. ** 1 Allocate a new page if doing so is inexpensive.
  45040. ** (createFlag==1 AND bPurgeable AND pDirty)
  45041. ** 2 Allocate a new page even it doing so is difficult.
  45042. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  45043. */
  45044. eCreate = createFlag & pCache->eCreate;
  45045. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  45046. assert( createFlag==0 || pCache->eCreate==eCreate );
  45047. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  45048. pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  45049. pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
  45050. createFlag?" create":"",pRes));
  45051. return pRes;
  45052. }
  45053. /*
  45054. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  45055. ** page because no clean pages are available for reuse and the cache
  45056. ** size limit has been reached, then this routine can be invoked to
  45057. ** try harder to allocate a page. This routine might invoke the stress
  45058. ** callback to spill dirty pages to the journal. It will then try to
  45059. ** allocate the new page and will only fail to allocate a new page on
  45060. ** an OOM error.
  45061. **
  45062. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  45063. */
  45064. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  45065. PCache *pCache, /* Obtain the page from this cache */
  45066. Pgno pgno, /* Page number to obtain */
  45067. sqlite3_pcache_page **ppPage /* Write result here */
  45068. ){
  45069. PgHdr *pPg;
  45070. if( pCache->eCreate==2 ) return 0;
  45071. if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
  45072. /* Find a dirty page to write-out and recycle. First try to find a
  45073. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  45074. ** cleared), but if that is not possible settle for any other
  45075. ** unreferenced dirty page.
  45076. **
  45077. ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
  45078. ** flag is currently referenced, then the following may leave pSynced
  45079. ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
  45080. ** cleared). This is Ok, as pSynced is just an optimization. */
  45081. for(pPg=pCache->pSynced;
  45082. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  45083. pPg=pPg->pDirtyPrev
  45084. );
  45085. pCache->pSynced = pPg;
  45086. if( !pPg ){
  45087. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  45088. }
  45089. if( pPg ){
  45090. int rc;
  45091. #ifdef SQLITE_LOG_CACHE_SPILL
  45092. sqlite3_log(SQLITE_FULL,
  45093. "spill page %d making room for %d - cache used: %d/%d",
  45094. pPg->pgno, pgno,
  45095. sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
  45096. numberOfCachePages(pCache));
  45097. #endif
  45098. pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
  45099. rc = pCache->xStress(pCache->pStress, pPg);
  45100. pcacheDump(pCache);
  45101. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  45102. return rc;
  45103. }
  45104. }
  45105. }
  45106. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  45107. return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  45108. }
  45109. /*
  45110. ** This is a helper routine for sqlite3PcacheFetchFinish()
  45111. **
  45112. ** In the uncommon case where the page being fetched has not been
  45113. ** initialized, this routine is invoked to do the initialization.
  45114. ** This routine is broken out into a separate function since it
  45115. ** requires extra stack manipulation that can be avoided in the common
  45116. ** case.
  45117. */
  45118. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  45119. PCache *pCache, /* Obtain the page from this cache */
  45120. Pgno pgno, /* Page number obtained */
  45121. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  45122. ){
  45123. PgHdr *pPgHdr;
  45124. assert( pPage!=0 );
  45125. pPgHdr = (PgHdr*)pPage->pExtra;
  45126. assert( pPgHdr->pPage==0 );
  45127. memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
  45128. pPgHdr->pPage = pPage;
  45129. pPgHdr->pData = pPage->pBuf;
  45130. pPgHdr->pExtra = (void *)&pPgHdr[1];
  45131. memset(pPgHdr->pExtra, 0, 8);
  45132. pPgHdr->pCache = pCache;
  45133. pPgHdr->pgno = pgno;
  45134. pPgHdr->flags = PGHDR_CLEAN;
  45135. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  45136. }
  45137. /*
  45138. ** This routine converts the sqlite3_pcache_page object returned by
  45139. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  45140. ** must be called after sqlite3PcacheFetch() in order to get a usable
  45141. ** result.
  45142. */
  45143. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  45144. PCache *pCache, /* Obtain the page from this cache */
  45145. Pgno pgno, /* Page number obtained */
  45146. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  45147. ){
  45148. PgHdr *pPgHdr;
  45149. assert( pPage!=0 );
  45150. pPgHdr = (PgHdr *)pPage->pExtra;
  45151. if( !pPgHdr->pPage ){
  45152. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  45153. }
  45154. pCache->nRefSum++;
  45155. pPgHdr->nRef++;
  45156. assert( sqlite3PcachePageSanity(pPgHdr) );
  45157. return pPgHdr;
  45158. }
  45159. /*
  45160. ** Decrement the reference count on a page. If the page is clean and the
  45161. ** reference count drops to 0, then it is made eligible for recycling.
  45162. */
  45163. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  45164. assert( p->nRef>0 );
  45165. p->pCache->nRefSum--;
  45166. if( (--p->nRef)==0 ){
  45167. if( p->flags&PGHDR_CLEAN ){
  45168. pcacheUnpin(p);
  45169. }else{
  45170. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  45171. }
  45172. }
  45173. }
  45174. /*
  45175. ** Increase the reference count of a supplied page by 1.
  45176. */
  45177. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  45178. assert(p->nRef>0);
  45179. assert( sqlite3PcachePageSanity(p) );
  45180. p->nRef++;
  45181. p->pCache->nRefSum++;
  45182. }
  45183. /*
  45184. ** Drop a page from the cache. There must be exactly one reference to the
  45185. ** page. This function deletes that reference, so after it returns the
  45186. ** page pointed to by p is invalid.
  45187. */
  45188. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  45189. assert( p->nRef==1 );
  45190. assert( sqlite3PcachePageSanity(p) );
  45191. if( p->flags&PGHDR_DIRTY ){
  45192. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  45193. }
  45194. p->pCache->nRefSum--;
  45195. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  45196. }
  45197. /*
  45198. ** Make sure the page is marked as dirty. If it isn't dirty already,
  45199. ** make it so.
  45200. */
  45201. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  45202. assert( p->nRef>0 );
  45203. assert( sqlite3PcachePageSanity(p) );
  45204. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
  45205. p->flags &= ~PGHDR_DONT_WRITE;
  45206. if( p->flags & PGHDR_CLEAN ){
  45207. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  45208. pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
  45209. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  45210. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  45211. }
  45212. assert( sqlite3PcachePageSanity(p) );
  45213. }
  45214. }
  45215. /*
  45216. ** Make sure the page is marked as clean. If it isn't clean already,
  45217. ** make it so.
  45218. */
  45219. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  45220. assert( sqlite3PcachePageSanity(p) );
  45221. assert( (p->flags & PGHDR_DIRTY)!=0 );
  45222. assert( (p->flags & PGHDR_CLEAN)==0 );
  45223. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  45224. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  45225. p->flags |= PGHDR_CLEAN;
  45226. pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
  45227. assert( sqlite3PcachePageSanity(p) );
  45228. if( p->nRef==0 ){
  45229. pcacheUnpin(p);
  45230. }
  45231. }
  45232. /*
  45233. ** Make every page in the cache clean.
  45234. */
  45235. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  45236. PgHdr *p;
  45237. pcacheTrace(("%p.CLEAN-ALL\n",pCache));
  45238. while( (p = pCache->pDirty)!=0 ){
  45239. sqlite3PcacheMakeClean(p);
  45240. }
  45241. }
  45242. /*
  45243. ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
  45244. */
  45245. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
  45246. PgHdr *p;
  45247. pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
  45248. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  45249. p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  45250. }
  45251. pCache->pSynced = pCache->pDirtyTail;
  45252. }
  45253. /*
  45254. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  45255. */
  45256. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  45257. PgHdr *p;
  45258. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  45259. p->flags &= ~PGHDR_NEED_SYNC;
  45260. }
  45261. pCache->pSynced = pCache->pDirtyTail;
  45262. }
  45263. /*
  45264. ** Change the page number of page p to newPgno.
  45265. */
  45266. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  45267. PCache *pCache = p->pCache;
  45268. assert( p->nRef>0 );
  45269. assert( newPgno>0 );
  45270. assert( sqlite3PcachePageSanity(p) );
  45271. pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
  45272. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  45273. p->pgno = newPgno;
  45274. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  45275. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  45276. }
  45277. }
  45278. /*
  45279. ** Drop every cache entry whose page number is greater than "pgno". The
  45280. ** caller must ensure that there are no outstanding references to any pages
  45281. ** other than page 1 with a page number greater than pgno.
  45282. **
  45283. ** If there is a reference to page 1 and the pgno parameter passed to this
  45284. ** function is 0, then the data area associated with page 1 is zeroed, but
  45285. ** the page object is not dropped.
  45286. */
  45287. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  45288. if( pCache->pCache ){
  45289. PgHdr *p;
  45290. PgHdr *pNext;
  45291. pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
  45292. for(p=pCache->pDirty; p; p=pNext){
  45293. pNext = p->pDirtyNext;
  45294. /* This routine never gets call with a positive pgno except right
  45295. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  45296. ** it must be that pgno==0.
  45297. */
  45298. assert( p->pgno>0 );
  45299. if( p->pgno>pgno ){
  45300. assert( p->flags&PGHDR_DIRTY );
  45301. sqlite3PcacheMakeClean(p);
  45302. }
  45303. }
  45304. if( pgno==0 && pCache->nRefSum ){
  45305. sqlite3_pcache_page *pPage1;
  45306. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  45307. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  45308. ** pCache->nRefSum>0 */
  45309. memset(pPage1->pBuf, 0, pCache->szPage);
  45310. pgno = 1;
  45311. }
  45312. }
  45313. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  45314. }
  45315. }
  45316. /*
  45317. ** Close a cache.
  45318. */
  45319. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  45320. assert( pCache->pCache!=0 );
  45321. pcacheTrace(("%p.CLOSE\n",pCache));
  45322. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  45323. }
  45324. /*
  45325. ** Discard the contents of the cache.
  45326. */
  45327. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  45328. sqlite3PcacheTruncate(pCache, 0);
  45329. }
  45330. /*
  45331. ** Merge two lists of pages connected by pDirty and in pgno order.
  45332. ** Do not bother fixing the pDirtyPrev pointers.
  45333. */
  45334. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  45335. PgHdr result, *pTail;
  45336. pTail = &result;
  45337. assert( pA!=0 && pB!=0 );
  45338. for(;;){
  45339. if( pA->pgno<pB->pgno ){
  45340. pTail->pDirty = pA;
  45341. pTail = pA;
  45342. pA = pA->pDirty;
  45343. if( pA==0 ){
  45344. pTail->pDirty = pB;
  45345. break;
  45346. }
  45347. }else{
  45348. pTail->pDirty = pB;
  45349. pTail = pB;
  45350. pB = pB->pDirty;
  45351. if( pB==0 ){
  45352. pTail->pDirty = pA;
  45353. break;
  45354. }
  45355. }
  45356. }
  45357. return result.pDirty;
  45358. }
  45359. /*
  45360. ** Sort the list of pages in accending order by pgno. Pages are
  45361. ** connected by pDirty pointers. The pDirtyPrev pointers are
  45362. ** corrupted by this sort.
  45363. **
  45364. ** Since there cannot be more than 2^31 distinct pages in a database,
  45365. ** there cannot be more than 31 buckets required by the merge sorter.
  45366. ** One extra bucket is added to catch overflow in case something
  45367. ** ever changes to make the previous sentence incorrect.
  45368. */
  45369. #define N_SORT_BUCKET 32
  45370. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  45371. PgHdr *a[N_SORT_BUCKET], *p;
  45372. int i;
  45373. memset(a, 0, sizeof(a));
  45374. while( pIn ){
  45375. p = pIn;
  45376. pIn = p->pDirty;
  45377. p->pDirty = 0;
  45378. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  45379. if( a[i]==0 ){
  45380. a[i] = p;
  45381. break;
  45382. }else{
  45383. p = pcacheMergeDirtyList(a[i], p);
  45384. a[i] = 0;
  45385. }
  45386. }
  45387. if( NEVER(i==N_SORT_BUCKET-1) ){
  45388. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  45389. ** the input list. But that is impossible.
  45390. */
  45391. a[i] = pcacheMergeDirtyList(a[i], p);
  45392. }
  45393. }
  45394. p = a[0];
  45395. for(i=1; i<N_SORT_BUCKET; i++){
  45396. if( a[i]==0 ) continue;
  45397. p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
  45398. }
  45399. return p;
  45400. }
  45401. /*
  45402. ** Return a list of all dirty pages in the cache, sorted by page number.
  45403. */
  45404. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  45405. PgHdr *p;
  45406. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  45407. p->pDirty = p->pDirtyNext;
  45408. }
  45409. return pcacheSortDirtyList(pCache->pDirty);
  45410. }
  45411. /*
  45412. ** Return the total number of references to all pages held by the cache.
  45413. **
  45414. ** This is not the total number of pages referenced, but the sum of the
  45415. ** reference count for all pages.
  45416. */
  45417. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  45418. return pCache->nRefSum;
  45419. }
  45420. /*
  45421. ** Return the number of references to the page supplied as an argument.
  45422. */
  45423. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  45424. return p->nRef;
  45425. }
  45426. /*
  45427. ** Return the total number of pages in the cache.
  45428. */
  45429. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  45430. assert( pCache->pCache!=0 );
  45431. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  45432. }
  45433. #ifdef SQLITE_TEST
  45434. /*
  45435. ** Get the suggested cache-size value.
  45436. */
  45437. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  45438. return numberOfCachePages(pCache);
  45439. }
  45440. #endif
  45441. /*
  45442. ** Set the suggested cache-size value.
  45443. */
  45444. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  45445. assert( pCache->pCache!=0 );
  45446. pCache->szCache = mxPage;
  45447. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  45448. numberOfCachePages(pCache));
  45449. }
  45450. /*
  45451. ** Set the suggested cache-spill value. Make no changes if if the
  45452. ** argument is zero. Return the effective cache-spill size, which will
  45453. ** be the larger of the szSpill and szCache.
  45454. */
  45455. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
  45456. int res;
  45457. assert( p->pCache!=0 );
  45458. if( mxPage ){
  45459. if( mxPage<0 ){
  45460. mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
  45461. }
  45462. p->szSpill = mxPage;
  45463. }
  45464. res = numberOfCachePages(p);
  45465. if( res<p->szSpill ) res = p->szSpill;
  45466. return res;
  45467. }
  45468. /*
  45469. ** Free up as much memory as possible from the page cache.
  45470. */
  45471. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  45472. assert( pCache->pCache!=0 );
  45473. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  45474. }
  45475. /*
  45476. ** Return the size of the header added by this middleware layer
  45477. ** in the page-cache hierarchy.
  45478. */
  45479. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  45480. /*
  45481. ** Return the number of dirty pages currently in the cache, as a percentage
  45482. ** of the configured cache size.
  45483. */
  45484. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
  45485. PgHdr *pDirty;
  45486. int nDirty = 0;
  45487. int nCache = numberOfCachePages(pCache);
  45488. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
  45489. return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
  45490. }
  45491. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  45492. /*
  45493. ** Return true if there are one or more dirty pages in the cache. Else false.
  45494. */
  45495. SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache){
  45496. return (pCache->pDirty!=0);
  45497. }
  45498. #endif
  45499. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  45500. /*
  45501. ** For all dirty pages currently in the cache, invoke the specified
  45502. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  45503. ** defined.
  45504. */
  45505. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  45506. PgHdr *pDirty;
  45507. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  45508. xIter(pDirty);
  45509. }
  45510. }
  45511. #endif
  45512. /************** End of pcache.c **********************************************/
  45513. /************** Begin file pcache1.c *****************************************/
  45514. /*
  45515. ** 2008 November 05
  45516. **
  45517. ** The author disclaims copyright to this source code. In place of
  45518. ** a legal notice, here is a blessing:
  45519. **
  45520. ** May you do good and not evil.
  45521. ** May you find forgiveness for yourself and forgive others.
  45522. ** May you share freely, never taking more than you give.
  45523. **
  45524. *************************************************************************
  45525. **
  45526. ** This file implements the default page cache implementation (the
  45527. ** sqlite3_pcache interface). It also contains part of the implementation
  45528. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  45529. ** If the default page cache implementation is overridden, then neither of
  45530. ** these two features are available.
  45531. **
  45532. ** A Page cache line looks like this:
  45533. **
  45534. ** -------------------------------------------------------------
  45535. ** | database page content | PgHdr1 | MemPage | PgHdr |
  45536. ** -------------------------------------------------------------
  45537. **
  45538. ** The database page content is up front (so that buffer overreads tend to
  45539. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  45540. ** is the extension added by the btree.c module containing information such
  45541. ** as the database page number and how that database page is used. PgHdr
  45542. ** is added by the pcache.c layer and contains information used to keep track
  45543. ** of which pages are "dirty". PgHdr1 is an extension added by this
  45544. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  45545. ** PgHdr1 contains information needed to look up a page by its page number.
  45546. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  45547. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  45548. **
  45549. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  45550. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  45551. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  45552. ** size can vary according to architecture, compile-time options, and
  45553. ** SQLite library version number.
  45554. **
  45555. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  45556. ** using a separate memory allocation from the database page content. This
  45557. ** seeks to overcome the "clownshoe" problem (also called "internal
  45558. ** fragmentation" in academic literature) of allocating a few bytes more
  45559. ** than a power of two with the memory allocator rounding up to the next
  45560. ** power of two, and leaving the rounded-up space unused.
  45561. **
  45562. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  45563. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  45564. **
  45565. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  45566. ** The btree.c module deals with pointers to MemPage objects.
  45567. **
  45568. ** SOURCE OF PAGE CACHE MEMORY:
  45569. **
  45570. ** Memory for a page might come from any of three sources:
  45571. **
  45572. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  45573. ** (2) Global page-cache memory provided using sqlite3_config() with
  45574. ** SQLITE_CONFIG_PAGECACHE.
  45575. ** (3) PCache-local bulk allocation.
  45576. **
  45577. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  45578. ** that is allocated when the page cache is created. The size of the local
  45579. ** bulk allocation can be adjusted using
  45580. **
  45581. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
  45582. **
  45583. ** If N is positive, then N pages worth of memory are allocated using a single
  45584. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  45585. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  45586. ** for as many pages as can be accomodated.
  45587. **
  45588. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  45589. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  45590. ** memory allocator (1).
  45591. **
  45592. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  45593. ** show that method (3) with N==100 provides about a 5% performance boost for
  45594. ** common workloads.
  45595. */
  45596. /* #include "sqliteInt.h" */
  45597. typedef struct PCache1 PCache1;
  45598. typedef struct PgHdr1 PgHdr1;
  45599. typedef struct PgFreeslot PgFreeslot;
  45600. typedef struct PGroup PGroup;
  45601. /*
  45602. ** Each cache entry is represented by an instance of the following
  45603. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  45604. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  45605. ** in memory.
  45606. */
  45607. struct PgHdr1 {
  45608. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  45609. unsigned int iKey; /* Key value (page number) */
  45610. u8 isBulkLocal; /* This page from bulk local storage */
  45611. u8 isAnchor; /* This is the PGroup.lru element */
  45612. PgHdr1 *pNext; /* Next in hash table chain */
  45613. PCache1 *pCache; /* Cache that currently owns this page */
  45614. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  45615. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  45616. };
  45617. /*
  45618. ** A page is pinned if it is not on the LRU list. To be "pinned" means
  45619. ** that the page is in active use and must not be deallocated.
  45620. */
  45621. #define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
  45622. #define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
  45623. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  45624. ** of one or more PCaches that are able to recycle each other's unpinned
  45625. ** pages when they are under memory pressure. A PGroup is an instance of
  45626. ** the following object.
  45627. **
  45628. ** This page cache implementation works in one of two modes:
  45629. **
  45630. ** (1) Every PCache is the sole member of its own PGroup. There is
  45631. ** one PGroup per PCache.
  45632. **
  45633. ** (2) There is a single global PGroup that all PCaches are a member
  45634. ** of.
  45635. **
  45636. ** Mode 1 uses more memory (since PCache instances are not able to rob
  45637. ** unused pages from other PCaches) but it also operates without a mutex,
  45638. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  45639. ** threadsafe, but recycles pages more efficiently.
  45640. **
  45641. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  45642. ** PGroup which is the pcache1.grp global variable and its mutex is
  45643. ** SQLITE_MUTEX_STATIC_LRU.
  45644. */
  45645. struct PGroup {
  45646. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  45647. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  45648. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  45649. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  45650. unsigned int nPurgeable; /* Number of purgeable pages allocated */
  45651. PgHdr1 lru; /* The beginning and end of the LRU list */
  45652. };
  45653. /* Each page cache is an instance of the following object. Every
  45654. ** open database file (including each in-memory database and each
  45655. ** temporary or transient database) has a single page cache which
  45656. ** is an instance of this object.
  45657. **
  45658. ** Pointers to structures of this type are cast and returned as
  45659. ** opaque sqlite3_pcache* handles.
  45660. */
  45661. struct PCache1 {
  45662. /* Cache configuration parameters. Page size (szPage) and the purgeable
  45663. ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
  45664. ** cache is created and are never changed thereafter. nMax may be
  45665. ** modified at any time by a call to the pcache1Cachesize() method.
  45666. ** The PGroup mutex must be held when accessing nMax.
  45667. */
  45668. PGroup *pGroup; /* PGroup this cache belongs to */
  45669. unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
  45670. int szPage; /* Size of database content section */
  45671. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  45672. int szAlloc; /* Total size of one pcache line */
  45673. int bPurgeable; /* True if cache is purgeable */
  45674. unsigned int nMin; /* Minimum number of pages reserved */
  45675. unsigned int nMax; /* Configured "cache_size" value */
  45676. unsigned int n90pct; /* nMax*9/10 */
  45677. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  45678. /* Hash table of all pages. The following variables may only be accessed
  45679. ** when the accessor is holding the PGroup mutex.
  45680. */
  45681. unsigned int nRecyclable; /* Number of pages in the LRU list */
  45682. unsigned int nPage; /* Total number of pages in apHash */
  45683. unsigned int nHash; /* Number of slots in apHash[] */
  45684. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  45685. PgHdr1 *pFree; /* List of unused pcache-local pages */
  45686. void *pBulk; /* Bulk memory used by pcache-local */
  45687. };
  45688. /*
  45689. ** Free slots in the allocator used to divide up the global page cache
  45690. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  45691. */
  45692. struct PgFreeslot {
  45693. PgFreeslot *pNext; /* Next free slot */
  45694. };
  45695. /*
  45696. ** Global data used by this cache.
  45697. */
  45698. static SQLITE_WSD struct PCacheGlobal {
  45699. PGroup grp; /* The global PGroup for mode (2) */
  45700. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  45701. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  45702. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  45703. ** The nFreeSlot and pFree values do require mutex protection.
  45704. */
  45705. int isInit; /* True if initialized */
  45706. int separateCache; /* Use a new PGroup for each PCache */
  45707. int nInitPage; /* Initial bulk allocation size */
  45708. int szSlot; /* Size of each free slot */
  45709. int nSlot; /* The number of pcache slots */
  45710. int nReserve; /* Try to keep nFreeSlot above this */
  45711. void *pStart, *pEnd; /* Bounds of global page cache memory */
  45712. /* Above requires no mutex. Use mutex below for variable that follow. */
  45713. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  45714. PgFreeslot *pFree; /* Free page blocks */
  45715. int nFreeSlot; /* Number of unused pcache slots */
  45716. /* The following value requires a mutex to change. We skip the mutex on
  45717. ** reading because (1) most platforms read a 32-bit integer atomically and
  45718. ** (2) even if an incorrect value is read, no great harm is done since this
  45719. ** is really just an optimization. */
  45720. int bUnderPressure; /* True if low on PAGECACHE memory */
  45721. } pcache1_g;
  45722. /*
  45723. ** All code in this file should access the global structure above via the
  45724. ** alias "pcache1". This ensures that the WSD emulation is used when
  45725. ** compiling for systems that do not support real WSD.
  45726. */
  45727. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  45728. /*
  45729. ** Macros to enter and leave the PCache LRU mutex.
  45730. */
  45731. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  45732. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  45733. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  45734. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  45735. #else
  45736. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  45737. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  45738. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  45739. #endif
  45740. /******************************************************************************/
  45741. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  45742. /*
  45743. ** This function is called during initialization if a static buffer is
  45744. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  45745. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  45746. ** enough to contain 'n' buffers of 'sz' bytes each.
  45747. **
  45748. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  45749. ** to be serialized already. There is no need for further mutexing.
  45750. */
  45751. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  45752. if( pcache1.isInit ){
  45753. PgFreeslot *p;
  45754. if( pBuf==0 ) sz = n = 0;
  45755. if( n==0 ) sz = 0;
  45756. sz = ROUNDDOWN8(sz);
  45757. pcache1.szSlot = sz;
  45758. pcache1.nSlot = pcache1.nFreeSlot = n;
  45759. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  45760. pcache1.pStart = pBuf;
  45761. pcache1.pFree = 0;
  45762. pcache1.bUnderPressure = 0;
  45763. while( n-- ){
  45764. p = (PgFreeslot*)pBuf;
  45765. p->pNext = pcache1.pFree;
  45766. pcache1.pFree = p;
  45767. pBuf = (void*)&((char*)pBuf)[sz];
  45768. }
  45769. pcache1.pEnd = pBuf;
  45770. }
  45771. }
  45772. /*
  45773. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  45774. ** true if pCache->pFree ends up containing one or more free pages.
  45775. */
  45776. static int pcache1InitBulk(PCache1 *pCache){
  45777. i64 szBulk;
  45778. char *zBulk;
  45779. if( pcache1.nInitPage==0 ) return 0;
  45780. /* Do not bother with a bulk allocation if the cache size very small */
  45781. if( pCache->nMax<3 ) return 0;
  45782. sqlite3BeginBenignMalloc();
  45783. if( pcache1.nInitPage>0 ){
  45784. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  45785. }else{
  45786. szBulk = -1024 * (i64)pcache1.nInitPage;
  45787. }
  45788. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  45789. szBulk = pCache->szAlloc*(i64)pCache->nMax;
  45790. }
  45791. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  45792. sqlite3EndBenignMalloc();
  45793. if( zBulk ){
  45794. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  45795. do{
  45796. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  45797. pX->page.pBuf = zBulk;
  45798. pX->page.pExtra = &pX[1];
  45799. pX->isBulkLocal = 1;
  45800. pX->isAnchor = 0;
  45801. pX->pNext = pCache->pFree;
  45802. pCache->pFree = pX;
  45803. zBulk += pCache->szAlloc;
  45804. }while( --nBulk );
  45805. }
  45806. return pCache->pFree!=0;
  45807. }
  45808. /*
  45809. ** Malloc function used within this file to allocate space from the buffer
  45810. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  45811. ** such buffer exists or there is no space left in it, this function falls
  45812. ** back to sqlite3Malloc().
  45813. **
  45814. ** Multiple threads can run this routine at the same time. Global variables
  45815. ** in pcache1 need to be protected via mutex.
  45816. */
  45817. static void *pcache1Alloc(int nByte){
  45818. void *p = 0;
  45819. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  45820. if( nByte<=pcache1.szSlot ){
  45821. sqlite3_mutex_enter(pcache1.mutex);
  45822. p = (PgHdr1 *)pcache1.pFree;
  45823. if( p ){
  45824. pcache1.pFree = pcache1.pFree->pNext;
  45825. pcache1.nFreeSlot--;
  45826. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  45827. assert( pcache1.nFreeSlot>=0 );
  45828. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  45829. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  45830. }
  45831. sqlite3_mutex_leave(pcache1.mutex);
  45832. }
  45833. if( p==0 ){
  45834. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  45835. ** it from sqlite3Malloc instead.
  45836. */
  45837. p = sqlite3Malloc(nByte);
  45838. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  45839. if( p ){
  45840. int sz = sqlite3MallocSize(p);
  45841. sqlite3_mutex_enter(pcache1.mutex);
  45842. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  45843. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  45844. sqlite3_mutex_leave(pcache1.mutex);
  45845. }
  45846. #endif
  45847. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  45848. }
  45849. return p;
  45850. }
  45851. /*
  45852. ** Free an allocated buffer obtained from pcache1Alloc().
  45853. */
  45854. static void pcache1Free(void *p){
  45855. if( p==0 ) return;
  45856. if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
  45857. PgFreeslot *pSlot;
  45858. sqlite3_mutex_enter(pcache1.mutex);
  45859. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  45860. pSlot = (PgFreeslot*)p;
  45861. pSlot->pNext = pcache1.pFree;
  45862. pcache1.pFree = pSlot;
  45863. pcache1.nFreeSlot++;
  45864. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  45865. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  45866. sqlite3_mutex_leave(pcache1.mutex);
  45867. }else{
  45868. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  45869. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  45870. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  45871. {
  45872. int nFreed = 0;
  45873. nFreed = sqlite3MallocSize(p);
  45874. sqlite3_mutex_enter(pcache1.mutex);
  45875. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  45876. sqlite3_mutex_leave(pcache1.mutex);
  45877. }
  45878. #endif
  45879. sqlite3_free(p);
  45880. }
  45881. }
  45882. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  45883. /*
  45884. ** Return the size of a pcache allocation
  45885. */
  45886. static int pcache1MemSize(void *p){
  45887. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  45888. return pcache1.szSlot;
  45889. }else{
  45890. int iSize;
  45891. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  45892. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  45893. iSize = sqlite3MallocSize(p);
  45894. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  45895. return iSize;
  45896. }
  45897. }
  45898. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  45899. /*
  45900. ** Allocate a new page object initially associated with cache pCache.
  45901. */
  45902. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  45903. PgHdr1 *p = 0;
  45904. void *pPg;
  45905. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  45906. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  45907. p = pCache->pFree;
  45908. pCache->pFree = p->pNext;
  45909. p->pNext = 0;
  45910. }else{
  45911. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  45912. /* The group mutex must be released before pcache1Alloc() is called. This
  45913. ** is because it might call sqlite3_release_memory(), which assumes that
  45914. ** this mutex is not held. */
  45915. assert( pcache1.separateCache==0 );
  45916. assert( pCache->pGroup==&pcache1.grp );
  45917. pcache1LeaveMutex(pCache->pGroup);
  45918. #endif
  45919. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  45920. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  45921. pPg = pcache1Alloc(pCache->szPage);
  45922. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  45923. if( !pPg || !p ){
  45924. pcache1Free(pPg);
  45925. sqlite3_free(p);
  45926. pPg = 0;
  45927. }
  45928. #else
  45929. pPg = pcache1Alloc(pCache->szAlloc);
  45930. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  45931. #endif
  45932. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  45933. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  45934. pcache1EnterMutex(pCache->pGroup);
  45935. #endif
  45936. if( pPg==0 ) return 0;
  45937. p->page.pBuf = pPg;
  45938. p->page.pExtra = &p[1];
  45939. p->isBulkLocal = 0;
  45940. p->isAnchor = 0;
  45941. }
  45942. (*pCache->pnPurgeable)++;
  45943. return p;
  45944. }
  45945. /*
  45946. ** Free a page object allocated by pcache1AllocPage().
  45947. */
  45948. static void pcache1FreePage(PgHdr1 *p){
  45949. PCache1 *pCache;
  45950. assert( p!=0 );
  45951. pCache = p->pCache;
  45952. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  45953. if( p->isBulkLocal ){
  45954. p->pNext = pCache->pFree;
  45955. pCache->pFree = p;
  45956. }else{
  45957. pcache1Free(p->page.pBuf);
  45958. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  45959. sqlite3_free(p);
  45960. #endif
  45961. }
  45962. (*pCache->pnPurgeable)--;
  45963. }
  45964. /*
  45965. ** Malloc function used by SQLite to obtain space from the buffer configured
  45966. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  45967. ** exists, this function falls back to sqlite3Malloc().
  45968. */
  45969. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  45970. return pcache1Alloc(sz);
  45971. }
  45972. /*
  45973. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  45974. */
  45975. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  45976. pcache1Free(p);
  45977. }
  45978. /*
  45979. ** Return true if it desirable to avoid allocating a new page cache
  45980. ** entry.
  45981. **
  45982. ** If memory was allocated specifically to the page cache using
  45983. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  45984. ** it is desirable to avoid allocating a new page cache entry because
  45985. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  45986. ** for all page cache needs and we should not need to spill the
  45987. ** allocation onto the heap.
  45988. **
  45989. ** Or, the heap is used for all page cache memory but the heap is
  45990. ** under memory pressure, then again it is desirable to avoid
  45991. ** allocating a new page cache entry in order to avoid stressing
  45992. ** the heap even further.
  45993. */
  45994. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  45995. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  45996. return pcache1.bUnderPressure;
  45997. }else{
  45998. return sqlite3HeapNearlyFull();
  45999. }
  46000. }
  46001. /******************************************************************************/
  46002. /******** General Implementation Functions ************************************/
  46003. /*
  46004. ** This function is used to resize the hash table used by the cache passed
  46005. ** as the first argument.
  46006. **
  46007. ** The PCache mutex must be held when this function is called.
  46008. */
  46009. static void pcache1ResizeHash(PCache1 *p){
  46010. PgHdr1 **apNew;
  46011. unsigned int nNew;
  46012. unsigned int i;
  46013. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  46014. nNew = p->nHash*2;
  46015. if( nNew<256 ){
  46016. nNew = 256;
  46017. }
  46018. pcache1LeaveMutex(p->pGroup);
  46019. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  46020. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  46021. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  46022. pcache1EnterMutex(p->pGroup);
  46023. if( apNew ){
  46024. for(i=0; i<p->nHash; i++){
  46025. PgHdr1 *pPage;
  46026. PgHdr1 *pNext = p->apHash[i];
  46027. while( (pPage = pNext)!=0 ){
  46028. unsigned int h = pPage->iKey % nNew;
  46029. pNext = pPage->pNext;
  46030. pPage->pNext = apNew[h];
  46031. apNew[h] = pPage;
  46032. }
  46033. }
  46034. sqlite3_free(p->apHash);
  46035. p->apHash = apNew;
  46036. p->nHash = nNew;
  46037. }
  46038. }
  46039. /*
  46040. ** This function is used internally to remove the page pPage from the
  46041. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  46042. ** LRU list, then this function is a no-op.
  46043. **
  46044. ** The PGroup mutex must be held when this function is called.
  46045. */
  46046. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  46047. assert( pPage!=0 );
  46048. assert( PAGE_IS_UNPINNED(pPage) );
  46049. assert( pPage->pLruNext );
  46050. assert( pPage->pLruPrev );
  46051. assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
  46052. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  46053. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  46054. pPage->pLruNext = 0;
  46055. pPage->pLruPrev = 0;
  46056. assert( pPage->isAnchor==0 );
  46057. assert( pPage->pCache->pGroup->lru.isAnchor==1 );
  46058. pPage->pCache->nRecyclable--;
  46059. return pPage;
  46060. }
  46061. /*
  46062. ** Remove the page supplied as an argument from the hash table
  46063. ** (PCache1.apHash structure) that it is currently stored in.
  46064. ** Also free the page if freePage is true.
  46065. **
  46066. ** The PGroup mutex must be held when this function is called.
  46067. */
  46068. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  46069. unsigned int h;
  46070. PCache1 *pCache = pPage->pCache;
  46071. PgHdr1 **pp;
  46072. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  46073. h = pPage->iKey % pCache->nHash;
  46074. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  46075. *pp = (*pp)->pNext;
  46076. pCache->nPage--;
  46077. if( freeFlag ) pcache1FreePage(pPage);
  46078. }
  46079. /*
  46080. ** If there are currently more than nMaxPage pages allocated, try
  46081. ** to recycle pages to reduce the number allocated to nMaxPage.
  46082. */
  46083. static void pcache1EnforceMaxPage(PCache1 *pCache){
  46084. PGroup *pGroup = pCache->pGroup;
  46085. PgHdr1 *p;
  46086. assert( sqlite3_mutex_held(pGroup->mutex) );
  46087. while( pGroup->nPurgeable>pGroup->nMaxPage
  46088. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  46089. ){
  46090. assert( p->pCache->pGroup==pGroup );
  46091. assert( PAGE_IS_UNPINNED(p) );
  46092. pcache1PinPage(p);
  46093. pcache1RemoveFromHash(p, 1);
  46094. }
  46095. if( pCache->nPage==0 && pCache->pBulk ){
  46096. sqlite3_free(pCache->pBulk);
  46097. pCache->pBulk = pCache->pFree = 0;
  46098. }
  46099. }
  46100. /*
  46101. ** Discard all pages from cache pCache with a page number (key value)
  46102. ** greater than or equal to iLimit. Any pinned pages that meet this
  46103. ** criteria are unpinned before they are discarded.
  46104. **
  46105. ** The PCache mutex must be held when this function is called.
  46106. */
  46107. static void pcache1TruncateUnsafe(
  46108. PCache1 *pCache, /* The cache to truncate */
  46109. unsigned int iLimit /* Drop pages with this pgno or larger */
  46110. ){
  46111. TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
  46112. unsigned int h, iStop;
  46113. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  46114. assert( pCache->iMaxKey >= iLimit );
  46115. assert( pCache->nHash > 0 );
  46116. if( pCache->iMaxKey - iLimit < pCache->nHash ){
  46117. /* If we are just shaving the last few pages off the end of the
  46118. ** cache, then there is no point in scanning the entire hash table.
  46119. ** Only scan those hash slots that might contain pages that need to
  46120. ** be removed. */
  46121. h = iLimit % pCache->nHash;
  46122. iStop = pCache->iMaxKey % pCache->nHash;
  46123. TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
  46124. }else{
  46125. /* This is the general case where many pages are being removed.
  46126. ** It is necessary to scan the entire hash table */
  46127. h = pCache->nHash/2;
  46128. iStop = h - 1;
  46129. }
  46130. for(;;){
  46131. PgHdr1 **pp;
  46132. PgHdr1 *pPage;
  46133. assert( h<pCache->nHash );
  46134. pp = &pCache->apHash[h];
  46135. while( (pPage = *pp)!=0 ){
  46136. if( pPage->iKey>=iLimit ){
  46137. pCache->nPage--;
  46138. *pp = pPage->pNext;
  46139. if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
  46140. pcache1FreePage(pPage);
  46141. }else{
  46142. pp = &pPage->pNext;
  46143. TESTONLY( if( nPage>=0 ) nPage++; )
  46144. }
  46145. }
  46146. if( h==iStop ) break;
  46147. h = (h+1) % pCache->nHash;
  46148. }
  46149. assert( nPage<0 || pCache->nPage==(unsigned)nPage );
  46150. }
  46151. /******************************************************************************/
  46152. /******** sqlite3_pcache Methods **********************************************/
  46153. /*
  46154. ** Implementation of the sqlite3_pcache.xInit method.
  46155. */
  46156. static int pcache1Init(void *NotUsed){
  46157. UNUSED_PARAMETER(NotUsed);
  46158. assert( pcache1.isInit==0 );
  46159. memset(&pcache1, 0, sizeof(pcache1));
  46160. /*
  46161. ** The pcache1.separateCache variable is true if each PCache has its own
  46162. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  46163. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  46164. **
  46165. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  46166. **
  46167. ** * Use a unified cache in single-threaded applications that have
  46168. ** configured a start-time buffer for use as page-cache memory using
  46169. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  46170. ** pBuf argument.
  46171. **
  46172. ** * Otherwise use separate caches (mode-1)
  46173. */
  46174. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  46175. pcache1.separateCache = 0;
  46176. #elif SQLITE_THREADSAFE
  46177. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  46178. || sqlite3GlobalConfig.bCoreMutex>0;
  46179. #else
  46180. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  46181. #endif
  46182. #if SQLITE_THREADSAFE
  46183. if( sqlite3GlobalConfig.bCoreMutex ){
  46184. pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
  46185. pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
  46186. }
  46187. #endif
  46188. if( pcache1.separateCache
  46189. && sqlite3GlobalConfig.nPage!=0
  46190. && sqlite3GlobalConfig.pPage==0
  46191. ){
  46192. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  46193. }else{
  46194. pcache1.nInitPage = 0;
  46195. }
  46196. pcache1.grp.mxPinned = 10;
  46197. pcache1.isInit = 1;
  46198. return SQLITE_OK;
  46199. }
  46200. /*
  46201. ** Implementation of the sqlite3_pcache.xShutdown method.
  46202. ** Note that the static mutex allocated in xInit does
  46203. ** not need to be freed.
  46204. */
  46205. static void pcache1Shutdown(void *NotUsed){
  46206. UNUSED_PARAMETER(NotUsed);
  46207. assert( pcache1.isInit!=0 );
  46208. memset(&pcache1, 0, sizeof(pcache1));
  46209. }
  46210. /* forward declaration */
  46211. static void pcache1Destroy(sqlite3_pcache *p);
  46212. /*
  46213. ** Implementation of the sqlite3_pcache.xCreate method.
  46214. **
  46215. ** Allocate a new cache.
  46216. */
  46217. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  46218. PCache1 *pCache; /* The newly created page cache */
  46219. PGroup *pGroup; /* The group the new page cache will belong to */
  46220. int sz; /* Bytes of memory required to allocate the new cache */
  46221. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  46222. assert( szExtra < 300 );
  46223. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  46224. pCache = (PCache1 *)sqlite3MallocZero(sz);
  46225. if( pCache ){
  46226. if( pcache1.separateCache ){
  46227. pGroup = (PGroup*)&pCache[1];
  46228. pGroup->mxPinned = 10;
  46229. }else{
  46230. pGroup = &pcache1.grp;
  46231. }
  46232. if( pGroup->lru.isAnchor==0 ){
  46233. pGroup->lru.isAnchor = 1;
  46234. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  46235. }
  46236. pCache->pGroup = pGroup;
  46237. pCache->szPage = szPage;
  46238. pCache->szExtra = szExtra;
  46239. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  46240. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  46241. pcache1EnterMutex(pGroup);
  46242. pcache1ResizeHash(pCache);
  46243. if( bPurgeable ){
  46244. pCache->nMin = 10;
  46245. pGroup->nMinPage += pCache->nMin;
  46246. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  46247. pCache->pnPurgeable = &pGroup->nPurgeable;
  46248. }else{
  46249. static unsigned int dummyCurrentPage;
  46250. pCache->pnPurgeable = &dummyCurrentPage;
  46251. }
  46252. pcache1LeaveMutex(pGroup);
  46253. if( pCache->nHash==0 ){
  46254. pcache1Destroy((sqlite3_pcache*)pCache);
  46255. pCache = 0;
  46256. }
  46257. }
  46258. return (sqlite3_pcache *)pCache;
  46259. }
  46260. /*
  46261. ** Implementation of the sqlite3_pcache.xCachesize method.
  46262. **
  46263. ** Configure the cache_size limit for a cache.
  46264. */
  46265. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  46266. PCache1 *pCache = (PCache1 *)p;
  46267. if( pCache->bPurgeable ){
  46268. PGroup *pGroup = pCache->pGroup;
  46269. pcache1EnterMutex(pGroup);
  46270. pGroup->nMaxPage += (nMax - pCache->nMax);
  46271. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  46272. pCache->nMax = nMax;
  46273. pCache->n90pct = pCache->nMax*9/10;
  46274. pcache1EnforceMaxPage(pCache);
  46275. pcache1LeaveMutex(pGroup);
  46276. }
  46277. }
  46278. /*
  46279. ** Implementation of the sqlite3_pcache.xShrink method.
  46280. **
  46281. ** Free up as much memory as possible.
  46282. */
  46283. static void pcache1Shrink(sqlite3_pcache *p){
  46284. PCache1 *pCache = (PCache1*)p;
  46285. if( pCache->bPurgeable ){
  46286. PGroup *pGroup = pCache->pGroup;
  46287. int savedMaxPage;
  46288. pcache1EnterMutex(pGroup);
  46289. savedMaxPage = pGroup->nMaxPage;
  46290. pGroup->nMaxPage = 0;
  46291. pcache1EnforceMaxPage(pCache);
  46292. pGroup->nMaxPage = savedMaxPage;
  46293. pcache1LeaveMutex(pGroup);
  46294. }
  46295. }
  46296. /*
  46297. ** Implementation of the sqlite3_pcache.xPagecount method.
  46298. */
  46299. static int pcache1Pagecount(sqlite3_pcache *p){
  46300. int n;
  46301. PCache1 *pCache = (PCache1*)p;
  46302. pcache1EnterMutex(pCache->pGroup);
  46303. n = pCache->nPage;
  46304. pcache1LeaveMutex(pCache->pGroup);
  46305. return n;
  46306. }
  46307. /*
  46308. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  46309. ** in the header of the pcache1Fetch() procedure.
  46310. **
  46311. ** This steps are broken out into a separate procedure because they are
  46312. ** usually not needed, and by avoiding the stack initialization required
  46313. ** for these steps, the main pcache1Fetch() procedure can run faster.
  46314. */
  46315. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  46316. PCache1 *pCache,
  46317. unsigned int iKey,
  46318. int createFlag
  46319. ){
  46320. unsigned int nPinned;
  46321. PGroup *pGroup = pCache->pGroup;
  46322. PgHdr1 *pPage = 0;
  46323. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  46324. assert( pCache->nPage >= pCache->nRecyclable );
  46325. nPinned = pCache->nPage - pCache->nRecyclable;
  46326. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  46327. assert( pCache->n90pct == pCache->nMax*9/10 );
  46328. if( createFlag==1 && (
  46329. nPinned>=pGroup->mxPinned
  46330. || nPinned>=pCache->n90pct
  46331. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  46332. )){
  46333. return 0;
  46334. }
  46335. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  46336. assert( pCache->nHash>0 && pCache->apHash );
  46337. /* Step 4. Try to recycle a page. */
  46338. if( pCache->bPurgeable
  46339. && !pGroup->lru.pLruPrev->isAnchor
  46340. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  46341. ){
  46342. PCache1 *pOther;
  46343. pPage = pGroup->lru.pLruPrev;
  46344. assert( PAGE_IS_UNPINNED(pPage) );
  46345. pcache1RemoveFromHash(pPage, 0);
  46346. pcache1PinPage(pPage);
  46347. pOther = pPage->pCache;
  46348. if( pOther->szAlloc != pCache->szAlloc ){
  46349. pcache1FreePage(pPage);
  46350. pPage = 0;
  46351. }else{
  46352. pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
  46353. }
  46354. }
  46355. /* Step 5. If a usable page buffer has still not been found,
  46356. ** attempt to allocate a new one.
  46357. */
  46358. if( !pPage ){
  46359. pPage = pcache1AllocPage(pCache, createFlag==1);
  46360. }
  46361. if( pPage ){
  46362. unsigned int h = iKey % pCache->nHash;
  46363. pCache->nPage++;
  46364. pPage->iKey = iKey;
  46365. pPage->pNext = pCache->apHash[h];
  46366. pPage->pCache = pCache;
  46367. pPage->pLruPrev = 0;
  46368. pPage->pLruNext = 0;
  46369. *(void **)pPage->page.pExtra = 0;
  46370. pCache->apHash[h] = pPage;
  46371. if( iKey>pCache->iMaxKey ){
  46372. pCache->iMaxKey = iKey;
  46373. }
  46374. }
  46375. return pPage;
  46376. }
  46377. /*
  46378. ** Implementation of the sqlite3_pcache.xFetch method.
  46379. **
  46380. ** Fetch a page by key value.
  46381. **
  46382. ** Whether or not a new page may be allocated by this function depends on
  46383. ** the value of the createFlag argument. 0 means do not allocate a new
  46384. ** page. 1 means allocate a new page if space is easily available. 2
  46385. ** means to try really hard to allocate a new page.
  46386. **
  46387. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  46388. ** database) there is really no difference between createFlag 1 and 2. So
  46389. ** the calling function (pcache.c) will never have a createFlag of 1 on
  46390. ** a non-purgeable cache.
  46391. **
  46392. ** There are three different approaches to obtaining space for a page,
  46393. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  46394. **
  46395. ** 1. Regardless of the value of createFlag, the cache is searched for a
  46396. ** copy of the requested page. If one is found, it is returned.
  46397. **
  46398. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  46399. ** returned.
  46400. **
  46401. ** 3. If createFlag is 1, and the page is not already in the cache, then
  46402. ** return NULL (do not allocate a new page) if any of the following
  46403. ** conditions are true:
  46404. **
  46405. ** (a) the number of pages pinned by the cache is greater than
  46406. ** PCache1.nMax, or
  46407. **
  46408. ** (b) the number of pages pinned by the cache is greater than
  46409. ** the sum of nMax for all purgeable caches, less the sum of
  46410. ** nMin for all other purgeable caches, or
  46411. **
  46412. ** 4. If none of the first three conditions apply and the cache is marked
  46413. ** as purgeable, and if one of the following is true:
  46414. **
  46415. ** (a) The number of pages allocated for the cache is already
  46416. ** PCache1.nMax, or
  46417. **
  46418. ** (b) The number of pages allocated for all purgeable caches is
  46419. ** already equal to or greater than the sum of nMax for all
  46420. ** purgeable caches,
  46421. **
  46422. ** (c) The system is under memory pressure and wants to avoid
  46423. ** unnecessary pages cache entry allocations
  46424. **
  46425. ** then attempt to recycle a page from the LRU list. If it is the right
  46426. ** size, return the recycled buffer. Otherwise, free the buffer and
  46427. ** proceed to step 5.
  46428. **
  46429. ** 5. Otherwise, allocate and return a new page buffer.
  46430. **
  46431. ** There are two versions of this routine. pcache1FetchWithMutex() is
  46432. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  46433. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  46434. ** invokes the appropriate routine.
  46435. */
  46436. static PgHdr1 *pcache1FetchNoMutex(
  46437. sqlite3_pcache *p,
  46438. unsigned int iKey,
  46439. int createFlag
  46440. ){
  46441. PCache1 *pCache = (PCache1 *)p;
  46442. PgHdr1 *pPage = 0;
  46443. /* Step 1: Search the hash table for an existing entry. */
  46444. pPage = pCache->apHash[iKey % pCache->nHash];
  46445. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  46446. /* Step 2: If the page was found in the hash table, then return it.
  46447. ** If the page was not in the hash table and createFlag is 0, abort.
  46448. ** Otherwise (page not in hash and createFlag!=0) continue with
  46449. ** subsequent steps to try to create the page. */
  46450. if( pPage ){
  46451. if( PAGE_IS_UNPINNED(pPage) ){
  46452. return pcache1PinPage(pPage);
  46453. }else{
  46454. return pPage;
  46455. }
  46456. }else if( createFlag ){
  46457. /* Steps 3, 4, and 5 implemented by this subroutine */
  46458. return pcache1FetchStage2(pCache, iKey, createFlag);
  46459. }else{
  46460. return 0;
  46461. }
  46462. }
  46463. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  46464. static PgHdr1 *pcache1FetchWithMutex(
  46465. sqlite3_pcache *p,
  46466. unsigned int iKey,
  46467. int createFlag
  46468. ){
  46469. PCache1 *pCache = (PCache1 *)p;
  46470. PgHdr1 *pPage;
  46471. pcache1EnterMutex(pCache->pGroup);
  46472. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  46473. assert( pPage==0 || pCache->iMaxKey>=iKey );
  46474. pcache1LeaveMutex(pCache->pGroup);
  46475. return pPage;
  46476. }
  46477. #endif
  46478. static sqlite3_pcache_page *pcache1Fetch(
  46479. sqlite3_pcache *p,
  46480. unsigned int iKey,
  46481. int createFlag
  46482. ){
  46483. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  46484. PCache1 *pCache = (PCache1 *)p;
  46485. #endif
  46486. assert( offsetof(PgHdr1,page)==0 );
  46487. assert( pCache->bPurgeable || createFlag!=1 );
  46488. assert( pCache->bPurgeable || pCache->nMin==0 );
  46489. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  46490. assert( pCache->nMin==0 || pCache->bPurgeable );
  46491. assert( pCache->nHash>0 );
  46492. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  46493. if( pCache->pGroup->mutex ){
  46494. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  46495. }else
  46496. #endif
  46497. {
  46498. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  46499. }
  46500. }
  46501. /*
  46502. ** Implementation of the sqlite3_pcache.xUnpin method.
  46503. **
  46504. ** Mark a page as unpinned (eligible for asynchronous recycling).
  46505. */
  46506. static void pcache1Unpin(
  46507. sqlite3_pcache *p,
  46508. sqlite3_pcache_page *pPg,
  46509. int reuseUnlikely
  46510. ){
  46511. PCache1 *pCache = (PCache1 *)p;
  46512. PgHdr1 *pPage = (PgHdr1 *)pPg;
  46513. PGroup *pGroup = pCache->pGroup;
  46514. assert( pPage->pCache==pCache );
  46515. pcache1EnterMutex(pGroup);
  46516. /* It is an error to call this function if the page is already
  46517. ** part of the PGroup LRU list.
  46518. */
  46519. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  46520. assert( PAGE_IS_PINNED(pPage) );
  46521. if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
  46522. pcache1RemoveFromHash(pPage, 1);
  46523. }else{
  46524. /* Add the page to the PGroup LRU list. */
  46525. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  46526. pPage->pLruPrev = &pGroup->lru;
  46527. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  46528. *ppFirst = pPage;
  46529. pCache->nRecyclable++;
  46530. }
  46531. pcache1LeaveMutex(pCache->pGroup);
  46532. }
  46533. /*
  46534. ** Implementation of the sqlite3_pcache.xRekey method.
  46535. */
  46536. static void pcache1Rekey(
  46537. sqlite3_pcache *p,
  46538. sqlite3_pcache_page *pPg,
  46539. unsigned int iOld,
  46540. unsigned int iNew
  46541. ){
  46542. PCache1 *pCache = (PCache1 *)p;
  46543. PgHdr1 *pPage = (PgHdr1 *)pPg;
  46544. PgHdr1 **pp;
  46545. unsigned int h;
  46546. assert( pPage->iKey==iOld );
  46547. assert( pPage->pCache==pCache );
  46548. pcache1EnterMutex(pCache->pGroup);
  46549. h = iOld%pCache->nHash;
  46550. pp = &pCache->apHash[h];
  46551. while( (*pp)!=pPage ){
  46552. pp = &(*pp)->pNext;
  46553. }
  46554. *pp = pPage->pNext;
  46555. h = iNew%pCache->nHash;
  46556. pPage->iKey = iNew;
  46557. pPage->pNext = pCache->apHash[h];
  46558. pCache->apHash[h] = pPage;
  46559. if( iNew>pCache->iMaxKey ){
  46560. pCache->iMaxKey = iNew;
  46561. }
  46562. pcache1LeaveMutex(pCache->pGroup);
  46563. }
  46564. /*
  46565. ** Implementation of the sqlite3_pcache.xTruncate method.
  46566. **
  46567. ** Discard all unpinned pages in the cache with a page number equal to
  46568. ** or greater than parameter iLimit. Any pinned pages with a page number
  46569. ** equal to or greater than iLimit are implicitly unpinned.
  46570. */
  46571. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  46572. PCache1 *pCache = (PCache1 *)p;
  46573. pcache1EnterMutex(pCache->pGroup);
  46574. if( iLimit<=pCache->iMaxKey ){
  46575. pcache1TruncateUnsafe(pCache, iLimit);
  46576. pCache->iMaxKey = iLimit-1;
  46577. }
  46578. pcache1LeaveMutex(pCache->pGroup);
  46579. }
  46580. /*
  46581. ** Implementation of the sqlite3_pcache.xDestroy method.
  46582. **
  46583. ** Destroy a cache allocated using pcache1Create().
  46584. */
  46585. static void pcache1Destroy(sqlite3_pcache *p){
  46586. PCache1 *pCache = (PCache1 *)p;
  46587. PGroup *pGroup = pCache->pGroup;
  46588. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  46589. pcache1EnterMutex(pGroup);
  46590. if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
  46591. assert( pGroup->nMaxPage >= pCache->nMax );
  46592. pGroup->nMaxPage -= pCache->nMax;
  46593. assert( pGroup->nMinPage >= pCache->nMin );
  46594. pGroup->nMinPage -= pCache->nMin;
  46595. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  46596. pcache1EnforceMaxPage(pCache);
  46597. pcache1LeaveMutex(pGroup);
  46598. sqlite3_free(pCache->pBulk);
  46599. sqlite3_free(pCache->apHash);
  46600. sqlite3_free(pCache);
  46601. }
  46602. /*
  46603. ** This function is called during initialization (sqlite3_initialize()) to
  46604. ** install the default pluggable cache module, assuming the user has not
  46605. ** already provided an alternative.
  46606. */
  46607. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  46608. static const sqlite3_pcache_methods2 defaultMethods = {
  46609. 1, /* iVersion */
  46610. 0, /* pArg */
  46611. pcache1Init, /* xInit */
  46612. pcache1Shutdown, /* xShutdown */
  46613. pcache1Create, /* xCreate */
  46614. pcache1Cachesize, /* xCachesize */
  46615. pcache1Pagecount, /* xPagecount */
  46616. pcache1Fetch, /* xFetch */
  46617. pcache1Unpin, /* xUnpin */
  46618. pcache1Rekey, /* xRekey */
  46619. pcache1Truncate, /* xTruncate */
  46620. pcache1Destroy, /* xDestroy */
  46621. pcache1Shrink /* xShrink */
  46622. };
  46623. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  46624. }
  46625. /*
  46626. ** Return the size of the header on each page of this PCACHE implementation.
  46627. */
  46628. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  46629. /*
  46630. ** Return the global mutex used by this PCACHE implementation. The
  46631. ** sqlite3_status() routine needs access to this mutex.
  46632. */
  46633. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  46634. return pcache1.mutex;
  46635. }
  46636. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  46637. /*
  46638. ** This function is called to free superfluous dynamically allocated memory
  46639. ** held by the pager system. Memory in use by any SQLite pager allocated
  46640. ** by the current thread may be sqlite3_free()ed.
  46641. **
  46642. ** nReq is the number of bytes of memory required. Once this much has
  46643. ** been released, the function returns. The return value is the total number
  46644. ** of bytes of memory released.
  46645. */
  46646. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  46647. int nFree = 0;
  46648. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  46649. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  46650. if( sqlite3GlobalConfig.pPage==0 ){
  46651. PgHdr1 *p;
  46652. pcache1EnterMutex(&pcache1.grp);
  46653. while( (nReq<0 || nFree<nReq)
  46654. && (p=pcache1.grp.lru.pLruPrev)!=0
  46655. && p->isAnchor==0
  46656. ){
  46657. nFree += pcache1MemSize(p->page.pBuf);
  46658. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  46659. nFree += sqlite3MemSize(p);
  46660. #endif
  46661. assert( PAGE_IS_UNPINNED(p) );
  46662. pcache1PinPage(p);
  46663. pcache1RemoveFromHash(p, 1);
  46664. }
  46665. pcache1LeaveMutex(&pcache1.grp);
  46666. }
  46667. return nFree;
  46668. }
  46669. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  46670. #ifdef SQLITE_TEST
  46671. /*
  46672. ** This function is used by test procedures to inspect the internal state
  46673. ** of the global cache.
  46674. */
  46675. SQLITE_PRIVATE void sqlite3PcacheStats(
  46676. int *pnCurrent, /* OUT: Total number of pages cached */
  46677. int *pnMax, /* OUT: Global maximum cache size */
  46678. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  46679. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  46680. ){
  46681. PgHdr1 *p;
  46682. int nRecyclable = 0;
  46683. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  46684. assert( PAGE_IS_UNPINNED(p) );
  46685. nRecyclable++;
  46686. }
  46687. *pnCurrent = pcache1.grp.nPurgeable;
  46688. *pnMax = (int)pcache1.grp.nMaxPage;
  46689. *pnMin = (int)pcache1.grp.nMinPage;
  46690. *pnRecyclable = nRecyclable;
  46691. }
  46692. #endif
  46693. /************** End of pcache1.c *********************************************/
  46694. /************** Begin file rowset.c ******************************************/
  46695. /*
  46696. ** 2008 December 3
  46697. **
  46698. ** The author disclaims copyright to this source code. In place of
  46699. ** a legal notice, here is a blessing:
  46700. **
  46701. ** May you do good and not evil.
  46702. ** May you find forgiveness for yourself and forgive others.
  46703. ** May you share freely, never taking more than you give.
  46704. **
  46705. *************************************************************************
  46706. **
  46707. ** This module implements an object we call a "RowSet".
  46708. **
  46709. ** The RowSet object is a collection of rowids. Rowids
  46710. ** are inserted into the RowSet in an arbitrary order. Inserts
  46711. ** can be intermixed with tests to see if a given rowid has been
  46712. ** previously inserted into the RowSet.
  46713. **
  46714. ** After all inserts are finished, it is possible to extract the
  46715. ** elements of the RowSet in sorted order. Once this extraction
  46716. ** process has started, no new elements may be inserted.
  46717. **
  46718. ** Hence, the primitive operations for a RowSet are:
  46719. **
  46720. ** CREATE
  46721. ** INSERT
  46722. ** TEST
  46723. ** SMALLEST
  46724. ** DESTROY
  46725. **
  46726. ** The CREATE and DESTROY primitives are the constructor and destructor,
  46727. ** obviously. The INSERT primitive adds a new element to the RowSet.
  46728. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  46729. ** extracts the least value from the RowSet.
  46730. **
  46731. ** The INSERT primitive might allocate additional memory. Memory is
  46732. ** allocated in chunks so most INSERTs do no allocation. There is an
  46733. ** upper bound on the size of allocated memory. No memory is freed
  46734. ** until DESTROY.
  46735. **
  46736. ** The TEST primitive includes a "batch" number. The TEST primitive
  46737. ** will only see elements that were inserted before the last change
  46738. ** in the batch number. In other words, if an INSERT occurs between
  46739. ** two TESTs where the TESTs have the same batch nubmer, then the
  46740. ** value added by the INSERT will not be visible to the second TEST.
  46741. ** The initial batch number is zero, so if the very first TEST contains
  46742. ** a non-zero batch number, it will see all prior INSERTs.
  46743. **
  46744. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  46745. ** that is attempted.
  46746. **
  46747. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  46748. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  46749. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  46750. ** The cost of a TEST using the same batch number is O(logN). The cost
  46751. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  46752. ** primitives are constant time. The cost of DESTROY is O(N).
  46753. **
  46754. ** TEST and SMALLEST may not be used by the same RowSet. This used to
  46755. ** be possible, but the feature was not used, so it was removed in order
  46756. ** to simplify the code.
  46757. */
  46758. /* #include "sqliteInt.h" */
  46759. /*
  46760. ** Target size for allocation chunks.
  46761. */
  46762. #define ROWSET_ALLOCATION_SIZE 1024
  46763. /*
  46764. ** The number of rowset entries per allocation chunk.
  46765. */
  46766. #define ROWSET_ENTRY_PER_CHUNK \
  46767. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  46768. /*
  46769. ** Each entry in a RowSet is an instance of the following object.
  46770. **
  46771. ** This same object is reused to store a linked list of trees of RowSetEntry
  46772. ** objects. In that alternative use, pRight points to the next entry
  46773. ** in the list, pLeft points to the tree, and v is unused. The
  46774. ** RowSet.pForest value points to the head of this forest list.
  46775. */
  46776. struct RowSetEntry {
  46777. i64 v; /* ROWID value for this entry */
  46778. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  46779. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  46780. };
  46781. /*
  46782. ** RowSetEntry objects are allocated in large chunks (instances of the
  46783. ** following structure) to reduce memory allocation overhead. The
  46784. ** chunks are kept on a linked list so that they can be deallocated
  46785. ** when the RowSet is destroyed.
  46786. */
  46787. struct RowSetChunk {
  46788. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  46789. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  46790. };
  46791. /*
  46792. ** A RowSet in an instance of the following structure.
  46793. **
  46794. ** A typedef of this structure if found in sqliteInt.h.
  46795. */
  46796. struct RowSet {
  46797. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  46798. sqlite3 *db; /* The database connection */
  46799. struct RowSetEntry *pEntry; /* List of entries using pRight */
  46800. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  46801. struct RowSetEntry *pFresh; /* Source of new entry objects */
  46802. struct RowSetEntry *pForest; /* List of binary trees of entries */
  46803. u16 nFresh; /* Number of objects on pFresh */
  46804. u16 rsFlags; /* Various flags */
  46805. int iBatch; /* Current insert batch */
  46806. };
  46807. /*
  46808. ** Allowed values for RowSet.rsFlags
  46809. */
  46810. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  46811. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  46812. /*
  46813. ** Allocate a RowSet object. Return NULL if a memory allocation
  46814. ** error occurs.
  46815. */
  46816. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db){
  46817. RowSet *p = sqlite3DbMallocRawNN(db, sizeof(*p));
  46818. if( p ){
  46819. int N = sqlite3DbMallocSize(db, p);
  46820. p->pChunk = 0;
  46821. p->db = db;
  46822. p->pEntry = 0;
  46823. p->pLast = 0;
  46824. p->pForest = 0;
  46825. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  46826. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  46827. p->rsFlags = ROWSET_SORTED;
  46828. p->iBatch = 0;
  46829. }
  46830. return p;
  46831. }
  46832. /*
  46833. ** Deallocate all chunks from a RowSet. This frees all memory that
  46834. ** the RowSet has allocated over its lifetime. This routine is
  46835. ** the destructor for the RowSet.
  46836. */
  46837. SQLITE_PRIVATE void sqlite3RowSetClear(void *pArg){
  46838. RowSet *p = (RowSet*)pArg;
  46839. struct RowSetChunk *pChunk, *pNextChunk;
  46840. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  46841. pNextChunk = pChunk->pNextChunk;
  46842. sqlite3DbFree(p->db, pChunk);
  46843. }
  46844. p->pChunk = 0;
  46845. p->nFresh = 0;
  46846. p->pEntry = 0;
  46847. p->pLast = 0;
  46848. p->pForest = 0;
  46849. p->rsFlags = ROWSET_SORTED;
  46850. }
  46851. /*
  46852. ** Deallocate all chunks from a RowSet. This frees all memory that
  46853. ** the RowSet has allocated over its lifetime. This routine is
  46854. ** the destructor for the RowSet.
  46855. */
  46856. SQLITE_PRIVATE void sqlite3RowSetDelete(void *pArg){
  46857. sqlite3RowSetClear(pArg);
  46858. sqlite3DbFree(((RowSet*)pArg)->db, pArg);
  46859. }
  46860. /*
  46861. ** Allocate a new RowSetEntry object that is associated with the
  46862. ** given RowSet. Return a pointer to the new and completely uninitialized
  46863. ** objected.
  46864. **
  46865. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  46866. ** routine returns NULL.
  46867. */
  46868. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  46869. assert( p!=0 );
  46870. if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
  46871. /* We could allocate a fresh RowSetEntry each time one is needed, but it
  46872. ** is more efficient to pull a preallocated entry from the pool */
  46873. struct RowSetChunk *pNew;
  46874. pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
  46875. if( pNew==0 ){
  46876. return 0;
  46877. }
  46878. pNew->pNextChunk = p->pChunk;
  46879. p->pChunk = pNew;
  46880. p->pFresh = pNew->aEntry;
  46881. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  46882. }
  46883. p->nFresh--;
  46884. return p->pFresh++;
  46885. }
  46886. /*
  46887. ** Insert a new value into a RowSet.
  46888. **
  46889. ** The mallocFailed flag of the database connection is set if a
  46890. ** memory allocation fails.
  46891. */
  46892. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  46893. struct RowSetEntry *pEntry; /* The new entry */
  46894. struct RowSetEntry *pLast; /* The last prior entry */
  46895. /* This routine is never called after sqlite3RowSetNext() */
  46896. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  46897. pEntry = rowSetEntryAlloc(p);
  46898. if( pEntry==0 ) return;
  46899. pEntry->v = rowid;
  46900. pEntry->pRight = 0;
  46901. pLast = p->pLast;
  46902. if( pLast ){
  46903. if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
  46904. /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
  46905. ** where possible */
  46906. p->rsFlags &= ~ROWSET_SORTED;
  46907. }
  46908. pLast->pRight = pEntry;
  46909. }else{
  46910. p->pEntry = pEntry;
  46911. }
  46912. p->pLast = pEntry;
  46913. }
  46914. /*
  46915. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  46916. **
  46917. ** The input lists are connected via pRight pointers and are
  46918. ** assumed to each already be in sorted order.
  46919. */
  46920. static struct RowSetEntry *rowSetEntryMerge(
  46921. struct RowSetEntry *pA, /* First sorted list to be merged */
  46922. struct RowSetEntry *pB /* Second sorted list to be merged */
  46923. ){
  46924. struct RowSetEntry head;
  46925. struct RowSetEntry *pTail;
  46926. pTail = &head;
  46927. assert( pA!=0 && pB!=0 );
  46928. for(;;){
  46929. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  46930. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  46931. if( pA->v<=pB->v ){
  46932. if( pA->v<pB->v ) pTail = pTail->pRight = pA;
  46933. pA = pA->pRight;
  46934. if( pA==0 ){
  46935. pTail->pRight = pB;
  46936. break;
  46937. }
  46938. }else{
  46939. pTail = pTail->pRight = pB;
  46940. pB = pB->pRight;
  46941. if( pB==0 ){
  46942. pTail->pRight = pA;
  46943. break;
  46944. }
  46945. }
  46946. }
  46947. return head.pRight;
  46948. }
  46949. /*
  46950. ** Sort all elements on the list of RowSetEntry objects into order of
  46951. ** increasing v.
  46952. */
  46953. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  46954. unsigned int i;
  46955. struct RowSetEntry *pNext, *aBucket[40];
  46956. memset(aBucket, 0, sizeof(aBucket));
  46957. while( pIn ){
  46958. pNext = pIn->pRight;
  46959. pIn->pRight = 0;
  46960. for(i=0; aBucket[i]; i++){
  46961. pIn = rowSetEntryMerge(aBucket[i], pIn);
  46962. aBucket[i] = 0;
  46963. }
  46964. aBucket[i] = pIn;
  46965. pIn = pNext;
  46966. }
  46967. pIn = aBucket[0];
  46968. for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  46969. if( aBucket[i]==0 ) continue;
  46970. pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
  46971. }
  46972. return pIn;
  46973. }
  46974. /*
  46975. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  46976. ** Convert this tree into a linked list connected by the pRight pointers
  46977. ** and return pointers to the first and last elements of the new list.
  46978. */
  46979. static void rowSetTreeToList(
  46980. struct RowSetEntry *pIn, /* Root of the input tree */
  46981. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  46982. struct RowSetEntry **ppLast /* Write tail of the output list here */
  46983. ){
  46984. assert( pIn!=0 );
  46985. if( pIn->pLeft ){
  46986. struct RowSetEntry *p;
  46987. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  46988. p->pRight = pIn;
  46989. }else{
  46990. *ppFirst = pIn;
  46991. }
  46992. if( pIn->pRight ){
  46993. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  46994. }else{
  46995. *ppLast = pIn;
  46996. }
  46997. assert( (*ppLast)->pRight==0 );
  46998. }
  46999. /*
  47000. ** Convert a sorted list of elements (connected by pRight) into a binary
  47001. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  47002. ** node taken from the head of *ppList. A depth of 2 means a tree with
  47003. ** three nodes. And so forth.
  47004. **
  47005. ** Use as many entries from the input list as required and update the
  47006. ** *ppList to point to the unused elements of the list. If the input
  47007. ** list contains too few elements, then construct an incomplete tree
  47008. ** and leave *ppList set to NULL.
  47009. **
  47010. ** Return a pointer to the root of the constructed binary tree.
  47011. */
  47012. static struct RowSetEntry *rowSetNDeepTree(
  47013. struct RowSetEntry **ppList,
  47014. int iDepth
  47015. ){
  47016. struct RowSetEntry *p; /* Root of the new tree */
  47017. struct RowSetEntry *pLeft; /* Left subtree */
  47018. if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
  47019. /* Prevent unnecessary deep recursion when we run out of entries */
  47020. return 0;
  47021. }
  47022. if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
  47023. /* This branch causes a *balanced* tree to be generated. A valid tree
  47024. ** is still generated without this branch, but the tree is wildly
  47025. ** unbalanced and inefficient. */
  47026. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  47027. p = *ppList;
  47028. if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47029. /* It is safe to always return here, but the resulting tree
  47030. ** would be unbalanced */
  47031. return pLeft;
  47032. }
  47033. p->pLeft = pLeft;
  47034. *ppList = p->pRight;
  47035. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  47036. }else{
  47037. p = *ppList;
  47038. *ppList = p->pRight;
  47039. p->pLeft = p->pRight = 0;
  47040. }
  47041. return p;
  47042. }
  47043. /*
  47044. ** Convert a sorted list of elements into a binary tree. Make the tree
  47045. ** as deep as it needs to be in order to contain the entire list.
  47046. */
  47047. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  47048. int iDepth; /* Depth of the tree so far */
  47049. struct RowSetEntry *p; /* Current tree root */
  47050. struct RowSetEntry *pLeft; /* Left subtree */
  47051. assert( pList!=0 );
  47052. p = pList;
  47053. pList = p->pRight;
  47054. p->pLeft = p->pRight = 0;
  47055. for(iDepth=1; pList; iDepth++){
  47056. pLeft = p;
  47057. p = pList;
  47058. pList = p->pRight;
  47059. p->pLeft = pLeft;
  47060. p->pRight = rowSetNDeepTree(&pList, iDepth);
  47061. }
  47062. return p;
  47063. }
  47064. /*
  47065. ** Extract the smallest element from the RowSet.
  47066. ** Write the element into *pRowid. Return 1 on success. Return
  47067. ** 0 if the RowSet is already empty.
  47068. **
  47069. ** After this routine has been called, the sqlite3RowSetInsert()
  47070. ** routine may not be called again.
  47071. **
  47072. ** This routine may not be called after sqlite3RowSetTest() has
  47073. ** been used. Older versions of RowSet allowed that, but as the
  47074. ** capability was not used by the code generator, it was removed
  47075. ** for code economy.
  47076. */
  47077. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  47078. assert( p!=0 );
  47079. assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
  47080. /* Merge the forest into a single sorted list on first call */
  47081. if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47082. if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47083. p->pEntry = rowSetEntrySort(p->pEntry);
  47084. }
  47085. p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
  47086. }
  47087. /* Return the next entry on the list */
  47088. if( p->pEntry ){
  47089. *pRowid = p->pEntry->v;
  47090. p->pEntry = p->pEntry->pRight;
  47091. if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
  47092. /* Free memory immediately, rather than waiting on sqlite3_finalize() */
  47093. sqlite3RowSetClear(p);
  47094. }
  47095. return 1;
  47096. }else{
  47097. return 0;
  47098. }
  47099. }
  47100. /*
  47101. ** Check to see if element iRowid was inserted into the rowset as
  47102. ** part of any insert batch prior to iBatch. Return 1 or 0.
  47103. **
  47104. ** If this is the first test of a new batch and if there exist entries
  47105. ** on pRowSet->pEntry, then sort those entries into the forest at
  47106. ** pRowSet->pForest so that they can be tested.
  47107. */
  47108. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  47109. struct RowSetEntry *p, *pTree;
  47110. /* This routine is never called after sqlite3RowSetNext() */
  47111. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  47112. /* Sort entries into the forest on the first test of a new batch.
  47113. ** To save unnecessary work, only do this when the batch number changes.
  47114. */
  47115. if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
  47116. p = pRowSet->pEntry;
  47117. if( p ){
  47118. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  47119. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47120. /* Only sort the current set of entiries if they need it */
  47121. p = rowSetEntrySort(p);
  47122. }
  47123. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  47124. ppPrevTree = &pTree->pRight;
  47125. if( pTree->pLeft==0 ){
  47126. pTree->pLeft = rowSetListToTree(p);
  47127. break;
  47128. }else{
  47129. struct RowSetEntry *pAux, *pTail;
  47130. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  47131. pTree->pLeft = 0;
  47132. p = rowSetEntryMerge(pAux, p);
  47133. }
  47134. }
  47135. if( pTree==0 ){
  47136. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  47137. if( pTree ){
  47138. pTree->v = 0;
  47139. pTree->pRight = 0;
  47140. pTree->pLeft = rowSetListToTree(p);
  47141. }
  47142. }
  47143. pRowSet->pEntry = 0;
  47144. pRowSet->pLast = 0;
  47145. pRowSet->rsFlags |= ROWSET_SORTED;
  47146. }
  47147. pRowSet->iBatch = iBatch;
  47148. }
  47149. /* Test to see if the iRowid value appears anywhere in the forest.
  47150. ** Return 1 if it does and 0 if not.
  47151. */
  47152. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  47153. p = pTree->pLeft;
  47154. while( p ){
  47155. if( p->v<iRowid ){
  47156. p = p->pRight;
  47157. }else if( p->v>iRowid ){
  47158. p = p->pLeft;
  47159. }else{
  47160. return 1;
  47161. }
  47162. }
  47163. }
  47164. return 0;
  47165. }
  47166. /************** End of rowset.c **********************************************/
  47167. /************** Begin file pager.c *******************************************/
  47168. /*
  47169. ** 2001 September 15
  47170. **
  47171. ** The author disclaims copyright to this source code. In place of
  47172. ** a legal notice, here is a blessing:
  47173. **
  47174. ** May you do good and not evil.
  47175. ** May you find forgiveness for yourself and forgive others.
  47176. ** May you share freely, never taking more than you give.
  47177. **
  47178. *************************************************************************
  47179. ** This is the implementation of the page cache subsystem or "pager".
  47180. **
  47181. ** The pager is used to access a database disk file. It implements
  47182. ** atomic commit and rollback through the use of a journal file that
  47183. ** is separate from the database file. The pager also implements file
  47184. ** locking to prevent two processes from writing the same database
  47185. ** file simultaneously, or one process from reading the database while
  47186. ** another is writing.
  47187. */
  47188. #ifndef SQLITE_OMIT_DISKIO
  47189. /* #include "sqliteInt.h" */
  47190. /************** Include wal.h in the middle of pager.c ***********************/
  47191. /************** Begin file wal.h *********************************************/
  47192. /*
  47193. ** 2010 February 1
  47194. **
  47195. ** The author disclaims copyright to this source code. In place of
  47196. ** a legal notice, here is a blessing:
  47197. **
  47198. ** May you do good and not evil.
  47199. ** May you find forgiveness for yourself and forgive others.
  47200. ** May you share freely, never taking more than you give.
  47201. **
  47202. *************************************************************************
  47203. ** This header file defines the interface to the write-ahead logging
  47204. ** system. Refer to the comments below and the header comment attached to
  47205. ** the implementation of each function in log.c for further details.
  47206. */
  47207. #ifndef SQLITE_WAL_H
  47208. #define SQLITE_WAL_H
  47209. /* #include "sqliteInt.h" */
  47210. /* Macros for extracting appropriate sync flags for either transaction
  47211. ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
  47212. */
  47213. #define WAL_SYNC_FLAGS(X) ((X)&0x03)
  47214. #define CKPT_SYNC_FLAGS(X) (((X)>>2)&0x03)
  47215. #ifdef SQLITE_OMIT_WAL
  47216. # define sqlite3WalOpen(x,y,z) 0
  47217. # define sqlite3WalLimit(x,y)
  47218. # define sqlite3WalClose(v,w,x,y,z) 0
  47219. # define sqlite3WalBeginReadTransaction(y,z) 0
  47220. # define sqlite3WalEndReadTransaction(z)
  47221. # define sqlite3WalDbsize(y) 0
  47222. # define sqlite3WalBeginWriteTransaction(y) 0
  47223. # define sqlite3WalEndWriteTransaction(x) 0
  47224. # define sqlite3WalUndo(x,y,z) 0
  47225. # define sqlite3WalSavepoint(y,z)
  47226. # define sqlite3WalSavepointUndo(y,z) 0
  47227. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  47228. # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
  47229. # define sqlite3WalCallback(z) 0
  47230. # define sqlite3WalExclusiveMode(y,z) 0
  47231. # define sqlite3WalHeapMemory(z) 0
  47232. # define sqlite3WalFramesize(z) 0
  47233. # define sqlite3WalFindFrame(x,y,z) 0
  47234. # define sqlite3WalFile(x) 0
  47235. #else
  47236. #define WAL_SAVEPOINT_NDATA 4
  47237. /* Connection to a write-ahead log (WAL) file.
  47238. ** There is one object of this type for each pager.
  47239. */
  47240. typedef struct Wal Wal;
  47241. /* Open and close a connection to a write-ahead log. */
  47242. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  47243. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
  47244. /* Set the limiting size of a WAL file. */
  47245. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  47246. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  47247. ** snapshot is like a read-transaction. It is the state of the database
  47248. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  47249. ** preserves the current state even if the other threads or processes
  47250. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  47251. ** transaction and releases the lock.
  47252. */
  47253. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  47254. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  47255. /* Read a page from the write-ahead log, if it is present. */
  47256. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  47257. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  47258. /* If the WAL is not empty, return the size of the database. */
  47259. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  47260. /* Obtain or release the WRITER lock. */
  47261. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  47262. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  47263. /* Undo any frames written (but not committed) to the log */
  47264. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  47265. /* Return an integer that records the current (uncommitted) write
  47266. ** position in the WAL */
  47267. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  47268. /* Move the write position of the WAL back to iFrame. Called in
  47269. ** response to a ROLLBACK TO command. */
  47270. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  47271. /* Write a frame or frames to the log. */
  47272. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  47273. /* Copy pages from the log to the database file */
  47274. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  47275. Wal *pWal, /* Write-ahead log connection */
  47276. sqlite3 *db, /* Check this handle's interrupt flag */
  47277. int eMode, /* One of PASSIVE, FULL and RESTART */
  47278. int (*xBusy)(void*), /* Function to call when busy */
  47279. void *pBusyArg, /* Context argument for xBusyHandler */
  47280. int sync_flags, /* Flags to sync db file with (or 0) */
  47281. int nBuf, /* Size of buffer nBuf */
  47282. u8 *zBuf, /* Temporary buffer to use */
  47283. int *pnLog, /* OUT: Number of frames in WAL */
  47284. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  47285. );
  47286. /* Return the value to pass to a sqlite3_wal_hook callback, the
  47287. ** number of frames in the WAL at the point of the last commit since
  47288. ** sqlite3WalCallback() was called. If no commits have occurred since
  47289. ** the last call, then return 0.
  47290. */
  47291. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  47292. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  47293. ** by the pager layer on the database file.
  47294. */
  47295. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  47296. /* Return true if the argument is non-NULL and the WAL module is using
  47297. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  47298. ** WAL module is using shared-memory, return false.
  47299. */
  47300. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  47301. #ifdef SQLITE_ENABLE_SNAPSHOT
  47302. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
  47303. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
  47304. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
  47305. SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot);
  47306. SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal);
  47307. #endif
  47308. #ifdef SQLITE_ENABLE_ZIPVFS
  47309. /* If the WAL file is not empty, return the number of bytes of content
  47310. ** stored in each frame (i.e. the db page-size when the WAL was created).
  47311. */
  47312. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  47313. #endif
  47314. /* Return the sqlite3_file object for the WAL file */
  47315. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
  47316. #endif /* ifndef SQLITE_OMIT_WAL */
  47317. #endif /* SQLITE_WAL_H */
  47318. /************** End of wal.h *************************************************/
  47319. /************** Continuing where we left off in pager.c **********************/
  47320. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  47321. **
  47322. ** This comment block describes invariants that hold when using a rollback
  47323. ** journal. These invariants do not apply for journal_mode=WAL,
  47324. ** journal_mode=MEMORY, or journal_mode=OFF.
  47325. **
  47326. ** Within this comment block, a page is deemed to have been synced
  47327. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  47328. ** Otherwise, the page is not synced until the xSync method of the VFS
  47329. ** is called successfully on the file containing the page.
  47330. **
  47331. ** Definition: A page of the database file is said to be "overwriteable" if
  47332. ** one or more of the following are true about the page:
  47333. **
  47334. ** (a) The original content of the page as it was at the beginning of
  47335. ** the transaction has been written into the rollback journal and
  47336. ** synced.
  47337. **
  47338. ** (b) The page was a freelist leaf page at the start of the transaction.
  47339. **
  47340. ** (c) The page number is greater than the largest page that existed in
  47341. ** the database file at the start of the transaction.
  47342. **
  47343. ** (1) A page of the database file is never overwritten unless one of the
  47344. ** following are true:
  47345. **
  47346. ** (a) The page and all other pages on the same sector are overwriteable.
  47347. **
  47348. ** (b) The atomic page write optimization is enabled, and the entire
  47349. ** transaction other than the update of the transaction sequence
  47350. ** number consists of a single page change.
  47351. **
  47352. ** (2) The content of a page written into the rollback journal exactly matches
  47353. ** both the content in the database when the rollback journal was written
  47354. ** and the content in the database at the beginning of the current
  47355. ** transaction.
  47356. **
  47357. ** (3) Writes to the database file are an integer multiple of the page size
  47358. ** in length and are aligned on a page boundary.
  47359. **
  47360. ** (4) Reads from the database file are either aligned on a page boundary and
  47361. ** an integer multiple of the page size in length or are taken from the
  47362. ** first 100 bytes of the database file.
  47363. **
  47364. ** (5) All writes to the database file are synced prior to the rollback journal
  47365. ** being deleted, truncated, or zeroed.
  47366. **
  47367. ** (6) If a master journal file is used, then all writes to the database file
  47368. ** are synced prior to the master journal being deleted.
  47369. **
  47370. ** Definition: Two databases (or the same database at two points it time)
  47371. ** are said to be "logically equivalent" if they give the same answer to
  47372. ** all queries. Note in particular the content of freelist leaf
  47373. ** pages can be changed arbitrarily without affecting the logical equivalence
  47374. ** of the database.
  47375. **
  47376. ** (7) At any time, if any subset, including the empty set and the total set,
  47377. ** of the unsynced changes to a rollback journal are removed and the
  47378. ** journal is rolled back, the resulting database file will be logically
  47379. ** equivalent to the database file at the beginning of the transaction.
  47380. **
  47381. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  47382. ** is called to restore the database file to the same size it was at
  47383. ** the beginning of the transaction. (In some VFSes, the xTruncate
  47384. ** method is a no-op, but that does not change the fact the SQLite will
  47385. ** invoke it.)
  47386. **
  47387. ** (9) Whenever the database file is modified, at least one bit in the range
  47388. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  47389. ** the EXCLUSIVE lock, thus signaling other connections on the same
  47390. ** database to flush their caches.
  47391. **
  47392. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  47393. ** than one billion transactions.
  47394. **
  47395. ** (11) A database file is well-formed at the beginning and at the conclusion
  47396. ** of every transaction.
  47397. **
  47398. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  47399. ** the database file.
  47400. **
  47401. ** (13) A SHARED lock is held on the database file while reading any
  47402. ** content out of the database file.
  47403. **
  47404. ******************************************************************************/
  47405. /*
  47406. ** Macros for troubleshooting. Normally turned off
  47407. */
  47408. #if 0
  47409. int sqlite3PagerTrace=1; /* True to enable tracing */
  47410. #define sqlite3DebugPrintf printf
  47411. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  47412. #else
  47413. #define PAGERTRACE(X)
  47414. #endif
  47415. /*
  47416. ** The following two macros are used within the PAGERTRACE() macros above
  47417. ** to print out file-descriptors.
  47418. **
  47419. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  47420. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  47421. ** struct as its argument.
  47422. */
  47423. #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
  47424. #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
  47425. /*
  47426. ** The Pager.eState variable stores the current 'state' of a pager. A
  47427. ** pager may be in any one of the seven states shown in the following
  47428. ** state diagram.
  47429. **
  47430. ** OPEN <------+------+
  47431. ** | | |
  47432. ** V | |
  47433. ** +---------> READER-------+ |
  47434. ** | | |
  47435. ** | V |
  47436. ** |<-------WRITER_LOCKED------> ERROR
  47437. ** | | ^
  47438. ** | V |
  47439. ** |<------WRITER_CACHEMOD-------->|
  47440. ** | | |
  47441. ** | V |
  47442. ** |<-------WRITER_DBMOD---------->|
  47443. ** | | |
  47444. ** | V |
  47445. ** +<------WRITER_FINISHED-------->+
  47446. **
  47447. **
  47448. ** List of state transitions and the C [function] that performs each:
  47449. **
  47450. ** OPEN -> READER [sqlite3PagerSharedLock]
  47451. ** READER -> OPEN [pager_unlock]
  47452. **
  47453. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  47454. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  47455. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  47456. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  47457. ** WRITER_*** -> READER [pager_end_transaction]
  47458. **
  47459. ** WRITER_*** -> ERROR [pager_error]
  47460. ** ERROR -> OPEN [pager_unlock]
  47461. **
  47462. **
  47463. ** OPEN:
  47464. **
  47465. ** The pager starts up in this state. Nothing is guaranteed in this
  47466. ** state - the file may or may not be locked and the database size is
  47467. ** unknown. The database may not be read or written.
  47468. **
  47469. ** * No read or write transaction is active.
  47470. ** * Any lock, or no lock at all, may be held on the database file.
  47471. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  47472. **
  47473. ** READER:
  47474. **
  47475. ** In this state all the requirements for reading the database in
  47476. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  47477. ** was) in exclusive-locking mode, a user-level read transaction is
  47478. ** open. The database size is known in this state.
  47479. **
  47480. ** A connection running with locking_mode=normal enters this state when
  47481. ** it opens a read-transaction on the database and returns to state
  47482. ** OPEN after the read-transaction is completed. However a connection
  47483. ** running in locking_mode=exclusive (including temp databases) remains in
  47484. ** this state even after the read-transaction is closed. The only way
  47485. ** a locking_mode=exclusive connection can transition from READER to OPEN
  47486. ** is via the ERROR state (see below).
  47487. **
  47488. ** * A read transaction may be active (but a write-transaction cannot).
  47489. ** * A SHARED or greater lock is held on the database file.
  47490. ** * The dbSize variable may be trusted (even if a user-level read
  47491. ** transaction is not active). The dbOrigSize and dbFileSize variables
  47492. ** may not be trusted at this point.
  47493. ** * If the database is a WAL database, then the WAL connection is open.
  47494. ** * Even if a read-transaction is not open, it is guaranteed that
  47495. ** there is no hot-journal in the file-system.
  47496. **
  47497. ** WRITER_LOCKED:
  47498. **
  47499. ** The pager moves to this state from READER when a write-transaction
  47500. ** is first opened on the database. In WRITER_LOCKED state, all locks
  47501. ** required to start a write-transaction are held, but no actual
  47502. ** modifications to the cache or database have taken place.
  47503. **
  47504. ** In rollback mode, a RESERVED or (if the transaction was opened with
  47505. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  47506. ** moving to this state, but the journal file is not written to or opened
  47507. ** to in this state. If the transaction is committed or rolled back while
  47508. ** in WRITER_LOCKED state, all that is required is to unlock the database
  47509. ** file.
  47510. **
  47511. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  47512. ** If the connection is running with locking_mode=exclusive, an attempt
  47513. ** is made to obtain an EXCLUSIVE lock on the database file.
  47514. **
  47515. ** * A write transaction is active.
  47516. ** * If the connection is open in rollback-mode, a RESERVED or greater
  47517. ** lock is held on the database file.
  47518. ** * If the connection is open in WAL-mode, a WAL write transaction
  47519. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  47520. ** called).
  47521. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  47522. ** * The contents of the pager cache have not been modified.
  47523. ** * The journal file may or may not be open.
  47524. ** * Nothing (not even the first header) has been written to the journal.
  47525. **
  47526. ** WRITER_CACHEMOD:
  47527. **
  47528. ** A pager moves from WRITER_LOCKED state to this state when a page is
  47529. ** first modified by the upper layer. In rollback mode the journal file
  47530. ** is opened (if it is not already open) and a header written to the
  47531. ** start of it. The database file on disk has not been modified.
  47532. **
  47533. ** * A write transaction is active.
  47534. ** * A RESERVED or greater lock is held on the database file.
  47535. ** * The journal file is open and the first header has been written
  47536. ** to it, but the header has not been synced to disk.
  47537. ** * The contents of the page cache have been modified.
  47538. **
  47539. ** WRITER_DBMOD:
  47540. **
  47541. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  47542. ** when it modifies the contents of the database file. WAL connections
  47543. ** never enter this state (since they do not modify the database file,
  47544. ** just the log file).
  47545. **
  47546. ** * A write transaction is active.
  47547. ** * An EXCLUSIVE or greater lock is held on the database file.
  47548. ** * The journal file is open and the first header has been written
  47549. ** and synced to disk.
  47550. ** * The contents of the page cache have been modified (and possibly
  47551. ** written to disk).
  47552. **
  47553. ** WRITER_FINISHED:
  47554. **
  47555. ** It is not possible for a WAL connection to enter this state.
  47556. **
  47557. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  47558. ** state after the entire transaction has been successfully written into the
  47559. ** database file. In this state the transaction may be committed simply
  47560. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  47561. ** not possible to modify the database further. At this point, the upper
  47562. ** layer must either commit or rollback the transaction.
  47563. **
  47564. ** * A write transaction is active.
  47565. ** * An EXCLUSIVE or greater lock is held on the database file.
  47566. ** * All writing and syncing of journal and database data has finished.
  47567. ** If no error occurred, all that remains is to finalize the journal to
  47568. ** commit the transaction. If an error did occur, the caller will need
  47569. ** to rollback the transaction.
  47570. **
  47571. ** ERROR:
  47572. **
  47573. ** The ERROR state is entered when an IO or disk-full error (including
  47574. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  47575. ** difficult to be sure that the in-memory pager state (cache contents,
  47576. ** db size etc.) are consistent with the contents of the file-system.
  47577. **
  47578. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  47579. ** cannot.
  47580. **
  47581. ** For example, if an IO error occurs while performing a rollback,
  47582. ** the contents of the page-cache may be left in an inconsistent state.
  47583. ** At this point it would be dangerous to change back to READER state
  47584. ** (as usually happens after a rollback). Any subsequent readers might
  47585. ** report database corruption (due to the inconsistent cache), and if
  47586. ** they upgrade to writers, they may inadvertently corrupt the database
  47587. ** file. To avoid this hazard, the pager switches into the ERROR state
  47588. ** instead of READER following such an error.
  47589. **
  47590. ** Once it has entered the ERROR state, any attempt to use the pager
  47591. ** to read or write data returns an error. Eventually, once all
  47592. ** outstanding transactions have been abandoned, the pager is able to
  47593. ** transition back to OPEN state, discarding the contents of the
  47594. ** page-cache and any other in-memory state at the same time. Everything
  47595. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  47596. ** when a read-transaction is next opened on the pager (transitioning
  47597. ** the pager into READER state). At that point the system has recovered
  47598. ** from the error.
  47599. **
  47600. ** Specifically, the pager jumps into the ERROR state if:
  47601. **
  47602. ** 1. An error occurs while attempting a rollback. This happens in
  47603. ** function sqlite3PagerRollback().
  47604. **
  47605. ** 2. An error occurs while attempting to finalize a journal file
  47606. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  47607. **
  47608. ** 3. An error occurs while attempting to write to the journal or
  47609. ** database file in function pagerStress() in order to free up
  47610. ** memory.
  47611. **
  47612. ** In other cases, the error is returned to the b-tree layer. The b-tree
  47613. ** layer then attempts a rollback operation. If the error condition
  47614. ** persists, the pager enters the ERROR state via condition (1) above.
  47615. **
  47616. ** Condition (3) is necessary because it can be triggered by a read-only
  47617. ** statement executed within a transaction. In this case, if the error
  47618. ** code were simply returned to the user, the b-tree layer would not
  47619. ** automatically attempt a rollback, as it assumes that an error in a
  47620. ** read-only statement cannot leave the pager in an internally inconsistent
  47621. ** state.
  47622. **
  47623. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  47624. ** * There are one or more outstanding references to pages (after the
  47625. ** last reference is dropped the pager should move back to OPEN state).
  47626. ** * The pager is not an in-memory pager.
  47627. **
  47628. **
  47629. ** Notes:
  47630. **
  47631. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  47632. ** connection is open in WAL mode. A WAL connection is always in one
  47633. ** of the first four states.
  47634. **
  47635. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  47636. ** state. There are two exceptions: immediately after exclusive-mode has
  47637. ** been turned on (and before any read or write transactions are
  47638. ** executed), and when the pager is leaving the "error state".
  47639. **
  47640. ** * See also: assert_pager_state().
  47641. */
  47642. #define PAGER_OPEN 0
  47643. #define PAGER_READER 1
  47644. #define PAGER_WRITER_LOCKED 2
  47645. #define PAGER_WRITER_CACHEMOD 3
  47646. #define PAGER_WRITER_DBMOD 4
  47647. #define PAGER_WRITER_FINISHED 5
  47648. #define PAGER_ERROR 6
  47649. /*
  47650. ** The Pager.eLock variable is almost always set to one of the
  47651. ** following locking-states, according to the lock currently held on
  47652. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  47653. ** This variable is kept up to date as locks are taken and released by
  47654. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  47655. **
  47656. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  47657. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  47658. ** the operation was successful. In these circumstances pagerLockDb() and
  47659. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  47660. ** when unlocking the file, and only updated when locking the file if the
  47661. ** VFS call is successful. This way, the Pager.eLock variable may be set
  47662. ** to a less exclusive (lower) value than the lock that is actually held
  47663. ** at the system level, but it is never set to a more exclusive value.
  47664. **
  47665. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  47666. ** be a few redundant xLock() calls or a lock may be held for longer than
  47667. ** required, but nothing really goes wrong.
  47668. **
  47669. ** The exception is when the database file is unlocked as the pager moves
  47670. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  47671. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  47672. ** transition, by the same pager or any other). If the call to xUnlock()
  47673. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  47674. ** can confuse the call to xCheckReservedLock() call made later as part
  47675. ** of hot-journal detection.
  47676. **
  47677. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  47678. ** lock held by this process or any others". So xCheckReservedLock may
  47679. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  47680. ** doesn't know it because of a previous error in xUnlock). If this happens
  47681. ** a hot-journal may be mistaken for a journal being created by an active
  47682. ** transaction in another process, causing SQLite to read from the database
  47683. ** without rolling it back.
  47684. **
  47685. ** To work around this, if a call to xUnlock() fails when unlocking the
  47686. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  47687. ** is only changed back to a real locking state after a successful call
  47688. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  47689. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  47690. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  47691. ** lock on the database file before attempting to roll it back. See function
  47692. ** PagerSharedLock() for more detail.
  47693. **
  47694. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  47695. ** PAGER_OPEN state.
  47696. */
  47697. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  47698. /*
  47699. ** A macro used for invoking the codec if there is one
  47700. */
  47701. #ifdef SQLITE_HAS_CODEC
  47702. # define CODEC1(P,D,N,X,E) \
  47703. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  47704. # define CODEC2(P,D,N,X,E,O) \
  47705. if( P->xCodec==0 ){ O=(char*)D; }else \
  47706. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  47707. #else
  47708. # define CODEC1(P,D,N,X,E) /* NO-OP */
  47709. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  47710. #endif
  47711. /*
  47712. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  47713. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  47714. ** This could conceivably cause corruption following a power failure on
  47715. ** such a system. This is currently an undocumented limit.
  47716. */
  47717. #define MAX_SECTOR_SIZE 0x10000
  47718. /*
  47719. ** An instance of the following structure is allocated for each active
  47720. ** savepoint and statement transaction in the system. All such structures
  47721. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  47722. ** resized using sqlite3Realloc().
  47723. **
  47724. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  47725. ** set to 0. If a journal-header is written into the main journal while
  47726. ** the savepoint is active, then iHdrOffset is set to the byte offset
  47727. ** immediately following the last journal record written into the main
  47728. ** journal before the journal-header. This is required during savepoint
  47729. ** rollback (see pagerPlaybackSavepoint()).
  47730. */
  47731. typedef struct PagerSavepoint PagerSavepoint;
  47732. struct PagerSavepoint {
  47733. i64 iOffset; /* Starting offset in main journal */
  47734. i64 iHdrOffset; /* See above */
  47735. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  47736. Pgno nOrig; /* Original number of pages in file */
  47737. Pgno iSubRec; /* Index of first record in sub-journal */
  47738. #ifndef SQLITE_OMIT_WAL
  47739. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  47740. #endif
  47741. };
  47742. /*
  47743. ** Bits of the Pager.doNotSpill flag. See further description below.
  47744. */
  47745. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  47746. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  47747. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  47748. /*
  47749. ** An open page cache is an instance of struct Pager. A description of
  47750. ** some of the more important member variables follows:
  47751. **
  47752. ** eState
  47753. **
  47754. ** The current 'state' of the pager object. See the comment and state
  47755. ** diagram above for a description of the pager state.
  47756. **
  47757. ** eLock
  47758. **
  47759. ** For a real on-disk database, the current lock held on the database file -
  47760. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  47761. **
  47762. ** For a temporary or in-memory database (neither of which require any
  47763. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  47764. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  47765. ** logic into thinking that it already has all the locks it will ever
  47766. ** need (and no reason to release them).
  47767. **
  47768. ** In some (obscure) circumstances, this variable may also be set to
  47769. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  47770. ** details.
  47771. **
  47772. ** changeCountDone
  47773. **
  47774. ** This boolean variable is used to make sure that the change-counter
  47775. ** (the 4-byte header field at byte offset 24 of the database file) is
  47776. ** not updated more often than necessary.
  47777. **
  47778. ** It is set to true when the change-counter field is updated, which
  47779. ** can only happen if an exclusive lock is held on the database file.
  47780. ** It is cleared (set to false) whenever an exclusive lock is
  47781. ** relinquished on the database file. Each time a transaction is committed,
  47782. ** The changeCountDone flag is inspected. If it is true, the work of
  47783. ** updating the change-counter is omitted for the current transaction.
  47784. **
  47785. ** This mechanism means that when running in exclusive mode, a connection
  47786. ** need only update the change-counter once, for the first transaction
  47787. ** committed.
  47788. **
  47789. ** setMaster
  47790. **
  47791. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  47792. ** (or may not) specify a master-journal name to be written into the
  47793. ** journal file before it is synced to disk.
  47794. **
  47795. ** Whether or not a journal file contains a master-journal pointer affects
  47796. ** the way in which the journal file is finalized after the transaction is
  47797. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  47798. ** If a journal file does not contain a master-journal pointer, it is
  47799. ** finalized by overwriting the first journal header with zeroes. If
  47800. ** it does contain a master-journal pointer the journal file is finalized
  47801. ** by truncating it to zero bytes, just as if the connection were
  47802. ** running in "journal_mode=truncate" mode.
  47803. **
  47804. ** Journal files that contain master journal pointers cannot be finalized
  47805. ** simply by overwriting the first journal-header with zeroes, as the
  47806. ** master journal pointer could interfere with hot-journal rollback of any
  47807. ** subsequently interrupted transaction that reuses the journal file.
  47808. **
  47809. ** The flag is cleared as soon as the journal file is finalized (either
  47810. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  47811. ** journal file from being successfully finalized, the setMaster flag
  47812. ** is cleared anyway (and the pager will move to ERROR state).
  47813. **
  47814. ** doNotSpill
  47815. **
  47816. ** This variables control the behavior of cache-spills (calls made by
  47817. ** the pcache module to the pagerStress() routine to write cached data
  47818. ** to the file-system in order to free up memory).
  47819. **
  47820. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  47821. ** writing to the database from pagerStress() is disabled altogether.
  47822. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  47823. ** comes up during savepoint rollback that requires the pcache module
  47824. ** to allocate a new page to prevent the journal file from being written
  47825. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  47826. ** case is a user preference.
  47827. **
  47828. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  47829. ** pagerStress() is permitted, but syncing the journal file is not.
  47830. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  47831. ** is larger than the database page-size in order to prevent a journal sync
  47832. ** from happening in between the journalling of two pages on the same sector.
  47833. **
  47834. ** subjInMemory
  47835. **
  47836. ** This is a boolean variable. If true, then any required sub-journal
  47837. ** is opened as an in-memory journal file. If false, then in-memory
  47838. ** sub-journals are only used for in-memory pager files.
  47839. **
  47840. ** This variable is updated by the upper layer each time a new
  47841. ** write-transaction is opened.
  47842. **
  47843. ** dbSize, dbOrigSize, dbFileSize
  47844. **
  47845. ** Variable dbSize is set to the number of pages in the database file.
  47846. ** It is valid in PAGER_READER and higher states (all states except for
  47847. ** OPEN and ERROR).
  47848. **
  47849. ** dbSize is set based on the size of the database file, which may be
  47850. ** larger than the size of the database (the value stored at offset
  47851. ** 28 of the database header by the btree). If the size of the file
  47852. ** is not an integer multiple of the page-size, the value stored in
  47853. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  47854. ** Except, any file that is greater than 0 bytes in size is considered
  47855. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  47856. ** to dbSize==1).
  47857. **
  47858. ** During a write-transaction, if pages with page-numbers greater than
  47859. ** dbSize are modified in the cache, dbSize is updated accordingly.
  47860. ** Similarly, if the database is truncated using PagerTruncateImage(),
  47861. ** dbSize is updated.
  47862. **
  47863. ** Variables dbOrigSize and dbFileSize are valid in states
  47864. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  47865. ** variable at the start of the transaction. It is used during rollback,
  47866. ** and to determine whether or not pages need to be journalled before
  47867. ** being modified.
  47868. **
  47869. ** Throughout a write-transaction, dbFileSize contains the size of
  47870. ** the file on disk in pages. It is set to a copy of dbSize when the
  47871. ** write-transaction is first opened, and updated when VFS calls are made
  47872. ** to write or truncate the database file on disk.
  47873. **
  47874. ** The only reason the dbFileSize variable is required is to suppress
  47875. ** unnecessary calls to xTruncate() after committing a transaction. If,
  47876. ** when a transaction is committed, the dbFileSize variable indicates
  47877. ** that the database file is larger than the database image (Pager.dbSize),
  47878. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  47879. ** to measure the database file on disk, and then truncates it if required.
  47880. ** dbFileSize is not used when rolling back a transaction. In this case
  47881. ** pager_truncate() is called unconditionally (which means there may be
  47882. ** a call to xFilesize() that is not strictly required). In either case,
  47883. ** pager_truncate() may cause the file to become smaller or larger.
  47884. **
  47885. ** dbHintSize
  47886. **
  47887. ** The dbHintSize variable is used to limit the number of calls made to
  47888. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  47889. **
  47890. ** dbHintSize is set to a copy of the dbSize variable when a
  47891. ** write-transaction is opened (at the same time as dbFileSize and
  47892. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  47893. ** dbHintSize is increased to the number of pages that correspond to the
  47894. ** size-hint passed to the method call. See pager_write_pagelist() for
  47895. ** details.
  47896. **
  47897. ** errCode
  47898. **
  47899. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  47900. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  47901. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  47902. ** sub-codes.
  47903. **
  47904. ** syncFlags, walSyncFlags
  47905. **
  47906. ** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
  47907. ** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode
  47908. ** and contains the flags used to sync the checkpoint operations in the
  47909. ** lower two bits, and sync flags used for transaction commits in the WAL
  47910. ** file in bits 0x04 and 0x08. In other words, to get the correct sync flags
  47911. ** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
  47912. ** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note
  47913. ** that with synchronous=NORMAL in WAL mode, transaction commit is not synced
  47914. ** meaning that the 0x04 and 0x08 bits are both zero.
  47915. */
  47916. struct Pager {
  47917. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  47918. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  47919. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  47920. u8 useJournal; /* Use a rollback journal on this file */
  47921. u8 noSync; /* Do not sync the journal if true */
  47922. u8 fullSync; /* Do extra syncs of the journal for robustness */
  47923. u8 extraSync; /* sync directory after journal delete */
  47924. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  47925. u8 walSyncFlags; /* See description above */
  47926. u8 tempFile; /* zFilename is a temporary or immutable file */
  47927. u8 noLock; /* Do not lock (except in WAL mode) */
  47928. u8 readOnly; /* True for a read-only database */
  47929. u8 memDb; /* True to inhibit all file I/O */
  47930. /**************************************************************************
  47931. ** The following block contains those class members that change during
  47932. ** routine operation. Class members not in this block are either fixed
  47933. ** when the pager is first created or else only change when there is a
  47934. ** significant mode change (such as changing the page_size, locking_mode,
  47935. ** or the journal_mode). From another view, these class members describe
  47936. ** the "state" of the pager, while other class members describe the
  47937. ** "configuration" of the pager.
  47938. */
  47939. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  47940. u8 eLock; /* Current lock held on database file */
  47941. u8 changeCountDone; /* Set after incrementing the change-counter */
  47942. u8 setMaster; /* True if a m-j name has been written to jrnl */
  47943. u8 doNotSpill; /* Do not spill the cache when non-zero */
  47944. u8 subjInMemory; /* True to use in-memory sub-journals */
  47945. u8 bUseFetch; /* True to use xFetch() */
  47946. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  47947. Pgno dbSize; /* Number of pages in the database */
  47948. Pgno dbOrigSize; /* dbSize before the current transaction */
  47949. Pgno dbFileSize; /* Number of pages in the database file */
  47950. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  47951. int errCode; /* One of several kinds of errors */
  47952. int nRec; /* Pages journalled since last j-header written */
  47953. u32 cksumInit; /* Quasi-random value added to every checksum */
  47954. u32 nSubRec; /* Number of records written to sub-journal */
  47955. Bitvec *pInJournal; /* One bit for each page in the database file */
  47956. sqlite3_file *fd; /* File descriptor for database */
  47957. sqlite3_file *jfd; /* File descriptor for main journal */
  47958. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  47959. i64 journalOff; /* Current write offset in the journal file */
  47960. i64 journalHdr; /* Byte offset to previous journal header */
  47961. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  47962. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  47963. int nSavepoint; /* Number of elements in aSavepoint[] */
  47964. u32 iDataVersion; /* Changes whenever database content changes */
  47965. char dbFileVers[16]; /* Changes whenever database file changes */
  47966. int nMmapOut; /* Number of mmap pages currently outstanding */
  47967. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  47968. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  47969. /*
  47970. ** End of the routinely-changing class members
  47971. ***************************************************************************/
  47972. u16 nExtra; /* Add this many bytes to each in-memory page */
  47973. i16 nReserve; /* Number of unused bytes at end of each page */
  47974. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  47975. u32 sectorSize; /* Assumed sector size during rollback */
  47976. int pageSize; /* Number of bytes in a page */
  47977. Pgno mxPgno; /* Maximum allowed size of the database */
  47978. i64 journalSizeLimit; /* Size limit for persistent journal files */
  47979. char *zFilename; /* Name of the database file */
  47980. char *zJournal; /* Name of the journal file */
  47981. int (*xBusyHandler)(void*); /* Function to call when busy */
  47982. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  47983. int aStat[4]; /* Total cache hits, misses, writes, spills */
  47984. #ifdef SQLITE_TEST
  47985. int nRead; /* Database pages read */
  47986. #endif
  47987. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  47988. int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
  47989. #ifdef SQLITE_HAS_CODEC
  47990. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  47991. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  47992. void (*xCodecFree)(void*); /* Destructor for the codec */
  47993. void *pCodec; /* First argument to xCodec... methods */
  47994. #endif
  47995. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  47996. PCache *pPCache; /* Pointer to page cache object */
  47997. #ifndef SQLITE_OMIT_WAL
  47998. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  47999. char *zWal; /* File name for write-ahead log */
  48000. #endif
  48001. };
  48002. /*
  48003. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  48004. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  48005. ** or CACHE_WRITE to sqlite3_db_status().
  48006. */
  48007. #define PAGER_STAT_HIT 0
  48008. #define PAGER_STAT_MISS 1
  48009. #define PAGER_STAT_WRITE 2
  48010. #define PAGER_STAT_SPILL 3
  48011. /*
  48012. ** The following global variables hold counters used for
  48013. ** testing purposes only. These variables do not exist in
  48014. ** a non-testing build. These variables are not thread-safe.
  48015. */
  48016. #ifdef SQLITE_TEST
  48017. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  48018. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  48019. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  48020. # define PAGER_INCR(v) v++
  48021. #else
  48022. # define PAGER_INCR(v)
  48023. #endif
  48024. /*
  48025. ** Journal files begin with the following magic string. The data
  48026. ** was obtained from /dev/random. It is used only as a sanity check.
  48027. **
  48028. ** Since version 2.8.0, the journal format contains additional sanity
  48029. ** checking information. If the power fails while the journal is being
  48030. ** written, semi-random garbage data might appear in the journal
  48031. ** file after power is restored. If an attempt is then made
  48032. ** to roll the journal back, the database could be corrupted. The additional
  48033. ** sanity checking data is an attempt to discover the garbage in the
  48034. ** journal and ignore it.
  48035. **
  48036. ** The sanity checking information for the new journal format consists
  48037. ** of a 32-bit checksum on each page of data. The checksum covers both
  48038. ** the page number and the pPager->pageSize bytes of data for the page.
  48039. ** This cksum is initialized to a 32-bit random value that appears in the
  48040. ** journal file right after the header. The random initializer is important,
  48041. ** because garbage data that appears at the end of a journal is likely
  48042. ** data that was once in other files that have now been deleted. If the
  48043. ** garbage data came from an obsolete journal file, the checksums might
  48044. ** be correct. But by initializing the checksum to random value which
  48045. ** is different for every journal, we minimize that risk.
  48046. */
  48047. static const unsigned char aJournalMagic[] = {
  48048. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  48049. };
  48050. /*
  48051. ** The size of the of each page record in the journal is given by
  48052. ** the following macro.
  48053. */
  48054. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  48055. /*
  48056. ** The journal header size for this pager. This is usually the same
  48057. ** size as a single disk sector. See also setSectorSize().
  48058. */
  48059. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  48060. /*
  48061. ** The macro MEMDB is true if we are dealing with an in-memory database.
  48062. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  48063. ** the value of MEMDB will be a constant and the compiler will optimize
  48064. ** out code that would never execute.
  48065. */
  48066. #ifdef SQLITE_OMIT_MEMORYDB
  48067. # define MEMDB 0
  48068. #else
  48069. # define MEMDB pPager->memDb
  48070. #endif
  48071. /*
  48072. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  48073. ** interfaces to access the database using memory-mapped I/O.
  48074. */
  48075. #if SQLITE_MAX_MMAP_SIZE>0
  48076. # define USEFETCH(x) ((x)->bUseFetch)
  48077. #else
  48078. # define USEFETCH(x) 0
  48079. #endif
  48080. /*
  48081. ** The maximum legal page number is (2^31 - 1).
  48082. */
  48083. #define PAGER_MAX_PGNO 2147483647
  48084. /*
  48085. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  48086. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  48087. **
  48088. ** This is so that expressions can be written as:
  48089. **
  48090. ** if( isOpen(pPager->jfd) ){ ...
  48091. **
  48092. ** instead of
  48093. **
  48094. ** if( pPager->jfd->pMethods ){ ...
  48095. */
  48096. #define isOpen(pFd) ((pFd)->pMethods!=0)
  48097. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  48098. /*
  48099. ** Return true if page pgno can be read directly from the database file
  48100. ** by the b-tree layer. This is the case if:
  48101. **
  48102. ** * the database file is open,
  48103. ** * there are no dirty pages in the cache, and
  48104. ** * the desired page is not currently in the wal file.
  48105. */
  48106. SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){
  48107. if( pPager->fd->pMethods==0 ) return 0;
  48108. if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
  48109. #ifndef SQLITE_OMIT_WAL
  48110. if( pPager->pWal ){
  48111. u32 iRead = 0;
  48112. int rc;
  48113. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
  48114. return (rc==SQLITE_OK && iRead==0);
  48115. }
  48116. #endif
  48117. return 1;
  48118. }
  48119. #endif
  48120. #ifndef SQLITE_OMIT_WAL
  48121. # define pagerUseWal(x) ((x)->pWal!=0)
  48122. #else
  48123. # define pagerUseWal(x) 0
  48124. # define pagerRollbackWal(x) 0
  48125. # define pagerWalFrames(v,w,x,y) 0
  48126. # define pagerOpenWalIfPresent(z) SQLITE_OK
  48127. # define pagerBeginReadTransaction(z) SQLITE_OK
  48128. #endif
  48129. #ifndef NDEBUG
  48130. /*
  48131. ** Usage:
  48132. **
  48133. ** assert( assert_pager_state(pPager) );
  48134. **
  48135. ** This function runs many asserts to try to find inconsistencies in
  48136. ** the internal state of the Pager object.
  48137. */
  48138. static int assert_pager_state(Pager *p){
  48139. Pager *pPager = p;
  48140. /* State must be valid. */
  48141. assert( p->eState==PAGER_OPEN
  48142. || p->eState==PAGER_READER
  48143. || p->eState==PAGER_WRITER_LOCKED
  48144. || p->eState==PAGER_WRITER_CACHEMOD
  48145. || p->eState==PAGER_WRITER_DBMOD
  48146. || p->eState==PAGER_WRITER_FINISHED
  48147. || p->eState==PAGER_ERROR
  48148. );
  48149. /* Regardless of the current state, a temp-file connection always behaves
  48150. ** as if it has an exclusive lock on the database file. It never updates
  48151. ** the change-counter field, so the changeCountDone flag is always set.
  48152. */
  48153. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  48154. assert( p->tempFile==0 || pPager->changeCountDone );
  48155. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  48156. ** And if the journal-mode is "OFF", the journal file must not be open.
  48157. */
  48158. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  48159. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  48160. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  48161. ** this means an in-memory pager performs no IO at all, it cannot encounter
  48162. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  48163. ** a journal file. (although the in-memory journal implementation may
  48164. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  48165. ** is therefore not possible for an in-memory pager to enter the ERROR
  48166. ** state.
  48167. */
  48168. if( MEMDB ){
  48169. assert( !isOpen(p->fd) );
  48170. assert( p->noSync );
  48171. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  48172. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  48173. );
  48174. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  48175. assert( pagerUseWal(p)==0 );
  48176. }
  48177. /* If changeCountDone is set, a RESERVED lock or greater must be held
  48178. ** on the file.
  48179. */
  48180. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  48181. assert( p->eLock!=PENDING_LOCK );
  48182. switch( p->eState ){
  48183. case PAGER_OPEN:
  48184. assert( !MEMDB );
  48185. assert( pPager->errCode==SQLITE_OK );
  48186. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  48187. break;
  48188. case PAGER_READER:
  48189. assert( pPager->errCode==SQLITE_OK );
  48190. assert( p->eLock!=UNKNOWN_LOCK );
  48191. assert( p->eLock>=SHARED_LOCK );
  48192. break;
  48193. case PAGER_WRITER_LOCKED:
  48194. assert( p->eLock!=UNKNOWN_LOCK );
  48195. assert( pPager->errCode==SQLITE_OK );
  48196. if( !pagerUseWal(pPager) ){
  48197. assert( p->eLock>=RESERVED_LOCK );
  48198. }
  48199. assert( pPager->dbSize==pPager->dbOrigSize );
  48200. assert( pPager->dbOrigSize==pPager->dbFileSize );
  48201. assert( pPager->dbOrigSize==pPager->dbHintSize );
  48202. assert( pPager->setMaster==0 );
  48203. break;
  48204. case PAGER_WRITER_CACHEMOD:
  48205. assert( p->eLock!=UNKNOWN_LOCK );
  48206. assert( pPager->errCode==SQLITE_OK );
  48207. if( !pagerUseWal(pPager) ){
  48208. /* It is possible that if journal_mode=wal here that neither the
  48209. ** journal file nor the WAL file are open. This happens during
  48210. ** a rollback transaction that switches from journal_mode=off
  48211. ** to journal_mode=wal.
  48212. */
  48213. assert( p->eLock>=RESERVED_LOCK );
  48214. assert( isOpen(p->jfd)
  48215. || p->journalMode==PAGER_JOURNALMODE_OFF
  48216. || p->journalMode==PAGER_JOURNALMODE_WAL
  48217. );
  48218. }
  48219. assert( pPager->dbOrigSize==pPager->dbFileSize );
  48220. assert( pPager->dbOrigSize==pPager->dbHintSize );
  48221. break;
  48222. case PAGER_WRITER_DBMOD:
  48223. assert( p->eLock==EXCLUSIVE_LOCK );
  48224. assert( pPager->errCode==SQLITE_OK );
  48225. assert( !pagerUseWal(pPager) );
  48226. assert( p->eLock>=EXCLUSIVE_LOCK );
  48227. assert( isOpen(p->jfd)
  48228. || p->journalMode==PAGER_JOURNALMODE_OFF
  48229. || p->journalMode==PAGER_JOURNALMODE_WAL
  48230. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  48231. );
  48232. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  48233. break;
  48234. case PAGER_WRITER_FINISHED:
  48235. assert( p->eLock==EXCLUSIVE_LOCK );
  48236. assert( pPager->errCode==SQLITE_OK );
  48237. assert( !pagerUseWal(pPager) );
  48238. assert( isOpen(p->jfd)
  48239. || p->journalMode==PAGER_JOURNALMODE_OFF
  48240. || p->journalMode==PAGER_JOURNALMODE_WAL
  48241. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  48242. );
  48243. break;
  48244. case PAGER_ERROR:
  48245. /* There must be at least one outstanding reference to the pager if
  48246. ** in ERROR state. Otherwise the pager should have already dropped
  48247. ** back to OPEN state.
  48248. */
  48249. assert( pPager->errCode!=SQLITE_OK );
  48250. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
  48251. break;
  48252. }
  48253. return 1;
  48254. }
  48255. #endif /* ifndef NDEBUG */
  48256. #ifdef SQLITE_DEBUG
  48257. /*
  48258. ** Return a pointer to a human readable string in a static buffer
  48259. ** containing the state of the Pager object passed as an argument. This
  48260. ** is intended to be used within debuggers. For example, as an alternative
  48261. ** to "print *pPager" in gdb:
  48262. **
  48263. ** (gdb) printf "%s", print_pager_state(pPager)
  48264. **
  48265. ** This routine has external linkage in order to suppress compiler warnings
  48266. ** about an unused function. It is enclosed within SQLITE_DEBUG and so does
  48267. ** not appear in normal builds.
  48268. */
  48269. char *print_pager_state(Pager *p){
  48270. static char zRet[1024];
  48271. sqlite3_snprintf(1024, zRet,
  48272. "Filename: %s\n"
  48273. "State: %s errCode=%d\n"
  48274. "Lock: %s\n"
  48275. "Locking mode: locking_mode=%s\n"
  48276. "Journal mode: journal_mode=%s\n"
  48277. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  48278. "Journal: journalOff=%lld journalHdr=%lld\n"
  48279. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  48280. , p->zFilename
  48281. , p->eState==PAGER_OPEN ? "OPEN" :
  48282. p->eState==PAGER_READER ? "READER" :
  48283. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  48284. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  48285. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  48286. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  48287. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  48288. , (int)p->errCode
  48289. , p->eLock==NO_LOCK ? "NO_LOCK" :
  48290. p->eLock==RESERVED_LOCK ? "RESERVED" :
  48291. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  48292. p->eLock==SHARED_LOCK ? "SHARED" :
  48293. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  48294. , p->exclusiveMode ? "exclusive" : "normal"
  48295. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  48296. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  48297. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  48298. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  48299. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  48300. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  48301. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  48302. , p->journalOff, p->journalHdr
  48303. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  48304. );
  48305. return zRet;
  48306. }
  48307. #endif
  48308. /* Forward references to the various page getters */
  48309. static int getPageNormal(Pager*,Pgno,DbPage**,int);
  48310. static int getPageError(Pager*,Pgno,DbPage**,int);
  48311. #if SQLITE_MAX_MMAP_SIZE>0
  48312. static int getPageMMap(Pager*,Pgno,DbPage**,int);
  48313. #endif
  48314. /*
  48315. ** Set the Pager.xGet method for the appropriate routine used to fetch
  48316. ** content from the pager.
  48317. */
  48318. static void setGetterMethod(Pager *pPager){
  48319. if( pPager->errCode ){
  48320. pPager->xGet = getPageError;
  48321. #if SQLITE_MAX_MMAP_SIZE>0
  48322. }else if( USEFETCH(pPager)
  48323. #ifdef SQLITE_HAS_CODEC
  48324. && pPager->xCodec==0
  48325. #endif
  48326. ){
  48327. pPager->xGet = getPageMMap;
  48328. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  48329. }else{
  48330. pPager->xGet = getPageNormal;
  48331. }
  48332. }
  48333. /*
  48334. ** Return true if it is necessary to write page *pPg into the sub-journal.
  48335. ** A page needs to be written into the sub-journal if there exists one
  48336. ** or more open savepoints for which:
  48337. **
  48338. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  48339. ** * The bit corresponding to the page-number is not set in
  48340. ** PagerSavepoint.pInSavepoint.
  48341. */
  48342. static int subjRequiresPage(PgHdr *pPg){
  48343. Pager *pPager = pPg->pPager;
  48344. PagerSavepoint *p;
  48345. Pgno pgno = pPg->pgno;
  48346. int i;
  48347. for(i=0; i<pPager->nSavepoint; i++){
  48348. p = &pPager->aSavepoint[i];
  48349. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  48350. return 1;
  48351. }
  48352. }
  48353. return 0;
  48354. }
  48355. #ifdef SQLITE_DEBUG
  48356. /*
  48357. ** Return true if the page is already in the journal file.
  48358. */
  48359. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  48360. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  48361. }
  48362. #endif
  48363. /*
  48364. ** Read a 32-bit integer from the given file descriptor. Store the integer
  48365. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  48366. ** error code is something goes wrong.
  48367. **
  48368. ** All values are stored on disk as big-endian.
  48369. */
  48370. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  48371. unsigned char ac[4];
  48372. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  48373. if( rc==SQLITE_OK ){
  48374. *pRes = sqlite3Get4byte(ac);
  48375. }
  48376. return rc;
  48377. }
  48378. /*
  48379. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  48380. */
  48381. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  48382. /*
  48383. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  48384. ** on success or an error code is something goes wrong.
  48385. */
  48386. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  48387. char ac[4];
  48388. put32bits(ac, val);
  48389. return sqlite3OsWrite(fd, ac, 4, offset);
  48390. }
  48391. /*
  48392. ** Unlock the database file to level eLock, which must be either NO_LOCK
  48393. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  48394. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  48395. **
  48396. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  48397. ** called, do not modify it. See the comment above the #define of
  48398. ** UNKNOWN_LOCK for an explanation of this.
  48399. */
  48400. static int pagerUnlockDb(Pager *pPager, int eLock){
  48401. int rc = SQLITE_OK;
  48402. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  48403. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  48404. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  48405. if( isOpen(pPager->fd) ){
  48406. assert( pPager->eLock>=eLock );
  48407. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  48408. if( pPager->eLock!=UNKNOWN_LOCK ){
  48409. pPager->eLock = (u8)eLock;
  48410. }
  48411. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  48412. }
  48413. return rc;
  48414. }
  48415. /*
  48416. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  48417. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  48418. ** Pager.eLock variable to the new locking state.
  48419. **
  48420. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  48421. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  48422. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  48423. ** of this.
  48424. */
  48425. static int pagerLockDb(Pager *pPager, int eLock){
  48426. int rc = SQLITE_OK;
  48427. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  48428. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  48429. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  48430. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  48431. pPager->eLock = (u8)eLock;
  48432. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  48433. }
  48434. }
  48435. return rc;
  48436. }
  48437. /*
  48438. ** This function determines whether or not the atomic-write or
  48439. ** atomic-batch-write optimizations can be used with this pager. The
  48440. ** atomic-write optimization can be used if:
  48441. **
  48442. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  48443. ** a database page may be written atomically, and
  48444. ** (b) the value returned by OsSectorSize() is less than or equal
  48445. ** to the page size.
  48446. **
  48447. ** If it can be used, then the value returned is the size of the journal
  48448. ** file when it contains rollback data for exactly one page.
  48449. **
  48450. ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
  48451. ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
  48452. ** returned in this case.
  48453. **
  48454. ** If neither optimization can be used, 0 is returned.
  48455. */
  48456. static int jrnlBufferSize(Pager *pPager){
  48457. assert( !MEMDB );
  48458. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  48459. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  48460. int dc; /* Device characteristics */
  48461. assert( isOpen(pPager->fd) );
  48462. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  48463. #else
  48464. UNUSED_PARAMETER(pPager);
  48465. #endif
  48466. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  48467. if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
  48468. return -1;
  48469. }
  48470. #endif
  48471. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  48472. {
  48473. int nSector = pPager->sectorSize;
  48474. int szPage = pPager->pageSize;
  48475. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  48476. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  48477. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  48478. return 0;
  48479. }
  48480. }
  48481. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  48482. #endif
  48483. return 0;
  48484. }
  48485. /*
  48486. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  48487. ** on the cache using a hash function. This is used for testing
  48488. ** and debugging only.
  48489. */
  48490. #ifdef SQLITE_CHECK_PAGES
  48491. /*
  48492. ** Return a 32-bit hash of the page data for pPage.
  48493. */
  48494. static u32 pager_datahash(int nByte, unsigned char *pData){
  48495. u32 hash = 0;
  48496. int i;
  48497. for(i=0; i<nByte; i++){
  48498. hash = (hash*1039) + pData[i];
  48499. }
  48500. return hash;
  48501. }
  48502. static u32 pager_pagehash(PgHdr *pPage){
  48503. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  48504. }
  48505. static void pager_set_pagehash(PgHdr *pPage){
  48506. pPage->pageHash = pager_pagehash(pPage);
  48507. }
  48508. /*
  48509. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  48510. ** is defined, and NDEBUG is not defined, an assert() statement checks
  48511. ** that the page is either dirty or still matches the calculated page-hash.
  48512. */
  48513. #define CHECK_PAGE(x) checkPage(x)
  48514. static void checkPage(PgHdr *pPg){
  48515. Pager *pPager = pPg->pPager;
  48516. assert( pPager->eState!=PAGER_ERROR );
  48517. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  48518. }
  48519. #else
  48520. #define pager_datahash(X,Y) 0
  48521. #define pager_pagehash(X) 0
  48522. #define pager_set_pagehash(X)
  48523. #define CHECK_PAGE(x)
  48524. #endif /* SQLITE_CHECK_PAGES */
  48525. /*
  48526. ** When this is called the journal file for pager pPager must be open.
  48527. ** This function attempts to read a master journal file name from the
  48528. ** end of the file and, if successful, copies it into memory supplied
  48529. ** by the caller. See comments above writeMasterJournal() for the format
  48530. ** used to store a master journal file name at the end of a journal file.
  48531. **
  48532. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  48533. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  48534. ** enough space to write the master journal name). If the master journal
  48535. ** name in the journal is longer than nMaster bytes (including a
  48536. ** nul-terminator), then this is handled as if no master journal name
  48537. ** were present in the journal.
  48538. **
  48539. ** If a master journal file name is present at the end of the journal
  48540. ** file, then it is copied into the buffer pointed to by zMaster. A
  48541. ** nul-terminator byte is appended to the buffer following the master
  48542. ** journal file name.
  48543. **
  48544. ** If it is determined that no master journal file name is present
  48545. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  48546. **
  48547. ** If an error occurs while reading from the journal file, an SQLite
  48548. ** error code is returned.
  48549. */
  48550. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  48551. int rc; /* Return code */
  48552. u32 len; /* Length in bytes of master journal name */
  48553. i64 szJ; /* Total size in bytes of journal file pJrnl */
  48554. u32 cksum; /* MJ checksum value read from journal */
  48555. u32 u; /* Unsigned loop counter */
  48556. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  48557. zMaster[0] = '\0';
  48558. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  48559. || szJ<16
  48560. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  48561. || len>=nMaster
  48562. || len>szJ-16
  48563. || len==0
  48564. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  48565. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  48566. || memcmp(aMagic, aJournalMagic, 8)
  48567. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  48568. ){
  48569. return rc;
  48570. }
  48571. /* See if the checksum matches the master journal name */
  48572. for(u=0; u<len; u++){
  48573. cksum -= zMaster[u];
  48574. }
  48575. if( cksum ){
  48576. /* If the checksum doesn't add up, then one or more of the disk sectors
  48577. ** containing the master journal filename is corrupted. This means
  48578. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  48579. ** master-journal filename.
  48580. */
  48581. len = 0;
  48582. }
  48583. zMaster[len] = '\0';
  48584. return SQLITE_OK;
  48585. }
  48586. /*
  48587. ** Return the offset of the sector boundary at or immediately
  48588. ** following the value in pPager->journalOff, assuming a sector
  48589. ** size of pPager->sectorSize bytes.
  48590. **
  48591. ** i.e for a sector size of 512:
  48592. **
  48593. ** Pager.journalOff Return value
  48594. ** ---------------------------------------
  48595. ** 0 0
  48596. ** 512 512
  48597. ** 100 512
  48598. ** 2000 2048
  48599. **
  48600. */
  48601. static i64 journalHdrOffset(Pager *pPager){
  48602. i64 offset = 0;
  48603. i64 c = pPager->journalOff;
  48604. if( c ){
  48605. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  48606. }
  48607. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  48608. assert( offset>=c );
  48609. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  48610. return offset;
  48611. }
  48612. /*
  48613. ** The journal file must be open when this function is called.
  48614. **
  48615. ** This function is a no-op if the journal file has not been written to
  48616. ** within the current transaction (i.e. if Pager.journalOff==0).
  48617. **
  48618. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  48619. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  48620. ** zero the 28-byte header at the start of the journal file. In either case,
  48621. ** if the pager is not in no-sync mode, sync the journal file immediately
  48622. ** after writing or truncating it.
  48623. **
  48624. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  48625. ** following the truncation or zeroing described above the size of the
  48626. ** journal file in bytes is larger than this value, then truncate the
  48627. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  48628. ** not need to be synced following this operation.
  48629. **
  48630. ** If an IO error occurs, abandon processing and return the IO error code.
  48631. ** Otherwise, return SQLITE_OK.
  48632. */
  48633. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  48634. int rc = SQLITE_OK; /* Return code */
  48635. assert( isOpen(pPager->jfd) );
  48636. assert( !sqlite3JournalIsInMemory(pPager->jfd) );
  48637. if( pPager->journalOff ){
  48638. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  48639. IOTRACE(("JZEROHDR %p\n", pPager))
  48640. if( doTruncate || iLimit==0 ){
  48641. rc = sqlite3OsTruncate(pPager->jfd, 0);
  48642. }else{
  48643. static const char zeroHdr[28] = {0};
  48644. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  48645. }
  48646. if( rc==SQLITE_OK && !pPager->noSync ){
  48647. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  48648. }
  48649. /* At this point the transaction is committed but the write lock
  48650. ** is still held on the file. If there is a size limit configured for
  48651. ** the persistent journal and the journal file currently consumes more
  48652. ** space than that limit allows for, truncate it now. There is no need
  48653. ** to sync the file following this operation.
  48654. */
  48655. if( rc==SQLITE_OK && iLimit>0 ){
  48656. i64 sz;
  48657. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  48658. if( rc==SQLITE_OK && sz>iLimit ){
  48659. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  48660. }
  48661. }
  48662. }
  48663. return rc;
  48664. }
  48665. /*
  48666. ** The journal file must be open when this routine is called. A journal
  48667. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  48668. ** current location.
  48669. **
  48670. ** The format for the journal header is as follows:
  48671. ** - 8 bytes: Magic identifying journal format.
  48672. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  48673. ** - 4 bytes: Random number used for page hash.
  48674. ** - 4 bytes: Initial database page count.
  48675. ** - 4 bytes: Sector size used by the process that wrote this journal.
  48676. ** - 4 bytes: Database page size.
  48677. **
  48678. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  48679. */
  48680. static int writeJournalHdr(Pager *pPager){
  48681. int rc = SQLITE_OK; /* Return code */
  48682. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  48683. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  48684. u32 nWrite; /* Bytes of header sector written */
  48685. int ii; /* Loop counter */
  48686. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  48687. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  48688. nHeader = JOURNAL_HDR_SZ(pPager);
  48689. }
  48690. /* If there are active savepoints and any of them were created
  48691. ** since the most recent journal header was written, update the
  48692. ** PagerSavepoint.iHdrOffset fields now.
  48693. */
  48694. for(ii=0; ii<pPager->nSavepoint; ii++){
  48695. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  48696. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  48697. }
  48698. }
  48699. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  48700. /*
  48701. ** Write the nRec Field - the number of page records that follow this
  48702. ** journal header. Normally, zero is written to this value at this time.
  48703. ** After the records are added to the journal (and the journal synced,
  48704. ** if in full-sync mode), the zero is overwritten with the true number
  48705. ** of records (see syncJournal()).
  48706. **
  48707. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  48708. ** reading the journal this value tells SQLite to assume that the
  48709. ** rest of the journal file contains valid page records. This assumption
  48710. ** is dangerous, as if a failure occurred whilst writing to the journal
  48711. ** file it may contain some garbage data. There are two scenarios
  48712. ** where this risk can be ignored:
  48713. **
  48714. ** * When the pager is in no-sync mode. Corruption can follow a
  48715. ** power failure in this case anyway.
  48716. **
  48717. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  48718. ** that garbage data is never appended to the journal file.
  48719. */
  48720. assert( isOpen(pPager->fd) || pPager->noSync );
  48721. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  48722. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  48723. ){
  48724. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  48725. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  48726. }else{
  48727. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  48728. }
  48729. /* The random check-hash initializer */
  48730. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  48731. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  48732. /* The initial database size */
  48733. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  48734. /* The assumed sector size for this process */
  48735. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  48736. /* The page size */
  48737. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  48738. /* Initializing the tail of the buffer is not necessary. Everything
  48739. ** works find if the following memset() is omitted. But initializing
  48740. ** the memory prevents valgrind from complaining, so we are willing to
  48741. ** take the performance hit.
  48742. */
  48743. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  48744. nHeader-(sizeof(aJournalMagic)+20));
  48745. /* In theory, it is only necessary to write the 28 bytes that the
  48746. ** journal header consumes to the journal file here. Then increment the
  48747. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  48748. ** record is written to the following sector (leaving a gap in the file
  48749. ** that will be implicitly filled in by the OS).
  48750. **
  48751. ** However it has been discovered that on some systems this pattern can
  48752. ** be significantly slower than contiguously writing data to the file,
  48753. ** even if that means explicitly writing data to the block of
  48754. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  48755. ** is done.
  48756. **
  48757. ** The loop is required here in case the sector-size is larger than the
  48758. ** database page size. Since the zHeader buffer is only Pager.pageSize
  48759. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  48760. ** to populate the entire journal header sector.
  48761. */
  48762. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  48763. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  48764. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  48765. assert( pPager->journalHdr <= pPager->journalOff );
  48766. pPager->journalOff += nHeader;
  48767. }
  48768. return rc;
  48769. }
  48770. /*
  48771. ** The journal file must be open when this is called. A journal header file
  48772. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  48773. ** file. The current location in the journal file is given by
  48774. ** pPager->journalOff. See comments above function writeJournalHdr() for
  48775. ** a description of the journal header format.
  48776. **
  48777. ** If the header is read successfully, *pNRec is set to the number of
  48778. ** page records following this header and *pDbSize is set to the size of the
  48779. ** database before the transaction began, in pages. Also, pPager->cksumInit
  48780. ** is set to the value read from the journal header. SQLITE_OK is returned
  48781. ** in this case.
  48782. **
  48783. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  48784. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  48785. ** cannot be read from the journal file an error code is returned.
  48786. */
  48787. static int readJournalHdr(
  48788. Pager *pPager, /* Pager object */
  48789. int isHot,
  48790. i64 journalSize, /* Size of the open journal file in bytes */
  48791. u32 *pNRec, /* OUT: Value read from the nRec field */
  48792. u32 *pDbSize /* OUT: Value of original database size field */
  48793. ){
  48794. int rc; /* Return code */
  48795. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  48796. i64 iHdrOff; /* Offset of journal header being read */
  48797. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  48798. /* Advance Pager.journalOff to the start of the next sector. If the
  48799. ** journal file is too small for there to be a header stored at this
  48800. ** point, return SQLITE_DONE.
  48801. */
  48802. pPager->journalOff = journalHdrOffset(pPager);
  48803. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  48804. return SQLITE_DONE;
  48805. }
  48806. iHdrOff = pPager->journalOff;
  48807. /* Read in the first 8 bytes of the journal header. If they do not match
  48808. ** the magic string found at the start of each journal header, return
  48809. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  48810. ** proceed.
  48811. */
  48812. if( isHot || iHdrOff!=pPager->journalHdr ){
  48813. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  48814. if( rc ){
  48815. return rc;
  48816. }
  48817. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  48818. return SQLITE_DONE;
  48819. }
  48820. }
  48821. /* Read the first three 32-bit fields of the journal header: The nRec
  48822. ** field, the checksum-initializer and the database size at the start
  48823. ** of the transaction. Return an error code if anything goes wrong.
  48824. */
  48825. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  48826. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  48827. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  48828. ){
  48829. return rc;
  48830. }
  48831. if( pPager->journalOff==0 ){
  48832. u32 iPageSize; /* Page-size field of journal header */
  48833. u32 iSectorSize; /* Sector-size field of journal header */
  48834. /* Read the page-size and sector-size journal header fields. */
  48835. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  48836. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  48837. ){
  48838. return rc;
  48839. }
  48840. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  48841. ** journal header to zero. In this case, assume that the Pager.pageSize
  48842. ** variable is already set to the correct page size.
  48843. */
  48844. if( iPageSize==0 ){
  48845. iPageSize = pPager->pageSize;
  48846. }
  48847. /* Check that the values read from the page-size and sector-size fields
  48848. ** are within range. To be 'in range', both values need to be a power
  48849. ** of two greater than or equal to 512 or 32, and not greater than their
  48850. ** respective compile time maximum limits.
  48851. */
  48852. if( iPageSize<512 || iSectorSize<32
  48853. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  48854. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  48855. ){
  48856. /* If the either the page-size or sector-size in the journal-header is
  48857. ** invalid, then the process that wrote the journal-header must have
  48858. ** crashed before the header was synced. In this case stop reading
  48859. ** the journal file here.
  48860. */
  48861. return SQLITE_DONE;
  48862. }
  48863. /* Update the page-size to match the value read from the journal.
  48864. ** Use a testcase() macro to make sure that malloc failure within
  48865. ** PagerSetPagesize() is tested.
  48866. */
  48867. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  48868. testcase( rc!=SQLITE_OK );
  48869. /* Update the assumed sector-size to match the value used by
  48870. ** the process that created this journal. If this journal was
  48871. ** created by a process other than this one, then this routine
  48872. ** is being called from within pager_playback(). The local value
  48873. ** of Pager.sectorSize is restored at the end of that routine.
  48874. */
  48875. pPager->sectorSize = iSectorSize;
  48876. }
  48877. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  48878. return rc;
  48879. }
  48880. /*
  48881. ** Write the supplied master journal name into the journal file for pager
  48882. ** pPager at the current location. The master journal name must be the last
  48883. ** thing written to a journal file. If the pager is in full-sync mode, the
  48884. ** journal file descriptor is advanced to the next sector boundary before
  48885. ** anything is written. The format is:
  48886. **
  48887. ** + 4 bytes: PAGER_MJ_PGNO.
  48888. ** + N bytes: Master journal filename in utf-8.
  48889. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  48890. ** + 4 bytes: Master journal name checksum.
  48891. ** + 8 bytes: aJournalMagic[].
  48892. **
  48893. ** The master journal page checksum is the sum of the bytes in the master
  48894. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  48895. **
  48896. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  48897. ** this call is a no-op.
  48898. */
  48899. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  48900. int rc; /* Return code */
  48901. int nMaster; /* Length of string zMaster */
  48902. i64 iHdrOff; /* Offset of header in journal file */
  48903. i64 jrnlSize; /* Size of journal file on disk */
  48904. u32 cksum = 0; /* Checksum of string zMaster */
  48905. assert( pPager->setMaster==0 );
  48906. assert( !pagerUseWal(pPager) );
  48907. if( !zMaster
  48908. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  48909. || !isOpen(pPager->jfd)
  48910. ){
  48911. return SQLITE_OK;
  48912. }
  48913. pPager->setMaster = 1;
  48914. assert( pPager->journalHdr <= pPager->journalOff );
  48915. /* Calculate the length in bytes and the checksum of zMaster */
  48916. for(nMaster=0; zMaster[nMaster]; nMaster++){
  48917. cksum += zMaster[nMaster];
  48918. }
  48919. /* If in full-sync mode, advance to the next disk sector before writing
  48920. ** the master journal name. This is in case the previous page written to
  48921. ** the journal has already been synced.
  48922. */
  48923. if( pPager->fullSync ){
  48924. pPager->journalOff = journalHdrOffset(pPager);
  48925. }
  48926. iHdrOff = pPager->journalOff;
  48927. /* Write the master journal data to the end of the journal file. If
  48928. ** an error occurs, return the error code to the caller.
  48929. */
  48930. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  48931. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  48932. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  48933. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  48934. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  48935. iHdrOff+4+nMaster+8)))
  48936. ){
  48937. return rc;
  48938. }
  48939. pPager->journalOff += (nMaster+20);
  48940. /* If the pager is in peristent-journal mode, then the physical
  48941. ** journal-file may extend past the end of the master-journal name
  48942. ** and 8 bytes of magic data just written to the file. This is
  48943. ** dangerous because the code to rollback a hot-journal file
  48944. ** will not be able to find the master-journal name to determine
  48945. ** whether or not the journal is hot.
  48946. **
  48947. ** Easiest thing to do in this scenario is to truncate the journal
  48948. ** file to the required size.
  48949. */
  48950. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  48951. && jrnlSize>pPager->journalOff
  48952. ){
  48953. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  48954. }
  48955. return rc;
  48956. }
  48957. /*
  48958. ** Discard the entire contents of the in-memory page-cache.
  48959. */
  48960. static void pager_reset(Pager *pPager){
  48961. pPager->iDataVersion++;
  48962. sqlite3BackupRestart(pPager->pBackup);
  48963. sqlite3PcacheClear(pPager->pPCache);
  48964. }
  48965. /*
  48966. ** Return the pPager->iDataVersion value
  48967. */
  48968. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  48969. return pPager->iDataVersion;
  48970. }
  48971. /*
  48972. ** Free all structures in the Pager.aSavepoint[] array and set both
  48973. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  48974. ** if it is open and the pager is not in exclusive mode.
  48975. */
  48976. static void releaseAllSavepoints(Pager *pPager){
  48977. int ii; /* Iterator for looping through Pager.aSavepoint */
  48978. for(ii=0; ii<pPager->nSavepoint; ii++){
  48979. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  48980. }
  48981. if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
  48982. sqlite3OsClose(pPager->sjfd);
  48983. }
  48984. sqlite3_free(pPager->aSavepoint);
  48985. pPager->aSavepoint = 0;
  48986. pPager->nSavepoint = 0;
  48987. pPager->nSubRec = 0;
  48988. }
  48989. /*
  48990. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  48991. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  48992. ** or SQLITE_NOMEM if a malloc failure occurs.
  48993. */
  48994. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  48995. int ii; /* Loop counter */
  48996. int rc = SQLITE_OK; /* Result code */
  48997. for(ii=0; ii<pPager->nSavepoint; ii++){
  48998. PagerSavepoint *p = &pPager->aSavepoint[ii];
  48999. if( pgno<=p->nOrig ){
  49000. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  49001. testcase( rc==SQLITE_NOMEM );
  49002. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  49003. }
  49004. }
  49005. return rc;
  49006. }
  49007. /*
  49008. ** This function is a no-op if the pager is in exclusive mode and not
  49009. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  49010. ** state.
  49011. **
  49012. ** If the pager is not in exclusive-access mode, the database file is
  49013. ** completely unlocked. If the file is unlocked and the file-system does
  49014. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  49015. ** closed (if it is open).
  49016. **
  49017. ** If the pager is in ERROR state when this function is called, the
  49018. ** contents of the pager cache are discarded before switching back to
  49019. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  49020. ** or not, any journal file left in the file-system will be treated
  49021. ** as a hot-journal and rolled back the next time a read-transaction
  49022. ** is opened (by this or by any other connection).
  49023. */
  49024. static void pager_unlock(Pager *pPager){
  49025. assert( pPager->eState==PAGER_READER
  49026. || pPager->eState==PAGER_OPEN
  49027. || pPager->eState==PAGER_ERROR
  49028. );
  49029. sqlite3BitvecDestroy(pPager->pInJournal);
  49030. pPager->pInJournal = 0;
  49031. releaseAllSavepoints(pPager);
  49032. if( pagerUseWal(pPager) ){
  49033. assert( !isOpen(pPager->jfd) );
  49034. sqlite3WalEndReadTransaction(pPager->pWal);
  49035. pPager->eState = PAGER_OPEN;
  49036. }else if( !pPager->exclusiveMode ){
  49037. int rc; /* Error code returned by pagerUnlockDb() */
  49038. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  49039. /* If the operating system support deletion of open files, then
  49040. ** close the journal file when dropping the database lock. Otherwise
  49041. ** another connection with journal_mode=delete might delete the file
  49042. ** out from under us.
  49043. */
  49044. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  49045. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  49046. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  49047. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  49048. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  49049. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  49050. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  49051. || 1!=(pPager->journalMode & 5)
  49052. ){
  49053. sqlite3OsClose(pPager->jfd);
  49054. }
  49055. /* If the pager is in the ERROR state and the call to unlock the database
  49056. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  49057. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  49058. ** is necessary.
  49059. */
  49060. rc = pagerUnlockDb(pPager, NO_LOCK);
  49061. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  49062. pPager->eLock = UNKNOWN_LOCK;
  49063. }
  49064. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  49065. ** without clearing the error code. This is intentional - the error
  49066. ** code is cleared and the cache reset in the block below.
  49067. */
  49068. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  49069. pPager->changeCountDone = 0;
  49070. pPager->eState = PAGER_OPEN;
  49071. }
  49072. /* If Pager.errCode is set, the contents of the pager cache cannot be
  49073. ** trusted. Now that there are no outstanding references to the pager,
  49074. ** it can safely move back to PAGER_OPEN state. This happens in both
  49075. ** normal and exclusive-locking mode.
  49076. */
  49077. assert( pPager->errCode==SQLITE_OK || !MEMDB );
  49078. if( pPager->errCode ){
  49079. if( pPager->tempFile==0 ){
  49080. pager_reset(pPager);
  49081. pPager->changeCountDone = 0;
  49082. pPager->eState = PAGER_OPEN;
  49083. }else{
  49084. pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
  49085. }
  49086. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  49087. pPager->errCode = SQLITE_OK;
  49088. setGetterMethod(pPager);
  49089. }
  49090. pPager->journalOff = 0;
  49091. pPager->journalHdr = 0;
  49092. pPager->setMaster = 0;
  49093. }
  49094. /*
  49095. ** This function is called whenever an IOERR or FULL error that requires
  49096. ** the pager to transition into the ERROR state may ahve occurred.
  49097. ** The first argument is a pointer to the pager structure, the second
  49098. ** the error-code about to be returned by a pager API function. The
  49099. ** value returned is a copy of the second argument to this function.
  49100. **
  49101. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  49102. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  49103. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  49104. ** all major API calls on the Pager will immediately return Pager.errCode.
  49105. **
  49106. ** The ERROR state indicates that the contents of the pager-cache
  49107. ** cannot be trusted. This state can be cleared by completely discarding
  49108. ** the contents of the pager-cache. If a transaction was active when
  49109. ** the persistent error occurred, then the rollback journal may need
  49110. ** to be replayed to restore the contents of the database file (as if
  49111. ** it were a hot-journal).
  49112. */
  49113. static int pager_error(Pager *pPager, int rc){
  49114. int rc2 = rc & 0xff;
  49115. assert( rc==SQLITE_OK || !MEMDB );
  49116. assert(
  49117. pPager->errCode==SQLITE_FULL ||
  49118. pPager->errCode==SQLITE_OK ||
  49119. (pPager->errCode & 0xff)==SQLITE_IOERR
  49120. );
  49121. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  49122. pPager->errCode = rc;
  49123. pPager->eState = PAGER_ERROR;
  49124. setGetterMethod(pPager);
  49125. }
  49126. return rc;
  49127. }
  49128. static int pager_truncate(Pager *pPager, Pgno nPage);
  49129. /*
  49130. ** The write transaction open on pPager is being committed (bCommit==1)
  49131. ** or rolled back (bCommit==0).
  49132. **
  49133. ** Return TRUE if and only if all dirty pages should be flushed to disk.
  49134. **
  49135. ** Rules:
  49136. **
  49137. ** * For non-TEMP databases, always sync to disk. This is necessary
  49138. ** for transactions to be durable.
  49139. **
  49140. ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
  49141. ** file has been created already (via a spill on pagerStress()) and
  49142. ** when the number of dirty pages in memory exceeds 25% of the total
  49143. ** cache size.
  49144. */
  49145. static int pagerFlushOnCommit(Pager *pPager, int bCommit){
  49146. if( pPager->tempFile==0 ) return 1;
  49147. if( !bCommit ) return 0;
  49148. if( !isOpen(pPager->fd) ) return 0;
  49149. return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
  49150. }
  49151. /*
  49152. ** This routine ends a transaction. A transaction is usually ended by
  49153. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  49154. ** after rollback of a hot-journal, or if an error occurs while opening
  49155. ** the journal file or writing the very first journal-header of a
  49156. ** database transaction.
  49157. **
  49158. ** This routine is never called in PAGER_ERROR state. If it is called
  49159. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  49160. ** exclusive than a RESERVED lock, it is a no-op.
  49161. **
  49162. ** Otherwise, any active savepoints are released.
  49163. **
  49164. ** If the journal file is open, then it is "finalized". Once a journal
  49165. ** file has been finalized it is not possible to use it to roll back a
  49166. ** transaction. Nor will it be considered to be a hot-journal by this
  49167. ** or any other database connection. Exactly how a journal is finalized
  49168. ** depends on whether or not the pager is running in exclusive mode and
  49169. ** the current journal-mode (Pager.journalMode value), as follows:
  49170. **
  49171. ** journalMode==MEMORY
  49172. ** Journal file descriptor is simply closed. This destroys an
  49173. ** in-memory journal.
  49174. **
  49175. ** journalMode==TRUNCATE
  49176. ** Journal file is truncated to zero bytes in size.
  49177. **
  49178. ** journalMode==PERSIST
  49179. ** The first 28 bytes of the journal file are zeroed. This invalidates
  49180. ** the first journal header in the file, and hence the entire journal
  49181. ** file. An invalid journal file cannot be rolled back.
  49182. **
  49183. ** journalMode==DELETE
  49184. ** The journal file is closed and deleted using sqlite3OsDelete().
  49185. **
  49186. ** If the pager is running in exclusive mode, this method of finalizing
  49187. ** the journal file is never used. Instead, if the journalMode is
  49188. ** DELETE and the pager is in exclusive mode, the method described under
  49189. ** journalMode==PERSIST is used instead.
  49190. **
  49191. ** After the journal is finalized, the pager moves to PAGER_READER state.
  49192. ** If running in non-exclusive rollback mode, the lock on the file is
  49193. ** downgraded to a SHARED_LOCK.
  49194. **
  49195. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  49196. ** any of the IO operations to finalize the journal file or unlock the
  49197. ** database then the IO error code is returned to the user. If the
  49198. ** operation to finalize the journal file fails, then the code still
  49199. ** tries to unlock the database file if not in exclusive mode. If the
  49200. ** unlock operation fails as well, then the first error code related
  49201. ** to the first error encountered (the journal finalization one) is
  49202. ** returned.
  49203. */
  49204. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  49205. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  49206. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  49207. /* Do nothing if the pager does not have an open write transaction
  49208. ** or at least a RESERVED lock. This function may be called when there
  49209. ** is no write-transaction active but a RESERVED or greater lock is
  49210. ** held under two circumstances:
  49211. **
  49212. ** 1. After a successful hot-journal rollback, it is called with
  49213. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  49214. **
  49215. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  49216. ** lock switches back to locking_mode=normal and then executes a
  49217. ** read-transaction, this function is called with eState==PAGER_READER
  49218. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  49219. */
  49220. assert( assert_pager_state(pPager) );
  49221. assert( pPager->eState!=PAGER_ERROR );
  49222. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  49223. return SQLITE_OK;
  49224. }
  49225. releaseAllSavepoints(pPager);
  49226. assert( isOpen(pPager->jfd) || pPager->pInJournal==0
  49227. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  49228. );
  49229. if( isOpen(pPager->jfd) ){
  49230. assert( !pagerUseWal(pPager) );
  49231. /* Finalize the journal file. */
  49232. if( sqlite3JournalIsInMemory(pPager->jfd) ){
  49233. /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
  49234. sqlite3OsClose(pPager->jfd);
  49235. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  49236. if( pPager->journalOff==0 ){
  49237. rc = SQLITE_OK;
  49238. }else{
  49239. rc = sqlite3OsTruncate(pPager->jfd, 0);
  49240. if( rc==SQLITE_OK && pPager->fullSync ){
  49241. /* Make sure the new file size is written into the inode right away.
  49242. ** Otherwise the journal might resurrect following a power loss and
  49243. ** cause the last transaction to roll back. See
  49244. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  49245. */
  49246. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  49247. }
  49248. }
  49249. pPager->journalOff = 0;
  49250. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  49251. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  49252. ){
  49253. rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
  49254. pPager->journalOff = 0;
  49255. }else{
  49256. /* This branch may be executed with Pager.journalMode==MEMORY if
  49257. ** a hot-journal was just rolled back. In this case the journal
  49258. ** file should be closed and deleted. If this connection writes to
  49259. ** the database file, it will do so using an in-memory journal.
  49260. */
  49261. int bDelete = !pPager->tempFile;
  49262. assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
  49263. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  49264. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  49265. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  49266. );
  49267. sqlite3OsClose(pPager->jfd);
  49268. if( bDelete ){
  49269. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
  49270. }
  49271. }
  49272. }
  49273. #ifdef SQLITE_CHECK_PAGES
  49274. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  49275. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  49276. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  49277. if( p ){
  49278. p->pageHash = 0;
  49279. sqlite3PagerUnrefNotNull(p);
  49280. }
  49281. }
  49282. #endif
  49283. sqlite3BitvecDestroy(pPager->pInJournal);
  49284. pPager->pInJournal = 0;
  49285. pPager->nRec = 0;
  49286. if( rc==SQLITE_OK ){
  49287. if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
  49288. sqlite3PcacheCleanAll(pPager->pPCache);
  49289. }else{
  49290. sqlite3PcacheClearWritable(pPager->pPCache);
  49291. }
  49292. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  49293. }
  49294. if( pagerUseWal(pPager) ){
  49295. /* Drop the WAL write-lock, if any. Also, if the connection was in
  49296. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  49297. ** lock held on the database file.
  49298. */
  49299. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  49300. assert( rc2==SQLITE_OK );
  49301. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  49302. /* This branch is taken when committing a transaction in rollback-journal
  49303. ** mode if the database file on disk is larger than the database image.
  49304. ** At this point the journal has been finalized and the transaction
  49305. ** successfully committed, but the EXCLUSIVE lock is still held on the
  49306. ** file. So it is safe to truncate the database file to its minimum
  49307. ** required size. */
  49308. assert( pPager->eLock==EXCLUSIVE_LOCK );
  49309. rc = pager_truncate(pPager, pPager->dbSize);
  49310. }
  49311. if( rc==SQLITE_OK && bCommit ){
  49312. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  49313. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  49314. }
  49315. if( !pPager->exclusiveMode
  49316. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  49317. ){
  49318. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  49319. pPager->changeCountDone = 0;
  49320. }
  49321. pPager->eState = PAGER_READER;
  49322. pPager->setMaster = 0;
  49323. return (rc==SQLITE_OK?rc2:rc);
  49324. }
  49325. /*
  49326. ** Execute a rollback if a transaction is active and unlock the
  49327. ** database file.
  49328. **
  49329. ** If the pager has already entered the ERROR state, do not attempt
  49330. ** the rollback at this time. Instead, pager_unlock() is called. The
  49331. ** call to pager_unlock() will discard all in-memory pages, unlock
  49332. ** the database file and move the pager back to OPEN state. If this
  49333. ** means that there is a hot-journal left in the file-system, the next
  49334. ** connection to obtain a shared lock on the pager (which may be this one)
  49335. ** will roll it back.
  49336. **
  49337. ** If the pager has not already entered the ERROR state, but an IO or
  49338. ** malloc error occurs during a rollback, then this will itself cause
  49339. ** the pager to enter the ERROR state. Which will be cleared by the
  49340. ** call to pager_unlock(), as described above.
  49341. */
  49342. static void pagerUnlockAndRollback(Pager *pPager){
  49343. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  49344. assert( assert_pager_state(pPager) );
  49345. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  49346. sqlite3BeginBenignMalloc();
  49347. sqlite3PagerRollback(pPager);
  49348. sqlite3EndBenignMalloc();
  49349. }else if( !pPager->exclusiveMode ){
  49350. assert( pPager->eState==PAGER_READER );
  49351. pager_end_transaction(pPager, 0, 0);
  49352. }
  49353. }
  49354. pager_unlock(pPager);
  49355. }
  49356. /*
  49357. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  49358. ** of data. Compute and return a checksum based ont the contents of the
  49359. ** page of data and the current value of pPager->cksumInit.
  49360. **
  49361. ** This is not a real checksum. It is really just the sum of the
  49362. ** random initial value (pPager->cksumInit) and every 200th byte
  49363. ** of the page data, starting with byte offset (pPager->pageSize%200).
  49364. ** Each byte is interpreted as an 8-bit unsigned integer.
  49365. **
  49366. ** Changing the formula used to compute this checksum results in an
  49367. ** incompatible journal file format.
  49368. **
  49369. ** If journal corruption occurs due to a power failure, the most likely
  49370. ** scenario is that one end or the other of the record will be changed.
  49371. ** It is much less likely that the two ends of the journal record will be
  49372. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  49373. ** though fast and simple, catches the mostly likely kind of corruption.
  49374. */
  49375. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  49376. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  49377. int i = pPager->pageSize-200; /* Loop counter */
  49378. while( i>0 ){
  49379. cksum += aData[i];
  49380. i -= 200;
  49381. }
  49382. return cksum;
  49383. }
  49384. /*
  49385. ** Report the current page size and number of reserved bytes back
  49386. ** to the codec.
  49387. */
  49388. #ifdef SQLITE_HAS_CODEC
  49389. static void pagerReportSize(Pager *pPager){
  49390. if( pPager->xCodecSizeChng ){
  49391. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  49392. (int)pPager->nReserve);
  49393. }
  49394. }
  49395. #else
  49396. # define pagerReportSize(X) /* No-op if we do not support a codec */
  49397. #endif
  49398. #ifdef SQLITE_HAS_CODEC
  49399. /*
  49400. ** Make sure the number of reserved bits is the same in the destination
  49401. ** pager as it is in the source. This comes up when a VACUUM changes the
  49402. ** number of reserved bits to the "optimal" amount.
  49403. */
  49404. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
  49405. if( pDest->nReserve!=pSrc->nReserve ){
  49406. pDest->nReserve = pSrc->nReserve;
  49407. pagerReportSize(pDest);
  49408. }
  49409. }
  49410. #endif
  49411. /*
  49412. ** Read a single page from either the journal file (if isMainJrnl==1) or
  49413. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  49414. ** The page begins at offset *pOffset into the file. The *pOffset
  49415. ** value is increased to the start of the next page in the journal.
  49416. **
  49417. ** The main rollback journal uses checksums - the statement journal does
  49418. ** not.
  49419. **
  49420. ** If the page number of the page record read from the (sub-)journal file
  49421. ** is greater than the current value of Pager.dbSize, then playback is
  49422. ** skipped and SQLITE_OK is returned.
  49423. **
  49424. ** If pDone is not NULL, then it is a record of pages that have already
  49425. ** been played back. If the page at *pOffset has already been played back
  49426. ** (if the corresponding pDone bit is set) then skip the playback.
  49427. ** Make sure the pDone bit corresponding to the *pOffset page is set
  49428. ** prior to returning.
  49429. **
  49430. ** If the page record is successfully read from the (sub-)journal file
  49431. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  49432. ** while reading the record from the (sub-)journal file or while writing
  49433. ** to the database file, then the IO error code is returned. If data
  49434. ** is successfully read from the (sub-)journal file but appears to be
  49435. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  49436. ** two circumstances:
  49437. **
  49438. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  49439. ** * If the record is being rolled back from the main journal file
  49440. ** and the checksum field does not match the record content.
  49441. **
  49442. ** Neither of these two scenarios are possible during a savepoint rollback.
  49443. **
  49444. ** If this is a savepoint rollback, then memory may have to be dynamically
  49445. ** allocated by this function. If this is the case and an allocation fails,
  49446. ** SQLITE_NOMEM is returned.
  49447. */
  49448. static int pager_playback_one_page(
  49449. Pager *pPager, /* The pager being played back */
  49450. i64 *pOffset, /* Offset of record to playback */
  49451. Bitvec *pDone, /* Bitvec of pages already played back */
  49452. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  49453. int isSavepnt /* True for a savepoint rollback */
  49454. ){
  49455. int rc;
  49456. PgHdr *pPg; /* An existing page in the cache */
  49457. Pgno pgno; /* The page number of a page in journal */
  49458. u32 cksum; /* Checksum used for sanity checking */
  49459. char *aData; /* Temporary storage for the page */
  49460. sqlite3_file *jfd; /* The file descriptor for the journal file */
  49461. int isSynced; /* True if journal page is synced */
  49462. #ifdef SQLITE_HAS_CODEC
  49463. /* The jrnlEnc flag is true if Journal pages should be passed through
  49464. ** the codec. It is false for pure in-memory journals. */
  49465. const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
  49466. #endif
  49467. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  49468. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  49469. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  49470. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  49471. aData = pPager->pTmpSpace;
  49472. assert( aData ); /* Temp storage must have already been allocated */
  49473. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  49474. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  49475. ** or savepoint rollback done at the request of the caller) or this is
  49476. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  49477. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  49478. ** only reads from the main journal, not the sub-journal.
  49479. */
  49480. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  49481. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  49482. );
  49483. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  49484. /* Read the page number and page data from the journal or sub-journal
  49485. ** file. Return an error code to the caller if an IO error occurs.
  49486. */
  49487. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  49488. rc = read32bits(jfd, *pOffset, &pgno);
  49489. if( rc!=SQLITE_OK ) return rc;
  49490. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  49491. if( rc!=SQLITE_OK ) return rc;
  49492. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  49493. /* Sanity checking on the page. This is more important that I originally
  49494. ** thought. If a power failure occurs while the journal is being written,
  49495. ** it could cause invalid data to be written into the journal. We need to
  49496. ** detect this invalid data (with high probability) and ignore it.
  49497. */
  49498. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  49499. assert( !isSavepnt );
  49500. return SQLITE_DONE;
  49501. }
  49502. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  49503. return SQLITE_OK;
  49504. }
  49505. if( isMainJrnl ){
  49506. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  49507. if( rc ) return rc;
  49508. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  49509. return SQLITE_DONE;
  49510. }
  49511. }
  49512. /* If this page has already been played back before during the current
  49513. ** rollback, then don't bother to play it back again.
  49514. */
  49515. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  49516. return rc;
  49517. }
  49518. /* When playing back page 1, restore the nReserve setting
  49519. */
  49520. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  49521. pPager->nReserve = ((u8*)aData)[20];
  49522. pagerReportSize(pPager);
  49523. }
  49524. /* If the pager is in CACHEMOD state, then there must be a copy of this
  49525. ** page in the pager cache. In this case just update the pager cache,
  49526. ** not the database file. The page is left marked dirty in this case.
  49527. **
  49528. ** An exception to the above rule: If the database is in no-sync mode
  49529. ** and a page is moved during an incremental vacuum then the page may
  49530. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  49531. ** during a Movepage() call, then the page may not be in the cache
  49532. ** either. So the condition described in the above paragraph is not
  49533. ** assert()able.
  49534. **
  49535. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  49536. ** pager cache if it exists and the main file. The page is then marked
  49537. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  49538. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  49539. ** if the pager is in OPEN state.
  49540. **
  49541. ** Ticket #1171: The statement journal might contain page content that is
  49542. ** different from the page content at the start of the transaction.
  49543. ** This occurs when a page is changed prior to the start of a statement
  49544. ** then changed again within the statement. When rolling back such a
  49545. ** statement we must not write to the original database unless we know
  49546. ** for certain that original page contents are synced into the main rollback
  49547. ** journal. Otherwise, a power loss might leave modified data in the
  49548. ** database file without an entry in the rollback journal that can
  49549. ** restore the database to its original form. Two conditions must be
  49550. ** met before writing to the database files. (1) the database must be
  49551. ** locked. (2) we know that the original page content is fully synced
  49552. ** in the main journal either because the page is not in cache or else
  49553. ** the page is marked as needSync==0.
  49554. **
  49555. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  49556. ** is possible to fail a statement on a database that does not yet exist.
  49557. ** Do not attempt to write if database file has never been opened.
  49558. */
  49559. if( pagerUseWal(pPager) ){
  49560. pPg = 0;
  49561. }else{
  49562. pPg = sqlite3PagerLookup(pPager, pgno);
  49563. }
  49564. assert( pPg || !MEMDB );
  49565. assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
  49566. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  49567. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  49568. (isMainJrnl?"main-journal":"sub-journal")
  49569. ));
  49570. if( isMainJrnl ){
  49571. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  49572. }else{
  49573. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  49574. }
  49575. if( isOpen(pPager->fd)
  49576. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  49577. && isSynced
  49578. ){
  49579. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  49580. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  49581. assert( !pagerUseWal(pPager) );
  49582. /* Write the data read from the journal back into the database file.
  49583. ** This is usually safe even for an encrypted database - as the data
  49584. ** was encrypted before it was written to the journal file. The exception
  49585. ** is if the data was just read from an in-memory sub-journal. In that
  49586. ** case it must be encrypted here before it is copied into the database
  49587. ** file. */
  49588. #ifdef SQLITE_HAS_CODEC
  49589. if( !jrnlEnc ){
  49590. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
  49591. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  49592. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  49593. }else
  49594. #endif
  49595. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  49596. if( pgno>pPager->dbFileSize ){
  49597. pPager->dbFileSize = pgno;
  49598. }
  49599. if( pPager->pBackup ){
  49600. #ifdef SQLITE_HAS_CODEC
  49601. if( jrnlEnc ){
  49602. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  49603. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  49604. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
  49605. }else
  49606. #endif
  49607. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  49608. }
  49609. }else if( !isMainJrnl && pPg==0 ){
  49610. /* If this is a rollback of a savepoint and data was not written to
  49611. ** the database and the page is not in-memory, there is a potential
  49612. ** problem. When the page is next fetched by the b-tree layer, it
  49613. ** will be read from the database file, which may or may not be
  49614. ** current.
  49615. **
  49616. ** There are a couple of different ways this can happen. All are quite
  49617. ** obscure. When running in synchronous mode, this can only happen
  49618. ** if the page is on the free-list at the start of the transaction, then
  49619. ** populated, then moved using sqlite3PagerMovepage().
  49620. **
  49621. ** The solution is to add an in-memory page to the cache containing
  49622. ** the data just read from the sub-journal. Mark the page as dirty
  49623. ** and if the pager requires a journal-sync, then mark the page as
  49624. ** requiring a journal-sync before it is written.
  49625. */
  49626. assert( isSavepnt );
  49627. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  49628. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  49629. rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
  49630. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  49631. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  49632. if( rc!=SQLITE_OK ) return rc;
  49633. sqlite3PcacheMakeDirty(pPg);
  49634. }
  49635. if( pPg ){
  49636. /* No page should ever be explicitly rolled back that is in use, except
  49637. ** for page 1 which is held in use in order to keep the lock on the
  49638. ** database active. However such a page may be rolled back as a result
  49639. ** of an internal error resulting in an automatic call to
  49640. ** sqlite3PagerRollback().
  49641. */
  49642. void *pData;
  49643. pData = pPg->pData;
  49644. memcpy(pData, (u8*)aData, pPager->pageSize);
  49645. pPager->xReiniter(pPg);
  49646. /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
  49647. ** that call was dangerous and had no detectable benefit since the cache
  49648. ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
  49649. ** has been removed. */
  49650. pager_set_pagehash(pPg);
  49651. /* If this was page 1, then restore the value of Pager.dbFileVers.
  49652. ** Do this before any decoding. */
  49653. if( pgno==1 ){
  49654. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  49655. }
  49656. /* Decode the page just read from disk */
  49657. #if SQLITE_HAS_CODEC
  49658. if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
  49659. #endif
  49660. sqlite3PcacheRelease(pPg);
  49661. }
  49662. return rc;
  49663. }
  49664. /*
  49665. ** Parameter zMaster is the name of a master journal file. A single journal
  49666. ** file that referred to the master journal file has just been rolled back.
  49667. ** This routine checks if it is possible to delete the master journal file,
  49668. ** and does so if it is.
  49669. **
  49670. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  49671. ** available for use within this function.
  49672. **
  49673. ** When a master journal file is created, it is populated with the names
  49674. ** of all of its child journals, one after another, formatted as utf-8
  49675. ** encoded text. The end of each child journal file is marked with a
  49676. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  49677. ** file for a transaction involving two databases might be:
  49678. **
  49679. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  49680. **
  49681. ** A master journal file may only be deleted once all of its child
  49682. ** journals have been rolled back.
  49683. **
  49684. ** This function reads the contents of the master-journal file into
  49685. ** memory and loops through each of the child journal names. For
  49686. ** each child journal, it checks if:
  49687. **
  49688. ** * if the child journal exists, and if so
  49689. ** * if the child journal contains a reference to master journal
  49690. ** file zMaster
  49691. **
  49692. ** If a child journal can be found that matches both of the criteria
  49693. ** above, this function returns without doing anything. Otherwise, if
  49694. ** no such child journal can be found, file zMaster is deleted from
  49695. ** the file-system using sqlite3OsDelete().
  49696. **
  49697. ** If an IO error within this function, an error code is returned. This
  49698. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  49699. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  49700. ** occur, SQLITE_OK is returned.
  49701. **
  49702. ** TODO: This function allocates a single block of memory to load
  49703. ** the entire contents of the master journal file. This could be
  49704. ** a couple of kilobytes or so - potentially larger than the page
  49705. ** size.
  49706. */
  49707. static int pager_delmaster(Pager *pPager, const char *zMaster){
  49708. sqlite3_vfs *pVfs = pPager->pVfs;
  49709. int rc; /* Return code */
  49710. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  49711. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  49712. char *zMasterJournal = 0; /* Contents of master journal file */
  49713. i64 nMasterJournal; /* Size of master journal file */
  49714. char *zJournal; /* Pointer to one journal within MJ file */
  49715. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  49716. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  49717. /* Allocate space for both the pJournal and pMaster file descriptors.
  49718. ** If successful, open the master journal file for reading.
  49719. */
  49720. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  49721. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  49722. if( !pMaster ){
  49723. rc = SQLITE_NOMEM_BKPT;
  49724. }else{
  49725. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  49726. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  49727. }
  49728. if( rc!=SQLITE_OK ) goto delmaster_out;
  49729. /* Load the entire master journal file into space obtained from
  49730. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  49731. ** sufficient space (in zMasterPtr) to hold the names of master
  49732. ** journal files extracted from regular rollback-journals.
  49733. */
  49734. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  49735. if( rc!=SQLITE_OK ) goto delmaster_out;
  49736. nMasterPtr = pVfs->mxPathname+1;
  49737. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  49738. if( !zMasterJournal ){
  49739. rc = SQLITE_NOMEM_BKPT;
  49740. goto delmaster_out;
  49741. }
  49742. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  49743. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  49744. if( rc!=SQLITE_OK ) goto delmaster_out;
  49745. zMasterJournal[nMasterJournal] = 0;
  49746. zJournal = zMasterJournal;
  49747. while( (zJournal-zMasterJournal)<nMasterJournal ){
  49748. int exists;
  49749. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  49750. if( rc!=SQLITE_OK ){
  49751. goto delmaster_out;
  49752. }
  49753. if( exists ){
  49754. /* One of the journals pointed to by the master journal exists.
  49755. ** Open it and check if it points at the master journal. If
  49756. ** so, return without deleting the master journal file.
  49757. */
  49758. int c;
  49759. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  49760. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  49761. if( rc!=SQLITE_OK ){
  49762. goto delmaster_out;
  49763. }
  49764. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  49765. sqlite3OsClose(pJournal);
  49766. if( rc!=SQLITE_OK ){
  49767. goto delmaster_out;
  49768. }
  49769. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  49770. if( c ){
  49771. /* We have a match. Do not delete the master journal file. */
  49772. goto delmaster_out;
  49773. }
  49774. }
  49775. zJournal += (sqlite3Strlen30(zJournal)+1);
  49776. }
  49777. sqlite3OsClose(pMaster);
  49778. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  49779. delmaster_out:
  49780. sqlite3_free(zMasterJournal);
  49781. if( pMaster ){
  49782. sqlite3OsClose(pMaster);
  49783. assert( !isOpen(pJournal) );
  49784. sqlite3_free(pMaster);
  49785. }
  49786. return rc;
  49787. }
  49788. /*
  49789. ** This function is used to change the actual size of the database
  49790. ** file in the file-system. This only happens when committing a transaction,
  49791. ** or rolling back a transaction (including rolling back a hot-journal).
  49792. **
  49793. ** If the main database file is not open, or the pager is not in either
  49794. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  49795. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  49796. ** If the file on disk is currently larger than nPage pages, then use the VFS
  49797. ** xTruncate() method to truncate it.
  49798. **
  49799. ** Or, it might be the case that the file on disk is smaller than
  49800. ** nPage pages. Some operating system implementations can get confused if
  49801. ** you try to truncate a file to some size that is larger than it
  49802. ** currently is, so detect this case and write a single zero byte to
  49803. ** the end of the new file instead.
  49804. **
  49805. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  49806. ** the database file, return the error code to the caller.
  49807. */
  49808. static int pager_truncate(Pager *pPager, Pgno nPage){
  49809. int rc = SQLITE_OK;
  49810. assert( pPager->eState!=PAGER_ERROR );
  49811. assert( pPager->eState!=PAGER_READER );
  49812. if( isOpen(pPager->fd)
  49813. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  49814. ){
  49815. i64 currentSize, newSize;
  49816. int szPage = pPager->pageSize;
  49817. assert( pPager->eLock==EXCLUSIVE_LOCK );
  49818. /* TODO: Is it safe to use Pager.dbFileSize here? */
  49819. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  49820. newSize = szPage*(i64)nPage;
  49821. if( rc==SQLITE_OK && currentSize!=newSize ){
  49822. if( currentSize>newSize ){
  49823. rc = sqlite3OsTruncate(pPager->fd, newSize);
  49824. }else if( (currentSize+szPage)<=newSize ){
  49825. char *pTmp = pPager->pTmpSpace;
  49826. memset(pTmp, 0, szPage);
  49827. testcase( (newSize-szPage) == currentSize );
  49828. testcase( (newSize-szPage) > currentSize );
  49829. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  49830. }
  49831. if( rc==SQLITE_OK ){
  49832. pPager->dbFileSize = nPage;
  49833. }
  49834. }
  49835. }
  49836. return rc;
  49837. }
  49838. /*
  49839. ** Return a sanitized version of the sector-size of OS file pFile. The
  49840. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  49841. */
  49842. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  49843. int iRet = sqlite3OsSectorSize(pFile);
  49844. if( iRet<32 ){
  49845. iRet = 512;
  49846. }else if( iRet>MAX_SECTOR_SIZE ){
  49847. assert( MAX_SECTOR_SIZE>=512 );
  49848. iRet = MAX_SECTOR_SIZE;
  49849. }
  49850. return iRet;
  49851. }
  49852. /*
  49853. ** Set the value of the Pager.sectorSize variable for the given
  49854. ** pager based on the value returned by the xSectorSize method
  49855. ** of the open database file. The sector size will be used
  49856. ** to determine the size and alignment of journal header and
  49857. ** master journal pointers within created journal files.
  49858. **
  49859. ** For temporary files the effective sector size is always 512 bytes.
  49860. **
  49861. ** Otherwise, for non-temporary files, the effective sector size is
  49862. ** the value returned by the xSectorSize() method rounded up to 32 if
  49863. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  49864. ** is greater than MAX_SECTOR_SIZE.
  49865. **
  49866. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  49867. ** the effective sector size to its minimum value (512). The purpose of
  49868. ** pPager->sectorSize is to define the "blast radius" of bytes that
  49869. ** might change if a crash occurs while writing to a single byte in
  49870. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  49871. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  49872. ** size. For backwards compatibility of the rollback journal file format,
  49873. ** we cannot reduce the effective sector size below 512.
  49874. */
  49875. static void setSectorSize(Pager *pPager){
  49876. assert( isOpen(pPager->fd) || pPager->tempFile );
  49877. if( pPager->tempFile
  49878. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  49879. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  49880. ){
  49881. /* Sector size doesn't matter for temporary files. Also, the file
  49882. ** may not have been opened yet, in which case the OsSectorSize()
  49883. ** call will segfault. */
  49884. pPager->sectorSize = 512;
  49885. }else{
  49886. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  49887. }
  49888. }
  49889. /*
  49890. ** Playback the journal and thus restore the database file to
  49891. ** the state it was in before we started making changes.
  49892. **
  49893. ** The journal file format is as follows:
  49894. **
  49895. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  49896. ** (2) 4 byte big-endian integer which is the number of valid page records
  49897. ** in the journal. If this value is 0xffffffff, then compute the
  49898. ** number of page records from the journal size.
  49899. ** (3) 4 byte big-endian integer which is the initial value for the
  49900. ** sanity checksum.
  49901. ** (4) 4 byte integer which is the number of pages to truncate the
  49902. ** database to during a rollback.
  49903. ** (5) 4 byte big-endian integer which is the sector size. The header
  49904. ** is this many bytes in size.
  49905. ** (6) 4 byte big-endian integer which is the page size.
  49906. ** (7) zero padding out to the next sector size.
  49907. ** (8) Zero or more pages instances, each as follows:
  49908. ** + 4 byte page number.
  49909. ** + pPager->pageSize bytes of data.
  49910. ** + 4 byte checksum
  49911. **
  49912. ** When we speak of the journal header, we mean the first 7 items above.
  49913. ** Each entry in the journal is an instance of the 8th item.
  49914. **
  49915. ** Call the value from the second bullet "nRec". nRec is the number of
  49916. ** valid page entries in the journal. In most cases, you can compute the
  49917. ** value of nRec from the size of the journal file. But if a power
  49918. ** failure occurred while the journal was being written, it could be the
  49919. ** case that the size of the journal file had already been increased but
  49920. ** the extra entries had not yet made it safely to disk. In such a case,
  49921. ** the value of nRec computed from the file size would be too large. For
  49922. ** that reason, we always use the nRec value in the header.
  49923. **
  49924. ** If the nRec value is 0xffffffff it means that nRec should be computed
  49925. ** from the file size. This value is used when the user selects the
  49926. ** no-sync option for the journal. A power failure could lead to corruption
  49927. ** in this case. But for things like temporary table (which will be
  49928. ** deleted when the power is restored) we don't care.
  49929. **
  49930. ** If the file opened as the journal file is not a well-formed
  49931. ** journal file then all pages up to the first corrupted page are rolled
  49932. ** back (or no pages if the journal header is corrupted). The journal file
  49933. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  49934. ** been encountered.
  49935. **
  49936. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  49937. ** and an error code is returned.
  49938. **
  49939. ** The isHot parameter indicates that we are trying to rollback a journal
  49940. ** that might be a hot journal. Or, it could be that the journal is
  49941. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  49942. ** If the journal really is hot, reset the pager cache prior rolling
  49943. ** back any content. If the journal is merely persistent, no reset is
  49944. ** needed.
  49945. */
  49946. static int pager_playback(Pager *pPager, int isHot){
  49947. sqlite3_vfs *pVfs = pPager->pVfs;
  49948. i64 szJ; /* Size of the journal file in bytes */
  49949. u32 nRec; /* Number of Records in the journal */
  49950. u32 u; /* Unsigned loop counter */
  49951. Pgno mxPg = 0; /* Size of the original file in pages */
  49952. int rc; /* Result code of a subroutine */
  49953. int res = 1; /* Value returned by sqlite3OsAccess() */
  49954. char *zMaster = 0; /* Name of master journal file if any */
  49955. int needPagerReset; /* True to reset page prior to first page rollback */
  49956. int nPlayback = 0; /* Total number of pages restored from journal */
  49957. u32 savedPageSize = pPager->pageSize;
  49958. /* Figure out how many records are in the journal. Abort early if
  49959. ** the journal is empty.
  49960. */
  49961. assert( isOpen(pPager->jfd) );
  49962. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  49963. if( rc!=SQLITE_OK ){
  49964. goto end_playback;
  49965. }
  49966. /* Read the master journal name from the journal, if it is present.
  49967. ** If a master journal file name is specified, but the file is not
  49968. ** present on disk, then the journal is not hot and does not need to be
  49969. ** played back.
  49970. **
  49971. ** TODO: Technically the following is an error because it assumes that
  49972. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  49973. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  49974. ** mxPathname is 512, which is the same as the minimum allowable value
  49975. ** for pageSize.
  49976. */
  49977. zMaster = pPager->pTmpSpace;
  49978. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  49979. if( rc==SQLITE_OK && zMaster[0] ){
  49980. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  49981. }
  49982. zMaster = 0;
  49983. if( rc!=SQLITE_OK || !res ){
  49984. goto end_playback;
  49985. }
  49986. pPager->journalOff = 0;
  49987. needPagerReset = isHot;
  49988. /* This loop terminates either when a readJournalHdr() or
  49989. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  49990. ** occurs.
  49991. */
  49992. while( 1 ){
  49993. /* Read the next journal header from the journal file. If there are
  49994. ** not enough bytes left in the journal file for a complete header, or
  49995. ** it is corrupted, then a process must have failed while writing it.
  49996. ** This indicates nothing more needs to be rolled back.
  49997. */
  49998. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  49999. if( rc!=SQLITE_OK ){
  50000. if( rc==SQLITE_DONE ){
  50001. rc = SQLITE_OK;
  50002. }
  50003. goto end_playback;
  50004. }
  50005. /* If nRec is 0xffffffff, then this journal was created by a process
  50006. ** working in no-sync mode. This means that the rest of the journal
  50007. ** file consists of pages, there are no more journal headers. Compute
  50008. ** the value of nRec based on this assumption.
  50009. */
  50010. if( nRec==0xffffffff ){
  50011. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  50012. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  50013. }
  50014. /* If nRec is 0 and this rollback is of a transaction created by this
  50015. ** process and if this is the final header in the journal, then it means
  50016. ** that this part of the journal was being filled but has not yet been
  50017. ** synced to disk. Compute the number of pages based on the remaining
  50018. ** size of the file.
  50019. **
  50020. ** The third term of the test was added to fix ticket #2565.
  50021. ** When rolling back a hot journal, nRec==0 always means that the next
  50022. ** chunk of the journal contains zero pages to be rolled back. But
  50023. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  50024. ** the journal, it means that the journal might contain additional
  50025. ** pages that need to be rolled back and that the number of pages
  50026. ** should be computed based on the journal file size.
  50027. */
  50028. if( nRec==0 && !isHot &&
  50029. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  50030. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  50031. }
  50032. /* If this is the first header read from the journal, truncate the
  50033. ** database file back to its original size.
  50034. */
  50035. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  50036. rc = pager_truncate(pPager, mxPg);
  50037. if( rc!=SQLITE_OK ){
  50038. goto end_playback;
  50039. }
  50040. pPager->dbSize = mxPg;
  50041. }
  50042. /* Copy original pages out of the journal and back into the
  50043. ** database file and/or page cache.
  50044. */
  50045. for(u=0; u<nRec; u++){
  50046. if( needPagerReset ){
  50047. pager_reset(pPager);
  50048. needPagerReset = 0;
  50049. }
  50050. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  50051. if( rc==SQLITE_OK ){
  50052. nPlayback++;
  50053. }else{
  50054. if( rc==SQLITE_DONE ){
  50055. pPager->journalOff = szJ;
  50056. break;
  50057. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  50058. /* If the journal has been truncated, simply stop reading and
  50059. ** processing the journal. This might happen if the journal was
  50060. ** not completely written and synced prior to a crash. In that
  50061. ** case, the database should have never been written in the
  50062. ** first place so it is OK to simply abandon the rollback. */
  50063. rc = SQLITE_OK;
  50064. goto end_playback;
  50065. }else{
  50066. /* If we are unable to rollback, quit and return the error
  50067. ** code. This will cause the pager to enter the error state
  50068. ** so that no further harm will be done. Perhaps the next
  50069. ** process to come along will be able to rollback the database.
  50070. */
  50071. goto end_playback;
  50072. }
  50073. }
  50074. }
  50075. }
  50076. /*NOTREACHED*/
  50077. assert( 0 );
  50078. end_playback:
  50079. if( rc==SQLITE_OK ){
  50080. rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
  50081. }
  50082. /* Following a rollback, the database file should be back in its original
  50083. ** state prior to the start of the transaction, so invoke the
  50084. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  50085. ** assertion that the transaction counter was modified.
  50086. */
  50087. #ifdef SQLITE_DEBUG
  50088. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  50089. #endif
  50090. /* If this playback is happening automatically as a result of an IO or
  50091. ** malloc error that occurred after the change-counter was updated but
  50092. ** before the transaction was committed, then the change-counter
  50093. ** modification may just have been reverted. If this happens in exclusive
  50094. ** mode, then subsequent transactions performed by the connection will not
  50095. ** update the change-counter at all. This may lead to cache inconsistency
  50096. ** problems for other processes at some point in the future. So, just
  50097. ** in case this has happened, clear the changeCountDone flag now.
  50098. */
  50099. pPager->changeCountDone = pPager->tempFile;
  50100. if( rc==SQLITE_OK ){
  50101. zMaster = pPager->pTmpSpace;
  50102. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  50103. testcase( rc!=SQLITE_OK );
  50104. }
  50105. if( rc==SQLITE_OK
  50106. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  50107. ){
  50108. rc = sqlite3PagerSync(pPager, 0);
  50109. }
  50110. if( rc==SQLITE_OK ){
  50111. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  50112. testcase( rc!=SQLITE_OK );
  50113. }
  50114. if( rc==SQLITE_OK && zMaster[0] && res ){
  50115. /* If there was a master journal and this routine will return success,
  50116. ** see if it is possible to delete the master journal.
  50117. */
  50118. rc = pager_delmaster(pPager, zMaster);
  50119. testcase( rc!=SQLITE_OK );
  50120. }
  50121. if( isHot && nPlayback ){
  50122. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  50123. nPlayback, pPager->zJournal);
  50124. }
  50125. /* The Pager.sectorSize variable may have been updated while rolling
  50126. ** back a journal created by a process with a different sector size
  50127. ** value. Reset it to the correct value for this process.
  50128. */
  50129. setSectorSize(pPager);
  50130. return rc;
  50131. }
  50132. /*
  50133. ** Read the content for page pPg out of the database file (or out of
  50134. ** the WAL if that is where the most recent copy if found) into
  50135. ** pPg->pData. A shared lock or greater must be held on the database
  50136. ** file before this function is called.
  50137. **
  50138. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  50139. ** the value read from the database file.
  50140. **
  50141. ** If an IO error occurs, then the IO error is returned to the caller.
  50142. ** Otherwise, SQLITE_OK is returned.
  50143. */
  50144. static int readDbPage(PgHdr *pPg){
  50145. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  50146. int rc = SQLITE_OK; /* Return code */
  50147. #ifndef SQLITE_OMIT_WAL
  50148. u32 iFrame = 0; /* Frame of WAL containing pgno */
  50149. assert( pPager->eState>=PAGER_READER && !MEMDB );
  50150. assert( isOpen(pPager->fd) );
  50151. if( pagerUseWal(pPager) ){
  50152. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  50153. if( rc ) return rc;
  50154. }
  50155. if( iFrame ){
  50156. rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
  50157. }else
  50158. #endif
  50159. {
  50160. i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
  50161. rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
  50162. if( rc==SQLITE_IOERR_SHORT_READ ){
  50163. rc = SQLITE_OK;
  50164. }
  50165. }
  50166. if( pPg->pgno==1 ){
  50167. if( rc ){
  50168. /* If the read is unsuccessful, set the dbFileVers[] to something
  50169. ** that will never be a valid file version. dbFileVers[] is a copy
  50170. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  50171. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  50172. ** should be page numbers which are never 0xffffffff. So filling
  50173. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  50174. **
  50175. ** For an encrypted database, the situation is more complex: bytes
  50176. ** 24..39 of the database are white noise. But the probability of
  50177. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  50178. ** we should still be ok.
  50179. */
  50180. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  50181. }else{
  50182. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  50183. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  50184. }
  50185. }
  50186. CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
  50187. PAGER_INCR(sqlite3_pager_readdb_count);
  50188. PAGER_INCR(pPager->nRead);
  50189. IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
  50190. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  50191. PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
  50192. return rc;
  50193. }
  50194. /*
  50195. ** Update the value of the change-counter at offsets 24 and 92 in
  50196. ** the header and the sqlite version number at offset 96.
  50197. **
  50198. ** This is an unconditional update. See also the pager_incr_changecounter()
  50199. ** routine which only updates the change-counter if the update is actually
  50200. ** needed, as determined by the pPager->changeCountDone state variable.
  50201. */
  50202. static void pager_write_changecounter(PgHdr *pPg){
  50203. u32 change_counter;
  50204. /* Increment the value just read and write it back to byte 24. */
  50205. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  50206. put32bits(((char*)pPg->pData)+24, change_counter);
  50207. /* Also store the SQLite version number in bytes 96..99 and in
  50208. ** bytes 92..95 store the change counter for which the version number
  50209. ** is valid. */
  50210. put32bits(((char*)pPg->pData)+92, change_counter);
  50211. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  50212. }
  50213. #ifndef SQLITE_OMIT_WAL
  50214. /*
  50215. ** This function is invoked once for each page that has already been
  50216. ** written into the log file when a WAL transaction is rolled back.
  50217. ** Parameter iPg is the page number of said page. The pCtx argument
  50218. ** is actually a pointer to the Pager structure.
  50219. **
  50220. ** If page iPg is present in the cache, and has no outstanding references,
  50221. ** it is discarded. Otherwise, if there are one or more outstanding
  50222. ** references, the page content is reloaded from the database. If the
  50223. ** attempt to reload content from the database is required and fails,
  50224. ** return an SQLite error code. Otherwise, SQLITE_OK.
  50225. */
  50226. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  50227. int rc = SQLITE_OK;
  50228. Pager *pPager = (Pager *)pCtx;
  50229. PgHdr *pPg;
  50230. assert( pagerUseWal(pPager) );
  50231. pPg = sqlite3PagerLookup(pPager, iPg);
  50232. if( pPg ){
  50233. if( sqlite3PcachePageRefcount(pPg)==1 ){
  50234. sqlite3PcacheDrop(pPg);
  50235. }else{
  50236. rc = readDbPage(pPg);
  50237. if( rc==SQLITE_OK ){
  50238. pPager->xReiniter(pPg);
  50239. }
  50240. sqlite3PagerUnrefNotNull(pPg);
  50241. }
  50242. }
  50243. /* Normally, if a transaction is rolled back, any backup processes are
  50244. ** updated as data is copied out of the rollback journal and into the
  50245. ** database. This is not generally possible with a WAL database, as
  50246. ** rollback involves simply truncating the log file. Therefore, if one
  50247. ** or more frames have already been written to the log (and therefore
  50248. ** also copied into the backup databases) as part of this transaction,
  50249. ** the backups must be restarted.
  50250. */
  50251. sqlite3BackupRestart(pPager->pBackup);
  50252. return rc;
  50253. }
  50254. /*
  50255. ** This function is called to rollback a transaction on a WAL database.
  50256. */
  50257. static int pagerRollbackWal(Pager *pPager){
  50258. int rc; /* Return Code */
  50259. PgHdr *pList; /* List of dirty pages to revert */
  50260. /* For all pages in the cache that are currently dirty or have already
  50261. ** been written (but not committed) to the log file, do one of the
  50262. ** following:
  50263. **
  50264. ** + Discard the cached page (if refcount==0), or
  50265. ** + Reload page content from the database (if refcount>0).
  50266. */
  50267. pPager->dbSize = pPager->dbOrigSize;
  50268. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  50269. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  50270. while( pList && rc==SQLITE_OK ){
  50271. PgHdr *pNext = pList->pDirty;
  50272. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  50273. pList = pNext;
  50274. }
  50275. return rc;
  50276. }
  50277. /*
  50278. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  50279. ** the contents of the list of pages headed by pList (connected by pDirty),
  50280. ** this function notifies any active backup processes that the pages have
  50281. ** changed.
  50282. **
  50283. ** The list of pages passed into this routine is always sorted by page number.
  50284. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  50285. */
  50286. static int pagerWalFrames(
  50287. Pager *pPager, /* Pager object */
  50288. PgHdr *pList, /* List of frames to log */
  50289. Pgno nTruncate, /* Database size after this commit */
  50290. int isCommit /* True if this is a commit */
  50291. ){
  50292. int rc; /* Return code */
  50293. int nList; /* Number of pages in pList */
  50294. PgHdr *p; /* For looping over pages */
  50295. assert( pPager->pWal );
  50296. assert( pList );
  50297. #ifdef SQLITE_DEBUG
  50298. /* Verify that the page list is in accending order */
  50299. for(p=pList; p && p->pDirty; p=p->pDirty){
  50300. assert( p->pgno < p->pDirty->pgno );
  50301. }
  50302. #endif
  50303. assert( pList->pDirty==0 || isCommit );
  50304. if( isCommit ){
  50305. /* If a WAL transaction is being committed, there is no point in writing
  50306. ** any pages with page numbers greater than nTruncate into the WAL file.
  50307. ** They will never be read by any client. So remove them from the pDirty
  50308. ** list here. */
  50309. PgHdr **ppNext = &pList;
  50310. nList = 0;
  50311. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  50312. if( p->pgno<=nTruncate ){
  50313. ppNext = &p->pDirty;
  50314. nList++;
  50315. }
  50316. }
  50317. assert( pList );
  50318. }else{
  50319. nList = 1;
  50320. }
  50321. pPager->aStat[PAGER_STAT_WRITE] += nList;
  50322. if( pList->pgno==1 ) pager_write_changecounter(pList);
  50323. rc = sqlite3WalFrames(pPager->pWal,
  50324. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  50325. );
  50326. if( rc==SQLITE_OK && pPager->pBackup ){
  50327. for(p=pList; p; p=p->pDirty){
  50328. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  50329. }
  50330. }
  50331. #ifdef SQLITE_CHECK_PAGES
  50332. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  50333. for(p=pList; p; p=p->pDirty){
  50334. pager_set_pagehash(p);
  50335. }
  50336. #endif
  50337. return rc;
  50338. }
  50339. /*
  50340. ** Begin a read transaction on the WAL.
  50341. **
  50342. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  50343. ** makes a snapshot of the database at the current point in time and preserves
  50344. ** that snapshot for use by the reader in spite of concurrently changes by
  50345. ** other writers or checkpointers.
  50346. */
  50347. static int pagerBeginReadTransaction(Pager *pPager){
  50348. int rc; /* Return code */
  50349. int changed = 0; /* True if cache must be reset */
  50350. assert( pagerUseWal(pPager) );
  50351. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  50352. /* sqlite3WalEndReadTransaction() was not called for the previous
  50353. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  50354. ** are in locking_mode=NORMAL and EndRead() was previously called,
  50355. ** the duplicate call is harmless.
  50356. */
  50357. sqlite3WalEndReadTransaction(pPager->pWal);
  50358. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  50359. if( rc!=SQLITE_OK || changed ){
  50360. pager_reset(pPager);
  50361. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  50362. }
  50363. return rc;
  50364. }
  50365. #endif
  50366. /*
  50367. ** This function is called as part of the transition from PAGER_OPEN
  50368. ** to PAGER_READER state to determine the size of the database file
  50369. ** in pages (assuming the page size currently stored in Pager.pageSize).
  50370. **
  50371. ** If no error occurs, SQLITE_OK is returned and the size of the database
  50372. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  50373. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  50374. */
  50375. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  50376. Pgno nPage; /* Value to return via *pnPage */
  50377. /* Query the WAL sub-system for the database size. The WalDbsize()
  50378. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  50379. ** if the database size is not available. The database size is not
  50380. ** available from the WAL sub-system if the log file is empty or
  50381. ** contains no valid committed transactions.
  50382. */
  50383. assert( pPager->eState==PAGER_OPEN );
  50384. assert( pPager->eLock>=SHARED_LOCK );
  50385. assert( isOpen(pPager->fd) );
  50386. assert( pPager->tempFile==0 );
  50387. nPage = sqlite3WalDbsize(pPager->pWal);
  50388. /* If the number of pages in the database is not available from the
  50389. ** WAL sub-system, determine the page count based on the size of
  50390. ** the database file. If the size of the database file is not an
  50391. ** integer multiple of the page-size, round up the result.
  50392. */
  50393. if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
  50394. i64 n = 0; /* Size of db file in bytes */
  50395. int rc = sqlite3OsFileSize(pPager->fd, &n);
  50396. if( rc!=SQLITE_OK ){
  50397. return rc;
  50398. }
  50399. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  50400. }
  50401. /* If the current number of pages in the file is greater than the
  50402. ** configured maximum pager number, increase the allowed limit so
  50403. ** that the file can be read.
  50404. */
  50405. if( nPage>pPager->mxPgno ){
  50406. pPager->mxPgno = (Pgno)nPage;
  50407. }
  50408. *pnPage = nPage;
  50409. return SQLITE_OK;
  50410. }
  50411. #ifndef SQLITE_OMIT_WAL
  50412. /*
  50413. ** Check if the *-wal file that corresponds to the database opened by pPager
  50414. ** exists if the database is not empy, or verify that the *-wal file does
  50415. ** not exist (by deleting it) if the database file is empty.
  50416. **
  50417. ** If the database is not empty and the *-wal file exists, open the pager
  50418. ** in WAL mode. If the database is empty or if no *-wal file exists and
  50419. ** if no error occurs, make sure Pager.journalMode is not set to
  50420. ** PAGER_JOURNALMODE_WAL.
  50421. **
  50422. ** Return SQLITE_OK or an error code.
  50423. **
  50424. ** The caller must hold a SHARED lock on the database file to call this
  50425. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  50426. ** a WAL on a none-empty database, this ensures there is no race condition
  50427. ** between the xAccess() below and an xDelete() being executed by some
  50428. ** other connection.
  50429. */
  50430. static int pagerOpenWalIfPresent(Pager *pPager){
  50431. int rc = SQLITE_OK;
  50432. assert( pPager->eState==PAGER_OPEN );
  50433. assert( pPager->eLock>=SHARED_LOCK );
  50434. if( !pPager->tempFile ){
  50435. int isWal; /* True if WAL file exists */
  50436. rc = sqlite3OsAccess(
  50437. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  50438. );
  50439. if( rc==SQLITE_OK ){
  50440. if( isWal ){
  50441. Pgno nPage; /* Size of the database file */
  50442. rc = pagerPagecount(pPager, &nPage);
  50443. if( rc ) return rc;
  50444. if( nPage==0 ){
  50445. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  50446. }else{
  50447. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  50448. rc = sqlite3PagerOpenWal(pPager, 0);
  50449. }
  50450. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  50451. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  50452. }
  50453. }
  50454. }
  50455. return rc;
  50456. }
  50457. #endif
  50458. /*
  50459. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  50460. ** the entire master journal file. The case pSavepoint==NULL occurs when
  50461. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  50462. ** savepoint.
  50463. **
  50464. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  50465. ** being rolled back), then the rollback consists of up to three stages,
  50466. ** performed in the order specified:
  50467. **
  50468. ** * Pages are played back from the main journal starting at byte
  50469. ** offset PagerSavepoint.iOffset and continuing to
  50470. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  50471. ** file if PagerSavepoint.iHdrOffset is zero.
  50472. **
  50473. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  50474. ** back starting from the journal header immediately following
  50475. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  50476. **
  50477. ** * Pages are then played back from the sub-journal file, starting
  50478. ** with the PagerSavepoint.iSubRec and continuing to the end of
  50479. ** the journal file.
  50480. **
  50481. ** Throughout the rollback process, each time a page is rolled back, the
  50482. ** corresponding bit is set in a bitvec structure (variable pDone in the
  50483. ** implementation below). This is used to ensure that a page is only
  50484. ** rolled back the first time it is encountered in either journal.
  50485. **
  50486. ** If pSavepoint is NULL, then pages are only played back from the main
  50487. ** journal file. There is no need for a bitvec in this case.
  50488. **
  50489. ** In either case, before playback commences the Pager.dbSize variable
  50490. ** is reset to the value that it held at the start of the savepoint
  50491. ** (or transaction). No page with a page-number greater than this value
  50492. ** is played back. If one is encountered it is simply skipped.
  50493. */
  50494. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  50495. i64 szJ; /* Effective size of the main journal */
  50496. i64 iHdrOff; /* End of first segment of main-journal records */
  50497. int rc = SQLITE_OK; /* Return code */
  50498. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  50499. assert( pPager->eState!=PAGER_ERROR );
  50500. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  50501. /* Allocate a bitvec to use to store the set of pages rolled back */
  50502. if( pSavepoint ){
  50503. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  50504. if( !pDone ){
  50505. return SQLITE_NOMEM_BKPT;
  50506. }
  50507. }
  50508. /* Set the database size back to the value it was before the savepoint
  50509. ** being reverted was opened.
  50510. */
  50511. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  50512. pPager->changeCountDone = pPager->tempFile;
  50513. if( !pSavepoint && pagerUseWal(pPager) ){
  50514. return pagerRollbackWal(pPager);
  50515. }
  50516. /* Use pPager->journalOff as the effective size of the main rollback
  50517. ** journal. The actual file might be larger than this in
  50518. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  50519. ** past pPager->journalOff is off-limits to us.
  50520. */
  50521. szJ = pPager->journalOff;
  50522. assert( pagerUseWal(pPager)==0 || szJ==0 );
  50523. /* Begin by rolling back records from the main journal starting at
  50524. ** PagerSavepoint.iOffset and continuing to the next journal header.
  50525. ** There might be records in the main journal that have a page number
  50526. ** greater than the current database size (pPager->dbSize) but those
  50527. ** will be skipped automatically. Pages are added to pDone as they
  50528. ** are played back.
  50529. */
  50530. if( pSavepoint && !pagerUseWal(pPager) ){
  50531. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  50532. pPager->journalOff = pSavepoint->iOffset;
  50533. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  50534. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  50535. }
  50536. assert( rc!=SQLITE_DONE );
  50537. }else{
  50538. pPager->journalOff = 0;
  50539. }
  50540. /* Continue rolling back records out of the main journal starting at
  50541. ** the first journal header seen and continuing until the effective end
  50542. ** of the main journal file. Continue to skip out-of-range pages and
  50543. ** continue adding pages rolled back to pDone.
  50544. */
  50545. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  50546. u32 ii; /* Loop counter */
  50547. u32 nJRec = 0; /* Number of Journal Records */
  50548. u32 dummy;
  50549. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  50550. assert( rc!=SQLITE_DONE );
  50551. /*
  50552. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  50553. ** test is related to ticket #2565. See the discussion in the
  50554. ** pager_playback() function for additional information.
  50555. */
  50556. if( nJRec==0
  50557. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  50558. ){
  50559. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  50560. }
  50561. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  50562. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  50563. }
  50564. assert( rc!=SQLITE_DONE );
  50565. }
  50566. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  50567. /* Finally, rollback pages from the sub-journal. Page that were
  50568. ** previously rolled back out of the main journal (and are hence in pDone)
  50569. ** will be skipped. Out-of-range pages are also skipped.
  50570. */
  50571. if( pSavepoint ){
  50572. u32 ii; /* Loop counter */
  50573. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  50574. if( pagerUseWal(pPager) ){
  50575. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  50576. }
  50577. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  50578. assert( offset==(i64)ii*(4+pPager->pageSize) );
  50579. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  50580. }
  50581. assert( rc!=SQLITE_DONE );
  50582. }
  50583. sqlite3BitvecDestroy(pDone);
  50584. if( rc==SQLITE_OK ){
  50585. pPager->journalOff = szJ;
  50586. }
  50587. return rc;
  50588. }
  50589. /*
  50590. ** Change the maximum number of in-memory pages that are allowed
  50591. ** before attempting to recycle clean and unused pages.
  50592. */
  50593. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  50594. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  50595. }
  50596. /*
  50597. ** Change the maximum number of in-memory pages that are allowed
  50598. ** before attempting to spill pages to journal.
  50599. */
  50600. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
  50601. return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
  50602. }
  50603. /*
  50604. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  50605. */
  50606. static void pagerFixMaplimit(Pager *pPager){
  50607. #if SQLITE_MAX_MMAP_SIZE>0
  50608. sqlite3_file *fd = pPager->fd;
  50609. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  50610. sqlite3_int64 sz;
  50611. sz = pPager->szMmap;
  50612. pPager->bUseFetch = (sz>0);
  50613. setGetterMethod(pPager);
  50614. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  50615. }
  50616. #endif
  50617. }
  50618. /*
  50619. ** Change the maximum size of any memory mapping made of the database file.
  50620. */
  50621. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  50622. pPager->szMmap = szMmap;
  50623. pagerFixMaplimit(pPager);
  50624. }
  50625. /*
  50626. ** Free as much memory as possible from the pager.
  50627. */
  50628. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  50629. sqlite3PcacheShrink(pPager->pPCache);
  50630. }
  50631. /*
  50632. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  50633. **
  50634. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  50635. ** of the database to damage due to OS crashes or power failures by
  50636. ** changing the number of syncs()s when writing the journals.
  50637. ** There are four levels:
  50638. **
  50639. ** OFF sqlite3OsSync() is never called. This is the default
  50640. ** for temporary and transient files.
  50641. **
  50642. ** NORMAL The journal is synced once before writes begin on the
  50643. ** database. This is normally adequate protection, but
  50644. ** it is theoretically possible, though very unlikely,
  50645. ** that an inopertune power failure could leave the journal
  50646. ** in a state which would cause damage to the database
  50647. ** when it is rolled back.
  50648. **
  50649. ** FULL The journal is synced twice before writes begin on the
  50650. ** database (with some additional information - the nRec field
  50651. ** of the journal header - being written in between the two
  50652. ** syncs). If we assume that writing a
  50653. ** single disk sector is atomic, then this mode provides
  50654. ** assurance that the journal will not be corrupted to the
  50655. ** point of causing damage to the database during rollback.
  50656. **
  50657. ** EXTRA This is like FULL except that is also syncs the directory
  50658. ** that contains the rollback journal after the rollback
  50659. ** journal is unlinked.
  50660. **
  50661. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  50662. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  50663. ** prior to the start of checkpoint and that the database file is synced
  50664. ** at the conclusion of the checkpoint if the entire content of the WAL
  50665. ** was written back into the database. But no sync operations occur for
  50666. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  50667. ** file is synced following each commit operation, in addition to the
  50668. ** syncs associated with NORMAL. There is no difference between FULL
  50669. ** and EXTRA for WAL mode.
  50670. **
  50671. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  50672. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  50673. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  50674. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  50675. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  50676. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  50677. ** the xSync primitive is called and is relevant to all platforms.
  50678. **
  50679. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  50680. ** and FULL=3.
  50681. */
  50682. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  50683. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  50684. Pager *pPager, /* The pager to set safety level for */
  50685. unsigned pgFlags /* Various flags */
  50686. ){
  50687. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  50688. if( pPager->tempFile ){
  50689. pPager->noSync = 1;
  50690. pPager->fullSync = 0;
  50691. pPager->extraSync = 0;
  50692. }else{
  50693. pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
  50694. pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
  50695. pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
  50696. }
  50697. if( pPager->noSync ){
  50698. pPager->syncFlags = 0;
  50699. }else if( pgFlags & PAGER_FULLFSYNC ){
  50700. pPager->syncFlags = SQLITE_SYNC_FULL;
  50701. }else{
  50702. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  50703. }
  50704. pPager->walSyncFlags = (pPager->syncFlags<<2);
  50705. if( pPager->fullSync ){
  50706. pPager->walSyncFlags |= pPager->syncFlags;
  50707. }
  50708. if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
  50709. pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
  50710. }
  50711. if( pgFlags & PAGER_CACHESPILL ){
  50712. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  50713. }else{
  50714. pPager->doNotSpill |= SPILLFLAG_OFF;
  50715. }
  50716. }
  50717. #endif
  50718. /*
  50719. ** The following global variable is incremented whenever the library
  50720. ** attempts to open a temporary file. This information is used for
  50721. ** testing and analysis only.
  50722. */
  50723. #ifdef SQLITE_TEST
  50724. SQLITE_API int sqlite3_opentemp_count = 0;
  50725. #endif
  50726. /*
  50727. ** Open a temporary file.
  50728. **
  50729. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  50730. ** or some other error code if we fail. The OS will automatically
  50731. ** delete the temporary file when it is closed.
  50732. **
  50733. ** The flags passed to the VFS layer xOpen() call are those specified
  50734. ** by parameter vfsFlags ORed with the following:
  50735. **
  50736. ** SQLITE_OPEN_READWRITE
  50737. ** SQLITE_OPEN_CREATE
  50738. ** SQLITE_OPEN_EXCLUSIVE
  50739. ** SQLITE_OPEN_DELETEONCLOSE
  50740. */
  50741. static int pagerOpentemp(
  50742. Pager *pPager, /* The pager object */
  50743. sqlite3_file *pFile, /* Write the file descriptor here */
  50744. int vfsFlags /* Flags passed through to the VFS */
  50745. ){
  50746. int rc; /* Return code */
  50747. #ifdef SQLITE_TEST
  50748. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  50749. #endif
  50750. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  50751. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  50752. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  50753. assert( rc!=SQLITE_OK || isOpen(pFile) );
  50754. return rc;
  50755. }
  50756. /*
  50757. ** Set the busy handler function.
  50758. **
  50759. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  50760. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  50761. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  50762. ** lock. It does *not* invoke the busy handler when upgrading from
  50763. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  50764. ** (which occurs during hot-journal rollback). Summary:
  50765. **
  50766. ** Transition | Invokes xBusyHandler
  50767. ** --------------------------------------------------------
  50768. ** NO_LOCK -> SHARED_LOCK | Yes
  50769. ** SHARED_LOCK -> RESERVED_LOCK | No
  50770. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  50771. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  50772. **
  50773. ** If the busy-handler callback returns non-zero, the lock is
  50774. ** retried. If it returns zero, then the SQLITE_BUSY error is
  50775. ** returned to the caller of the pager API function.
  50776. */
  50777. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(
  50778. Pager *pPager, /* Pager object */
  50779. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  50780. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  50781. ){
  50782. void **ap;
  50783. pPager->xBusyHandler = xBusyHandler;
  50784. pPager->pBusyHandlerArg = pBusyHandlerArg;
  50785. ap = (void **)&pPager->xBusyHandler;
  50786. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  50787. assert( ap[1]==pBusyHandlerArg );
  50788. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  50789. }
  50790. /*
  50791. ** Change the page size used by the Pager object. The new page size
  50792. ** is passed in *pPageSize.
  50793. **
  50794. ** If the pager is in the error state when this function is called, it
  50795. ** is a no-op. The value returned is the error state error code (i.e.
  50796. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  50797. **
  50798. ** Otherwise, if all of the following are true:
  50799. **
  50800. ** * the new page size (value of *pPageSize) is valid (a power
  50801. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  50802. **
  50803. ** * there are no outstanding page references, and
  50804. **
  50805. ** * the database is either not an in-memory database or it is
  50806. ** an in-memory database that currently consists of zero pages.
  50807. **
  50808. ** then the pager object page size is set to *pPageSize.
  50809. **
  50810. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  50811. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  50812. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  50813. ** In all other cases, SQLITE_OK is returned.
  50814. **
  50815. ** If the page size is not changed, either because one of the enumerated
  50816. ** conditions above is not true, the pager was in error state when this
  50817. ** function was called, or because the memory allocation attempt failed,
  50818. ** then *pPageSize is set to the old, retained page size before returning.
  50819. */
  50820. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  50821. int rc = SQLITE_OK;
  50822. /* It is not possible to do a full assert_pager_state() here, as this
  50823. ** function may be called from within PagerOpen(), before the state
  50824. ** of the Pager object is internally consistent.
  50825. **
  50826. ** At one point this function returned an error if the pager was in
  50827. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  50828. ** there is at least one outstanding page reference, this function
  50829. ** is a no-op for that case anyhow.
  50830. */
  50831. u32 pageSize = *pPageSize;
  50832. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  50833. if( (pPager->memDb==0 || pPager->dbSize==0)
  50834. && sqlite3PcacheRefCount(pPager->pPCache)==0
  50835. && pageSize && pageSize!=(u32)pPager->pageSize
  50836. ){
  50837. char *pNew = NULL; /* New temp space */
  50838. i64 nByte = 0;
  50839. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  50840. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  50841. }
  50842. if( rc==SQLITE_OK ){
  50843. pNew = (char *)sqlite3PageMalloc(pageSize);
  50844. if( !pNew ) rc = SQLITE_NOMEM_BKPT;
  50845. }
  50846. if( rc==SQLITE_OK ){
  50847. pager_reset(pPager);
  50848. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  50849. }
  50850. if( rc==SQLITE_OK ){
  50851. sqlite3PageFree(pPager->pTmpSpace);
  50852. pPager->pTmpSpace = pNew;
  50853. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  50854. pPager->pageSize = pageSize;
  50855. }else{
  50856. sqlite3PageFree(pNew);
  50857. }
  50858. }
  50859. *pPageSize = pPager->pageSize;
  50860. if( rc==SQLITE_OK ){
  50861. if( nReserve<0 ) nReserve = pPager->nReserve;
  50862. assert( nReserve>=0 && nReserve<1000 );
  50863. pPager->nReserve = (i16)nReserve;
  50864. pagerReportSize(pPager);
  50865. pagerFixMaplimit(pPager);
  50866. }
  50867. return rc;
  50868. }
  50869. /*
  50870. ** Return a pointer to the "temporary page" buffer held internally
  50871. ** by the pager. This is a buffer that is big enough to hold the
  50872. ** entire content of a database page. This buffer is used internally
  50873. ** during rollback and will be overwritten whenever a rollback
  50874. ** occurs. But other modules are free to use it too, as long as
  50875. ** no rollbacks are happening.
  50876. */
  50877. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  50878. return pPager->pTmpSpace;
  50879. }
  50880. /*
  50881. ** Attempt to set the maximum database page count if mxPage is positive.
  50882. ** Make no changes if mxPage is zero or negative. And never reduce the
  50883. ** maximum page count below the current size of the database.
  50884. **
  50885. ** Regardless of mxPage, return the current maximum page count.
  50886. */
  50887. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  50888. if( mxPage>0 ){
  50889. pPager->mxPgno = mxPage;
  50890. }
  50891. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  50892. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  50893. return pPager->mxPgno;
  50894. }
  50895. /*
  50896. ** The following set of routines are used to disable the simulated
  50897. ** I/O error mechanism. These routines are used to avoid simulated
  50898. ** errors in places where we do not care about errors.
  50899. **
  50900. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  50901. ** and generate no code.
  50902. */
  50903. #ifdef SQLITE_TEST
  50904. SQLITE_API extern int sqlite3_io_error_pending;
  50905. SQLITE_API extern int sqlite3_io_error_hit;
  50906. static int saved_cnt;
  50907. void disable_simulated_io_errors(void){
  50908. saved_cnt = sqlite3_io_error_pending;
  50909. sqlite3_io_error_pending = -1;
  50910. }
  50911. void enable_simulated_io_errors(void){
  50912. sqlite3_io_error_pending = saved_cnt;
  50913. }
  50914. #else
  50915. # define disable_simulated_io_errors()
  50916. # define enable_simulated_io_errors()
  50917. #endif
  50918. /*
  50919. ** Read the first N bytes from the beginning of the file into memory
  50920. ** that pDest points to.
  50921. **
  50922. ** If the pager was opened on a transient file (zFilename==""), or
  50923. ** opened on a file less than N bytes in size, the output buffer is
  50924. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  50925. ** function is used to read database headers, and a new transient or
  50926. ** zero sized database has a header than consists entirely of zeroes.
  50927. **
  50928. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  50929. ** the error code is returned to the caller and the contents of the
  50930. ** output buffer undefined.
  50931. */
  50932. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  50933. int rc = SQLITE_OK;
  50934. memset(pDest, 0, N);
  50935. assert( isOpen(pPager->fd) || pPager->tempFile );
  50936. /* This routine is only called by btree immediately after creating
  50937. ** the Pager object. There has not been an opportunity to transition
  50938. ** to WAL mode yet.
  50939. */
  50940. assert( !pagerUseWal(pPager) );
  50941. if( isOpen(pPager->fd) ){
  50942. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  50943. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  50944. if( rc==SQLITE_IOERR_SHORT_READ ){
  50945. rc = SQLITE_OK;
  50946. }
  50947. }
  50948. return rc;
  50949. }
  50950. /*
  50951. ** This function may only be called when a read-transaction is open on
  50952. ** the pager. It returns the total number of pages in the database.
  50953. **
  50954. ** However, if the file is between 1 and <page-size> bytes in size, then
  50955. ** this is considered a 1 page file.
  50956. */
  50957. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  50958. assert( pPager->eState>=PAGER_READER );
  50959. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  50960. *pnPage = (int)pPager->dbSize;
  50961. }
  50962. /*
  50963. ** Try to obtain a lock of type locktype on the database file. If
  50964. ** a similar or greater lock is already held, this function is a no-op
  50965. ** (returning SQLITE_OK immediately).
  50966. **
  50967. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  50968. ** the busy callback if the lock is currently not available. Repeat
  50969. ** until the busy callback returns false or until the attempt to
  50970. ** obtain the lock succeeds.
  50971. **
  50972. ** Return SQLITE_OK on success and an error code if we cannot obtain
  50973. ** the lock. If the lock is obtained successfully, set the Pager.state
  50974. ** variable to locktype before returning.
  50975. */
  50976. static int pager_wait_on_lock(Pager *pPager, int locktype){
  50977. int rc; /* Return code */
  50978. /* Check that this is either a no-op (because the requested lock is
  50979. ** already held), or one of the transitions that the busy-handler
  50980. ** may be invoked during, according to the comment above
  50981. ** sqlite3PagerSetBusyhandler().
  50982. */
  50983. assert( (pPager->eLock>=locktype)
  50984. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  50985. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  50986. );
  50987. do {
  50988. rc = pagerLockDb(pPager, locktype);
  50989. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  50990. return rc;
  50991. }
  50992. /*
  50993. ** Function assertTruncateConstraint(pPager) checks that one of the
  50994. ** following is true for all dirty pages currently in the page-cache:
  50995. **
  50996. ** a) The page number is less than or equal to the size of the
  50997. ** current database image, in pages, OR
  50998. **
  50999. ** b) if the page content were written at this time, it would not
  51000. ** be necessary to write the current content out to the sub-journal
  51001. ** (as determined by function subjRequiresPage()).
  51002. **
  51003. ** If the condition asserted by this function were not true, and the
  51004. ** dirty page were to be discarded from the cache via the pagerStress()
  51005. ** routine, pagerStress() would not write the current page content to
  51006. ** the database file. If a savepoint transaction were rolled back after
  51007. ** this happened, the correct behavior would be to restore the current
  51008. ** content of the page. However, since this content is not present in either
  51009. ** the database file or the portion of the rollback journal and
  51010. ** sub-journal rolled back the content could not be restored and the
  51011. ** database image would become corrupt. It is therefore fortunate that
  51012. ** this circumstance cannot arise.
  51013. */
  51014. #if defined(SQLITE_DEBUG)
  51015. static void assertTruncateConstraintCb(PgHdr *pPg){
  51016. assert( pPg->flags&PGHDR_DIRTY );
  51017. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  51018. }
  51019. static void assertTruncateConstraint(Pager *pPager){
  51020. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  51021. }
  51022. #else
  51023. # define assertTruncateConstraint(pPager)
  51024. #endif
  51025. /*
  51026. ** Truncate the in-memory database file image to nPage pages. This
  51027. ** function does not actually modify the database file on disk. It
  51028. ** just sets the internal state of the pager object so that the
  51029. ** truncation will be done when the current transaction is committed.
  51030. **
  51031. ** This function is only called right before committing a transaction.
  51032. ** Once this function has been called, the transaction must either be
  51033. ** rolled back or committed. It is not safe to call this function and
  51034. ** then continue writing to the database.
  51035. */
  51036. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  51037. assert( pPager->dbSize>=nPage );
  51038. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  51039. pPager->dbSize = nPage;
  51040. /* At one point the code here called assertTruncateConstraint() to
  51041. ** ensure that all pages being truncated away by this operation are,
  51042. ** if one or more savepoints are open, present in the savepoint
  51043. ** journal so that they can be restored if the savepoint is rolled
  51044. ** back. This is no longer necessary as this function is now only
  51045. ** called right before committing a transaction. So although the
  51046. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  51047. ** they cannot be rolled back. So the assertTruncateConstraint() call
  51048. ** is no longer correct. */
  51049. }
  51050. /*
  51051. ** This function is called before attempting a hot-journal rollback. It
  51052. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  51053. ** size of the journal file so that the pager_playback() routine knows
  51054. ** that the entire journal file has been synced.
  51055. **
  51056. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  51057. ** that if a power-failure occurs during the rollback, the process that
  51058. ** attempts rollback following system recovery sees the same journal
  51059. ** content as this process.
  51060. **
  51061. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  51062. ** an SQLite error code.
  51063. */
  51064. static int pagerSyncHotJournal(Pager *pPager){
  51065. int rc = SQLITE_OK;
  51066. if( !pPager->noSync ){
  51067. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  51068. }
  51069. if( rc==SQLITE_OK ){
  51070. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  51071. }
  51072. return rc;
  51073. }
  51074. #if SQLITE_MAX_MMAP_SIZE>0
  51075. /*
  51076. ** Obtain a reference to a memory mapped page object for page number pgno.
  51077. ** The new object will use the pointer pData, obtained from xFetch().
  51078. ** If successful, set *ppPage to point to the new page reference
  51079. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  51080. ** *ppPage to zero.
  51081. **
  51082. ** Page references obtained by calling this function should be released
  51083. ** by calling pagerReleaseMapPage().
  51084. */
  51085. static int pagerAcquireMapPage(
  51086. Pager *pPager, /* Pager object */
  51087. Pgno pgno, /* Page number */
  51088. void *pData, /* xFetch()'d data for this page */
  51089. PgHdr **ppPage /* OUT: Acquired page object */
  51090. ){
  51091. PgHdr *p; /* Memory mapped page to return */
  51092. if( pPager->pMmapFreelist ){
  51093. *ppPage = p = pPager->pMmapFreelist;
  51094. pPager->pMmapFreelist = p->pDirty;
  51095. p->pDirty = 0;
  51096. assert( pPager->nExtra>=8 );
  51097. memset(p->pExtra, 0, 8);
  51098. }else{
  51099. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  51100. if( p==0 ){
  51101. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  51102. return SQLITE_NOMEM_BKPT;
  51103. }
  51104. p->pExtra = (void *)&p[1];
  51105. p->flags = PGHDR_MMAP;
  51106. p->nRef = 1;
  51107. p->pPager = pPager;
  51108. }
  51109. assert( p->pExtra==(void *)&p[1] );
  51110. assert( p->pPage==0 );
  51111. assert( p->flags==PGHDR_MMAP );
  51112. assert( p->pPager==pPager );
  51113. assert( p->nRef==1 );
  51114. p->pgno = pgno;
  51115. p->pData = pData;
  51116. pPager->nMmapOut++;
  51117. return SQLITE_OK;
  51118. }
  51119. #endif
  51120. /*
  51121. ** Release a reference to page pPg. pPg must have been returned by an
  51122. ** earlier call to pagerAcquireMapPage().
  51123. */
  51124. static void pagerReleaseMapPage(PgHdr *pPg){
  51125. Pager *pPager = pPg->pPager;
  51126. pPager->nMmapOut--;
  51127. pPg->pDirty = pPager->pMmapFreelist;
  51128. pPager->pMmapFreelist = pPg;
  51129. assert( pPager->fd->pMethods->iVersion>=3 );
  51130. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  51131. }
  51132. /*
  51133. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  51134. */
  51135. static void pagerFreeMapHdrs(Pager *pPager){
  51136. PgHdr *p;
  51137. PgHdr *pNext;
  51138. for(p=pPager->pMmapFreelist; p; p=pNext){
  51139. pNext = p->pDirty;
  51140. sqlite3_free(p);
  51141. }
  51142. }
  51143. /* Verify that the database file has not be deleted or renamed out from
  51144. ** under the pager. Return SQLITE_OK if the database is still where it ought
  51145. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  51146. ** code from sqlite3OsAccess()) if the database has gone missing.
  51147. */
  51148. static int databaseIsUnmoved(Pager *pPager){
  51149. int bHasMoved = 0;
  51150. int rc;
  51151. if( pPager->tempFile ) return SQLITE_OK;
  51152. if( pPager->dbSize==0 ) return SQLITE_OK;
  51153. assert( pPager->zFilename && pPager->zFilename[0] );
  51154. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  51155. if( rc==SQLITE_NOTFOUND ){
  51156. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  51157. ** has not been moved. That is the historical behavior of SQLite: prior to
  51158. ** version 3.8.3, it never checked */
  51159. rc = SQLITE_OK;
  51160. }else if( rc==SQLITE_OK && bHasMoved ){
  51161. rc = SQLITE_READONLY_DBMOVED;
  51162. }
  51163. return rc;
  51164. }
  51165. /*
  51166. ** Shutdown the page cache. Free all memory and close all files.
  51167. **
  51168. ** If a transaction was in progress when this routine is called, that
  51169. ** transaction is rolled back. All outstanding pages are invalidated
  51170. ** and their memory is freed. Any attempt to use a page associated
  51171. ** with this page cache after this function returns will likely
  51172. ** result in a coredump.
  51173. **
  51174. ** This function always succeeds. If a transaction is active an attempt
  51175. ** is made to roll it back. If an error occurs during the rollback
  51176. ** a hot journal may be left in the filesystem but no error is returned
  51177. ** to the caller.
  51178. */
  51179. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
  51180. u8 *pTmp = (u8*)pPager->pTmpSpace;
  51181. assert( db || pagerUseWal(pPager)==0 );
  51182. assert( assert_pager_state(pPager) );
  51183. disable_simulated_io_errors();
  51184. sqlite3BeginBenignMalloc();
  51185. pagerFreeMapHdrs(pPager);
  51186. /* pPager->errCode = 0; */
  51187. pPager->exclusiveMode = 0;
  51188. #ifndef SQLITE_OMIT_WAL
  51189. {
  51190. u8 *a = 0;
  51191. assert( db || pPager->pWal==0 );
  51192. if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
  51193. && SQLITE_OK==databaseIsUnmoved(pPager)
  51194. ){
  51195. a = pTmp;
  51196. }
  51197. sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
  51198. pPager->pWal = 0;
  51199. }
  51200. #endif
  51201. pager_reset(pPager);
  51202. if( MEMDB ){
  51203. pager_unlock(pPager);
  51204. }else{
  51205. /* If it is open, sync the journal file before calling UnlockAndRollback.
  51206. ** If this is not done, then an unsynced portion of the open journal
  51207. ** file may be played back into the database. If a power failure occurs
  51208. ** while this is happening, the database could become corrupt.
  51209. **
  51210. ** If an error occurs while trying to sync the journal, shift the pager
  51211. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  51212. ** database and close the journal file without attempting to roll it
  51213. ** back or finalize it. The next database user will have to do hot-journal
  51214. ** rollback before accessing the database file.
  51215. */
  51216. if( isOpen(pPager->jfd) ){
  51217. pager_error(pPager, pagerSyncHotJournal(pPager));
  51218. }
  51219. pagerUnlockAndRollback(pPager);
  51220. }
  51221. sqlite3EndBenignMalloc();
  51222. enable_simulated_io_errors();
  51223. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  51224. IOTRACE(("CLOSE %p\n", pPager))
  51225. sqlite3OsClose(pPager->jfd);
  51226. sqlite3OsClose(pPager->fd);
  51227. sqlite3PageFree(pTmp);
  51228. sqlite3PcacheClose(pPager->pPCache);
  51229. #ifdef SQLITE_HAS_CODEC
  51230. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  51231. #endif
  51232. assert( !pPager->aSavepoint && !pPager->pInJournal );
  51233. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  51234. sqlite3_free(pPager);
  51235. return SQLITE_OK;
  51236. }
  51237. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  51238. /*
  51239. ** Return the page number for page pPg.
  51240. */
  51241. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  51242. return pPg->pgno;
  51243. }
  51244. #endif
  51245. /*
  51246. ** Increment the reference count for page pPg.
  51247. */
  51248. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  51249. sqlite3PcacheRef(pPg);
  51250. }
  51251. /*
  51252. ** Sync the journal. In other words, make sure all the pages that have
  51253. ** been written to the journal have actually reached the surface of the
  51254. ** disk and can be restored in the event of a hot-journal rollback.
  51255. **
  51256. ** If the Pager.noSync flag is set, then this function is a no-op.
  51257. ** Otherwise, the actions required depend on the journal-mode and the
  51258. ** device characteristics of the file-system, as follows:
  51259. **
  51260. ** * If the journal file is an in-memory journal file, no action need
  51261. ** be taken.
  51262. **
  51263. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  51264. ** then the nRec field of the most recently written journal header
  51265. ** is updated to contain the number of journal records that have
  51266. ** been written following it. If the pager is operating in full-sync
  51267. ** mode, then the journal file is synced before this field is updated.
  51268. **
  51269. ** * If the device does not support the SEQUENTIAL property, then
  51270. ** journal file is synced.
  51271. **
  51272. ** Or, in pseudo-code:
  51273. **
  51274. ** if( NOT <in-memory journal> ){
  51275. ** if( NOT SAFE_APPEND ){
  51276. ** if( <full-sync mode> ) xSync(<journal file>);
  51277. ** <update nRec field>
  51278. ** }
  51279. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  51280. ** }
  51281. **
  51282. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  51283. ** page currently held in memory before returning SQLITE_OK. If an IO
  51284. ** error is encountered, then the IO error code is returned to the caller.
  51285. */
  51286. static int syncJournal(Pager *pPager, int newHdr){
  51287. int rc; /* Return code */
  51288. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  51289. || pPager->eState==PAGER_WRITER_DBMOD
  51290. );
  51291. assert( assert_pager_state(pPager) );
  51292. assert( !pagerUseWal(pPager) );
  51293. rc = sqlite3PagerExclusiveLock(pPager);
  51294. if( rc!=SQLITE_OK ) return rc;
  51295. if( !pPager->noSync ){
  51296. assert( !pPager->tempFile );
  51297. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  51298. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  51299. assert( isOpen(pPager->jfd) );
  51300. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  51301. /* This block deals with an obscure problem. If the last connection
  51302. ** that wrote to this database was operating in persistent-journal
  51303. ** mode, then the journal file may at this point actually be larger
  51304. ** than Pager.journalOff bytes. If the next thing in the journal
  51305. ** file happens to be a journal-header (written as part of the
  51306. ** previous connection's transaction), and a crash or power-failure
  51307. ** occurs after nRec is updated but before this connection writes
  51308. ** anything else to the journal file (or commits/rolls back its
  51309. ** transaction), then SQLite may become confused when doing the
  51310. ** hot-journal rollback following recovery. It may roll back all
  51311. ** of this connections data, then proceed to rolling back the old,
  51312. ** out-of-date data that follows it. Database corruption.
  51313. **
  51314. ** To work around this, if the journal file does appear to contain
  51315. ** a valid header following Pager.journalOff, then write a 0x00
  51316. ** byte to the start of it to prevent it from being recognized.
  51317. **
  51318. ** Variable iNextHdrOffset is set to the offset at which this
  51319. ** problematic header will occur, if it exists. aMagic is used
  51320. ** as a temporary buffer to inspect the first couple of bytes of
  51321. ** the potential journal header.
  51322. */
  51323. i64 iNextHdrOffset;
  51324. u8 aMagic[8];
  51325. u8 zHeader[sizeof(aJournalMagic)+4];
  51326. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  51327. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  51328. iNextHdrOffset = journalHdrOffset(pPager);
  51329. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  51330. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  51331. static const u8 zerobyte = 0;
  51332. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  51333. }
  51334. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  51335. return rc;
  51336. }
  51337. /* Write the nRec value into the journal file header. If in
  51338. ** full-synchronous mode, sync the journal first. This ensures that
  51339. ** all data has really hit the disk before nRec is updated to mark
  51340. ** it as a candidate for rollback.
  51341. **
  51342. ** This is not required if the persistent media supports the
  51343. ** SAFE_APPEND property. Because in this case it is not possible
  51344. ** for garbage data to be appended to the file, the nRec field
  51345. ** is populated with 0xFFFFFFFF when the journal header is written
  51346. ** and never needs to be updated.
  51347. */
  51348. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  51349. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  51350. IOTRACE(("JSYNC %p\n", pPager))
  51351. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  51352. if( rc!=SQLITE_OK ) return rc;
  51353. }
  51354. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  51355. rc = sqlite3OsWrite(
  51356. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  51357. );
  51358. if( rc!=SQLITE_OK ) return rc;
  51359. }
  51360. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  51361. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  51362. IOTRACE(("JSYNC %p\n", pPager))
  51363. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  51364. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  51365. );
  51366. if( rc!=SQLITE_OK ) return rc;
  51367. }
  51368. pPager->journalHdr = pPager->journalOff;
  51369. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  51370. pPager->nRec = 0;
  51371. rc = writeJournalHdr(pPager);
  51372. if( rc!=SQLITE_OK ) return rc;
  51373. }
  51374. }else{
  51375. pPager->journalHdr = pPager->journalOff;
  51376. }
  51377. }
  51378. /* Unless the pager is in noSync mode, the journal file was just
  51379. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  51380. ** all pages.
  51381. */
  51382. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  51383. pPager->eState = PAGER_WRITER_DBMOD;
  51384. assert( assert_pager_state(pPager) );
  51385. return SQLITE_OK;
  51386. }
  51387. /*
  51388. ** The argument is the first in a linked list of dirty pages connected
  51389. ** by the PgHdr.pDirty pointer. This function writes each one of the
  51390. ** in-memory pages in the list to the database file. The argument may
  51391. ** be NULL, representing an empty list. In this case this function is
  51392. ** a no-op.
  51393. **
  51394. ** The pager must hold at least a RESERVED lock when this function
  51395. ** is called. Before writing anything to the database file, this lock
  51396. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  51397. ** SQLITE_BUSY is returned and no data is written to the database file.
  51398. **
  51399. ** If the pager is a temp-file pager and the actual file-system file
  51400. ** is not yet open, it is created and opened before any data is
  51401. ** written out.
  51402. **
  51403. ** Once the lock has been upgraded and, if necessary, the file opened,
  51404. ** the pages are written out to the database file in list order. Writing
  51405. ** a page is skipped if it meets either of the following criteria:
  51406. **
  51407. ** * The page number is greater than Pager.dbSize, or
  51408. ** * The PGHDR_DONT_WRITE flag is set on the page.
  51409. **
  51410. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  51411. ** is updated accordingly. If page 1 is written out, then the value cached
  51412. ** in Pager.dbFileVers[] is updated to match the new value stored in
  51413. ** the database file.
  51414. **
  51415. ** If everything is successful, SQLITE_OK is returned. If an IO error
  51416. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  51417. ** be obtained, SQLITE_BUSY is returned.
  51418. */
  51419. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  51420. int rc = SQLITE_OK; /* Return code */
  51421. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  51422. assert( !pagerUseWal(pPager) );
  51423. assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
  51424. assert( pPager->eLock==EXCLUSIVE_LOCK );
  51425. assert( isOpen(pPager->fd) || pList->pDirty==0 );
  51426. /* If the file is a temp-file has not yet been opened, open it now. It
  51427. ** is not possible for rc to be other than SQLITE_OK if this branch
  51428. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  51429. */
  51430. if( !isOpen(pPager->fd) ){
  51431. assert( pPager->tempFile && rc==SQLITE_OK );
  51432. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  51433. }
  51434. /* Before the first write, give the VFS a hint of what the final
  51435. ** file size will be.
  51436. */
  51437. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  51438. if( rc==SQLITE_OK
  51439. && pPager->dbHintSize<pPager->dbSize
  51440. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  51441. ){
  51442. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  51443. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  51444. pPager->dbHintSize = pPager->dbSize;
  51445. }
  51446. while( rc==SQLITE_OK && pList ){
  51447. Pgno pgno = pList->pgno;
  51448. /* If there are dirty pages in the page cache with page numbers greater
  51449. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  51450. ** make the file smaller (presumably by auto-vacuum code). Do not write
  51451. ** any such pages to the file.
  51452. **
  51453. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  51454. ** set (set by sqlite3PagerDontWrite()).
  51455. */
  51456. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  51457. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  51458. char *pData; /* Data to write */
  51459. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  51460. if( pList->pgno==1 ) pager_write_changecounter(pList);
  51461. /* Encode the database */
  51462. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
  51463. /* Write out the page data. */
  51464. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  51465. /* If page 1 was just written, update Pager.dbFileVers to match
  51466. ** the value now stored in the database file. If writing this
  51467. ** page caused the database file to grow, update dbFileSize.
  51468. */
  51469. if( pgno==1 ){
  51470. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  51471. }
  51472. if( pgno>pPager->dbFileSize ){
  51473. pPager->dbFileSize = pgno;
  51474. }
  51475. pPager->aStat[PAGER_STAT_WRITE]++;
  51476. /* Update any backup objects copying the contents of this pager. */
  51477. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  51478. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  51479. PAGERID(pPager), pgno, pager_pagehash(pList)));
  51480. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  51481. PAGER_INCR(sqlite3_pager_writedb_count);
  51482. }else{
  51483. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  51484. }
  51485. pager_set_pagehash(pList);
  51486. pList = pList->pDirty;
  51487. }
  51488. return rc;
  51489. }
  51490. /*
  51491. ** Ensure that the sub-journal file is open. If it is already open, this
  51492. ** function is a no-op.
  51493. **
  51494. ** SQLITE_OK is returned if everything goes according to plan. An
  51495. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  51496. ** fails.
  51497. */
  51498. static int openSubJournal(Pager *pPager){
  51499. int rc = SQLITE_OK;
  51500. if( !isOpen(pPager->sjfd) ){
  51501. const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
  51502. | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
  51503. | SQLITE_OPEN_DELETEONCLOSE;
  51504. int nStmtSpill = sqlite3Config.nStmtSpill;
  51505. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  51506. nStmtSpill = -1;
  51507. }
  51508. rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
  51509. }
  51510. return rc;
  51511. }
  51512. /*
  51513. ** Append a record of the current state of page pPg to the sub-journal.
  51514. **
  51515. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  51516. ** for all open savepoints before returning.
  51517. **
  51518. ** This function returns SQLITE_OK if everything is successful, an IO
  51519. ** error code if the attempt to write to the sub-journal fails, or
  51520. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  51521. ** bitvec.
  51522. */
  51523. static int subjournalPage(PgHdr *pPg){
  51524. int rc = SQLITE_OK;
  51525. Pager *pPager = pPg->pPager;
  51526. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  51527. /* Open the sub-journal, if it has not already been opened */
  51528. assert( pPager->useJournal );
  51529. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  51530. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  51531. assert( pagerUseWal(pPager)
  51532. || pageInJournal(pPager, pPg)
  51533. || pPg->pgno>pPager->dbOrigSize
  51534. );
  51535. rc = openSubJournal(pPager);
  51536. /* If the sub-journal was opened successfully (or was already open),
  51537. ** write the journal record into the file. */
  51538. if( rc==SQLITE_OK ){
  51539. void *pData = pPg->pData;
  51540. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  51541. char *pData2;
  51542. #if SQLITE_HAS_CODEC
  51543. if( !pPager->subjInMemory ){
  51544. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  51545. }else
  51546. #endif
  51547. pData2 = pData;
  51548. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  51549. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  51550. if( rc==SQLITE_OK ){
  51551. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  51552. }
  51553. }
  51554. }
  51555. if( rc==SQLITE_OK ){
  51556. pPager->nSubRec++;
  51557. assert( pPager->nSavepoint>0 );
  51558. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  51559. }
  51560. return rc;
  51561. }
  51562. static int subjournalPageIfRequired(PgHdr *pPg){
  51563. if( subjRequiresPage(pPg) ){
  51564. return subjournalPage(pPg);
  51565. }else{
  51566. return SQLITE_OK;
  51567. }
  51568. }
  51569. /*
  51570. ** This function is called by the pcache layer when it has reached some
  51571. ** soft memory limit. The first argument is a pointer to a Pager object
  51572. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  51573. ** database). The second argument is a reference to a page that is
  51574. ** currently dirty but has no outstanding references. The page
  51575. ** is always associated with the Pager object passed as the first
  51576. ** argument.
  51577. **
  51578. ** The job of this function is to make pPg clean by writing its contents
  51579. ** out to the database file, if possible. This may involve syncing the
  51580. ** journal file.
  51581. **
  51582. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  51583. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  51584. ** page clean, the IO error code is returned. If the page cannot be
  51585. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  51586. ** is returned by sqlite3PcacheMakeClean() is not called.
  51587. */
  51588. static int pagerStress(void *p, PgHdr *pPg){
  51589. Pager *pPager = (Pager *)p;
  51590. int rc = SQLITE_OK;
  51591. assert( pPg->pPager==pPager );
  51592. assert( pPg->flags&PGHDR_DIRTY );
  51593. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  51594. ** journal (and adding a new header) is not allowed. This occurs
  51595. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  51596. ** pages belonging to the same sector.
  51597. **
  51598. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  51599. ** regardless of whether or not a sync is required. This is set during
  51600. ** a rollback or by user request, respectively.
  51601. **
  51602. ** Spilling is also prohibited when in an error state since that could
  51603. ** lead to database corruption. In the current implementation it
  51604. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  51605. ** while in the error state, hence it is impossible for this routine to
  51606. ** be called in the error state. Nevertheless, we include a NEVER()
  51607. ** test for the error state as a safeguard against future changes.
  51608. */
  51609. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  51610. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  51611. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  51612. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  51613. if( pPager->doNotSpill
  51614. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  51615. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  51616. ){
  51617. return SQLITE_OK;
  51618. }
  51619. pPager->aStat[PAGER_STAT_SPILL]++;
  51620. pPg->pDirty = 0;
  51621. if( pagerUseWal(pPager) ){
  51622. /* Write a single frame for this page to the log. */
  51623. rc = subjournalPageIfRequired(pPg);
  51624. if( rc==SQLITE_OK ){
  51625. rc = pagerWalFrames(pPager, pPg, 0, 0);
  51626. }
  51627. }else{
  51628. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  51629. if( pPager->tempFile==0 ){
  51630. rc = sqlite3JournalCreate(pPager->jfd);
  51631. if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
  51632. }
  51633. #endif
  51634. /* Sync the journal file if required. */
  51635. if( pPg->flags&PGHDR_NEED_SYNC
  51636. || pPager->eState==PAGER_WRITER_CACHEMOD
  51637. ){
  51638. rc = syncJournal(pPager, 1);
  51639. }
  51640. /* Write the contents of the page out to the database file. */
  51641. if( rc==SQLITE_OK ){
  51642. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  51643. rc = pager_write_pagelist(pPager, pPg);
  51644. }
  51645. }
  51646. /* Mark the page as clean. */
  51647. if( rc==SQLITE_OK ){
  51648. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  51649. sqlite3PcacheMakeClean(pPg);
  51650. }
  51651. return pager_error(pPager, rc);
  51652. }
  51653. /*
  51654. ** Flush all unreferenced dirty pages to disk.
  51655. */
  51656. SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
  51657. int rc = pPager->errCode;
  51658. if( !MEMDB ){
  51659. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  51660. assert( assert_pager_state(pPager) );
  51661. while( rc==SQLITE_OK && pList ){
  51662. PgHdr *pNext = pList->pDirty;
  51663. if( pList->nRef==0 ){
  51664. rc = pagerStress((void*)pPager, pList);
  51665. }
  51666. pList = pNext;
  51667. }
  51668. }
  51669. return rc;
  51670. }
  51671. /*
  51672. ** Allocate and initialize a new Pager object and put a pointer to it
  51673. ** in *ppPager. The pager should eventually be freed by passing it
  51674. ** to sqlite3PagerClose().
  51675. **
  51676. ** The zFilename argument is the path to the database file to open.
  51677. ** If zFilename is NULL then a randomly-named temporary file is created
  51678. ** and used as the file to be cached. Temporary files are be deleted
  51679. ** automatically when they are closed. If zFilename is ":memory:" then
  51680. ** all information is held in cache. It is never written to disk.
  51681. ** This can be used to implement an in-memory database.
  51682. **
  51683. ** The nExtra parameter specifies the number of bytes of space allocated
  51684. ** along with each page reference. This space is available to the user
  51685. ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the
  51686. ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
  51687. ** (The extra space is used by btree as the MemPage object.)
  51688. **
  51689. ** The flags argument is used to specify properties that affect the
  51690. ** operation of the pager. It should be passed some bitwise combination
  51691. ** of the PAGER_* flags.
  51692. **
  51693. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  51694. ** of the xOpen() method of the supplied VFS when opening files.
  51695. **
  51696. ** If the pager object is allocated and the specified file opened
  51697. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  51698. ** the new pager object. If an error occurs, *ppPager is set to NULL
  51699. ** and error code returned. This function may return SQLITE_NOMEM
  51700. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  51701. ** various SQLITE_IO_XXX errors.
  51702. */
  51703. SQLITE_PRIVATE int sqlite3PagerOpen(
  51704. sqlite3_vfs *pVfs, /* The virtual file system to use */
  51705. Pager **ppPager, /* OUT: Return the Pager structure here */
  51706. const char *zFilename, /* Name of the database file to open */
  51707. int nExtra, /* Extra bytes append to each in-memory page */
  51708. int flags, /* flags controlling this file */
  51709. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  51710. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  51711. ){
  51712. u8 *pPtr;
  51713. Pager *pPager = 0; /* Pager object to allocate and return */
  51714. int rc = SQLITE_OK; /* Return code */
  51715. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  51716. int memDb = 0; /* True if this is an in-memory file */
  51717. #ifdef SQLITE_ENABLE_DESERIALIZE
  51718. int memJM = 0; /* Memory journal mode */
  51719. #else
  51720. # define memJM 0
  51721. #endif
  51722. int readOnly = 0; /* True if this is a read-only file */
  51723. int journalFileSize; /* Bytes to allocate for each journal fd */
  51724. char *zPathname = 0; /* Full path to database file */
  51725. int nPathname = 0; /* Number of bytes in zPathname */
  51726. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  51727. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  51728. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  51729. const char *zUri = 0; /* URI args to copy */
  51730. int nUri = 0; /* Number of bytes of URI args at *zUri */
  51731. /* Figure out how much space is required for each journal file-handle
  51732. ** (there are two of them, the main journal and the sub-journal). */
  51733. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  51734. /* Set the output variable to NULL in case an error occurs. */
  51735. *ppPager = 0;
  51736. #ifndef SQLITE_OMIT_MEMORYDB
  51737. if( flags & PAGER_MEMORY ){
  51738. memDb = 1;
  51739. if( zFilename && zFilename[0] ){
  51740. zPathname = sqlite3DbStrDup(0, zFilename);
  51741. if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
  51742. nPathname = sqlite3Strlen30(zPathname);
  51743. zFilename = 0;
  51744. }
  51745. }
  51746. #endif
  51747. /* Compute and store the full pathname in an allocated buffer pointed
  51748. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  51749. ** leave both nPathname and zPathname set to 0.
  51750. */
  51751. if( zFilename && zFilename[0] ){
  51752. const char *z;
  51753. nPathname = pVfs->mxPathname+1;
  51754. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  51755. if( zPathname==0 ){
  51756. return SQLITE_NOMEM_BKPT;
  51757. }
  51758. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  51759. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  51760. nPathname = sqlite3Strlen30(zPathname);
  51761. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  51762. while( *z ){
  51763. z += sqlite3Strlen30(z)+1;
  51764. z += sqlite3Strlen30(z)+1;
  51765. }
  51766. nUri = (int)(&z[1] - zUri);
  51767. assert( nUri>=0 );
  51768. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  51769. /* This branch is taken when the journal path required by
  51770. ** the database being opened will be more than pVfs->mxPathname
  51771. ** bytes in length. This means the database cannot be opened,
  51772. ** as it will not be possible to open the journal file or even
  51773. ** check for a hot-journal before reading.
  51774. */
  51775. rc = SQLITE_CANTOPEN_BKPT;
  51776. }
  51777. if( rc!=SQLITE_OK ){
  51778. sqlite3DbFree(0, zPathname);
  51779. return rc;
  51780. }
  51781. }
  51782. /* Allocate memory for the Pager structure, PCache object, the
  51783. ** three file descriptors, the database file name and the journal
  51784. ** file name. The layout in memory is as follows:
  51785. **
  51786. ** Pager object (sizeof(Pager) bytes)
  51787. ** PCache object (sqlite3PcacheSize() bytes)
  51788. ** Database file handle (pVfs->szOsFile bytes)
  51789. ** Sub-journal file handle (journalFileSize bytes)
  51790. ** Main journal file handle (journalFileSize bytes)
  51791. ** Database file name (nPathname+1 bytes)
  51792. ** Journal file name (nPathname+8+1 bytes)
  51793. */
  51794. pPtr = (u8 *)sqlite3MallocZero(
  51795. ROUND8(sizeof(*pPager)) + /* Pager structure */
  51796. ROUND8(pcacheSize) + /* PCache object */
  51797. ROUND8(pVfs->szOsFile) + /* The main db file */
  51798. journalFileSize * 2 + /* The two journal files */
  51799. nPathname + 1 + nUri + /* zFilename */
  51800. nPathname + 8 + 2 /* zJournal */
  51801. #ifndef SQLITE_OMIT_WAL
  51802. + nPathname + 4 + 2 /* zWal */
  51803. #endif
  51804. );
  51805. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  51806. if( !pPtr ){
  51807. sqlite3DbFree(0, zPathname);
  51808. return SQLITE_NOMEM_BKPT;
  51809. }
  51810. pPager = (Pager*)(pPtr);
  51811. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  51812. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  51813. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  51814. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  51815. pPager->zFilename = (char*)(pPtr += journalFileSize);
  51816. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  51817. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  51818. if( zPathname ){
  51819. assert( nPathname>0 );
  51820. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  51821. memcpy(pPager->zFilename, zPathname, nPathname);
  51822. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  51823. memcpy(pPager->zJournal, zPathname, nPathname);
  51824. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  51825. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  51826. #ifndef SQLITE_OMIT_WAL
  51827. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  51828. memcpy(pPager->zWal, zPathname, nPathname);
  51829. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  51830. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  51831. #endif
  51832. sqlite3DbFree(0, zPathname);
  51833. }
  51834. pPager->pVfs = pVfs;
  51835. pPager->vfsFlags = vfsFlags;
  51836. /* Open the pager file.
  51837. */
  51838. if( zFilename && zFilename[0] ){
  51839. int fout = 0; /* VFS flags returned by xOpen() */
  51840. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  51841. assert( !memDb );
  51842. #ifdef SQLITE_ENABLE_DESERIALIZE
  51843. memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
  51844. #endif
  51845. readOnly = (fout&SQLITE_OPEN_READONLY)!=0;
  51846. /* If the file was successfully opened for read/write access,
  51847. ** choose a default page size in case we have to create the
  51848. ** database file. The default page size is the maximum of:
  51849. **
  51850. ** + SQLITE_DEFAULT_PAGE_SIZE,
  51851. ** + The value returned by sqlite3OsSectorSize()
  51852. ** + The largest page size that can be written atomically.
  51853. */
  51854. if( rc==SQLITE_OK ){
  51855. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  51856. if( !readOnly ){
  51857. setSectorSize(pPager);
  51858. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  51859. if( szPageDflt<pPager->sectorSize ){
  51860. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  51861. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  51862. }else{
  51863. szPageDflt = (u32)pPager->sectorSize;
  51864. }
  51865. }
  51866. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  51867. {
  51868. int ii;
  51869. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  51870. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  51871. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  51872. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  51873. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  51874. szPageDflt = ii;
  51875. }
  51876. }
  51877. }
  51878. #endif
  51879. }
  51880. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  51881. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  51882. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  51883. vfsFlags |= SQLITE_OPEN_READONLY;
  51884. goto act_like_temp_file;
  51885. }
  51886. }
  51887. }else{
  51888. /* If a temporary file is requested, it is not opened immediately.
  51889. ** In this case we accept the default page size and delay actually
  51890. ** opening the file until the first call to OsWrite().
  51891. **
  51892. ** This branch is also run for an in-memory database. An in-memory
  51893. ** database is the same as a temp-file that is never written out to
  51894. ** disk and uses an in-memory rollback journal.
  51895. **
  51896. ** This branch also runs for files marked as immutable.
  51897. */
  51898. act_like_temp_file:
  51899. tempFile = 1;
  51900. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  51901. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  51902. pPager->noLock = 1; /* Do no locking */
  51903. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  51904. }
  51905. /* The following call to PagerSetPagesize() serves to set the value of
  51906. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  51907. */
  51908. if( rc==SQLITE_OK ){
  51909. assert( pPager->memDb==0 );
  51910. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  51911. testcase( rc!=SQLITE_OK );
  51912. }
  51913. /* Initialize the PCache object. */
  51914. if( rc==SQLITE_OK ){
  51915. nExtra = ROUND8(nExtra);
  51916. assert( nExtra>=8 && nExtra<1000 );
  51917. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  51918. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  51919. }
  51920. /* If an error occurred above, free the Pager structure and close the file.
  51921. */
  51922. if( rc!=SQLITE_OK ){
  51923. sqlite3OsClose(pPager->fd);
  51924. sqlite3PageFree(pPager->pTmpSpace);
  51925. sqlite3_free(pPager);
  51926. return rc;
  51927. }
  51928. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  51929. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  51930. pPager->useJournal = (u8)useJournal;
  51931. /* pPager->stmtOpen = 0; */
  51932. /* pPager->stmtInUse = 0; */
  51933. /* pPager->nRef = 0; */
  51934. /* pPager->stmtSize = 0; */
  51935. /* pPager->stmtJSize = 0; */
  51936. /* pPager->nPage = 0; */
  51937. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  51938. /* pPager->state = PAGER_UNLOCK; */
  51939. /* pPager->errMask = 0; */
  51940. pPager->tempFile = (u8)tempFile;
  51941. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  51942. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  51943. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  51944. pPager->exclusiveMode = (u8)tempFile;
  51945. pPager->changeCountDone = pPager->tempFile;
  51946. pPager->memDb = (u8)memDb;
  51947. pPager->readOnly = (u8)readOnly;
  51948. assert( useJournal || pPager->tempFile );
  51949. pPager->noSync = pPager->tempFile;
  51950. if( pPager->noSync ){
  51951. assert( pPager->fullSync==0 );
  51952. assert( pPager->extraSync==0 );
  51953. assert( pPager->syncFlags==0 );
  51954. assert( pPager->walSyncFlags==0 );
  51955. }else{
  51956. pPager->fullSync = 1;
  51957. pPager->extraSync = 0;
  51958. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  51959. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
  51960. }
  51961. /* pPager->pFirst = 0; */
  51962. /* pPager->pFirstSynced = 0; */
  51963. /* pPager->pLast = 0; */
  51964. pPager->nExtra = (u16)nExtra;
  51965. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  51966. assert( isOpen(pPager->fd) || tempFile );
  51967. setSectorSize(pPager);
  51968. if( !useJournal ){
  51969. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  51970. }else if( memDb || memJM ){
  51971. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  51972. }
  51973. /* pPager->xBusyHandler = 0; */
  51974. /* pPager->pBusyHandlerArg = 0; */
  51975. pPager->xReiniter = xReinit;
  51976. setGetterMethod(pPager);
  51977. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  51978. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  51979. *ppPager = pPager;
  51980. return SQLITE_OK;
  51981. }
  51982. /*
  51983. ** This function is called after transitioning from PAGER_UNLOCK to
  51984. ** PAGER_SHARED state. It tests if there is a hot journal present in
  51985. ** the file-system for the given pager. A hot journal is one that
  51986. ** needs to be played back. According to this function, a hot-journal
  51987. ** file exists if the following criteria are met:
  51988. **
  51989. ** * The journal file exists in the file system, and
  51990. ** * No process holds a RESERVED or greater lock on the database file, and
  51991. ** * The database file itself is greater than 0 bytes in size, and
  51992. ** * The first byte of the journal file exists and is not 0x00.
  51993. **
  51994. ** If the current size of the database file is 0 but a journal file
  51995. ** exists, that is probably an old journal left over from a prior
  51996. ** database with the same name. In this case the journal file is
  51997. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  51998. ** is returned.
  51999. **
  52000. ** This routine does not check if there is a master journal filename
  52001. ** at the end of the file. If there is, and that master journal file
  52002. ** does not exist, then the journal file is not really hot. In this
  52003. ** case this routine will return a false-positive. The pager_playback()
  52004. ** routine will discover that the journal file is not really hot and
  52005. ** will not roll it back.
  52006. **
  52007. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  52008. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  52009. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  52010. ** to determine whether or not a hot-journal file exists, the IO error
  52011. ** code is returned and the value of *pExists is undefined.
  52012. */
  52013. static int hasHotJournal(Pager *pPager, int *pExists){
  52014. sqlite3_vfs * const pVfs = pPager->pVfs;
  52015. int rc = SQLITE_OK; /* Return code */
  52016. int exists = 1; /* True if a journal file is present */
  52017. int jrnlOpen = !!isOpen(pPager->jfd);
  52018. assert( pPager->useJournal );
  52019. assert( isOpen(pPager->fd) );
  52020. assert( pPager->eState==PAGER_OPEN );
  52021. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  52022. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  52023. ));
  52024. *pExists = 0;
  52025. if( !jrnlOpen ){
  52026. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  52027. }
  52028. if( rc==SQLITE_OK && exists ){
  52029. int locked = 0; /* True if some process holds a RESERVED lock */
  52030. /* Race condition here: Another process might have been holding the
  52031. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  52032. ** call above, but then delete the journal and drop the lock before
  52033. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  52034. ** is the case, this routine might think there is a hot journal when
  52035. ** in fact there is none. This results in a false-positive which will
  52036. ** be dealt with by the playback routine. Ticket #3883.
  52037. */
  52038. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  52039. if( rc==SQLITE_OK && !locked ){
  52040. Pgno nPage; /* Number of pages in database file */
  52041. assert( pPager->tempFile==0 );
  52042. rc = pagerPagecount(pPager, &nPage);
  52043. if( rc==SQLITE_OK ){
  52044. /* If the database is zero pages in size, that means that either (1) the
  52045. ** journal is a remnant from a prior database with the same name where
  52046. ** the database file but not the journal was deleted, or (2) the initial
  52047. ** transaction that populates a new database is being rolled back.
  52048. ** In either case, the journal file can be deleted. However, take care
  52049. ** not to delete the journal file if it is already open due to
  52050. ** journal_mode=PERSIST.
  52051. */
  52052. if( nPage==0 && !jrnlOpen ){
  52053. sqlite3BeginBenignMalloc();
  52054. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  52055. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  52056. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  52057. }
  52058. sqlite3EndBenignMalloc();
  52059. }else{
  52060. /* The journal file exists and no other connection has a reserved
  52061. ** or greater lock on the database file. Now check that there is
  52062. ** at least one non-zero bytes at the start of the journal file.
  52063. ** If there is, then we consider this journal to be hot. If not,
  52064. ** it can be ignored.
  52065. */
  52066. if( !jrnlOpen ){
  52067. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  52068. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  52069. }
  52070. if( rc==SQLITE_OK ){
  52071. u8 first = 0;
  52072. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  52073. if( rc==SQLITE_IOERR_SHORT_READ ){
  52074. rc = SQLITE_OK;
  52075. }
  52076. if( !jrnlOpen ){
  52077. sqlite3OsClose(pPager->jfd);
  52078. }
  52079. *pExists = (first!=0);
  52080. }else if( rc==SQLITE_CANTOPEN ){
  52081. /* If we cannot open the rollback journal file in order to see if
  52082. ** it has a zero header, that might be due to an I/O error, or
  52083. ** it might be due to the race condition described above and in
  52084. ** ticket #3883. Either way, assume that the journal is hot.
  52085. ** This might be a false positive. But if it is, then the
  52086. ** automatic journal playback and recovery mechanism will deal
  52087. ** with it under an EXCLUSIVE lock where we do not need to
  52088. ** worry so much with race conditions.
  52089. */
  52090. *pExists = 1;
  52091. rc = SQLITE_OK;
  52092. }
  52093. }
  52094. }
  52095. }
  52096. }
  52097. return rc;
  52098. }
  52099. /*
  52100. ** This function is called to obtain a shared lock on the database file.
  52101. ** It is illegal to call sqlite3PagerGet() until after this function
  52102. ** has been successfully called. If a shared-lock is already held when
  52103. ** this function is called, it is a no-op.
  52104. **
  52105. ** The following operations are also performed by this function.
  52106. **
  52107. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  52108. ** on the database file), then an attempt is made to obtain a
  52109. ** SHARED lock on the database file. Immediately after obtaining
  52110. ** the SHARED lock, the file-system is checked for a hot-journal,
  52111. ** which is played back if present. Following any hot-journal
  52112. ** rollback, the contents of the cache are validated by checking
  52113. ** the 'change-counter' field of the database file header and
  52114. ** discarded if they are found to be invalid.
  52115. **
  52116. ** 2) If the pager is running in exclusive-mode, and there are currently
  52117. ** no outstanding references to any pages, and is in the error state,
  52118. ** then an attempt is made to clear the error state by discarding
  52119. ** the contents of the page cache and rolling back any open journal
  52120. ** file.
  52121. **
  52122. ** If everything is successful, SQLITE_OK is returned. If an IO error
  52123. ** occurs while locking the database, checking for a hot-journal file or
  52124. ** rolling back a journal file, the IO error code is returned.
  52125. */
  52126. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  52127. int rc = SQLITE_OK; /* Return code */
  52128. /* This routine is only called from b-tree and only when there are no
  52129. ** outstanding pages. This implies that the pager state should either
  52130. ** be OPEN or READER. READER is only possible if the pager is or was in
  52131. ** exclusive access mode. */
  52132. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  52133. assert( assert_pager_state(pPager) );
  52134. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  52135. assert( pPager->errCode==SQLITE_OK );
  52136. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  52137. int bHotJournal = 1; /* True if there exists a hot journal-file */
  52138. assert( !MEMDB );
  52139. assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
  52140. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  52141. if( rc!=SQLITE_OK ){
  52142. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  52143. goto failed;
  52144. }
  52145. /* If a journal file exists, and there is no RESERVED lock on the
  52146. ** database file, then it either needs to be played back or deleted.
  52147. */
  52148. if( pPager->eLock<=SHARED_LOCK ){
  52149. rc = hasHotJournal(pPager, &bHotJournal);
  52150. }
  52151. if( rc!=SQLITE_OK ){
  52152. goto failed;
  52153. }
  52154. if( bHotJournal ){
  52155. if( pPager->readOnly ){
  52156. rc = SQLITE_READONLY_ROLLBACK;
  52157. goto failed;
  52158. }
  52159. /* Get an EXCLUSIVE lock on the database file. At this point it is
  52160. ** important that a RESERVED lock is not obtained on the way to the
  52161. ** EXCLUSIVE lock. If it were, another process might open the
  52162. ** database file, detect the RESERVED lock, and conclude that the
  52163. ** database is safe to read while this process is still rolling the
  52164. ** hot-journal back.
  52165. **
  52166. ** Because the intermediate RESERVED lock is not requested, any
  52167. ** other process attempting to access the database file will get to
  52168. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  52169. ** on the database file.
  52170. **
  52171. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  52172. ** downgraded to SHARED_LOCK before this function returns.
  52173. */
  52174. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  52175. if( rc!=SQLITE_OK ){
  52176. goto failed;
  52177. }
  52178. /* If it is not already open and the file exists on disk, open the
  52179. ** journal for read/write access. Write access is required because
  52180. ** in exclusive-access mode the file descriptor will be kept open
  52181. ** and possibly used for a transaction later on. Also, write-access
  52182. ** is usually required to finalize the journal in journal_mode=persist
  52183. ** mode (and also for journal_mode=truncate on some systems).
  52184. **
  52185. ** If the journal does not exist, it usually means that some
  52186. ** other connection managed to get in and roll it back before
  52187. ** this connection obtained the exclusive lock above. Or, it
  52188. ** may mean that the pager was in the error-state when this
  52189. ** function was called and the journal file does not exist.
  52190. */
  52191. if( !isOpen(pPager->jfd) ){
  52192. sqlite3_vfs * const pVfs = pPager->pVfs;
  52193. int bExists; /* True if journal file exists */
  52194. rc = sqlite3OsAccess(
  52195. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  52196. if( rc==SQLITE_OK && bExists ){
  52197. int fout = 0;
  52198. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  52199. assert( !pPager->tempFile );
  52200. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  52201. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  52202. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  52203. rc = SQLITE_CANTOPEN_BKPT;
  52204. sqlite3OsClose(pPager->jfd);
  52205. }
  52206. }
  52207. }
  52208. /* Playback and delete the journal. Drop the database write
  52209. ** lock and reacquire the read lock. Purge the cache before
  52210. ** playing back the hot-journal so that we don't end up with
  52211. ** an inconsistent cache. Sync the hot journal before playing
  52212. ** it back since the process that crashed and left the hot journal
  52213. ** probably did not sync it and we are required to always sync
  52214. ** the journal before playing it back.
  52215. */
  52216. if( isOpen(pPager->jfd) ){
  52217. assert( rc==SQLITE_OK );
  52218. rc = pagerSyncHotJournal(pPager);
  52219. if( rc==SQLITE_OK ){
  52220. rc = pager_playback(pPager, !pPager->tempFile);
  52221. pPager->eState = PAGER_OPEN;
  52222. }
  52223. }else if( !pPager->exclusiveMode ){
  52224. pagerUnlockDb(pPager, SHARED_LOCK);
  52225. }
  52226. if( rc!=SQLITE_OK ){
  52227. /* This branch is taken if an error occurs while trying to open
  52228. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  52229. ** pager_unlock() routine will be called before returning to unlock
  52230. ** the file. If the unlock attempt fails, then Pager.eLock must be
  52231. ** set to UNKNOWN_LOCK (see the comment above the #define for
  52232. ** UNKNOWN_LOCK above for an explanation).
  52233. **
  52234. ** In order to get pager_unlock() to do this, set Pager.eState to
  52235. ** PAGER_ERROR now. This is not actually counted as a transition
  52236. ** to ERROR state in the state diagram at the top of this file,
  52237. ** since we know that the same call to pager_unlock() will very
  52238. ** shortly transition the pager object to the OPEN state. Calling
  52239. ** assert_pager_state() would fail now, as it should not be possible
  52240. ** to be in ERROR state when there are zero outstanding page
  52241. ** references.
  52242. */
  52243. pager_error(pPager, rc);
  52244. goto failed;
  52245. }
  52246. assert( pPager->eState==PAGER_OPEN );
  52247. assert( (pPager->eLock==SHARED_LOCK)
  52248. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  52249. );
  52250. }
  52251. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  52252. /* The shared-lock has just been acquired then check to
  52253. ** see if the database has been modified. If the database has changed,
  52254. ** flush the cache. The hasHeldSharedLock flag prevents this from
  52255. ** occurring on the very first access to a file, in order to save a
  52256. ** single unnecessary sqlite3OsRead() call at the start-up.
  52257. **
  52258. ** Database changes are detected by looking at 15 bytes beginning
  52259. ** at offset 24 into the file. The first 4 of these 16 bytes are
  52260. ** a 32-bit counter that is incremented with each change. The
  52261. ** other bytes change randomly with each file change when
  52262. ** a codec is in use.
  52263. **
  52264. ** There is a vanishingly small chance that a change will not be
  52265. ** detected. The chance of an undetected change is so small that
  52266. ** it can be neglected.
  52267. */
  52268. char dbFileVers[sizeof(pPager->dbFileVers)];
  52269. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  52270. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  52271. if( rc!=SQLITE_OK ){
  52272. if( rc!=SQLITE_IOERR_SHORT_READ ){
  52273. goto failed;
  52274. }
  52275. memset(dbFileVers, 0, sizeof(dbFileVers));
  52276. }
  52277. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  52278. pager_reset(pPager);
  52279. /* Unmap the database file. It is possible that external processes
  52280. ** may have truncated the database file and then extended it back
  52281. ** to its original size while this process was not holding a lock.
  52282. ** In this case there may exist a Pager.pMap mapping that appears
  52283. ** to be the right size but is not actually valid. Avoid this
  52284. ** possibility by unmapping the db here. */
  52285. if( USEFETCH(pPager) ){
  52286. sqlite3OsUnfetch(pPager->fd, 0, 0);
  52287. }
  52288. }
  52289. }
  52290. /* If there is a WAL file in the file-system, open this database in WAL
  52291. ** mode. Otherwise, the following function call is a no-op.
  52292. */
  52293. rc = pagerOpenWalIfPresent(pPager);
  52294. #ifndef SQLITE_OMIT_WAL
  52295. assert( pPager->pWal==0 || rc==SQLITE_OK );
  52296. #endif
  52297. }
  52298. if( pagerUseWal(pPager) ){
  52299. assert( rc==SQLITE_OK );
  52300. rc = pagerBeginReadTransaction(pPager);
  52301. }
  52302. if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  52303. rc = pagerPagecount(pPager, &pPager->dbSize);
  52304. }
  52305. failed:
  52306. if( rc!=SQLITE_OK ){
  52307. assert( !MEMDB );
  52308. pager_unlock(pPager);
  52309. assert( pPager->eState==PAGER_OPEN );
  52310. }else{
  52311. pPager->eState = PAGER_READER;
  52312. pPager->hasHeldSharedLock = 1;
  52313. }
  52314. return rc;
  52315. }
  52316. /*
  52317. ** If the reference count has reached zero, rollback any active
  52318. ** transaction and unlock the pager.
  52319. **
  52320. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  52321. ** the rollback journal, the unlock is not performed and there is
  52322. ** nothing to rollback, so this routine is a no-op.
  52323. */
  52324. static void pagerUnlockIfUnused(Pager *pPager){
  52325. if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
  52326. assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
  52327. pagerUnlockAndRollback(pPager);
  52328. }
  52329. }
  52330. /*
  52331. ** The page getter methods each try to acquire a reference to a
  52332. ** page with page number pgno. If the requested reference is
  52333. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  52334. **
  52335. ** There are different implementations of the getter method depending
  52336. ** on the current state of the pager.
  52337. **
  52338. ** getPageNormal() -- The normal getter
  52339. ** getPageError() -- Used if the pager is in an error state
  52340. ** getPageMmap() -- Used if memory-mapped I/O is enabled
  52341. **
  52342. ** If the requested page is already in the cache, it is returned.
  52343. ** Otherwise, a new page object is allocated and populated with data
  52344. ** read from the database file. In some cases, the pcache module may
  52345. ** choose not to allocate a new page object and may reuse an existing
  52346. ** object with no outstanding references.
  52347. **
  52348. ** The extra data appended to a page is always initialized to zeros the
  52349. ** first time a page is loaded into memory. If the page requested is
  52350. ** already in the cache when this function is called, then the extra
  52351. ** data is left as it was when the page object was last used.
  52352. **
  52353. ** If the database image is smaller than the requested page or if
  52354. ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
  52355. ** requested page is not already stored in the cache, then no
  52356. ** actual disk read occurs. In this case the memory image of the
  52357. ** page is initialized to all zeros.
  52358. **
  52359. ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
  52360. ** the contents of the page. This occurs in two scenarios:
  52361. **
  52362. ** a) When reading a free-list leaf page from the database, and
  52363. **
  52364. ** b) When a savepoint is being rolled back and we need to load
  52365. ** a new page into the cache to be filled with the data read
  52366. ** from the savepoint journal.
  52367. **
  52368. ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
  52369. ** of being read from the database. Additionally, the bits corresponding
  52370. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  52371. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  52372. ** savepoints are set. This means if the page is made writable at any
  52373. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  52374. ** will not be journaled. This saves IO.
  52375. **
  52376. ** The acquisition might fail for several reasons. In all cases,
  52377. ** an appropriate error code is returned and *ppPage is set to NULL.
  52378. **
  52379. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  52380. ** to find a page in the in-memory cache first. If the page is not already
  52381. ** in memory, this routine goes to disk to read it in whereas Lookup()
  52382. ** just returns 0. This routine acquires a read-lock the first time it
  52383. ** has to go to disk, and could also playback an old journal if necessary.
  52384. ** Since Lookup() never goes to disk, it never has to deal with locks
  52385. ** or journal files.
  52386. */
  52387. static int getPageNormal(
  52388. Pager *pPager, /* The pager open on the database file */
  52389. Pgno pgno, /* Page number to fetch */
  52390. DbPage **ppPage, /* Write a pointer to the page here */
  52391. int flags /* PAGER_GET_XXX flags */
  52392. ){
  52393. int rc = SQLITE_OK;
  52394. PgHdr *pPg;
  52395. u8 noContent; /* True if PAGER_GET_NOCONTENT is set */
  52396. sqlite3_pcache_page *pBase;
  52397. assert( pPager->errCode==SQLITE_OK );
  52398. assert( pPager->eState>=PAGER_READER );
  52399. assert( assert_pager_state(pPager) );
  52400. assert( pPager->hasHeldSharedLock==1 );
  52401. if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
  52402. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  52403. if( pBase==0 ){
  52404. pPg = 0;
  52405. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  52406. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  52407. if( pBase==0 ){
  52408. rc = SQLITE_NOMEM_BKPT;
  52409. goto pager_acquire_err;
  52410. }
  52411. }
  52412. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  52413. assert( pPg==(*ppPage) );
  52414. assert( pPg->pgno==pgno );
  52415. assert( pPg->pPager==pPager || pPg->pPager==0 );
  52416. noContent = (flags & PAGER_GET_NOCONTENT)!=0;
  52417. if( pPg->pPager && !noContent ){
  52418. /* In this case the pcache already contains an initialized copy of
  52419. ** the page. Return without further ado. */
  52420. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  52421. pPager->aStat[PAGER_STAT_HIT]++;
  52422. return SQLITE_OK;
  52423. }else{
  52424. /* The pager cache has created a new page. Its content needs to
  52425. ** be initialized. But first some error checks:
  52426. **
  52427. ** (1) The maximum page number is 2^31
  52428. ** (2) Never try to fetch the locking page
  52429. */
  52430. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  52431. rc = SQLITE_CORRUPT_BKPT;
  52432. goto pager_acquire_err;
  52433. }
  52434. pPg->pPager = pPager;
  52435. assert( !isOpen(pPager->fd) || !MEMDB );
  52436. if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
  52437. if( pgno>pPager->mxPgno ){
  52438. rc = SQLITE_FULL;
  52439. goto pager_acquire_err;
  52440. }
  52441. if( noContent ){
  52442. /* Failure to set the bits in the InJournal bit-vectors is benign.
  52443. ** It merely means that we might do some extra work to journal a
  52444. ** page that does not need to be journaled. Nevertheless, be sure
  52445. ** to test the case where a malloc error occurs while trying to set
  52446. ** a bit in a bit vector.
  52447. */
  52448. sqlite3BeginBenignMalloc();
  52449. if( pgno<=pPager->dbOrigSize ){
  52450. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  52451. testcase( rc==SQLITE_NOMEM );
  52452. }
  52453. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  52454. testcase( rc==SQLITE_NOMEM );
  52455. sqlite3EndBenignMalloc();
  52456. }
  52457. memset(pPg->pData, 0, pPager->pageSize);
  52458. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  52459. }else{
  52460. assert( pPg->pPager==pPager );
  52461. pPager->aStat[PAGER_STAT_MISS]++;
  52462. rc = readDbPage(pPg);
  52463. if( rc!=SQLITE_OK ){
  52464. goto pager_acquire_err;
  52465. }
  52466. }
  52467. pager_set_pagehash(pPg);
  52468. }
  52469. return SQLITE_OK;
  52470. pager_acquire_err:
  52471. assert( rc!=SQLITE_OK );
  52472. if( pPg ){
  52473. sqlite3PcacheDrop(pPg);
  52474. }
  52475. pagerUnlockIfUnused(pPager);
  52476. *ppPage = 0;
  52477. return rc;
  52478. }
  52479. #if SQLITE_MAX_MMAP_SIZE>0
  52480. /* The page getter for when memory-mapped I/O is enabled */
  52481. static int getPageMMap(
  52482. Pager *pPager, /* The pager open on the database file */
  52483. Pgno pgno, /* Page number to fetch */
  52484. DbPage **ppPage, /* Write a pointer to the page here */
  52485. int flags /* PAGER_GET_XXX flags */
  52486. ){
  52487. int rc = SQLITE_OK;
  52488. PgHdr *pPg = 0;
  52489. u32 iFrame = 0; /* Frame to read from WAL file */
  52490. /* It is acceptable to use a read-only (mmap) page for any page except
  52491. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  52492. ** flag was specified by the caller. And so long as the db is not a
  52493. ** temporary or in-memory database. */
  52494. const int bMmapOk = (pgno>1
  52495. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  52496. );
  52497. assert( USEFETCH(pPager) );
  52498. #ifdef SQLITE_HAS_CODEC
  52499. assert( pPager->xCodec==0 );
  52500. #endif
  52501. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  52502. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  52503. ** test in the previous statement, and avoid testing pgno==0 in the
  52504. ** common case where pgno is large. */
  52505. if( pgno<=1 && pgno==0 ){
  52506. return SQLITE_CORRUPT_BKPT;
  52507. }
  52508. assert( pPager->eState>=PAGER_READER );
  52509. assert( assert_pager_state(pPager) );
  52510. assert( pPager->hasHeldSharedLock==1 );
  52511. assert( pPager->errCode==SQLITE_OK );
  52512. if( bMmapOk && pagerUseWal(pPager) ){
  52513. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  52514. if( rc!=SQLITE_OK ){
  52515. *ppPage = 0;
  52516. return rc;
  52517. }
  52518. }
  52519. if( bMmapOk && iFrame==0 ){
  52520. void *pData = 0;
  52521. rc = sqlite3OsFetch(pPager->fd,
  52522. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  52523. );
  52524. if( rc==SQLITE_OK && pData ){
  52525. if( pPager->eState>PAGER_READER || pPager->tempFile ){
  52526. pPg = sqlite3PagerLookup(pPager, pgno);
  52527. }
  52528. if( pPg==0 ){
  52529. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  52530. }else{
  52531. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  52532. }
  52533. if( pPg ){
  52534. assert( rc==SQLITE_OK );
  52535. *ppPage = pPg;
  52536. return SQLITE_OK;
  52537. }
  52538. }
  52539. if( rc!=SQLITE_OK ){
  52540. *ppPage = 0;
  52541. return rc;
  52542. }
  52543. }
  52544. return getPageNormal(pPager, pgno, ppPage, flags);
  52545. }
  52546. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  52547. /* The page getter method for when the pager is an error state */
  52548. static int getPageError(
  52549. Pager *pPager, /* The pager open on the database file */
  52550. Pgno pgno, /* Page number to fetch */
  52551. DbPage **ppPage, /* Write a pointer to the page here */
  52552. int flags /* PAGER_GET_XXX flags */
  52553. ){
  52554. UNUSED_PARAMETER(pgno);
  52555. UNUSED_PARAMETER(flags);
  52556. assert( pPager->errCode!=SQLITE_OK );
  52557. *ppPage = 0;
  52558. return pPager->errCode;
  52559. }
  52560. /* Dispatch all page fetch requests to the appropriate getter method.
  52561. */
  52562. SQLITE_PRIVATE int sqlite3PagerGet(
  52563. Pager *pPager, /* The pager open on the database file */
  52564. Pgno pgno, /* Page number to fetch */
  52565. DbPage **ppPage, /* Write a pointer to the page here */
  52566. int flags /* PAGER_GET_XXX flags */
  52567. ){
  52568. return pPager->xGet(pPager, pgno, ppPage, flags);
  52569. }
  52570. /*
  52571. ** Acquire a page if it is already in the in-memory cache. Do
  52572. ** not read the page from disk. Return a pointer to the page,
  52573. ** or 0 if the page is not in cache.
  52574. **
  52575. ** See also sqlite3PagerGet(). The difference between this routine
  52576. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  52577. ** in the page if the page is not already in cache. This routine
  52578. ** returns NULL if the page is not in cache or if a disk I/O error
  52579. ** has ever happened.
  52580. */
  52581. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  52582. sqlite3_pcache_page *pPage;
  52583. assert( pPager!=0 );
  52584. assert( pgno!=0 );
  52585. assert( pPager->pPCache!=0 );
  52586. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  52587. assert( pPage==0 || pPager->hasHeldSharedLock );
  52588. if( pPage==0 ) return 0;
  52589. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  52590. }
  52591. /*
  52592. ** Release a page reference.
  52593. **
  52594. ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
  52595. ** used if we know that the page being released is not the last page.
  52596. ** The btree layer always holds page1 open until the end, so these first
  52597. ** to routines can be used to release any page other than BtShared.pPage1.
  52598. **
  52599. ** Use sqlite3PagerUnrefPageOne() to release page1. This latter routine
  52600. ** checks the total number of outstanding pages and if the number of
  52601. ** pages reaches zero it drops the database lock.
  52602. */
  52603. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  52604. TESTONLY( Pager *pPager = pPg->pPager; )
  52605. assert( pPg!=0 );
  52606. if( pPg->flags & PGHDR_MMAP ){
  52607. assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */
  52608. pagerReleaseMapPage(pPg);
  52609. }else{
  52610. sqlite3PcacheRelease(pPg);
  52611. }
  52612. /* Do not use this routine to release the last reference to page1 */
  52613. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  52614. }
  52615. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  52616. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  52617. }
  52618. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
  52619. Pager *pPager;
  52620. assert( pPg!=0 );
  52621. assert( pPg->pgno==1 );
  52622. assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
  52623. pPager = pPg->pPager;
  52624. sqlite3PagerResetLockTimeout(pPager);
  52625. sqlite3PcacheRelease(pPg);
  52626. pagerUnlockIfUnused(pPager);
  52627. }
  52628. /*
  52629. ** This function is called at the start of every write transaction.
  52630. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  52631. ** file when this routine is called.
  52632. **
  52633. ** Open the journal file for pager pPager and write a journal header
  52634. ** to the start of it. If there are active savepoints, open the sub-journal
  52635. ** as well. This function is only used when the journal file is being
  52636. ** opened to write a rollback log for a transaction. It is not used
  52637. ** when opening a hot journal file to roll it back.
  52638. **
  52639. ** If the journal file is already open (as it may be in exclusive mode),
  52640. ** then this function just writes a journal header to the start of the
  52641. ** already open file.
  52642. **
  52643. ** Whether or not the journal file is opened by this function, the
  52644. ** Pager.pInJournal bitvec structure is allocated.
  52645. **
  52646. ** Return SQLITE_OK if everything is successful. Otherwise, return
  52647. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  52648. ** an IO error code if opening or writing the journal file fails.
  52649. */
  52650. static int pager_open_journal(Pager *pPager){
  52651. int rc = SQLITE_OK; /* Return code */
  52652. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  52653. assert( pPager->eState==PAGER_WRITER_LOCKED );
  52654. assert( assert_pager_state(pPager) );
  52655. assert( pPager->pInJournal==0 );
  52656. /* If already in the error state, this function is a no-op. But on
  52657. ** the other hand, this routine is never called if we are already in
  52658. ** an error state. */
  52659. if( NEVER(pPager->errCode) ) return pPager->errCode;
  52660. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  52661. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  52662. if( pPager->pInJournal==0 ){
  52663. return SQLITE_NOMEM_BKPT;
  52664. }
  52665. /* Open the journal file if it is not already open. */
  52666. if( !isOpen(pPager->jfd) ){
  52667. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  52668. sqlite3MemJournalOpen(pPager->jfd);
  52669. }else{
  52670. int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  52671. int nSpill;
  52672. if( pPager->tempFile ){
  52673. flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
  52674. nSpill = sqlite3Config.nStmtSpill;
  52675. }else{
  52676. flags |= SQLITE_OPEN_MAIN_JOURNAL;
  52677. nSpill = jrnlBufferSize(pPager);
  52678. }
  52679. /* Verify that the database still has the same name as it did when
  52680. ** it was originally opened. */
  52681. rc = databaseIsUnmoved(pPager);
  52682. if( rc==SQLITE_OK ){
  52683. rc = sqlite3JournalOpen (
  52684. pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
  52685. );
  52686. }
  52687. }
  52688. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  52689. }
  52690. /* Write the first journal header to the journal file and open
  52691. ** the sub-journal if necessary.
  52692. */
  52693. if( rc==SQLITE_OK ){
  52694. /* TODO: Check if all of these are really required. */
  52695. pPager->nRec = 0;
  52696. pPager->journalOff = 0;
  52697. pPager->setMaster = 0;
  52698. pPager->journalHdr = 0;
  52699. rc = writeJournalHdr(pPager);
  52700. }
  52701. }
  52702. if( rc!=SQLITE_OK ){
  52703. sqlite3BitvecDestroy(pPager->pInJournal);
  52704. pPager->pInJournal = 0;
  52705. }else{
  52706. assert( pPager->eState==PAGER_WRITER_LOCKED );
  52707. pPager->eState = PAGER_WRITER_CACHEMOD;
  52708. }
  52709. return rc;
  52710. }
  52711. /*
  52712. ** Begin a write-transaction on the specified pager object. If a
  52713. ** write-transaction has already been opened, this function is a no-op.
  52714. **
  52715. ** If the exFlag argument is false, then acquire at least a RESERVED
  52716. ** lock on the database file. If exFlag is true, then acquire at least
  52717. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  52718. ** functions need be called.
  52719. **
  52720. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  52721. ** within this transaction will be opened as an in-memory file. This
  52722. ** has no effect if the sub-journal is already opened (as it may be when
  52723. ** running in exclusive mode) or if the transaction does not require a
  52724. ** sub-journal. If the subjInMemory argument is zero, then any required
  52725. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  52726. ** or using a temporary file otherwise.
  52727. */
  52728. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  52729. int rc = SQLITE_OK;
  52730. if( pPager->errCode ) return pPager->errCode;
  52731. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  52732. pPager->subjInMemory = (u8)subjInMemory;
  52733. if( ALWAYS(pPager->eState==PAGER_READER) ){
  52734. assert( pPager->pInJournal==0 );
  52735. if( pagerUseWal(pPager) ){
  52736. /* If the pager is configured to use locking_mode=exclusive, and an
  52737. ** exclusive lock on the database is not already held, obtain it now.
  52738. */
  52739. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  52740. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  52741. if( rc!=SQLITE_OK ){
  52742. return rc;
  52743. }
  52744. (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
  52745. }
  52746. /* Grab the write lock on the log file. If successful, upgrade to
  52747. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  52748. ** The busy-handler is not invoked if another connection already
  52749. ** holds the write-lock. If possible, the upper layer will call it.
  52750. */
  52751. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  52752. }else{
  52753. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  52754. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  52755. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  52756. ** lock, but not when obtaining the RESERVED lock.
  52757. */
  52758. rc = pagerLockDb(pPager, RESERVED_LOCK);
  52759. if( rc==SQLITE_OK && exFlag ){
  52760. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  52761. }
  52762. }
  52763. if( rc==SQLITE_OK ){
  52764. /* Change to WRITER_LOCKED state.
  52765. **
  52766. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  52767. ** when it has an open transaction, but never to DBMOD or FINISHED.
  52768. ** This is because in those states the code to roll back savepoint
  52769. ** transactions may copy data from the sub-journal into the database
  52770. ** file as well as into the page cache. Which would be incorrect in
  52771. ** WAL mode.
  52772. */
  52773. pPager->eState = PAGER_WRITER_LOCKED;
  52774. pPager->dbHintSize = pPager->dbSize;
  52775. pPager->dbFileSize = pPager->dbSize;
  52776. pPager->dbOrigSize = pPager->dbSize;
  52777. pPager->journalOff = 0;
  52778. }
  52779. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  52780. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  52781. assert( assert_pager_state(pPager) );
  52782. }
  52783. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  52784. return rc;
  52785. }
  52786. /*
  52787. ** Write page pPg onto the end of the rollback journal.
  52788. */
  52789. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  52790. Pager *pPager = pPg->pPager;
  52791. int rc;
  52792. u32 cksum;
  52793. char *pData2;
  52794. i64 iOff = pPager->journalOff;
  52795. /* We should never write to the journal file the page that
  52796. ** contains the database locks. The following assert verifies
  52797. ** that we do not. */
  52798. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  52799. assert( pPager->journalHdr<=pPager->journalOff );
  52800. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  52801. cksum = pager_cksum(pPager, (u8*)pData2);
  52802. /* Even if an IO or diskfull error occurs while journalling the
  52803. ** page in the block above, set the need-sync flag for the page.
  52804. ** Otherwise, when the transaction is rolled back, the logic in
  52805. ** playback_one_page() will think that the page needs to be restored
  52806. ** in the database file. And if an IO error occurs while doing so,
  52807. ** then corruption may follow.
  52808. */
  52809. pPg->flags |= PGHDR_NEED_SYNC;
  52810. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  52811. if( rc!=SQLITE_OK ) return rc;
  52812. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  52813. if( rc!=SQLITE_OK ) return rc;
  52814. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  52815. if( rc!=SQLITE_OK ) return rc;
  52816. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  52817. pPager->journalOff, pPager->pageSize));
  52818. PAGER_INCR(sqlite3_pager_writej_count);
  52819. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  52820. PAGERID(pPager), pPg->pgno,
  52821. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  52822. pPager->journalOff += 8 + pPager->pageSize;
  52823. pPager->nRec++;
  52824. assert( pPager->pInJournal!=0 );
  52825. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  52826. testcase( rc==SQLITE_NOMEM );
  52827. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  52828. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  52829. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  52830. return rc;
  52831. }
  52832. /*
  52833. ** Mark a single data page as writeable. The page is written into the
  52834. ** main journal or sub-journal as required. If the page is written into
  52835. ** one of the journals, the corresponding bit is set in the
  52836. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  52837. ** of any open savepoints as appropriate.
  52838. */
  52839. static int pager_write(PgHdr *pPg){
  52840. Pager *pPager = pPg->pPager;
  52841. int rc = SQLITE_OK;
  52842. /* This routine is not called unless a write-transaction has already
  52843. ** been started. The journal file may or may not be open at this point.
  52844. ** It is never called in the ERROR state.
  52845. */
  52846. assert( pPager->eState==PAGER_WRITER_LOCKED
  52847. || pPager->eState==PAGER_WRITER_CACHEMOD
  52848. || pPager->eState==PAGER_WRITER_DBMOD
  52849. );
  52850. assert( assert_pager_state(pPager) );
  52851. assert( pPager->errCode==0 );
  52852. assert( pPager->readOnly==0 );
  52853. CHECK_PAGE(pPg);
  52854. /* The journal file needs to be opened. Higher level routines have already
  52855. ** obtained the necessary locks to begin the write-transaction, but the
  52856. ** rollback journal might not yet be open. Open it now if this is the case.
  52857. **
  52858. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  52859. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  52860. ** an error might occur and the pager would end up in WRITER_LOCKED state
  52861. ** with pages marked as dirty in the cache.
  52862. */
  52863. if( pPager->eState==PAGER_WRITER_LOCKED ){
  52864. rc = pager_open_journal(pPager);
  52865. if( rc!=SQLITE_OK ) return rc;
  52866. }
  52867. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  52868. assert( assert_pager_state(pPager) );
  52869. /* Mark the page that is about to be modified as dirty. */
  52870. sqlite3PcacheMakeDirty(pPg);
  52871. /* If a rollback journal is in use, them make sure the page that is about
  52872. ** to change is in the rollback journal, or if the page is a new page off
  52873. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  52874. */
  52875. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  52876. if( pPager->pInJournal!=0
  52877. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  52878. ){
  52879. assert( pagerUseWal(pPager)==0 );
  52880. if( pPg->pgno<=pPager->dbOrigSize ){
  52881. rc = pagerAddPageToRollbackJournal(pPg);
  52882. if( rc!=SQLITE_OK ){
  52883. return rc;
  52884. }
  52885. }else{
  52886. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  52887. pPg->flags |= PGHDR_NEED_SYNC;
  52888. }
  52889. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  52890. PAGERID(pPager), pPg->pgno,
  52891. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  52892. }
  52893. }
  52894. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  52895. ** and before writing the page into the rollback journal. Wait until now,
  52896. ** after the page has been successfully journalled, before setting the
  52897. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  52898. */
  52899. pPg->flags |= PGHDR_WRITEABLE;
  52900. /* If the statement journal is open and the page is not in it,
  52901. ** then write the page into the statement journal.
  52902. */
  52903. if( pPager->nSavepoint>0 ){
  52904. rc = subjournalPageIfRequired(pPg);
  52905. }
  52906. /* Update the database size and return. */
  52907. if( pPager->dbSize<pPg->pgno ){
  52908. pPager->dbSize = pPg->pgno;
  52909. }
  52910. return rc;
  52911. }
  52912. /*
  52913. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  52914. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  52915. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  52916. ** a sector need to be journalled in case of a power loss in the middle of
  52917. ** a write.
  52918. **
  52919. ** Usually, the sector size is less than or equal to the page size, in which
  52920. ** case pages can be individually written. This routine only runs in the
  52921. ** exceptional case where the page size is smaller than the sector size.
  52922. */
  52923. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  52924. int rc = SQLITE_OK; /* Return code */
  52925. Pgno nPageCount; /* Total number of pages in database file */
  52926. Pgno pg1; /* First page of the sector pPg is located on. */
  52927. int nPage = 0; /* Number of pages starting at pg1 to journal */
  52928. int ii; /* Loop counter */
  52929. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  52930. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  52931. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  52932. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  52933. ** a journal header to be written between the pages journaled by
  52934. ** this function.
  52935. */
  52936. assert( !MEMDB );
  52937. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  52938. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  52939. /* This trick assumes that both the page-size and sector-size are
  52940. ** an integer power of 2. It sets variable pg1 to the identifier
  52941. ** of the first page of the sector pPg is located on.
  52942. */
  52943. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  52944. nPageCount = pPager->dbSize;
  52945. if( pPg->pgno>nPageCount ){
  52946. nPage = (pPg->pgno - pg1)+1;
  52947. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  52948. nPage = nPageCount+1-pg1;
  52949. }else{
  52950. nPage = nPagePerSector;
  52951. }
  52952. assert(nPage>0);
  52953. assert(pg1<=pPg->pgno);
  52954. assert((pg1+nPage)>pPg->pgno);
  52955. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  52956. Pgno pg = pg1+ii;
  52957. PgHdr *pPage;
  52958. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  52959. if( pg!=PAGER_MJ_PGNO(pPager) ){
  52960. rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
  52961. if( rc==SQLITE_OK ){
  52962. rc = pager_write(pPage);
  52963. if( pPage->flags&PGHDR_NEED_SYNC ){
  52964. needSync = 1;
  52965. }
  52966. sqlite3PagerUnrefNotNull(pPage);
  52967. }
  52968. }
  52969. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  52970. if( pPage->flags&PGHDR_NEED_SYNC ){
  52971. needSync = 1;
  52972. }
  52973. sqlite3PagerUnrefNotNull(pPage);
  52974. }
  52975. }
  52976. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  52977. ** starting at pg1, then it needs to be set for all of them. Because
  52978. ** writing to any of these nPage pages may damage the others, the
  52979. ** journal file must contain sync()ed copies of all of them
  52980. ** before any of them can be written out to the database file.
  52981. */
  52982. if( rc==SQLITE_OK && needSync ){
  52983. assert( !MEMDB );
  52984. for(ii=0; ii<nPage; ii++){
  52985. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  52986. if( pPage ){
  52987. pPage->flags |= PGHDR_NEED_SYNC;
  52988. sqlite3PagerUnrefNotNull(pPage);
  52989. }
  52990. }
  52991. }
  52992. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  52993. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  52994. return rc;
  52995. }
  52996. /*
  52997. ** Mark a data page as writeable. This routine must be called before
  52998. ** making changes to a page. The caller must check the return value
  52999. ** of this function and be careful not to change any page data unless
  53000. ** this routine returns SQLITE_OK.
  53001. **
  53002. ** The difference between this function and pager_write() is that this
  53003. ** function also deals with the special case where 2 or more pages
  53004. ** fit on a single disk sector. In this case all co-resident pages
  53005. ** must have been written to the journal file before returning.
  53006. **
  53007. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  53008. ** as appropriate. Otherwise, SQLITE_OK.
  53009. */
  53010. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  53011. Pager *pPager = pPg->pPager;
  53012. assert( (pPg->flags & PGHDR_MMAP)==0 );
  53013. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  53014. assert( assert_pager_state(pPager) );
  53015. if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  53016. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  53017. return SQLITE_OK;
  53018. }else if( pPager->errCode ){
  53019. return pPager->errCode;
  53020. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  53021. assert( pPager->tempFile==0 );
  53022. return pagerWriteLargeSector(pPg);
  53023. }else{
  53024. return pager_write(pPg);
  53025. }
  53026. }
  53027. /*
  53028. ** Return TRUE if the page given in the argument was previously passed
  53029. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  53030. ** to change the content of the page.
  53031. */
  53032. #ifndef NDEBUG
  53033. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  53034. return pPg->flags & PGHDR_WRITEABLE;
  53035. }
  53036. #endif
  53037. /*
  53038. ** A call to this routine tells the pager that it is not necessary to
  53039. ** write the information on page pPg back to the disk, even though
  53040. ** that page might be marked as dirty. This happens, for example, when
  53041. ** the page has been added as a leaf of the freelist and so its
  53042. ** content no longer matters.
  53043. **
  53044. ** The overlying software layer calls this routine when all of the data
  53045. ** on the given page is unused. The pager marks the page as clean so
  53046. ** that it does not get written to disk.
  53047. **
  53048. ** Tests show that this optimization can quadruple the speed of large
  53049. ** DELETE operations.
  53050. **
  53051. ** This optimization cannot be used with a temp-file, as the page may
  53052. ** have been dirty at the start of the transaction. In that case, if
  53053. ** memory pressure forces page pPg out of the cache, the data does need
  53054. ** to be written out to disk so that it may be read back in if the
  53055. ** current transaction is rolled back.
  53056. */
  53057. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  53058. Pager *pPager = pPg->pPager;
  53059. if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  53060. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  53061. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  53062. pPg->flags |= PGHDR_DONT_WRITE;
  53063. pPg->flags &= ~PGHDR_WRITEABLE;
  53064. testcase( pPg->flags & PGHDR_NEED_SYNC );
  53065. pager_set_pagehash(pPg);
  53066. }
  53067. }
  53068. /*
  53069. ** This routine is called to increment the value of the database file
  53070. ** change-counter, stored as a 4-byte big-endian integer starting at
  53071. ** byte offset 24 of the pager file. The secondary change counter at
  53072. ** 92 is also updated, as is the SQLite version number at offset 96.
  53073. **
  53074. ** But this only happens if the pPager->changeCountDone flag is false.
  53075. ** To avoid excess churning of page 1, the update only happens once.
  53076. ** See also the pager_write_changecounter() routine that does an
  53077. ** unconditional update of the change counters.
  53078. **
  53079. ** If the isDirectMode flag is zero, then this is done by calling
  53080. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  53081. ** page data. In this case the file will be updated when the current
  53082. ** transaction is committed.
  53083. **
  53084. ** The isDirectMode flag may only be non-zero if the library was compiled
  53085. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  53086. ** if isDirect is non-zero, then the database file is updated directly
  53087. ** by writing an updated version of page 1 using a call to the
  53088. ** sqlite3OsWrite() function.
  53089. */
  53090. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  53091. int rc = SQLITE_OK;
  53092. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  53093. || pPager->eState==PAGER_WRITER_DBMOD
  53094. );
  53095. assert( assert_pager_state(pPager) );
  53096. /* Declare and initialize constant integer 'isDirect'. If the
  53097. ** atomic-write optimization is enabled in this build, then isDirect
  53098. ** is initialized to the value passed as the isDirectMode parameter
  53099. ** to this function. Otherwise, it is always set to zero.
  53100. **
  53101. ** The idea is that if the atomic-write optimization is not
  53102. ** enabled at compile time, the compiler can omit the tests of
  53103. ** 'isDirect' below, as well as the block enclosed in the
  53104. ** "if( isDirect )" condition.
  53105. */
  53106. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  53107. # define DIRECT_MODE 0
  53108. assert( isDirectMode==0 );
  53109. UNUSED_PARAMETER(isDirectMode);
  53110. #else
  53111. # define DIRECT_MODE isDirectMode
  53112. #endif
  53113. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  53114. PgHdr *pPgHdr; /* Reference to page 1 */
  53115. assert( !pPager->tempFile && isOpen(pPager->fd) );
  53116. /* Open page 1 of the file for writing. */
  53117. rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
  53118. assert( pPgHdr==0 || rc==SQLITE_OK );
  53119. /* If page one was fetched successfully, and this function is not
  53120. ** operating in direct-mode, make page 1 writable. When not in
  53121. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  53122. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  53123. */
  53124. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  53125. rc = sqlite3PagerWrite(pPgHdr);
  53126. }
  53127. if( rc==SQLITE_OK ){
  53128. /* Actually do the update of the change counter */
  53129. pager_write_changecounter(pPgHdr);
  53130. /* If running in direct mode, write the contents of page 1 to the file. */
  53131. if( DIRECT_MODE ){
  53132. const void *zBuf;
  53133. assert( pPager->dbFileSize>0 );
  53134. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
  53135. if( rc==SQLITE_OK ){
  53136. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  53137. pPager->aStat[PAGER_STAT_WRITE]++;
  53138. }
  53139. if( rc==SQLITE_OK ){
  53140. /* Update the pager's copy of the change-counter. Otherwise, the
  53141. ** next time a read transaction is opened the cache will be
  53142. ** flushed (as the change-counter values will not match). */
  53143. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  53144. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  53145. pPager->changeCountDone = 1;
  53146. }
  53147. }else{
  53148. pPager->changeCountDone = 1;
  53149. }
  53150. }
  53151. /* Release the page reference. */
  53152. sqlite3PagerUnref(pPgHdr);
  53153. }
  53154. return rc;
  53155. }
  53156. /*
  53157. ** Sync the database file to disk. This is a no-op for in-memory databases
  53158. ** or pages with the Pager.noSync flag set.
  53159. **
  53160. ** If successful, or if called on a pager for which it is a no-op, this
  53161. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  53162. */
  53163. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  53164. int rc = SQLITE_OK;
  53165. void *pArg = (void*)zMaster;
  53166. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  53167. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  53168. if( rc==SQLITE_OK && !pPager->noSync ){
  53169. assert( !MEMDB );
  53170. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  53171. }
  53172. return rc;
  53173. }
  53174. /*
  53175. ** This function may only be called while a write-transaction is active in
  53176. ** rollback. If the connection is in WAL mode, this call is a no-op.
  53177. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  53178. ** the database file, an attempt is made to obtain one.
  53179. **
  53180. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  53181. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  53182. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  53183. ** returned.
  53184. */
  53185. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  53186. int rc = pPager->errCode;
  53187. assert( assert_pager_state(pPager) );
  53188. if( rc==SQLITE_OK ){
  53189. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  53190. || pPager->eState==PAGER_WRITER_DBMOD
  53191. || pPager->eState==PAGER_WRITER_LOCKED
  53192. );
  53193. assert( assert_pager_state(pPager) );
  53194. if( 0==pagerUseWal(pPager) ){
  53195. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  53196. }
  53197. }
  53198. return rc;
  53199. }
  53200. /*
  53201. ** Sync the database file for the pager pPager. zMaster points to the name
  53202. ** of a master journal file that should be written into the individual
  53203. ** journal file. zMaster may be NULL, which is interpreted as no master
  53204. ** journal (a single database transaction).
  53205. **
  53206. ** This routine ensures that:
  53207. **
  53208. ** * The database file change-counter is updated,
  53209. ** * the journal is synced (unless the atomic-write optimization is used),
  53210. ** * all dirty pages are written to the database file,
  53211. ** * the database file is truncated (if required), and
  53212. ** * the database file synced.
  53213. **
  53214. ** The only thing that remains to commit the transaction is to finalize
  53215. ** (delete, truncate or zero the first part of) the journal file (or
  53216. ** delete the master journal file if specified).
  53217. **
  53218. ** Note that if zMaster==NULL, this does not overwrite a previous value
  53219. ** passed to an sqlite3PagerCommitPhaseOne() call.
  53220. **
  53221. ** If the final parameter - noSync - is true, then the database file itself
  53222. ** is not synced. The caller must call sqlite3PagerSync() directly to
  53223. ** sync the database file before calling CommitPhaseTwo() to delete the
  53224. ** journal file in this case.
  53225. */
  53226. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  53227. Pager *pPager, /* Pager object */
  53228. const char *zMaster, /* If not NULL, the master journal name */
  53229. int noSync /* True to omit the xSync on the db file */
  53230. ){
  53231. int rc = SQLITE_OK; /* Return code */
  53232. assert( pPager->eState==PAGER_WRITER_LOCKED
  53233. || pPager->eState==PAGER_WRITER_CACHEMOD
  53234. || pPager->eState==PAGER_WRITER_DBMOD
  53235. || pPager->eState==PAGER_ERROR
  53236. );
  53237. assert( assert_pager_state(pPager) );
  53238. /* If a prior error occurred, report that error again. */
  53239. if( NEVER(pPager->errCode) ) return pPager->errCode;
  53240. /* Provide the ability to easily simulate an I/O error during testing */
  53241. if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
  53242. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  53243. pPager->zFilename, zMaster, pPager->dbSize));
  53244. /* If no database changes have been made, return early. */
  53245. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  53246. assert( MEMDB==0 || pPager->tempFile );
  53247. assert( isOpen(pPager->fd) || pPager->tempFile );
  53248. if( 0==pagerFlushOnCommit(pPager, 1) ){
  53249. /* If this is an in-memory db, or no pages have been written to, or this
  53250. ** function has already been called, it is mostly a no-op. However, any
  53251. ** backup in progress needs to be restarted. */
  53252. sqlite3BackupRestart(pPager->pBackup);
  53253. }else{
  53254. PgHdr *pList;
  53255. if( pagerUseWal(pPager) ){
  53256. PgHdr *pPageOne = 0;
  53257. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  53258. if( pList==0 ){
  53259. /* Must have at least one page for the WAL commit flag.
  53260. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  53261. rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
  53262. pList = pPageOne;
  53263. pList->pDirty = 0;
  53264. }
  53265. assert( rc==SQLITE_OK );
  53266. if( ALWAYS(pList) ){
  53267. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  53268. }
  53269. sqlite3PagerUnref(pPageOne);
  53270. if( rc==SQLITE_OK ){
  53271. sqlite3PcacheCleanAll(pPager->pPCache);
  53272. }
  53273. }else{
  53274. /* The bBatch boolean is true if the batch-atomic-write commit method
  53275. ** should be used. No rollback journal is created if batch-atomic-write
  53276. ** is enabled.
  53277. */
  53278. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  53279. sqlite3_file *fd = pPager->fd;
  53280. int bBatch = zMaster==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
  53281. && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
  53282. && !pPager->noSync
  53283. && sqlite3JournalIsInMemory(pPager->jfd);
  53284. #else
  53285. # define bBatch 0
  53286. #endif
  53287. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  53288. /* The following block updates the change-counter. Exactly how it
  53289. ** does this depends on whether or not the atomic-update optimization
  53290. ** was enabled at compile time, and if this transaction meets the
  53291. ** runtime criteria to use the operation:
  53292. **
  53293. ** * The file-system supports the atomic-write property for
  53294. ** blocks of size page-size, and
  53295. ** * This commit is not part of a multi-file transaction, and
  53296. ** * Exactly one page has been modified and store in the journal file.
  53297. **
  53298. ** If the optimization was not enabled at compile time, then the
  53299. ** pager_incr_changecounter() function is called to update the change
  53300. ** counter in 'indirect-mode'. If the optimization is compiled in but
  53301. ** is not applicable to this transaction, call sqlite3JournalCreate()
  53302. ** to make sure the journal file has actually been created, then call
  53303. ** pager_incr_changecounter() to update the change-counter in indirect
  53304. ** mode.
  53305. **
  53306. ** Otherwise, if the optimization is both enabled and applicable,
  53307. ** then call pager_incr_changecounter() to update the change-counter
  53308. ** in 'direct' mode. In this case the journal file will never be
  53309. ** created for this transaction.
  53310. */
  53311. if( bBatch==0 ){
  53312. PgHdr *pPg;
  53313. assert( isOpen(pPager->jfd)
  53314. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  53315. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  53316. );
  53317. if( !zMaster && isOpen(pPager->jfd)
  53318. && pPager->journalOff==jrnlBufferSize(pPager)
  53319. && pPager->dbSize>=pPager->dbOrigSize
  53320. && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  53321. ){
  53322. /* Update the db file change counter via the direct-write method. The
  53323. ** following call will modify the in-memory representation of page 1
  53324. ** to include the updated change counter and then write page 1
  53325. ** directly to the database file. Because of the atomic-write
  53326. ** property of the host file-system, this is safe.
  53327. */
  53328. rc = pager_incr_changecounter(pPager, 1);
  53329. }else{
  53330. rc = sqlite3JournalCreate(pPager->jfd);
  53331. if( rc==SQLITE_OK ){
  53332. rc = pager_incr_changecounter(pPager, 0);
  53333. }
  53334. }
  53335. }
  53336. #else /* SQLITE_ENABLE_ATOMIC_WRITE */
  53337. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  53338. if( zMaster ){
  53339. rc = sqlite3JournalCreate(pPager->jfd);
  53340. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53341. assert( bBatch==0 );
  53342. }
  53343. #endif
  53344. rc = pager_incr_changecounter(pPager, 0);
  53345. #endif /* !SQLITE_ENABLE_ATOMIC_WRITE */
  53346. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53347. /* Write the master journal name into the journal file. If a master
  53348. ** journal file name has already been written to the journal file,
  53349. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  53350. */
  53351. rc = writeMasterJournal(pPager, zMaster);
  53352. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53353. /* Sync the journal file and write all dirty pages to the database.
  53354. ** If the atomic-update optimization is being used, this sync will not
  53355. ** create the journal file or perform any real IO.
  53356. **
  53357. ** Because the change-counter page was just modified, unless the
  53358. ** atomic-update optimization is used it is almost certain that the
  53359. ** journal requires a sync here. However, in locking_mode=exclusive
  53360. ** on a system under memory pressure it is just possible that this is
  53361. ** not the case. In this case it is likely enough that the redundant
  53362. ** xSync() call will be changed to a no-op by the OS anyhow.
  53363. */
  53364. rc = syncJournal(pPager, 0);
  53365. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53366. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  53367. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  53368. if( bBatch ){
  53369. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
  53370. if( rc==SQLITE_OK ){
  53371. rc = pager_write_pagelist(pPager, pList);
  53372. if( rc==SQLITE_OK ){
  53373. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
  53374. }
  53375. if( rc!=SQLITE_OK ){
  53376. sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
  53377. }
  53378. }
  53379. if( (rc&0xFF)==SQLITE_IOERR && rc!=SQLITE_IOERR_NOMEM ){
  53380. rc = sqlite3JournalCreate(pPager->jfd);
  53381. if( rc!=SQLITE_OK ){
  53382. sqlite3OsClose(pPager->jfd);
  53383. goto commit_phase_one_exit;
  53384. }
  53385. bBatch = 0;
  53386. }else{
  53387. sqlite3OsClose(pPager->jfd);
  53388. }
  53389. }
  53390. #endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  53391. if( bBatch==0 ){
  53392. rc = pager_write_pagelist(pPager, pList);
  53393. }
  53394. if( rc!=SQLITE_OK ){
  53395. assert( rc!=SQLITE_IOERR_BLOCKED );
  53396. goto commit_phase_one_exit;
  53397. }
  53398. sqlite3PcacheCleanAll(pPager->pPCache);
  53399. /* If the file on disk is smaller than the database image, use
  53400. ** pager_truncate to grow the file here. This can happen if the database
  53401. ** image was extended as part of the current transaction and then the
  53402. ** last page in the db image moved to the free-list. In this case the
  53403. ** last page is never written out to disk, leaving the database file
  53404. ** undersized. Fix this now if it is the case. */
  53405. if( pPager->dbSize>pPager->dbFileSize ){
  53406. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  53407. assert( pPager->eState==PAGER_WRITER_DBMOD );
  53408. rc = pager_truncate(pPager, nNew);
  53409. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53410. }
  53411. /* Finally, sync the database file. */
  53412. if( !noSync ){
  53413. rc = sqlite3PagerSync(pPager, zMaster);
  53414. }
  53415. IOTRACE(("DBSYNC %p\n", pPager))
  53416. }
  53417. }
  53418. commit_phase_one_exit:
  53419. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  53420. pPager->eState = PAGER_WRITER_FINISHED;
  53421. }
  53422. return rc;
  53423. }
  53424. /*
  53425. ** When this function is called, the database file has been completely
  53426. ** updated to reflect the changes made by the current transaction and
  53427. ** synced to disk. The journal file still exists in the file-system
  53428. ** though, and if a failure occurs at this point it will eventually
  53429. ** be used as a hot-journal and the current transaction rolled back.
  53430. **
  53431. ** This function finalizes the journal file, either by deleting,
  53432. ** truncating or partially zeroing it, so that it cannot be used
  53433. ** for hot-journal rollback. Once this is done the transaction is
  53434. ** irrevocably committed.
  53435. **
  53436. ** If an error occurs, an IO error code is returned and the pager
  53437. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  53438. */
  53439. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  53440. int rc = SQLITE_OK; /* Return code */
  53441. /* This routine should not be called if a prior error has occurred.
  53442. ** But if (due to a coding error elsewhere in the system) it does get
  53443. ** called, just return the same error code without doing anything. */
  53444. if( NEVER(pPager->errCode) ) return pPager->errCode;
  53445. assert( pPager->eState==PAGER_WRITER_LOCKED
  53446. || pPager->eState==PAGER_WRITER_FINISHED
  53447. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  53448. );
  53449. assert( assert_pager_state(pPager) );
  53450. /* An optimization. If the database was not actually modified during
  53451. ** this transaction, the pager is running in exclusive-mode and is
  53452. ** using persistent journals, then this function is a no-op.
  53453. **
  53454. ** The start of the journal file currently contains a single journal
  53455. ** header with the nRec field set to 0. If such a journal is used as
  53456. ** a hot-journal during hot-journal rollback, 0 changes will be made
  53457. ** to the database file. So there is no need to zero the journal
  53458. ** header. Since the pager is in exclusive mode, there is no need
  53459. ** to drop any locks either.
  53460. */
  53461. if( pPager->eState==PAGER_WRITER_LOCKED
  53462. && pPager->exclusiveMode
  53463. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  53464. ){
  53465. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  53466. pPager->eState = PAGER_READER;
  53467. return SQLITE_OK;
  53468. }
  53469. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  53470. pPager->iDataVersion++;
  53471. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  53472. return pager_error(pPager, rc);
  53473. }
  53474. /*
  53475. ** If a write transaction is open, then all changes made within the
  53476. ** transaction are reverted and the current write-transaction is closed.
  53477. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  53478. ** state if an error occurs.
  53479. **
  53480. ** If the pager is already in PAGER_ERROR state when this function is called,
  53481. ** it returns Pager.errCode immediately. No work is performed in this case.
  53482. **
  53483. ** Otherwise, in rollback mode, this function performs two functions:
  53484. **
  53485. ** 1) It rolls back the journal file, restoring all database file and
  53486. ** in-memory cache pages to the state they were in when the transaction
  53487. ** was opened, and
  53488. **
  53489. ** 2) It finalizes the journal file, so that it is not used for hot
  53490. ** rollback at any point in the future.
  53491. **
  53492. ** Finalization of the journal file (task 2) is only performed if the
  53493. ** rollback is successful.
  53494. **
  53495. ** In WAL mode, all cache-entries containing data modified within the
  53496. ** current transaction are either expelled from the cache or reverted to
  53497. ** their pre-transaction state by re-reading data from the database or
  53498. ** WAL files. The WAL transaction is then closed.
  53499. */
  53500. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  53501. int rc = SQLITE_OK; /* Return code */
  53502. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  53503. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  53504. ** the pager is already in the ERROR state, the rollback is not
  53505. ** attempted here. Instead, the error code is returned to the caller.
  53506. */
  53507. assert( assert_pager_state(pPager) );
  53508. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  53509. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  53510. if( pagerUseWal(pPager) ){
  53511. int rc2;
  53512. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  53513. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  53514. if( rc==SQLITE_OK ) rc = rc2;
  53515. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  53516. int eState = pPager->eState;
  53517. rc = pager_end_transaction(pPager, 0, 0);
  53518. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  53519. /* This can happen using journal_mode=off. Move the pager to the error
  53520. ** state to indicate that the contents of the cache may not be trusted.
  53521. ** Any active readers will get SQLITE_ABORT.
  53522. */
  53523. pPager->errCode = SQLITE_ABORT;
  53524. pPager->eState = PAGER_ERROR;
  53525. setGetterMethod(pPager);
  53526. return rc;
  53527. }
  53528. }else{
  53529. rc = pager_playback(pPager, 0);
  53530. }
  53531. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  53532. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  53533. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  53534. || rc==SQLITE_CANTOPEN
  53535. );
  53536. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  53537. ** cache. So call pager_error() on the way out to make any error persistent.
  53538. */
  53539. return pager_error(pPager, rc);
  53540. }
  53541. /*
  53542. ** Return TRUE if the database file is opened read-only. Return FALSE
  53543. ** if the database is (in theory) writable.
  53544. */
  53545. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  53546. return pPager->readOnly;
  53547. }
  53548. #ifdef SQLITE_DEBUG
  53549. /*
  53550. ** Return the sum of the reference counts for all pages held by pPager.
  53551. */
  53552. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  53553. return sqlite3PcacheRefCount(pPager->pPCache);
  53554. }
  53555. #endif
  53556. /*
  53557. ** Return the approximate number of bytes of memory currently
  53558. ** used by the pager and its associated cache.
  53559. */
  53560. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  53561. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  53562. + 5*sizeof(void*);
  53563. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  53564. + sqlite3MallocSize(pPager)
  53565. + pPager->pageSize;
  53566. }
  53567. /*
  53568. ** Return the number of references to the specified page.
  53569. */
  53570. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  53571. return sqlite3PcachePageRefcount(pPage);
  53572. }
  53573. #ifdef SQLITE_TEST
  53574. /*
  53575. ** This routine is used for testing and analysis only.
  53576. */
  53577. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  53578. static int a[11];
  53579. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  53580. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  53581. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  53582. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  53583. a[4] = pPager->eState;
  53584. a[5] = pPager->errCode;
  53585. a[6] = pPager->aStat[PAGER_STAT_HIT];
  53586. a[7] = pPager->aStat[PAGER_STAT_MISS];
  53587. a[8] = 0; /* Used to be pPager->nOvfl */
  53588. a[9] = pPager->nRead;
  53589. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  53590. return a;
  53591. }
  53592. #endif
  53593. /*
  53594. ** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE,
  53595. ** or _WRITE+1. The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation
  53596. ** of SQLITE_DBSTATUS_CACHE_SPILL. The _SPILL case is not contiguous because
  53597. ** it was added later.
  53598. **
  53599. ** Before returning, *pnVal is incremented by the
  53600. ** current cache hit or miss count, according to the value of eStat. If the
  53601. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  53602. ** returning.
  53603. */
  53604. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  53605. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  53606. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  53607. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  53608. || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1
  53609. );
  53610. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  53611. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  53612. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1
  53613. && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 );
  53614. eStat -= SQLITE_DBSTATUS_CACHE_HIT;
  53615. *pnVal += pPager->aStat[eStat];
  53616. if( reset ){
  53617. pPager->aStat[eStat] = 0;
  53618. }
  53619. }
  53620. /*
  53621. ** Return true if this is an in-memory or temp-file backed pager.
  53622. */
  53623. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  53624. return pPager->tempFile;
  53625. }
  53626. /*
  53627. ** Check that there are at least nSavepoint savepoints open. If there are
  53628. ** currently less than nSavepoints open, then open one or more savepoints
  53629. ** to make up the difference. If the number of savepoints is already
  53630. ** equal to nSavepoint, then this function is a no-op.
  53631. **
  53632. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  53633. ** occurs while opening the sub-journal file, then an IO error code is
  53634. ** returned. Otherwise, SQLITE_OK.
  53635. */
  53636. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  53637. int rc = SQLITE_OK; /* Return code */
  53638. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  53639. int ii; /* Iterator variable */
  53640. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  53641. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  53642. assert( assert_pager_state(pPager) );
  53643. assert( nSavepoint>nCurrent && pPager->useJournal );
  53644. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  53645. ** if the allocation fails. Otherwise, zero the new portion in case a
  53646. ** malloc failure occurs while populating it in the for(...) loop below.
  53647. */
  53648. aNew = (PagerSavepoint *)sqlite3Realloc(
  53649. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  53650. );
  53651. if( !aNew ){
  53652. return SQLITE_NOMEM_BKPT;
  53653. }
  53654. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  53655. pPager->aSavepoint = aNew;
  53656. /* Populate the PagerSavepoint structures just allocated. */
  53657. for(ii=nCurrent; ii<nSavepoint; ii++){
  53658. aNew[ii].nOrig = pPager->dbSize;
  53659. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  53660. aNew[ii].iOffset = pPager->journalOff;
  53661. }else{
  53662. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  53663. }
  53664. aNew[ii].iSubRec = pPager->nSubRec;
  53665. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  53666. if( !aNew[ii].pInSavepoint ){
  53667. return SQLITE_NOMEM_BKPT;
  53668. }
  53669. if( pagerUseWal(pPager) ){
  53670. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  53671. }
  53672. pPager->nSavepoint = ii+1;
  53673. }
  53674. assert( pPager->nSavepoint==nSavepoint );
  53675. assertTruncateConstraint(pPager);
  53676. return rc;
  53677. }
  53678. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  53679. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  53680. assert( assert_pager_state(pPager) );
  53681. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  53682. return pagerOpenSavepoint(pPager, nSavepoint);
  53683. }else{
  53684. return SQLITE_OK;
  53685. }
  53686. }
  53687. /*
  53688. ** This function is called to rollback or release (commit) a savepoint.
  53689. ** The savepoint to release or rollback need not be the most recently
  53690. ** created savepoint.
  53691. **
  53692. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  53693. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  53694. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  53695. ** that have occurred since the specified savepoint was created.
  53696. **
  53697. ** The savepoint to rollback or release is identified by parameter
  53698. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  53699. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  53700. ** on the most recently created savepoint. If iSavepoint is greater than
  53701. ** (Pager.nSavepoint-1), then this function is a no-op.
  53702. **
  53703. ** If a negative value is passed to this function, then the current
  53704. ** transaction is rolled back. This is different to calling
  53705. ** sqlite3PagerRollback() because this function does not terminate
  53706. ** the transaction or unlock the database, it just restores the
  53707. ** contents of the database to its original state.
  53708. **
  53709. ** In any case, all savepoints with an index greater than iSavepoint
  53710. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  53711. ** then savepoint iSavepoint is also destroyed.
  53712. **
  53713. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  53714. ** or an IO error code if an IO error occurs while rolling back a
  53715. ** savepoint. If no errors occur, SQLITE_OK is returned.
  53716. */
  53717. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  53718. int rc = pPager->errCode;
  53719. #ifdef SQLITE_ENABLE_ZIPVFS
  53720. if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
  53721. #endif
  53722. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  53723. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  53724. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  53725. int ii; /* Iterator variable */
  53726. int nNew; /* Number of remaining savepoints after this op. */
  53727. /* Figure out how many savepoints will still be active after this
  53728. ** operation. Store this value in nNew. Then free resources associated
  53729. ** with any savepoints that are destroyed by this operation.
  53730. */
  53731. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  53732. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  53733. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  53734. }
  53735. pPager->nSavepoint = nNew;
  53736. /* If this is a release of the outermost savepoint, truncate
  53737. ** the sub-journal to zero bytes in size. */
  53738. if( op==SAVEPOINT_RELEASE ){
  53739. if( nNew==0 && isOpen(pPager->sjfd) ){
  53740. /* Only truncate if it is an in-memory sub-journal. */
  53741. if( sqlite3JournalIsInMemory(pPager->sjfd) ){
  53742. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  53743. assert( rc==SQLITE_OK );
  53744. }
  53745. pPager->nSubRec = 0;
  53746. }
  53747. }
  53748. /* Else this is a rollback operation, playback the specified savepoint.
  53749. ** If this is a temp-file, it is possible that the journal file has
  53750. ** not yet been opened. In this case there have been no changes to
  53751. ** the database file, so the playback operation can be skipped.
  53752. */
  53753. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  53754. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  53755. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  53756. assert(rc!=SQLITE_DONE);
  53757. }
  53758. #ifdef SQLITE_ENABLE_ZIPVFS
  53759. /* If the cache has been modified but the savepoint cannot be rolled
  53760. ** back journal_mode=off, put the pager in the error state. This way,
  53761. ** if the VFS used by this pager includes ZipVFS, the entire transaction
  53762. ** can be rolled back at the ZipVFS level. */
  53763. else if(
  53764. pPager->journalMode==PAGER_JOURNALMODE_OFF
  53765. && pPager->eState>=PAGER_WRITER_CACHEMOD
  53766. ){
  53767. pPager->errCode = SQLITE_ABORT;
  53768. pPager->eState = PAGER_ERROR;
  53769. setGetterMethod(pPager);
  53770. }
  53771. #endif
  53772. }
  53773. return rc;
  53774. }
  53775. /*
  53776. ** Return the full pathname of the database file.
  53777. **
  53778. ** Except, if the pager is in-memory only, then return an empty string if
  53779. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  53780. ** used to report the filename to the user, for compatibility with legacy
  53781. ** behavior. But when the Btree needs to know the filename for matching to
  53782. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  53783. ** participate in shared-cache.
  53784. */
  53785. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  53786. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  53787. }
  53788. /*
  53789. ** Return the VFS structure for the pager.
  53790. */
  53791. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  53792. return pPager->pVfs;
  53793. }
  53794. /*
  53795. ** Return the file handle for the database file associated
  53796. ** with the pager. This might return NULL if the file has
  53797. ** not yet been opened.
  53798. */
  53799. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  53800. return pPager->fd;
  53801. }
  53802. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  53803. /*
  53804. ** Reset the lock timeout for pager.
  53805. */
  53806. SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager){
  53807. int x = 0;
  53808. sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_LOCK_TIMEOUT, &x);
  53809. }
  53810. #endif
  53811. /*
  53812. ** Return the file handle for the journal file (if it exists).
  53813. ** This will be either the rollback journal or the WAL file.
  53814. */
  53815. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
  53816. #if SQLITE_OMIT_WAL
  53817. return pPager->jfd;
  53818. #else
  53819. return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
  53820. #endif
  53821. }
  53822. /*
  53823. ** Return the full pathname of the journal file.
  53824. */
  53825. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  53826. return pPager->zJournal;
  53827. }
  53828. #ifdef SQLITE_HAS_CODEC
  53829. /*
  53830. ** Set or retrieve the codec for this pager
  53831. */
  53832. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  53833. Pager *pPager,
  53834. void *(*xCodec)(void*,void*,Pgno,int),
  53835. void (*xCodecSizeChng)(void*,int,int),
  53836. void (*xCodecFree)(void*),
  53837. void *pCodec
  53838. ){
  53839. if( pPager->xCodecFree ){
  53840. pPager->xCodecFree(pPager->pCodec);
  53841. }else{
  53842. pager_reset(pPager);
  53843. }
  53844. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  53845. pPager->xCodecSizeChng = xCodecSizeChng;
  53846. pPager->xCodecFree = xCodecFree;
  53847. pPager->pCodec = pCodec;
  53848. setGetterMethod(pPager);
  53849. pagerReportSize(pPager);
  53850. }
  53851. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  53852. return pPager->pCodec;
  53853. }
  53854. /*
  53855. ** This function is called by the wal module when writing page content
  53856. ** into the log file.
  53857. **
  53858. ** This function returns a pointer to a buffer containing the encrypted
  53859. ** page content. If a malloc fails, this function may return NULL.
  53860. */
  53861. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  53862. void *aData = 0;
  53863. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  53864. return aData;
  53865. }
  53866. /*
  53867. ** Return the current pager state
  53868. */
  53869. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  53870. return pPager->eState;
  53871. }
  53872. #endif /* SQLITE_HAS_CODEC */
  53873. #ifndef SQLITE_OMIT_AUTOVACUUM
  53874. /*
  53875. ** Move the page pPg to location pgno in the file.
  53876. **
  53877. ** There must be no references to the page previously located at
  53878. ** pgno (which we call pPgOld) though that page is allowed to be
  53879. ** in cache. If the page previously located at pgno is not already
  53880. ** in the rollback journal, it is not put there by by this routine.
  53881. **
  53882. ** References to the page pPg remain valid. Updating any
  53883. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  53884. ** allocated along with the page) is the responsibility of the caller.
  53885. **
  53886. ** A transaction must be active when this routine is called. It used to be
  53887. ** required that a statement transaction was not active, but this restriction
  53888. ** has been removed (CREATE INDEX needs to move a page when a statement
  53889. ** transaction is active).
  53890. **
  53891. ** If the fourth argument, isCommit, is non-zero, then this page is being
  53892. ** moved as part of a database reorganization just before the transaction
  53893. ** is being committed. In this case, it is guaranteed that the database page
  53894. ** pPg refers to will not be written to again within this transaction.
  53895. **
  53896. ** This function may return SQLITE_NOMEM or an IO error code if an error
  53897. ** occurs. Otherwise, it returns SQLITE_OK.
  53898. */
  53899. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  53900. PgHdr *pPgOld; /* The page being overwritten. */
  53901. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  53902. int rc; /* Return code */
  53903. Pgno origPgno; /* The original page number */
  53904. assert( pPg->nRef>0 );
  53905. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  53906. || pPager->eState==PAGER_WRITER_DBMOD
  53907. );
  53908. assert( assert_pager_state(pPager) );
  53909. /* In order to be able to rollback, an in-memory database must journal
  53910. ** the page we are moving from.
  53911. */
  53912. assert( pPager->tempFile || !MEMDB );
  53913. if( pPager->tempFile ){
  53914. rc = sqlite3PagerWrite(pPg);
  53915. if( rc ) return rc;
  53916. }
  53917. /* If the page being moved is dirty and has not been saved by the latest
  53918. ** savepoint, then save the current contents of the page into the
  53919. ** sub-journal now. This is required to handle the following scenario:
  53920. **
  53921. ** BEGIN;
  53922. ** <journal page X, then modify it in memory>
  53923. ** SAVEPOINT one;
  53924. ** <Move page X to location Y>
  53925. ** ROLLBACK TO one;
  53926. **
  53927. ** If page X were not written to the sub-journal here, it would not
  53928. ** be possible to restore its contents when the "ROLLBACK TO one"
  53929. ** statement were is processed.
  53930. **
  53931. ** subjournalPage() may need to allocate space to store pPg->pgno into
  53932. ** one or more savepoint bitvecs. This is the reason this function
  53933. ** may return SQLITE_NOMEM.
  53934. */
  53935. if( (pPg->flags & PGHDR_DIRTY)!=0
  53936. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  53937. ){
  53938. return rc;
  53939. }
  53940. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  53941. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  53942. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  53943. /* If the journal needs to be sync()ed before page pPg->pgno can
  53944. ** be written to, store pPg->pgno in local variable needSyncPgno.
  53945. **
  53946. ** If the isCommit flag is set, there is no need to remember that
  53947. ** the journal needs to be sync()ed before database page pPg->pgno
  53948. ** can be written to. The caller has already promised not to write to it.
  53949. */
  53950. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  53951. needSyncPgno = pPg->pgno;
  53952. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  53953. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  53954. assert( pPg->flags&PGHDR_DIRTY );
  53955. }
  53956. /* If the cache contains a page with page-number pgno, remove it
  53957. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  53958. ** page pgno before the 'move' operation, it needs to be retained
  53959. ** for the page moved there.
  53960. */
  53961. pPg->flags &= ~PGHDR_NEED_SYNC;
  53962. pPgOld = sqlite3PagerLookup(pPager, pgno);
  53963. assert( !pPgOld || pPgOld->nRef==1 );
  53964. if( pPgOld ){
  53965. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  53966. if( pPager->tempFile ){
  53967. /* Do not discard pages from an in-memory database since we might
  53968. ** need to rollback later. Just move the page out of the way. */
  53969. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  53970. }else{
  53971. sqlite3PcacheDrop(pPgOld);
  53972. }
  53973. }
  53974. origPgno = pPg->pgno;
  53975. sqlite3PcacheMove(pPg, pgno);
  53976. sqlite3PcacheMakeDirty(pPg);
  53977. /* For an in-memory database, make sure the original page continues
  53978. ** to exist, in case the transaction needs to roll back. Use pPgOld
  53979. ** as the original page since it has already been allocated.
  53980. */
  53981. if( pPager->tempFile && pPgOld ){
  53982. sqlite3PcacheMove(pPgOld, origPgno);
  53983. sqlite3PagerUnrefNotNull(pPgOld);
  53984. }
  53985. if( needSyncPgno ){
  53986. /* If needSyncPgno is non-zero, then the journal file needs to be
  53987. ** sync()ed before any data is written to database file page needSyncPgno.
  53988. ** Currently, no such page exists in the page-cache and the
  53989. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  53990. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  53991. ** flag.
  53992. **
  53993. ** If the attempt to load the page into the page-cache fails, (due
  53994. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  53995. ** array. Otherwise, if the page is loaded and written again in
  53996. ** this transaction, it may be written to the database file before
  53997. ** it is synced into the journal file. This way, it may end up in
  53998. ** the journal file twice, but that is not a problem.
  53999. */
  54000. PgHdr *pPgHdr;
  54001. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
  54002. if( rc!=SQLITE_OK ){
  54003. if( needSyncPgno<=pPager->dbOrigSize ){
  54004. assert( pPager->pTmpSpace!=0 );
  54005. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  54006. }
  54007. return rc;
  54008. }
  54009. pPgHdr->flags |= PGHDR_NEED_SYNC;
  54010. sqlite3PcacheMakeDirty(pPgHdr);
  54011. sqlite3PagerUnrefNotNull(pPgHdr);
  54012. }
  54013. return SQLITE_OK;
  54014. }
  54015. #endif
  54016. /*
  54017. ** The page handle passed as the first argument refers to a dirty page
  54018. ** with a page number other than iNew. This function changes the page's
  54019. ** page number to iNew and sets the value of the PgHdr.flags field to
  54020. ** the value passed as the third parameter.
  54021. */
  54022. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  54023. assert( pPg->pgno!=iNew );
  54024. pPg->flags = flags;
  54025. sqlite3PcacheMove(pPg, iNew);
  54026. }
  54027. /*
  54028. ** Return a pointer to the data for the specified page.
  54029. */
  54030. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  54031. assert( pPg->nRef>0 || pPg->pPager->memDb );
  54032. return pPg->pData;
  54033. }
  54034. /*
  54035. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  54036. ** allocated along with the specified page.
  54037. */
  54038. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  54039. return pPg->pExtra;
  54040. }
  54041. /*
  54042. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  54043. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  54044. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  54045. ** the locking-mode is set to the value specified.
  54046. **
  54047. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  54048. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  54049. ** locking-mode.
  54050. */
  54051. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  54052. assert( eMode==PAGER_LOCKINGMODE_QUERY
  54053. || eMode==PAGER_LOCKINGMODE_NORMAL
  54054. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  54055. assert( PAGER_LOCKINGMODE_QUERY<0 );
  54056. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  54057. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  54058. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  54059. pPager->exclusiveMode = (u8)eMode;
  54060. }
  54061. return (int)pPager->exclusiveMode;
  54062. }
  54063. /*
  54064. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  54065. **
  54066. ** PAGER_JOURNALMODE_DELETE
  54067. ** PAGER_JOURNALMODE_TRUNCATE
  54068. ** PAGER_JOURNALMODE_PERSIST
  54069. ** PAGER_JOURNALMODE_OFF
  54070. ** PAGER_JOURNALMODE_MEMORY
  54071. ** PAGER_JOURNALMODE_WAL
  54072. **
  54073. ** The journalmode is set to the value specified if the change is allowed.
  54074. ** The change may be disallowed for the following reasons:
  54075. **
  54076. ** * An in-memory database can only have its journal_mode set to _OFF
  54077. ** or _MEMORY.
  54078. **
  54079. ** * Temporary databases cannot have _WAL journalmode.
  54080. **
  54081. ** The returned indicate the current (possibly updated) journal-mode.
  54082. */
  54083. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  54084. u8 eOld = pPager->journalMode; /* Prior journalmode */
  54085. /* The eMode parameter is always valid */
  54086. assert( eMode==PAGER_JOURNALMODE_DELETE
  54087. || eMode==PAGER_JOURNALMODE_TRUNCATE
  54088. || eMode==PAGER_JOURNALMODE_PERSIST
  54089. || eMode==PAGER_JOURNALMODE_OFF
  54090. || eMode==PAGER_JOURNALMODE_WAL
  54091. || eMode==PAGER_JOURNALMODE_MEMORY );
  54092. /* This routine is only called from the OP_JournalMode opcode, and
  54093. ** the logic there will never allow a temporary file to be changed
  54094. ** to WAL mode.
  54095. */
  54096. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  54097. /* Do allow the journalmode of an in-memory database to be set to
  54098. ** anything other than MEMORY or OFF
  54099. */
  54100. if( MEMDB ){
  54101. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  54102. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  54103. eMode = eOld;
  54104. }
  54105. }
  54106. if( eMode!=eOld ){
  54107. /* Change the journal mode. */
  54108. assert( pPager->eState!=PAGER_ERROR );
  54109. pPager->journalMode = (u8)eMode;
  54110. /* When transistioning from TRUNCATE or PERSIST to any other journal
  54111. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  54112. ** delete the journal file.
  54113. */
  54114. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  54115. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  54116. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  54117. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  54118. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  54119. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  54120. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  54121. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  54122. /* In this case we would like to delete the journal file. If it is
  54123. ** not possible, then that is not a problem. Deleting the journal file
  54124. ** here is an optimization only.
  54125. **
  54126. ** Before deleting the journal file, obtain a RESERVED lock on the
  54127. ** database file. This ensures that the journal file is not deleted
  54128. ** while it is in use by some other client.
  54129. */
  54130. sqlite3OsClose(pPager->jfd);
  54131. if( pPager->eLock>=RESERVED_LOCK ){
  54132. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  54133. }else{
  54134. int rc = SQLITE_OK;
  54135. int state = pPager->eState;
  54136. assert( state==PAGER_OPEN || state==PAGER_READER );
  54137. if( state==PAGER_OPEN ){
  54138. rc = sqlite3PagerSharedLock(pPager);
  54139. }
  54140. if( pPager->eState==PAGER_READER ){
  54141. assert( rc==SQLITE_OK );
  54142. rc = pagerLockDb(pPager, RESERVED_LOCK);
  54143. }
  54144. if( rc==SQLITE_OK ){
  54145. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  54146. }
  54147. if( rc==SQLITE_OK && state==PAGER_READER ){
  54148. pagerUnlockDb(pPager, SHARED_LOCK);
  54149. }else if( state==PAGER_OPEN ){
  54150. pager_unlock(pPager);
  54151. }
  54152. assert( state==pPager->eState );
  54153. }
  54154. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  54155. sqlite3OsClose(pPager->jfd);
  54156. }
  54157. }
  54158. /* Return the new journal mode */
  54159. return (int)pPager->journalMode;
  54160. }
  54161. /*
  54162. ** Return the current journal mode.
  54163. */
  54164. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  54165. return (int)pPager->journalMode;
  54166. }
  54167. /*
  54168. ** Return TRUE if the pager is in a state where it is OK to change the
  54169. ** journalmode. Journalmode changes can only happen when the database
  54170. ** is unmodified.
  54171. */
  54172. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  54173. assert( assert_pager_state(pPager) );
  54174. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  54175. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  54176. return 1;
  54177. }
  54178. /*
  54179. ** Get/set the size-limit used for persistent journal files.
  54180. **
  54181. ** Setting the size limit to -1 means no limit is enforced.
  54182. ** An attempt to set a limit smaller than -1 is a no-op.
  54183. */
  54184. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  54185. if( iLimit>=-1 ){
  54186. pPager->journalSizeLimit = iLimit;
  54187. sqlite3WalLimit(pPager->pWal, iLimit);
  54188. }
  54189. return pPager->journalSizeLimit;
  54190. }
  54191. /*
  54192. ** Return a pointer to the pPager->pBackup variable. The backup module
  54193. ** in backup.c maintains the content of this variable. This module
  54194. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  54195. ** sqlite3BackupUpdate() only.
  54196. */
  54197. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  54198. return &pPager->pBackup;
  54199. }
  54200. #ifndef SQLITE_OMIT_VACUUM
  54201. /*
  54202. ** Unless this is an in-memory or temporary database, clear the pager cache.
  54203. */
  54204. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  54205. assert( MEMDB==0 || pPager->tempFile );
  54206. if( pPager->tempFile==0 ) pager_reset(pPager);
  54207. }
  54208. #endif
  54209. #ifndef SQLITE_OMIT_WAL
  54210. /*
  54211. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  54212. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  54213. ** or wal_blocking_checkpoint() API functions.
  54214. **
  54215. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  54216. */
  54217. SQLITE_PRIVATE int sqlite3PagerCheckpoint(
  54218. Pager *pPager, /* Checkpoint on this pager */
  54219. sqlite3 *db, /* Db handle used to check for interrupts */
  54220. int eMode, /* Type of checkpoint */
  54221. int *pnLog, /* OUT: Final number of frames in log */
  54222. int *pnCkpt /* OUT: Final number of checkpointed frames */
  54223. ){
  54224. int rc = SQLITE_OK;
  54225. if( pPager->pWal ){
  54226. rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
  54227. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  54228. pPager->pBusyHandlerArg,
  54229. pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  54230. pnLog, pnCkpt
  54231. );
  54232. sqlite3PagerResetLockTimeout(pPager);
  54233. }
  54234. return rc;
  54235. }
  54236. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  54237. return sqlite3WalCallback(pPager->pWal);
  54238. }
  54239. /*
  54240. ** Return true if the underlying VFS for the given pager supports the
  54241. ** primitives necessary for write-ahead logging.
  54242. */
  54243. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  54244. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  54245. if( pPager->noLock ) return 0;
  54246. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  54247. }
  54248. /*
  54249. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  54250. ** is obtained instead, immediately release it.
  54251. */
  54252. static int pagerExclusiveLock(Pager *pPager){
  54253. int rc; /* Return code */
  54254. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  54255. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  54256. if( rc!=SQLITE_OK ){
  54257. /* If the attempt to grab the exclusive lock failed, release the
  54258. ** pending lock that may have been obtained instead. */
  54259. pagerUnlockDb(pPager, SHARED_LOCK);
  54260. }
  54261. return rc;
  54262. }
  54263. /*
  54264. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  54265. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  54266. ** lock on the database file and use heap-memory to store the wal-index
  54267. ** in. Otherwise, use the normal shared-memory.
  54268. */
  54269. static int pagerOpenWal(Pager *pPager){
  54270. int rc = SQLITE_OK;
  54271. assert( pPager->pWal==0 && pPager->tempFile==0 );
  54272. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  54273. /* If the pager is already in exclusive-mode, the WAL module will use
  54274. ** heap-memory for the wal-index instead of the VFS shared-memory
  54275. ** implementation. Take the exclusive lock now, before opening the WAL
  54276. ** file, to make sure this is safe.
  54277. */
  54278. if( pPager->exclusiveMode ){
  54279. rc = pagerExclusiveLock(pPager);
  54280. }
  54281. /* Open the connection to the log file. If this operation fails,
  54282. ** (e.g. due to malloc() failure), return an error code.
  54283. */
  54284. if( rc==SQLITE_OK ){
  54285. rc = sqlite3WalOpen(pPager->pVfs,
  54286. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  54287. pPager->journalSizeLimit, &pPager->pWal
  54288. );
  54289. }
  54290. pagerFixMaplimit(pPager);
  54291. return rc;
  54292. }
  54293. /*
  54294. ** The caller must be holding a SHARED lock on the database file to call
  54295. ** this function.
  54296. **
  54297. ** If the pager passed as the first argument is open on a real database
  54298. ** file (not a temp file or an in-memory database), and the WAL file
  54299. ** is not already open, make an attempt to open it now. If successful,
  54300. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  54301. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  54302. ** not modified in either case.
  54303. **
  54304. ** If the pager is open on a temp-file (or in-memory database), or if
  54305. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  54306. ** without doing anything.
  54307. */
  54308. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  54309. Pager *pPager, /* Pager object */
  54310. int *pbOpen /* OUT: Set to true if call is a no-op */
  54311. ){
  54312. int rc = SQLITE_OK; /* Return code */
  54313. assert( assert_pager_state(pPager) );
  54314. assert( pPager->eState==PAGER_OPEN || pbOpen );
  54315. assert( pPager->eState==PAGER_READER || !pbOpen );
  54316. assert( pbOpen==0 || *pbOpen==0 );
  54317. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  54318. if( !pPager->tempFile && !pPager->pWal ){
  54319. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  54320. /* Close any rollback journal previously open */
  54321. sqlite3OsClose(pPager->jfd);
  54322. rc = pagerOpenWal(pPager);
  54323. if( rc==SQLITE_OK ){
  54324. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  54325. pPager->eState = PAGER_OPEN;
  54326. }
  54327. }else{
  54328. *pbOpen = 1;
  54329. }
  54330. return rc;
  54331. }
  54332. /*
  54333. ** This function is called to close the connection to the log file prior
  54334. ** to switching from WAL to rollback mode.
  54335. **
  54336. ** Before closing the log file, this function attempts to take an
  54337. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  54338. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  54339. ** If successful, the EXCLUSIVE lock is not released before returning.
  54340. */
  54341. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
  54342. int rc = SQLITE_OK;
  54343. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  54344. /* If the log file is not already open, but does exist in the file-system,
  54345. ** it may need to be checkpointed before the connection can switch to
  54346. ** rollback mode. Open it now so this can happen.
  54347. */
  54348. if( !pPager->pWal ){
  54349. int logexists = 0;
  54350. rc = pagerLockDb(pPager, SHARED_LOCK);
  54351. if( rc==SQLITE_OK ){
  54352. rc = sqlite3OsAccess(
  54353. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  54354. );
  54355. }
  54356. if( rc==SQLITE_OK && logexists ){
  54357. rc = pagerOpenWal(pPager);
  54358. }
  54359. }
  54360. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  54361. ** the database file, the log and log-summary files will be deleted.
  54362. */
  54363. if( rc==SQLITE_OK && pPager->pWal ){
  54364. rc = pagerExclusiveLock(pPager);
  54365. if( rc==SQLITE_OK ){
  54366. rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
  54367. pPager->pageSize, (u8*)pPager->pTmpSpace);
  54368. pPager->pWal = 0;
  54369. pagerFixMaplimit(pPager);
  54370. if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  54371. }
  54372. }
  54373. return rc;
  54374. }
  54375. #ifdef SQLITE_ENABLE_SNAPSHOT
  54376. /*
  54377. ** If this is a WAL database, obtain a snapshot handle for the snapshot
  54378. ** currently open. Otherwise, return an error.
  54379. */
  54380. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
  54381. int rc = SQLITE_ERROR;
  54382. if( pPager->pWal ){
  54383. rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
  54384. }
  54385. return rc;
  54386. }
  54387. /*
  54388. ** If this is a WAL database, store a pointer to pSnapshot. Next time a
  54389. ** read transaction is opened, attempt to read from the snapshot it
  54390. ** identifies. If this is not a WAL database, return an error.
  54391. */
  54392. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
  54393. int rc = SQLITE_OK;
  54394. if( pPager->pWal ){
  54395. sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
  54396. }else{
  54397. rc = SQLITE_ERROR;
  54398. }
  54399. return rc;
  54400. }
  54401. /*
  54402. ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
  54403. ** is not a WAL database, return an error.
  54404. */
  54405. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
  54406. int rc;
  54407. if( pPager->pWal ){
  54408. rc = sqlite3WalSnapshotRecover(pPager->pWal);
  54409. }else{
  54410. rc = SQLITE_ERROR;
  54411. }
  54412. return rc;
  54413. }
  54414. /*
  54415. ** The caller currently has a read transaction open on the database.
  54416. ** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise,
  54417. ** this function takes a SHARED lock on the CHECKPOINTER slot and then
  54418. ** checks if the snapshot passed as the second argument is still
  54419. ** available. If so, SQLITE_OK is returned.
  54420. **
  54421. ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
  54422. ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
  54423. ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
  54424. ** lock is released before returning.
  54425. */
  54426. SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot){
  54427. int rc;
  54428. if( pPager->pWal ){
  54429. rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot);
  54430. }else{
  54431. rc = SQLITE_ERROR;
  54432. }
  54433. return rc;
  54434. }
  54435. /*
  54436. ** Release a lock obtained by an earlier successful call to
  54437. ** sqlite3PagerSnapshotCheck().
  54438. */
  54439. SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager){
  54440. assert( pPager->pWal );
  54441. return sqlite3WalSnapshotUnlock(pPager->pWal);
  54442. }
  54443. #endif /* SQLITE_ENABLE_SNAPSHOT */
  54444. #endif /* !SQLITE_OMIT_WAL */
  54445. #ifdef SQLITE_ENABLE_ZIPVFS
  54446. /*
  54447. ** A read-lock must be held on the pager when this function is called. If
  54448. ** the pager is in WAL mode and the WAL file currently contains one or more
  54449. ** frames, return the size in bytes of the page images stored within the
  54450. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  54451. ** is empty, return 0.
  54452. */
  54453. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  54454. assert( pPager->eState>=PAGER_READER );
  54455. return sqlite3WalFramesize(pPager->pWal);
  54456. }
  54457. #endif
  54458. #endif /* SQLITE_OMIT_DISKIO */
  54459. /************** End of pager.c ***********************************************/
  54460. /************** Begin file wal.c *********************************************/
  54461. /*
  54462. ** 2010 February 1
  54463. **
  54464. ** The author disclaims copyright to this source code. In place of
  54465. ** a legal notice, here is a blessing:
  54466. **
  54467. ** May you do good and not evil.
  54468. ** May you find forgiveness for yourself and forgive others.
  54469. ** May you share freely, never taking more than you give.
  54470. **
  54471. *************************************************************************
  54472. **
  54473. ** This file contains the implementation of a write-ahead log (WAL) used in
  54474. ** "journal_mode=WAL" mode.
  54475. **
  54476. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  54477. **
  54478. ** A WAL file consists of a header followed by zero or more "frames".
  54479. ** Each frame records the revised content of a single page from the
  54480. ** database file. All changes to the database are recorded by writing
  54481. ** frames into the WAL. Transactions commit when a frame is written that
  54482. ** contains a commit marker. A single WAL can and usually does record
  54483. ** multiple transactions. Periodically, the content of the WAL is
  54484. ** transferred back into the database file in an operation called a
  54485. ** "checkpoint".
  54486. **
  54487. ** A single WAL file can be used multiple times. In other words, the
  54488. ** WAL can fill up with frames and then be checkpointed and then new
  54489. ** frames can overwrite the old ones. A WAL always grows from beginning
  54490. ** toward the end. Checksums and counters attached to each frame are
  54491. ** used to determine which frames within the WAL are valid and which
  54492. ** are leftovers from prior checkpoints.
  54493. **
  54494. ** The WAL header is 32 bytes in size and consists of the following eight
  54495. ** big-endian 32-bit unsigned integer values:
  54496. **
  54497. ** 0: Magic number. 0x377f0682 or 0x377f0683
  54498. ** 4: File format version. Currently 3007000
  54499. ** 8: Database page size. Example: 1024
  54500. ** 12: Checkpoint sequence number
  54501. ** 16: Salt-1, random integer incremented with each checkpoint
  54502. ** 20: Salt-2, a different random integer changing with each ckpt
  54503. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  54504. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  54505. **
  54506. ** Immediately following the wal-header are zero or more frames. Each
  54507. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  54508. ** of page data. The frame-header is six big-endian 32-bit unsigned
  54509. ** integer values, as follows:
  54510. **
  54511. ** 0: Page number.
  54512. ** 4: For commit records, the size of the database image in pages
  54513. ** after the commit. For all other records, zero.
  54514. ** 8: Salt-1 (copied from the header)
  54515. ** 12: Salt-2 (copied from the header)
  54516. ** 16: Checksum-1.
  54517. ** 20: Checksum-2.
  54518. **
  54519. ** A frame is considered valid if and only if the following conditions are
  54520. ** true:
  54521. **
  54522. ** (1) The salt-1 and salt-2 values in the frame-header match
  54523. ** salt values in the wal-header
  54524. **
  54525. ** (2) The checksum values in the final 8 bytes of the frame-header
  54526. ** exactly match the checksum computed consecutively on the
  54527. ** WAL header and the first 8 bytes and the content of all frames
  54528. ** up to and including the current frame.
  54529. **
  54530. ** The checksum is computed using 32-bit big-endian integers if the
  54531. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  54532. ** is computed using little-endian if the magic number is 0x377f0682.
  54533. ** The checksum values are always stored in the frame header in a
  54534. ** big-endian format regardless of which byte order is used to compute
  54535. ** the checksum. The checksum is computed by interpreting the input as
  54536. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  54537. ** algorithm used for the checksum is as follows:
  54538. **
  54539. ** for i from 0 to n-1 step 2:
  54540. ** s0 += x[i] + s1;
  54541. ** s1 += x[i+1] + s0;
  54542. ** endfor
  54543. **
  54544. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  54545. ** in reverse order (the largest fibonacci weight occurs on the first element
  54546. ** of the sequence being summed.) The s1 value spans all 32-bit
  54547. ** terms of the sequence whereas s0 omits the final term.
  54548. **
  54549. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  54550. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  54551. ** The VFS.xSync operations serve as write barriers - all writes launched
  54552. ** before the xSync must complete before any write that launches after the
  54553. ** xSync begins.
  54554. **
  54555. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  54556. ** value is randomized. This prevents old and new frames in the WAL from
  54557. ** being considered valid at the same time and being checkpointing together
  54558. ** following a crash.
  54559. **
  54560. ** READER ALGORITHM
  54561. **
  54562. ** To read a page from the database (call it page number P), a reader
  54563. ** first checks the WAL to see if it contains page P. If so, then the
  54564. ** last valid instance of page P that is a followed by a commit frame
  54565. ** or is a commit frame itself becomes the value read. If the WAL
  54566. ** contains no copies of page P that are valid and which are a commit
  54567. ** frame or are followed by a commit frame, then page P is read from
  54568. ** the database file.
  54569. **
  54570. ** To start a read transaction, the reader records the index of the last
  54571. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  54572. ** for all subsequent read operations. New transactions can be appended
  54573. ** to the WAL, but as long as the reader uses its original mxFrame value
  54574. ** and ignores the newly appended content, it will see a consistent snapshot
  54575. ** of the database from a single point in time. This technique allows
  54576. ** multiple concurrent readers to view different versions of the database
  54577. ** content simultaneously.
  54578. **
  54579. ** The reader algorithm in the previous paragraphs works correctly, but
  54580. ** because frames for page P can appear anywhere within the WAL, the
  54581. ** reader has to scan the entire WAL looking for page P frames. If the
  54582. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  54583. ** and read performance suffers. To overcome this problem, a separate
  54584. ** data structure called the wal-index is maintained to expedite the
  54585. ** search for frames of a particular page.
  54586. **
  54587. ** WAL-INDEX FORMAT
  54588. **
  54589. ** Conceptually, the wal-index is shared memory, though VFS implementations
  54590. ** might choose to implement the wal-index using a mmapped file. Because
  54591. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  54592. ** on a network filesystem. All users of the database must be able to
  54593. ** share memory.
  54594. **
  54595. ** In the default unix and windows implementation, the wal-index is a mmapped
  54596. ** file whose name is the database name with a "-shm" suffix added. For that
  54597. ** reason, the wal-index is sometimes called the "shm" file.
  54598. **
  54599. ** The wal-index is transient. After a crash, the wal-index can (and should
  54600. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  54601. ** to either truncate or zero the header of the wal-index when the last
  54602. ** connection to it closes. Because the wal-index is transient, it can
  54603. ** use an architecture-specific format; it does not have to be cross-platform.
  54604. ** Hence, unlike the database and WAL file formats which store all values
  54605. ** as big endian, the wal-index can store multi-byte values in the native
  54606. ** byte order of the host computer.
  54607. **
  54608. ** The purpose of the wal-index is to answer this question quickly: Given
  54609. ** a page number P and a maximum frame index M, return the index of the
  54610. ** last frame in the wal before frame M for page P in the WAL, or return
  54611. ** NULL if there are no frames for page P in the WAL prior to M.
  54612. **
  54613. ** The wal-index consists of a header region, followed by an one or
  54614. ** more index blocks.
  54615. **
  54616. ** The wal-index header contains the total number of frames within the WAL
  54617. ** in the mxFrame field.
  54618. **
  54619. ** Each index block except for the first contains information on
  54620. ** HASHTABLE_NPAGE frames. The first index block contains information on
  54621. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  54622. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  54623. ** first index block are the same size as all other index blocks in the
  54624. ** wal-index.
  54625. **
  54626. ** Each index block contains two sections, a page-mapping that contains the
  54627. ** database page number associated with each wal frame, and a hash-table
  54628. ** that allows readers to query an index block for a specific page number.
  54629. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  54630. ** for the first index block) 32-bit page numbers. The first entry in the
  54631. ** first index-block contains the database page number corresponding to the
  54632. ** first frame in the WAL file. The first entry in the second index block
  54633. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  54634. ** the log, and so on.
  54635. **
  54636. ** The last index block in a wal-index usually contains less than the full
  54637. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  54638. ** depending on the contents of the WAL file. This does not change the
  54639. ** allocated size of the page-mapping array - the page-mapping array merely
  54640. ** contains unused entries.
  54641. **
  54642. ** Even without using the hash table, the last frame for page P
  54643. ** can be found by scanning the page-mapping sections of each index block
  54644. ** starting with the last index block and moving toward the first, and
  54645. ** within each index block, starting at the end and moving toward the
  54646. ** beginning. The first entry that equals P corresponds to the frame
  54647. ** holding the content for that page.
  54648. **
  54649. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  54650. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  54651. ** hash table for each page number in the mapping section, so the hash
  54652. ** table is never more than half full. The expected number of collisions
  54653. ** prior to finding a match is 1. Each entry of the hash table is an
  54654. ** 1-based index of an entry in the mapping section of the same
  54655. ** index block. Let K be the 1-based index of the largest entry in
  54656. ** the mapping section. (For index blocks other than the last, K will
  54657. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  54658. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  54659. ** contain a value of 0.
  54660. **
  54661. ** To look for page P in the hash table, first compute a hash iKey on
  54662. ** P as follows:
  54663. **
  54664. ** iKey = (P * 383) % HASHTABLE_NSLOT
  54665. **
  54666. ** Then start scanning entries of the hash table, starting with iKey
  54667. ** (wrapping around to the beginning when the end of the hash table is
  54668. ** reached) until an unused hash slot is found. Let the first unused slot
  54669. ** be at index iUnused. (iUnused might be less than iKey if there was
  54670. ** wrap-around.) Because the hash table is never more than half full,
  54671. ** the search is guaranteed to eventually hit an unused entry. Let
  54672. ** iMax be the value between iKey and iUnused, closest to iUnused,
  54673. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  54674. ** no hash slot such that aHash[i]==p) then page P is not in the
  54675. ** current index block. Otherwise the iMax-th mapping entry of the
  54676. ** current index block corresponds to the last entry that references
  54677. ** page P.
  54678. **
  54679. ** A hash search begins with the last index block and moves toward the
  54680. ** first index block, looking for entries corresponding to page P. On
  54681. ** average, only two or three slots in each index block need to be
  54682. ** examined in order to either find the last entry for page P, or to
  54683. ** establish that no such entry exists in the block. Each index block
  54684. ** holds over 4000 entries. So two or three index blocks are sufficient
  54685. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  54686. ** comparisons (on average) suffice to either locate a frame in the
  54687. ** WAL or to establish that the frame does not exist in the WAL. This
  54688. ** is much faster than scanning the entire 10MB WAL.
  54689. **
  54690. ** Note that entries are added in order of increasing K. Hence, one
  54691. ** reader might be using some value K0 and a second reader that started
  54692. ** at a later time (after additional transactions were added to the WAL
  54693. ** and to the wal-index) might be using a different value K1, where K1>K0.
  54694. ** Both readers can use the same hash table and mapping section to get
  54695. ** the correct result. There may be entries in the hash table with
  54696. ** K>K0 but to the first reader, those entries will appear to be unused
  54697. ** slots in the hash table and so the first reader will get an answer as
  54698. ** if no values greater than K0 had ever been inserted into the hash table
  54699. ** in the first place - which is what reader one wants. Meanwhile, the
  54700. ** second reader using K1 will see additional values that were inserted
  54701. ** later, which is exactly what reader two wants.
  54702. **
  54703. ** When a rollback occurs, the value of K is decreased. Hash table entries
  54704. ** that correspond to frames greater than the new K value are removed
  54705. ** from the hash table at this point.
  54706. */
  54707. #ifndef SQLITE_OMIT_WAL
  54708. /* #include "wal.h" */
  54709. /*
  54710. ** Trace output macros
  54711. */
  54712. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  54713. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  54714. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  54715. #else
  54716. # define WALTRACE(X)
  54717. #endif
  54718. /*
  54719. ** WAL mode depends on atomic aligned 32-bit loads and stores in a few
  54720. ** places. The following macros try to make this explicit.
  54721. */
  54722. #if GCC_VESRION>=5004000
  54723. # define AtomicLoad(PTR) __atomic_load_n((PTR),__ATOMIC_RELAXED)
  54724. # define AtomicStore(PTR,VAL) __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
  54725. #else
  54726. # define AtomicLoad(PTR) (*(PTR))
  54727. # define AtomicStore(PTR,VAL) (*(PTR) = (VAL))
  54728. #endif
  54729. /*
  54730. ** The maximum (and only) versions of the wal and wal-index formats
  54731. ** that may be interpreted by this version of SQLite.
  54732. **
  54733. ** If a client begins recovering a WAL file and finds that (a) the checksum
  54734. ** values in the wal-header are correct and (b) the version field is not
  54735. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  54736. **
  54737. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  54738. ** checksum test is successful) and finds that the version field is not
  54739. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  54740. ** returns SQLITE_CANTOPEN.
  54741. */
  54742. #define WAL_MAX_VERSION 3007000
  54743. #define WALINDEX_MAX_VERSION 3007000
  54744. /*
  54745. ** Index numbers for various locking bytes. WAL_NREADER is the number
  54746. ** of available reader locks and should be at least 3. The default
  54747. ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
  54748. **
  54749. ** Technically, the various VFSes are free to implement these locks however
  54750. ** they see fit. However, compatibility is encouraged so that VFSes can
  54751. ** interoperate. The standard implemention used on both unix and windows
  54752. ** is for the index number to indicate a byte offset into the
  54753. ** WalCkptInfo.aLock[] array in the wal-index header. In other words, all
  54754. ** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which
  54755. ** should be 120) is the location in the shm file for the first locking
  54756. ** byte.
  54757. */
  54758. #define WAL_WRITE_LOCK 0
  54759. #define WAL_ALL_BUT_WRITE 1
  54760. #define WAL_CKPT_LOCK 1
  54761. #define WAL_RECOVER_LOCK 2
  54762. #define WAL_READ_LOCK(I) (3+(I))
  54763. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  54764. /* Object declarations */
  54765. typedef struct WalIndexHdr WalIndexHdr;
  54766. typedef struct WalIterator WalIterator;
  54767. typedef struct WalCkptInfo WalCkptInfo;
  54768. /*
  54769. ** The following object holds a copy of the wal-index header content.
  54770. **
  54771. ** The actual header in the wal-index consists of two copies of this
  54772. ** object followed by one instance of the WalCkptInfo object.
  54773. ** For all versions of SQLite through 3.10.0 and probably beyond,
  54774. ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
  54775. ** the total header size is 136 bytes.
  54776. **
  54777. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  54778. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  54779. ** added in 3.7.1 when support for 64K pages was added.
  54780. */
  54781. struct WalIndexHdr {
  54782. u32 iVersion; /* Wal-index version */
  54783. u32 unused; /* Unused (padding) field */
  54784. u32 iChange; /* Counter incremented each transaction */
  54785. u8 isInit; /* 1 when initialized */
  54786. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  54787. u16 szPage; /* Database page size in bytes. 1==64K */
  54788. u32 mxFrame; /* Index of last valid frame in the WAL */
  54789. u32 nPage; /* Size of database in pages */
  54790. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  54791. u32 aSalt[2]; /* Two salt values copied from WAL header */
  54792. u32 aCksum[2]; /* Checksum over all prior fields */
  54793. };
  54794. /*
  54795. ** A copy of the following object occurs in the wal-index immediately
  54796. ** following the second copy of the WalIndexHdr. This object stores
  54797. ** information used by checkpoint.
  54798. **
  54799. ** nBackfill is the number of frames in the WAL that have been written
  54800. ** back into the database. (We call the act of moving content from WAL to
  54801. ** database "backfilling".) The nBackfill number is never greater than
  54802. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  54803. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  54804. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  54805. ** mxFrame back to zero when the WAL is reset.
  54806. **
  54807. ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
  54808. ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
  54809. ** the nBackfillAttempted is set before any backfilling is done and the
  54810. ** nBackfill is only set after all backfilling completes. So if a checkpoint
  54811. ** crashes, nBackfillAttempted might be larger than nBackfill. The
  54812. ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
  54813. **
  54814. ** The aLock[] field is a set of bytes used for locking. These bytes should
  54815. ** never be read or written.
  54816. **
  54817. ** There is one entry in aReadMark[] for each reader lock. If a reader
  54818. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  54819. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  54820. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  54821. ** a special case; its value is never used and it exists as a place-holder
  54822. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  54823. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  54824. ** directly from the database.
  54825. **
  54826. ** The value of aReadMark[K] may only be changed by a thread that
  54827. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  54828. ** aReadMark[K] cannot changed while there is a reader is using that mark
  54829. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  54830. **
  54831. ** The checkpointer may only transfer frames from WAL to database where
  54832. ** the frame numbers are less than or equal to every aReadMark[] that is
  54833. ** in use (that is, every aReadMark[j] for which there is a corresponding
  54834. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  54835. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  54836. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  54837. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  54838. ** in the WAL has been backfilled into the database) then new readers
  54839. ** will choose aReadMark[0] which has value 0 and hence such reader will
  54840. ** get all their all content directly from the database file and ignore
  54841. ** the WAL.
  54842. **
  54843. ** Writers normally append new frames to the end of the WAL. However,
  54844. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  54845. ** written back into the database) and if no readers are using the WAL
  54846. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  54847. ** the writer will first "reset" the WAL back to the beginning and start
  54848. ** writing new content beginning at frame 1.
  54849. **
  54850. ** We assume that 32-bit loads are atomic and so no locks are needed in
  54851. ** order to read from any aReadMark[] entries.
  54852. */
  54853. struct WalCkptInfo {
  54854. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  54855. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  54856. u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
  54857. u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
  54858. u32 notUsed0; /* Available for future enhancements */
  54859. };
  54860. #define READMARK_NOT_USED 0xffffffff
  54861. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  54862. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  54863. ** only support mandatory file-locks, we do not read or write data
  54864. ** from the region of the file on which locks are applied.
  54865. */
  54866. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
  54867. #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
  54868. /* Size of header before each frame in wal */
  54869. #define WAL_FRAME_HDRSIZE 24
  54870. /* Size of write ahead log header, including checksum. */
  54871. #define WAL_HDRSIZE 32
  54872. /* WAL magic value. Either this value, or the same value with the least
  54873. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  54874. ** big-endian format in the first 4 bytes of a WAL file.
  54875. **
  54876. ** If the LSB is set, then the checksums for each frame within the WAL
  54877. ** file are calculated by treating all data as an array of 32-bit
  54878. ** big-endian words. Otherwise, they are calculated by interpreting
  54879. ** all data as 32-bit little-endian words.
  54880. */
  54881. #define WAL_MAGIC 0x377f0682
  54882. /*
  54883. ** Return the offset of frame iFrame in the write-ahead log file,
  54884. ** assuming a database page size of szPage bytes. The offset returned
  54885. ** is to the start of the write-ahead log frame-header.
  54886. */
  54887. #define walFrameOffset(iFrame, szPage) ( \
  54888. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  54889. )
  54890. /*
  54891. ** An open write-ahead log file is represented by an instance of the
  54892. ** following object.
  54893. */
  54894. struct Wal {
  54895. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  54896. sqlite3_file *pDbFd; /* File handle for the database file */
  54897. sqlite3_file *pWalFd; /* File handle for WAL file */
  54898. u32 iCallback; /* Value to pass to log callback (or 0) */
  54899. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  54900. int nWiData; /* Size of array apWiData */
  54901. int szFirstBlock; /* Size of first block written to WAL file */
  54902. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  54903. u32 szPage; /* Database page size */
  54904. i16 readLock; /* Which read lock is being held. -1 for none */
  54905. u8 syncFlags; /* Flags to use to sync header writes */
  54906. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  54907. u8 writeLock; /* True if in a write transaction */
  54908. u8 ckptLock; /* True if holding a checkpoint lock */
  54909. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  54910. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  54911. u8 syncHeader; /* Fsync the WAL header if true */
  54912. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  54913. u8 bShmUnreliable; /* SHM content is read-only and unreliable */
  54914. WalIndexHdr hdr; /* Wal-index header for current transaction */
  54915. u32 minFrame; /* Ignore wal frames before this one */
  54916. u32 iReCksum; /* On commit, recalculate checksums from here */
  54917. const char *zWalName; /* Name of WAL file */
  54918. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  54919. #ifdef SQLITE_DEBUG
  54920. u8 lockError; /* True if a locking error has occurred */
  54921. #endif
  54922. #ifdef SQLITE_ENABLE_SNAPSHOT
  54923. WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
  54924. #endif
  54925. };
  54926. /*
  54927. ** Candidate values for Wal.exclusiveMode.
  54928. */
  54929. #define WAL_NORMAL_MODE 0
  54930. #define WAL_EXCLUSIVE_MODE 1
  54931. #define WAL_HEAPMEMORY_MODE 2
  54932. /*
  54933. ** Possible values for WAL.readOnly
  54934. */
  54935. #define WAL_RDWR 0 /* Normal read/write connection */
  54936. #define WAL_RDONLY 1 /* The WAL file is readonly */
  54937. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  54938. /*
  54939. ** Each page of the wal-index mapping contains a hash-table made up of
  54940. ** an array of HASHTABLE_NSLOT elements of the following type.
  54941. */
  54942. typedef u16 ht_slot;
  54943. /*
  54944. ** This structure is used to implement an iterator that loops through
  54945. ** all frames in the WAL in database page order. Where two or more frames
  54946. ** correspond to the same database page, the iterator visits only the
  54947. ** frame most recently written to the WAL (in other words, the frame with
  54948. ** the largest index).
  54949. **
  54950. ** The internals of this structure are only accessed by:
  54951. **
  54952. ** walIteratorInit() - Create a new iterator,
  54953. ** walIteratorNext() - Step an iterator,
  54954. ** walIteratorFree() - Free an iterator.
  54955. **
  54956. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  54957. */
  54958. struct WalIterator {
  54959. int iPrior; /* Last result returned from the iterator */
  54960. int nSegment; /* Number of entries in aSegment[] */
  54961. struct WalSegment {
  54962. int iNext; /* Next slot in aIndex[] not yet returned */
  54963. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  54964. u32 *aPgno; /* Array of page numbers. */
  54965. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  54966. int iZero; /* Frame number associated with aPgno[0] */
  54967. } aSegment[1]; /* One for every 32KB page in the wal-index */
  54968. };
  54969. /*
  54970. ** Define the parameters of the hash tables in the wal-index file. There
  54971. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  54972. ** wal-index.
  54973. **
  54974. ** Changing any of these constants will alter the wal-index format and
  54975. ** create incompatibilities.
  54976. */
  54977. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  54978. #define HASHTABLE_HASH_1 383 /* Should be prime */
  54979. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  54980. /*
  54981. ** The block of page numbers associated with the first hash-table in a
  54982. ** wal-index is smaller than usual. This is so that there is a complete
  54983. ** hash-table on each aligned 32KB page of the wal-index.
  54984. */
  54985. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  54986. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  54987. #define WALINDEX_PGSZ ( \
  54988. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  54989. )
  54990. /*
  54991. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  54992. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  54993. ** numbered from zero.
  54994. **
  54995. ** If the wal-index is currently smaller the iPage pages then the size
  54996. ** of the wal-index might be increased, but only if it is safe to do
  54997. ** so. It is safe to enlarge the wal-index if pWal->writeLock is true
  54998. ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
  54999. **
  55000. ** If this call is successful, *ppPage is set to point to the wal-index
  55001. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  55002. ** then an SQLite error code is returned and *ppPage is set to 0.
  55003. */
  55004. static SQLITE_NOINLINE int walIndexPageRealloc(
  55005. Wal *pWal, /* The WAL context */
  55006. int iPage, /* The page we seek */
  55007. volatile u32 **ppPage /* Write the page pointer here */
  55008. ){
  55009. int rc = SQLITE_OK;
  55010. /* Enlarge the pWal->apWiData[] array if required */
  55011. if( pWal->nWiData<=iPage ){
  55012. int nByte = sizeof(u32*)*(iPage+1);
  55013. volatile u32 **apNew;
  55014. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  55015. if( !apNew ){
  55016. *ppPage = 0;
  55017. return SQLITE_NOMEM_BKPT;
  55018. }
  55019. memset((void*)&apNew[pWal->nWiData], 0,
  55020. sizeof(u32*)*(iPage+1-pWal->nWiData));
  55021. pWal->apWiData = apNew;
  55022. pWal->nWiData = iPage+1;
  55023. }
  55024. /* Request a pointer to the required page from the VFS */
  55025. assert( pWal->apWiData[iPage]==0 );
  55026. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  55027. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  55028. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
  55029. }else{
  55030. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  55031. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  55032. );
  55033. assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );
  55034. testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
  55035. if( (rc&0xff)==SQLITE_READONLY ){
  55036. pWal->readOnly |= WAL_SHM_RDONLY;
  55037. if( rc==SQLITE_READONLY ){
  55038. rc = SQLITE_OK;
  55039. }
  55040. }
  55041. }
  55042. *ppPage = pWal->apWiData[iPage];
  55043. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  55044. return rc;
  55045. }
  55046. static int walIndexPage(
  55047. Wal *pWal, /* The WAL context */
  55048. int iPage, /* The page we seek */
  55049. volatile u32 **ppPage /* Write the page pointer here */
  55050. ){
  55051. if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
  55052. return walIndexPageRealloc(pWal, iPage, ppPage);
  55053. }
  55054. return SQLITE_OK;
  55055. }
  55056. /*
  55057. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  55058. */
  55059. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  55060. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  55061. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  55062. }
  55063. /*
  55064. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  55065. */
  55066. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  55067. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  55068. return (volatile WalIndexHdr*)pWal->apWiData[0];
  55069. }
  55070. /*
  55071. ** The argument to this macro must be of type u32. On a little-endian
  55072. ** architecture, it returns the u32 value that results from interpreting
  55073. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  55074. ** returns the value that would be produced by interpreting the 4 bytes
  55075. ** of the input value as a little-endian integer.
  55076. */
  55077. #define BYTESWAP32(x) ( \
  55078. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  55079. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  55080. )
  55081. /*
  55082. ** Generate or extend an 8 byte checksum based on the data in
  55083. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  55084. ** initial values of 0 and 0 if aIn==NULL).
  55085. **
  55086. ** The checksum is written back into aOut[] before returning.
  55087. **
  55088. ** nByte must be a positive multiple of 8.
  55089. */
  55090. static void walChecksumBytes(
  55091. int nativeCksum, /* True for native byte-order, false for non-native */
  55092. u8 *a, /* Content to be checksummed */
  55093. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  55094. const u32 *aIn, /* Initial checksum value input */
  55095. u32 *aOut /* OUT: Final checksum value output */
  55096. ){
  55097. u32 s1, s2;
  55098. u32 *aData = (u32 *)a;
  55099. u32 *aEnd = (u32 *)&a[nByte];
  55100. if( aIn ){
  55101. s1 = aIn[0];
  55102. s2 = aIn[1];
  55103. }else{
  55104. s1 = s2 = 0;
  55105. }
  55106. assert( nByte>=8 );
  55107. assert( (nByte&0x00000007)==0 );
  55108. if( nativeCksum ){
  55109. do {
  55110. s1 += *aData++ + s2;
  55111. s2 += *aData++ + s1;
  55112. }while( aData<aEnd );
  55113. }else{
  55114. do {
  55115. s1 += BYTESWAP32(aData[0]) + s2;
  55116. s2 += BYTESWAP32(aData[1]) + s1;
  55117. aData += 2;
  55118. }while( aData<aEnd );
  55119. }
  55120. aOut[0] = s1;
  55121. aOut[1] = s2;
  55122. }
  55123. static void walShmBarrier(Wal *pWal){
  55124. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  55125. sqlite3OsShmBarrier(pWal->pDbFd);
  55126. }
  55127. }
  55128. /*
  55129. ** Write the header information in pWal->hdr into the wal-index.
  55130. **
  55131. ** The checksum on pWal->hdr is updated before it is written.
  55132. */
  55133. static void walIndexWriteHdr(Wal *pWal){
  55134. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  55135. const int nCksum = offsetof(WalIndexHdr, aCksum);
  55136. assert( pWal->writeLock );
  55137. pWal->hdr.isInit = 1;
  55138. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  55139. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  55140. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  55141. walShmBarrier(pWal);
  55142. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  55143. }
  55144. /*
  55145. ** This function encodes a single frame header and writes it to a buffer
  55146. ** supplied by the caller. A frame-header is made up of a series of
  55147. ** 4-byte big-endian integers, as follows:
  55148. **
  55149. ** 0: Page number.
  55150. ** 4: For commit records, the size of the database image in pages
  55151. ** after the commit. For all other records, zero.
  55152. ** 8: Salt-1 (copied from the wal-header)
  55153. ** 12: Salt-2 (copied from the wal-header)
  55154. ** 16: Checksum-1.
  55155. ** 20: Checksum-2.
  55156. */
  55157. static void walEncodeFrame(
  55158. Wal *pWal, /* The write-ahead log */
  55159. u32 iPage, /* Database page number for frame */
  55160. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  55161. u8 *aData, /* Pointer to page data */
  55162. u8 *aFrame /* OUT: Write encoded frame here */
  55163. ){
  55164. int nativeCksum; /* True for native byte-order checksums */
  55165. u32 *aCksum = pWal->hdr.aFrameCksum;
  55166. assert( WAL_FRAME_HDRSIZE==24 );
  55167. sqlite3Put4byte(&aFrame[0], iPage);
  55168. sqlite3Put4byte(&aFrame[4], nTruncate);
  55169. if( pWal->iReCksum==0 ){
  55170. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  55171. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  55172. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  55173. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  55174. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  55175. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  55176. }else{
  55177. memset(&aFrame[8], 0, 16);
  55178. }
  55179. }
  55180. /*
  55181. ** Check to see if the frame with header in aFrame[] and content
  55182. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  55183. ** *pnTruncate and return true. Return if the frame is not valid.
  55184. */
  55185. static int walDecodeFrame(
  55186. Wal *pWal, /* The write-ahead log */
  55187. u32 *piPage, /* OUT: Database page number for frame */
  55188. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  55189. u8 *aData, /* Pointer to page data (for checksum) */
  55190. u8 *aFrame /* Frame data */
  55191. ){
  55192. int nativeCksum; /* True for native byte-order checksums */
  55193. u32 *aCksum = pWal->hdr.aFrameCksum;
  55194. u32 pgno; /* Page number of the frame */
  55195. assert( WAL_FRAME_HDRSIZE==24 );
  55196. /* A frame is only valid if the salt values in the frame-header
  55197. ** match the salt values in the wal-header.
  55198. */
  55199. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  55200. return 0;
  55201. }
  55202. /* A frame is only valid if the page number is creater than zero.
  55203. */
  55204. pgno = sqlite3Get4byte(&aFrame[0]);
  55205. if( pgno==0 ){
  55206. return 0;
  55207. }
  55208. /* A frame is only valid if a checksum of the WAL header,
  55209. ** all prior frams, the first 16 bytes of this frame-header,
  55210. ** and the frame-data matches the checksum in the last 8
  55211. ** bytes of this frame-header.
  55212. */
  55213. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  55214. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  55215. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  55216. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  55217. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  55218. ){
  55219. /* Checksum failed. */
  55220. return 0;
  55221. }
  55222. /* If we reach this point, the frame is valid. Return the page number
  55223. ** and the new database size.
  55224. */
  55225. *piPage = pgno;
  55226. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  55227. return 1;
  55228. }
  55229. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  55230. /*
  55231. ** Names of locks. This routine is used to provide debugging output and is not
  55232. ** a part of an ordinary build.
  55233. */
  55234. static const char *walLockName(int lockIdx){
  55235. if( lockIdx==WAL_WRITE_LOCK ){
  55236. return "WRITE-LOCK";
  55237. }else if( lockIdx==WAL_CKPT_LOCK ){
  55238. return "CKPT-LOCK";
  55239. }else if( lockIdx==WAL_RECOVER_LOCK ){
  55240. return "RECOVER-LOCK";
  55241. }else{
  55242. static char zName[15];
  55243. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  55244. lockIdx-WAL_READ_LOCK(0));
  55245. return zName;
  55246. }
  55247. }
  55248. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  55249. /*
  55250. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  55251. ** A lock cannot be moved directly between shared and exclusive - it must go
  55252. ** through the unlocked state first.
  55253. **
  55254. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  55255. */
  55256. static int walLockShared(Wal *pWal, int lockIdx){
  55257. int rc;
  55258. if( pWal->exclusiveMode ) return SQLITE_OK;
  55259. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  55260. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  55261. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  55262. walLockName(lockIdx), rc ? "failed" : "ok"));
  55263. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  55264. return rc;
  55265. }
  55266. static void walUnlockShared(Wal *pWal, int lockIdx){
  55267. if( pWal->exclusiveMode ) return;
  55268. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  55269. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  55270. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  55271. }
  55272. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  55273. int rc;
  55274. if( pWal->exclusiveMode ) return SQLITE_OK;
  55275. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  55276. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  55277. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  55278. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  55279. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  55280. return rc;
  55281. }
  55282. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  55283. if( pWal->exclusiveMode ) return;
  55284. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  55285. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  55286. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  55287. walLockName(lockIdx), n));
  55288. }
  55289. /*
  55290. ** Compute a hash on a page number. The resulting hash value must land
  55291. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  55292. ** the hash to the next value in the event of a collision.
  55293. */
  55294. static int walHash(u32 iPage){
  55295. assert( iPage>0 );
  55296. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  55297. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  55298. }
  55299. static int walNextHash(int iPriorHash){
  55300. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  55301. }
  55302. /*
  55303. ** An instance of the WalHashLoc object is used to describe the location
  55304. ** of a page hash table in the wal-index. This becomes the return value
  55305. ** from walHashGet().
  55306. */
  55307. typedef struct WalHashLoc WalHashLoc;
  55308. struct WalHashLoc {
  55309. volatile ht_slot *aHash; /* Start of the wal-index hash table */
  55310. volatile u32 *aPgno; /* aPgno[1] is the page of first frame indexed */
  55311. u32 iZero; /* One less than the frame number of first indexed*/
  55312. };
  55313. /*
  55314. ** Return pointers to the hash table and page number array stored on
  55315. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  55316. ** numbered starting from 0.
  55317. **
  55318. ** Set output variable pLoc->aHash to point to the start of the hash table
  55319. ** in the wal-index file. Set pLoc->iZero to one less than the frame
  55320. ** number of the first frame indexed by this hash table. If a
  55321. ** slot in the hash table is set to N, it refers to frame number
  55322. ** (pLoc->iZero+N) in the log.
  55323. **
  55324. ** Finally, set pLoc->aPgno so that pLoc->aPgno[1] is the page number of the
  55325. ** first frame indexed by the hash table, frame (pLoc->iZero+1).
  55326. */
  55327. static int walHashGet(
  55328. Wal *pWal, /* WAL handle */
  55329. int iHash, /* Find the iHash'th table */
  55330. WalHashLoc *pLoc /* OUT: Hash table location */
  55331. ){
  55332. int rc; /* Return code */
  55333. rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
  55334. assert( rc==SQLITE_OK || iHash>0 );
  55335. if( rc==SQLITE_OK ){
  55336. pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
  55337. if( iHash==0 ){
  55338. pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  55339. pLoc->iZero = 0;
  55340. }else{
  55341. pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  55342. }
  55343. pLoc->aPgno = &pLoc->aPgno[-1];
  55344. }
  55345. return rc;
  55346. }
  55347. /*
  55348. ** Return the number of the wal-index page that contains the hash-table
  55349. ** and page-number array that contain entries corresponding to WAL frame
  55350. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  55351. ** are numbered starting from 0.
  55352. */
  55353. static int walFramePage(u32 iFrame){
  55354. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  55355. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  55356. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  55357. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  55358. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  55359. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  55360. );
  55361. return iHash;
  55362. }
  55363. /*
  55364. ** Return the page number associated with frame iFrame in this WAL.
  55365. */
  55366. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  55367. int iHash = walFramePage(iFrame);
  55368. if( iHash==0 ){
  55369. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  55370. }
  55371. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  55372. }
  55373. /*
  55374. ** Remove entries from the hash table that point to WAL slots greater
  55375. ** than pWal->hdr.mxFrame.
  55376. **
  55377. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  55378. ** to a rollback or savepoint.
  55379. **
  55380. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  55381. ** updated. Any later hash tables will be automatically cleared when
  55382. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  55383. ** actually needed.
  55384. */
  55385. static void walCleanupHash(Wal *pWal){
  55386. WalHashLoc sLoc; /* Hash table location */
  55387. int iLimit = 0; /* Zero values greater than this */
  55388. int nByte; /* Number of bytes to zero in aPgno[] */
  55389. int i; /* Used to iterate through aHash[] */
  55390. assert( pWal->writeLock );
  55391. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  55392. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  55393. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  55394. if( pWal->hdr.mxFrame==0 ) return;
  55395. /* Obtain pointers to the hash-table and page-number array containing
  55396. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  55397. ** that the page said hash-table and array reside on is already mapped.
  55398. */
  55399. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  55400. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  55401. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
  55402. /* Zero all hash-table entries that correspond to frame numbers greater
  55403. ** than pWal->hdr.mxFrame.
  55404. */
  55405. iLimit = pWal->hdr.mxFrame - sLoc.iZero;
  55406. assert( iLimit>0 );
  55407. for(i=0; i<HASHTABLE_NSLOT; i++){
  55408. if( sLoc.aHash[i]>iLimit ){
  55409. sLoc.aHash[i] = 0;
  55410. }
  55411. }
  55412. /* Zero the entries in the aPgno array that correspond to frames with
  55413. ** frame numbers greater than pWal->hdr.mxFrame.
  55414. */
  55415. nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]);
  55416. memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte);
  55417. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  55418. /* Verify that the every entry in the mapping region is still reachable
  55419. ** via the hash table even after the cleanup.
  55420. */
  55421. if( iLimit ){
  55422. int j; /* Loop counter */
  55423. int iKey; /* Hash key */
  55424. for(j=1; j<=iLimit; j++){
  55425. for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
  55426. if( sLoc.aHash[iKey]==j ) break;
  55427. }
  55428. assert( sLoc.aHash[iKey]==j );
  55429. }
  55430. }
  55431. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  55432. }
  55433. /*
  55434. ** Set an entry in the wal-index that will map database page number
  55435. ** pPage into WAL frame iFrame.
  55436. */
  55437. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  55438. int rc; /* Return code */
  55439. WalHashLoc sLoc; /* Wal-index hash table location */
  55440. rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
  55441. /* Assuming the wal-index file was successfully mapped, populate the
  55442. ** page number array and hash table entry.
  55443. */
  55444. if( rc==SQLITE_OK ){
  55445. int iKey; /* Hash table key */
  55446. int idx; /* Value to write to hash-table slot */
  55447. int nCollide; /* Number of hash collisions */
  55448. idx = iFrame - sLoc.iZero;
  55449. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  55450. /* If this is the first entry to be added to this hash-table, zero the
  55451. ** entire hash table and aPgno[] array before proceeding.
  55452. */
  55453. if( idx==1 ){
  55454. int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT]
  55455. - (u8 *)&sLoc.aPgno[1]);
  55456. memset((void*)&sLoc.aPgno[1], 0, nByte);
  55457. }
  55458. /* If the entry in aPgno[] is already set, then the previous writer
  55459. ** must have exited unexpectedly in the middle of a transaction (after
  55460. ** writing one or more dirty pages to the WAL to free up memory).
  55461. ** Remove the remnants of that writers uncommitted transaction from
  55462. ** the hash-table before writing any new entries.
  55463. */
  55464. if( sLoc.aPgno[idx] ){
  55465. walCleanupHash(pWal);
  55466. assert( !sLoc.aPgno[idx] );
  55467. }
  55468. /* Write the aPgno[] array entry and the hash-table slot. */
  55469. nCollide = idx;
  55470. for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
  55471. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  55472. }
  55473. sLoc.aPgno[idx] = iPage;
  55474. sLoc.aHash[iKey] = (ht_slot)idx;
  55475. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  55476. /* Verify that the number of entries in the hash table exactly equals
  55477. ** the number of entries in the mapping region.
  55478. */
  55479. {
  55480. int i; /* Loop counter */
  55481. int nEntry = 0; /* Number of entries in the hash table */
  55482. for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }
  55483. assert( nEntry==idx );
  55484. }
  55485. /* Verify that the every entry in the mapping region is reachable
  55486. ** via the hash table. This turns out to be a really, really expensive
  55487. ** thing to check, so only do this occasionally - not on every
  55488. ** iteration.
  55489. */
  55490. if( (idx&0x3ff)==0 ){
  55491. int i; /* Loop counter */
  55492. for(i=1; i<=idx; i++){
  55493. for(iKey=walHash(sLoc.aPgno[i]);
  55494. sLoc.aHash[iKey];
  55495. iKey=walNextHash(iKey)){
  55496. if( sLoc.aHash[iKey]==i ) break;
  55497. }
  55498. assert( sLoc.aHash[iKey]==i );
  55499. }
  55500. }
  55501. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  55502. }
  55503. return rc;
  55504. }
  55505. /*
  55506. ** Recover the wal-index by reading the write-ahead log file.
  55507. **
  55508. ** This routine first tries to establish an exclusive lock on the
  55509. ** wal-index to prevent other threads/processes from doing anything
  55510. ** with the WAL or wal-index while recovery is running. The
  55511. ** WAL_RECOVER_LOCK is also held so that other threads will know
  55512. ** that this thread is running recovery. If unable to establish
  55513. ** the necessary locks, this routine returns SQLITE_BUSY.
  55514. */
  55515. static int walIndexRecover(Wal *pWal){
  55516. int rc; /* Return Code */
  55517. i64 nSize; /* Size of log file */
  55518. u32 aFrameCksum[2] = {0, 0};
  55519. int iLock; /* Lock offset to lock for checkpoint */
  55520. /* Obtain an exclusive lock on all byte in the locking range not already
  55521. ** locked by the caller. The caller is guaranteed to have locked the
  55522. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  55523. ** If successful, the same bytes that are locked here are unlocked before
  55524. ** this function returns.
  55525. */
  55526. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  55527. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  55528. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  55529. assert( pWal->writeLock );
  55530. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  55531. rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  55532. if( rc==SQLITE_OK ){
  55533. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  55534. if( rc!=SQLITE_OK ){
  55535. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  55536. }
  55537. }
  55538. if( rc ){
  55539. return rc;
  55540. }
  55541. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  55542. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  55543. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  55544. if( rc!=SQLITE_OK ){
  55545. goto recovery_error;
  55546. }
  55547. if( nSize>WAL_HDRSIZE ){
  55548. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  55549. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  55550. int szFrame; /* Number of bytes in buffer aFrame[] */
  55551. u8 *aData; /* Pointer to data part of aFrame buffer */
  55552. int iFrame; /* Index of last frame read */
  55553. i64 iOffset; /* Next offset to read from log file */
  55554. int szPage; /* Page size according to the log */
  55555. u32 magic; /* Magic value read from WAL header */
  55556. u32 version; /* Magic value read from WAL header */
  55557. int isValid; /* True if this frame is valid */
  55558. /* Read in the WAL header. */
  55559. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  55560. if( rc!=SQLITE_OK ){
  55561. goto recovery_error;
  55562. }
  55563. /* If the database page size is not a power of two, or is greater than
  55564. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  55565. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  55566. ** WAL file.
  55567. */
  55568. magic = sqlite3Get4byte(&aBuf[0]);
  55569. szPage = sqlite3Get4byte(&aBuf[8]);
  55570. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  55571. || szPage&(szPage-1)
  55572. || szPage>SQLITE_MAX_PAGE_SIZE
  55573. || szPage<512
  55574. ){
  55575. goto finished;
  55576. }
  55577. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  55578. pWal->szPage = szPage;
  55579. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  55580. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  55581. /* Verify that the WAL header checksum is correct */
  55582. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  55583. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  55584. );
  55585. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  55586. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  55587. ){
  55588. goto finished;
  55589. }
  55590. /* Verify that the version number on the WAL format is one that
  55591. ** are able to understand */
  55592. version = sqlite3Get4byte(&aBuf[4]);
  55593. if( version!=WAL_MAX_VERSION ){
  55594. rc = SQLITE_CANTOPEN_BKPT;
  55595. goto finished;
  55596. }
  55597. /* Malloc a buffer to read frames into. */
  55598. szFrame = szPage + WAL_FRAME_HDRSIZE;
  55599. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  55600. if( !aFrame ){
  55601. rc = SQLITE_NOMEM_BKPT;
  55602. goto recovery_error;
  55603. }
  55604. aData = &aFrame[WAL_FRAME_HDRSIZE];
  55605. /* Read all frames from the log file. */
  55606. iFrame = 0;
  55607. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  55608. u32 pgno; /* Database page number for frame */
  55609. u32 nTruncate; /* dbsize field from frame header */
  55610. /* Read and decode the next log frame. */
  55611. iFrame++;
  55612. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  55613. if( rc!=SQLITE_OK ) break;
  55614. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  55615. if( !isValid ) break;
  55616. rc = walIndexAppend(pWal, iFrame, pgno);
  55617. if( rc!=SQLITE_OK ) break;
  55618. /* If nTruncate is non-zero, this is a commit record. */
  55619. if( nTruncate ){
  55620. pWal->hdr.mxFrame = iFrame;
  55621. pWal->hdr.nPage = nTruncate;
  55622. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  55623. testcase( szPage<=32768 );
  55624. testcase( szPage>=65536 );
  55625. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  55626. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  55627. }
  55628. }
  55629. sqlite3_free(aFrame);
  55630. }
  55631. finished:
  55632. if( rc==SQLITE_OK ){
  55633. volatile WalCkptInfo *pInfo;
  55634. int i;
  55635. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  55636. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  55637. walIndexWriteHdr(pWal);
  55638. /* Reset the checkpoint-header. This is safe because this thread is
  55639. ** currently holding locks that exclude all other readers, writers and
  55640. ** checkpointers.
  55641. */
  55642. pInfo = walCkptInfo(pWal);
  55643. pInfo->nBackfill = 0;
  55644. pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
  55645. pInfo->aReadMark[0] = 0;
  55646. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  55647. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  55648. /* If more than one frame was recovered from the log file, report an
  55649. ** event via sqlite3_log(). This is to help with identifying performance
  55650. ** problems caused by applications routinely shutting down without
  55651. ** checkpointing the log file.
  55652. */
  55653. if( pWal->hdr.nPage ){
  55654. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  55655. "recovered %d frames from WAL file %s",
  55656. pWal->hdr.mxFrame, pWal->zWalName
  55657. );
  55658. }
  55659. }
  55660. recovery_error:
  55661. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  55662. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  55663. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  55664. return rc;
  55665. }
  55666. /*
  55667. ** Close an open wal-index.
  55668. */
  55669. static void walIndexClose(Wal *pWal, int isDelete){
  55670. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
  55671. int i;
  55672. for(i=0; i<pWal->nWiData; i++){
  55673. sqlite3_free((void *)pWal->apWiData[i]);
  55674. pWal->apWiData[i] = 0;
  55675. }
  55676. }
  55677. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  55678. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  55679. }
  55680. }
  55681. /*
  55682. ** Open a connection to the WAL file zWalName. The database file must
  55683. ** already be opened on connection pDbFd. The buffer that zWalName points
  55684. ** to must remain valid for the lifetime of the returned Wal* handle.
  55685. **
  55686. ** A SHARED lock should be held on the database file when this function
  55687. ** is called. The purpose of this SHARED lock is to prevent any other
  55688. ** client from unlinking the WAL or wal-index file. If another process
  55689. ** were to do this just after this client opened one of these files, the
  55690. ** system would be badly broken.
  55691. **
  55692. ** If the log file is successfully opened, SQLITE_OK is returned and
  55693. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  55694. ** an SQLite error code is returned and *ppWal is left unmodified.
  55695. */
  55696. SQLITE_PRIVATE int sqlite3WalOpen(
  55697. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  55698. sqlite3_file *pDbFd, /* The open database file */
  55699. const char *zWalName, /* Name of the WAL file */
  55700. int bNoShm, /* True to run in heap-memory mode */
  55701. i64 mxWalSize, /* Truncate WAL to this size on reset */
  55702. Wal **ppWal /* OUT: Allocated Wal handle */
  55703. ){
  55704. int rc; /* Return Code */
  55705. Wal *pRet; /* Object to allocate and return */
  55706. int flags; /* Flags passed to OsOpen() */
  55707. assert( zWalName && zWalName[0] );
  55708. assert( pDbFd );
  55709. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  55710. ** this source file. Verify that the #defines of the locking byte offsets
  55711. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  55712. ** For that matter, if the lock offset ever changes from its initial design
  55713. ** value of 120, we need to know that so there is an assert() to check it.
  55714. */
  55715. assert( 120==WALINDEX_LOCK_OFFSET );
  55716. assert( 136==WALINDEX_HDR_SIZE );
  55717. #ifdef WIN_SHM_BASE
  55718. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  55719. #endif
  55720. #ifdef UNIX_SHM_BASE
  55721. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  55722. #endif
  55723. /* Allocate an instance of struct Wal to return. */
  55724. *ppWal = 0;
  55725. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  55726. if( !pRet ){
  55727. return SQLITE_NOMEM_BKPT;
  55728. }
  55729. pRet->pVfs = pVfs;
  55730. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  55731. pRet->pDbFd = pDbFd;
  55732. pRet->readLock = -1;
  55733. pRet->mxWalSize = mxWalSize;
  55734. pRet->zWalName = zWalName;
  55735. pRet->syncHeader = 1;
  55736. pRet->padToSectorBoundary = 1;
  55737. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  55738. /* Open file handle on the write-ahead log file. */
  55739. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  55740. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  55741. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  55742. pRet->readOnly = WAL_RDONLY;
  55743. }
  55744. if( rc!=SQLITE_OK ){
  55745. walIndexClose(pRet, 0);
  55746. sqlite3OsClose(pRet->pWalFd);
  55747. sqlite3_free(pRet);
  55748. }else{
  55749. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  55750. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  55751. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  55752. pRet->padToSectorBoundary = 0;
  55753. }
  55754. *ppWal = pRet;
  55755. WALTRACE(("WAL%d: opened\n", pRet));
  55756. }
  55757. return rc;
  55758. }
  55759. /*
  55760. ** Change the size to which the WAL file is trucated on each reset.
  55761. */
  55762. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  55763. if( pWal ) pWal->mxWalSize = iLimit;
  55764. }
  55765. /*
  55766. ** Find the smallest page number out of all pages held in the WAL that
  55767. ** has not been returned by any prior invocation of this method on the
  55768. ** same WalIterator object. Write into *piFrame the frame index where
  55769. ** that page was last written into the WAL. Write into *piPage the page
  55770. ** number.
  55771. **
  55772. ** Return 0 on success. If there are no pages in the WAL with a page
  55773. ** number larger than *piPage, then return 1.
  55774. */
  55775. static int walIteratorNext(
  55776. WalIterator *p, /* Iterator */
  55777. u32 *piPage, /* OUT: The page number of the next page */
  55778. u32 *piFrame /* OUT: Wal frame index of next page */
  55779. ){
  55780. u32 iMin; /* Result pgno must be greater than iMin */
  55781. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  55782. int i; /* For looping through segments */
  55783. iMin = p->iPrior;
  55784. assert( iMin<0xffffffff );
  55785. for(i=p->nSegment-1; i>=0; i--){
  55786. struct WalSegment *pSegment = &p->aSegment[i];
  55787. while( pSegment->iNext<pSegment->nEntry ){
  55788. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  55789. if( iPg>iMin ){
  55790. if( iPg<iRet ){
  55791. iRet = iPg;
  55792. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  55793. }
  55794. break;
  55795. }
  55796. pSegment->iNext++;
  55797. }
  55798. }
  55799. *piPage = p->iPrior = iRet;
  55800. return (iRet==0xFFFFFFFF);
  55801. }
  55802. /*
  55803. ** This function merges two sorted lists into a single sorted list.
  55804. **
  55805. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  55806. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  55807. ** is guaranteed for all J<K:
  55808. **
  55809. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  55810. ** aContent[aRight[J]] < aContent[aRight[K]]
  55811. **
  55812. ** This routine overwrites aRight[] with a new (probably longer) sequence
  55813. ** of indices such that the aRight[] contains every index that appears in
  55814. ** either aLeft[] or the old aRight[] and such that the second condition
  55815. ** above is still met.
  55816. **
  55817. ** The aContent[aLeft[X]] values will be unique for all X. And the
  55818. ** aContent[aRight[X]] values will be unique too. But there might be
  55819. ** one or more combinations of X and Y such that
  55820. **
  55821. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  55822. **
  55823. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  55824. */
  55825. static void walMerge(
  55826. const u32 *aContent, /* Pages in wal - keys for the sort */
  55827. ht_slot *aLeft, /* IN: Left hand input list */
  55828. int nLeft, /* IN: Elements in array *paLeft */
  55829. ht_slot **paRight, /* IN/OUT: Right hand input list */
  55830. int *pnRight, /* IN/OUT: Elements in *paRight */
  55831. ht_slot *aTmp /* Temporary buffer */
  55832. ){
  55833. int iLeft = 0; /* Current index in aLeft */
  55834. int iRight = 0; /* Current index in aRight */
  55835. int iOut = 0; /* Current index in output buffer */
  55836. int nRight = *pnRight;
  55837. ht_slot *aRight = *paRight;
  55838. assert( nLeft>0 && nRight>0 );
  55839. while( iRight<nRight || iLeft<nLeft ){
  55840. ht_slot logpage;
  55841. Pgno dbpage;
  55842. if( (iLeft<nLeft)
  55843. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  55844. ){
  55845. logpage = aLeft[iLeft++];
  55846. }else{
  55847. logpage = aRight[iRight++];
  55848. }
  55849. dbpage = aContent[logpage];
  55850. aTmp[iOut++] = logpage;
  55851. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  55852. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  55853. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  55854. }
  55855. *paRight = aLeft;
  55856. *pnRight = iOut;
  55857. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  55858. }
  55859. /*
  55860. ** Sort the elements in list aList using aContent[] as the sort key.
  55861. ** Remove elements with duplicate keys, preferring to keep the
  55862. ** larger aList[] values.
  55863. **
  55864. ** The aList[] entries are indices into aContent[]. The values in
  55865. ** aList[] are to be sorted so that for all J<K:
  55866. **
  55867. ** aContent[aList[J]] < aContent[aList[K]]
  55868. **
  55869. ** For any X and Y such that
  55870. **
  55871. ** aContent[aList[X]] == aContent[aList[Y]]
  55872. **
  55873. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  55874. ** the smaller.
  55875. */
  55876. static void walMergesort(
  55877. const u32 *aContent, /* Pages in wal */
  55878. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  55879. ht_slot *aList, /* IN/OUT: List to sort */
  55880. int *pnList /* IN/OUT: Number of elements in aList[] */
  55881. ){
  55882. struct Sublist {
  55883. int nList; /* Number of elements in aList */
  55884. ht_slot *aList; /* Pointer to sub-list content */
  55885. };
  55886. const int nList = *pnList; /* Size of input list */
  55887. int nMerge = 0; /* Number of elements in list aMerge */
  55888. ht_slot *aMerge = 0; /* List to be merged */
  55889. int iList; /* Index into input list */
  55890. u32 iSub = 0; /* Index into aSub array */
  55891. struct Sublist aSub[13]; /* Array of sub-lists */
  55892. memset(aSub, 0, sizeof(aSub));
  55893. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  55894. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  55895. for(iList=0; iList<nList; iList++){
  55896. nMerge = 1;
  55897. aMerge = &aList[iList];
  55898. for(iSub=0; iList & (1<<iSub); iSub++){
  55899. struct Sublist *p;
  55900. assert( iSub<ArraySize(aSub) );
  55901. p = &aSub[iSub];
  55902. assert( p->aList && p->nList<=(1<<iSub) );
  55903. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  55904. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  55905. }
  55906. aSub[iSub].aList = aMerge;
  55907. aSub[iSub].nList = nMerge;
  55908. }
  55909. for(iSub++; iSub<ArraySize(aSub); iSub++){
  55910. if( nList & (1<<iSub) ){
  55911. struct Sublist *p;
  55912. assert( iSub<ArraySize(aSub) );
  55913. p = &aSub[iSub];
  55914. assert( p->nList<=(1<<iSub) );
  55915. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  55916. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  55917. }
  55918. }
  55919. assert( aMerge==aList );
  55920. *pnList = nMerge;
  55921. #ifdef SQLITE_DEBUG
  55922. {
  55923. int i;
  55924. for(i=1; i<*pnList; i++){
  55925. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  55926. }
  55927. }
  55928. #endif
  55929. }
  55930. /*
  55931. ** Free an iterator allocated by walIteratorInit().
  55932. */
  55933. static void walIteratorFree(WalIterator *p){
  55934. sqlite3_free(p);
  55935. }
  55936. /*
  55937. ** Construct a WalInterator object that can be used to loop over all
  55938. ** pages in the WAL following frame nBackfill in ascending order. Frames
  55939. ** nBackfill or earlier may be included - excluding them is an optimization
  55940. ** only. The caller must hold the checkpoint lock.
  55941. **
  55942. ** On success, make *pp point to the newly allocated WalInterator object
  55943. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  55944. ** returns an error, the value of *pp is undefined.
  55945. **
  55946. ** The calling routine should invoke walIteratorFree() to destroy the
  55947. ** WalIterator object when it has finished with it.
  55948. */
  55949. static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
  55950. WalIterator *p; /* Return value */
  55951. int nSegment; /* Number of segments to merge */
  55952. u32 iLast; /* Last frame in log */
  55953. int nByte; /* Number of bytes to allocate */
  55954. int i; /* Iterator variable */
  55955. ht_slot *aTmp; /* Temp space used by merge-sort */
  55956. int rc = SQLITE_OK; /* Return Code */
  55957. /* This routine only runs while holding the checkpoint lock. And
  55958. ** it only runs if there is actually content in the log (mxFrame>0).
  55959. */
  55960. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  55961. iLast = pWal->hdr.mxFrame;
  55962. /* Allocate space for the WalIterator object. */
  55963. nSegment = walFramePage(iLast) + 1;
  55964. nByte = sizeof(WalIterator)
  55965. + (nSegment-1)*sizeof(struct WalSegment)
  55966. + iLast*sizeof(ht_slot);
  55967. p = (WalIterator *)sqlite3_malloc64(nByte);
  55968. if( !p ){
  55969. return SQLITE_NOMEM_BKPT;
  55970. }
  55971. memset(p, 0, nByte);
  55972. p->nSegment = nSegment;
  55973. /* Allocate temporary space used by the merge-sort routine. This block
  55974. ** of memory will be freed before this function returns.
  55975. */
  55976. aTmp = (ht_slot *)sqlite3_malloc64(
  55977. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  55978. );
  55979. if( !aTmp ){
  55980. rc = SQLITE_NOMEM_BKPT;
  55981. }
  55982. for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
  55983. WalHashLoc sLoc;
  55984. rc = walHashGet(pWal, i, &sLoc);
  55985. if( rc==SQLITE_OK ){
  55986. int j; /* Counter variable */
  55987. int nEntry; /* Number of entries in this segment */
  55988. ht_slot *aIndex; /* Sorted index for this segment */
  55989. sLoc.aPgno++;
  55990. if( (i+1)==nSegment ){
  55991. nEntry = (int)(iLast - sLoc.iZero);
  55992. }else{
  55993. nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
  55994. }
  55995. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
  55996. sLoc.iZero++;
  55997. for(j=0; j<nEntry; j++){
  55998. aIndex[j] = (ht_slot)j;
  55999. }
  56000. walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
  56001. p->aSegment[i].iZero = sLoc.iZero;
  56002. p->aSegment[i].nEntry = nEntry;
  56003. p->aSegment[i].aIndex = aIndex;
  56004. p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
  56005. }
  56006. }
  56007. sqlite3_free(aTmp);
  56008. if( rc!=SQLITE_OK ){
  56009. walIteratorFree(p);
  56010. p = 0;
  56011. }
  56012. *pp = p;
  56013. return rc;
  56014. }
  56015. /*
  56016. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  56017. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  56018. ** busy-handler function. Invoke it and retry the lock until either the
  56019. ** lock is successfully obtained or the busy-handler returns 0.
  56020. */
  56021. static int walBusyLock(
  56022. Wal *pWal, /* WAL connection */
  56023. int (*xBusy)(void*), /* Function to call when busy */
  56024. void *pBusyArg, /* Context argument for xBusyHandler */
  56025. int lockIdx, /* Offset of first byte to lock */
  56026. int n /* Number of bytes to lock */
  56027. ){
  56028. int rc;
  56029. do {
  56030. rc = walLockExclusive(pWal, lockIdx, n);
  56031. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  56032. return rc;
  56033. }
  56034. /*
  56035. ** The cache of the wal-index header must be valid to call this function.
  56036. ** Return the page-size in bytes used by the database.
  56037. */
  56038. static int walPagesize(Wal *pWal){
  56039. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  56040. }
  56041. /*
  56042. ** The following is guaranteed when this function is called:
  56043. **
  56044. ** a) the WRITER lock is held,
  56045. ** b) the entire log file has been checkpointed, and
  56046. ** c) any existing readers are reading exclusively from the database
  56047. ** file - there are no readers that may attempt to read a frame from
  56048. ** the log file.
  56049. **
  56050. ** This function updates the shared-memory structures so that the next
  56051. ** client to write to the database (which may be this one) does so by
  56052. ** writing frames into the start of the log file.
  56053. **
  56054. ** The value of parameter salt1 is used as the aSalt[1] value in the
  56055. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  56056. ** one obtained from sqlite3_randomness()).
  56057. */
  56058. static void walRestartHdr(Wal *pWal, u32 salt1){
  56059. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  56060. int i; /* Loop counter */
  56061. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  56062. pWal->nCkpt++;
  56063. pWal->hdr.mxFrame = 0;
  56064. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  56065. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  56066. walIndexWriteHdr(pWal);
  56067. pInfo->nBackfill = 0;
  56068. pInfo->nBackfillAttempted = 0;
  56069. pInfo->aReadMark[1] = 0;
  56070. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  56071. assert( pInfo->aReadMark[0]==0 );
  56072. }
  56073. /*
  56074. ** Copy as much content as we can from the WAL back into the database file
  56075. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  56076. **
  56077. ** The amount of information copies from WAL to database might be limited
  56078. ** by active readers. This routine will never overwrite a database page
  56079. ** that a concurrent reader might be using.
  56080. **
  56081. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  56082. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  56083. ** checkpoints are always run by a background thread or background
  56084. ** process, foreground threads will never block on a lengthy fsync call.
  56085. **
  56086. ** Fsync is called on the WAL before writing content out of the WAL and
  56087. ** into the database. This ensures that if the new content is persistent
  56088. ** in the WAL and can be recovered following a power-loss or hard reset.
  56089. **
  56090. ** Fsync is also called on the database file if (and only if) the entire
  56091. ** WAL content is copied into the database file. This second fsync makes
  56092. ** it safe to delete the WAL since the new content will persist in the
  56093. ** database file.
  56094. **
  56095. ** This routine uses and updates the nBackfill field of the wal-index header.
  56096. ** This is the only routine that will increase the value of nBackfill.
  56097. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  56098. ** its value.)
  56099. **
  56100. ** The caller must be holding sufficient locks to ensure that no other
  56101. ** checkpoint is running (in any other thread or process) at the same
  56102. ** time.
  56103. */
  56104. static int walCheckpoint(
  56105. Wal *pWal, /* Wal connection */
  56106. sqlite3 *db, /* Check for interrupts on this handle */
  56107. int eMode, /* One of PASSIVE, FULL or RESTART */
  56108. int (*xBusy)(void*), /* Function to call when busy */
  56109. void *pBusyArg, /* Context argument for xBusyHandler */
  56110. int sync_flags, /* Flags for OsSync() (or 0) */
  56111. u8 *zBuf /* Temporary buffer to use */
  56112. ){
  56113. int rc = SQLITE_OK; /* Return code */
  56114. int szPage; /* Database page-size */
  56115. WalIterator *pIter = 0; /* Wal iterator context */
  56116. u32 iDbpage = 0; /* Next database page to write */
  56117. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  56118. u32 mxSafeFrame; /* Max frame that can be backfilled */
  56119. u32 mxPage; /* Max database page to write */
  56120. int i; /* Loop counter */
  56121. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  56122. szPage = walPagesize(pWal);
  56123. testcase( szPage<=32768 );
  56124. testcase( szPage>=65536 );
  56125. pInfo = walCkptInfo(pWal);
  56126. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  56127. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  56128. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  56129. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  56130. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  56131. ** safe to write into the database. Frames beyond mxSafeFrame might
  56132. ** overwrite database pages that are in use by active readers and thus
  56133. ** cannot be backfilled from the WAL.
  56134. */
  56135. mxSafeFrame = pWal->hdr.mxFrame;
  56136. mxPage = pWal->hdr.nPage;
  56137. for(i=1; i<WAL_NREADER; i++){
  56138. /* Thread-sanitizer reports that the following is an unsafe read,
  56139. ** as some other thread may be in the process of updating the value
  56140. ** of the aReadMark[] slot. The assumption here is that if that is
  56141. ** happening, the other client may only be increasing the value,
  56142. ** not decreasing it. So assuming either that either the "old" or
  56143. ** "new" version of the value is read, and not some arbitrary value
  56144. ** that would never be written by a real client, things are still
  56145. ** safe. */
  56146. u32 y = pInfo->aReadMark[i];
  56147. if( mxSafeFrame>y ){
  56148. assert( y<=pWal->hdr.mxFrame );
  56149. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  56150. if( rc==SQLITE_OK ){
  56151. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  56152. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  56153. }else if( rc==SQLITE_BUSY ){
  56154. mxSafeFrame = y;
  56155. xBusy = 0;
  56156. }else{
  56157. goto walcheckpoint_out;
  56158. }
  56159. }
  56160. }
  56161. /* Allocate the iterator */
  56162. if( pInfo->nBackfill<mxSafeFrame ){
  56163. rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
  56164. assert( rc==SQLITE_OK || pIter==0 );
  56165. }
  56166. if( pIter
  56167. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  56168. ){
  56169. u32 nBackfill = pInfo->nBackfill;
  56170. pInfo->nBackfillAttempted = mxSafeFrame;
  56171. /* Sync the WAL to disk */
  56172. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  56173. /* If the database may grow as a result of this checkpoint, hint
  56174. ** about the eventual size of the db file to the VFS layer.
  56175. */
  56176. if( rc==SQLITE_OK ){
  56177. i64 nReq = ((i64)mxPage * szPage);
  56178. i64 nSize; /* Current size of database file */
  56179. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  56180. if( rc==SQLITE_OK && nSize<nReq ){
  56181. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  56182. }
  56183. }
  56184. /* Iterate through the contents of the WAL, copying data to the db file */
  56185. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  56186. i64 iOffset;
  56187. assert( walFramePgno(pWal, iFrame)==iDbpage );
  56188. if( db->u1.isInterrupted ){
  56189. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  56190. break;
  56191. }
  56192. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  56193. continue;
  56194. }
  56195. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  56196. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  56197. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  56198. if( rc!=SQLITE_OK ) break;
  56199. iOffset = (iDbpage-1)*(i64)szPage;
  56200. testcase( IS_BIG_INT(iOffset) );
  56201. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  56202. if( rc!=SQLITE_OK ) break;
  56203. }
  56204. /* If work was actually accomplished... */
  56205. if( rc==SQLITE_OK ){
  56206. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  56207. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  56208. testcase( IS_BIG_INT(szDb) );
  56209. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  56210. if( rc==SQLITE_OK ){
  56211. rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
  56212. }
  56213. }
  56214. if( rc==SQLITE_OK ){
  56215. pInfo->nBackfill = mxSafeFrame;
  56216. }
  56217. }
  56218. /* Release the reader lock held while backfilling */
  56219. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  56220. }
  56221. if( rc==SQLITE_BUSY ){
  56222. /* Reset the return code so as not to report a checkpoint failure
  56223. ** just because there are active readers. */
  56224. rc = SQLITE_OK;
  56225. }
  56226. }
  56227. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  56228. ** entire wal file has been copied into the database file, then block
  56229. ** until all readers have finished using the wal file. This ensures that
  56230. ** the next process to write to the database restarts the wal file.
  56231. */
  56232. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  56233. assert( pWal->writeLock );
  56234. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  56235. rc = SQLITE_BUSY;
  56236. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  56237. u32 salt1;
  56238. sqlite3_randomness(4, &salt1);
  56239. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  56240. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  56241. if( rc==SQLITE_OK ){
  56242. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  56243. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  56244. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  56245. ** truncates the log file to zero bytes just prior to a
  56246. ** successful return.
  56247. **
  56248. ** In theory, it might be safe to do this without updating the
  56249. ** wal-index header in shared memory, as all subsequent reader or
  56250. ** writer clients should see that the entire log file has been
  56251. ** checkpointed and behave accordingly. This seems unsafe though,
  56252. ** as it would leave the system in a state where the contents of
  56253. ** the wal-index header do not match the contents of the
  56254. ** file-system. To avoid this, update the wal-index header to
  56255. ** indicate that the log file contains zero valid frames. */
  56256. walRestartHdr(pWal, salt1);
  56257. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  56258. }
  56259. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  56260. }
  56261. }
  56262. }
  56263. walcheckpoint_out:
  56264. walIteratorFree(pIter);
  56265. return rc;
  56266. }
  56267. /*
  56268. ** If the WAL file is currently larger than nMax bytes in size, truncate
  56269. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  56270. */
  56271. static void walLimitSize(Wal *pWal, i64 nMax){
  56272. i64 sz;
  56273. int rx;
  56274. sqlite3BeginBenignMalloc();
  56275. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  56276. if( rx==SQLITE_OK && (sz > nMax ) ){
  56277. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  56278. }
  56279. sqlite3EndBenignMalloc();
  56280. if( rx ){
  56281. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  56282. }
  56283. }
  56284. /*
  56285. ** Close a connection to a log file.
  56286. */
  56287. SQLITE_PRIVATE int sqlite3WalClose(
  56288. Wal *pWal, /* Wal to close */
  56289. sqlite3 *db, /* For interrupt flag */
  56290. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  56291. int nBuf,
  56292. u8 *zBuf /* Buffer of at least nBuf bytes */
  56293. ){
  56294. int rc = SQLITE_OK;
  56295. if( pWal ){
  56296. int isDelete = 0; /* True to unlink wal and wal-index files */
  56297. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  56298. ** ordinary, rollback-mode locking methods, this guarantees that the
  56299. ** connection associated with this log file is the only connection to
  56300. ** the database. In this case checkpoint the database and unlink both
  56301. ** the wal and wal-index files.
  56302. **
  56303. ** The EXCLUSIVE lock is not released before returning.
  56304. */
  56305. if( zBuf!=0
  56306. && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
  56307. ){
  56308. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  56309. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  56310. }
  56311. rc = sqlite3WalCheckpoint(pWal, db,
  56312. SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  56313. );
  56314. if( rc==SQLITE_OK ){
  56315. int bPersist = -1;
  56316. sqlite3OsFileControlHint(
  56317. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  56318. );
  56319. if( bPersist!=1 ){
  56320. /* Try to delete the WAL file if the checkpoint completed and
  56321. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  56322. ** mode (!bPersist) */
  56323. isDelete = 1;
  56324. }else if( pWal->mxWalSize>=0 ){
  56325. /* Try to truncate the WAL file to zero bytes if the checkpoint
  56326. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  56327. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  56328. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  56329. ** to zero bytes as truncating to the journal_size_limit might
  56330. ** leave a corrupt WAL file on disk. */
  56331. walLimitSize(pWal, 0);
  56332. }
  56333. }
  56334. }
  56335. walIndexClose(pWal, isDelete);
  56336. sqlite3OsClose(pWal->pWalFd);
  56337. if( isDelete ){
  56338. sqlite3BeginBenignMalloc();
  56339. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  56340. sqlite3EndBenignMalloc();
  56341. }
  56342. WALTRACE(("WAL%p: closed\n", pWal));
  56343. sqlite3_free((void *)pWal->apWiData);
  56344. sqlite3_free(pWal);
  56345. }
  56346. return rc;
  56347. }
  56348. /*
  56349. ** Try to read the wal-index header. Return 0 on success and 1 if
  56350. ** there is a problem.
  56351. **
  56352. ** The wal-index is in shared memory. Another thread or process might
  56353. ** be writing the header at the same time this procedure is trying to
  56354. ** read it, which might result in inconsistency. A dirty read is detected
  56355. ** by verifying that both copies of the header are the same and also by
  56356. ** a checksum on the header.
  56357. **
  56358. ** If and only if the read is consistent and the header is different from
  56359. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  56360. ** and *pChanged is set to 1.
  56361. **
  56362. ** If the checksum cannot be verified return non-zero. If the header
  56363. ** is read successfully and the checksum verified, return zero.
  56364. */
  56365. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  56366. u32 aCksum[2]; /* Checksum on the header content */
  56367. WalIndexHdr h1, h2; /* Two copies of the header content */
  56368. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  56369. /* The first page of the wal-index must be mapped at this point. */
  56370. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  56371. /* Read the header. This might happen concurrently with a write to the
  56372. ** same area of shared memory on a different CPU in a SMP,
  56373. ** meaning it is possible that an inconsistent snapshot is read
  56374. ** from the file. If this happens, return non-zero.
  56375. **
  56376. ** There are two copies of the header at the beginning of the wal-index.
  56377. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  56378. ** Memory barriers are used to prevent the compiler or the hardware from
  56379. ** reordering the reads and writes.
  56380. */
  56381. aHdr = walIndexHdr(pWal);
  56382. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  56383. walShmBarrier(pWal);
  56384. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  56385. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  56386. return 1; /* Dirty read */
  56387. }
  56388. if( h1.isInit==0 ){
  56389. return 1; /* Malformed header - probably all zeros */
  56390. }
  56391. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  56392. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  56393. return 1; /* Checksum does not match */
  56394. }
  56395. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  56396. *pChanged = 1;
  56397. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  56398. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  56399. testcase( pWal->szPage<=32768 );
  56400. testcase( pWal->szPage>=65536 );
  56401. }
  56402. /* The header was successfully read. Return zero. */
  56403. return 0;
  56404. }
  56405. /*
  56406. ** This is the value that walTryBeginRead returns when it needs to
  56407. ** be retried.
  56408. */
  56409. #define WAL_RETRY (-1)
  56410. /*
  56411. ** Read the wal-index header from the wal-index and into pWal->hdr.
  56412. ** If the wal-header appears to be corrupt, try to reconstruct the
  56413. ** wal-index from the WAL before returning.
  56414. **
  56415. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  56416. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  56417. ** to 0.
  56418. **
  56419. ** If the wal-index header is successfully read, return SQLITE_OK.
  56420. ** Otherwise an SQLite error code.
  56421. */
  56422. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  56423. int rc; /* Return code */
  56424. int badHdr; /* True if a header read failed */
  56425. volatile u32 *page0; /* Chunk of wal-index containing header */
  56426. /* Ensure that page 0 of the wal-index (the page that contains the
  56427. ** wal-index header) is mapped. Return early if an error occurs here.
  56428. */
  56429. assert( pChanged );
  56430. rc = walIndexPage(pWal, 0, &page0);
  56431. if( rc!=SQLITE_OK ){
  56432. assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
  56433. if( rc==SQLITE_READONLY_CANTINIT ){
  56434. /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
  56435. ** was openable but is not writable, and this thread is unable to
  56436. ** confirm that another write-capable connection has the shared-memory
  56437. ** open, and hence the content of the shared-memory is unreliable,
  56438. ** since the shared-memory might be inconsistent with the WAL file
  56439. ** and there is no writer on hand to fix it. */
  56440. assert( page0==0 );
  56441. assert( pWal->writeLock==0 );
  56442. assert( pWal->readOnly & WAL_SHM_RDONLY );
  56443. pWal->bShmUnreliable = 1;
  56444. pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
  56445. *pChanged = 1;
  56446. }else{
  56447. return rc; /* Any other non-OK return is just an error */
  56448. }
  56449. }else{
  56450. /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
  56451. ** is zero, which prevents the SHM from growing */
  56452. testcase( page0!=0 );
  56453. }
  56454. assert( page0!=0 || pWal->writeLock==0 );
  56455. /* If the first page of the wal-index has been mapped, try to read the
  56456. ** wal-index header immediately, without holding any lock. This usually
  56457. ** works, but may fail if the wal-index header is corrupt or currently
  56458. ** being modified by another thread or process.
  56459. */
  56460. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  56461. /* If the first attempt failed, it might have been due to a race
  56462. ** with a writer. So get a WRITE lock and try again.
  56463. */
  56464. assert( badHdr==0 || pWal->writeLock==0 );
  56465. if( badHdr ){
  56466. if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
  56467. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  56468. walUnlockShared(pWal, WAL_WRITE_LOCK);
  56469. rc = SQLITE_READONLY_RECOVERY;
  56470. }
  56471. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  56472. pWal->writeLock = 1;
  56473. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  56474. badHdr = walIndexTryHdr(pWal, pChanged);
  56475. if( badHdr ){
  56476. /* If the wal-index header is still malformed even while holding
  56477. ** a WRITE lock, it can only mean that the header is corrupted and
  56478. ** needs to be reconstructed. So run recovery to do exactly that.
  56479. */
  56480. rc = walIndexRecover(pWal);
  56481. *pChanged = 1;
  56482. }
  56483. }
  56484. pWal->writeLock = 0;
  56485. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  56486. }
  56487. }
  56488. /* If the header is read successfully, check the version number to make
  56489. ** sure the wal-index was not constructed with some future format that
  56490. ** this version of SQLite cannot understand.
  56491. */
  56492. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  56493. rc = SQLITE_CANTOPEN_BKPT;
  56494. }
  56495. if( pWal->bShmUnreliable ){
  56496. if( rc!=SQLITE_OK ){
  56497. walIndexClose(pWal, 0);
  56498. pWal->bShmUnreliable = 0;
  56499. assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
  56500. /* walIndexRecover() might have returned SHORT_READ if a concurrent
  56501. ** writer truncated the WAL out from under it. If that happens, it
  56502. ** indicates that a writer has fixed the SHM file for us, so retry */
  56503. if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
  56504. }
  56505. pWal->exclusiveMode = WAL_NORMAL_MODE;
  56506. }
  56507. return rc;
  56508. }
  56509. /*
  56510. ** Open a transaction in a connection where the shared-memory is read-only
  56511. ** and where we cannot verify that there is a separate write-capable connection
  56512. ** on hand to keep the shared-memory up-to-date with the WAL file.
  56513. **
  56514. ** This can happen, for example, when the shared-memory is implemented by
  56515. ** memory-mapping a *-shm file, where a prior writer has shut down and
  56516. ** left the *-shm file on disk, and now the present connection is trying
  56517. ** to use that database but lacks write permission on the *-shm file.
  56518. ** Other scenarios are also possible, depending on the VFS implementation.
  56519. **
  56520. ** Precondition:
  56521. **
  56522. ** The *-wal file has been read and an appropriate wal-index has been
  56523. ** constructed in pWal->apWiData[] using heap memory instead of shared
  56524. ** memory.
  56525. **
  56526. ** If this function returns SQLITE_OK, then the read transaction has
  56527. ** been successfully opened. In this case output variable (*pChanged)
  56528. ** is set to true before returning if the caller should discard the
  56529. ** contents of the page cache before proceeding. Or, if it returns
  56530. ** WAL_RETRY, then the heap memory wal-index has been discarded and
  56531. ** the caller should retry opening the read transaction from the
  56532. ** beginning (including attempting to map the *-shm file).
  56533. **
  56534. ** If an error occurs, an SQLite error code is returned.
  56535. */
  56536. static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
  56537. i64 szWal; /* Size of wal file on disk in bytes */
  56538. i64 iOffset; /* Current offset when reading wal file */
  56539. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  56540. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  56541. int szFrame; /* Number of bytes in buffer aFrame[] */
  56542. u8 *aData; /* Pointer to data part of aFrame buffer */
  56543. volatile void *pDummy; /* Dummy argument for xShmMap */
  56544. int rc; /* Return code */
  56545. u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */
  56546. assert( pWal->bShmUnreliable );
  56547. assert( pWal->readOnly & WAL_SHM_RDONLY );
  56548. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  56549. /* Take WAL_READ_LOCK(0). This has the effect of preventing any
  56550. ** writers from running a checkpoint, but does not stop them
  56551. ** from running recovery. */
  56552. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  56553. if( rc!=SQLITE_OK ){
  56554. if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
  56555. goto begin_unreliable_shm_out;
  56556. }
  56557. pWal->readLock = 0;
  56558. /* Check to see if a separate writer has attached to the shared-memory area,
  56559. ** thus making the shared-memory "reliable" again. Do this by invoking
  56560. ** the xShmMap() routine of the VFS and looking to see if the return
  56561. ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
  56562. **
  56563. ** If the shared-memory is now "reliable" return WAL_RETRY, which will
  56564. ** cause the heap-memory WAL-index to be discarded and the actual
  56565. ** shared memory to be used in its place.
  56566. **
  56567. ** This step is important because, even though this connection is holding
  56568. ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
  56569. ** have already checkpointed the WAL file and, while the current
  56570. ** is active, wrap the WAL and start overwriting frames that this
  56571. ** process wants to use.
  56572. **
  56573. ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
  56574. ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
  56575. ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
  56576. ** even if some external agent does a "chmod" to make the shared-memory
  56577. ** writable by us, until sqlite3OsShmUnmap() has been called.
  56578. ** This is a requirement on the VFS implementation.
  56579. */
  56580. rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
  56581. assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
  56582. if( rc!=SQLITE_READONLY_CANTINIT ){
  56583. rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
  56584. goto begin_unreliable_shm_out;
  56585. }
  56586. /* We reach this point only if the real shared-memory is still unreliable.
  56587. ** Assume the in-memory WAL-index substitute is correct and load it
  56588. ** into pWal->hdr.
  56589. */
  56590. memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
  56591. /* Make sure some writer hasn't come in and changed the WAL file out
  56592. ** from under us, then disconnected, while we were not looking.
  56593. */
  56594. rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
  56595. if( rc!=SQLITE_OK ){
  56596. goto begin_unreliable_shm_out;
  56597. }
  56598. if( szWal<WAL_HDRSIZE ){
  56599. /* If the wal file is too small to contain a wal-header and the
  56600. ** wal-index header has mxFrame==0, then it must be safe to proceed
  56601. ** reading the database file only. However, the page cache cannot
  56602. ** be trusted, as a read/write connection may have connected, written
  56603. ** the db, run a checkpoint, truncated the wal file and disconnected
  56604. ** since this client's last read transaction. */
  56605. *pChanged = 1;
  56606. rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
  56607. goto begin_unreliable_shm_out;
  56608. }
  56609. /* Check the salt keys at the start of the wal file still match. */
  56610. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  56611. if( rc!=SQLITE_OK ){
  56612. goto begin_unreliable_shm_out;
  56613. }
  56614. if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
  56615. /* Some writer has wrapped the WAL file while we were not looking.
  56616. ** Return WAL_RETRY which will cause the in-memory WAL-index to be
  56617. ** rebuilt. */
  56618. rc = WAL_RETRY;
  56619. goto begin_unreliable_shm_out;
  56620. }
  56621. /* Allocate a buffer to read frames into */
  56622. szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE;
  56623. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  56624. if( aFrame==0 ){
  56625. rc = SQLITE_NOMEM_BKPT;
  56626. goto begin_unreliable_shm_out;
  56627. }
  56628. aData = &aFrame[WAL_FRAME_HDRSIZE];
  56629. /* Check to see if a complete transaction has been appended to the
  56630. ** wal file since the heap-memory wal-index was created. If so, the
  56631. ** heap-memory wal-index is discarded and WAL_RETRY returned to
  56632. ** the caller. */
  56633. aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
  56634. aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
  56635. for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage);
  56636. iOffset+szFrame<=szWal;
  56637. iOffset+=szFrame
  56638. ){
  56639. u32 pgno; /* Database page number for frame */
  56640. u32 nTruncate; /* dbsize field from frame header */
  56641. /* Read and decode the next log frame. */
  56642. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  56643. if( rc!=SQLITE_OK ) break;
  56644. if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
  56645. /* If nTruncate is non-zero, then a complete transaction has been
  56646. ** appended to this wal file. Set rc to WAL_RETRY and break out of
  56647. ** the loop. */
  56648. if( nTruncate ){
  56649. rc = WAL_RETRY;
  56650. break;
  56651. }
  56652. }
  56653. pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
  56654. pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
  56655. begin_unreliable_shm_out:
  56656. sqlite3_free(aFrame);
  56657. if( rc!=SQLITE_OK ){
  56658. int i;
  56659. for(i=0; i<pWal->nWiData; i++){
  56660. sqlite3_free((void*)pWal->apWiData[i]);
  56661. pWal->apWiData[i] = 0;
  56662. }
  56663. pWal->bShmUnreliable = 0;
  56664. sqlite3WalEndReadTransaction(pWal);
  56665. *pChanged = 1;
  56666. }
  56667. return rc;
  56668. }
  56669. /*
  56670. ** Attempt to start a read transaction. This might fail due to a race or
  56671. ** other transient condition. When that happens, it returns WAL_RETRY to
  56672. ** indicate to the caller that it is safe to retry immediately.
  56673. **
  56674. ** On success return SQLITE_OK. On a permanent failure (such an
  56675. ** I/O error or an SQLITE_BUSY because another process is running
  56676. ** recovery) return a positive error code.
  56677. **
  56678. ** The useWal parameter is true to force the use of the WAL and disable
  56679. ** the case where the WAL is bypassed because it has been completely
  56680. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  56681. ** to make a copy of the wal-index header into pWal->hdr. If the
  56682. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  56683. ** to the caller that the local page cache is obsolete and needs to be
  56684. ** flushed.) When useWal==1, the wal-index header is assumed to already
  56685. ** be loaded and the pChanged parameter is unused.
  56686. **
  56687. ** The caller must set the cnt parameter to the number of prior calls to
  56688. ** this routine during the current read attempt that returned WAL_RETRY.
  56689. ** This routine will start taking more aggressive measures to clear the
  56690. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  56691. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  56692. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  56693. ** and is not honoring the locking protocol. There is a vanishingly small
  56694. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  56695. ** bad luck when there is lots of contention for the wal-index, but that
  56696. ** possibility is so small that it can be safely neglected, we believe.
  56697. **
  56698. ** On success, this routine obtains a read lock on
  56699. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  56700. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  56701. ** that means the Wal does not hold any read lock. The reader must not
  56702. ** access any database page that is modified by a WAL frame up to and
  56703. ** including frame number aReadMark[pWal->readLock]. The reader will
  56704. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  56705. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  56706. ** completely and get all content directly from the database file.
  56707. ** If the useWal parameter is 1 then the WAL will never be ignored and
  56708. ** this routine will always set pWal->readLock>0 on success.
  56709. ** When the read transaction is completed, the caller must release the
  56710. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  56711. **
  56712. ** This routine uses the nBackfill and aReadMark[] fields of the header
  56713. ** to select a particular WAL_READ_LOCK() that strives to let the
  56714. ** checkpoint process do as much work as possible. This routine might
  56715. ** update values of the aReadMark[] array in the header, but if it does
  56716. ** so it takes care to hold an exclusive lock on the corresponding
  56717. ** WAL_READ_LOCK() while changing values.
  56718. */
  56719. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  56720. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  56721. u32 mxReadMark; /* Largest aReadMark[] value */
  56722. int mxI; /* Index of largest aReadMark[] value */
  56723. int i; /* Loop counter */
  56724. int rc = SQLITE_OK; /* Return code */
  56725. u32 mxFrame; /* Wal frame to lock to */
  56726. assert( pWal->readLock<0 ); /* Not currently locked */
  56727. /* useWal may only be set for read/write connections */
  56728. assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
  56729. /* Take steps to avoid spinning forever if there is a protocol error.
  56730. **
  56731. ** Circumstances that cause a RETRY should only last for the briefest
  56732. ** instances of time. No I/O or other system calls are done while the
  56733. ** locks are held, so the locks should not be held for very long. But
  56734. ** if we are unlucky, another process that is holding a lock might get
  56735. ** paged out or take a page-fault that is time-consuming to resolve,
  56736. ** during the few nanoseconds that it is holding the lock. In that case,
  56737. ** it might take longer than normal for the lock to free.
  56738. **
  56739. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  56740. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  56741. ** is more of a scheduler yield than an actual delay. But on the 10th
  56742. ** an subsequent retries, the delays start becoming longer and longer,
  56743. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  56744. ** The total delay time before giving up is less than 10 seconds.
  56745. */
  56746. if( cnt>5 ){
  56747. int nDelay = 1; /* Pause time in microseconds */
  56748. if( cnt>100 ){
  56749. VVA_ONLY( pWal->lockError = 1; )
  56750. return SQLITE_PROTOCOL;
  56751. }
  56752. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  56753. sqlite3OsSleep(pWal->pVfs, nDelay);
  56754. }
  56755. if( !useWal ){
  56756. assert( rc==SQLITE_OK );
  56757. if( pWal->bShmUnreliable==0 ){
  56758. rc = walIndexReadHdr(pWal, pChanged);
  56759. }
  56760. if( rc==SQLITE_BUSY ){
  56761. /* If there is not a recovery running in another thread or process
  56762. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  56763. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  56764. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  56765. ** would be technically correct. But the race is benign since with
  56766. ** WAL_RETRY this routine will be called again and will probably be
  56767. ** right on the second iteration.
  56768. */
  56769. if( pWal->apWiData[0]==0 ){
  56770. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  56771. ** We assume this is a transient condition, so return WAL_RETRY. The
  56772. ** xShmMap() implementation used by the default unix and win32 VFS
  56773. ** modules may return SQLITE_BUSY due to a race condition in the
  56774. ** code that determines whether or not the shared-memory region
  56775. ** must be zeroed before the requested page is returned.
  56776. */
  56777. rc = WAL_RETRY;
  56778. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  56779. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  56780. rc = WAL_RETRY;
  56781. }else if( rc==SQLITE_BUSY ){
  56782. rc = SQLITE_BUSY_RECOVERY;
  56783. }
  56784. }
  56785. if( rc!=SQLITE_OK ){
  56786. return rc;
  56787. }
  56788. else if( pWal->bShmUnreliable ){
  56789. return walBeginShmUnreliable(pWal, pChanged);
  56790. }
  56791. }
  56792. assert( pWal->nWiData>0 );
  56793. assert( pWal->apWiData[0]!=0 );
  56794. pInfo = walCkptInfo(pWal);
  56795. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
  56796. #ifdef SQLITE_ENABLE_SNAPSHOT
  56797. && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
  56798. #endif
  56799. ){
  56800. /* The WAL has been completely backfilled (or it is empty).
  56801. ** and can be safely ignored.
  56802. */
  56803. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  56804. walShmBarrier(pWal);
  56805. if( rc==SQLITE_OK ){
  56806. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  56807. /* It is not safe to allow the reader to continue here if frames
  56808. ** may have been appended to the log before READ_LOCK(0) was obtained.
  56809. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  56810. ** which implies that the database file contains a trustworthy
  56811. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  56812. ** happening, this is usually correct.
  56813. **
  56814. ** However, if frames have been appended to the log (or if the log
  56815. ** is wrapped and written for that matter) before the READ_LOCK(0)
  56816. ** is obtained, that is not necessarily true. A checkpointer may
  56817. ** have started to backfill the appended frames but crashed before
  56818. ** it finished. Leaving a corrupt image in the database file.
  56819. */
  56820. walUnlockShared(pWal, WAL_READ_LOCK(0));
  56821. return WAL_RETRY;
  56822. }
  56823. pWal->readLock = 0;
  56824. return SQLITE_OK;
  56825. }else if( rc!=SQLITE_BUSY ){
  56826. return rc;
  56827. }
  56828. }
  56829. /* If we get this far, it means that the reader will want to use
  56830. ** the WAL to get at content from recent commits. The job now is
  56831. ** to select one of the aReadMark[] entries that is closest to
  56832. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  56833. */
  56834. mxReadMark = 0;
  56835. mxI = 0;
  56836. mxFrame = pWal->hdr.mxFrame;
  56837. #ifdef SQLITE_ENABLE_SNAPSHOT
  56838. if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
  56839. mxFrame = pWal->pSnapshot->mxFrame;
  56840. }
  56841. #endif
  56842. for(i=1; i<WAL_NREADER; i++){
  56843. u32 thisMark = AtomicLoad(pInfo->aReadMark+i);
  56844. if( mxReadMark<=thisMark && thisMark<=mxFrame ){
  56845. assert( thisMark!=READMARK_NOT_USED );
  56846. mxReadMark = thisMark;
  56847. mxI = i;
  56848. }
  56849. }
  56850. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  56851. && (mxReadMark<mxFrame || mxI==0)
  56852. ){
  56853. for(i=1; i<WAL_NREADER; i++){
  56854. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  56855. if( rc==SQLITE_OK ){
  56856. mxReadMark = AtomicStore(pInfo->aReadMark+i,mxFrame);
  56857. mxI = i;
  56858. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  56859. break;
  56860. }else if( rc!=SQLITE_BUSY ){
  56861. return rc;
  56862. }
  56863. }
  56864. }
  56865. if( mxI==0 ){
  56866. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  56867. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
  56868. }
  56869. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  56870. if( rc ){
  56871. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  56872. }
  56873. /* Now that the read-lock has been obtained, check that neither the
  56874. ** value in the aReadMark[] array or the contents of the wal-index
  56875. ** header have changed.
  56876. **
  56877. ** It is necessary to check that the wal-index header did not change
  56878. ** between the time it was read and when the shared-lock was obtained
  56879. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  56880. ** that the log file may have been wrapped by a writer, or that frames
  56881. ** that occur later in the log than pWal->hdr.mxFrame may have been
  56882. ** copied into the database by a checkpointer. If either of these things
  56883. ** happened, then reading the database with the current value of
  56884. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  56885. ** instead.
  56886. **
  56887. ** Before checking that the live wal-index header has not changed
  56888. ** since it was read, set Wal.minFrame to the first frame in the wal
  56889. ** file that has not yet been checkpointed. This client will not need
  56890. ** to read any frames earlier than minFrame from the wal file - they
  56891. ** can be safely read directly from the database file.
  56892. **
  56893. ** Because a ShmBarrier() call is made between taking the copy of
  56894. ** nBackfill and checking that the wal-header in shared-memory still
  56895. ** matches the one cached in pWal->hdr, it is guaranteed that the
  56896. ** checkpointer that set nBackfill was not working with a wal-index
  56897. ** header newer than that cached in pWal->hdr. If it were, that could
  56898. ** cause a problem. The checkpointer could omit to checkpoint
  56899. ** a version of page X that lies before pWal->minFrame (call that version
  56900. ** A) on the basis that there is a newer version (version B) of the same
  56901. ** page later in the wal file. But if version B happens to like past
  56902. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  56903. ** that it can read version A from the database file. However, since
  56904. ** we can guarantee that the checkpointer that set nBackfill could not
  56905. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  56906. */
  56907. pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1;
  56908. walShmBarrier(pWal);
  56909. if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
  56910. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  56911. ){
  56912. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  56913. return WAL_RETRY;
  56914. }else{
  56915. assert( mxReadMark<=pWal->hdr.mxFrame );
  56916. pWal->readLock = (i16)mxI;
  56917. }
  56918. return rc;
  56919. }
  56920. #ifdef SQLITE_ENABLE_SNAPSHOT
  56921. /*
  56922. ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
  56923. ** variable so that older snapshots can be accessed. To do this, loop
  56924. ** through all wal frames from nBackfillAttempted to (nBackfill+1),
  56925. ** comparing their content to the corresponding page with the database
  56926. ** file, if any. Set nBackfillAttempted to the frame number of the
  56927. ** first frame for which the wal file content matches the db file.
  56928. **
  56929. ** This is only really safe if the file-system is such that any page
  56930. ** writes made by earlier checkpointers were atomic operations, which
  56931. ** is not always true. It is also possible that nBackfillAttempted
  56932. ** may be left set to a value larger than expected, if a wal frame
  56933. ** contains content that duplicate of an earlier version of the same
  56934. ** page.
  56935. **
  56936. ** SQLITE_OK is returned if successful, or an SQLite error code if an
  56937. ** error occurs. It is not an error if nBackfillAttempted cannot be
  56938. ** decreased at all.
  56939. */
  56940. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
  56941. int rc;
  56942. assert( pWal->readLock>=0 );
  56943. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  56944. if( rc==SQLITE_OK ){
  56945. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  56946. int szPage = (int)pWal->szPage;
  56947. i64 szDb; /* Size of db file in bytes */
  56948. rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
  56949. if( rc==SQLITE_OK ){
  56950. void *pBuf1 = sqlite3_malloc(szPage);
  56951. void *pBuf2 = sqlite3_malloc(szPage);
  56952. if( pBuf1==0 || pBuf2==0 ){
  56953. rc = SQLITE_NOMEM;
  56954. }else{
  56955. u32 i = pInfo->nBackfillAttempted;
  56956. for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
  56957. WalHashLoc sLoc; /* Hash table location */
  56958. u32 pgno; /* Page number in db file */
  56959. i64 iDbOff; /* Offset of db file entry */
  56960. i64 iWalOff; /* Offset of wal file entry */
  56961. rc = walHashGet(pWal, walFramePage(i), &sLoc);
  56962. if( rc!=SQLITE_OK ) break;
  56963. pgno = sLoc.aPgno[i-sLoc.iZero];
  56964. iDbOff = (i64)(pgno-1) * szPage;
  56965. if( iDbOff+szPage<=szDb ){
  56966. iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
  56967. rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
  56968. if( rc==SQLITE_OK ){
  56969. rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
  56970. }
  56971. if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
  56972. break;
  56973. }
  56974. }
  56975. pInfo->nBackfillAttempted = i-1;
  56976. }
  56977. }
  56978. sqlite3_free(pBuf1);
  56979. sqlite3_free(pBuf2);
  56980. }
  56981. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  56982. }
  56983. return rc;
  56984. }
  56985. #endif /* SQLITE_ENABLE_SNAPSHOT */
  56986. /*
  56987. ** Begin a read transaction on the database.
  56988. **
  56989. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  56990. ** it takes a snapshot of the state of the WAL and wal-index for the current
  56991. ** instant in time. The current thread will continue to use this snapshot.
  56992. ** Other threads might append new content to the WAL and wal-index but
  56993. ** that extra content is ignored by the current thread.
  56994. **
  56995. ** If the database contents have changes since the previous read
  56996. ** transaction, then *pChanged is set to 1 before returning. The
  56997. ** Pager layer will use this to know that its cache is stale and
  56998. ** needs to be flushed.
  56999. */
  57000. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  57001. int rc; /* Return code */
  57002. int cnt = 0; /* Number of TryBeginRead attempts */
  57003. #ifdef SQLITE_ENABLE_SNAPSHOT
  57004. int bChanged = 0;
  57005. WalIndexHdr *pSnapshot = pWal->pSnapshot;
  57006. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  57007. bChanged = 1;
  57008. }
  57009. #endif
  57010. do{
  57011. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  57012. }while( rc==WAL_RETRY );
  57013. testcase( (rc&0xff)==SQLITE_BUSY );
  57014. testcase( (rc&0xff)==SQLITE_IOERR );
  57015. testcase( rc==SQLITE_PROTOCOL );
  57016. testcase( rc==SQLITE_OK );
  57017. #ifdef SQLITE_ENABLE_SNAPSHOT
  57018. if( rc==SQLITE_OK ){
  57019. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  57020. /* At this point the client has a lock on an aReadMark[] slot holding
  57021. ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
  57022. ** is populated with the wal-index header corresponding to the head
  57023. ** of the wal file. Verify that pSnapshot is still valid before
  57024. ** continuing. Reasons why pSnapshot might no longer be valid:
  57025. **
  57026. ** (1) The WAL file has been reset since the snapshot was taken.
  57027. ** In this case, the salt will have changed.
  57028. **
  57029. ** (2) A checkpoint as been attempted that wrote frames past
  57030. ** pSnapshot->mxFrame into the database file. Note that the
  57031. ** checkpoint need not have completed for this to cause problems.
  57032. */
  57033. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  57034. assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
  57035. assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
  57036. /* It is possible that there is a checkpointer thread running
  57037. ** concurrent with this code. If this is the case, it may be that the
  57038. ** checkpointer has already determined that it will checkpoint
  57039. ** snapshot X, where X is later in the wal file than pSnapshot, but
  57040. ** has not yet set the pInfo->nBackfillAttempted variable to indicate
  57041. ** its intent. To avoid the race condition this leads to, ensure that
  57042. ** there is no checkpointer process by taking a shared CKPT lock
  57043. ** before checking pInfo->nBackfillAttempted.
  57044. **
  57045. ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
  57046. ** this already?
  57047. */
  57048. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  57049. if( rc==SQLITE_OK ){
  57050. /* Check that the wal file has not been wrapped. Assuming that it has
  57051. ** not, also check that no checkpointer has attempted to checkpoint any
  57052. ** frames beyond pSnapshot->mxFrame. If either of these conditions are
  57053. ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
  57054. ** with *pSnapshot and set *pChanged as appropriate for opening the
  57055. ** snapshot. */
  57056. if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  57057. && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
  57058. ){
  57059. assert( pWal->readLock>0 );
  57060. memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
  57061. *pChanged = bChanged;
  57062. }else{
  57063. rc = SQLITE_ERROR_SNAPSHOT;
  57064. }
  57065. /* Release the shared CKPT lock obtained above. */
  57066. walUnlockShared(pWal, WAL_CKPT_LOCK);
  57067. pWal->minFrame = 1;
  57068. }
  57069. if( rc!=SQLITE_OK ){
  57070. sqlite3WalEndReadTransaction(pWal);
  57071. }
  57072. }
  57073. }
  57074. #endif
  57075. return rc;
  57076. }
  57077. /*
  57078. ** Finish with a read transaction. All this does is release the
  57079. ** read-lock.
  57080. */
  57081. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  57082. sqlite3WalEndWriteTransaction(pWal);
  57083. if( pWal->readLock>=0 ){
  57084. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  57085. pWal->readLock = -1;
  57086. }
  57087. }
  57088. /*
  57089. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  57090. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  57091. ** to zero.
  57092. **
  57093. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  57094. ** error does occur, the final value of *piRead is undefined.
  57095. */
  57096. SQLITE_PRIVATE int sqlite3WalFindFrame(
  57097. Wal *pWal, /* WAL handle */
  57098. Pgno pgno, /* Database page number to read data for */
  57099. u32 *piRead /* OUT: Frame number (or zero) */
  57100. ){
  57101. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  57102. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  57103. int iHash; /* Used to loop through N hash tables */
  57104. int iMinHash;
  57105. /* This routine is only be called from within a read transaction. */
  57106. assert( pWal->readLock>=0 || pWal->lockError );
  57107. /* If the "last page" field of the wal-index header snapshot is 0, then
  57108. ** no data will be read from the wal under any circumstances. Return early
  57109. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  57110. ** then the WAL is ignored by the reader so return early, as if the
  57111. ** WAL were empty.
  57112. */
  57113. if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
  57114. *piRead = 0;
  57115. return SQLITE_OK;
  57116. }
  57117. /* Search the hash table or tables for an entry matching page number
  57118. ** pgno. Each iteration of the following for() loop searches one
  57119. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  57120. **
  57121. ** This code might run concurrently to the code in walIndexAppend()
  57122. ** that adds entries to the wal-index (and possibly to this hash
  57123. ** table). This means the value just read from the hash
  57124. ** slot (aHash[iKey]) may have been added before or after the
  57125. ** current read transaction was opened. Values added after the
  57126. ** read transaction was opened may have been written incorrectly -
  57127. ** i.e. these slots may contain garbage data. However, we assume
  57128. ** that any slots written before the current read transaction was
  57129. ** opened remain unmodified.
  57130. **
  57131. ** For the reasons above, the if(...) condition featured in the inner
  57132. ** loop of the following block is more stringent that would be required
  57133. ** if we had exclusive access to the hash-table:
  57134. **
  57135. ** (aPgno[iFrame]==pgno):
  57136. ** This condition filters out normal hash-table collisions.
  57137. **
  57138. ** (iFrame<=iLast):
  57139. ** This condition filters out entries that were added to the hash
  57140. ** table after the current read-transaction had started.
  57141. */
  57142. iMinHash = walFramePage(pWal->minFrame);
  57143. for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
  57144. WalHashLoc sLoc; /* Hash table location */
  57145. int iKey; /* Hash slot index */
  57146. int nCollide; /* Number of hash collisions remaining */
  57147. int rc; /* Error code */
  57148. rc = walHashGet(pWal, iHash, &sLoc);
  57149. if( rc!=SQLITE_OK ){
  57150. return rc;
  57151. }
  57152. nCollide = HASHTABLE_NSLOT;
  57153. for(iKey=walHash(pgno); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
  57154. u32 iFrame = sLoc.aHash[iKey] + sLoc.iZero;
  57155. if( iFrame<=iLast && iFrame>=pWal->minFrame
  57156. && sLoc.aPgno[sLoc.aHash[iKey]]==pgno ){
  57157. assert( iFrame>iRead || CORRUPT_DB );
  57158. iRead = iFrame;
  57159. }
  57160. if( (nCollide--)==0 ){
  57161. return SQLITE_CORRUPT_BKPT;
  57162. }
  57163. }
  57164. if( iRead ) break;
  57165. }
  57166. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  57167. /* If expensive assert() statements are available, do a linear search
  57168. ** of the wal-index file content. Make sure the results agree with the
  57169. ** result obtained using the hash indexes above. */
  57170. {
  57171. u32 iRead2 = 0;
  57172. u32 iTest;
  57173. assert( pWal->bShmUnreliable || pWal->minFrame>0 );
  57174. for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
  57175. if( walFramePgno(pWal, iTest)==pgno ){
  57176. iRead2 = iTest;
  57177. break;
  57178. }
  57179. }
  57180. assert( iRead==iRead2 );
  57181. }
  57182. #endif
  57183. *piRead = iRead;
  57184. return SQLITE_OK;
  57185. }
  57186. /*
  57187. ** Read the contents of frame iRead from the wal file into buffer pOut
  57188. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  57189. ** error code otherwise.
  57190. */
  57191. SQLITE_PRIVATE int sqlite3WalReadFrame(
  57192. Wal *pWal, /* WAL handle */
  57193. u32 iRead, /* Frame to read */
  57194. int nOut, /* Size of buffer pOut in bytes */
  57195. u8 *pOut /* Buffer to write page data to */
  57196. ){
  57197. int sz;
  57198. i64 iOffset;
  57199. sz = pWal->hdr.szPage;
  57200. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  57201. testcase( sz<=32768 );
  57202. testcase( sz>=65536 );
  57203. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  57204. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  57205. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  57206. }
  57207. /*
  57208. ** Return the size of the database in pages (or zero, if unknown).
  57209. */
  57210. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  57211. if( pWal && ALWAYS(pWal->readLock>=0) ){
  57212. return pWal->hdr.nPage;
  57213. }
  57214. return 0;
  57215. }
  57216. /*
  57217. ** This function starts a write transaction on the WAL.
  57218. **
  57219. ** A read transaction must have already been started by a prior call
  57220. ** to sqlite3WalBeginReadTransaction().
  57221. **
  57222. ** If another thread or process has written into the database since
  57223. ** the read transaction was started, then it is not possible for this
  57224. ** thread to write as doing so would cause a fork. So this routine
  57225. ** returns SQLITE_BUSY in that case and no write transaction is started.
  57226. **
  57227. ** There can only be a single writer active at a time.
  57228. */
  57229. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  57230. int rc;
  57231. /* Cannot start a write transaction without first holding a read
  57232. ** transaction. */
  57233. assert( pWal->readLock>=0 );
  57234. assert( pWal->writeLock==0 && pWal->iReCksum==0 );
  57235. if( pWal->readOnly ){
  57236. return SQLITE_READONLY;
  57237. }
  57238. /* Only one writer allowed at a time. Get the write lock. Return
  57239. ** SQLITE_BUSY if unable.
  57240. */
  57241. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57242. if( rc ){
  57243. return rc;
  57244. }
  57245. pWal->writeLock = 1;
  57246. /* If another connection has written to the database file since the
  57247. ** time the read transaction on this connection was started, then
  57248. ** the write is disallowed.
  57249. */
  57250. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  57251. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57252. pWal->writeLock = 0;
  57253. rc = SQLITE_BUSY_SNAPSHOT;
  57254. }
  57255. return rc;
  57256. }
  57257. /*
  57258. ** End a write transaction. The commit has already been done. This
  57259. ** routine merely releases the lock.
  57260. */
  57261. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  57262. if( pWal->writeLock ){
  57263. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57264. pWal->writeLock = 0;
  57265. pWal->iReCksum = 0;
  57266. pWal->truncateOnCommit = 0;
  57267. }
  57268. return SQLITE_OK;
  57269. }
  57270. /*
  57271. ** If any data has been written (but not committed) to the log file, this
  57272. ** function moves the write-pointer back to the start of the transaction.
  57273. **
  57274. ** Additionally, the callback function is invoked for each frame written
  57275. ** to the WAL since the start of the transaction. If the callback returns
  57276. ** other than SQLITE_OK, it is not invoked again and the error code is
  57277. ** returned to the caller.
  57278. **
  57279. ** Otherwise, if the callback function does not return an error, this
  57280. ** function returns SQLITE_OK.
  57281. */
  57282. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  57283. int rc = SQLITE_OK;
  57284. if( ALWAYS(pWal->writeLock) ){
  57285. Pgno iMax = pWal->hdr.mxFrame;
  57286. Pgno iFrame;
  57287. /* Restore the clients cache of the wal-index header to the state it
  57288. ** was in before the client began writing to the database.
  57289. */
  57290. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  57291. for(iFrame=pWal->hdr.mxFrame+1;
  57292. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  57293. iFrame++
  57294. ){
  57295. /* This call cannot fail. Unless the page for which the page number
  57296. ** is passed as the second argument is (a) in the cache and
  57297. ** (b) has an outstanding reference, then xUndo is either a no-op
  57298. ** (if (a) is false) or simply expels the page from the cache (if (b)
  57299. ** is false).
  57300. **
  57301. ** If the upper layer is doing a rollback, it is guaranteed that there
  57302. ** are no outstanding references to any page other than page 1. And
  57303. ** page 1 is never written to the log until the transaction is
  57304. ** committed. As a result, the call to xUndo may not fail.
  57305. */
  57306. assert( walFramePgno(pWal, iFrame)!=1 );
  57307. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  57308. }
  57309. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  57310. }
  57311. return rc;
  57312. }
  57313. /*
  57314. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  57315. ** values. This function populates the array with values required to
  57316. ** "rollback" the write position of the WAL handle back to the current
  57317. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  57318. */
  57319. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  57320. assert( pWal->writeLock );
  57321. aWalData[0] = pWal->hdr.mxFrame;
  57322. aWalData[1] = pWal->hdr.aFrameCksum[0];
  57323. aWalData[2] = pWal->hdr.aFrameCksum[1];
  57324. aWalData[3] = pWal->nCkpt;
  57325. }
  57326. /*
  57327. ** Move the write position of the WAL back to the point identified by
  57328. ** the values in the aWalData[] array. aWalData must point to an array
  57329. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  57330. ** by a call to WalSavepoint().
  57331. */
  57332. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  57333. int rc = SQLITE_OK;
  57334. assert( pWal->writeLock );
  57335. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  57336. if( aWalData[3]!=pWal->nCkpt ){
  57337. /* This savepoint was opened immediately after the write-transaction
  57338. ** was started. Right after that, the writer decided to wrap around
  57339. ** to the start of the log. Update the savepoint values to match.
  57340. */
  57341. aWalData[0] = 0;
  57342. aWalData[3] = pWal->nCkpt;
  57343. }
  57344. if( aWalData[0]<pWal->hdr.mxFrame ){
  57345. pWal->hdr.mxFrame = aWalData[0];
  57346. pWal->hdr.aFrameCksum[0] = aWalData[1];
  57347. pWal->hdr.aFrameCksum[1] = aWalData[2];
  57348. walCleanupHash(pWal);
  57349. }
  57350. return rc;
  57351. }
  57352. /*
  57353. ** This function is called just before writing a set of frames to the log
  57354. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  57355. ** to the current log file, it is possible to overwrite the start of the
  57356. ** existing log file with the new frames (i.e. "reset" the log). If so,
  57357. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  57358. ** unchanged.
  57359. **
  57360. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  57361. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  57362. ** if an error occurs.
  57363. */
  57364. static int walRestartLog(Wal *pWal){
  57365. int rc = SQLITE_OK;
  57366. int cnt;
  57367. if( pWal->readLock==0 ){
  57368. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  57369. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  57370. if( pInfo->nBackfill>0 ){
  57371. u32 salt1;
  57372. sqlite3_randomness(4, &salt1);
  57373. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  57374. if( rc==SQLITE_OK ){
  57375. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  57376. ** readers are currently using the WAL), then the transactions
  57377. ** frames will overwrite the start of the existing log. Update the
  57378. ** wal-index header to reflect this.
  57379. **
  57380. ** In theory it would be Ok to update the cache of the header only
  57381. ** at this point. But updating the actual wal-index header is also
  57382. ** safe and means there is no special case for sqlite3WalUndo()
  57383. ** to handle if this transaction is rolled back. */
  57384. walRestartHdr(pWal, salt1);
  57385. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  57386. }else if( rc!=SQLITE_BUSY ){
  57387. return rc;
  57388. }
  57389. }
  57390. walUnlockShared(pWal, WAL_READ_LOCK(0));
  57391. pWal->readLock = -1;
  57392. cnt = 0;
  57393. do{
  57394. int notUsed;
  57395. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  57396. }while( rc==WAL_RETRY );
  57397. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  57398. testcase( (rc&0xff)==SQLITE_IOERR );
  57399. testcase( rc==SQLITE_PROTOCOL );
  57400. testcase( rc==SQLITE_OK );
  57401. }
  57402. return rc;
  57403. }
  57404. /*
  57405. ** Information about the current state of the WAL file and where
  57406. ** the next fsync should occur - passed from sqlite3WalFrames() into
  57407. ** walWriteToLog().
  57408. */
  57409. typedef struct WalWriter {
  57410. Wal *pWal; /* The complete WAL information */
  57411. sqlite3_file *pFd; /* The WAL file to which we write */
  57412. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  57413. int syncFlags; /* Flags for the fsync */
  57414. int szPage; /* Size of one page */
  57415. } WalWriter;
  57416. /*
  57417. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  57418. ** Do a sync when crossing the p->iSyncPoint boundary.
  57419. **
  57420. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  57421. ** first write the part before iSyncPoint, then sync, then write the
  57422. ** rest.
  57423. */
  57424. static int walWriteToLog(
  57425. WalWriter *p, /* WAL to write to */
  57426. void *pContent, /* Content to be written */
  57427. int iAmt, /* Number of bytes to write */
  57428. sqlite3_int64 iOffset /* Start writing at this offset */
  57429. ){
  57430. int rc;
  57431. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  57432. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  57433. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  57434. if( rc ) return rc;
  57435. iOffset += iFirstAmt;
  57436. iAmt -= iFirstAmt;
  57437. pContent = (void*)(iFirstAmt + (char*)pContent);
  57438. assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
  57439. rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
  57440. if( iAmt==0 || rc ) return rc;
  57441. }
  57442. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  57443. return rc;
  57444. }
  57445. /*
  57446. ** Write out a single frame of the WAL
  57447. */
  57448. static int walWriteOneFrame(
  57449. WalWriter *p, /* Where to write the frame */
  57450. PgHdr *pPage, /* The page of the frame to be written */
  57451. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  57452. sqlite3_int64 iOffset /* Byte offset at which to write */
  57453. ){
  57454. int rc; /* Result code from subfunctions */
  57455. void *pData; /* Data actually written */
  57456. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  57457. #if defined(SQLITE_HAS_CODEC)
  57458. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
  57459. #else
  57460. pData = pPage->pData;
  57461. #endif
  57462. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  57463. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  57464. if( rc ) return rc;
  57465. /* Write the page data */
  57466. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  57467. return rc;
  57468. }
  57469. /*
  57470. ** This function is called as part of committing a transaction within which
  57471. ** one or more frames have been overwritten. It updates the checksums for
  57472. ** all frames written to the wal file by the current transaction starting
  57473. ** with the earliest to have been overwritten.
  57474. **
  57475. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  57476. */
  57477. static int walRewriteChecksums(Wal *pWal, u32 iLast){
  57478. const int szPage = pWal->szPage;/* Database page size */
  57479. int rc = SQLITE_OK; /* Return code */
  57480. u8 *aBuf; /* Buffer to load data from wal file into */
  57481. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
  57482. u32 iRead; /* Next frame to read from wal file */
  57483. i64 iCksumOff;
  57484. aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
  57485. if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
  57486. /* Find the checksum values to use as input for the recalculating the
  57487. ** first checksum. If the first frame is frame 1 (implying that the current
  57488. ** transaction restarted the wal file), these values must be read from the
  57489. ** wal-file header. Otherwise, read them from the frame header of the
  57490. ** previous frame. */
  57491. assert( pWal->iReCksum>0 );
  57492. if( pWal->iReCksum==1 ){
  57493. iCksumOff = 24;
  57494. }else{
  57495. iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
  57496. }
  57497. rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  57498. pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
  57499. pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
  57500. iRead = pWal->iReCksum;
  57501. pWal->iReCksum = 0;
  57502. for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
  57503. i64 iOff = walFrameOffset(iRead, szPage);
  57504. rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
  57505. if( rc==SQLITE_OK ){
  57506. u32 iPgno, nDbSize;
  57507. iPgno = sqlite3Get4byte(aBuf);
  57508. nDbSize = sqlite3Get4byte(&aBuf[4]);
  57509. walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
  57510. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
  57511. }
  57512. }
  57513. sqlite3_free(aBuf);
  57514. return rc;
  57515. }
  57516. /*
  57517. ** Write a set of frames to the log. The caller must hold the write-lock
  57518. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  57519. */
  57520. SQLITE_PRIVATE int sqlite3WalFrames(
  57521. Wal *pWal, /* Wal handle to write to */
  57522. int szPage, /* Database page-size in bytes */
  57523. PgHdr *pList, /* List of dirty pages to write */
  57524. Pgno nTruncate, /* Database size after this commit */
  57525. int isCommit, /* True if this is a commit */
  57526. int sync_flags /* Flags to pass to OsSync() (or 0) */
  57527. ){
  57528. int rc; /* Used to catch return codes */
  57529. u32 iFrame; /* Next frame address */
  57530. PgHdr *p; /* Iterator to run through pList with. */
  57531. PgHdr *pLast = 0; /* Last frame in list */
  57532. int nExtra = 0; /* Number of extra copies of last page */
  57533. int szFrame; /* The size of a single frame */
  57534. i64 iOffset; /* Next byte to write in WAL file */
  57535. WalWriter w; /* The writer */
  57536. u32 iFirst = 0; /* First frame that may be overwritten */
  57537. WalIndexHdr *pLive; /* Pointer to shared header */
  57538. assert( pList );
  57539. assert( pWal->writeLock );
  57540. /* If this frame set completes a transaction, then nTruncate>0. If
  57541. ** nTruncate==0 then this frame set does not complete the transaction. */
  57542. assert( (isCommit!=0)==(nTruncate!=0) );
  57543. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  57544. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  57545. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  57546. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  57547. }
  57548. #endif
  57549. pLive = (WalIndexHdr*)walIndexHdr(pWal);
  57550. if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
  57551. iFirst = pLive->mxFrame+1;
  57552. }
  57553. /* See if it is possible to write these frames into the start of the
  57554. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  57555. */
  57556. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  57557. return rc;
  57558. }
  57559. /* If this is the first frame written into the log, write the WAL
  57560. ** header to the start of the WAL file. See comments at the top of
  57561. ** this source file for a description of the WAL header format.
  57562. */
  57563. iFrame = pWal->hdr.mxFrame;
  57564. if( iFrame==0 ){
  57565. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  57566. u32 aCksum[2]; /* Checksum for wal-header */
  57567. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  57568. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  57569. sqlite3Put4byte(&aWalHdr[8], szPage);
  57570. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  57571. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  57572. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  57573. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  57574. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  57575. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  57576. pWal->szPage = szPage;
  57577. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  57578. pWal->hdr.aFrameCksum[0] = aCksum[0];
  57579. pWal->hdr.aFrameCksum[1] = aCksum[1];
  57580. pWal->truncateOnCommit = 1;
  57581. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  57582. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  57583. if( rc!=SQLITE_OK ){
  57584. return rc;
  57585. }
  57586. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  57587. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  57588. ** an out-of-order write following a WAL restart could result in
  57589. ** database corruption. See the ticket:
  57590. **
  57591. ** https://sqlite.org/src/info/ff5be73dee
  57592. */
  57593. if( pWal->syncHeader ){
  57594. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  57595. if( rc ) return rc;
  57596. }
  57597. }
  57598. assert( (int)pWal->szPage==szPage );
  57599. /* Setup information needed to write frames into the WAL */
  57600. w.pWal = pWal;
  57601. w.pFd = pWal->pWalFd;
  57602. w.iSyncPoint = 0;
  57603. w.syncFlags = sync_flags;
  57604. w.szPage = szPage;
  57605. iOffset = walFrameOffset(iFrame+1, szPage);
  57606. szFrame = szPage + WAL_FRAME_HDRSIZE;
  57607. /* Write all frames into the log file exactly once */
  57608. for(p=pList; p; p=p->pDirty){
  57609. int nDbSize; /* 0 normally. Positive == commit flag */
  57610. /* Check if this page has already been written into the wal file by
  57611. ** the current transaction. If so, overwrite the existing frame and
  57612. ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
  57613. ** checksums must be recomputed when the transaction is committed. */
  57614. if( iFirst && (p->pDirty || isCommit==0) ){
  57615. u32 iWrite = 0;
  57616. VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
  57617. assert( rc==SQLITE_OK || iWrite==0 );
  57618. if( iWrite>=iFirst ){
  57619. i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
  57620. void *pData;
  57621. if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
  57622. pWal->iReCksum = iWrite;
  57623. }
  57624. #if defined(SQLITE_HAS_CODEC)
  57625. if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
  57626. #else
  57627. pData = p->pData;
  57628. #endif
  57629. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
  57630. if( rc ) return rc;
  57631. p->flags &= ~PGHDR_WAL_APPEND;
  57632. continue;
  57633. }
  57634. }
  57635. iFrame++;
  57636. assert( iOffset==walFrameOffset(iFrame, szPage) );
  57637. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  57638. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  57639. if( rc ) return rc;
  57640. pLast = p;
  57641. iOffset += szFrame;
  57642. p->flags |= PGHDR_WAL_APPEND;
  57643. }
  57644. /* Recalculate checksums within the wal file if required. */
  57645. if( isCommit && pWal->iReCksum ){
  57646. rc = walRewriteChecksums(pWal, iFrame);
  57647. if( rc ) return rc;
  57648. }
  57649. /* If this is the end of a transaction, then we might need to pad
  57650. ** the transaction and/or sync the WAL file.
  57651. **
  57652. ** Padding and syncing only occur if this set of frames complete a
  57653. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  57654. ** or synchronous==OFF, then no padding or syncing are needed.
  57655. **
  57656. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  57657. ** needed and only the sync is done. If padding is needed, then the
  57658. ** final frame is repeated (with its commit mark) until the next sector
  57659. ** boundary is crossed. Only the part of the WAL prior to the last
  57660. ** sector boundary is synced; the part of the last frame that extends
  57661. ** past the sector boundary is written after the sync.
  57662. */
  57663. if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
  57664. int bSync = 1;
  57665. if( pWal->padToSectorBoundary ){
  57666. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  57667. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  57668. bSync = (w.iSyncPoint==iOffset);
  57669. testcase( bSync );
  57670. while( iOffset<w.iSyncPoint ){
  57671. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  57672. if( rc ) return rc;
  57673. iOffset += szFrame;
  57674. nExtra++;
  57675. }
  57676. }
  57677. if( bSync ){
  57678. assert( rc==SQLITE_OK );
  57679. rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
  57680. }
  57681. }
  57682. /* If this frame set completes the first transaction in the WAL and
  57683. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  57684. ** journal size limit, if possible.
  57685. */
  57686. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  57687. i64 sz = pWal->mxWalSize;
  57688. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  57689. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  57690. }
  57691. walLimitSize(pWal, sz);
  57692. pWal->truncateOnCommit = 0;
  57693. }
  57694. /* Append data to the wal-index. It is not necessary to lock the
  57695. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  57696. ** guarantees that there are no other writers, and no data that may
  57697. ** be in use by existing readers is being overwritten.
  57698. */
  57699. iFrame = pWal->hdr.mxFrame;
  57700. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  57701. if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
  57702. iFrame++;
  57703. rc = walIndexAppend(pWal, iFrame, p->pgno);
  57704. }
  57705. while( rc==SQLITE_OK && nExtra>0 ){
  57706. iFrame++;
  57707. nExtra--;
  57708. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  57709. }
  57710. if( rc==SQLITE_OK ){
  57711. /* Update the private copy of the header. */
  57712. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  57713. testcase( szPage<=32768 );
  57714. testcase( szPage>=65536 );
  57715. pWal->hdr.mxFrame = iFrame;
  57716. if( isCommit ){
  57717. pWal->hdr.iChange++;
  57718. pWal->hdr.nPage = nTruncate;
  57719. }
  57720. /* If this is a commit, update the wal-index header too. */
  57721. if( isCommit ){
  57722. walIndexWriteHdr(pWal);
  57723. pWal->iCallback = iFrame;
  57724. }
  57725. }
  57726. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  57727. return rc;
  57728. }
  57729. /*
  57730. ** This routine is called to implement sqlite3_wal_checkpoint() and
  57731. ** related interfaces.
  57732. **
  57733. ** Obtain a CHECKPOINT lock and then backfill as much information as
  57734. ** we can from WAL into the database.
  57735. **
  57736. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  57737. ** callback. In this case this function runs a blocking checkpoint.
  57738. */
  57739. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  57740. Wal *pWal, /* Wal connection */
  57741. sqlite3 *db, /* Check this handle's interrupt flag */
  57742. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  57743. int (*xBusy)(void*), /* Function to call when busy */
  57744. void *pBusyArg, /* Context argument for xBusyHandler */
  57745. int sync_flags, /* Flags to sync db file with (or 0) */
  57746. int nBuf, /* Size of temporary buffer */
  57747. u8 *zBuf, /* Temporary buffer to use */
  57748. int *pnLog, /* OUT: Number of frames in WAL */
  57749. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  57750. ){
  57751. int rc; /* Return code */
  57752. int isChanged = 0; /* True if a new wal-index header is loaded */
  57753. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  57754. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  57755. assert( pWal->ckptLock==0 );
  57756. assert( pWal->writeLock==0 );
  57757. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  57758. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  57759. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  57760. if( pWal->readOnly ) return SQLITE_READONLY;
  57761. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  57762. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  57763. ** "checkpoint" lock on the database file. */
  57764. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  57765. if( rc ){
  57766. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  57767. ** checkpoint operation at the same time, the lock cannot be obtained and
  57768. ** SQLITE_BUSY is returned.
  57769. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  57770. ** it will not be invoked in this case.
  57771. */
  57772. testcase( rc==SQLITE_BUSY );
  57773. testcase( xBusy!=0 );
  57774. return rc;
  57775. }
  57776. pWal->ckptLock = 1;
  57777. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  57778. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  57779. ** file.
  57780. **
  57781. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  57782. ** immediately, and a busy-handler is configured, it is invoked and the
  57783. ** writer lock retried until either the busy-handler returns 0 or the
  57784. ** lock is successfully obtained.
  57785. */
  57786. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  57787. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  57788. if( rc==SQLITE_OK ){
  57789. pWal->writeLock = 1;
  57790. }else if( rc==SQLITE_BUSY ){
  57791. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  57792. xBusy2 = 0;
  57793. rc = SQLITE_OK;
  57794. }
  57795. }
  57796. /* Read the wal-index header. */
  57797. if( rc==SQLITE_OK ){
  57798. rc = walIndexReadHdr(pWal, &isChanged);
  57799. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  57800. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  57801. }
  57802. }
  57803. /* Copy data from the log to the database file. */
  57804. if( rc==SQLITE_OK ){
  57805. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  57806. rc = SQLITE_CORRUPT_BKPT;
  57807. }else{
  57808. rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  57809. }
  57810. /* If no error occurred, set the output variables. */
  57811. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  57812. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  57813. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  57814. }
  57815. }
  57816. if( isChanged ){
  57817. /* If a new wal-index header was loaded before the checkpoint was
  57818. ** performed, then the pager-cache associated with pWal is now
  57819. ** out of date. So zero the cached wal-index header to ensure that
  57820. ** next time the pager opens a snapshot on this database it knows that
  57821. ** the cache needs to be reset.
  57822. */
  57823. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  57824. }
  57825. /* Release the locks. */
  57826. sqlite3WalEndWriteTransaction(pWal);
  57827. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  57828. pWal->ckptLock = 0;
  57829. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  57830. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  57831. }
  57832. /* Return the value to pass to a sqlite3_wal_hook callback, the
  57833. ** number of frames in the WAL at the point of the last commit since
  57834. ** sqlite3WalCallback() was called. If no commits have occurred since
  57835. ** the last call, then return 0.
  57836. */
  57837. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  57838. u32 ret = 0;
  57839. if( pWal ){
  57840. ret = pWal->iCallback;
  57841. pWal->iCallback = 0;
  57842. }
  57843. return (int)ret;
  57844. }
  57845. /*
  57846. ** This function is called to change the WAL subsystem into or out
  57847. ** of locking_mode=EXCLUSIVE.
  57848. **
  57849. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  57850. ** into locking_mode=NORMAL. This means that we must acquire a lock
  57851. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  57852. ** or if the acquisition of the lock fails, then return 0. If the
  57853. ** transition out of exclusive-mode is successful, return 1. This
  57854. ** operation must occur while the pager is still holding the exclusive
  57855. ** lock on the main database file.
  57856. **
  57857. ** If op is one, then change from locking_mode=NORMAL into
  57858. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  57859. ** be released. Return 1 if the transition is made and 0 if the
  57860. ** WAL is already in exclusive-locking mode - meaning that this
  57861. ** routine is a no-op. The pager must already hold the exclusive lock
  57862. ** on the main database file before invoking this operation.
  57863. **
  57864. ** If op is negative, then do a dry-run of the op==1 case but do
  57865. ** not actually change anything. The pager uses this to see if it
  57866. ** should acquire the database exclusive lock prior to invoking
  57867. ** the op==1 case.
  57868. */
  57869. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  57870. int rc;
  57871. assert( pWal->writeLock==0 );
  57872. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  57873. /* pWal->readLock is usually set, but might be -1 if there was a
  57874. ** prior error while attempting to acquire are read-lock. This cannot
  57875. ** happen if the connection is actually in exclusive mode (as no xShmLock
  57876. ** locks are taken in this case). Nor should the pager attempt to
  57877. ** upgrade to exclusive-mode following such an error.
  57878. */
  57879. assert( pWal->readLock>=0 || pWal->lockError );
  57880. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  57881. if( op==0 ){
  57882. if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
  57883. pWal->exclusiveMode = WAL_NORMAL_MODE;
  57884. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  57885. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  57886. }
  57887. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  57888. }else{
  57889. /* Already in locking_mode=NORMAL */
  57890. rc = 0;
  57891. }
  57892. }else if( op>0 ){
  57893. assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
  57894. assert( pWal->readLock>=0 );
  57895. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  57896. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  57897. rc = 1;
  57898. }else{
  57899. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  57900. }
  57901. return rc;
  57902. }
  57903. /*
  57904. ** Return true if the argument is non-NULL and the WAL module is using
  57905. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  57906. ** WAL module is using shared-memory, return false.
  57907. */
  57908. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  57909. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  57910. }
  57911. #ifdef SQLITE_ENABLE_SNAPSHOT
  57912. /* Create a snapshot object. The content of a snapshot is opaque to
  57913. ** every other subsystem, so the WAL module can put whatever it needs
  57914. ** in the object.
  57915. */
  57916. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  57917. int rc = SQLITE_OK;
  57918. WalIndexHdr *pRet;
  57919. static const u32 aZero[4] = { 0, 0, 0, 0 };
  57920. assert( pWal->readLock>=0 && pWal->writeLock==0 );
  57921. if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
  57922. *ppSnapshot = 0;
  57923. return SQLITE_ERROR;
  57924. }
  57925. pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  57926. if( pRet==0 ){
  57927. rc = SQLITE_NOMEM_BKPT;
  57928. }else{
  57929. memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
  57930. *ppSnapshot = (sqlite3_snapshot*)pRet;
  57931. }
  57932. return rc;
  57933. }
  57934. /* Try to open on pSnapshot when the next read-transaction starts
  57935. */
  57936. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
  57937. pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
  57938. }
  57939. /*
  57940. ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
  57941. ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
  57942. */
  57943. SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
  57944. WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
  57945. WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
  57946. /* aSalt[0] is a copy of the value stored in the wal file header. It
  57947. ** is incremented each time the wal file is restarted. */
  57948. if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
  57949. if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
  57950. if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
  57951. if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
  57952. return 0;
  57953. }
  57954. /*
  57955. ** The caller currently has a read transaction open on the database.
  57956. ** This function takes a SHARED lock on the CHECKPOINTER slot and then
  57957. ** checks if the snapshot passed as the second argument is still
  57958. ** available. If so, SQLITE_OK is returned.
  57959. **
  57960. ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
  57961. ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
  57962. ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
  57963. ** lock is released before returning.
  57964. */
  57965. SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
  57966. int rc;
  57967. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  57968. if( rc==SQLITE_OK ){
  57969. WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
  57970. if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  57971. || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
  57972. ){
  57973. rc = SQLITE_ERROR_SNAPSHOT;
  57974. walUnlockShared(pWal, WAL_CKPT_LOCK);
  57975. }
  57976. }
  57977. return rc;
  57978. }
  57979. /*
  57980. ** Release a lock obtained by an earlier successful call to
  57981. ** sqlite3WalSnapshotCheck().
  57982. */
  57983. SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal){
  57984. assert( pWal );
  57985. walUnlockShared(pWal, WAL_CKPT_LOCK);
  57986. }
  57987. #endif /* SQLITE_ENABLE_SNAPSHOT */
  57988. #ifdef SQLITE_ENABLE_ZIPVFS
  57989. /*
  57990. ** If the argument is not NULL, it points to a Wal object that holds a
  57991. ** read-lock. This function returns the database page-size if it is known,
  57992. ** or zero if it is not (or if pWal is NULL).
  57993. */
  57994. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  57995. assert( pWal==0 || pWal->readLock>=0 );
  57996. return (pWal ? pWal->szPage : 0);
  57997. }
  57998. #endif
  57999. /* Return the sqlite3_file object for the WAL file
  58000. */
  58001. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
  58002. return pWal->pWalFd;
  58003. }
  58004. #endif /* #ifndef SQLITE_OMIT_WAL */
  58005. /************** End of wal.c *************************************************/
  58006. /************** Begin file btmutex.c *****************************************/
  58007. /*
  58008. ** 2007 August 27
  58009. **
  58010. ** The author disclaims copyright to this source code. In place of
  58011. ** a legal notice, here is a blessing:
  58012. **
  58013. ** May you do good and not evil.
  58014. ** May you find forgiveness for yourself and forgive others.
  58015. ** May you share freely, never taking more than you give.
  58016. **
  58017. *************************************************************************
  58018. **
  58019. ** This file contains code used to implement mutexes on Btree objects.
  58020. ** This code really belongs in btree.c. But btree.c is getting too
  58021. ** big and we want to break it down some. This packaged seemed like
  58022. ** a good breakout.
  58023. */
  58024. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  58025. /************** Begin file btreeInt.h ****************************************/
  58026. /*
  58027. ** 2004 April 6
  58028. **
  58029. ** The author disclaims copyright to this source code. In place of
  58030. ** a legal notice, here is a blessing:
  58031. **
  58032. ** May you do good and not evil.
  58033. ** May you find forgiveness for yourself and forgive others.
  58034. ** May you share freely, never taking more than you give.
  58035. **
  58036. *************************************************************************
  58037. ** This file implements an external (disk-based) database using BTrees.
  58038. ** For a detailed discussion of BTrees, refer to
  58039. **
  58040. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  58041. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  58042. ** Publishing Company, Reading, Massachusetts.
  58043. **
  58044. ** The basic idea is that each page of the file contains N database
  58045. ** entries and N+1 pointers to subpages.
  58046. **
  58047. ** ----------------------------------------------------------------
  58048. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  58049. ** ----------------------------------------------------------------
  58050. **
  58051. ** All of the keys on the page that Ptr(0) points to have values less
  58052. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  58053. ** values greater than Key(0) and less than Key(1). All of the keys
  58054. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  58055. ** so forth.
  58056. **
  58057. ** Finding a particular key requires reading O(log(M)) pages from the
  58058. ** disk where M is the number of entries in the tree.
  58059. **
  58060. ** In this implementation, a single file can hold one or more separate
  58061. ** BTrees. Each BTree is identified by the index of its root page. The
  58062. ** key and data for any entry are combined to form the "payload". A
  58063. ** fixed amount of payload can be carried directly on the database
  58064. ** page. If the payload is larger than the preset amount then surplus
  58065. ** bytes are stored on overflow pages. The payload for an entry
  58066. ** and the preceding pointer are combined to form a "Cell". Each
  58067. ** page has a small header which contains the Ptr(N) pointer and other
  58068. ** information such as the size of key and data.
  58069. **
  58070. ** FORMAT DETAILS
  58071. **
  58072. ** The file is divided into pages. The first page is called page 1,
  58073. ** the second is page 2, and so forth. A page number of zero indicates
  58074. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  58075. ** Each page can be either a btree page, a freelist page, an overflow
  58076. ** page, or a pointer-map page.
  58077. **
  58078. ** The first page is always a btree page. The first 100 bytes of the first
  58079. ** page contain a special header (the "file header") that describes the file.
  58080. ** The format of the file header is as follows:
  58081. **
  58082. ** OFFSET SIZE DESCRIPTION
  58083. ** 0 16 Header string: "SQLite format 3\000"
  58084. ** 16 2 Page size in bytes. (1 means 65536)
  58085. ** 18 1 File format write version
  58086. ** 19 1 File format read version
  58087. ** 20 1 Bytes of unused space at the end of each page
  58088. ** 21 1 Max embedded payload fraction (must be 64)
  58089. ** 22 1 Min embedded payload fraction (must be 32)
  58090. ** 23 1 Min leaf payload fraction (must be 32)
  58091. ** 24 4 File change counter
  58092. ** 28 4 Reserved for future use
  58093. ** 32 4 First freelist page
  58094. ** 36 4 Number of freelist pages in the file
  58095. ** 40 60 15 4-byte meta values passed to higher layers
  58096. **
  58097. ** 40 4 Schema cookie
  58098. ** 44 4 File format of schema layer
  58099. ** 48 4 Size of page cache
  58100. ** 52 4 Largest root-page (auto/incr_vacuum)
  58101. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  58102. ** 60 4 User version
  58103. ** 64 4 Incremental vacuum mode
  58104. ** 68 4 Application-ID
  58105. ** 72 20 unused
  58106. ** 92 4 The version-valid-for number
  58107. ** 96 4 SQLITE_VERSION_NUMBER
  58108. **
  58109. ** All of the integer values are big-endian (most significant byte first).
  58110. **
  58111. ** The file change counter is incremented when the database is changed
  58112. ** This counter allows other processes to know when the file has changed
  58113. ** and thus when they need to flush their cache.
  58114. **
  58115. ** The max embedded payload fraction is the amount of the total usable
  58116. ** space in a page that can be consumed by a single cell for standard
  58117. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  58118. ** is to limit the maximum cell size so that at least 4 cells will fit
  58119. ** on one page. Thus the default max embedded payload fraction is 64.
  58120. **
  58121. ** If the payload for a cell is larger than the max payload, then extra
  58122. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  58123. ** as many bytes as possible are moved into the overflow pages without letting
  58124. ** the cell size drop below the min embedded payload fraction.
  58125. **
  58126. ** The min leaf payload fraction is like the min embedded payload fraction
  58127. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  58128. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  58129. ** not specified in the header.
  58130. **
  58131. ** Each btree pages is divided into three sections: The header, the
  58132. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  58133. ** file header that occurs before the page header.
  58134. **
  58135. ** |----------------|
  58136. ** | file header | 100 bytes. Page 1 only.
  58137. ** |----------------|
  58138. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  58139. ** |----------------|
  58140. ** | cell pointer | | 2 bytes per cell. Sorted order.
  58141. ** | array | | Grows downward
  58142. ** | | v
  58143. ** |----------------|
  58144. ** | unallocated |
  58145. ** | space |
  58146. ** |----------------| ^ Grows upwards
  58147. ** | cell content | | Arbitrary order interspersed with freeblocks.
  58148. ** | area | | and free space fragments.
  58149. ** |----------------|
  58150. **
  58151. ** The page headers looks like this:
  58152. **
  58153. ** OFFSET SIZE DESCRIPTION
  58154. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  58155. ** 1 2 byte offset to the first freeblock
  58156. ** 3 2 number of cells on this page
  58157. ** 5 2 first byte of the cell content area
  58158. ** 7 1 number of fragmented free bytes
  58159. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  58160. **
  58161. ** The flags define the format of this btree page. The leaf flag means that
  58162. ** this page has no children. The zerodata flag means that this page carries
  58163. ** only keys and no data. The intkey flag means that the key is an integer
  58164. ** which is stored in the key size entry of the cell header rather than in
  58165. ** the payload area.
  58166. **
  58167. ** The cell pointer array begins on the first byte after the page header.
  58168. ** The cell pointer array contains zero or more 2-byte numbers which are
  58169. ** offsets from the beginning of the page to the cell content in the cell
  58170. ** content area. The cell pointers occur in sorted order. The system strives
  58171. ** to keep free space after the last cell pointer so that new cells can
  58172. ** be easily added without having to defragment the page.
  58173. **
  58174. ** Cell content is stored at the very end of the page and grows toward the
  58175. ** beginning of the page.
  58176. **
  58177. ** Unused space within the cell content area is collected into a linked list of
  58178. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  58179. ** to the first freeblock is given in the header. Freeblocks occur in
  58180. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  58181. ** any group of 3 or fewer unused bytes in the cell content area cannot
  58182. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  58183. ** a fragment. The total number of bytes in all fragments is recorded.
  58184. ** in the page header at offset 7.
  58185. **
  58186. ** SIZE DESCRIPTION
  58187. ** 2 Byte offset of the next freeblock
  58188. ** 2 Bytes in this freeblock
  58189. **
  58190. ** Cells are of variable length. Cells are stored in the cell content area at
  58191. ** the end of the page. Pointers to the cells are in the cell pointer array
  58192. ** that immediately follows the page header. Cells is not necessarily
  58193. ** contiguous or in order, but cell pointers are contiguous and in order.
  58194. **
  58195. ** Cell content makes use of variable length integers. A variable
  58196. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  58197. ** byte are used. The integer consists of all bytes that have bit 8 set and
  58198. ** the first byte with bit 8 clear. The most significant byte of the integer
  58199. ** appears first. A variable-length integer may not be more than 9 bytes long.
  58200. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  58201. ** allows a 64-bit integer to be encoded in 9 bytes.
  58202. **
  58203. ** 0x00 becomes 0x00000000
  58204. ** 0x7f becomes 0x0000007f
  58205. ** 0x81 0x00 becomes 0x00000080
  58206. ** 0x82 0x00 becomes 0x00000100
  58207. ** 0x80 0x7f becomes 0x0000007f
  58208. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  58209. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  58210. **
  58211. ** Variable length integers are used for rowids and to hold the number of
  58212. ** bytes of key and data in a btree cell.
  58213. **
  58214. ** The content of a cell looks like this:
  58215. **
  58216. ** SIZE DESCRIPTION
  58217. ** 4 Page number of the left child. Omitted if leaf flag is set.
  58218. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  58219. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  58220. ** * Payload
  58221. ** 4 First page of the overflow chain. Omitted if no overflow
  58222. **
  58223. ** Overflow pages form a linked list. Each page except the last is completely
  58224. ** filled with data (pagesize - 4 bytes). The last page can have as little
  58225. ** as 1 byte of data.
  58226. **
  58227. ** SIZE DESCRIPTION
  58228. ** 4 Page number of next overflow page
  58229. ** * Data
  58230. **
  58231. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  58232. ** file header points to the first in a linked list of trunk page. Each trunk
  58233. ** page points to multiple leaf pages. The content of a leaf page is
  58234. ** unspecified. A trunk page looks like this:
  58235. **
  58236. ** SIZE DESCRIPTION
  58237. ** 4 Page number of next trunk page
  58238. ** 4 Number of leaf pointers on this page
  58239. ** * zero or more pages numbers of leaves
  58240. */
  58241. /* #include "sqliteInt.h" */
  58242. /* The following value is the maximum cell size assuming a maximum page
  58243. ** size give above.
  58244. */
  58245. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  58246. /* The maximum number of cells on a single page of the database. This
  58247. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  58248. ** plus 2 bytes for the index to the cell in the page header). Such
  58249. ** small cells will be rare, but they are possible.
  58250. */
  58251. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  58252. /* Forward declarations */
  58253. typedef struct MemPage MemPage;
  58254. typedef struct BtLock BtLock;
  58255. typedef struct CellInfo CellInfo;
  58256. /*
  58257. ** This is a magic string that appears at the beginning of every
  58258. ** SQLite database in order to identify the file as a real database.
  58259. **
  58260. ** You can change this value at compile-time by specifying a
  58261. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  58262. ** header must be exactly 16 bytes including the zero-terminator so
  58263. ** the string itself should be 15 characters long. If you change
  58264. ** the header, then your custom library will not be able to read
  58265. ** databases generated by the standard tools and the standard tools
  58266. ** will not be able to read databases created by your custom library.
  58267. */
  58268. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  58269. # define SQLITE_FILE_HEADER "SQLite format 3"
  58270. #endif
  58271. /*
  58272. ** Page type flags. An ORed combination of these flags appear as the
  58273. ** first byte of on-disk image of every BTree page.
  58274. */
  58275. #define PTF_INTKEY 0x01
  58276. #define PTF_ZERODATA 0x02
  58277. #define PTF_LEAFDATA 0x04
  58278. #define PTF_LEAF 0x08
  58279. /*
  58280. ** An instance of this object stores information about each a single database
  58281. ** page that has been loaded into memory. The information in this object
  58282. ** is derived from the raw on-disk page content.
  58283. **
  58284. ** As each database page is loaded into memory, the pager allocats an
  58285. ** instance of this object and zeros the first 8 bytes. (This is the
  58286. ** "extra" information associated with each page of the pager.)
  58287. **
  58288. ** Access to all fields of this structure is controlled by the mutex
  58289. ** stored in MemPage.pBt->mutex.
  58290. */
  58291. struct MemPage {
  58292. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  58293. u8 bBusy; /* Prevent endless loops on corrupt database files */
  58294. u8 intKey; /* True if table b-trees. False for index b-trees */
  58295. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  58296. Pgno pgno; /* Page number for this page */
  58297. /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
  58298. ** is allocated. All fields that follow must be initialized before use */
  58299. u8 leaf; /* True if a leaf page */
  58300. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  58301. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  58302. u8 max1bytePayload; /* min(maxLocal,127) */
  58303. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  58304. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  58305. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  58306. u16 cellOffset; /* Index in aData of first cell pointer */
  58307. u16 nFree; /* Number of free bytes on the page */
  58308. u16 nCell; /* Number of cells on this page, local and ovfl */
  58309. u16 maskPage; /* Mask for page offset */
  58310. u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
  58311. ** non-overflow cell */
  58312. u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
  58313. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  58314. u8 *aData; /* Pointer to disk image of the page data */
  58315. u8 *aDataEnd; /* One byte past the end of usable data */
  58316. u8 *aCellIdx; /* The cell index area */
  58317. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  58318. DbPage *pDbPage; /* Pager page handle */
  58319. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  58320. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  58321. };
  58322. /*
  58323. ** A linked list of the following structures is stored at BtShared.pLock.
  58324. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  58325. ** is opened on the table with root page BtShared.iTable. Locks are removed
  58326. ** from this list when a transaction is committed or rolled back, or when
  58327. ** a btree handle is closed.
  58328. */
  58329. struct BtLock {
  58330. Btree *pBtree; /* Btree handle holding this lock */
  58331. Pgno iTable; /* Root page of table */
  58332. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  58333. BtLock *pNext; /* Next in BtShared.pLock list */
  58334. };
  58335. /* Candidate values for BtLock.eLock */
  58336. #define READ_LOCK 1
  58337. #define WRITE_LOCK 2
  58338. /* A Btree handle
  58339. **
  58340. ** A database connection contains a pointer to an instance of
  58341. ** this object for every database file that it has open. This structure
  58342. ** is opaque to the database connection. The database connection cannot
  58343. ** see the internals of this structure and only deals with pointers to
  58344. ** this structure.
  58345. **
  58346. ** For some database files, the same underlying database cache might be
  58347. ** shared between multiple connections. In that case, each connection
  58348. ** has it own instance of this object. But each instance of this object
  58349. ** points to the same BtShared object. The database cache and the
  58350. ** schema associated with the database file are all contained within
  58351. ** the BtShared object.
  58352. **
  58353. ** All fields in this structure are accessed under sqlite3.mutex.
  58354. ** The pBt pointer itself may not be changed while there exists cursors
  58355. ** in the referenced BtShared that point back to this Btree since those
  58356. ** cursors have to go through this Btree to find their BtShared and
  58357. ** they often do so without holding sqlite3.mutex.
  58358. */
  58359. struct Btree {
  58360. sqlite3 *db; /* The database connection holding this btree */
  58361. BtShared *pBt; /* Sharable content of this btree */
  58362. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  58363. u8 sharable; /* True if we can share pBt with another db */
  58364. u8 locked; /* True if db currently has pBt locked */
  58365. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  58366. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  58367. int nBackup; /* Number of backup operations reading this btree */
  58368. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  58369. Btree *pNext; /* List of other sharable Btrees from the same db */
  58370. Btree *pPrev; /* Back pointer of the same list */
  58371. #ifndef SQLITE_OMIT_SHARED_CACHE
  58372. BtLock lock; /* Object used to lock page 1 */
  58373. #endif
  58374. };
  58375. /*
  58376. ** Btree.inTrans may take one of the following values.
  58377. **
  58378. ** If the shared-data extension is enabled, there may be multiple users
  58379. ** of the Btree structure. At most one of these may open a write transaction,
  58380. ** but any number may have active read transactions.
  58381. */
  58382. #define TRANS_NONE 0
  58383. #define TRANS_READ 1
  58384. #define TRANS_WRITE 2
  58385. /*
  58386. ** An instance of this object represents a single database file.
  58387. **
  58388. ** A single database file can be in use at the same time by two
  58389. ** or more database connections. When two or more connections are
  58390. ** sharing the same database file, each connection has it own
  58391. ** private Btree object for the file and each of those Btrees points
  58392. ** to this one BtShared object. BtShared.nRef is the number of
  58393. ** connections currently sharing this database file.
  58394. **
  58395. ** Fields in this structure are accessed under the BtShared.mutex
  58396. ** mutex, except for nRef and pNext which are accessed under the
  58397. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  58398. ** may not be modified once it is initially set as long as nRef>0.
  58399. ** The pSchema field may be set once under BtShared.mutex and
  58400. ** thereafter is unchanged as long as nRef>0.
  58401. **
  58402. ** isPending:
  58403. **
  58404. ** If a BtShared client fails to obtain a write-lock on a database
  58405. ** table (because there exists one or more read-locks on the table),
  58406. ** the shared-cache enters 'pending-lock' state and isPending is
  58407. ** set to true.
  58408. **
  58409. ** The shared-cache leaves the 'pending lock' state when either of
  58410. ** the following occur:
  58411. **
  58412. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  58413. ** 2) The number of locks held by other connections drops to zero.
  58414. **
  58415. ** while in the 'pending-lock' state, no connection may start a new
  58416. ** transaction.
  58417. **
  58418. ** This feature is included to help prevent writer-starvation.
  58419. */
  58420. struct BtShared {
  58421. Pager *pPager; /* The page cache */
  58422. sqlite3 *db; /* Database connection currently using this Btree */
  58423. BtCursor *pCursor; /* A list of all open cursors */
  58424. MemPage *pPage1; /* First page of the database */
  58425. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  58426. #ifndef SQLITE_OMIT_AUTOVACUUM
  58427. u8 autoVacuum; /* True if auto-vacuum is enabled */
  58428. u8 incrVacuum; /* True if incr-vacuum is enabled */
  58429. u8 bDoTruncate; /* True to truncate db on commit */
  58430. #endif
  58431. u8 inTransaction; /* Transaction state */
  58432. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  58433. #ifdef SQLITE_HAS_CODEC
  58434. u8 optimalReserve; /* Desired amount of reserved space per page */
  58435. #endif
  58436. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  58437. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  58438. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  58439. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  58440. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  58441. u32 pageSize; /* Total number of bytes on a page */
  58442. u32 usableSize; /* Number of usable bytes on each page */
  58443. int nTransaction; /* Number of open transactions (read + write) */
  58444. u32 nPage; /* Number of pages in the database */
  58445. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  58446. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  58447. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  58448. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  58449. #ifndef SQLITE_OMIT_SHARED_CACHE
  58450. int nRef; /* Number of references to this structure */
  58451. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  58452. BtLock *pLock; /* List of locks held on this shared-btree struct */
  58453. Btree *pWriter; /* Btree with currently open write transaction */
  58454. #endif
  58455. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  58456. };
  58457. /*
  58458. ** Allowed values for BtShared.btsFlags
  58459. */
  58460. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  58461. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  58462. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  58463. #define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */
  58464. #define BTS_FAST_SECURE 0x000c /* Combination of the previous two */
  58465. #define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */
  58466. #define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
  58467. #define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */
  58468. #define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
  58469. /*
  58470. ** An instance of the following structure is used to hold information
  58471. ** about a cell. The parseCellPtr() function fills in this structure
  58472. ** based on information extract from the raw disk page.
  58473. */
  58474. struct CellInfo {
  58475. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  58476. u8 *pPayload; /* Pointer to the start of payload */
  58477. u32 nPayload; /* Bytes of payload */
  58478. u16 nLocal; /* Amount of payload held locally, not on overflow */
  58479. u16 nSize; /* Size of the cell content on the main b-tree page */
  58480. };
  58481. /*
  58482. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  58483. ** this will be declared corrupt. This value is calculated based on a
  58484. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  58485. ** root-node and 3 for all other internal nodes.
  58486. **
  58487. ** If a tree that appears to be taller than this is encountered, it is
  58488. ** assumed that the database is corrupt.
  58489. */
  58490. #define BTCURSOR_MAX_DEPTH 20
  58491. /*
  58492. ** A cursor is a pointer to a particular entry within a particular
  58493. ** b-tree within a database file.
  58494. **
  58495. ** The entry is identified by its MemPage and the index in
  58496. ** MemPage.aCell[] of the entry.
  58497. **
  58498. ** A single database file can be shared by two more database connections,
  58499. ** but cursors cannot be shared. Each cursor is associated with a
  58500. ** particular database connection identified BtCursor.pBtree.db.
  58501. **
  58502. ** Fields in this structure are accessed under the BtShared.mutex
  58503. ** found at self->pBt->mutex.
  58504. **
  58505. ** skipNext meaning:
  58506. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  58507. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  58508. ** eState==FAULT: Cursor fault with skipNext as error code.
  58509. */
  58510. struct BtCursor {
  58511. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  58512. u8 curFlags; /* zero or more BTCF_* flags defined below */
  58513. u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
  58514. u8 hints; /* As configured by CursorSetHints() */
  58515. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  58516. ** Error code if eState==CURSOR_FAULT */
  58517. Btree *pBtree; /* The Btree to which this cursor belongs */
  58518. Pgno *aOverflow; /* Cache of overflow page locations */
  58519. void *pKey; /* Saved key that was cursor last known position */
  58520. /* All fields above are zeroed when the cursor is allocated. See
  58521. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  58522. ** initialized. */
  58523. #define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */
  58524. BtShared *pBt; /* The BtShared this cursor points to */
  58525. BtCursor *pNext; /* Forms a linked list of all cursors */
  58526. CellInfo info; /* A parse of the cell we are pointing at */
  58527. i64 nKey; /* Size of pKey, or last integer key */
  58528. Pgno pgnoRoot; /* The root page of this tree */
  58529. i8 iPage; /* Index of current page in apPage */
  58530. u8 curIntKey; /* Value of apPage[0]->intKey */
  58531. u16 ix; /* Current index for apPage[iPage] */
  58532. u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
  58533. struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
  58534. MemPage *pPage; /* Current page */
  58535. MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
  58536. };
  58537. /*
  58538. ** Legal values for BtCursor.curFlags
  58539. */
  58540. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  58541. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  58542. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  58543. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  58544. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  58545. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  58546. /*
  58547. ** Potential values for BtCursor.eState.
  58548. **
  58549. ** CURSOR_INVALID:
  58550. ** Cursor does not point to a valid entry. This can happen (for example)
  58551. ** because the table is empty or because BtreeCursorFirst() has not been
  58552. ** called.
  58553. **
  58554. ** CURSOR_VALID:
  58555. ** Cursor points to a valid entry. getPayload() etc. may be called.
  58556. **
  58557. ** CURSOR_SKIPNEXT:
  58558. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  58559. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  58560. ** operation should be a no-op.
  58561. **
  58562. ** CURSOR_REQUIRESEEK:
  58563. ** The table that this cursor was opened on still exists, but has been
  58564. ** modified since the cursor was last used. The cursor position is saved
  58565. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  58566. ** this state, restoreCursorPosition() can be called to attempt to
  58567. ** seek the cursor to the saved position.
  58568. **
  58569. ** CURSOR_FAULT:
  58570. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  58571. ** on a different connection that shares the BtShared cache with this
  58572. ** cursor. The error has left the cache in an inconsistent state.
  58573. ** Do nothing else with this cursor. Any attempt to use the cursor
  58574. ** should return the error code stored in BtCursor.skipNext
  58575. */
  58576. #define CURSOR_VALID 0
  58577. #define CURSOR_INVALID 1
  58578. #define CURSOR_SKIPNEXT 2
  58579. #define CURSOR_REQUIRESEEK 3
  58580. #define CURSOR_FAULT 4
  58581. /*
  58582. ** The database page the PENDING_BYTE occupies. This page is never used.
  58583. */
  58584. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  58585. /*
  58586. ** These macros define the location of the pointer-map entry for a
  58587. ** database page. The first argument to each is the number of usable
  58588. ** bytes on each page of the database (often 1024). The second is the
  58589. ** page number to look up in the pointer map.
  58590. **
  58591. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  58592. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  58593. ** the offset of the requested map entry.
  58594. **
  58595. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  58596. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  58597. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  58598. ** this test.
  58599. */
  58600. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  58601. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  58602. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  58603. /*
  58604. ** The pointer map is a lookup table that identifies the parent page for
  58605. ** each child page in the database file. The parent page is the page that
  58606. ** contains a pointer to the child. Every page in the database contains
  58607. ** 0 or 1 parent pages. (In this context 'database page' refers
  58608. ** to any page that is not part of the pointer map itself.) Each pointer map
  58609. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  58610. ** The PTRMAP_XXX identifiers below are the valid types.
  58611. **
  58612. ** The purpose of the pointer map is to facility moving pages from one
  58613. ** position in the file to another as part of autovacuum. When a page
  58614. ** is moved, the pointer in its parent must be updated to point to the
  58615. ** new location. The pointer map is used to locate the parent page quickly.
  58616. **
  58617. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  58618. ** used in this case.
  58619. **
  58620. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  58621. ** is not used in this case.
  58622. **
  58623. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  58624. ** overflow pages. The page number identifies the page that
  58625. ** contains the cell with a pointer to this overflow page.
  58626. **
  58627. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  58628. ** overflow pages. The page-number identifies the previous
  58629. ** page in the overflow page list.
  58630. **
  58631. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  58632. ** identifies the parent page in the btree.
  58633. */
  58634. #define PTRMAP_ROOTPAGE 1
  58635. #define PTRMAP_FREEPAGE 2
  58636. #define PTRMAP_OVERFLOW1 3
  58637. #define PTRMAP_OVERFLOW2 4
  58638. #define PTRMAP_BTREE 5
  58639. /* A bunch of assert() statements to check the transaction state variables
  58640. ** of handle p (type Btree*) are internally consistent.
  58641. */
  58642. #define btreeIntegrity(p) \
  58643. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  58644. assert( p->pBt->inTransaction>=p->inTrans );
  58645. /*
  58646. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  58647. ** if the database supports auto-vacuum or not. Because it is used
  58648. ** within an expression that is an argument to another macro
  58649. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  58650. ** So, this macro is defined instead.
  58651. */
  58652. #ifndef SQLITE_OMIT_AUTOVACUUM
  58653. #define ISAUTOVACUUM (pBt->autoVacuum)
  58654. #else
  58655. #define ISAUTOVACUUM 0
  58656. #endif
  58657. /*
  58658. ** This structure is passed around through all the sanity checking routines
  58659. ** in order to keep track of some global state information.
  58660. **
  58661. ** The aRef[] array is allocated so that there is 1 bit for each page in
  58662. ** the database. As the integrity-check proceeds, for each page used in
  58663. ** the database the corresponding bit is set. This allows integrity-check to
  58664. ** detect pages that are used twice and orphaned pages (both of which
  58665. ** indicate corruption).
  58666. */
  58667. typedef struct IntegrityCk IntegrityCk;
  58668. struct IntegrityCk {
  58669. BtShared *pBt; /* The tree being checked out */
  58670. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  58671. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  58672. Pgno nPage; /* Number of pages in the database */
  58673. int mxErr; /* Stop accumulating errors when this reaches zero */
  58674. int nErr; /* Number of messages written to zErrMsg so far */
  58675. int mallocFailed; /* A memory allocation error has occurred */
  58676. const char *zPfx; /* Error message prefix */
  58677. int v1, v2; /* Values for up to two %d fields in zPfx */
  58678. StrAccum errMsg; /* Accumulate the error message text here */
  58679. u32 *heap; /* Min-heap used for analyzing cell coverage */
  58680. };
  58681. /*
  58682. ** Routines to read or write a two- and four-byte big-endian integer values.
  58683. */
  58684. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  58685. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  58686. #define get4byte sqlite3Get4byte
  58687. #define put4byte sqlite3Put4byte
  58688. /*
  58689. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  58690. ** two-byte aligned address. get2bytea() is only used for accessing the
  58691. ** cell addresses in a btree header.
  58692. */
  58693. #if SQLITE_BYTEORDER==4321
  58694. # define get2byteAligned(x) (*(u16*)(x))
  58695. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
  58696. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  58697. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  58698. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  58699. #else
  58700. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  58701. #endif
  58702. /************** End of btreeInt.h ********************************************/
  58703. /************** Continuing where we left off in btmutex.c ********************/
  58704. #ifndef SQLITE_OMIT_SHARED_CACHE
  58705. #if SQLITE_THREADSAFE
  58706. /*
  58707. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  58708. ** set BtShared.db to the database handle associated with p and the
  58709. ** p->locked boolean to true.
  58710. */
  58711. static void lockBtreeMutex(Btree *p){
  58712. assert( p->locked==0 );
  58713. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  58714. assert( sqlite3_mutex_held(p->db->mutex) );
  58715. sqlite3_mutex_enter(p->pBt->mutex);
  58716. p->pBt->db = p->db;
  58717. p->locked = 1;
  58718. }
  58719. /*
  58720. ** Release the BtShared mutex associated with B-Tree handle p and
  58721. ** clear the p->locked boolean.
  58722. */
  58723. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  58724. BtShared *pBt = p->pBt;
  58725. assert( p->locked==1 );
  58726. assert( sqlite3_mutex_held(pBt->mutex) );
  58727. assert( sqlite3_mutex_held(p->db->mutex) );
  58728. assert( p->db==pBt->db );
  58729. sqlite3_mutex_leave(pBt->mutex);
  58730. p->locked = 0;
  58731. }
  58732. /* Forward reference */
  58733. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  58734. /*
  58735. ** Enter a mutex on the given BTree object.
  58736. **
  58737. ** If the object is not sharable, then no mutex is ever required
  58738. ** and this routine is a no-op. The underlying mutex is non-recursive.
  58739. ** But we keep a reference count in Btree.wantToLock so the behavior
  58740. ** of this interface is recursive.
  58741. **
  58742. ** To avoid deadlocks, multiple Btrees are locked in the same order
  58743. ** by all database connections. The p->pNext is a list of other
  58744. ** Btrees belonging to the same database connection as the p Btree
  58745. ** which need to be locked after p. If we cannot get a lock on
  58746. ** p, then first unlock all of the others on p->pNext, then wait
  58747. ** for the lock to become available on p, then relock all of the
  58748. ** subsequent Btrees that desire a lock.
  58749. */
  58750. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  58751. /* Some basic sanity checking on the Btree. The list of Btrees
  58752. ** connected by pNext and pPrev should be in sorted order by
  58753. ** Btree.pBt value. All elements of the list should belong to
  58754. ** the same connection. Only shared Btrees are on the list. */
  58755. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  58756. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  58757. assert( p->pNext==0 || p->pNext->db==p->db );
  58758. assert( p->pPrev==0 || p->pPrev->db==p->db );
  58759. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  58760. /* Check for locking consistency */
  58761. assert( !p->locked || p->wantToLock>0 );
  58762. assert( p->sharable || p->wantToLock==0 );
  58763. /* We should already hold a lock on the database connection */
  58764. assert( sqlite3_mutex_held(p->db->mutex) );
  58765. /* Unless the database is sharable and unlocked, then BtShared.db
  58766. ** should already be set correctly. */
  58767. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  58768. if( !p->sharable ) return;
  58769. p->wantToLock++;
  58770. if( p->locked ) return;
  58771. btreeLockCarefully(p);
  58772. }
  58773. /* This is a helper function for sqlite3BtreeLock(). By moving
  58774. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  58775. ** into this routine, we avoid unnecessary stack pointer changes
  58776. ** and thus help the sqlite3BtreeLock() routine to run much faster
  58777. ** in the common case.
  58778. */
  58779. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  58780. Btree *pLater;
  58781. /* In most cases, we should be able to acquire the lock we
  58782. ** want without having to go through the ascending lock
  58783. ** procedure that follows. Just be sure not to block.
  58784. */
  58785. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  58786. p->pBt->db = p->db;
  58787. p->locked = 1;
  58788. return;
  58789. }
  58790. /* To avoid deadlock, first release all locks with a larger
  58791. ** BtShared address. Then acquire our lock. Then reacquire
  58792. ** the other BtShared locks that we used to hold in ascending
  58793. ** order.
  58794. */
  58795. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  58796. assert( pLater->sharable );
  58797. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  58798. assert( !pLater->locked || pLater->wantToLock>0 );
  58799. if( pLater->locked ){
  58800. unlockBtreeMutex(pLater);
  58801. }
  58802. }
  58803. lockBtreeMutex(p);
  58804. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  58805. if( pLater->wantToLock ){
  58806. lockBtreeMutex(pLater);
  58807. }
  58808. }
  58809. }
  58810. /*
  58811. ** Exit the recursive mutex on a Btree.
  58812. */
  58813. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  58814. assert( sqlite3_mutex_held(p->db->mutex) );
  58815. if( p->sharable ){
  58816. assert( p->wantToLock>0 );
  58817. p->wantToLock--;
  58818. if( p->wantToLock==0 ){
  58819. unlockBtreeMutex(p);
  58820. }
  58821. }
  58822. }
  58823. #ifndef NDEBUG
  58824. /*
  58825. ** Return true if the BtShared mutex is held on the btree, or if the
  58826. ** B-Tree is not marked as sharable.
  58827. **
  58828. ** This routine is used only from within assert() statements.
  58829. */
  58830. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  58831. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  58832. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  58833. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  58834. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  58835. return (p->sharable==0 || p->locked);
  58836. }
  58837. #endif
  58838. /*
  58839. ** Enter the mutex on every Btree associated with a database
  58840. ** connection. This is needed (for example) prior to parsing
  58841. ** a statement since we will be comparing table and column names
  58842. ** against all schemas and we do not want those schemas being
  58843. ** reset out from under us.
  58844. **
  58845. ** There is a corresponding leave-all procedures.
  58846. **
  58847. ** Enter the mutexes in accending order by BtShared pointer address
  58848. ** to avoid the possibility of deadlock when two threads with
  58849. ** two or more btrees in common both try to lock all their btrees
  58850. ** at the same instant.
  58851. */
  58852. static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
  58853. int i;
  58854. int skipOk = 1;
  58855. Btree *p;
  58856. assert( sqlite3_mutex_held(db->mutex) );
  58857. for(i=0; i<db->nDb; i++){
  58858. p = db->aDb[i].pBt;
  58859. if( p && p->sharable ){
  58860. sqlite3BtreeEnter(p);
  58861. skipOk = 0;
  58862. }
  58863. }
  58864. db->noSharedCache = skipOk;
  58865. }
  58866. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  58867. if( db->noSharedCache==0 ) btreeEnterAll(db);
  58868. }
  58869. static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
  58870. int i;
  58871. Btree *p;
  58872. assert( sqlite3_mutex_held(db->mutex) );
  58873. for(i=0; i<db->nDb; i++){
  58874. p = db->aDb[i].pBt;
  58875. if( p ) sqlite3BtreeLeave(p);
  58876. }
  58877. }
  58878. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  58879. if( db->noSharedCache==0 ) btreeLeaveAll(db);
  58880. }
  58881. #ifndef NDEBUG
  58882. /*
  58883. ** Return true if the current thread holds the database connection
  58884. ** mutex and all required BtShared mutexes.
  58885. **
  58886. ** This routine is used inside assert() statements only.
  58887. */
  58888. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  58889. int i;
  58890. if( !sqlite3_mutex_held(db->mutex) ){
  58891. return 0;
  58892. }
  58893. for(i=0; i<db->nDb; i++){
  58894. Btree *p;
  58895. p = db->aDb[i].pBt;
  58896. if( p && p->sharable &&
  58897. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  58898. return 0;
  58899. }
  58900. }
  58901. return 1;
  58902. }
  58903. #endif /* NDEBUG */
  58904. #ifndef NDEBUG
  58905. /*
  58906. ** Return true if the correct mutexes are held for accessing the
  58907. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  58908. ** access are:
  58909. **
  58910. ** (1) The mutex on db
  58911. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  58912. **
  58913. ** If pSchema is not NULL, then iDb is computed from pSchema and
  58914. ** db using sqlite3SchemaToIndex().
  58915. */
  58916. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  58917. Btree *p;
  58918. assert( db!=0 );
  58919. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  58920. assert( iDb>=0 && iDb<db->nDb );
  58921. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  58922. if( iDb==1 ) return 1;
  58923. p = db->aDb[iDb].pBt;
  58924. assert( p!=0 );
  58925. return p->sharable==0 || p->locked==1;
  58926. }
  58927. #endif /* NDEBUG */
  58928. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  58929. /*
  58930. ** The following are special cases for mutex enter routines for use
  58931. ** in single threaded applications that use shared cache. Except for
  58932. ** these two routines, all mutex operations are no-ops in that case and
  58933. ** are null #defines in btree.h.
  58934. **
  58935. ** If shared cache is disabled, then all btree mutex routines, including
  58936. ** the ones below, are no-ops and are null #defines in btree.h.
  58937. */
  58938. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  58939. p->pBt->db = p->db;
  58940. }
  58941. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  58942. int i;
  58943. for(i=0; i<db->nDb; i++){
  58944. Btree *p = db->aDb[i].pBt;
  58945. if( p ){
  58946. p->pBt->db = p->db;
  58947. }
  58948. }
  58949. }
  58950. #endif /* if SQLITE_THREADSAFE */
  58951. #ifndef SQLITE_OMIT_INCRBLOB
  58952. /*
  58953. ** Enter a mutex on a Btree given a cursor owned by that Btree.
  58954. **
  58955. ** These entry points are used by incremental I/O only. Enter() is required
  58956. ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
  58957. ** the build is threadsafe. Leave() is only required by threadsafe builds.
  58958. */
  58959. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  58960. sqlite3BtreeEnter(pCur->pBtree);
  58961. }
  58962. # if SQLITE_THREADSAFE
  58963. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  58964. sqlite3BtreeLeave(pCur->pBtree);
  58965. }
  58966. # endif
  58967. #endif /* ifndef SQLITE_OMIT_INCRBLOB */
  58968. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  58969. /************** End of btmutex.c *********************************************/
  58970. /************** Begin file btree.c *******************************************/
  58971. /*
  58972. ** 2004 April 6
  58973. **
  58974. ** The author disclaims copyright to this source code. In place of
  58975. ** a legal notice, here is a blessing:
  58976. **
  58977. ** May you do good and not evil.
  58978. ** May you find forgiveness for yourself and forgive others.
  58979. ** May you share freely, never taking more than you give.
  58980. **
  58981. *************************************************************************
  58982. ** This file implements an external (disk-based) database using BTrees.
  58983. ** See the header comment on "btreeInt.h" for additional information.
  58984. ** Including a description of file format and an overview of operation.
  58985. */
  58986. /* #include "btreeInt.h" */
  58987. /*
  58988. ** The header string that appears at the beginning of every
  58989. ** SQLite database.
  58990. */
  58991. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  58992. /*
  58993. ** Set this global variable to 1 to enable tracing using the TRACE
  58994. ** macro.
  58995. */
  58996. #if 0
  58997. int sqlite3BtreeTrace=1; /* True to enable tracing */
  58998. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  58999. #else
  59000. # define TRACE(X)
  59001. #endif
  59002. /*
  59003. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  59004. ** But if the value is zero, make it 65536.
  59005. **
  59006. ** This routine is used to extract the "offset to cell content area" value
  59007. ** from the header of a btree page. If the page size is 65536 and the page
  59008. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  59009. ** This routine makes the necessary adjustment to 65536.
  59010. */
  59011. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  59012. /*
  59013. ** Values passed as the 5th argument to allocateBtreePage()
  59014. */
  59015. #define BTALLOC_ANY 0 /* Allocate any page */
  59016. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  59017. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  59018. /*
  59019. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  59020. ** defined, or 0 if it is. For example:
  59021. **
  59022. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  59023. */
  59024. #ifndef SQLITE_OMIT_AUTOVACUUM
  59025. #define IfNotOmitAV(expr) (expr)
  59026. #else
  59027. #define IfNotOmitAV(expr) 0
  59028. #endif
  59029. #ifndef SQLITE_OMIT_SHARED_CACHE
  59030. /*
  59031. ** A list of BtShared objects that are eligible for participation
  59032. ** in shared cache. This variable has file scope during normal builds,
  59033. ** but the test harness needs to access it so we make it global for
  59034. ** test builds.
  59035. **
  59036. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  59037. */
  59038. #ifdef SQLITE_TEST
  59039. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  59040. #else
  59041. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  59042. #endif
  59043. #endif /* SQLITE_OMIT_SHARED_CACHE */
  59044. #ifndef SQLITE_OMIT_SHARED_CACHE
  59045. /*
  59046. ** Enable or disable the shared pager and schema features.
  59047. **
  59048. ** This routine has no effect on existing database connections.
  59049. ** The shared cache setting effects only future calls to
  59050. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  59051. */
  59052. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  59053. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  59054. return SQLITE_OK;
  59055. }
  59056. #endif
  59057. #ifdef SQLITE_OMIT_SHARED_CACHE
  59058. /*
  59059. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  59060. ** and clearAllSharedCacheTableLocks()
  59061. ** manipulate entries in the BtShared.pLock linked list used to store
  59062. ** shared-cache table level locks. If the library is compiled with the
  59063. ** shared-cache feature disabled, then there is only ever one user
  59064. ** of each BtShared structure and so this locking is not necessary.
  59065. ** So define the lock related functions as no-ops.
  59066. */
  59067. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  59068. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  59069. #define clearAllSharedCacheTableLocks(a)
  59070. #define downgradeAllSharedCacheTableLocks(a)
  59071. #define hasSharedCacheTableLock(a,b,c,d) 1
  59072. #define hasReadConflicts(a, b) 0
  59073. #endif
  59074. /*
  59075. ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
  59076. ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
  59077. **
  59078. ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
  59079. ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
  59080. ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
  59081. ** with the page number and filename associated with the (MemPage*).
  59082. */
  59083. #ifdef SQLITE_DEBUG
  59084. int corruptPageError(int lineno, MemPage *p){
  59085. char *zMsg;
  59086. sqlite3BeginBenignMalloc();
  59087. zMsg = sqlite3_mprintf("database corruption page %d of %s",
  59088. (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
  59089. );
  59090. sqlite3EndBenignMalloc();
  59091. if( zMsg ){
  59092. sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  59093. }
  59094. sqlite3_free(zMsg);
  59095. return SQLITE_CORRUPT_BKPT;
  59096. }
  59097. # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
  59098. #else
  59099. # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
  59100. #endif
  59101. #ifndef SQLITE_OMIT_SHARED_CACHE
  59102. #ifdef SQLITE_DEBUG
  59103. /*
  59104. **** This function is only used as part of an assert() statement. ***
  59105. **
  59106. ** Check to see if pBtree holds the required locks to read or write to the
  59107. ** table with root page iRoot. Return 1 if it does and 0 if not.
  59108. **
  59109. ** For example, when writing to a table with root-page iRoot via
  59110. ** Btree connection pBtree:
  59111. **
  59112. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  59113. **
  59114. ** When writing to an index that resides in a sharable database, the
  59115. ** caller should have first obtained a lock specifying the root page of
  59116. ** the corresponding table. This makes things a bit more complicated,
  59117. ** as this module treats each table as a separate structure. To determine
  59118. ** the table corresponding to the index being written, this
  59119. ** function has to search through the database schema.
  59120. **
  59121. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  59122. ** hold a write-lock on the schema table (root page 1). This is also
  59123. ** acceptable.
  59124. */
  59125. static int hasSharedCacheTableLock(
  59126. Btree *pBtree, /* Handle that must hold lock */
  59127. Pgno iRoot, /* Root page of b-tree */
  59128. int isIndex, /* True if iRoot is the root of an index b-tree */
  59129. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  59130. ){
  59131. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  59132. Pgno iTab = 0;
  59133. BtLock *pLock;
  59134. /* If this database is not shareable, or if the client is reading
  59135. ** and has the read-uncommitted flag set, then no lock is required.
  59136. ** Return true immediately.
  59137. */
  59138. if( (pBtree->sharable==0)
  59139. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
  59140. ){
  59141. return 1;
  59142. }
  59143. /* If the client is reading or writing an index and the schema is
  59144. ** not loaded, then it is too difficult to actually check to see if
  59145. ** the correct locks are held. So do not bother - just return true.
  59146. ** This case does not come up very often anyhow.
  59147. */
  59148. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  59149. return 1;
  59150. }
  59151. /* Figure out the root-page that the lock should be held on. For table
  59152. ** b-trees, this is just the root page of the b-tree being read or
  59153. ** written. For index b-trees, it is the root page of the associated
  59154. ** table. */
  59155. if( isIndex ){
  59156. HashElem *p;
  59157. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  59158. Index *pIdx = (Index *)sqliteHashData(p);
  59159. if( pIdx->tnum==(int)iRoot ){
  59160. if( iTab ){
  59161. /* Two or more indexes share the same root page. There must
  59162. ** be imposter tables. So just return true. The assert is not
  59163. ** useful in that case. */
  59164. return 1;
  59165. }
  59166. iTab = pIdx->pTable->tnum;
  59167. }
  59168. }
  59169. }else{
  59170. iTab = iRoot;
  59171. }
  59172. /* Search for the required lock. Either a write-lock on root-page iTab, a
  59173. ** write-lock on the schema table, or (if the client is reading) a
  59174. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  59175. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  59176. if( pLock->pBtree==pBtree
  59177. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  59178. && pLock->eLock>=eLockType
  59179. ){
  59180. return 1;
  59181. }
  59182. }
  59183. /* Failed to find the required lock. */
  59184. return 0;
  59185. }
  59186. #endif /* SQLITE_DEBUG */
  59187. #ifdef SQLITE_DEBUG
  59188. /*
  59189. **** This function may be used as part of assert() statements only. ****
  59190. **
  59191. ** Return true if it would be illegal for pBtree to write into the
  59192. ** table or index rooted at iRoot because other shared connections are
  59193. ** simultaneously reading that same table or index.
  59194. **
  59195. ** It is illegal for pBtree to write if some other Btree object that
  59196. ** shares the same BtShared object is currently reading or writing
  59197. ** the iRoot table. Except, if the other Btree object has the
  59198. ** read-uncommitted flag set, then it is OK for the other object to
  59199. ** have a read cursor.
  59200. **
  59201. ** For example, before writing to any part of the table or index
  59202. ** rooted at page iRoot, one should call:
  59203. **
  59204. ** assert( !hasReadConflicts(pBtree, iRoot) );
  59205. */
  59206. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  59207. BtCursor *p;
  59208. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  59209. if( p->pgnoRoot==iRoot
  59210. && p->pBtree!=pBtree
  59211. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
  59212. ){
  59213. return 1;
  59214. }
  59215. }
  59216. return 0;
  59217. }
  59218. #endif /* #ifdef SQLITE_DEBUG */
  59219. /*
  59220. ** Query to see if Btree handle p may obtain a lock of type eLock
  59221. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  59222. ** SQLITE_OK if the lock may be obtained (by calling
  59223. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  59224. */
  59225. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  59226. BtShared *pBt = p->pBt;
  59227. BtLock *pIter;
  59228. assert( sqlite3BtreeHoldsMutex(p) );
  59229. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  59230. assert( p->db!=0 );
  59231. assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
  59232. /* If requesting a write-lock, then the Btree must have an open write
  59233. ** transaction on this file. And, obviously, for this to be so there
  59234. ** must be an open write transaction on the file itself.
  59235. */
  59236. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  59237. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  59238. /* This routine is a no-op if the shared-cache is not enabled */
  59239. if( !p->sharable ){
  59240. return SQLITE_OK;
  59241. }
  59242. /* If some other connection is holding an exclusive lock, the
  59243. ** requested lock may not be obtained.
  59244. */
  59245. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  59246. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  59247. return SQLITE_LOCKED_SHAREDCACHE;
  59248. }
  59249. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  59250. /* The condition (pIter->eLock!=eLock) in the following if(...)
  59251. ** statement is a simplification of:
  59252. **
  59253. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  59254. **
  59255. ** since we know that if eLock==WRITE_LOCK, then no other connection
  59256. ** may hold a WRITE_LOCK on any table in this file (since there can
  59257. ** only be a single writer).
  59258. */
  59259. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  59260. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  59261. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  59262. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  59263. if( eLock==WRITE_LOCK ){
  59264. assert( p==pBt->pWriter );
  59265. pBt->btsFlags |= BTS_PENDING;
  59266. }
  59267. return SQLITE_LOCKED_SHAREDCACHE;
  59268. }
  59269. }
  59270. return SQLITE_OK;
  59271. }
  59272. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  59273. #ifndef SQLITE_OMIT_SHARED_CACHE
  59274. /*
  59275. ** Add a lock on the table with root-page iTable to the shared-btree used
  59276. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  59277. ** WRITE_LOCK.
  59278. **
  59279. ** This function assumes the following:
  59280. **
  59281. ** (a) The specified Btree object p is connected to a sharable
  59282. ** database (one with the BtShared.sharable flag set), and
  59283. **
  59284. ** (b) No other Btree objects hold a lock that conflicts
  59285. ** with the requested lock (i.e. querySharedCacheTableLock() has
  59286. ** already been called and returned SQLITE_OK).
  59287. **
  59288. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  59289. ** is returned if a malloc attempt fails.
  59290. */
  59291. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  59292. BtShared *pBt = p->pBt;
  59293. BtLock *pLock = 0;
  59294. BtLock *pIter;
  59295. assert( sqlite3BtreeHoldsMutex(p) );
  59296. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  59297. assert( p->db!=0 );
  59298. /* A connection with the read-uncommitted flag set will never try to
  59299. ** obtain a read-lock using this function. The only read-lock obtained
  59300. ** by a connection in read-uncommitted mode is on the sqlite_master
  59301. ** table, and that lock is obtained in BtreeBeginTrans(). */
  59302. assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
  59303. /* This function should only be called on a sharable b-tree after it
  59304. ** has been determined that no other b-tree holds a conflicting lock. */
  59305. assert( p->sharable );
  59306. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  59307. /* First search the list for an existing lock on this table. */
  59308. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  59309. if( pIter->iTable==iTable && pIter->pBtree==p ){
  59310. pLock = pIter;
  59311. break;
  59312. }
  59313. }
  59314. /* If the above search did not find a BtLock struct associating Btree p
  59315. ** with table iTable, allocate one and link it into the list.
  59316. */
  59317. if( !pLock ){
  59318. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  59319. if( !pLock ){
  59320. return SQLITE_NOMEM_BKPT;
  59321. }
  59322. pLock->iTable = iTable;
  59323. pLock->pBtree = p;
  59324. pLock->pNext = pBt->pLock;
  59325. pBt->pLock = pLock;
  59326. }
  59327. /* Set the BtLock.eLock variable to the maximum of the current lock
  59328. ** and the requested lock. This means if a write-lock was already held
  59329. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  59330. */
  59331. assert( WRITE_LOCK>READ_LOCK );
  59332. if( eLock>pLock->eLock ){
  59333. pLock->eLock = eLock;
  59334. }
  59335. return SQLITE_OK;
  59336. }
  59337. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  59338. #ifndef SQLITE_OMIT_SHARED_CACHE
  59339. /*
  59340. ** Release all the table locks (locks obtained via calls to
  59341. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  59342. **
  59343. ** This function assumes that Btree p has an open read or write
  59344. ** transaction. If it does not, then the BTS_PENDING flag
  59345. ** may be incorrectly cleared.
  59346. */
  59347. static void clearAllSharedCacheTableLocks(Btree *p){
  59348. BtShared *pBt = p->pBt;
  59349. BtLock **ppIter = &pBt->pLock;
  59350. assert( sqlite3BtreeHoldsMutex(p) );
  59351. assert( p->sharable || 0==*ppIter );
  59352. assert( p->inTrans>0 );
  59353. while( *ppIter ){
  59354. BtLock *pLock = *ppIter;
  59355. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  59356. assert( pLock->pBtree->inTrans>=pLock->eLock );
  59357. if( pLock->pBtree==p ){
  59358. *ppIter = pLock->pNext;
  59359. assert( pLock->iTable!=1 || pLock==&p->lock );
  59360. if( pLock->iTable!=1 ){
  59361. sqlite3_free(pLock);
  59362. }
  59363. }else{
  59364. ppIter = &pLock->pNext;
  59365. }
  59366. }
  59367. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  59368. if( pBt->pWriter==p ){
  59369. pBt->pWriter = 0;
  59370. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  59371. }else if( pBt->nTransaction==2 ){
  59372. /* This function is called when Btree p is concluding its
  59373. ** transaction. If there currently exists a writer, and p is not
  59374. ** that writer, then the number of locks held by connections other
  59375. ** than the writer must be about to drop to zero. In this case
  59376. ** set the BTS_PENDING flag to 0.
  59377. **
  59378. ** If there is not currently a writer, then BTS_PENDING must
  59379. ** be zero already. So this next line is harmless in that case.
  59380. */
  59381. pBt->btsFlags &= ~BTS_PENDING;
  59382. }
  59383. }
  59384. /*
  59385. ** This function changes all write-locks held by Btree p into read-locks.
  59386. */
  59387. static void downgradeAllSharedCacheTableLocks(Btree *p){
  59388. BtShared *pBt = p->pBt;
  59389. if( pBt->pWriter==p ){
  59390. BtLock *pLock;
  59391. pBt->pWriter = 0;
  59392. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  59393. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  59394. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  59395. pLock->eLock = READ_LOCK;
  59396. }
  59397. }
  59398. }
  59399. #endif /* SQLITE_OMIT_SHARED_CACHE */
  59400. static void releasePage(MemPage *pPage); /* Forward reference */
  59401. static void releasePageOne(MemPage *pPage); /* Forward reference */
  59402. static void releasePageNotNull(MemPage *pPage); /* Forward reference */
  59403. /*
  59404. ***** This routine is used inside of assert() only ****
  59405. **
  59406. ** Verify that the cursor holds the mutex on its BtShared
  59407. */
  59408. #ifdef SQLITE_DEBUG
  59409. static int cursorHoldsMutex(BtCursor *p){
  59410. return sqlite3_mutex_held(p->pBt->mutex);
  59411. }
  59412. /* Verify that the cursor and the BtShared agree about what is the current
  59413. ** database connetion. This is important in shared-cache mode. If the database
  59414. ** connection pointers get out-of-sync, it is possible for routines like
  59415. ** btreeInitPage() to reference an stale connection pointer that references a
  59416. ** a connection that has already closed. This routine is used inside assert()
  59417. ** statements only and for the purpose of double-checking that the btree code
  59418. ** does keep the database connection pointers up-to-date.
  59419. */
  59420. static int cursorOwnsBtShared(BtCursor *p){
  59421. assert( cursorHoldsMutex(p) );
  59422. return (p->pBtree->db==p->pBt->db);
  59423. }
  59424. #endif
  59425. /*
  59426. ** Invalidate the overflow cache of the cursor passed as the first argument.
  59427. ** on the shared btree structure pBt.
  59428. */
  59429. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  59430. /*
  59431. ** Invalidate the overflow page-list cache for all cursors opened
  59432. ** on the shared btree structure pBt.
  59433. */
  59434. static void invalidateAllOverflowCache(BtShared *pBt){
  59435. BtCursor *p;
  59436. assert( sqlite3_mutex_held(pBt->mutex) );
  59437. for(p=pBt->pCursor; p; p=p->pNext){
  59438. invalidateOverflowCache(p);
  59439. }
  59440. }
  59441. #ifndef SQLITE_OMIT_INCRBLOB
  59442. /*
  59443. ** This function is called before modifying the contents of a table
  59444. ** to invalidate any incrblob cursors that are open on the
  59445. ** row or one of the rows being modified.
  59446. **
  59447. ** If argument isClearTable is true, then the entire contents of the
  59448. ** table is about to be deleted. In this case invalidate all incrblob
  59449. ** cursors open on any row within the table with root-page pgnoRoot.
  59450. **
  59451. ** Otherwise, if argument isClearTable is false, then the row with
  59452. ** rowid iRow is being replaced or deleted. In this case invalidate
  59453. ** only those incrblob cursors open on that specific row.
  59454. */
  59455. static void invalidateIncrblobCursors(
  59456. Btree *pBtree, /* The database file to check */
  59457. Pgno pgnoRoot, /* The table that might be changing */
  59458. i64 iRow, /* The rowid that might be changing */
  59459. int isClearTable /* True if all rows are being deleted */
  59460. ){
  59461. BtCursor *p;
  59462. if( pBtree->hasIncrblobCur==0 ) return;
  59463. assert( sqlite3BtreeHoldsMutex(pBtree) );
  59464. pBtree->hasIncrblobCur = 0;
  59465. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  59466. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  59467. pBtree->hasIncrblobCur = 1;
  59468. if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
  59469. p->eState = CURSOR_INVALID;
  59470. }
  59471. }
  59472. }
  59473. }
  59474. #else
  59475. /* Stub function when INCRBLOB is omitted */
  59476. #define invalidateIncrblobCursors(w,x,y,z)
  59477. #endif /* SQLITE_OMIT_INCRBLOB */
  59478. /*
  59479. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  59480. ** when a page that previously contained data becomes a free-list leaf
  59481. ** page.
  59482. **
  59483. ** The BtShared.pHasContent bitvec exists to work around an obscure
  59484. ** bug caused by the interaction of two useful IO optimizations surrounding
  59485. ** free-list leaf pages:
  59486. **
  59487. ** 1) When all data is deleted from a page and the page becomes
  59488. ** a free-list leaf page, the page is not written to the database
  59489. ** (as free-list leaf pages contain no meaningful data). Sometimes
  59490. ** such a page is not even journalled (as it will not be modified,
  59491. ** why bother journalling it?).
  59492. **
  59493. ** 2) When a free-list leaf page is reused, its content is not read
  59494. ** from the database or written to the journal file (why should it
  59495. ** be, if it is not at all meaningful?).
  59496. **
  59497. ** By themselves, these optimizations work fine and provide a handy
  59498. ** performance boost to bulk delete or insert operations. However, if
  59499. ** a page is moved to the free-list and then reused within the same
  59500. ** transaction, a problem comes up. If the page is not journalled when
  59501. ** it is moved to the free-list and it is also not journalled when it
  59502. ** is extracted from the free-list and reused, then the original data
  59503. ** may be lost. In the event of a rollback, it may not be possible
  59504. ** to restore the database to its original configuration.
  59505. **
  59506. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  59507. ** moved to become a free-list leaf page, the corresponding bit is
  59508. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  59509. ** optimization 2 above is omitted if the corresponding bit is already
  59510. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  59511. ** at the end of every transaction.
  59512. */
  59513. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  59514. int rc = SQLITE_OK;
  59515. if( !pBt->pHasContent ){
  59516. assert( pgno<=pBt->nPage );
  59517. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  59518. if( !pBt->pHasContent ){
  59519. rc = SQLITE_NOMEM_BKPT;
  59520. }
  59521. }
  59522. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  59523. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  59524. }
  59525. return rc;
  59526. }
  59527. /*
  59528. ** Query the BtShared.pHasContent vector.
  59529. **
  59530. ** This function is called when a free-list leaf page is removed from the
  59531. ** free-list for reuse. It returns false if it is safe to retrieve the
  59532. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  59533. */
  59534. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  59535. Bitvec *p = pBt->pHasContent;
  59536. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  59537. }
  59538. /*
  59539. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  59540. ** invoked at the conclusion of each write-transaction.
  59541. */
  59542. static void btreeClearHasContent(BtShared *pBt){
  59543. sqlite3BitvecDestroy(pBt->pHasContent);
  59544. pBt->pHasContent = 0;
  59545. }
  59546. /*
  59547. ** Release all of the apPage[] pages for a cursor.
  59548. */
  59549. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  59550. int i;
  59551. if( pCur->iPage>=0 ){
  59552. for(i=0; i<pCur->iPage; i++){
  59553. releasePageNotNull(pCur->apPage[i]);
  59554. }
  59555. releasePageNotNull(pCur->pPage);
  59556. pCur->iPage = -1;
  59557. }
  59558. }
  59559. /*
  59560. ** The cursor passed as the only argument must point to a valid entry
  59561. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  59562. ** function saves the current cursor key in variables pCur->nKey and
  59563. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  59564. ** code otherwise.
  59565. **
  59566. ** If the cursor is open on an intkey table, then the integer key
  59567. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  59568. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  59569. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  59570. ** the key.
  59571. */
  59572. static int saveCursorKey(BtCursor *pCur){
  59573. int rc = SQLITE_OK;
  59574. assert( CURSOR_VALID==pCur->eState );
  59575. assert( 0==pCur->pKey );
  59576. assert( cursorHoldsMutex(pCur) );
  59577. if( pCur->curIntKey ){
  59578. /* Only the rowid is required for a table btree */
  59579. pCur->nKey = sqlite3BtreeIntegerKey(pCur);
  59580. }else{
  59581. /* For an index btree, save the complete key content */
  59582. void *pKey;
  59583. pCur->nKey = sqlite3BtreePayloadSize(pCur);
  59584. pKey = sqlite3Malloc( pCur->nKey );
  59585. if( pKey ){
  59586. rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
  59587. if( rc==SQLITE_OK ){
  59588. pCur->pKey = pKey;
  59589. }else{
  59590. sqlite3_free(pKey);
  59591. }
  59592. }else{
  59593. rc = SQLITE_NOMEM_BKPT;
  59594. }
  59595. }
  59596. assert( !pCur->curIntKey || !pCur->pKey );
  59597. return rc;
  59598. }
  59599. /*
  59600. ** Save the current cursor position in the variables BtCursor.nKey
  59601. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  59602. **
  59603. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  59604. ** prior to calling this routine.
  59605. */
  59606. static int saveCursorPosition(BtCursor *pCur){
  59607. int rc;
  59608. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  59609. assert( 0==pCur->pKey );
  59610. assert( cursorHoldsMutex(pCur) );
  59611. if( pCur->eState==CURSOR_SKIPNEXT ){
  59612. pCur->eState = CURSOR_VALID;
  59613. }else{
  59614. pCur->skipNext = 0;
  59615. }
  59616. rc = saveCursorKey(pCur);
  59617. if( rc==SQLITE_OK ){
  59618. btreeReleaseAllCursorPages(pCur);
  59619. pCur->eState = CURSOR_REQUIRESEEK;
  59620. }
  59621. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  59622. return rc;
  59623. }
  59624. /* Forward reference */
  59625. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  59626. /*
  59627. ** Save the positions of all cursors (except pExcept) that are open on
  59628. ** the table with root-page iRoot. "Saving the cursor position" means that
  59629. ** the location in the btree is remembered in such a way that it can be
  59630. ** moved back to the same spot after the btree has been modified. This
  59631. ** routine is called just before cursor pExcept is used to modify the
  59632. ** table, for example in BtreeDelete() or BtreeInsert().
  59633. **
  59634. ** If there are two or more cursors on the same btree, then all such
  59635. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  59636. ** routine enforces that rule. This routine only needs to be called in
  59637. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  59638. **
  59639. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  59640. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  59641. ** pointless call to this routine.
  59642. **
  59643. ** Implementation note: This routine merely checks to see if any cursors
  59644. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  59645. ** event that cursors are in need to being saved.
  59646. */
  59647. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  59648. BtCursor *p;
  59649. assert( sqlite3_mutex_held(pBt->mutex) );
  59650. assert( pExcept==0 || pExcept->pBt==pBt );
  59651. for(p=pBt->pCursor; p; p=p->pNext){
  59652. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  59653. }
  59654. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  59655. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  59656. return SQLITE_OK;
  59657. }
  59658. /* This helper routine to saveAllCursors does the actual work of saving
  59659. ** the cursors if and when a cursor is found that actually requires saving.
  59660. ** The common case is that no cursors need to be saved, so this routine is
  59661. ** broken out from its caller to avoid unnecessary stack pointer movement.
  59662. */
  59663. static int SQLITE_NOINLINE saveCursorsOnList(
  59664. BtCursor *p, /* The first cursor that needs saving */
  59665. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  59666. BtCursor *pExcept /* Do not save this cursor */
  59667. ){
  59668. do{
  59669. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  59670. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  59671. int rc = saveCursorPosition(p);
  59672. if( SQLITE_OK!=rc ){
  59673. return rc;
  59674. }
  59675. }else{
  59676. testcase( p->iPage>=0 );
  59677. btreeReleaseAllCursorPages(p);
  59678. }
  59679. }
  59680. p = p->pNext;
  59681. }while( p );
  59682. return SQLITE_OK;
  59683. }
  59684. /*
  59685. ** Clear the current cursor position.
  59686. */
  59687. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  59688. assert( cursorHoldsMutex(pCur) );
  59689. sqlite3_free(pCur->pKey);
  59690. pCur->pKey = 0;
  59691. pCur->eState = CURSOR_INVALID;
  59692. }
  59693. /*
  59694. ** In this version of BtreeMoveto, pKey is a packed index record
  59695. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  59696. ** record and then call BtreeMovetoUnpacked() to do the work.
  59697. */
  59698. static int btreeMoveto(
  59699. BtCursor *pCur, /* Cursor open on the btree to be searched */
  59700. const void *pKey, /* Packed key if the btree is an index */
  59701. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  59702. int bias, /* Bias search to the high end */
  59703. int *pRes /* Write search results here */
  59704. ){
  59705. int rc; /* Status code */
  59706. UnpackedRecord *pIdxKey; /* Unpacked index key */
  59707. if( pKey ){
  59708. assert( nKey==(i64)(int)nKey );
  59709. pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
  59710. if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
  59711. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  59712. if( pIdxKey->nField==0 ){
  59713. rc = SQLITE_CORRUPT_BKPT;
  59714. goto moveto_done;
  59715. }
  59716. }else{
  59717. pIdxKey = 0;
  59718. }
  59719. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  59720. moveto_done:
  59721. if( pIdxKey ){
  59722. sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
  59723. }
  59724. return rc;
  59725. }
  59726. /*
  59727. ** Restore the cursor to the position it was in (or as close to as possible)
  59728. ** when saveCursorPosition() was called. Note that this call deletes the
  59729. ** saved position info stored by saveCursorPosition(), so there can be
  59730. ** at most one effective restoreCursorPosition() call after each
  59731. ** saveCursorPosition().
  59732. */
  59733. static int btreeRestoreCursorPosition(BtCursor *pCur){
  59734. int rc;
  59735. int skipNext;
  59736. assert( cursorOwnsBtShared(pCur) );
  59737. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  59738. if( pCur->eState==CURSOR_FAULT ){
  59739. return pCur->skipNext;
  59740. }
  59741. pCur->eState = CURSOR_INVALID;
  59742. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  59743. if( rc==SQLITE_OK ){
  59744. sqlite3_free(pCur->pKey);
  59745. pCur->pKey = 0;
  59746. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  59747. pCur->skipNext |= skipNext;
  59748. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  59749. pCur->eState = CURSOR_SKIPNEXT;
  59750. }
  59751. }
  59752. return rc;
  59753. }
  59754. #define restoreCursorPosition(p) \
  59755. (p->eState>=CURSOR_REQUIRESEEK ? \
  59756. btreeRestoreCursorPosition(p) : \
  59757. SQLITE_OK)
  59758. /*
  59759. ** Determine whether or not a cursor has moved from the position where
  59760. ** it was last placed, or has been invalidated for any other reason.
  59761. ** Cursors can move when the row they are pointing at is deleted out
  59762. ** from under them, for example. Cursor might also move if a btree
  59763. ** is rebalanced.
  59764. **
  59765. ** Calling this routine with a NULL cursor pointer returns false.
  59766. **
  59767. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  59768. ** back to where it ought to be if this routine returns true.
  59769. */
  59770. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  59771. assert( EIGHT_BYTE_ALIGNMENT(pCur)
  59772. || pCur==sqlite3BtreeFakeValidCursor() );
  59773. assert( offsetof(BtCursor, eState)==0 );
  59774. assert( sizeof(pCur->eState)==1 );
  59775. return CURSOR_VALID != *(u8*)pCur;
  59776. }
  59777. /*
  59778. ** Return a pointer to a fake BtCursor object that will always answer
  59779. ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
  59780. ** cursor returned must not be used with any other Btree interface.
  59781. */
  59782. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
  59783. static u8 fakeCursor = CURSOR_VALID;
  59784. assert( offsetof(BtCursor, eState)==0 );
  59785. return (BtCursor*)&fakeCursor;
  59786. }
  59787. /*
  59788. ** This routine restores a cursor back to its original position after it
  59789. ** has been moved by some outside activity (such as a btree rebalance or
  59790. ** a row having been deleted out from under the cursor).
  59791. **
  59792. ** On success, the *pDifferentRow parameter is false if the cursor is left
  59793. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  59794. ** was pointing to has been deleted, forcing the cursor to point to some
  59795. ** nearby row.
  59796. **
  59797. ** This routine should only be called for a cursor that just returned
  59798. ** TRUE from sqlite3BtreeCursorHasMoved().
  59799. */
  59800. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  59801. int rc;
  59802. assert( pCur!=0 );
  59803. assert( pCur->eState!=CURSOR_VALID );
  59804. rc = restoreCursorPosition(pCur);
  59805. if( rc ){
  59806. *pDifferentRow = 1;
  59807. return rc;
  59808. }
  59809. if( pCur->eState!=CURSOR_VALID ){
  59810. *pDifferentRow = 1;
  59811. }else{
  59812. assert( pCur->skipNext==0 );
  59813. *pDifferentRow = 0;
  59814. }
  59815. return SQLITE_OK;
  59816. }
  59817. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  59818. /*
  59819. ** Provide hints to the cursor. The particular hint given (and the type
  59820. ** and number of the varargs parameters) is determined by the eHintType
  59821. ** parameter. See the definitions of the BTREE_HINT_* macros for details.
  59822. */
  59823. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  59824. /* Used only by system that substitute their own storage engine */
  59825. }
  59826. #endif
  59827. /*
  59828. ** Provide flag hints to the cursor.
  59829. */
  59830. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  59831. assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  59832. pCur->hints = x;
  59833. }
  59834. #ifndef SQLITE_OMIT_AUTOVACUUM
  59835. /*
  59836. ** Given a page number of a regular database page, return the page
  59837. ** number for the pointer-map page that contains the entry for the
  59838. ** input page number.
  59839. **
  59840. ** Return 0 (not a valid page) for pgno==1 since there is
  59841. ** no pointer map associated with page 1. The integrity_check logic
  59842. ** requires that ptrmapPageno(*,1)!=1.
  59843. */
  59844. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  59845. int nPagesPerMapPage;
  59846. Pgno iPtrMap, ret;
  59847. assert( sqlite3_mutex_held(pBt->mutex) );
  59848. if( pgno<2 ) return 0;
  59849. nPagesPerMapPage = (pBt->usableSize/5)+1;
  59850. iPtrMap = (pgno-2)/nPagesPerMapPage;
  59851. ret = (iPtrMap*nPagesPerMapPage) + 2;
  59852. if( ret==PENDING_BYTE_PAGE(pBt) ){
  59853. ret++;
  59854. }
  59855. return ret;
  59856. }
  59857. /*
  59858. ** Write an entry into the pointer map.
  59859. **
  59860. ** This routine updates the pointer map entry for page number 'key'
  59861. ** so that it maps to type 'eType' and parent page number 'pgno'.
  59862. **
  59863. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  59864. ** a no-op. If an error occurs, the appropriate error code is written
  59865. ** into *pRC.
  59866. */
  59867. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  59868. DbPage *pDbPage; /* The pointer map page */
  59869. u8 *pPtrmap; /* The pointer map data */
  59870. Pgno iPtrmap; /* The pointer map page number */
  59871. int offset; /* Offset in pointer map page */
  59872. int rc; /* Return code from subfunctions */
  59873. if( *pRC ) return;
  59874. assert( sqlite3_mutex_held(pBt->mutex) );
  59875. /* The master-journal page number must never be used as a pointer map page */
  59876. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  59877. assert( pBt->autoVacuum );
  59878. if( key==0 ){
  59879. *pRC = SQLITE_CORRUPT_BKPT;
  59880. return;
  59881. }
  59882. iPtrmap = PTRMAP_PAGENO(pBt, key);
  59883. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  59884. if( rc!=SQLITE_OK ){
  59885. *pRC = rc;
  59886. return;
  59887. }
  59888. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  59889. if( offset<0 ){
  59890. *pRC = SQLITE_CORRUPT_BKPT;
  59891. goto ptrmap_exit;
  59892. }
  59893. assert( offset <= (int)pBt->usableSize-5 );
  59894. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  59895. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  59896. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  59897. *pRC= rc = sqlite3PagerWrite(pDbPage);
  59898. if( rc==SQLITE_OK ){
  59899. pPtrmap[offset] = eType;
  59900. put4byte(&pPtrmap[offset+1], parent);
  59901. }
  59902. }
  59903. ptrmap_exit:
  59904. sqlite3PagerUnref(pDbPage);
  59905. }
  59906. /*
  59907. ** Read an entry from the pointer map.
  59908. **
  59909. ** This routine retrieves the pointer map entry for page 'key', writing
  59910. ** the type and parent page number to *pEType and *pPgno respectively.
  59911. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  59912. */
  59913. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  59914. DbPage *pDbPage; /* The pointer map page */
  59915. int iPtrmap; /* Pointer map page index */
  59916. u8 *pPtrmap; /* Pointer map page data */
  59917. int offset; /* Offset of entry in pointer map */
  59918. int rc;
  59919. assert( sqlite3_mutex_held(pBt->mutex) );
  59920. iPtrmap = PTRMAP_PAGENO(pBt, key);
  59921. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  59922. if( rc!=0 ){
  59923. return rc;
  59924. }
  59925. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  59926. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  59927. if( offset<0 ){
  59928. sqlite3PagerUnref(pDbPage);
  59929. return SQLITE_CORRUPT_BKPT;
  59930. }
  59931. assert( offset <= (int)pBt->usableSize-5 );
  59932. assert( pEType!=0 );
  59933. *pEType = pPtrmap[offset];
  59934. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  59935. sqlite3PagerUnref(pDbPage);
  59936. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
  59937. return SQLITE_OK;
  59938. }
  59939. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  59940. #define ptrmapPut(w,x,y,z,rc)
  59941. #define ptrmapGet(w,x,y,z) SQLITE_OK
  59942. #define ptrmapPutOvflPtr(x, y, rc)
  59943. #endif
  59944. /*
  59945. ** Given a btree page and a cell index (0 means the first cell on
  59946. ** the page, 1 means the second cell, and so forth) return a pointer
  59947. ** to the cell content.
  59948. **
  59949. ** findCellPastPtr() does the same except it skips past the initial
  59950. ** 4-byte child pointer found on interior pages, if there is one.
  59951. **
  59952. ** This routine works only for pages that do not contain overflow cells.
  59953. */
  59954. #define findCell(P,I) \
  59955. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  59956. #define findCellPastPtr(P,I) \
  59957. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  59958. /*
  59959. ** This is common tail processing for btreeParseCellPtr() and
  59960. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  59961. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  59962. ** structure.
  59963. */
  59964. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  59965. MemPage *pPage, /* Page containing the cell */
  59966. u8 *pCell, /* Pointer to the cell text. */
  59967. CellInfo *pInfo /* Fill in this structure */
  59968. ){
  59969. /* If the payload will not fit completely on the local page, we have
  59970. ** to decide how much to store locally and how much to spill onto
  59971. ** overflow pages. The strategy is to minimize the amount of unused
  59972. ** space on overflow pages while keeping the amount of local storage
  59973. ** in between minLocal and maxLocal.
  59974. **
  59975. ** Warning: changing the way overflow payload is distributed in any
  59976. ** way will result in an incompatible file format.
  59977. */
  59978. int minLocal; /* Minimum amount of payload held locally */
  59979. int maxLocal; /* Maximum amount of payload held locally */
  59980. int surplus; /* Overflow payload available for local storage */
  59981. minLocal = pPage->minLocal;
  59982. maxLocal = pPage->maxLocal;
  59983. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  59984. testcase( surplus==maxLocal );
  59985. testcase( surplus==maxLocal+1 );
  59986. if( surplus <= maxLocal ){
  59987. pInfo->nLocal = (u16)surplus;
  59988. }else{
  59989. pInfo->nLocal = (u16)minLocal;
  59990. }
  59991. pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
  59992. }
  59993. /*
  59994. ** The following routines are implementations of the MemPage.xParseCell()
  59995. ** method.
  59996. **
  59997. ** Parse a cell content block and fill in the CellInfo structure.
  59998. **
  59999. ** btreeParseCellPtr() => table btree leaf nodes
  60000. ** btreeParseCellNoPayload() => table btree internal nodes
  60001. ** btreeParseCellPtrIndex() => index btree nodes
  60002. **
  60003. ** There is also a wrapper function btreeParseCell() that works for
  60004. ** all MemPage types and that references the cell by index rather than
  60005. ** by pointer.
  60006. */
  60007. static void btreeParseCellPtrNoPayload(
  60008. MemPage *pPage, /* Page containing the cell */
  60009. u8 *pCell, /* Pointer to the cell text. */
  60010. CellInfo *pInfo /* Fill in this structure */
  60011. ){
  60012. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60013. assert( pPage->leaf==0 );
  60014. assert( pPage->childPtrSize==4 );
  60015. #ifndef SQLITE_DEBUG
  60016. UNUSED_PARAMETER(pPage);
  60017. #endif
  60018. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  60019. pInfo->nPayload = 0;
  60020. pInfo->nLocal = 0;
  60021. pInfo->pPayload = 0;
  60022. return;
  60023. }
  60024. static void btreeParseCellPtr(
  60025. MemPage *pPage, /* Page containing the cell */
  60026. u8 *pCell, /* Pointer to the cell text. */
  60027. CellInfo *pInfo /* Fill in this structure */
  60028. ){
  60029. u8 *pIter; /* For scanning through pCell */
  60030. u32 nPayload; /* Number of bytes of cell payload */
  60031. u64 iKey; /* Extracted Key value */
  60032. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60033. assert( pPage->leaf==0 || pPage->leaf==1 );
  60034. assert( pPage->intKeyLeaf );
  60035. assert( pPage->childPtrSize==0 );
  60036. pIter = pCell;
  60037. /* The next block of code is equivalent to:
  60038. **
  60039. ** pIter += getVarint32(pIter, nPayload);
  60040. **
  60041. ** The code is inlined to avoid a function call.
  60042. */
  60043. nPayload = *pIter;
  60044. if( nPayload>=0x80 ){
  60045. u8 *pEnd = &pIter[8];
  60046. nPayload &= 0x7f;
  60047. do{
  60048. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  60049. }while( (*pIter)>=0x80 && pIter<pEnd );
  60050. }
  60051. pIter++;
  60052. /* The next block of code is equivalent to:
  60053. **
  60054. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  60055. **
  60056. ** The code is inlined to avoid a function call.
  60057. */
  60058. iKey = *pIter;
  60059. if( iKey>=0x80 ){
  60060. u8 *pEnd = &pIter[7];
  60061. iKey &= 0x7f;
  60062. while(1){
  60063. iKey = (iKey<<7) | (*++pIter & 0x7f);
  60064. if( (*pIter)<0x80 ) break;
  60065. if( pIter>=pEnd ){
  60066. iKey = (iKey<<8) | *++pIter;
  60067. break;
  60068. }
  60069. }
  60070. }
  60071. pIter++;
  60072. pInfo->nKey = *(i64*)&iKey;
  60073. pInfo->nPayload = nPayload;
  60074. pInfo->pPayload = pIter;
  60075. testcase( nPayload==pPage->maxLocal );
  60076. testcase( nPayload==pPage->maxLocal+1 );
  60077. if( nPayload<=pPage->maxLocal ){
  60078. /* This is the (easy) common case where the entire payload fits
  60079. ** on the local page. No overflow is required.
  60080. */
  60081. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  60082. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  60083. pInfo->nLocal = (u16)nPayload;
  60084. }else{
  60085. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  60086. }
  60087. }
  60088. static void btreeParseCellPtrIndex(
  60089. MemPage *pPage, /* Page containing the cell */
  60090. u8 *pCell, /* Pointer to the cell text. */
  60091. CellInfo *pInfo /* Fill in this structure */
  60092. ){
  60093. u8 *pIter; /* For scanning through pCell */
  60094. u32 nPayload; /* Number of bytes of cell payload */
  60095. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60096. assert( pPage->leaf==0 || pPage->leaf==1 );
  60097. assert( pPage->intKeyLeaf==0 );
  60098. pIter = pCell + pPage->childPtrSize;
  60099. nPayload = *pIter;
  60100. if( nPayload>=0x80 ){
  60101. u8 *pEnd = &pIter[8];
  60102. nPayload &= 0x7f;
  60103. do{
  60104. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  60105. }while( *(pIter)>=0x80 && pIter<pEnd );
  60106. }
  60107. pIter++;
  60108. pInfo->nKey = nPayload;
  60109. pInfo->nPayload = nPayload;
  60110. pInfo->pPayload = pIter;
  60111. testcase( nPayload==pPage->maxLocal );
  60112. testcase( nPayload==pPage->maxLocal+1 );
  60113. if( nPayload<=pPage->maxLocal ){
  60114. /* This is the (easy) common case where the entire payload fits
  60115. ** on the local page. No overflow is required.
  60116. */
  60117. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  60118. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  60119. pInfo->nLocal = (u16)nPayload;
  60120. }else{
  60121. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  60122. }
  60123. }
  60124. static void btreeParseCell(
  60125. MemPage *pPage, /* Page containing the cell */
  60126. int iCell, /* The cell index. First cell is 0 */
  60127. CellInfo *pInfo /* Fill in this structure */
  60128. ){
  60129. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  60130. }
  60131. /*
  60132. ** The following routines are implementations of the MemPage.xCellSize
  60133. ** method.
  60134. **
  60135. ** Compute the total number of bytes that a Cell needs in the cell
  60136. ** data area of the btree-page. The return number includes the cell
  60137. ** data header and the local payload, but not any overflow page or
  60138. ** the space used by the cell pointer.
  60139. **
  60140. ** cellSizePtrNoPayload() => table internal nodes
  60141. ** cellSizePtr() => all index nodes & table leaf nodes
  60142. */
  60143. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  60144. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  60145. u8 *pEnd; /* End mark for a varint */
  60146. u32 nSize; /* Size value to return */
  60147. #ifdef SQLITE_DEBUG
  60148. /* The value returned by this function should always be the same as
  60149. ** the (CellInfo.nSize) value found by doing a full parse of the
  60150. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  60151. ** this function verifies that this invariant is not violated. */
  60152. CellInfo debuginfo;
  60153. pPage->xParseCell(pPage, pCell, &debuginfo);
  60154. #endif
  60155. nSize = *pIter;
  60156. if( nSize>=0x80 ){
  60157. pEnd = &pIter[8];
  60158. nSize &= 0x7f;
  60159. do{
  60160. nSize = (nSize<<7) | (*++pIter & 0x7f);
  60161. }while( *(pIter)>=0x80 && pIter<pEnd );
  60162. }
  60163. pIter++;
  60164. if( pPage->intKey ){
  60165. /* pIter now points at the 64-bit integer key value, a variable length
  60166. ** integer. The following block moves pIter to point at the first byte
  60167. ** past the end of the key value. */
  60168. pEnd = &pIter[9];
  60169. while( (*pIter++)&0x80 && pIter<pEnd );
  60170. }
  60171. testcase( nSize==pPage->maxLocal );
  60172. testcase( nSize==pPage->maxLocal+1 );
  60173. if( nSize<=pPage->maxLocal ){
  60174. nSize += (u32)(pIter - pCell);
  60175. if( nSize<4 ) nSize = 4;
  60176. }else{
  60177. int minLocal = pPage->minLocal;
  60178. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  60179. testcase( nSize==pPage->maxLocal );
  60180. testcase( nSize==pPage->maxLocal+1 );
  60181. if( nSize>pPage->maxLocal ){
  60182. nSize = minLocal;
  60183. }
  60184. nSize += 4 + (u16)(pIter - pCell);
  60185. }
  60186. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  60187. return (u16)nSize;
  60188. }
  60189. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  60190. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  60191. u8 *pEnd; /* End mark for a varint */
  60192. #ifdef SQLITE_DEBUG
  60193. /* The value returned by this function should always be the same as
  60194. ** the (CellInfo.nSize) value found by doing a full parse of the
  60195. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  60196. ** this function verifies that this invariant is not violated. */
  60197. CellInfo debuginfo;
  60198. pPage->xParseCell(pPage, pCell, &debuginfo);
  60199. #else
  60200. UNUSED_PARAMETER(pPage);
  60201. #endif
  60202. assert( pPage->childPtrSize==4 );
  60203. pEnd = pIter + 9;
  60204. while( (*pIter++)&0x80 && pIter<pEnd );
  60205. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  60206. return (u16)(pIter - pCell);
  60207. }
  60208. #ifdef SQLITE_DEBUG
  60209. /* This variation on cellSizePtr() is used inside of assert() statements
  60210. ** only. */
  60211. static u16 cellSize(MemPage *pPage, int iCell){
  60212. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  60213. }
  60214. #endif
  60215. #ifndef SQLITE_OMIT_AUTOVACUUM
  60216. /*
  60217. ** If the cell pCell, part of page pPage contains a pointer
  60218. ** to an overflow page, insert an entry into the pointer-map
  60219. ** for the overflow page.
  60220. */
  60221. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  60222. CellInfo info;
  60223. if( *pRC ) return;
  60224. assert( pCell!=0 );
  60225. pPage->xParseCell(pPage, pCell, &info);
  60226. if( info.nLocal<info.nPayload ){
  60227. Pgno ovfl = get4byte(&pCell[info.nSize-4]);
  60228. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  60229. }
  60230. }
  60231. #endif
  60232. /*
  60233. ** Defragment the page given. This routine reorganizes cells within the
  60234. ** page so that there are no free-blocks on the free-block list.
  60235. **
  60236. ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
  60237. ** present in the page after this routine returns.
  60238. **
  60239. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  60240. ** b-tree page so that there are no freeblocks or fragment bytes, all
  60241. ** unused bytes are contained in the unallocated space region, and all
  60242. ** cells are packed tightly at the end of the page.
  60243. */
  60244. static int defragmentPage(MemPage *pPage, int nMaxFrag){
  60245. int i; /* Loop counter */
  60246. int pc; /* Address of the i-th cell */
  60247. int hdr; /* Offset to the page header */
  60248. int size; /* Size of a cell */
  60249. int usableSize; /* Number of usable bytes on a page */
  60250. int cellOffset; /* Offset to the cell pointer array */
  60251. int cbrk; /* Offset to the cell content area */
  60252. int nCell; /* Number of cells on the page */
  60253. unsigned char *data; /* The page data */
  60254. unsigned char *temp; /* Temp area for cell content */
  60255. unsigned char *src; /* Source of content */
  60256. int iCellFirst; /* First allowable cell index */
  60257. int iCellLast; /* Last possible cell index */
  60258. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60259. assert( pPage->pBt!=0 );
  60260. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  60261. assert( pPage->nOverflow==0 );
  60262. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60263. temp = 0;
  60264. src = data = pPage->aData;
  60265. hdr = pPage->hdrOffset;
  60266. cellOffset = pPage->cellOffset;
  60267. nCell = pPage->nCell;
  60268. assert( nCell==get2byte(&data[hdr+3]) );
  60269. iCellFirst = cellOffset + 2*nCell;
  60270. usableSize = pPage->pBt->usableSize;
  60271. /* This block handles pages with two or fewer free blocks and nMaxFrag
  60272. ** or fewer fragmented bytes. In this case it is faster to move the
  60273. ** two (or one) blocks of cells using memmove() and add the required
  60274. ** offsets to each pointer in the cell-pointer array than it is to
  60275. ** reconstruct the entire page. */
  60276. if( (int)data[hdr+7]<=nMaxFrag ){
  60277. int iFree = get2byte(&data[hdr+1]);
  60278. if( iFree ){
  60279. int iFree2 = get2byte(&data[iFree]);
  60280. /* pageFindSlot() has already verified that free blocks are sorted
  60281. ** in order of offset within the page, and that no block extends
  60282. ** past the end of the page. Provided the two free slots do not
  60283. ** overlap, this guarantees that the memmove() calls below will not
  60284. ** overwrite the usableSize byte buffer, even if the database page
  60285. ** is corrupt. */
  60286. assert( iFree2==0 || iFree2>iFree );
  60287. assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
  60288. assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
  60289. if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
  60290. u8 *pEnd = &data[cellOffset + nCell*2];
  60291. u8 *pAddr;
  60292. int sz2 = 0;
  60293. int sz = get2byte(&data[iFree+2]);
  60294. int top = get2byte(&data[hdr+5]);
  60295. if( top>=iFree ){
  60296. return SQLITE_CORRUPT_PAGE(pPage);
  60297. }
  60298. if( iFree2 ){
  60299. assert( iFree+sz<=iFree2 ); /* Verified by pageFindSlot() */
  60300. sz2 = get2byte(&data[iFree2+2]);
  60301. assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
  60302. memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
  60303. sz += sz2;
  60304. }
  60305. cbrk = top+sz;
  60306. assert( cbrk+(iFree-top) <= usableSize );
  60307. memmove(&data[cbrk], &data[top], iFree-top);
  60308. for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
  60309. pc = get2byte(pAddr);
  60310. if( pc<iFree ){ put2byte(pAddr, pc+sz); }
  60311. else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
  60312. }
  60313. goto defragment_out;
  60314. }
  60315. }
  60316. }
  60317. cbrk = usableSize;
  60318. iCellLast = usableSize - 4;
  60319. for(i=0; i<nCell; i++){
  60320. u8 *pAddr; /* The i-th cell pointer */
  60321. pAddr = &data[cellOffset + i*2];
  60322. pc = get2byte(pAddr);
  60323. testcase( pc==iCellFirst );
  60324. testcase( pc==iCellLast );
  60325. /* These conditions have already been verified in btreeInitPage()
  60326. ** if PRAGMA cell_size_check=ON.
  60327. */
  60328. if( pc<iCellFirst || pc>iCellLast ){
  60329. return SQLITE_CORRUPT_PAGE(pPage);
  60330. }
  60331. assert( pc>=iCellFirst && pc<=iCellLast );
  60332. size = pPage->xCellSize(pPage, &src[pc]);
  60333. cbrk -= size;
  60334. if( cbrk<iCellFirst || pc+size>usableSize ){
  60335. return SQLITE_CORRUPT_PAGE(pPage);
  60336. }
  60337. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  60338. testcase( cbrk+size==usableSize );
  60339. testcase( pc+size==usableSize );
  60340. put2byte(pAddr, cbrk);
  60341. if( temp==0 ){
  60342. int x;
  60343. if( cbrk==pc ) continue;
  60344. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  60345. x = get2byte(&data[hdr+5]);
  60346. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  60347. src = temp;
  60348. }
  60349. memcpy(&data[cbrk], &src[pc], size);
  60350. }
  60351. data[hdr+7] = 0;
  60352. defragment_out:
  60353. if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
  60354. return SQLITE_CORRUPT_PAGE(pPage);
  60355. }
  60356. assert( cbrk>=iCellFirst );
  60357. put2byte(&data[hdr+5], cbrk);
  60358. data[hdr+1] = 0;
  60359. data[hdr+2] = 0;
  60360. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  60361. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60362. return SQLITE_OK;
  60363. }
  60364. /*
  60365. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  60366. ** size. If one can be found, return a pointer to the space and remove it
  60367. ** from the free-list.
  60368. **
  60369. ** If no suitable space can be found on the free-list, return NULL.
  60370. **
  60371. ** This function may detect corruption within pPg. If corruption is
  60372. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  60373. **
  60374. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  60375. ** will be ignored if adding the extra space to the fragmentation count
  60376. ** causes the fragmentation count to exceed 60.
  60377. */
  60378. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  60379. const int hdr = pPg->hdrOffset;
  60380. u8 * const aData = pPg->aData;
  60381. int iAddr = hdr + 1;
  60382. int pc = get2byte(&aData[iAddr]);
  60383. int x;
  60384. int usableSize = pPg->pBt->usableSize;
  60385. int size; /* Size of the free slot */
  60386. assert( pc>0 );
  60387. while( pc<=usableSize-4 ){
  60388. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  60389. ** freeblock form a big-endian integer which is the size of the freeblock
  60390. ** in bytes, including the 4-byte header. */
  60391. size = get2byte(&aData[pc+2]);
  60392. if( (x = size - nByte)>=0 ){
  60393. testcase( x==4 );
  60394. testcase( x==3 );
  60395. if( size+pc > usableSize ){
  60396. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  60397. return 0;
  60398. }else if( x<4 ){
  60399. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  60400. ** number of bytes in fragments may not exceed 60. */
  60401. if( aData[hdr+7]>57 ) return 0;
  60402. /* Remove the slot from the free-list. Update the number of
  60403. ** fragmented bytes within the page. */
  60404. memcpy(&aData[iAddr], &aData[pc], 2);
  60405. aData[hdr+7] += (u8)x;
  60406. }else{
  60407. /* The slot remains on the free-list. Reduce its size to account
  60408. ** for the portion used by the new allocation. */
  60409. put2byte(&aData[pc+2], x);
  60410. }
  60411. return &aData[pc + x];
  60412. }
  60413. iAddr = pc;
  60414. pc = get2byte(&aData[pc]);
  60415. if( pc<iAddr+size ) break;
  60416. }
  60417. if( pc ){
  60418. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  60419. }
  60420. return 0;
  60421. }
  60422. /*
  60423. ** Allocate nByte bytes of space from within the B-Tree page passed
  60424. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  60425. ** of the first byte of allocated space. Return either SQLITE_OK or
  60426. ** an error code (usually SQLITE_CORRUPT).
  60427. **
  60428. ** The caller guarantees that there is sufficient space to make the
  60429. ** allocation. This routine might need to defragment in order to bring
  60430. ** all the space together, however. This routine will avoid using
  60431. ** the first two bytes past the cell pointer area since presumably this
  60432. ** allocation is being made in order to insert a new cell, so we will
  60433. ** also end up needing a new cell pointer.
  60434. */
  60435. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  60436. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  60437. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  60438. int top; /* First byte of cell content area */
  60439. int rc = SQLITE_OK; /* Integer return code */
  60440. int gap; /* First byte of gap between cell pointers and cell content */
  60441. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60442. assert( pPage->pBt );
  60443. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60444. assert( nByte>=0 ); /* Minimum cell size is 4 */
  60445. assert( pPage->nFree>=nByte );
  60446. assert( pPage->nOverflow==0 );
  60447. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  60448. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  60449. gap = pPage->cellOffset + 2*pPage->nCell;
  60450. assert( gap<=65536 );
  60451. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  60452. ** and the reserved space is zero (the usual value for reserved space)
  60453. ** then the cell content offset of an empty page wants to be 65536.
  60454. ** However, that integer is too large to be stored in a 2-byte unsigned
  60455. ** integer, so a value of 0 is used in its place. */
  60456. top = get2byte(&data[hdr+5]);
  60457. assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
  60458. if( gap>top ){
  60459. if( top==0 && pPage->pBt->usableSize==65536 ){
  60460. top = 65536;
  60461. }else{
  60462. return SQLITE_CORRUPT_PAGE(pPage);
  60463. }
  60464. }
  60465. /* If there is enough space between gap and top for one more cell pointer
  60466. ** array entry offset, and if the freelist is not empty, then search the
  60467. ** freelist looking for a free slot big enough to satisfy the request.
  60468. */
  60469. testcase( gap+2==top );
  60470. testcase( gap+1==top );
  60471. testcase( gap==top );
  60472. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  60473. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  60474. if( pSpace ){
  60475. assert( pSpace>=data && (pSpace - data)<65536 );
  60476. *pIdx = (int)(pSpace - data);
  60477. return SQLITE_OK;
  60478. }else if( rc ){
  60479. return rc;
  60480. }
  60481. }
  60482. /* The request could not be fulfilled using a freelist slot. Check
  60483. ** to see if defragmentation is necessary.
  60484. */
  60485. testcase( gap+2+nByte==top );
  60486. if( gap+2+nByte>top ){
  60487. assert( pPage->nCell>0 || CORRUPT_DB );
  60488. rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
  60489. if( rc ) return rc;
  60490. top = get2byteNotZero(&data[hdr+5]);
  60491. assert( gap+2+nByte<=top );
  60492. }
  60493. /* Allocate memory from the gap in between the cell pointer array
  60494. ** and the cell content area. The btreeInitPage() call has already
  60495. ** validated the freelist. Given that the freelist is valid, there
  60496. ** is no way that the allocation can extend off the end of the page.
  60497. ** The assert() below verifies the previous sentence.
  60498. */
  60499. top -= nByte;
  60500. put2byte(&data[hdr+5], top);
  60501. assert( top+nByte <= (int)pPage->pBt->usableSize );
  60502. *pIdx = top;
  60503. return SQLITE_OK;
  60504. }
  60505. /*
  60506. ** Return a section of the pPage->aData to the freelist.
  60507. ** The first byte of the new free block is pPage->aData[iStart]
  60508. ** and the size of the block is iSize bytes.
  60509. **
  60510. ** Adjacent freeblocks are coalesced.
  60511. **
  60512. ** Note that even though the freeblock list was checked by btreeInitPage(),
  60513. ** that routine will not detect overlap between cells or freeblocks. Nor
  60514. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  60515. ** at the end of the page. So do additional corruption checks inside this
  60516. ** routine and return SQLITE_CORRUPT if any problems are found.
  60517. */
  60518. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  60519. u16 iPtr; /* Address of ptr to next freeblock */
  60520. u16 iFreeBlk; /* Address of the next freeblock */
  60521. u8 hdr; /* Page header size. 0 or 100 */
  60522. u8 nFrag = 0; /* Reduction in fragmentation */
  60523. u16 iOrigSize = iSize; /* Original value of iSize */
  60524. u16 x; /* Offset to cell content area */
  60525. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  60526. unsigned char *data = pPage->aData; /* Page content */
  60527. assert( pPage->pBt!=0 );
  60528. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60529. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  60530. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  60531. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60532. assert( iSize>=4 ); /* Minimum cell size is 4 */
  60533. assert( iStart<=pPage->pBt->usableSize-4 );
  60534. /* The list of freeblocks must be in ascending order. Find the
  60535. ** spot on the list where iStart should be inserted.
  60536. */
  60537. hdr = pPage->hdrOffset;
  60538. iPtr = hdr + 1;
  60539. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  60540. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  60541. }else{
  60542. while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
  60543. if( iFreeBlk<iPtr+4 ){
  60544. if( iFreeBlk==0 ) break;
  60545. return SQLITE_CORRUPT_PAGE(pPage);
  60546. }
  60547. iPtr = iFreeBlk;
  60548. }
  60549. if( iFreeBlk>pPage->pBt->usableSize-4 ){
  60550. return SQLITE_CORRUPT_PAGE(pPage);
  60551. }
  60552. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  60553. /* At this point:
  60554. ** iFreeBlk: First freeblock after iStart, or zero if none
  60555. ** iPtr: The address of a pointer to iFreeBlk
  60556. **
  60557. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  60558. */
  60559. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  60560. nFrag = iFreeBlk - iEnd;
  60561. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
  60562. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  60563. if( iEnd > pPage->pBt->usableSize ){
  60564. return SQLITE_CORRUPT_PAGE(pPage);
  60565. }
  60566. iSize = iEnd - iStart;
  60567. iFreeBlk = get2byte(&data[iFreeBlk]);
  60568. }
  60569. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  60570. ** pointer in the page header) then check to see if iStart should be
  60571. ** coalesced onto the end of iPtr.
  60572. */
  60573. if( iPtr>hdr+1 ){
  60574. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  60575. if( iPtrEnd+3>=iStart ){
  60576. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
  60577. nFrag += iStart - iPtrEnd;
  60578. iSize = iEnd - iPtr;
  60579. iStart = iPtr;
  60580. }
  60581. }
  60582. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
  60583. data[hdr+7] -= nFrag;
  60584. }
  60585. x = get2byte(&data[hdr+5]);
  60586. if( iStart<=x ){
  60587. /* The new freeblock is at the beginning of the cell content area,
  60588. ** so just extend the cell content area rather than create another
  60589. ** freelist entry */
  60590. if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
  60591. put2byte(&data[hdr+1], iFreeBlk);
  60592. put2byte(&data[hdr+5], iEnd);
  60593. }else{
  60594. /* Insert the new freeblock into the freelist */
  60595. put2byte(&data[iPtr], iStart);
  60596. }
  60597. if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
  60598. /* Overwrite deleted information with zeros when the secure_delete
  60599. ** option is enabled */
  60600. memset(&data[iStart], 0, iSize);
  60601. }
  60602. put2byte(&data[iStart], iFreeBlk);
  60603. put2byte(&data[iStart+2], iSize);
  60604. pPage->nFree += iOrigSize;
  60605. return SQLITE_OK;
  60606. }
  60607. /*
  60608. ** Decode the flags byte (the first byte of the header) for a page
  60609. ** and initialize fields of the MemPage structure accordingly.
  60610. **
  60611. ** Only the following combinations are supported. Anything different
  60612. ** indicates a corrupt database files:
  60613. **
  60614. ** PTF_ZERODATA
  60615. ** PTF_ZERODATA | PTF_LEAF
  60616. ** PTF_LEAFDATA | PTF_INTKEY
  60617. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  60618. */
  60619. static int decodeFlags(MemPage *pPage, int flagByte){
  60620. BtShared *pBt; /* A copy of pPage->pBt */
  60621. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  60622. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60623. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  60624. flagByte &= ~PTF_LEAF;
  60625. pPage->childPtrSize = 4-4*pPage->leaf;
  60626. pPage->xCellSize = cellSizePtr;
  60627. pBt = pPage->pBt;
  60628. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  60629. /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
  60630. ** interior table b-tree page. */
  60631. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  60632. /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
  60633. ** leaf table b-tree page. */
  60634. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  60635. pPage->intKey = 1;
  60636. if( pPage->leaf ){
  60637. pPage->intKeyLeaf = 1;
  60638. pPage->xParseCell = btreeParseCellPtr;
  60639. }else{
  60640. pPage->intKeyLeaf = 0;
  60641. pPage->xCellSize = cellSizePtrNoPayload;
  60642. pPage->xParseCell = btreeParseCellPtrNoPayload;
  60643. }
  60644. pPage->maxLocal = pBt->maxLeaf;
  60645. pPage->minLocal = pBt->minLeaf;
  60646. }else if( flagByte==PTF_ZERODATA ){
  60647. /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
  60648. ** interior index b-tree page. */
  60649. assert( (PTF_ZERODATA)==2 );
  60650. /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
  60651. ** leaf index b-tree page. */
  60652. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  60653. pPage->intKey = 0;
  60654. pPage->intKeyLeaf = 0;
  60655. pPage->xParseCell = btreeParseCellPtrIndex;
  60656. pPage->maxLocal = pBt->maxLocal;
  60657. pPage->minLocal = pBt->minLocal;
  60658. }else{
  60659. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  60660. ** an error. */
  60661. return SQLITE_CORRUPT_PAGE(pPage);
  60662. }
  60663. pPage->max1bytePayload = pBt->max1bytePayload;
  60664. return SQLITE_OK;
  60665. }
  60666. /*
  60667. ** Initialize the auxiliary information for a disk block.
  60668. **
  60669. ** Return SQLITE_OK on success. If we see that the page does
  60670. ** not contain a well-formed database page, then return
  60671. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  60672. ** guarantee that the page is well-formed. It only shows that
  60673. ** we failed to detect any corruption.
  60674. */
  60675. static int btreeInitPage(MemPage *pPage){
  60676. int pc; /* Address of a freeblock within pPage->aData[] */
  60677. u8 hdr; /* Offset to beginning of page header */
  60678. u8 *data; /* Equal to pPage->aData */
  60679. BtShared *pBt; /* The main btree structure */
  60680. int usableSize; /* Amount of usable space on each page */
  60681. u16 cellOffset; /* Offset from start of page to first cell pointer */
  60682. int nFree; /* Number of unused bytes on the page */
  60683. int top; /* First byte of the cell content area */
  60684. int iCellFirst; /* First allowable cell or freeblock offset */
  60685. int iCellLast; /* Last possible cell or freeblock offset */
  60686. assert( pPage->pBt!=0 );
  60687. assert( pPage->pBt->db!=0 );
  60688. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60689. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  60690. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  60691. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  60692. assert( pPage->isInit==0 );
  60693. pBt = pPage->pBt;
  60694. hdr = pPage->hdrOffset;
  60695. data = pPage->aData;
  60696. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  60697. ** the b-tree page type. */
  60698. if( decodeFlags(pPage, data[hdr]) ){
  60699. return SQLITE_CORRUPT_PAGE(pPage);
  60700. }
  60701. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  60702. pPage->maskPage = (u16)(pBt->pageSize - 1);
  60703. pPage->nOverflow = 0;
  60704. usableSize = pBt->usableSize;
  60705. pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
  60706. pPage->aDataEnd = &data[usableSize];
  60707. pPage->aCellIdx = &data[cellOffset];
  60708. pPage->aDataOfst = &data[pPage->childPtrSize];
  60709. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  60710. ** the start of the cell content area. A zero value for this integer is
  60711. ** interpreted as 65536. */
  60712. top = get2byteNotZero(&data[hdr+5]);
  60713. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  60714. ** number of cells on the page. */
  60715. pPage->nCell = get2byte(&data[hdr+3]);
  60716. if( pPage->nCell>MX_CELL(pBt) ){
  60717. /* To many cells for a single page. The page must be corrupt */
  60718. return SQLITE_CORRUPT_PAGE(pPage);
  60719. }
  60720. testcase( pPage->nCell==MX_CELL(pBt) );
  60721. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  60722. ** possible for a root page of a table that contains no rows) then the
  60723. ** offset to the cell content area will equal the page size minus the
  60724. ** bytes of reserved space. */
  60725. assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
  60726. /* A malformed database page might cause us to read past the end
  60727. ** of page when parsing a cell.
  60728. **
  60729. ** The following block of code checks early to see if a cell extends
  60730. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  60731. ** returned if it does.
  60732. */
  60733. iCellFirst = cellOffset + 2*pPage->nCell;
  60734. iCellLast = usableSize - 4;
  60735. if( pBt->db->flags & SQLITE_CellSizeCk ){
  60736. int i; /* Index into the cell pointer array */
  60737. int sz; /* Size of a cell */
  60738. if( !pPage->leaf ) iCellLast--;
  60739. for(i=0; i<pPage->nCell; i++){
  60740. pc = get2byteAligned(&data[cellOffset+i*2]);
  60741. testcase( pc==iCellFirst );
  60742. testcase( pc==iCellLast );
  60743. if( pc<iCellFirst || pc>iCellLast ){
  60744. return SQLITE_CORRUPT_PAGE(pPage);
  60745. }
  60746. sz = pPage->xCellSize(pPage, &data[pc]);
  60747. testcase( pc+sz==usableSize );
  60748. if( pc+sz>usableSize ){
  60749. return SQLITE_CORRUPT_PAGE(pPage);
  60750. }
  60751. }
  60752. if( !pPage->leaf ) iCellLast++;
  60753. }
  60754. /* Compute the total free space on the page
  60755. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  60756. ** start of the first freeblock on the page, or is zero if there are no
  60757. ** freeblocks. */
  60758. pc = get2byte(&data[hdr+1]);
  60759. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  60760. if( pc>0 ){
  60761. u32 next, size;
  60762. if( pc<iCellFirst ){
  60763. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  60764. ** always be at least one cell before the first freeblock.
  60765. */
  60766. return SQLITE_CORRUPT_PAGE(pPage);
  60767. }
  60768. while( 1 ){
  60769. if( pc>iCellLast ){
  60770. /* Freeblock off the end of the page */
  60771. return SQLITE_CORRUPT_PAGE(pPage);
  60772. }
  60773. next = get2byte(&data[pc]);
  60774. size = get2byte(&data[pc+2]);
  60775. nFree = nFree + size;
  60776. if( next<=pc+size+3 ) break;
  60777. pc = next;
  60778. }
  60779. if( next>0 ){
  60780. /* Freeblock not in ascending order */
  60781. return SQLITE_CORRUPT_PAGE(pPage);
  60782. }
  60783. if( pc+size>(unsigned int)usableSize ){
  60784. /* Last freeblock extends past page end */
  60785. return SQLITE_CORRUPT_PAGE(pPage);
  60786. }
  60787. }
  60788. /* At this point, nFree contains the sum of the offset to the start
  60789. ** of the cell-content area plus the number of free bytes within
  60790. ** the cell-content area. If this is greater than the usable-size
  60791. ** of the page, then the page must be corrupted. This check also
  60792. ** serves to verify that the offset to the start of the cell-content
  60793. ** area, according to the page header, lies within the page.
  60794. */
  60795. if( nFree>usableSize ){
  60796. return SQLITE_CORRUPT_PAGE(pPage);
  60797. }
  60798. pPage->nFree = (u16)(nFree - iCellFirst);
  60799. pPage->isInit = 1;
  60800. return SQLITE_OK;
  60801. }
  60802. /*
  60803. ** Set up a raw page so that it looks like a database page holding
  60804. ** no entries.
  60805. */
  60806. static void zeroPage(MemPage *pPage, int flags){
  60807. unsigned char *data = pPage->aData;
  60808. BtShared *pBt = pPage->pBt;
  60809. u8 hdr = pPage->hdrOffset;
  60810. u16 first;
  60811. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  60812. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  60813. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  60814. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60815. assert( sqlite3_mutex_held(pBt->mutex) );
  60816. if( pBt->btsFlags & BTS_FAST_SECURE ){
  60817. memset(&data[hdr], 0, pBt->usableSize - hdr);
  60818. }
  60819. data[hdr] = (char)flags;
  60820. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  60821. memset(&data[hdr+1], 0, 4);
  60822. data[hdr+7] = 0;
  60823. put2byte(&data[hdr+5], pBt->usableSize);
  60824. pPage->nFree = (u16)(pBt->usableSize - first);
  60825. decodeFlags(pPage, flags);
  60826. pPage->cellOffset = first;
  60827. pPage->aDataEnd = &data[pBt->usableSize];
  60828. pPage->aCellIdx = &data[first];
  60829. pPage->aDataOfst = &data[pPage->childPtrSize];
  60830. pPage->nOverflow = 0;
  60831. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  60832. pPage->maskPage = (u16)(pBt->pageSize - 1);
  60833. pPage->nCell = 0;
  60834. pPage->isInit = 1;
  60835. }
  60836. /*
  60837. ** Convert a DbPage obtained from the pager into a MemPage used by
  60838. ** the btree layer.
  60839. */
  60840. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  60841. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  60842. if( pgno!=pPage->pgno ){
  60843. pPage->aData = sqlite3PagerGetData(pDbPage);
  60844. pPage->pDbPage = pDbPage;
  60845. pPage->pBt = pBt;
  60846. pPage->pgno = pgno;
  60847. pPage->hdrOffset = pgno==1 ? 100 : 0;
  60848. }
  60849. assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
  60850. return pPage;
  60851. }
  60852. /*
  60853. ** Get a page from the pager. Initialize the MemPage.pBt and
  60854. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  60855. **
  60856. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  60857. ** about the content of the page at this time. So do not go to the disk
  60858. ** to fetch the content. Just fill in the content with zeros for now.
  60859. ** If in the future we call sqlite3PagerWrite() on this page, that
  60860. ** means we have started to be concerned about content and the disk
  60861. ** read should occur at that point.
  60862. */
  60863. static int btreeGetPage(
  60864. BtShared *pBt, /* The btree */
  60865. Pgno pgno, /* Number of the page to fetch */
  60866. MemPage **ppPage, /* Return the page in this parameter */
  60867. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  60868. ){
  60869. int rc;
  60870. DbPage *pDbPage;
  60871. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  60872. assert( sqlite3_mutex_held(pBt->mutex) );
  60873. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  60874. if( rc ) return rc;
  60875. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  60876. return SQLITE_OK;
  60877. }
  60878. /*
  60879. ** Retrieve a page from the pager cache. If the requested page is not
  60880. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  60881. ** MemPage.aData elements if needed.
  60882. */
  60883. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  60884. DbPage *pDbPage;
  60885. assert( sqlite3_mutex_held(pBt->mutex) );
  60886. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  60887. if( pDbPage ){
  60888. return btreePageFromDbPage(pDbPage, pgno, pBt);
  60889. }
  60890. return 0;
  60891. }
  60892. /*
  60893. ** Return the size of the database file in pages. If there is any kind of
  60894. ** error, return ((unsigned int)-1).
  60895. */
  60896. static Pgno btreePagecount(BtShared *pBt){
  60897. return pBt->nPage;
  60898. }
  60899. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  60900. assert( sqlite3BtreeHoldsMutex(p) );
  60901. assert( ((p->pBt->nPage)&0x80000000)==0 );
  60902. return btreePagecount(p->pBt);
  60903. }
  60904. /*
  60905. ** Get a page from the pager and initialize it.
  60906. **
  60907. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  60908. ** call. Do additional sanity checking on the page in this case.
  60909. ** And if the fetch fails, this routine must decrement pCur->iPage.
  60910. **
  60911. ** The page is fetched as read-write unless pCur is not NULL and is
  60912. ** a read-only cursor.
  60913. **
  60914. ** If an error occurs, then *ppPage is undefined. It
  60915. ** may remain unchanged, or it may be set to an invalid value.
  60916. */
  60917. static int getAndInitPage(
  60918. BtShared *pBt, /* The database file */
  60919. Pgno pgno, /* Number of the page to get */
  60920. MemPage **ppPage, /* Write the page pointer here */
  60921. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  60922. int bReadOnly /* True for a read-only page */
  60923. ){
  60924. int rc;
  60925. DbPage *pDbPage;
  60926. assert( sqlite3_mutex_held(pBt->mutex) );
  60927. assert( pCur==0 || ppPage==&pCur->pPage );
  60928. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  60929. assert( pCur==0 || pCur->iPage>0 );
  60930. if( pgno>btreePagecount(pBt) ){
  60931. rc = SQLITE_CORRUPT_BKPT;
  60932. goto getAndInitPage_error;
  60933. }
  60934. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  60935. if( rc ){
  60936. goto getAndInitPage_error;
  60937. }
  60938. *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  60939. if( (*ppPage)->isInit==0 ){
  60940. btreePageFromDbPage(pDbPage, pgno, pBt);
  60941. rc = btreeInitPage(*ppPage);
  60942. if( rc!=SQLITE_OK ){
  60943. releasePage(*ppPage);
  60944. goto getAndInitPage_error;
  60945. }
  60946. }
  60947. assert( (*ppPage)->pgno==pgno );
  60948. assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
  60949. /* If obtaining a child page for a cursor, we must verify that the page is
  60950. ** compatible with the root page. */
  60951. if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
  60952. rc = SQLITE_CORRUPT_PGNO(pgno);
  60953. releasePage(*ppPage);
  60954. goto getAndInitPage_error;
  60955. }
  60956. return SQLITE_OK;
  60957. getAndInitPage_error:
  60958. if( pCur ){
  60959. pCur->iPage--;
  60960. pCur->pPage = pCur->apPage[pCur->iPage];
  60961. }
  60962. testcase( pgno==0 );
  60963. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  60964. return rc;
  60965. }
  60966. /*
  60967. ** Release a MemPage. This should be called once for each prior
  60968. ** call to btreeGetPage.
  60969. **
  60970. ** Page1 is a special case and must be released using releasePageOne().
  60971. */
  60972. static void releasePageNotNull(MemPage *pPage){
  60973. assert( pPage->aData );
  60974. assert( pPage->pBt );
  60975. assert( pPage->pDbPage!=0 );
  60976. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  60977. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  60978. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60979. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  60980. }
  60981. static void releasePage(MemPage *pPage){
  60982. if( pPage ) releasePageNotNull(pPage);
  60983. }
  60984. static void releasePageOne(MemPage *pPage){
  60985. assert( pPage!=0 );
  60986. assert( pPage->aData );
  60987. assert( pPage->pBt );
  60988. assert( pPage->pDbPage!=0 );
  60989. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  60990. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  60991. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60992. sqlite3PagerUnrefPageOne(pPage->pDbPage);
  60993. }
  60994. /*
  60995. ** Get an unused page.
  60996. **
  60997. ** This works just like btreeGetPage() with the addition:
  60998. **
  60999. ** * If the page is already in use for some other purpose, immediately
  61000. ** release it and return an SQLITE_CURRUPT error.
  61001. ** * Make sure the isInit flag is clear
  61002. */
  61003. static int btreeGetUnusedPage(
  61004. BtShared *pBt, /* The btree */
  61005. Pgno pgno, /* Number of the page to fetch */
  61006. MemPage **ppPage, /* Return the page in this parameter */
  61007. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  61008. ){
  61009. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  61010. if( rc==SQLITE_OK ){
  61011. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  61012. releasePage(*ppPage);
  61013. *ppPage = 0;
  61014. return SQLITE_CORRUPT_BKPT;
  61015. }
  61016. (*ppPage)->isInit = 0;
  61017. }else{
  61018. *ppPage = 0;
  61019. }
  61020. return rc;
  61021. }
  61022. /*
  61023. ** During a rollback, when the pager reloads information into the cache
  61024. ** so that the cache is restored to its original state at the start of
  61025. ** the transaction, for each page restored this routine is called.
  61026. **
  61027. ** This routine needs to reset the extra data section at the end of the
  61028. ** page to agree with the restored data.
  61029. */
  61030. static void pageReinit(DbPage *pData){
  61031. MemPage *pPage;
  61032. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  61033. assert( sqlite3PagerPageRefcount(pData)>0 );
  61034. if( pPage->isInit ){
  61035. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61036. pPage->isInit = 0;
  61037. if( sqlite3PagerPageRefcount(pData)>1 ){
  61038. /* pPage might not be a btree page; it might be an overflow page
  61039. ** or ptrmap page or a free page. In those cases, the following
  61040. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  61041. ** But no harm is done by this. And it is very important that
  61042. ** btreeInitPage() be called on every btree page so we make
  61043. ** the call for every page that comes in for re-initing. */
  61044. btreeInitPage(pPage);
  61045. }
  61046. }
  61047. }
  61048. /*
  61049. ** Invoke the busy handler for a btree.
  61050. */
  61051. static int btreeInvokeBusyHandler(void *pArg){
  61052. BtShared *pBt = (BtShared*)pArg;
  61053. assert( pBt->db );
  61054. assert( sqlite3_mutex_held(pBt->db->mutex) );
  61055. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler,
  61056. sqlite3PagerFile(pBt->pPager));
  61057. }
  61058. /*
  61059. ** Open a database file.
  61060. **
  61061. ** zFilename is the name of the database file. If zFilename is NULL
  61062. ** then an ephemeral database is created. The ephemeral database might
  61063. ** be exclusively in memory, or it might use a disk-based memory cache.
  61064. ** Either way, the ephemeral database will be automatically deleted
  61065. ** when sqlite3BtreeClose() is called.
  61066. **
  61067. ** If zFilename is ":memory:" then an in-memory database is created
  61068. ** that is automatically destroyed when it is closed.
  61069. **
  61070. ** The "flags" parameter is a bitmask that might contain bits like
  61071. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  61072. **
  61073. ** If the database is already opened in the same database connection
  61074. ** and we are in shared cache mode, then the open will fail with an
  61075. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  61076. ** objects in the same database connection since doing so will lead
  61077. ** to problems with locking.
  61078. */
  61079. SQLITE_PRIVATE int sqlite3BtreeOpen(
  61080. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  61081. const char *zFilename, /* Name of the file containing the BTree database */
  61082. sqlite3 *db, /* Associated database handle */
  61083. Btree **ppBtree, /* Pointer to new Btree object written here */
  61084. int flags, /* Options */
  61085. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  61086. ){
  61087. BtShared *pBt = 0; /* Shared part of btree structure */
  61088. Btree *p; /* Handle to return */
  61089. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  61090. int rc = SQLITE_OK; /* Result code from this function */
  61091. u8 nReserve; /* Byte of unused space on each page */
  61092. unsigned char zDbHeader[100]; /* Database header content */
  61093. /* True if opening an ephemeral, temporary database */
  61094. const int isTempDb = zFilename==0 || zFilename[0]==0;
  61095. /* Set the variable isMemdb to true for an in-memory database, or
  61096. ** false for a file-based database.
  61097. */
  61098. #ifdef SQLITE_OMIT_MEMORYDB
  61099. const int isMemdb = 0;
  61100. #else
  61101. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  61102. || (isTempDb && sqlite3TempInMemory(db))
  61103. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  61104. #endif
  61105. assert( db!=0 );
  61106. assert( pVfs!=0 );
  61107. assert( sqlite3_mutex_held(db->mutex) );
  61108. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  61109. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  61110. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  61111. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  61112. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  61113. if( isMemdb ){
  61114. flags |= BTREE_MEMORY;
  61115. }
  61116. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  61117. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  61118. }
  61119. p = sqlite3MallocZero(sizeof(Btree));
  61120. if( !p ){
  61121. return SQLITE_NOMEM_BKPT;
  61122. }
  61123. p->inTrans = TRANS_NONE;
  61124. p->db = db;
  61125. #ifndef SQLITE_OMIT_SHARED_CACHE
  61126. p->lock.pBtree = p;
  61127. p->lock.iTable = 1;
  61128. #endif
  61129. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  61130. /*
  61131. ** If this Btree is a candidate for shared cache, try to find an
  61132. ** existing BtShared object that we can share with
  61133. */
  61134. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  61135. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  61136. int nFilename = sqlite3Strlen30(zFilename)+1;
  61137. int nFullPathname = pVfs->mxPathname+1;
  61138. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  61139. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  61140. p->sharable = 1;
  61141. if( !zFullPathname ){
  61142. sqlite3_free(p);
  61143. return SQLITE_NOMEM_BKPT;
  61144. }
  61145. if( isMemdb ){
  61146. memcpy(zFullPathname, zFilename, nFilename);
  61147. }else{
  61148. rc = sqlite3OsFullPathname(pVfs, zFilename,
  61149. nFullPathname, zFullPathname);
  61150. if( rc ){
  61151. sqlite3_free(zFullPathname);
  61152. sqlite3_free(p);
  61153. return rc;
  61154. }
  61155. }
  61156. #if SQLITE_THREADSAFE
  61157. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  61158. sqlite3_mutex_enter(mutexOpen);
  61159. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  61160. sqlite3_mutex_enter(mutexShared);
  61161. #endif
  61162. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  61163. assert( pBt->nRef>0 );
  61164. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  61165. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  61166. int iDb;
  61167. for(iDb=db->nDb-1; iDb>=0; iDb--){
  61168. Btree *pExisting = db->aDb[iDb].pBt;
  61169. if( pExisting && pExisting->pBt==pBt ){
  61170. sqlite3_mutex_leave(mutexShared);
  61171. sqlite3_mutex_leave(mutexOpen);
  61172. sqlite3_free(zFullPathname);
  61173. sqlite3_free(p);
  61174. return SQLITE_CONSTRAINT;
  61175. }
  61176. }
  61177. p->pBt = pBt;
  61178. pBt->nRef++;
  61179. break;
  61180. }
  61181. }
  61182. sqlite3_mutex_leave(mutexShared);
  61183. sqlite3_free(zFullPathname);
  61184. }
  61185. #ifdef SQLITE_DEBUG
  61186. else{
  61187. /* In debug mode, we mark all persistent databases as sharable
  61188. ** even when they are not. This exercises the locking code and
  61189. ** gives more opportunity for asserts(sqlite3_mutex_held())
  61190. ** statements to find locking problems.
  61191. */
  61192. p->sharable = 1;
  61193. }
  61194. #endif
  61195. }
  61196. #endif
  61197. if( pBt==0 ){
  61198. /*
  61199. ** The following asserts make sure that structures used by the btree are
  61200. ** the right size. This is to guard against size changes that result
  61201. ** when compiling on a different architecture.
  61202. */
  61203. assert( sizeof(i64)==8 );
  61204. assert( sizeof(u64)==8 );
  61205. assert( sizeof(u32)==4 );
  61206. assert( sizeof(u16)==2 );
  61207. assert( sizeof(Pgno)==4 );
  61208. pBt = sqlite3MallocZero( sizeof(*pBt) );
  61209. if( pBt==0 ){
  61210. rc = SQLITE_NOMEM_BKPT;
  61211. goto btree_open_out;
  61212. }
  61213. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  61214. sizeof(MemPage), flags, vfsFlags, pageReinit);
  61215. if( rc==SQLITE_OK ){
  61216. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  61217. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  61218. }
  61219. if( rc!=SQLITE_OK ){
  61220. goto btree_open_out;
  61221. }
  61222. pBt->openFlags = (u8)flags;
  61223. pBt->db = db;
  61224. sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  61225. p->pBt = pBt;
  61226. pBt->pCursor = 0;
  61227. pBt->pPage1 = 0;
  61228. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  61229. #if defined(SQLITE_SECURE_DELETE)
  61230. pBt->btsFlags |= BTS_SECURE_DELETE;
  61231. #elif defined(SQLITE_FAST_SECURE_DELETE)
  61232. pBt->btsFlags |= BTS_OVERWRITE;
  61233. #endif
  61234. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  61235. ** determined by the 2-byte integer located at an offset of 16 bytes from
  61236. ** the beginning of the database file. */
  61237. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  61238. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  61239. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  61240. pBt->pageSize = 0;
  61241. #ifndef SQLITE_OMIT_AUTOVACUUM
  61242. /* If the magic name ":memory:" will create an in-memory database, then
  61243. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  61244. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  61245. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  61246. ** regular file-name. In this case the auto-vacuum applies as per normal.
  61247. */
  61248. if( zFilename && !isMemdb ){
  61249. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  61250. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  61251. }
  61252. #endif
  61253. nReserve = 0;
  61254. }else{
  61255. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  61256. ** determined by the one-byte unsigned integer found at an offset of 20
  61257. ** into the database file header. */
  61258. nReserve = zDbHeader[20];
  61259. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  61260. #ifndef SQLITE_OMIT_AUTOVACUUM
  61261. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  61262. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  61263. #endif
  61264. }
  61265. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  61266. if( rc ) goto btree_open_out;
  61267. pBt->usableSize = pBt->pageSize - nReserve;
  61268. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  61269. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  61270. /* Add the new BtShared object to the linked list sharable BtShareds.
  61271. */
  61272. pBt->nRef = 1;
  61273. if( p->sharable ){
  61274. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  61275. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  61276. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  61277. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  61278. if( pBt->mutex==0 ){
  61279. rc = SQLITE_NOMEM_BKPT;
  61280. goto btree_open_out;
  61281. }
  61282. }
  61283. sqlite3_mutex_enter(mutexShared);
  61284. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  61285. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  61286. sqlite3_mutex_leave(mutexShared);
  61287. }
  61288. #endif
  61289. }
  61290. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  61291. /* If the new Btree uses a sharable pBtShared, then link the new
  61292. ** Btree into the list of all sharable Btrees for the same connection.
  61293. ** The list is kept in ascending order by pBt address.
  61294. */
  61295. if( p->sharable ){
  61296. int i;
  61297. Btree *pSib;
  61298. for(i=0; i<db->nDb; i++){
  61299. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  61300. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  61301. if( (uptr)p->pBt<(uptr)pSib->pBt ){
  61302. p->pNext = pSib;
  61303. p->pPrev = 0;
  61304. pSib->pPrev = p;
  61305. }else{
  61306. while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
  61307. pSib = pSib->pNext;
  61308. }
  61309. p->pNext = pSib->pNext;
  61310. p->pPrev = pSib;
  61311. if( p->pNext ){
  61312. p->pNext->pPrev = p;
  61313. }
  61314. pSib->pNext = p;
  61315. }
  61316. break;
  61317. }
  61318. }
  61319. }
  61320. #endif
  61321. *ppBtree = p;
  61322. btree_open_out:
  61323. if( rc!=SQLITE_OK ){
  61324. if( pBt && pBt->pPager ){
  61325. sqlite3PagerClose(pBt->pPager, 0);
  61326. }
  61327. sqlite3_free(pBt);
  61328. sqlite3_free(p);
  61329. *ppBtree = 0;
  61330. }else{
  61331. sqlite3_file *pFile;
  61332. /* If the B-Tree was successfully opened, set the pager-cache size to the
  61333. ** default value. Except, when opening on an existing shared pager-cache,
  61334. ** do not change the pager-cache size.
  61335. */
  61336. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  61337. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  61338. }
  61339. pFile = sqlite3PagerFile(pBt->pPager);
  61340. if( pFile->pMethods ){
  61341. sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
  61342. }
  61343. }
  61344. if( mutexOpen ){
  61345. assert( sqlite3_mutex_held(mutexOpen) );
  61346. sqlite3_mutex_leave(mutexOpen);
  61347. }
  61348. assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
  61349. return rc;
  61350. }
  61351. /*
  61352. ** Decrement the BtShared.nRef counter. When it reaches zero,
  61353. ** remove the BtShared structure from the sharing list. Return
  61354. ** true if the BtShared.nRef counter reaches zero and return
  61355. ** false if it is still positive.
  61356. */
  61357. static int removeFromSharingList(BtShared *pBt){
  61358. #ifndef SQLITE_OMIT_SHARED_CACHE
  61359. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  61360. BtShared *pList;
  61361. int removed = 0;
  61362. assert( sqlite3_mutex_notheld(pBt->mutex) );
  61363. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  61364. sqlite3_mutex_enter(pMaster);
  61365. pBt->nRef--;
  61366. if( pBt->nRef<=0 ){
  61367. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  61368. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  61369. }else{
  61370. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  61371. while( ALWAYS(pList) && pList->pNext!=pBt ){
  61372. pList=pList->pNext;
  61373. }
  61374. if( ALWAYS(pList) ){
  61375. pList->pNext = pBt->pNext;
  61376. }
  61377. }
  61378. if( SQLITE_THREADSAFE ){
  61379. sqlite3_mutex_free(pBt->mutex);
  61380. }
  61381. removed = 1;
  61382. }
  61383. sqlite3_mutex_leave(pMaster);
  61384. return removed;
  61385. #else
  61386. return 1;
  61387. #endif
  61388. }
  61389. /*
  61390. ** Make sure pBt->pTmpSpace points to an allocation of
  61391. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  61392. ** pointer.
  61393. */
  61394. static void allocateTempSpace(BtShared *pBt){
  61395. if( !pBt->pTmpSpace ){
  61396. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  61397. /* One of the uses of pBt->pTmpSpace is to format cells before
  61398. ** inserting them into a leaf page (function fillInCell()). If
  61399. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  61400. ** by the various routines that manipulate binary cells. Which
  61401. ** can mean that fillInCell() only initializes the first 2 or 3
  61402. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  61403. ** it into a database page. This is not actually a problem, but it
  61404. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  61405. ** data is passed to system call write(). So to avoid this error,
  61406. ** zero the first 4 bytes of temp space here.
  61407. **
  61408. ** Also: Provide four bytes of initialized space before the
  61409. ** beginning of pTmpSpace as an area available to prepend the
  61410. ** left-child pointer to the beginning of a cell.
  61411. */
  61412. if( pBt->pTmpSpace ){
  61413. memset(pBt->pTmpSpace, 0, 8);
  61414. pBt->pTmpSpace += 4;
  61415. }
  61416. }
  61417. }
  61418. /*
  61419. ** Free the pBt->pTmpSpace allocation
  61420. */
  61421. static void freeTempSpace(BtShared *pBt){
  61422. if( pBt->pTmpSpace ){
  61423. pBt->pTmpSpace -= 4;
  61424. sqlite3PageFree(pBt->pTmpSpace);
  61425. pBt->pTmpSpace = 0;
  61426. }
  61427. }
  61428. /*
  61429. ** Close an open database and invalidate all cursors.
  61430. */
  61431. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  61432. BtShared *pBt = p->pBt;
  61433. BtCursor *pCur;
  61434. /* Close all cursors opened via this handle. */
  61435. assert( sqlite3_mutex_held(p->db->mutex) );
  61436. sqlite3BtreeEnter(p);
  61437. pCur = pBt->pCursor;
  61438. while( pCur ){
  61439. BtCursor *pTmp = pCur;
  61440. pCur = pCur->pNext;
  61441. if( pTmp->pBtree==p ){
  61442. sqlite3BtreeCloseCursor(pTmp);
  61443. }
  61444. }
  61445. /* Rollback any active transaction and free the handle structure.
  61446. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  61447. ** this handle.
  61448. */
  61449. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  61450. sqlite3BtreeLeave(p);
  61451. /* If there are still other outstanding references to the shared-btree
  61452. ** structure, return now. The remainder of this procedure cleans
  61453. ** up the shared-btree.
  61454. */
  61455. assert( p->wantToLock==0 && p->locked==0 );
  61456. if( !p->sharable || removeFromSharingList(pBt) ){
  61457. /* The pBt is no longer on the sharing list, so we can access
  61458. ** it without having to hold the mutex.
  61459. **
  61460. ** Clean out and delete the BtShared object.
  61461. */
  61462. assert( !pBt->pCursor );
  61463. sqlite3PagerClose(pBt->pPager, p->db);
  61464. if( pBt->xFreeSchema && pBt->pSchema ){
  61465. pBt->xFreeSchema(pBt->pSchema);
  61466. }
  61467. sqlite3DbFree(0, pBt->pSchema);
  61468. freeTempSpace(pBt);
  61469. sqlite3_free(pBt);
  61470. }
  61471. #ifndef SQLITE_OMIT_SHARED_CACHE
  61472. assert( p->wantToLock==0 );
  61473. assert( p->locked==0 );
  61474. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  61475. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  61476. #endif
  61477. sqlite3_free(p);
  61478. return SQLITE_OK;
  61479. }
  61480. /*
  61481. ** Change the "soft" limit on the number of pages in the cache.
  61482. ** Unused and unmodified pages will be recycled when the number of
  61483. ** pages in the cache exceeds this soft limit. But the size of the
  61484. ** cache is allowed to grow larger than this limit if it contains
  61485. ** dirty pages or pages still in active use.
  61486. */
  61487. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  61488. BtShared *pBt = p->pBt;
  61489. assert( sqlite3_mutex_held(p->db->mutex) );
  61490. sqlite3BtreeEnter(p);
  61491. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  61492. sqlite3BtreeLeave(p);
  61493. return SQLITE_OK;
  61494. }
  61495. /*
  61496. ** Change the "spill" limit on the number of pages in the cache.
  61497. ** If the number of pages exceeds this limit during a write transaction,
  61498. ** the pager might attempt to "spill" pages to the journal early in
  61499. ** order to free up memory.
  61500. **
  61501. ** The value returned is the current spill size. If zero is passed
  61502. ** as an argument, no changes are made to the spill size setting, so
  61503. ** using mxPage of 0 is a way to query the current spill size.
  61504. */
  61505. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
  61506. BtShared *pBt = p->pBt;
  61507. int res;
  61508. assert( sqlite3_mutex_held(p->db->mutex) );
  61509. sqlite3BtreeEnter(p);
  61510. res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
  61511. sqlite3BtreeLeave(p);
  61512. return res;
  61513. }
  61514. #if SQLITE_MAX_MMAP_SIZE>0
  61515. /*
  61516. ** Change the limit on the amount of the database file that may be
  61517. ** memory mapped.
  61518. */
  61519. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  61520. BtShared *pBt = p->pBt;
  61521. assert( sqlite3_mutex_held(p->db->mutex) );
  61522. sqlite3BtreeEnter(p);
  61523. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  61524. sqlite3BtreeLeave(p);
  61525. return SQLITE_OK;
  61526. }
  61527. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  61528. /*
  61529. ** Change the way data is synced to disk in order to increase or decrease
  61530. ** how well the database resists damage due to OS crashes and power
  61531. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  61532. ** there is a high probability of damage) Level 2 is the default. There
  61533. ** is a very low but non-zero probability of damage. Level 3 reduces the
  61534. ** probability of damage to near zero but with a write performance reduction.
  61535. */
  61536. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  61537. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  61538. Btree *p, /* The btree to set the safety level on */
  61539. unsigned pgFlags /* Various PAGER_* flags */
  61540. ){
  61541. BtShared *pBt = p->pBt;
  61542. assert( sqlite3_mutex_held(p->db->mutex) );
  61543. sqlite3BtreeEnter(p);
  61544. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  61545. sqlite3BtreeLeave(p);
  61546. return SQLITE_OK;
  61547. }
  61548. #endif
  61549. /*
  61550. ** Change the default pages size and the number of reserved bytes per page.
  61551. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  61552. ** without changing anything.
  61553. **
  61554. ** The page size must be a power of 2 between 512 and 65536. If the page
  61555. ** size supplied does not meet this constraint then the page size is not
  61556. ** changed.
  61557. **
  61558. ** Page sizes are constrained to be a power of two so that the region
  61559. ** of the database file used for locking (beginning at PENDING_BYTE,
  61560. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  61561. ** at the beginning of a page.
  61562. **
  61563. ** If parameter nReserve is less than zero, then the number of reserved
  61564. ** bytes per page is left unchanged.
  61565. **
  61566. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  61567. ** and autovacuum mode can no longer be changed.
  61568. */
  61569. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  61570. int rc = SQLITE_OK;
  61571. BtShared *pBt = p->pBt;
  61572. assert( nReserve>=-1 && nReserve<=255 );
  61573. sqlite3BtreeEnter(p);
  61574. #if SQLITE_HAS_CODEC
  61575. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  61576. #endif
  61577. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  61578. sqlite3BtreeLeave(p);
  61579. return SQLITE_READONLY;
  61580. }
  61581. if( nReserve<0 ){
  61582. nReserve = pBt->pageSize - pBt->usableSize;
  61583. }
  61584. assert( nReserve>=0 && nReserve<=255 );
  61585. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  61586. ((pageSize-1)&pageSize)==0 ){
  61587. assert( (pageSize & 7)==0 );
  61588. assert( !pBt->pCursor );
  61589. pBt->pageSize = (u32)pageSize;
  61590. freeTempSpace(pBt);
  61591. }
  61592. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  61593. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  61594. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  61595. sqlite3BtreeLeave(p);
  61596. return rc;
  61597. }
  61598. /*
  61599. ** Return the currently defined page size
  61600. */
  61601. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  61602. return p->pBt->pageSize;
  61603. }
  61604. /*
  61605. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  61606. ** may only be called if it is guaranteed that the b-tree mutex is already
  61607. ** held.
  61608. **
  61609. ** This is useful in one special case in the backup API code where it is
  61610. ** known that the shared b-tree mutex is held, but the mutex on the
  61611. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  61612. ** were to be called, it might collide with some other operation on the
  61613. ** database handle that owns *p, causing undefined behavior.
  61614. */
  61615. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  61616. int n;
  61617. assert( sqlite3_mutex_held(p->pBt->mutex) );
  61618. n = p->pBt->pageSize - p->pBt->usableSize;
  61619. return n;
  61620. }
  61621. /*
  61622. ** Return the number of bytes of space at the end of every page that
  61623. ** are intentually left unused. This is the "reserved" space that is
  61624. ** sometimes used by extensions.
  61625. **
  61626. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  61627. ** greater of the current reserved space and the maximum requested
  61628. ** reserve space.
  61629. */
  61630. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  61631. int n;
  61632. sqlite3BtreeEnter(p);
  61633. n = sqlite3BtreeGetReserveNoMutex(p);
  61634. #ifdef SQLITE_HAS_CODEC
  61635. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  61636. #endif
  61637. sqlite3BtreeLeave(p);
  61638. return n;
  61639. }
  61640. /*
  61641. ** Set the maximum page count for a database if mxPage is positive.
  61642. ** No changes are made if mxPage is 0 or negative.
  61643. ** Regardless of the value of mxPage, return the maximum page count.
  61644. */
  61645. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  61646. int n;
  61647. sqlite3BtreeEnter(p);
  61648. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  61649. sqlite3BtreeLeave(p);
  61650. return n;
  61651. }
  61652. /*
  61653. ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
  61654. **
  61655. ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
  61656. ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
  61657. ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
  61658. ** newFlag==(-1) No changes
  61659. **
  61660. ** This routine acts as a query if newFlag is less than zero
  61661. **
  61662. ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
  61663. ** freelist leaf pages are not written back to the database. Thus in-page
  61664. ** deleted content is cleared, but freelist deleted content is not.
  61665. **
  61666. ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
  61667. ** that freelist leaf pages are written back into the database, increasing
  61668. ** the amount of disk I/O.
  61669. */
  61670. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  61671. int b;
  61672. if( p==0 ) return 0;
  61673. sqlite3BtreeEnter(p);
  61674. assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
  61675. assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
  61676. if( newFlag>=0 ){
  61677. p->pBt->btsFlags &= ~BTS_FAST_SECURE;
  61678. p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
  61679. }
  61680. b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
  61681. sqlite3BtreeLeave(p);
  61682. return b;
  61683. }
  61684. /*
  61685. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  61686. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  61687. ** is disabled. The default value for the auto-vacuum property is
  61688. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  61689. */
  61690. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  61691. #ifdef SQLITE_OMIT_AUTOVACUUM
  61692. return SQLITE_READONLY;
  61693. #else
  61694. BtShared *pBt = p->pBt;
  61695. int rc = SQLITE_OK;
  61696. u8 av = (u8)autoVacuum;
  61697. sqlite3BtreeEnter(p);
  61698. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  61699. rc = SQLITE_READONLY;
  61700. }else{
  61701. pBt->autoVacuum = av ?1:0;
  61702. pBt->incrVacuum = av==2 ?1:0;
  61703. }
  61704. sqlite3BtreeLeave(p);
  61705. return rc;
  61706. #endif
  61707. }
  61708. /*
  61709. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  61710. ** enabled 1 is returned. Otherwise 0.
  61711. */
  61712. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  61713. #ifdef SQLITE_OMIT_AUTOVACUUM
  61714. return BTREE_AUTOVACUUM_NONE;
  61715. #else
  61716. int rc;
  61717. sqlite3BtreeEnter(p);
  61718. rc = (
  61719. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  61720. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  61721. BTREE_AUTOVACUUM_INCR
  61722. );
  61723. sqlite3BtreeLeave(p);
  61724. return rc;
  61725. #endif
  61726. }
  61727. /*
  61728. ** If the user has not set the safety-level for this database connection
  61729. ** using "PRAGMA synchronous", and if the safety-level is not already
  61730. ** set to the value passed to this function as the second parameter,
  61731. ** set it so.
  61732. */
  61733. #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
  61734. && !defined(SQLITE_OMIT_WAL)
  61735. static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
  61736. sqlite3 *db;
  61737. Db *pDb;
  61738. if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
  61739. while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
  61740. if( pDb->bSyncSet==0
  61741. && pDb->safety_level!=safety_level
  61742. && pDb!=&db->aDb[1]
  61743. ){
  61744. pDb->safety_level = safety_level;
  61745. sqlite3PagerSetFlags(pBt->pPager,
  61746. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
  61747. }
  61748. }
  61749. }
  61750. #else
  61751. # define setDefaultSyncFlag(pBt,safety_level)
  61752. #endif
  61753. /* Forward declaration */
  61754. static int newDatabase(BtShared*);
  61755. /*
  61756. ** Get a reference to pPage1 of the database file. This will
  61757. ** also acquire a readlock on that file.
  61758. **
  61759. ** SQLITE_OK is returned on success. If the file is not a
  61760. ** well-formed database file, then SQLITE_CORRUPT is returned.
  61761. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  61762. ** is returned if we run out of memory.
  61763. */
  61764. static int lockBtree(BtShared *pBt){
  61765. int rc; /* Result code from subfunctions */
  61766. MemPage *pPage1; /* Page 1 of the database file */
  61767. int nPage; /* Number of pages in the database */
  61768. int nPageFile = 0; /* Number of pages in the database file */
  61769. int nPageHeader; /* Number of pages in the database according to hdr */
  61770. assert( sqlite3_mutex_held(pBt->mutex) );
  61771. assert( pBt->pPage1==0 );
  61772. rc = sqlite3PagerSharedLock(pBt->pPager);
  61773. if( rc!=SQLITE_OK ) return rc;
  61774. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  61775. if( rc!=SQLITE_OK ) return rc;
  61776. /* Do some checking to help insure the file we opened really is
  61777. ** a valid database file.
  61778. */
  61779. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  61780. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  61781. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  61782. nPage = nPageFile;
  61783. }
  61784. if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
  61785. nPage = 0;
  61786. }
  61787. if( nPage>0 ){
  61788. u32 pageSize;
  61789. u32 usableSize;
  61790. u8 *page1 = pPage1->aData;
  61791. rc = SQLITE_NOTADB;
  61792. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  61793. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  61794. ** 61 74 20 33 00. */
  61795. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  61796. goto page1_init_failed;
  61797. }
  61798. #ifdef SQLITE_OMIT_WAL
  61799. if( page1[18]>1 ){
  61800. pBt->btsFlags |= BTS_READ_ONLY;
  61801. }
  61802. if( page1[19]>1 ){
  61803. goto page1_init_failed;
  61804. }
  61805. #else
  61806. if( page1[18]>2 ){
  61807. pBt->btsFlags |= BTS_READ_ONLY;
  61808. }
  61809. if( page1[19]>2 ){
  61810. goto page1_init_failed;
  61811. }
  61812. /* If the write version is set to 2, this database should be accessed
  61813. ** in WAL mode. If the log is not already open, open it now. Then
  61814. ** return SQLITE_OK and return without populating BtShared.pPage1.
  61815. ** The caller detects this and calls this function again. This is
  61816. ** required as the version of page 1 currently in the page1 buffer
  61817. ** may not be the latest version - there may be a newer one in the log
  61818. ** file.
  61819. */
  61820. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  61821. int isOpen = 0;
  61822. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  61823. if( rc!=SQLITE_OK ){
  61824. goto page1_init_failed;
  61825. }else{
  61826. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
  61827. if( isOpen==0 ){
  61828. releasePageOne(pPage1);
  61829. return SQLITE_OK;
  61830. }
  61831. }
  61832. rc = SQLITE_NOTADB;
  61833. }else{
  61834. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
  61835. }
  61836. #endif
  61837. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  61838. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  61839. **
  61840. ** The original design allowed these amounts to vary, but as of
  61841. ** version 3.6.0, we require them to be fixed.
  61842. */
  61843. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  61844. goto page1_init_failed;
  61845. }
  61846. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  61847. ** determined by the 2-byte integer located at an offset of 16 bytes from
  61848. ** the beginning of the database file. */
  61849. pageSize = (page1[16]<<8) | (page1[17]<<16);
  61850. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  61851. ** between 512 and 65536 inclusive. */
  61852. if( ((pageSize-1)&pageSize)!=0
  61853. || pageSize>SQLITE_MAX_PAGE_SIZE
  61854. || pageSize<=256
  61855. ){
  61856. goto page1_init_failed;
  61857. }
  61858. assert( (pageSize & 7)==0 );
  61859. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  61860. ** integer at offset 20 is the number of bytes of space at the end of
  61861. ** each page to reserve for extensions.
  61862. **
  61863. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  61864. ** determined by the one-byte unsigned integer found at an offset of 20
  61865. ** into the database file header. */
  61866. usableSize = pageSize - page1[20];
  61867. if( (u32)pageSize!=pBt->pageSize ){
  61868. /* After reading the first page of the database assuming a page size
  61869. ** of BtShared.pageSize, we have discovered that the page-size is
  61870. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  61871. ** zero and return SQLITE_OK. The caller will call this function
  61872. ** again with the correct page-size.
  61873. */
  61874. releasePageOne(pPage1);
  61875. pBt->usableSize = usableSize;
  61876. pBt->pageSize = pageSize;
  61877. freeTempSpace(pBt);
  61878. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  61879. pageSize-usableSize);
  61880. return rc;
  61881. }
  61882. if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
  61883. rc = SQLITE_CORRUPT_BKPT;
  61884. goto page1_init_failed;
  61885. }
  61886. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  61887. ** be less than 480. In other words, if the page size is 512, then the
  61888. ** reserved space size cannot exceed 32. */
  61889. if( usableSize<480 ){
  61890. goto page1_init_failed;
  61891. }
  61892. pBt->pageSize = pageSize;
  61893. pBt->usableSize = usableSize;
  61894. #ifndef SQLITE_OMIT_AUTOVACUUM
  61895. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  61896. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  61897. #endif
  61898. }
  61899. /* maxLocal is the maximum amount of payload to store locally for
  61900. ** a cell. Make sure it is small enough so that at least minFanout
  61901. ** cells can will fit on one page. We assume a 10-byte page header.
  61902. ** Besides the payload, the cell must store:
  61903. ** 2-byte pointer to the cell
  61904. ** 4-byte child pointer
  61905. ** 9-byte nKey value
  61906. ** 4-byte nData value
  61907. ** 4-byte overflow page pointer
  61908. ** So a cell consists of a 2-byte pointer, a header which is as much as
  61909. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  61910. ** page pointer.
  61911. */
  61912. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  61913. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  61914. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  61915. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  61916. if( pBt->maxLocal>127 ){
  61917. pBt->max1bytePayload = 127;
  61918. }else{
  61919. pBt->max1bytePayload = (u8)pBt->maxLocal;
  61920. }
  61921. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  61922. pBt->pPage1 = pPage1;
  61923. pBt->nPage = nPage;
  61924. return SQLITE_OK;
  61925. page1_init_failed:
  61926. releasePageOne(pPage1);
  61927. pBt->pPage1 = 0;
  61928. return rc;
  61929. }
  61930. #ifndef NDEBUG
  61931. /*
  61932. ** Return the number of cursors open on pBt. This is for use
  61933. ** in assert() expressions, so it is only compiled if NDEBUG is not
  61934. ** defined.
  61935. **
  61936. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  61937. ** false then all cursors are counted.
  61938. **
  61939. ** For the purposes of this routine, a cursor is any cursor that
  61940. ** is capable of reading or writing to the database. Cursors that
  61941. ** have been tripped into the CURSOR_FAULT state are not counted.
  61942. */
  61943. static int countValidCursors(BtShared *pBt, int wrOnly){
  61944. BtCursor *pCur;
  61945. int r = 0;
  61946. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  61947. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  61948. && pCur->eState!=CURSOR_FAULT ) r++;
  61949. }
  61950. return r;
  61951. }
  61952. #endif
  61953. /*
  61954. ** If there are no outstanding cursors and we are not in the middle
  61955. ** of a transaction but there is a read lock on the database, then
  61956. ** this routine unrefs the first page of the database file which
  61957. ** has the effect of releasing the read lock.
  61958. **
  61959. ** If there is a transaction in progress, this routine is a no-op.
  61960. */
  61961. static void unlockBtreeIfUnused(BtShared *pBt){
  61962. assert( sqlite3_mutex_held(pBt->mutex) );
  61963. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  61964. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  61965. MemPage *pPage1 = pBt->pPage1;
  61966. assert( pPage1->aData );
  61967. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  61968. pBt->pPage1 = 0;
  61969. releasePageOne(pPage1);
  61970. }
  61971. }
  61972. /*
  61973. ** If pBt points to an empty file then convert that empty file
  61974. ** into a new empty database by initializing the first page of
  61975. ** the database.
  61976. */
  61977. static int newDatabase(BtShared *pBt){
  61978. MemPage *pP1;
  61979. unsigned char *data;
  61980. int rc;
  61981. assert( sqlite3_mutex_held(pBt->mutex) );
  61982. if( pBt->nPage>0 ){
  61983. return SQLITE_OK;
  61984. }
  61985. pP1 = pBt->pPage1;
  61986. assert( pP1!=0 );
  61987. data = pP1->aData;
  61988. rc = sqlite3PagerWrite(pP1->pDbPage);
  61989. if( rc ) return rc;
  61990. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  61991. assert( sizeof(zMagicHeader)==16 );
  61992. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  61993. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  61994. data[18] = 1;
  61995. data[19] = 1;
  61996. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  61997. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  61998. data[21] = 64;
  61999. data[22] = 32;
  62000. data[23] = 32;
  62001. memset(&data[24], 0, 100-24);
  62002. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  62003. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  62004. #ifndef SQLITE_OMIT_AUTOVACUUM
  62005. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  62006. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  62007. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  62008. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  62009. #endif
  62010. pBt->nPage = 1;
  62011. data[31] = 1;
  62012. return SQLITE_OK;
  62013. }
  62014. /*
  62015. ** Initialize the first page of the database file (creating a database
  62016. ** consisting of a single page and no schema objects). Return SQLITE_OK
  62017. ** if successful, or an SQLite error code otherwise.
  62018. */
  62019. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  62020. int rc;
  62021. sqlite3BtreeEnter(p);
  62022. p->pBt->nPage = 0;
  62023. rc = newDatabase(p->pBt);
  62024. sqlite3BtreeLeave(p);
  62025. return rc;
  62026. }
  62027. /*
  62028. ** Attempt to start a new transaction. A write-transaction
  62029. ** is started if the second argument is nonzero, otherwise a read-
  62030. ** transaction. If the second argument is 2 or more and exclusive
  62031. ** transaction is started, meaning that no other process is allowed
  62032. ** to access the database. A preexisting transaction may not be
  62033. ** upgraded to exclusive by calling this routine a second time - the
  62034. ** exclusivity flag only works for a new transaction.
  62035. **
  62036. ** A write-transaction must be started before attempting any
  62037. ** changes to the database. None of the following routines
  62038. ** will work unless a transaction is started first:
  62039. **
  62040. ** sqlite3BtreeCreateTable()
  62041. ** sqlite3BtreeCreateIndex()
  62042. ** sqlite3BtreeClearTable()
  62043. ** sqlite3BtreeDropTable()
  62044. ** sqlite3BtreeInsert()
  62045. ** sqlite3BtreeDelete()
  62046. ** sqlite3BtreeUpdateMeta()
  62047. **
  62048. ** If an initial attempt to acquire the lock fails because of lock contention
  62049. ** and the database was previously unlocked, then invoke the busy handler
  62050. ** if there is one. But if there was previously a read-lock, do not
  62051. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  62052. ** returned when there is already a read-lock in order to avoid a deadlock.
  62053. **
  62054. ** Suppose there are two processes A and B. A has a read lock and B has
  62055. ** a reserved lock. B tries to promote to exclusive but is blocked because
  62056. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  62057. ** One or the other of the two processes must give way or there can be
  62058. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  62059. ** when A already has a read lock, we encourage A to give up and let B
  62060. ** proceed.
  62061. */
  62062. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
  62063. BtShared *pBt = p->pBt;
  62064. int rc = SQLITE_OK;
  62065. sqlite3BtreeEnter(p);
  62066. btreeIntegrity(p);
  62067. /* If the btree is already in a write-transaction, or it
  62068. ** is already in a read-transaction and a read-transaction
  62069. ** is requested, this is a no-op.
  62070. */
  62071. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  62072. goto trans_begun;
  62073. }
  62074. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  62075. if( (p->db->flags & SQLITE_ResetDatabase)
  62076. && sqlite3PagerIsreadonly(pBt->pPager)==0
  62077. ){
  62078. pBt->btsFlags &= ~BTS_READ_ONLY;
  62079. }
  62080. /* Write transactions are not possible on a read-only database */
  62081. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  62082. rc = SQLITE_READONLY;
  62083. goto trans_begun;
  62084. }
  62085. #ifndef SQLITE_OMIT_SHARED_CACHE
  62086. {
  62087. sqlite3 *pBlock = 0;
  62088. /* If another database handle has already opened a write transaction
  62089. ** on this shared-btree structure and a second write transaction is
  62090. ** requested, return SQLITE_LOCKED.
  62091. */
  62092. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  62093. || (pBt->btsFlags & BTS_PENDING)!=0
  62094. ){
  62095. pBlock = pBt->pWriter->db;
  62096. }else if( wrflag>1 ){
  62097. BtLock *pIter;
  62098. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  62099. if( pIter->pBtree!=p ){
  62100. pBlock = pIter->pBtree->db;
  62101. break;
  62102. }
  62103. }
  62104. }
  62105. if( pBlock ){
  62106. sqlite3ConnectionBlocked(p->db, pBlock);
  62107. rc = SQLITE_LOCKED_SHAREDCACHE;
  62108. goto trans_begun;
  62109. }
  62110. }
  62111. #endif
  62112. /* Any read-only or read-write transaction implies a read-lock on
  62113. ** page 1. So if some other shared-cache client already has a write-lock
  62114. ** on page 1, the transaction cannot be opened. */
  62115. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  62116. if( SQLITE_OK!=rc ) goto trans_begun;
  62117. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  62118. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  62119. do {
  62120. /* Call lockBtree() until either pBt->pPage1 is populated or
  62121. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  62122. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  62123. ** reading page 1 it discovers that the page-size of the database
  62124. ** file is not pBt->pageSize. In this case lockBtree() will update
  62125. ** pBt->pageSize to the page-size of the file on disk.
  62126. */
  62127. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  62128. if( rc==SQLITE_OK && wrflag ){
  62129. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  62130. rc = SQLITE_READONLY;
  62131. }else{
  62132. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  62133. if( rc==SQLITE_OK ){
  62134. rc = newDatabase(pBt);
  62135. }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
  62136. /* if there was no transaction opened when this function was
  62137. ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
  62138. ** code to SQLITE_BUSY. */
  62139. rc = SQLITE_BUSY;
  62140. }
  62141. }
  62142. }
  62143. if( rc!=SQLITE_OK ){
  62144. unlockBtreeIfUnused(pBt);
  62145. }
  62146. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  62147. btreeInvokeBusyHandler(pBt) );
  62148. sqlite3PagerResetLockTimeout(pBt->pPager);
  62149. if( rc==SQLITE_OK ){
  62150. if( p->inTrans==TRANS_NONE ){
  62151. pBt->nTransaction++;
  62152. #ifndef SQLITE_OMIT_SHARED_CACHE
  62153. if( p->sharable ){
  62154. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  62155. p->lock.eLock = READ_LOCK;
  62156. p->lock.pNext = pBt->pLock;
  62157. pBt->pLock = &p->lock;
  62158. }
  62159. #endif
  62160. }
  62161. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  62162. if( p->inTrans>pBt->inTransaction ){
  62163. pBt->inTransaction = p->inTrans;
  62164. }
  62165. if( wrflag ){
  62166. MemPage *pPage1 = pBt->pPage1;
  62167. #ifndef SQLITE_OMIT_SHARED_CACHE
  62168. assert( !pBt->pWriter );
  62169. pBt->pWriter = p;
  62170. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  62171. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  62172. #endif
  62173. /* If the db-size header field is incorrect (as it may be if an old
  62174. ** client has been writing the database file), update it now. Doing
  62175. ** this sooner rather than later means the database size can safely
  62176. ** re-read the database size from page 1 if a savepoint or transaction
  62177. ** rollback occurs within the transaction.
  62178. */
  62179. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  62180. rc = sqlite3PagerWrite(pPage1->pDbPage);
  62181. if( rc==SQLITE_OK ){
  62182. put4byte(&pPage1->aData[28], pBt->nPage);
  62183. }
  62184. }
  62185. }
  62186. }
  62187. trans_begun:
  62188. if( rc==SQLITE_OK ){
  62189. if( pSchemaVersion ){
  62190. *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
  62191. }
  62192. if( wrflag ){
  62193. /* This call makes sure that the pager has the correct number of
  62194. ** open savepoints. If the second parameter is greater than 0 and
  62195. ** the sub-journal is not already open, then it will be opened here.
  62196. */
  62197. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  62198. }
  62199. }
  62200. btreeIntegrity(p);
  62201. sqlite3BtreeLeave(p);
  62202. return rc;
  62203. }
  62204. #ifndef SQLITE_OMIT_AUTOVACUUM
  62205. /*
  62206. ** Set the pointer-map entries for all children of page pPage. Also, if
  62207. ** pPage contains cells that point to overflow pages, set the pointer
  62208. ** map entries for the overflow pages as well.
  62209. */
  62210. static int setChildPtrmaps(MemPage *pPage){
  62211. int i; /* Counter variable */
  62212. int nCell; /* Number of cells in page pPage */
  62213. int rc; /* Return code */
  62214. BtShared *pBt = pPage->pBt;
  62215. Pgno pgno = pPage->pgno;
  62216. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62217. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  62218. if( rc!=SQLITE_OK ) return rc;
  62219. nCell = pPage->nCell;
  62220. for(i=0; i<nCell; i++){
  62221. u8 *pCell = findCell(pPage, i);
  62222. ptrmapPutOvflPtr(pPage, pCell, &rc);
  62223. if( !pPage->leaf ){
  62224. Pgno childPgno = get4byte(pCell);
  62225. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  62226. }
  62227. }
  62228. if( !pPage->leaf ){
  62229. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  62230. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  62231. }
  62232. return rc;
  62233. }
  62234. /*
  62235. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  62236. ** that it points to iTo. Parameter eType describes the type of pointer to
  62237. ** be modified, as follows:
  62238. **
  62239. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  62240. ** page of pPage.
  62241. **
  62242. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  62243. ** page pointed to by one of the cells on pPage.
  62244. **
  62245. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  62246. ** overflow page in the list.
  62247. */
  62248. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  62249. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62250. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  62251. if( eType==PTRMAP_OVERFLOW2 ){
  62252. /* The pointer is always the first 4 bytes of the page in this case. */
  62253. if( get4byte(pPage->aData)!=iFrom ){
  62254. return SQLITE_CORRUPT_PAGE(pPage);
  62255. }
  62256. put4byte(pPage->aData, iTo);
  62257. }else{
  62258. int i;
  62259. int nCell;
  62260. int rc;
  62261. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  62262. if( rc ) return rc;
  62263. nCell = pPage->nCell;
  62264. for(i=0; i<nCell; i++){
  62265. u8 *pCell = findCell(pPage, i);
  62266. if( eType==PTRMAP_OVERFLOW1 ){
  62267. CellInfo info;
  62268. pPage->xParseCell(pPage, pCell, &info);
  62269. if( info.nLocal<info.nPayload ){
  62270. if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
  62271. return SQLITE_CORRUPT_PAGE(pPage);
  62272. }
  62273. if( iFrom==get4byte(pCell+info.nSize-4) ){
  62274. put4byte(pCell+info.nSize-4, iTo);
  62275. break;
  62276. }
  62277. }
  62278. }else{
  62279. if( get4byte(pCell)==iFrom ){
  62280. put4byte(pCell, iTo);
  62281. break;
  62282. }
  62283. }
  62284. }
  62285. if( i==nCell ){
  62286. if( eType!=PTRMAP_BTREE ||
  62287. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  62288. return SQLITE_CORRUPT_PAGE(pPage);
  62289. }
  62290. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  62291. }
  62292. }
  62293. return SQLITE_OK;
  62294. }
  62295. /*
  62296. ** Move the open database page pDbPage to location iFreePage in the
  62297. ** database. The pDbPage reference remains valid.
  62298. **
  62299. ** The isCommit flag indicates that there is no need to remember that
  62300. ** the journal needs to be sync()ed before database page pDbPage->pgno
  62301. ** can be written to. The caller has already promised not to write to that
  62302. ** page.
  62303. */
  62304. static int relocatePage(
  62305. BtShared *pBt, /* Btree */
  62306. MemPage *pDbPage, /* Open page to move */
  62307. u8 eType, /* Pointer map 'type' entry for pDbPage */
  62308. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  62309. Pgno iFreePage, /* The location to move pDbPage to */
  62310. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  62311. ){
  62312. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  62313. Pgno iDbPage = pDbPage->pgno;
  62314. Pager *pPager = pBt->pPager;
  62315. int rc;
  62316. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  62317. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  62318. assert( sqlite3_mutex_held(pBt->mutex) );
  62319. assert( pDbPage->pBt==pBt );
  62320. if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
  62321. /* Move page iDbPage from its current location to page number iFreePage */
  62322. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  62323. iDbPage, iFreePage, iPtrPage, eType));
  62324. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  62325. if( rc!=SQLITE_OK ){
  62326. return rc;
  62327. }
  62328. pDbPage->pgno = iFreePage;
  62329. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  62330. ** that point to overflow pages. The pointer map entries for all these
  62331. ** pages need to be changed.
  62332. **
  62333. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  62334. ** pointer to a subsequent overflow page. If this is the case, then
  62335. ** the pointer map needs to be updated for the subsequent overflow page.
  62336. */
  62337. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  62338. rc = setChildPtrmaps(pDbPage);
  62339. if( rc!=SQLITE_OK ){
  62340. return rc;
  62341. }
  62342. }else{
  62343. Pgno nextOvfl = get4byte(pDbPage->aData);
  62344. if( nextOvfl!=0 ){
  62345. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  62346. if( rc!=SQLITE_OK ){
  62347. return rc;
  62348. }
  62349. }
  62350. }
  62351. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  62352. ** that it points at iFreePage. Also fix the pointer map entry for
  62353. ** iPtrPage.
  62354. */
  62355. if( eType!=PTRMAP_ROOTPAGE ){
  62356. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  62357. if( rc!=SQLITE_OK ){
  62358. return rc;
  62359. }
  62360. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  62361. if( rc!=SQLITE_OK ){
  62362. releasePage(pPtrPage);
  62363. return rc;
  62364. }
  62365. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  62366. releasePage(pPtrPage);
  62367. if( rc==SQLITE_OK ){
  62368. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  62369. }
  62370. }
  62371. return rc;
  62372. }
  62373. /* Forward declaration required by incrVacuumStep(). */
  62374. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  62375. /*
  62376. ** Perform a single step of an incremental-vacuum. If successful, return
  62377. ** SQLITE_OK. If there is no work to do (and therefore no point in
  62378. ** calling this function again), return SQLITE_DONE. Or, if an error
  62379. ** occurs, return some other error code.
  62380. **
  62381. ** More specifically, this function attempts to re-organize the database so
  62382. ** that the last page of the file currently in use is no longer in use.
  62383. **
  62384. ** Parameter nFin is the number of pages that this database would contain
  62385. ** were this function called until it returns SQLITE_DONE.
  62386. **
  62387. ** If the bCommit parameter is non-zero, this function assumes that the
  62388. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  62389. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  62390. ** operation, or false for an incremental vacuum.
  62391. */
  62392. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  62393. Pgno nFreeList; /* Number of pages still on the free-list */
  62394. int rc;
  62395. assert( sqlite3_mutex_held(pBt->mutex) );
  62396. assert( iLastPg>nFin );
  62397. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  62398. u8 eType;
  62399. Pgno iPtrPage;
  62400. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  62401. if( nFreeList==0 ){
  62402. return SQLITE_DONE;
  62403. }
  62404. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  62405. if( rc!=SQLITE_OK ){
  62406. return rc;
  62407. }
  62408. if( eType==PTRMAP_ROOTPAGE ){
  62409. return SQLITE_CORRUPT_BKPT;
  62410. }
  62411. if( eType==PTRMAP_FREEPAGE ){
  62412. if( bCommit==0 ){
  62413. /* Remove the page from the files free-list. This is not required
  62414. ** if bCommit is non-zero. In that case, the free-list will be
  62415. ** truncated to zero after this function returns, so it doesn't
  62416. ** matter if it still contains some garbage entries.
  62417. */
  62418. Pgno iFreePg;
  62419. MemPage *pFreePg;
  62420. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  62421. if( rc!=SQLITE_OK ){
  62422. return rc;
  62423. }
  62424. assert( iFreePg==iLastPg );
  62425. releasePage(pFreePg);
  62426. }
  62427. } else {
  62428. Pgno iFreePg; /* Index of free page to move pLastPg to */
  62429. MemPage *pLastPg;
  62430. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  62431. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  62432. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  62433. if( rc!=SQLITE_OK ){
  62434. return rc;
  62435. }
  62436. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  62437. ** is swapped with the first free page pulled off the free list.
  62438. **
  62439. ** On the other hand, if bCommit is greater than zero, then keep
  62440. ** looping until a free-page located within the first nFin pages
  62441. ** of the file is found.
  62442. */
  62443. if( bCommit==0 ){
  62444. eMode = BTALLOC_LE;
  62445. iNear = nFin;
  62446. }
  62447. do {
  62448. MemPage *pFreePg;
  62449. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  62450. if( rc!=SQLITE_OK ){
  62451. releasePage(pLastPg);
  62452. return rc;
  62453. }
  62454. releasePage(pFreePg);
  62455. }while( bCommit && iFreePg>nFin );
  62456. assert( iFreePg<iLastPg );
  62457. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  62458. releasePage(pLastPg);
  62459. if( rc!=SQLITE_OK ){
  62460. return rc;
  62461. }
  62462. }
  62463. }
  62464. if( bCommit==0 ){
  62465. do {
  62466. iLastPg--;
  62467. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  62468. pBt->bDoTruncate = 1;
  62469. pBt->nPage = iLastPg;
  62470. }
  62471. return SQLITE_OK;
  62472. }
  62473. /*
  62474. ** The database opened by the first argument is an auto-vacuum database
  62475. ** nOrig pages in size containing nFree free pages. Return the expected
  62476. ** size of the database in pages following an auto-vacuum operation.
  62477. */
  62478. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  62479. int nEntry; /* Number of entries on one ptrmap page */
  62480. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  62481. Pgno nFin; /* Return value */
  62482. nEntry = pBt->usableSize/5;
  62483. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  62484. nFin = nOrig - nFree - nPtrmap;
  62485. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  62486. nFin--;
  62487. }
  62488. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  62489. nFin--;
  62490. }
  62491. return nFin;
  62492. }
  62493. /*
  62494. ** A write-transaction must be opened before calling this function.
  62495. ** It performs a single unit of work towards an incremental vacuum.
  62496. **
  62497. ** If the incremental vacuum is finished after this function has run,
  62498. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  62499. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  62500. */
  62501. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  62502. int rc;
  62503. BtShared *pBt = p->pBt;
  62504. sqlite3BtreeEnter(p);
  62505. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  62506. if( !pBt->autoVacuum ){
  62507. rc = SQLITE_DONE;
  62508. }else{
  62509. Pgno nOrig = btreePagecount(pBt);
  62510. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  62511. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  62512. if( nOrig<nFin ){
  62513. rc = SQLITE_CORRUPT_BKPT;
  62514. }else if( nFree>0 ){
  62515. rc = saveAllCursors(pBt, 0, 0);
  62516. if( rc==SQLITE_OK ){
  62517. invalidateAllOverflowCache(pBt);
  62518. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  62519. }
  62520. if( rc==SQLITE_OK ){
  62521. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  62522. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  62523. }
  62524. }else{
  62525. rc = SQLITE_DONE;
  62526. }
  62527. }
  62528. sqlite3BtreeLeave(p);
  62529. return rc;
  62530. }
  62531. /*
  62532. ** This routine is called prior to sqlite3PagerCommit when a transaction
  62533. ** is committed for an auto-vacuum database.
  62534. **
  62535. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  62536. ** the database file should be truncated to during the commit process.
  62537. ** i.e. the database has been reorganized so that only the first *pnTrunc
  62538. ** pages are in use.
  62539. */
  62540. static int autoVacuumCommit(BtShared *pBt){
  62541. int rc = SQLITE_OK;
  62542. Pager *pPager = pBt->pPager;
  62543. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  62544. assert( sqlite3_mutex_held(pBt->mutex) );
  62545. invalidateAllOverflowCache(pBt);
  62546. assert(pBt->autoVacuum);
  62547. if( !pBt->incrVacuum ){
  62548. Pgno nFin; /* Number of pages in database after autovacuuming */
  62549. Pgno nFree; /* Number of pages on the freelist initially */
  62550. Pgno iFree; /* The next page to be freed */
  62551. Pgno nOrig; /* Database size before freeing */
  62552. nOrig = btreePagecount(pBt);
  62553. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  62554. /* It is not possible to create a database for which the final page
  62555. ** is either a pointer-map page or the pending-byte page. If one
  62556. ** is encountered, this indicates corruption.
  62557. */
  62558. return SQLITE_CORRUPT_BKPT;
  62559. }
  62560. nFree = get4byte(&pBt->pPage1->aData[36]);
  62561. nFin = finalDbSize(pBt, nOrig, nFree);
  62562. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  62563. if( nFin<nOrig ){
  62564. rc = saveAllCursors(pBt, 0, 0);
  62565. }
  62566. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  62567. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  62568. }
  62569. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  62570. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  62571. put4byte(&pBt->pPage1->aData[32], 0);
  62572. put4byte(&pBt->pPage1->aData[36], 0);
  62573. put4byte(&pBt->pPage1->aData[28], nFin);
  62574. pBt->bDoTruncate = 1;
  62575. pBt->nPage = nFin;
  62576. }
  62577. if( rc!=SQLITE_OK ){
  62578. sqlite3PagerRollback(pPager);
  62579. }
  62580. }
  62581. assert( nRef>=sqlite3PagerRefcount(pPager) );
  62582. return rc;
  62583. }
  62584. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  62585. # define setChildPtrmaps(x) SQLITE_OK
  62586. #endif
  62587. /*
  62588. ** This routine does the first phase of a two-phase commit. This routine
  62589. ** causes a rollback journal to be created (if it does not already exist)
  62590. ** and populated with enough information so that if a power loss occurs
  62591. ** the database can be restored to its original state by playing back
  62592. ** the journal. Then the contents of the journal are flushed out to
  62593. ** the disk. After the journal is safely on oxide, the changes to the
  62594. ** database are written into the database file and flushed to oxide.
  62595. ** At the end of this call, the rollback journal still exists on the
  62596. ** disk and we are still holding all locks, so the transaction has not
  62597. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  62598. ** commit process.
  62599. **
  62600. ** This call is a no-op if no write-transaction is currently active on pBt.
  62601. **
  62602. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  62603. ** the name of a master journal file that should be written into the
  62604. ** individual journal file, or is NULL, indicating no master journal file
  62605. ** (single database transaction).
  62606. **
  62607. ** When this is called, the master journal should already have been
  62608. ** created, populated with this journal pointer and synced to disk.
  62609. **
  62610. ** Once this is routine has returned, the only thing required to commit
  62611. ** the write-transaction for this database file is to delete the journal.
  62612. */
  62613. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  62614. int rc = SQLITE_OK;
  62615. if( p->inTrans==TRANS_WRITE ){
  62616. BtShared *pBt = p->pBt;
  62617. sqlite3BtreeEnter(p);
  62618. #ifndef SQLITE_OMIT_AUTOVACUUM
  62619. if( pBt->autoVacuum ){
  62620. rc = autoVacuumCommit(pBt);
  62621. if( rc!=SQLITE_OK ){
  62622. sqlite3BtreeLeave(p);
  62623. return rc;
  62624. }
  62625. }
  62626. if( pBt->bDoTruncate ){
  62627. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  62628. }
  62629. #endif
  62630. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  62631. sqlite3BtreeLeave(p);
  62632. }
  62633. return rc;
  62634. }
  62635. /*
  62636. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  62637. ** at the conclusion of a transaction.
  62638. */
  62639. static void btreeEndTransaction(Btree *p){
  62640. BtShared *pBt = p->pBt;
  62641. sqlite3 *db = p->db;
  62642. assert( sqlite3BtreeHoldsMutex(p) );
  62643. #ifndef SQLITE_OMIT_AUTOVACUUM
  62644. pBt->bDoTruncate = 0;
  62645. #endif
  62646. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  62647. /* If there are other active statements that belong to this database
  62648. ** handle, downgrade to a read-only transaction. The other statements
  62649. ** may still be reading from the database. */
  62650. downgradeAllSharedCacheTableLocks(p);
  62651. p->inTrans = TRANS_READ;
  62652. }else{
  62653. /* If the handle had any kind of transaction open, decrement the
  62654. ** transaction count of the shared btree. If the transaction count
  62655. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  62656. ** call below will unlock the pager. */
  62657. if( p->inTrans!=TRANS_NONE ){
  62658. clearAllSharedCacheTableLocks(p);
  62659. pBt->nTransaction--;
  62660. if( 0==pBt->nTransaction ){
  62661. pBt->inTransaction = TRANS_NONE;
  62662. }
  62663. }
  62664. /* Set the current transaction state to TRANS_NONE and unlock the
  62665. ** pager if this call closed the only read or write transaction. */
  62666. p->inTrans = TRANS_NONE;
  62667. unlockBtreeIfUnused(pBt);
  62668. }
  62669. btreeIntegrity(p);
  62670. }
  62671. /*
  62672. ** Commit the transaction currently in progress.
  62673. **
  62674. ** This routine implements the second phase of a 2-phase commit. The
  62675. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  62676. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  62677. ** routine did all the work of writing information out to disk and flushing the
  62678. ** contents so that they are written onto the disk platter. All this
  62679. ** routine has to do is delete or truncate or zero the header in the
  62680. ** the rollback journal (which causes the transaction to commit) and
  62681. ** drop locks.
  62682. **
  62683. ** Normally, if an error occurs while the pager layer is attempting to
  62684. ** finalize the underlying journal file, this function returns an error and
  62685. ** the upper layer will attempt a rollback. However, if the second argument
  62686. ** is non-zero then this b-tree transaction is part of a multi-file
  62687. ** transaction. In this case, the transaction has already been committed
  62688. ** (by deleting a master journal file) and the caller will ignore this
  62689. ** functions return code. So, even if an error occurs in the pager layer,
  62690. ** reset the b-tree objects internal state to indicate that the write
  62691. ** transaction has been closed. This is quite safe, as the pager will have
  62692. ** transitioned to the error state.
  62693. **
  62694. ** This will release the write lock on the database file. If there
  62695. ** are no active cursors, it also releases the read lock.
  62696. */
  62697. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  62698. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  62699. sqlite3BtreeEnter(p);
  62700. btreeIntegrity(p);
  62701. /* If the handle has a write-transaction open, commit the shared-btrees
  62702. ** transaction and set the shared state to TRANS_READ.
  62703. */
  62704. if( p->inTrans==TRANS_WRITE ){
  62705. int rc;
  62706. BtShared *pBt = p->pBt;
  62707. assert( pBt->inTransaction==TRANS_WRITE );
  62708. assert( pBt->nTransaction>0 );
  62709. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  62710. if( rc!=SQLITE_OK && bCleanup==0 ){
  62711. sqlite3BtreeLeave(p);
  62712. return rc;
  62713. }
  62714. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  62715. pBt->inTransaction = TRANS_READ;
  62716. btreeClearHasContent(pBt);
  62717. }
  62718. btreeEndTransaction(p);
  62719. sqlite3BtreeLeave(p);
  62720. return SQLITE_OK;
  62721. }
  62722. /*
  62723. ** Do both phases of a commit.
  62724. */
  62725. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  62726. int rc;
  62727. sqlite3BtreeEnter(p);
  62728. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  62729. if( rc==SQLITE_OK ){
  62730. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  62731. }
  62732. sqlite3BtreeLeave(p);
  62733. return rc;
  62734. }
  62735. /*
  62736. ** This routine sets the state to CURSOR_FAULT and the error
  62737. ** code to errCode for every cursor on any BtShared that pBtree
  62738. ** references. Or if the writeOnly flag is set to 1, then only
  62739. ** trip write cursors and leave read cursors unchanged.
  62740. **
  62741. ** Every cursor is a candidate to be tripped, including cursors
  62742. ** that belong to other database connections that happen to be
  62743. ** sharing the cache with pBtree.
  62744. **
  62745. ** This routine gets called when a rollback occurs. If the writeOnly
  62746. ** flag is true, then only write-cursors need be tripped - read-only
  62747. ** cursors save their current positions so that they may continue
  62748. ** following the rollback. Or, if writeOnly is false, all cursors are
  62749. ** tripped. In general, writeOnly is false if the transaction being
  62750. ** rolled back modified the database schema. In this case b-tree root
  62751. ** pages may be moved or deleted from the database altogether, making
  62752. ** it unsafe for read cursors to continue.
  62753. **
  62754. ** If the writeOnly flag is true and an error is encountered while
  62755. ** saving the current position of a read-only cursor, all cursors,
  62756. ** including all read-cursors are tripped.
  62757. **
  62758. ** SQLITE_OK is returned if successful, or if an error occurs while
  62759. ** saving a cursor position, an SQLite error code.
  62760. */
  62761. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  62762. BtCursor *p;
  62763. int rc = SQLITE_OK;
  62764. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  62765. if( pBtree ){
  62766. sqlite3BtreeEnter(pBtree);
  62767. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  62768. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  62769. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  62770. rc = saveCursorPosition(p);
  62771. if( rc!=SQLITE_OK ){
  62772. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  62773. break;
  62774. }
  62775. }
  62776. }else{
  62777. sqlite3BtreeClearCursor(p);
  62778. p->eState = CURSOR_FAULT;
  62779. p->skipNext = errCode;
  62780. }
  62781. btreeReleaseAllCursorPages(p);
  62782. }
  62783. sqlite3BtreeLeave(pBtree);
  62784. }
  62785. return rc;
  62786. }
  62787. /*
  62788. ** Rollback the transaction in progress.
  62789. **
  62790. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  62791. ** Only write cursors are tripped if writeOnly is true but all cursors are
  62792. ** tripped if writeOnly is false. Any attempt to use
  62793. ** a tripped cursor will result in an error.
  62794. **
  62795. ** This will release the write lock on the database file. If there
  62796. ** are no active cursors, it also releases the read lock.
  62797. */
  62798. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  62799. int rc;
  62800. BtShared *pBt = p->pBt;
  62801. MemPage *pPage1;
  62802. assert( writeOnly==1 || writeOnly==0 );
  62803. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  62804. sqlite3BtreeEnter(p);
  62805. if( tripCode==SQLITE_OK ){
  62806. rc = tripCode = saveAllCursors(pBt, 0, 0);
  62807. if( rc ) writeOnly = 0;
  62808. }else{
  62809. rc = SQLITE_OK;
  62810. }
  62811. if( tripCode ){
  62812. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  62813. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  62814. if( rc2!=SQLITE_OK ) rc = rc2;
  62815. }
  62816. btreeIntegrity(p);
  62817. if( p->inTrans==TRANS_WRITE ){
  62818. int rc2;
  62819. assert( TRANS_WRITE==pBt->inTransaction );
  62820. rc2 = sqlite3PagerRollback(pBt->pPager);
  62821. if( rc2!=SQLITE_OK ){
  62822. rc = rc2;
  62823. }
  62824. /* The rollback may have destroyed the pPage1->aData value. So
  62825. ** call btreeGetPage() on page 1 again to make
  62826. ** sure pPage1->aData is set correctly. */
  62827. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  62828. int nPage = get4byte(28+(u8*)pPage1->aData);
  62829. testcase( nPage==0 );
  62830. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  62831. testcase( pBt->nPage!=nPage );
  62832. pBt->nPage = nPage;
  62833. releasePageOne(pPage1);
  62834. }
  62835. assert( countValidCursors(pBt, 1)==0 );
  62836. pBt->inTransaction = TRANS_READ;
  62837. btreeClearHasContent(pBt);
  62838. }
  62839. btreeEndTransaction(p);
  62840. sqlite3BtreeLeave(p);
  62841. return rc;
  62842. }
  62843. /*
  62844. ** Start a statement subtransaction. The subtransaction can be rolled
  62845. ** back independently of the main transaction. You must start a transaction
  62846. ** before starting a subtransaction. The subtransaction is ended automatically
  62847. ** if the main transaction commits or rolls back.
  62848. **
  62849. ** Statement subtransactions are used around individual SQL statements
  62850. ** that are contained within a BEGIN...COMMIT block. If a constraint
  62851. ** error occurs within the statement, the effect of that one statement
  62852. ** can be rolled back without having to rollback the entire transaction.
  62853. **
  62854. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  62855. ** value passed as the second parameter is the total number of savepoints,
  62856. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  62857. ** are no active savepoints and no other statement-transactions open,
  62858. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  62859. ** using the sqlite3BtreeSavepoint() function.
  62860. */
  62861. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  62862. int rc;
  62863. BtShared *pBt = p->pBt;
  62864. sqlite3BtreeEnter(p);
  62865. assert( p->inTrans==TRANS_WRITE );
  62866. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  62867. assert( iStatement>0 );
  62868. assert( iStatement>p->db->nSavepoint );
  62869. assert( pBt->inTransaction==TRANS_WRITE );
  62870. /* At the pager level, a statement transaction is a savepoint with
  62871. ** an index greater than all savepoints created explicitly using
  62872. ** SQL statements. It is illegal to open, release or rollback any
  62873. ** such savepoints while the statement transaction savepoint is active.
  62874. */
  62875. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  62876. sqlite3BtreeLeave(p);
  62877. return rc;
  62878. }
  62879. /*
  62880. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  62881. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  62882. ** savepoint identified by parameter iSavepoint, depending on the value
  62883. ** of op.
  62884. **
  62885. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  62886. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  62887. ** contents of the entire transaction are rolled back. This is different
  62888. ** from a normal transaction rollback, as no locks are released and the
  62889. ** transaction remains open.
  62890. */
  62891. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  62892. int rc = SQLITE_OK;
  62893. if( p && p->inTrans==TRANS_WRITE ){
  62894. BtShared *pBt = p->pBt;
  62895. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  62896. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  62897. sqlite3BtreeEnter(p);
  62898. if( op==SAVEPOINT_ROLLBACK ){
  62899. rc = saveAllCursors(pBt, 0, 0);
  62900. }
  62901. if( rc==SQLITE_OK ){
  62902. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  62903. }
  62904. if( rc==SQLITE_OK ){
  62905. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  62906. pBt->nPage = 0;
  62907. }
  62908. rc = newDatabase(pBt);
  62909. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  62910. /* The database size was written into the offset 28 of the header
  62911. ** when the transaction started, so we know that the value at offset
  62912. ** 28 is nonzero. */
  62913. assert( pBt->nPage>0 );
  62914. }
  62915. sqlite3BtreeLeave(p);
  62916. }
  62917. return rc;
  62918. }
  62919. /*
  62920. ** Create a new cursor for the BTree whose root is on the page
  62921. ** iTable. If a read-only cursor is requested, it is assumed that
  62922. ** the caller already has at least a read-only transaction open
  62923. ** on the database already. If a write-cursor is requested, then
  62924. ** the caller is assumed to have an open write transaction.
  62925. **
  62926. ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
  62927. ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
  62928. ** can be used for reading or for writing if other conditions for writing
  62929. ** are also met. These are the conditions that must be met in order
  62930. ** for writing to be allowed:
  62931. **
  62932. ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
  62933. **
  62934. ** 2: Other database connections that share the same pager cache
  62935. ** but which are not in the READ_UNCOMMITTED state may not have
  62936. ** cursors open with wrFlag==0 on the same table. Otherwise
  62937. ** the changes made by this write cursor would be visible to
  62938. ** the read cursors in the other database connection.
  62939. **
  62940. ** 3: The database must be writable (not on read-only media)
  62941. **
  62942. ** 4: There must be an active transaction.
  62943. **
  62944. ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
  62945. ** is set. If FORDELETE is set, that is a hint to the implementation that
  62946. ** this cursor will only be used to seek to and delete entries of an index
  62947. ** as part of a larger DELETE statement. The FORDELETE hint is not used by
  62948. ** this implementation. But in a hypothetical alternative storage engine
  62949. ** in which index entries are automatically deleted when corresponding table
  62950. ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
  62951. ** operations on this cursor can be no-ops and all READ operations can
  62952. ** return a null row (2-bytes: 0x01 0x00).
  62953. **
  62954. ** No checking is done to make sure that page iTable really is the
  62955. ** root page of a b-tree. If it is not, then the cursor acquired
  62956. ** will not work correctly.
  62957. **
  62958. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  62959. ** on pCur to initialize the memory space prior to invoking this routine.
  62960. */
  62961. static int btreeCursor(
  62962. Btree *p, /* The btree */
  62963. int iTable, /* Root page of table to open */
  62964. int wrFlag, /* 1 to write. 0 read-only */
  62965. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  62966. BtCursor *pCur /* Space for new cursor */
  62967. ){
  62968. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  62969. BtCursor *pX; /* Looping over other all cursors */
  62970. assert( sqlite3BtreeHoldsMutex(p) );
  62971. assert( wrFlag==0
  62972. || wrFlag==BTREE_WRCSR
  62973. || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
  62974. );
  62975. /* The following assert statements verify that if this is a sharable
  62976. ** b-tree database, the connection is holding the required table locks,
  62977. ** and that no other connection has any open cursor that conflicts with
  62978. ** this lock. */
  62979. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
  62980. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  62981. /* Assert that the caller has opened the required transaction. */
  62982. assert( p->inTrans>TRANS_NONE );
  62983. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  62984. assert( pBt->pPage1 && pBt->pPage1->aData );
  62985. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  62986. if( wrFlag ){
  62987. allocateTempSpace(pBt);
  62988. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
  62989. }
  62990. if( iTable==1 && btreePagecount(pBt)==0 ){
  62991. assert( wrFlag==0 );
  62992. iTable = 0;
  62993. }
  62994. /* Now that no other errors can occur, finish filling in the BtCursor
  62995. ** variables and link the cursor into the BtShared list. */
  62996. pCur->pgnoRoot = (Pgno)iTable;
  62997. pCur->iPage = -1;
  62998. pCur->pKeyInfo = pKeyInfo;
  62999. pCur->pBtree = p;
  63000. pCur->pBt = pBt;
  63001. pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
  63002. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  63003. /* If there are two or more cursors on the same btree, then all such
  63004. ** cursors *must* have the BTCF_Multiple flag set. */
  63005. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  63006. if( pX->pgnoRoot==(Pgno)iTable ){
  63007. pX->curFlags |= BTCF_Multiple;
  63008. pCur->curFlags |= BTCF_Multiple;
  63009. }
  63010. }
  63011. pCur->pNext = pBt->pCursor;
  63012. pBt->pCursor = pCur;
  63013. pCur->eState = CURSOR_INVALID;
  63014. return SQLITE_OK;
  63015. }
  63016. SQLITE_PRIVATE int sqlite3BtreeCursor(
  63017. Btree *p, /* The btree */
  63018. int iTable, /* Root page of table to open */
  63019. int wrFlag, /* 1 to write. 0 read-only */
  63020. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  63021. BtCursor *pCur /* Write new cursor here */
  63022. ){
  63023. int rc;
  63024. if( iTable<1 ){
  63025. rc = SQLITE_CORRUPT_BKPT;
  63026. }else{
  63027. sqlite3BtreeEnter(p);
  63028. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  63029. sqlite3BtreeLeave(p);
  63030. }
  63031. return rc;
  63032. }
  63033. /*
  63034. ** Return the size of a BtCursor object in bytes.
  63035. **
  63036. ** This interfaces is needed so that users of cursors can preallocate
  63037. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  63038. ** to users so they cannot do the sizeof() themselves - they must call
  63039. ** this routine.
  63040. */
  63041. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  63042. return ROUND8(sizeof(BtCursor));
  63043. }
  63044. /*
  63045. ** Initialize memory that will be converted into a BtCursor object.
  63046. **
  63047. ** The simple approach here would be to memset() the entire object
  63048. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  63049. ** do not need to be zeroed and they are large, so we can save a lot
  63050. ** of run-time by skipping the initialization of those elements.
  63051. */
  63052. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  63053. memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
  63054. }
  63055. /*
  63056. ** Close a cursor. The read lock on the database file is released
  63057. ** when the last cursor is closed.
  63058. */
  63059. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  63060. Btree *pBtree = pCur->pBtree;
  63061. if( pBtree ){
  63062. BtShared *pBt = pCur->pBt;
  63063. sqlite3BtreeEnter(pBtree);
  63064. assert( pBt->pCursor!=0 );
  63065. if( pBt->pCursor==pCur ){
  63066. pBt->pCursor = pCur->pNext;
  63067. }else{
  63068. BtCursor *pPrev = pBt->pCursor;
  63069. do{
  63070. if( pPrev->pNext==pCur ){
  63071. pPrev->pNext = pCur->pNext;
  63072. break;
  63073. }
  63074. pPrev = pPrev->pNext;
  63075. }while( ALWAYS(pPrev) );
  63076. }
  63077. btreeReleaseAllCursorPages(pCur);
  63078. unlockBtreeIfUnused(pBt);
  63079. sqlite3_free(pCur->aOverflow);
  63080. sqlite3_free(pCur->pKey);
  63081. sqlite3BtreeLeave(pBtree);
  63082. }
  63083. return SQLITE_OK;
  63084. }
  63085. /*
  63086. ** Make sure the BtCursor* given in the argument has a valid
  63087. ** BtCursor.info structure. If it is not already valid, call
  63088. ** btreeParseCell() to fill it in.
  63089. **
  63090. ** BtCursor.info is a cache of the information in the current cell.
  63091. ** Using this cache reduces the number of calls to btreeParseCell().
  63092. */
  63093. #ifndef NDEBUG
  63094. static int cellInfoEqual(CellInfo *a, CellInfo *b){
  63095. if( a->nKey!=b->nKey ) return 0;
  63096. if( a->pPayload!=b->pPayload ) return 0;
  63097. if( a->nPayload!=b->nPayload ) return 0;
  63098. if( a->nLocal!=b->nLocal ) return 0;
  63099. if( a->nSize!=b->nSize ) return 0;
  63100. return 1;
  63101. }
  63102. static void assertCellInfo(BtCursor *pCur){
  63103. CellInfo info;
  63104. memset(&info, 0, sizeof(info));
  63105. btreeParseCell(pCur->pPage, pCur->ix, &info);
  63106. assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
  63107. }
  63108. #else
  63109. #define assertCellInfo(x)
  63110. #endif
  63111. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  63112. if( pCur->info.nSize==0 ){
  63113. pCur->curFlags |= BTCF_ValidNKey;
  63114. btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
  63115. }else{
  63116. assertCellInfo(pCur);
  63117. }
  63118. }
  63119. #ifndef NDEBUG /* The next routine used only within assert() statements */
  63120. /*
  63121. ** Return true if the given BtCursor is valid. A valid cursor is one
  63122. ** that is currently pointing to a row in a (non-empty) table.
  63123. ** This is a verification routine is used only within assert() statements.
  63124. */
  63125. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  63126. return pCur && pCur->eState==CURSOR_VALID;
  63127. }
  63128. #endif /* NDEBUG */
  63129. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
  63130. assert( pCur!=0 );
  63131. return pCur->eState==CURSOR_VALID;
  63132. }
  63133. /*
  63134. ** Return the value of the integer key or "rowid" for a table btree.
  63135. ** This routine is only valid for a cursor that is pointing into a
  63136. ** ordinary table btree. If the cursor points to an index btree or
  63137. ** is invalid, the result of this routine is undefined.
  63138. */
  63139. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
  63140. assert( cursorHoldsMutex(pCur) );
  63141. assert( pCur->eState==CURSOR_VALID );
  63142. assert( pCur->curIntKey );
  63143. getCellInfo(pCur);
  63144. return pCur->info.nKey;
  63145. }
  63146. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  63147. /*
  63148. ** Return the offset into the database file for the start of the
  63149. ** payload to which the cursor is pointing.
  63150. */
  63151. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){
  63152. assert( cursorHoldsMutex(pCur) );
  63153. assert( pCur->eState==CURSOR_VALID );
  63154. getCellInfo(pCur);
  63155. return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
  63156. (i64)(pCur->info.pPayload - pCur->pPage->aData);
  63157. }
  63158. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  63159. /*
  63160. ** Return the number of bytes of payload for the entry that pCur is
  63161. ** currently pointing to. For table btrees, this will be the amount
  63162. ** of data. For index btrees, this will be the size of the key.
  63163. **
  63164. ** The caller must guarantee that the cursor is pointing to a non-NULL
  63165. ** valid entry. In other words, the calling procedure must guarantee
  63166. ** that the cursor has Cursor.eState==CURSOR_VALID.
  63167. */
  63168. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
  63169. assert( cursorHoldsMutex(pCur) );
  63170. assert( pCur->eState==CURSOR_VALID );
  63171. getCellInfo(pCur);
  63172. return pCur->info.nPayload;
  63173. }
  63174. /*
  63175. ** Given the page number of an overflow page in the database (parameter
  63176. ** ovfl), this function finds the page number of the next page in the
  63177. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  63178. ** pointer-map data instead of reading the content of page ovfl to do so.
  63179. **
  63180. ** If an error occurs an SQLite error code is returned. Otherwise:
  63181. **
  63182. ** The page number of the next overflow page in the linked list is
  63183. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  63184. ** list, *pPgnoNext is set to zero.
  63185. **
  63186. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  63187. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  63188. ** reference. It is the responsibility of the caller to call releasePage()
  63189. ** on *ppPage to free the reference. In no reference was obtained (because
  63190. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  63191. ** *ppPage is set to zero.
  63192. */
  63193. static int getOverflowPage(
  63194. BtShared *pBt, /* The database file */
  63195. Pgno ovfl, /* Current overflow page number */
  63196. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  63197. Pgno *pPgnoNext /* OUT: Next overflow page number */
  63198. ){
  63199. Pgno next = 0;
  63200. MemPage *pPage = 0;
  63201. int rc = SQLITE_OK;
  63202. assert( sqlite3_mutex_held(pBt->mutex) );
  63203. assert(pPgnoNext);
  63204. #ifndef SQLITE_OMIT_AUTOVACUUM
  63205. /* Try to find the next page in the overflow list using the
  63206. ** autovacuum pointer-map pages. Guess that the next page in
  63207. ** the overflow list is page number (ovfl+1). If that guess turns
  63208. ** out to be wrong, fall back to loading the data of page
  63209. ** number ovfl to determine the next page number.
  63210. */
  63211. if( pBt->autoVacuum ){
  63212. Pgno pgno;
  63213. Pgno iGuess = ovfl+1;
  63214. u8 eType;
  63215. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  63216. iGuess++;
  63217. }
  63218. if( iGuess<=btreePagecount(pBt) ){
  63219. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  63220. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  63221. next = iGuess;
  63222. rc = SQLITE_DONE;
  63223. }
  63224. }
  63225. }
  63226. #endif
  63227. assert( next==0 || rc==SQLITE_DONE );
  63228. if( rc==SQLITE_OK ){
  63229. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  63230. assert( rc==SQLITE_OK || pPage==0 );
  63231. if( rc==SQLITE_OK ){
  63232. next = get4byte(pPage->aData);
  63233. }
  63234. }
  63235. *pPgnoNext = next;
  63236. if( ppPage ){
  63237. *ppPage = pPage;
  63238. }else{
  63239. releasePage(pPage);
  63240. }
  63241. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  63242. }
  63243. /*
  63244. ** Copy data from a buffer to a page, or from a page to a buffer.
  63245. **
  63246. ** pPayload is a pointer to data stored on database page pDbPage.
  63247. ** If argument eOp is false, then nByte bytes of data are copied
  63248. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  63249. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  63250. ** of data are copied from the buffer pBuf to pPayload.
  63251. **
  63252. ** SQLITE_OK is returned on success, otherwise an error code.
  63253. */
  63254. static int copyPayload(
  63255. void *pPayload, /* Pointer to page data */
  63256. void *pBuf, /* Pointer to buffer */
  63257. int nByte, /* Number of bytes to copy */
  63258. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  63259. DbPage *pDbPage /* Page containing pPayload */
  63260. ){
  63261. if( eOp ){
  63262. /* Copy data from buffer to page (a write operation) */
  63263. int rc = sqlite3PagerWrite(pDbPage);
  63264. if( rc!=SQLITE_OK ){
  63265. return rc;
  63266. }
  63267. memcpy(pPayload, pBuf, nByte);
  63268. }else{
  63269. /* Copy data from page to buffer (a read operation) */
  63270. memcpy(pBuf, pPayload, nByte);
  63271. }
  63272. return SQLITE_OK;
  63273. }
  63274. /*
  63275. ** This function is used to read or overwrite payload information
  63276. ** for the entry that the pCur cursor is pointing to. The eOp
  63277. ** argument is interpreted as follows:
  63278. **
  63279. ** 0: The operation is a read. Populate the overflow cache.
  63280. ** 1: The operation is a write. Populate the overflow cache.
  63281. **
  63282. ** A total of "amt" bytes are read or written beginning at "offset".
  63283. ** Data is read to or from the buffer pBuf.
  63284. **
  63285. ** The content being read or written might appear on the main page
  63286. ** or be scattered out on multiple overflow pages.
  63287. **
  63288. ** If the current cursor entry uses one or more overflow pages
  63289. ** this function may allocate space for and lazily populate
  63290. ** the overflow page-list cache array (BtCursor.aOverflow).
  63291. ** Subsequent calls use this cache to make seeking to the supplied offset
  63292. ** more efficient.
  63293. **
  63294. ** Once an overflow page-list cache has been allocated, it must be
  63295. ** invalidated if some other cursor writes to the same table, or if
  63296. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  63297. ** mode, the following events may invalidate an overflow page-list cache.
  63298. **
  63299. ** * An incremental vacuum,
  63300. ** * A commit in auto_vacuum="full" mode,
  63301. ** * Creating a table (may require moving an overflow page).
  63302. */
  63303. static int accessPayload(
  63304. BtCursor *pCur, /* Cursor pointing to entry to read from */
  63305. u32 offset, /* Begin reading this far into payload */
  63306. u32 amt, /* Read this many bytes */
  63307. unsigned char *pBuf, /* Write the bytes into this buffer */
  63308. int eOp /* zero to read. non-zero to write. */
  63309. ){
  63310. unsigned char *aPayload;
  63311. int rc = SQLITE_OK;
  63312. int iIdx = 0;
  63313. MemPage *pPage = pCur->pPage; /* Btree page of current entry */
  63314. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  63315. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  63316. unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
  63317. #endif
  63318. assert( pPage );
  63319. assert( eOp==0 || eOp==1 );
  63320. assert( pCur->eState==CURSOR_VALID );
  63321. assert( pCur->ix<pPage->nCell );
  63322. assert( cursorHoldsMutex(pCur) );
  63323. getCellInfo(pCur);
  63324. aPayload = pCur->info.pPayload;
  63325. assert( offset+amt <= pCur->info.nPayload );
  63326. assert( aPayload > pPage->aData );
  63327. if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
  63328. /* Trying to read or write past the end of the data is an error. The
  63329. ** conditional above is really:
  63330. ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  63331. ** but is recast into its current form to avoid integer overflow problems
  63332. */
  63333. return SQLITE_CORRUPT_PAGE(pPage);
  63334. }
  63335. /* Check if data must be read/written to/from the btree page itself. */
  63336. if( offset<pCur->info.nLocal ){
  63337. int a = amt;
  63338. if( a+offset>pCur->info.nLocal ){
  63339. a = pCur->info.nLocal - offset;
  63340. }
  63341. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  63342. offset = 0;
  63343. pBuf += a;
  63344. amt -= a;
  63345. }else{
  63346. offset -= pCur->info.nLocal;
  63347. }
  63348. if( rc==SQLITE_OK && amt>0 ){
  63349. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  63350. Pgno nextPage;
  63351. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  63352. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  63353. **
  63354. ** The aOverflow[] array is sized at one entry for each overflow page
  63355. ** in the overflow chain. The page number of the first overflow page is
  63356. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  63357. ** means "not yet known" (the cache is lazily populated).
  63358. */
  63359. if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  63360. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  63361. if( pCur->aOverflow==0
  63362. || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
  63363. ){
  63364. Pgno *aNew = (Pgno*)sqlite3Realloc(
  63365. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  63366. );
  63367. if( aNew==0 ){
  63368. return SQLITE_NOMEM_BKPT;
  63369. }else{
  63370. pCur->aOverflow = aNew;
  63371. }
  63372. }
  63373. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  63374. pCur->curFlags |= BTCF_ValidOvfl;
  63375. }else{
  63376. /* If the overflow page-list cache has been allocated and the
  63377. ** entry for the first required overflow page is valid, skip
  63378. ** directly to it.
  63379. */
  63380. if( pCur->aOverflow[offset/ovflSize] ){
  63381. iIdx = (offset/ovflSize);
  63382. nextPage = pCur->aOverflow[iIdx];
  63383. offset = (offset%ovflSize);
  63384. }
  63385. }
  63386. assert( rc==SQLITE_OK && amt>0 );
  63387. while( nextPage ){
  63388. /* If required, populate the overflow page-list cache. */
  63389. assert( pCur->aOverflow[iIdx]==0
  63390. || pCur->aOverflow[iIdx]==nextPage
  63391. || CORRUPT_DB );
  63392. pCur->aOverflow[iIdx] = nextPage;
  63393. if( offset>=ovflSize ){
  63394. /* The only reason to read this page is to obtain the page
  63395. ** number for the next page in the overflow chain. The page
  63396. ** data is not required. So first try to lookup the overflow
  63397. ** page-list cache, if any, then fall back to the getOverflowPage()
  63398. ** function.
  63399. */
  63400. assert( pCur->curFlags & BTCF_ValidOvfl );
  63401. assert( pCur->pBtree->db==pBt->db );
  63402. if( pCur->aOverflow[iIdx+1] ){
  63403. nextPage = pCur->aOverflow[iIdx+1];
  63404. }else{
  63405. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  63406. }
  63407. offset -= ovflSize;
  63408. }else{
  63409. /* Need to read this page properly. It contains some of the
  63410. ** range of data that is being read (eOp==0) or written (eOp!=0).
  63411. */
  63412. int a = amt;
  63413. if( a + offset > ovflSize ){
  63414. a = ovflSize - offset;
  63415. }
  63416. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  63417. /* If all the following are true:
  63418. **
  63419. ** 1) this is a read operation, and
  63420. ** 2) data is required from the start of this overflow page, and
  63421. ** 3) there are no dirty pages in the page-cache
  63422. ** 4) the database is file-backed, and
  63423. ** 5) the page is not in the WAL file
  63424. ** 6) at least 4 bytes have already been read into the output buffer
  63425. **
  63426. ** then data can be read directly from the database file into the
  63427. ** output buffer, bypassing the page-cache altogether. This speeds
  63428. ** up loading large records that span many overflow pages.
  63429. */
  63430. if( eOp==0 /* (1) */
  63431. && offset==0 /* (2) */
  63432. && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
  63433. && &pBuf[-4]>=pBufStart /* (6) */
  63434. ){
  63435. sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
  63436. u8 aSave[4];
  63437. u8 *aWrite = &pBuf[-4];
  63438. assert( aWrite>=pBufStart ); /* due to (6) */
  63439. memcpy(aSave, aWrite, 4);
  63440. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  63441. nextPage = get4byte(aWrite);
  63442. memcpy(aWrite, aSave, 4);
  63443. }else
  63444. #endif
  63445. {
  63446. DbPage *pDbPage;
  63447. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
  63448. (eOp==0 ? PAGER_GET_READONLY : 0)
  63449. );
  63450. if( rc==SQLITE_OK ){
  63451. aPayload = sqlite3PagerGetData(pDbPage);
  63452. nextPage = get4byte(aPayload);
  63453. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  63454. sqlite3PagerUnref(pDbPage);
  63455. offset = 0;
  63456. }
  63457. }
  63458. amt -= a;
  63459. if( amt==0 ) return rc;
  63460. pBuf += a;
  63461. }
  63462. if( rc ) break;
  63463. iIdx++;
  63464. }
  63465. }
  63466. if( rc==SQLITE_OK && amt>0 ){
  63467. /* Overflow chain ends prematurely */
  63468. return SQLITE_CORRUPT_PAGE(pPage);
  63469. }
  63470. return rc;
  63471. }
  63472. /*
  63473. ** Read part of the payload for the row at which that cursor pCur is currently
  63474. ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
  63475. ** begins at "offset".
  63476. **
  63477. ** pCur can be pointing to either a table or an index b-tree.
  63478. ** If pointing to a table btree, then the content section is read. If
  63479. ** pCur is pointing to an index b-tree then the key section is read.
  63480. **
  63481. ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
  63482. ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
  63483. ** cursor might be invalid or might need to be restored before being read.
  63484. **
  63485. ** Return SQLITE_OK on success or an error code if anything goes
  63486. ** wrong. An error is returned if "offset+amt" is larger than
  63487. ** the available payload.
  63488. */
  63489. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  63490. assert( cursorHoldsMutex(pCur) );
  63491. assert( pCur->eState==CURSOR_VALID );
  63492. assert( pCur->iPage>=0 && pCur->pPage );
  63493. assert( pCur->ix<pCur->pPage->nCell );
  63494. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  63495. }
  63496. /*
  63497. ** This variant of sqlite3BtreePayload() works even if the cursor has not
  63498. ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
  63499. ** interface.
  63500. */
  63501. #ifndef SQLITE_OMIT_INCRBLOB
  63502. static SQLITE_NOINLINE int accessPayloadChecked(
  63503. BtCursor *pCur,
  63504. u32 offset,
  63505. u32 amt,
  63506. void *pBuf
  63507. ){
  63508. int rc;
  63509. if ( pCur->eState==CURSOR_INVALID ){
  63510. return SQLITE_ABORT;
  63511. }
  63512. assert( cursorOwnsBtShared(pCur) );
  63513. rc = btreeRestoreCursorPosition(pCur);
  63514. return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
  63515. }
  63516. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  63517. if( pCur->eState==CURSOR_VALID ){
  63518. assert( cursorOwnsBtShared(pCur) );
  63519. return accessPayload(pCur, offset, amt, pBuf, 0);
  63520. }else{
  63521. return accessPayloadChecked(pCur, offset, amt, pBuf);
  63522. }
  63523. }
  63524. #endif /* SQLITE_OMIT_INCRBLOB */
  63525. /*
  63526. ** Return a pointer to payload information from the entry that the
  63527. ** pCur cursor is pointing to. The pointer is to the beginning of
  63528. ** the key if index btrees (pPage->intKey==0) and is the data for
  63529. ** table btrees (pPage->intKey==1). The number of bytes of available
  63530. ** key/data is written into *pAmt. If *pAmt==0, then the value
  63531. ** returned will not be a valid pointer.
  63532. **
  63533. ** This routine is an optimization. It is common for the entire key
  63534. ** and data to fit on the local page and for there to be no overflow
  63535. ** pages. When that is so, this routine can be used to access the
  63536. ** key and data without making a copy. If the key and/or data spills
  63537. ** onto overflow pages, then accessPayload() must be used to reassemble
  63538. ** the key/data and copy it into a preallocated buffer.
  63539. **
  63540. ** The pointer returned by this routine looks directly into the cached
  63541. ** page of the database. The data might change or move the next time
  63542. ** any btree routine is called.
  63543. */
  63544. static const void *fetchPayload(
  63545. BtCursor *pCur, /* Cursor pointing to entry to read from */
  63546. u32 *pAmt /* Write the number of available bytes here */
  63547. ){
  63548. int amt;
  63549. assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
  63550. assert( pCur->eState==CURSOR_VALID );
  63551. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  63552. assert( cursorOwnsBtShared(pCur) );
  63553. assert( pCur->ix<pCur->pPage->nCell );
  63554. assert( pCur->info.nSize>0 );
  63555. assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
  63556. assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
  63557. amt = pCur->info.nLocal;
  63558. if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
  63559. /* There is too little space on the page for the expected amount
  63560. ** of local content. Database must be corrupt. */
  63561. assert( CORRUPT_DB );
  63562. amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
  63563. }
  63564. *pAmt = (u32)amt;
  63565. return (void*)pCur->info.pPayload;
  63566. }
  63567. /*
  63568. ** For the entry that cursor pCur is point to, return as
  63569. ** many bytes of the key or data as are available on the local
  63570. ** b-tree page. Write the number of available bytes into *pAmt.
  63571. **
  63572. ** The pointer returned is ephemeral. The key/data may move
  63573. ** or be destroyed on the next call to any Btree routine,
  63574. ** including calls from other threads against the same cache.
  63575. ** Hence, a mutex on the BtShared should be held prior to calling
  63576. ** this routine.
  63577. **
  63578. ** These routines is used to get quick access to key and data
  63579. ** in the common case where no overflow pages are used.
  63580. */
  63581. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
  63582. return fetchPayload(pCur, pAmt);
  63583. }
  63584. /*
  63585. ** Move the cursor down to a new child page. The newPgno argument is the
  63586. ** page number of the child page to move to.
  63587. **
  63588. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  63589. ** the new child page does not match the flags field of the parent (i.e.
  63590. ** if an intkey page appears to be the parent of a non-intkey page, or
  63591. ** vice-versa).
  63592. */
  63593. static int moveToChild(BtCursor *pCur, u32 newPgno){
  63594. BtShared *pBt = pCur->pBt;
  63595. assert( cursorOwnsBtShared(pCur) );
  63596. assert( pCur->eState==CURSOR_VALID );
  63597. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  63598. assert( pCur->iPage>=0 );
  63599. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  63600. return SQLITE_CORRUPT_BKPT;
  63601. }
  63602. pCur->info.nSize = 0;
  63603. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  63604. pCur->aiIdx[pCur->iPage] = pCur->ix;
  63605. pCur->apPage[pCur->iPage] = pCur->pPage;
  63606. pCur->ix = 0;
  63607. pCur->iPage++;
  63608. return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
  63609. }
  63610. #ifdef SQLITE_DEBUG
  63611. /*
  63612. ** Page pParent is an internal (non-leaf) tree page. This function
  63613. ** asserts that page number iChild is the left-child if the iIdx'th
  63614. ** cell in page pParent. Or, if iIdx is equal to the total number of
  63615. ** cells in pParent, that page number iChild is the right-child of
  63616. ** the page.
  63617. */
  63618. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  63619. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  63620. ** in a corrupt database */
  63621. assert( iIdx<=pParent->nCell );
  63622. if( iIdx==pParent->nCell ){
  63623. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  63624. }else{
  63625. assert( get4byte(findCell(pParent, iIdx))==iChild );
  63626. }
  63627. }
  63628. #else
  63629. # define assertParentIndex(x,y,z)
  63630. #endif
  63631. /*
  63632. ** Move the cursor up to the parent page.
  63633. **
  63634. ** pCur->idx is set to the cell index that contains the pointer
  63635. ** to the page we are coming from. If we are coming from the
  63636. ** right-most child page then pCur->idx is set to one more than
  63637. ** the largest cell index.
  63638. */
  63639. static void moveToParent(BtCursor *pCur){
  63640. MemPage *pLeaf;
  63641. assert( cursorOwnsBtShared(pCur) );
  63642. assert( pCur->eState==CURSOR_VALID );
  63643. assert( pCur->iPage>0 );
  63644. assert( pCur->pPage );
  63645. assertParentIndex(
  63646. pCur->apPage[pCur->iPage-1],
  63647. pCur->aiIdx[pCur->iPage-1],
  63648. pCur->pPage->pgno
  63649. );
  63650. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  63651. pCur->info.nSize = 0;
  63652. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  63653. pCur->ix = pCur->aiIdx[pCur->iPage-1];
  63654. pLeaf = pCur->pPage;
  63655. pCur->pPage = pCur->apPage[--pCur->iPage];
  63656. releasePageNotNull(pLeaf);
  63657. }
  63658. /*
  63659. ** Move the cursor to point to the root page of its b-tree structure.
  63660. **
  63661. ** If the table has a virtual root page, then the cursor is moved to point
  63662. ** to the virtual root page instead of the actual root page. A table has a
  63663. ** virtual root page when the actual root page contains no cells and a
  63664. ** single child page. This can only happen with the table rooted at page 1.
  63665. **
  63666. ** If the b-tree structure is empty, the cursor state is set to
  63667. ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
  63668. ** the cursor is set to point to the first cell located on the root
  63669. ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
  63670. **
  63671. ** If this function returns successfully, it may be assumed that the
  63672. ** page-header flags indicate that the [virtual] root-page is the expected
  63673. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  63674. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  63675. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  63676. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  63677. ** b-tree).
  63678. */
  63679. static int moveToRoot(BtCursor *pCur){
  63680. MemPage *pRoot;
  63681. int rc = SQLITE_OK;
  63682. assert( cursorOwnsBtShared(pCur) );
  63683. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  63684. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  63685. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  63686. assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
  63687. assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
  63688. if( pCur->iPage>=0 ){
  63689. if( pCur->iPage ){
  63690. releasePageNotNull(pCur->pPage);
  63691. while( --pCur->iPage ){
  63692. releasePageNotNull(pCur->apPage[pCur->iPage]);
  63693. }
  63694. pCur->pPage = pCur->apPage[0];
  63695. goto skip_init;
  63696. }
  63697. }else if( pCur->pgnoRoot==0 ){
  63698. pCur->eState = CURSOR_INVALID;
  63699. return SQLITE_EMPTY;
  63700. }else{
  63701. assert( pCur->iPage==(-1) );
  63702. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  63703. if( pCur->eState==CURSOR_FAULT ){
  63704. assert( pCur->skipNext!=SQLITE_OK );
  63705. return pCur->skipNext;
  63706. }
  63707. sqlite3BtreeClearCursor(pCur);
  63708. }
  63709. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
  63710. 0, pCur->curPagerFlags);
  63711. if( rc!=SQLITE_OK ){
  63712. pCur->eState = CURSOR_INVALID;
  63713. return rc;
  63714. }
  63715. pCur->iPage = 0;
  63716. pCur->curIntKey = pCur->pPage->intKey;
  63717. }
  63718. pRoot = pCur->pPage;
  63719. assert( pRoot->pgno==pCur->pgnoRoot );
  63720. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  63721. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  63722. ** NULL, the caller expects a table b-tree. If this is not the case,
  63723. ** return an SQLITE_CORRUPT error.
  63724. **
  63725. ** Earlier versions of SQLite assumed that this test could not fail
  63726. ** if the root page was already loaded when this function was called (i.e.
  63727. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  63728. ** in such a way that page pRoot is linked into a second b-tree table
  63729. ** (or the freelist). */
  63730. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  63731. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  63732. return SQLITE_CORRUPT_PAGE(pCur->pPage);
  63733. }
  63734. skip_init:
  63735. pCur->ix = 0;
  63736. pCur->info.nSize = 0;
  63737. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  63738. pRoot = pCur->pPage;
  63739. if( pRoot->nCell>0 ){
  63740. pCur->eState = CURSOR_VALID;
  63741. }else if( !pRoot->leaf ){
  63742. Pgno subpage;
  63743. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  63744. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  63745. pCur->eState = CURSOR_VALID;
  63746. rc = moveToChild(pCur, subpage);
  63747. }else{
  63748. pCur->eState = CURSOR_INVALID;
  63749. rc = SQLITE_EMPTY;
  63750. }
  63751. return rc;
  63752. }
  63753. /*
  63754. ** Move the cursor down to the left-most leaf entry beneath the
  63755. ** entry to which it is currently pointing.
  63756. **
  63757. ** The left-most leaf is the one with the smallest key - the first
  63758. ** in ascending order.
  63759. */
  63760. static int moveToLeftmost(BtCursor *pCur){
  63761. Pgno pgno;
  63762. int rc = SQLITE_OK;
  63763. MemPage *pPage;
  63764. assert( cursorOwnsBtShared(pCur) );
  63765. assert( pCur->eState==CURSOR_VALID );
  63766. while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
  63767. assert( pCur->ix<pPage->nCell );
  63768. pgno = get4byte(findCell(pPage, pCur->ix));
  63769. rc = moveToChild(pCur, pgno);
  63770. }
  63771. return rc;
  63772. }
  63773. /*
  63774. ** Move the cursor down to the right-most leaf entry beneath the
  63775. ** page to which it is currently pointing. Notice the difference
  63776. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  63777. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  63778. ** finds the right-most entry beneath the *page*.
  63779. **
  63780. ** The right-most entry is the one with the largest key - the last
  63781. ** key in ascending order.
  63782. */
  63783. static int moveToRightmost(BtCursor *pCur){
  63784. Pgno pgno;
  63785. int rc = SQLITE_OK;
  63786. MemPage *pPage = 0;
  63787. assert( cursorOwnsBtShared(pCur) );
  63788. assert( pCur->eState==CURSOR_VALID );
  63789. while( !(pPage = pCur->pPage)->leaf ){
  63790. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  63791. pCur->ix = pPage->nCell;
  63792. rc = moveToChild(pCur, pgno);
  63793. if( rc ) return rc;
  63794. }
  63795. pCur->ix = pPage->nCell-1;
  63796. assert( pCur->info.nSize==0 );
  63797. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  63798. return SQLITE_OK;
  63799. }
  63800. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  63801. ** on success. Set *pRes to 0 if the cursor actually points to something
  63802. ** or set *pRes to 1 if the table is empty.
  63803. */
  63804. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  63805. int rc;
  63806. assert( cursorOwnsBtShared(pCur) );
  63807. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  63808. rc = moveToRoot(pCur);
  63809. if( rc==SQLITE_OK ){
  63810. assert( pCur->pPage->nCell>0 );
  63811. *pRes = 0;
  63812. rc = moveToLeftmost(pCur);
  63813. }else if( rc==SQLITE_EMPTY ){
  63814. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  63815. *pRes = 1;
  63816. rc = SQLITE_OK;
  63817. }
  63818. return rc;
  63819. }
  63820. /*
  63821. ** This function is a no-op if cursor pCur does not point to a valid row.
  63822. ** Otherwise, if pCur is valid, configure it so that the next call to
  63823. ** sqlite3BtreeNext() is a no-op.
  63824. */
  63825. #ifndef SQLITE_OMIT_WINDOWFUNC
  63826. SQLITE_PRIVATE void sqlite3BtreeSkipNext(BtCursor *pCur){
  63827. /* We believe that the cursor must always be in the valid state when
  63828. ** this routine is called, but the proof is difficult, so we add an
  63829. ** ALWaYS() test just in case we are wrong. */
  63830. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  63831. pCur->eState = CURSOR_SKIPNEXT;
  63832. pCur->skipNext = 1;
  63833. }
  63834. }
  63835. #endif /* SQLITE_OMIT_WINDOWFUNC */
  63836. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  63837. ** on success. Set *pRes to 0 if the cursor actually points to something
  63838. ** or set *pRes to 1 if the table is empty.
  63839. */
  63840. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  63841. int rc;
  63842. assert( cursorOwnsBtShared(pCur) );
  63843. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  63844. /* If the cursor already points to the last entry, this is a no-op. */
  63845. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  63846. #ifdef SQLITE_DEBUG
  63847. /* This block serves to assert() that the cursor really does point
  63848. ** to the last entry in the b-tree. */
  63849. int ii;
  63850. for(ii=0; ii<pCur->iPage; ii++){
  63851. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  63852. }
  63853. assert( pCur->ix==pCur->pPage->nCell-1 );
  63854. assert( pCur->pPage->leaf );
  63855. #endif
  63856. return SQLITE_OK;
  63857. }
  63858. rc = moveToRoot(pCur);
  63859. if( rc==SQLITE_OK ){
  63860. assert( pCur->eState==CURSOR_VALID );
  63861. *pRes = 0;
  63862. rc = moveToRightmost(pCur);
  63863. if( rc==SQLITE_OK ){
  63864. pCur->curFlags |= BTCF_AtLast;
  63865. }else{
  63866. pCur->curFlags &= ~BTCF_AtLast;
  63867. }
  63868. }else if( rc==SQLITE_EMPTY ){
  63869. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  63870. *pRes = 1;
  63871. rc = SQLITE_OK;
  63872. }
  63873. return rc;
  63874. }
  63875. /* Move the cursor so that it points to an entry near the key
  63876. ** specified by pIdxKey or intKey. Return a success code.
  63877. **
  63878. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  63879. ** must be NULL. For index tables, pIdxKey is used and intKey
  63880. ** is ignored.
  63881. **
  63882. ** If an exact match is not found, then the cursor is always
  63883. ** left pointing at a leaf page which would hold the entry if it
  63884. ** were present. The cursor might point to an entry that comes
  63885. ** before or after the key.
  63886. **
  63887. ** An integer is written into *pRes which is the result of
  63888. ** comparing the key with the entry to which the cursor is
  63889. ** pointing. The meaning of the integer written into
  63890. ** *pRes is as follows:
  63891. **
  63892. ** *pRes<0 The cursor is left pointing at an entry that
  63893. ** is smaller than intKey/pIdxKey or if the table is empty
  63894. ** and the cursor is therefore left point to nothing.
  63895. **
  63896. ** *pRes==0 The cursor is left pointing at an entry that
  63897. ** exactly matches intKey/pIdxKey.
  63898. **
  63899. ** *pRes>0 The cursor is left pointing at an entry that
  63900. ** is larger than intKey/pIdxKey.
  63901. **
  63902. ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
  63903. ** exists an entry in the table that exactly matches pIdxKey.
  63904. */
  63905. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  63906. BtCursor *pCur, /* The cursor to be moved */
  63907. UnpackedRecord *pIdxKey, /* Unpacked index key */
  63908. i64 intKey, /* The table key */
  63909. int biasRight, /* If true, bias the search to the high end */
  63910. int *pRes /* Write search results here */
  63911. ){
  63912. int rc;
  63913. RecordCompare xRecordCompare;
  63914. assert( cursorOwnsBtShared(pCur) );
  63915. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  63916. assert( pRes );
  63917. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  63918. assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
  63919. /* If the cursor is already positioned at the point we are trying
  63920. ** to move to, then just return without doing any work */
  63921. if( pIdxKey==0
  63922. && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  63923. ){
  63924. if( pCur->info.nKey==intKey ){
  63925. *pRes = 0;
  63926. return SQLITE_OK;
  63927. }
  63928. if( pCur->info.nKey<intKey ){
  63929. if( (pCur->curFlags & BTCF_AtLast)!=0 ){
  63930. *pRes = -1;
  63931. return SQLITE_OK;
  63932. }
  63933. /* If the requested key is one more than the previous key, then
  63934. ** try to get there using sqlite3BtreeNext() rather than a full
  63935. ** binary search. This is an optimization only. The correct answer
  63936. ** is still obtained without this case, only a little more slowely */
  63937. if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
  63938. *pRes = 0;
  63939. rc = sqlite3BtreeNext(pCur, 0);
  63940. if( rc==SQLITE_OK ){
  63941. getCellInfo(pCur);
  63942. if( pCur->info.nKey==intKey ){
  63943. return SQLITE_OK;
  63944. }
  63945. }else if( rc==SQLITE_DONE ){
  63946. rc = SQLITE_OK;
  63947. }else{
  63948. return rc;
  63949. }
  63950. }
  63951. }
  63952. }
  63953. if( pIdxKey ){
  63954. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  63955. pIdxKey->errCode = 0;
  63956. assert( pIdxKey->default_rc==1
  63957. || pIdxKey->default_rc==0
  63958. || pIdxKey->default_rc==-1
  63959. );
  63960. }else{
  63961. xRecordCompare = 0; /* All keys are integers */
  63962. }
  63963. rc = moveToRoot(pCur);
  63964. if( rc ){
  63965. if( rc==SQLITE_EMPTY ){
  63966. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  63967. *pRes = -1;
  63968. return SQLITE_OK;
  63969. }
  63970. return rc;
  63971. }
  63972. assert( pCur->pPage );
  63973. assert( pCur->pPage->isInit );
  63974. assert( pCur->eState==CURSOR_VALID );
  63975. assert( pCur->pPage->nCell > 0 );
  63976. assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
  63977. assert( pCur->curIntKey || pIdxKey );
  63978. for(;;){
  63979. int lwr, upr, idx, c;
  63980. Pgno chldPg;
  63981. MemPage *pPage = pCur->pPage;
  63982. u8 *pCell; /* Pointer to current cell in pPage */
  63983. /* pPage->nCell must be greater than zero. If this is the root-page
  63984. ** the cursor would have been INVALID above and this for(;;) loop
  63985. ** not run. If this is not the root-page, then the moveToChild() routine
  63986. ** would have already detected db corruption. Similarly, pPage must
  63987. ** be the right kind (index or table) of b-tree page. Otherwise
  63988. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  63989. assert( pPage->nCell>0 );
  63990. assert( pPage->intKey==(pIdxKey==0) );
  63991. lwr = 0;
  63992. upr = pPage->nCell-1;
  63993. assert( biasRight==0 || biasRight==1 );
  63994. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  63995. pCur->ix = (u16)idx;
  63996. if( xRecordCompare==0 ){
  63997. for(;;){
  63998. i64 nCellKey;
  63999. pCell = findCellPastPtr(pPage, idx);
  64000. if( pPage->intKeyLeaf ){
  64001. while( 0x80 <= *(pCell++) ){
  64002. if( pCell>=pPage->aDataEnd ){
  64003. return SQLITE_CORRUPT_PAGE(pPage);
  64004. }
  64005. }
  64006. }
  64007. getVarint(pCell, (u64*)&nCellKey);
  64008. if( nCellKey<intKey ){
  64009. lwr = idx+1;
  64010. if( lwr>upr ){ c = -1; break; }
  64011. }else if( nCellKey>intKey ){
  64012. upr = idx-1;
  64013. if( lwr>upr ){ c = +1; break; }
  64014. }else{
  64015. assert( nCellKey==intKey );
  64016. pCur->ix = (u16)idx;
  64017. if( !pPage->leaf ){
  64018. lwr = idx;
  64019. goto moveto_next_layer;
  64020. }else{
  64021. pCur->curFlags |= BTCF_ValidNKey;
  64022. pCur->info.nKey = nCellKey;
  64023. pCur->info.nSize = 0;
  64024. *pRes = 0;
  64025. return SQLITE_OK;
  64026. }
  64027. }
  64028. assert( lwr+upr>=0 );
  64029. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  64030. }
  64031. }else{
  64032. for(;;){
  64033. int nCell; /* Size of the pCell cell in bytes */
  64034. pCell = findCellPastPtr(pPage, idx);
  64035. /* The maximum supported page-size is 65536 bytes. This means that
  64036. ** the maximum number of record bytes stored on an index B-Tree
  64037. ** page is less than 16384 bytes and may be stored as a 2-byte
  64038. ** varint. This information is used to attempt to avoid parsing
  64039. ** the entire cell by checking for the cases where the record is
  64040. ** stored entirely within the b-tree page by inspecting the first
  64041. ** 2 bytes of the cell.
  64042. */
  64043. nCell = pCell[0];
  64044. if( nCell<=pPage->max1bytePayload ){
  64045. /* This branch runs if the record-size field of the cell is a
  64046. ** single byte varint and the record fits entirely on the main
  64047. ** b-tree page. */
  64048. testcase( pCell+nCell+1==pPage->aDataEnd );
  64049. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  64050. }else if( !(pCell[1] & 0x80)
  64051. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  64052. ){
  64053. /* The record-size field is a 2 byte varint and the record
  64054. ** fits entirely on the main b-tree page. */
  64055. testcase( pCell+nCell+2==pPage->aDataEnd );
  64056. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  64057. }else{
  64058. /* The record flows over onto one or more overflow pages. In
  64059. ** this case the whole cell needs to be parsed, a buffer allocated
  64060. ** and accessPayload() used to retrieve the record into the
  64061. ** buffer before VdbeRecordCompare() can be called.
  64062. **
  64063. ** If the record is corrupt, the xRecordCompare routine may read
  64064. ** up to two varints past the end of the buffer. An extra 18
  64065. ** bytes of padding is allocated at the end of the buffer in
  64066. ** case this happens. */
  64067. void *pCellKey;
  64068. u8 * const pCellBody = pCell - pPage->childPtrSize;
  64069. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  64070. nCell = (int)pCur->info.nKey;
  64071. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  64072. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  64073. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  64074. testcase( nCell==2 ); /* Minimum legal index key size */
  64075. if( nCell<2 ){
  64076. rc = SQLITE_CORRUPT_PAGE(pPage);
  64077. goto moveto_finish;
  64078. }
  64079. pCellKey = sqlite3Malloc( nCell+18 );
  64080. if( pCellKey==0 ){
  64081. rc = SQLITE_NOMEM_BKPT;
  64082. goto moveto_finish;
  64083. }
  64084. pCur->ix = (u16)idx;
  64085. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  64086. pCur->curFlags &= ~BTCF_ValidOvfl;
  64087. if( rc ){
  64088. sqlite3_free(pCellKey);
  64089. goto moveto_finish;
  64090. }
  64091. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  64092. sqlite3_free(pCellKey);
  64093. }
  64094. assert(
  64095. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  64096. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  64097. );
  64098. if( c<0 ){
  64099. lwr = idx+1;
  64100. }else if( c>0 ){
  64101. upr = idx-1;
  64102. }else{
  64103. assert( c==0 );
  64104. *pRes = 0;
  64105. rc = SQLITE_OK;
  64106. pCur->ix = (u16)idx;
  64107. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
  64108. goto moveto_finish;
  64109. }
  64110. if( lwr>upr ) break;
  64111. assert( lwr+upr>=0 );
  64112. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  64113. }
  64114. }
  64115. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  64116. assert( pPage->isInit );
  64117. if( pPage->leaf ){
  64118. assert( pCur->ix<pCur->pPage->nCell );
  64119. pCur->ix = (u16)idx;
  64120. *pRes = c;
  64121. rc = SQLITE_OK;
  64122. goto moveto_finish;
  64123. }
  64124. moveto_next_layer:
  64125. if( lwr>=pPage->nCell ){
  64126. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  64127. }else{
  64128. chldPg = get4byte(findCell(pPage, lwr));
  64129. }
  64130. pCur->ix = (u16)lwr;
  64131. rc = moveToChild(pCur, chldPg);
  64132. if( rc ) break;
  64133. }
  64134. moveto_finish:
  64135. pCur->info.nSize = 0;
  64136. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  64137. return rc;
  64138. }
  64139. /*
  64140. ** Return TRUE if the cursor is not pointing at an entry of the table.
  64141. **
  64142. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  64143. ** past the last entry in the table or sqlite3BtreePrev() moves past
  64144. ** the first entry. TRUE is also returned if the table is empty.
  64145. */
  64146. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  64147. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  64148. ** have been deleted? This API will need to change to return an error code
  64149. ** as well as the boolean result value.
  64150. */
  64151. return (CURSOR_VALID!=pCur->eState);
  64152. }
  64153. /*
  64154. ** Return an estimate for the number of rows in the table that pCur is
  64155. ** pointing to. Return a negative number if no estimate is currently
  64156. ** available.
  64157. */
  64158. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
  64159. i64 n;
  64160. u8 i;
  64161. assert( cursorOwnsBtShared(pCur) );
  64162. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  64163. /* Currently this interface is only called by the OP_IfSmaller
  64164. ** opcode, and it that case the cursor will always be valid and
  64165. ** will always point to a leaf node. */
  64166. if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
  64167. if( NEVER(pCur->pPage->leaf==0) ) return -1;
  64168. n = pCur->pPage->nCell;
  64169. for(i=0; i<pCur->iPage; i++){
  64170. n *= pCur->apPage[i]->nCell;
  64171. }
  64172. return n;
  64173. }
  64174. /*
  64175. ** Advance the cursor to the next entry in the database.
  64176. ** Return value:
  64177. **
  64178. ** SQLITE_OK success
  64179. ** SQLITE_DONE cursor is already pointing at the last element
  64180. ** otherwise some kind of error occurred
  64181. **
  64182. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  64183. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  64184. ** to the next cell on the current page. The (slower) btreeNext() helper
  64185. ** routine is called when it is necessary to move to a different page or
  64186. ** to restore the cursor.
  64187. **
  64188. ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
  64189. ** cursor corresponds to an SQL index and this routine could have been
  64190. ** skipped if the SQL index had been a unique index. The F argument
  64191. ** is a hint to the implement. SQLite btree implementation does not use
  64192. ** this hint, but COMDB2 does.
  64193. */
  64194. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
  64195. int rc;
  64196. int idx;
  64197. MemPage *pPage;
  64198. assert( cursorOwnsBtShared(pCur) );
  64199. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  64200. if( pCur->eState!=CURSOR_VALID ){
  64201. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  64202. rc = restoreCursorPosition(pCur);
  64203. if( rc!=SQLITE_OK ){
  64204. return rc;
  64205. }
  64206. if( CURSOR_INVALID==pCur->eState ){
  64207. return SQLITE_DONE;
  64208. }
  64209. if( pCur->skipNext ){
  64210. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  64211. pCur->eState = CURSOR_VALID;
  64212. if( pCur->skipNext>0 ){
  64213. pCur->skipNext = 0;
  64214. return SQLITE_OK;
  64215. }
  64216. pCur->skipNext = 0;
  64217. }
  64218. }
  64219. pPage = pCur->pPage;
  64220. idx = ++pCur->ix;
  64221. if( !pPage->isInit ){
  64222. /* The only known way for this to happen is for there to be a
  64223. ** recursive SQL function that does a DELETE operation as part of a
  64224. ** SELECT which deletes content out from under an active cursor
  64225. ** in a corrupt database file where the table being DELETE-ed from
  64226. ** has pages in common with the table being queried. See TH3
  64227. ** module cov1/btree78.test testcase 220 (2018-06-08) for an
  64228. ** example. */
  64229. return SQLITE_CORRUPT_BKPT;
  64230. }
  64231. /* If the database file is corrupt, it is possible for the value of idx
  64232. ** to be invalid here. This can only occur if a second cursor modifies
  64233. ** the page while cursor pCur is holding a reference to it. Which can
  64234. ** only happen if the database is corrupt in such a way as to link the
  64235. ** page into more than one b-tree structure. */
  64236. testcase( idx>pPage->nCell );
  64237. if( idx>=pPage->nCell ){
  64238. if( !pPage->leaf ){
  64239. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  64240. if( rc ) return rc;
  64241. return moveToLeftmost(pCur);
  64242. }
  64243. do{
  64244. if( pCur->iPage==0 ){
  64245. pCur->eState = CURSOR_INVALID;
  64246. return SQLITE_DONE;
  64247. }
  64248. moveToParent(pCur);
  64249. pPage = pCur->pPage;
  64250. }while( pCur->ix>=pPage->nCell );
  64251. if( pPage->intKey ){
  64252. return sqlite3BtreeNext(pCur, 0);
  64253. }else{
  64254. return SQLITE_OK;
  64255. }
  64256. }
  64257. if( pPage->leaf ){
  64258. return SQLITE_OK;
  64259. }else{
  64260. return moveToLeftmost(pCur);
  64261. }
  64262. }
  64263. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
  64264. MemPage *pPage;
  64265. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  64266. assert( cursorOwnsBtShared(pCur) );
  64267. assert( flags==0 || flags==1 );
  64268. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  64269. pCur->info.nSize = 0;
  64270. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  64271. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
  64272. pPage = pCur->pPage;
  64273. if( (++pCur->ix)>=pPage->nCell ){
  64274. pCur->ix--;
  64275. return btreeNext(pCur);
  64276. }
  64277. if( pPage->leaf ){
  64278. return SQLITE_OK;
  64279. }else{
  64280. return moveToLeftmost(pCur);
  64281. }
  64282. }
  64283. /*
  64284. ** Step the cursor to the back to the previous entry in the database.
  64285. ** Return values:
  64286. **
  64287. ** SQLITE_OK success
  64288. ** SQLITE_DONE the cursor is already on the first element of the table
  64289. ** otherwise some kind of error occurred
  64290. **
  64291. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  64292. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  64293. ** to the previous cell on the current page. The (slower) btreePrevious()
  64294. ** helper routine is called when it is necessary to move to a different page
  64295. ** or to restore the cursor.
  64296. **
  64297. ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
  64298. ** the cursor corresponds to an SQL index and this routine could have been
  64299. ** skipped if the SQL index had been a unique index. The F argument is a
  64300. ** hint to the implement. The native SQLite btree implementation does not
  64301. ** use this hint, but COMDB2 does.
  64302. */
  64303. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
  64304. int rc;
  64305. MemPage *pPage;
  64306. assert( cursorOwnsBtShared(pCur) );
  64307. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  64308. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  64309. assert( pCur->info.nSize==0 );
  64310. if( pCur->eState!=CURSOR_VALID ){
  64311. rc = restoreCursorPosition(pCur);
  64312. if( rc!=SQLITE_OK ){
  64313. return rc;
  64314. }
  64315. if( CURSOR_INVALID==pCur->eState ){
  64316. return SQLITE_DONE;
  64317. }
  64318. if( pCur->skipNext ){
  64319. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  64320. pCur->eState = CURSOR_VALID;
  64321. if( pCur->skipNext<0 ){
  64322. pCur->skipNext = 0;
  64323. return SQLITE_OK;
  64324. }
  64325. pCur->skipNext = 0;
  64326. }
  64327. }
  64328. pPage = pCur->pPage;
  64329. assert( pPage->isInit );
  64330. if( !pPage->leaf ){
  64331. int idx = pCur->ix;
  64332. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  64333. if( rc ) return rc;
  64334. rc = moveToRightmost(pCur);
  64335. }else{
  64336. while( pCur->ix==0 ){
  64337. if( pCur->iPage==0 ){
  64338. pCur->eState = CURSOR_INVALID;
  64339. return SQLITE_DONE;
  64340. }
  64341. moveToParent(pCur);
  64342. }
  64343. assert( pCur->info.nSize==0 );
  64344. assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
  64345. pCur->ix--;
  64346. pPage = pCur->pPage;
  64347. if( pPage->intKey && !pPage->leaf ){
  64348. rc = sqlite3BtreePrevious(pCur, 0);
  64349. }else{
  64350. rc = SQLITE_OK;
  64351. }
  64352. }
  64353. return rc;
  64354. }
  64355. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
  64356. assert( cursorOwnsBtShared(pCur) );
  64357. assert( flags==0 || flags==1 );
  64358. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  64359. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  64360. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  64361. pCur->info.nSize = 0;
  64362. if( pCur->eState!=CURSOR_VALID
  64363. || pCur->ix==0
  64364. || pCur->pPage->leaf==0
  64365. ){
  64366. return btreePrevious(pCur);
  64367. }
  64368. pCur->ix--;
  64369. return SQLITE_OK;
  64370. }
  64371. /*
  64372. ** Allocate a new page from the database file.
  64373. **
  64374. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  64375. ** has already been called on the new page.) The new page has also
  64376. ** been referenced and the calling routine is responsible for calling
  64377. ** sqlite3PagerUnref() on the new page when it is done.
  64378. **
  64379. ** SQLITE_OK is returned on success. Any other return value indicates
  64380. ** an error. *ppPage is set to NULL in the event of an error.
  64381. **
  64382. ** If the "nearby" parameter is not 0, then an effort is made to
  64383. ** locate a page close to the page number "nearby". This can be used in an
  64384. ** attempt to keep related pages close to each other in the database file,
  64385. ** which in turn can make database access faster.
  64386. **
  64387. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  64388. ** anywhere on the free-list, then it is guaranteed to be returned. If
  64389. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  64390. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  64391. ** are no restrictions on which page is returned.
  64392. */
  64393. static int allocateBtreePage(
  64394. BtShared *pBt, /* The btree */
  64395. MemPage **ppPage, /* Store pointer to the allocated page here */
  64396. Pgno *pPgno, /* Store the page number here */
  64397. Pgno nearby, /* Search for a page near this one */
  64398. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  64399. ){
  64400. MemPage *pPage1;
  64401. int rc;
  64402. u32 n; /* Number of pages on the freelist */
  64403. u32 k; /* Number of leaves on the trunk of the freelist */
  64404. MemPage *pTrunk = 0;
  64405. MemPage *pPrevTrunk = 0;
  64406. Pgno mxPage; /* Total size of the database file */
  64407. assert( sqlite3_mutex_held(pBt->mutex) );
  64408. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  64409. pPage1 = pBt->pPage1;
  64410. mxPage = btreePagecount(pBt);
  64411. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  64412. ** stores stores the total number of pages on the freelist. */
  64413. n = get4byte(&pPage1->aData[36]);
  64414. testcase( n==mxPage-1 );
  64415. if( n>=mxPage ){
  64416. return SQLITE_CORRUPT_BKPT;
  64417. }
  64418. if( n>0 ){
  64419. /* There are pages on the freelist. Reuse one of those pages. */
  64420. Pgno iTrunk;
  64421. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  64422. u32 nSearch = 0; /* Count of the number of search attempts */
  64423. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  64424. ** shows that the page 'nearby' is somewhere on the free-list, then
  64425. ** the entire-list will be searched for that page.
  64426. */
  64427. #ifndef SQLITE_OMIT_AUTOVACUUM
  64428. if( eMode==BTALLOC_EXACT ){
  64429. if( nearby<=mxPage ){
  64430. u8 eType;
  64431. assert( nearby>0 );
  64432. assert( pBt->autoVacuum );
  64433. rc = ptrmapGet(pBt, nearby, &eType, 0);
  64434. if( rc ) return rc;
  64435. if( eType==PTRMAP_FREEPAGE ){
  64436. searchList = 1;
  64437. }
  64438. }
  64439. }else if( eMode==BTALLOC_LE ){
  64440. searchList = 1;
  64441. }
  64442. #endif
  64443. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  64444. ** first free-list trunk page. iPrevTrunk is initially 1.
  64445. */
  64446. rc = sqlite3PagerWrite(pPage1->pDbPage);
  64447. if( rc ) return rc;
  64448. put4byte(&pPage1->aData[36], n-1);
  64449. /* The code within this loop is run only once if the 'searchList' variable
  64450. ** is not true. Otherwise, it runs once for each trunk-page on the
  64451. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  64452. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  64453. */
  64454. do {
  64455. pPrevTrunk = pTrunk;
  64456. if( pPrevTrunk ){
  64457. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  64458. ** is the page number of the next freelist trunk page in the list or
  64459. ** zero if this is the last freelist trunk page. */
  64460. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  64461. }else{
  64462. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  64463. ** stores the page number of the first page of the freelist, or zero if
  64464. ** the freelist is empty. */
  64465. iTrunk = get4byte(&pPage1->aData[32]);
  64466. }
  64467. testcase( iTrunk==mxPage );
  64468. if( iTrunk>mxPage || nSearch++ > n ){
  64469. rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
  64470. }else{
  64471. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  64472. }
  64473. if( rc ){
  64474. pTrunk = 0;
  64475. goto end_allocate_page;
  64476. }
  64477. assert( pTrunk!=0 );
  64478. assert( pTrunk->aData!=0 );
  64479. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  64480. ** is the number of leaf page pointers to follow. */
  64481. k = get4byte(&pTrunk->aData[4]);
  64482. if( k==0 && !searchList ){
  64483. /* The trunk has no leaves and the list is not being searched.
  64484. ** So extract the trunk page itself and use it as the newly
  64485. ** allocated page */
  64486. assert( pPrevTrunk==0 );
  64487. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  64488. if( rc ){
  64489. goto end_allocate_page;
  64490. }
  64491. *pPgno = iTrunk;
  64492. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  64493. *ppPage = pTrunk;
  64494. pTrunk = 0;
  64495. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  64496. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  64497. /* Value of k is out of range. Database corruption */
  64498. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  64499. goto end_allocate_page;
  64500. #ifndef SQLITE_OMIT_AUTOVACUUM
  64501. }else if( searchList
  64502. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  64503. ){
  64504. /* The list is being searched and this trunk page is the page
  64505. ** to allocate, regardless of whether it has leaves.
  64506. */
  64507. *pPgno = iTrunk;
  64508. *ppPage = pTrunk;
  64509. searchList = 0;
  64510. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  64511. if( rc ){
  64512. goto end_allocate_page;
  64513. }
  64514. if( k==0 ){
  64515. if( !pPrevTrunk ){
  64516. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  64517. }else{
  64518. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  64519. if( rc!=SQLITE_OK ){
  64520. goto end_allocate_page;
  64521. }
  64522. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  64523. }
  64524. }else{
  64525. /* The trunk page is required by the caller but it contains
  64526. ** pointers to free-list leaves. The first leaf becomes a trunk
  64527. ** page in this case.
  64528. */
  64529. MemPage *pNewTrunk;
  64530. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  64531. if( iNewTrunk>mxPage ){
  64532. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  64533. goto end_allocate_page;
  64534. }
  64535. testcase( iNewTrunk==mxPage );
  64536. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  64537. if( rc!=SQLITE_OK ){
  64538. goto end_allocate_page;
  64539. }
  64540. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  64541. if( rc!=SQLITE_OK ){
  64542. releasePage(pNewTrunk);
  64543. goto end_allocate_page;
  64544. }
  64545. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  64546. put4byte(&pNewTrunk->aData[4], k-1);
  64547. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  64548. releasePage(pNewTrunk);
  64549. if( !pPrevTrunk ){
  64550. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  64551. put4byte(&pPage1->aData[32], iNewTrunk);
  64552. }else{
  64553. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  64554. if( rc ){
  64555. goto end_allocate_page;
  64556. }
  64557. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  64558. }
  64559. }
  64560. pTrunk = 0;
  64561. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  64562. #endif
  64563. }else if( k>0 ){
  64564. /* Extract a leaf from the trunk */
  64565. u32 closest;
  64566. Pgno iPage;
  64567. unsigned char *aData = pTrunk->aData;
  64568. if( nearby>0 ){
  64569. u32 i;
  64570. closest = 0;
  64571. if( eMode==BTALLOC_LE ){
  64572. for(i=0; i<k; i++){
  64573. iPage = get4byte(&aData[8+i*4]);
  64574. if( iPage<=nearby ){
  64575. closest = i;
  64576. break;
  64577. }
  64578. }
  64579. }else{
  64580. int dist;
  64581. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  64582. for(i=1; i<k; i++){
  64583. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  64584. if( d2<dist ){
  64585. closest = i;
  64586. dist = d2;
  64587. }
  64588. }
  64589. }
  64590. }else{
  64591. closest = 0;
  64592. }
  64593. iPage = get4byte(&aData[8+closest*4]);
  64594. testcase( iPage==mxPage );
  64595. if( iPage>mxPage ){
  64596. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  64597. goto end_allocate_page;
  64598. }
  64599. testcase( iPage==mxPage );
  64600. if( !searchList
  64601. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  64602. ){
  64603. int noContent;
  64604. *pPgno = iPage;
  64605. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  64606. ": %d more free pages\n",
  64607. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  64608. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  64609. if( rc ) goto end_allocate_page;
  64610. if( closest<k-1 ){
  64611. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  64612. }
  64613. put4byte(&aData[4], k-1);
  64614. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  64615. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  64616. if( rc==SQLITE_OK ){
  64617. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  64618. if( rc!=SQLITE_OK ){
  64619. releasePage(*ppPage);
  64620. *ppPage = 0;
  64621. }
  64622. }
  64623. searchList = 0;
  64624. }
  64625. }
  64626. releasePage(pPrevTrunk);
  64627. pPrevTrunk = 0;
  64628. }while( searchList );
  64629. }else{
  64630. /* There are no pages on the freelist, so append a new page to the
  64631. ** database image.
  64632. **
  64633. ** Normally, new pages allocated by this block can be requested from the
  64634. ** pager layer with the 'no-content' flag set. This prevents the pager
  64635. ** from trying to read the pages content from disk. However, if the
  64636. ** current transaction has already run one or more incremental-vacuum
  64637. ** steps, then the page we are about to allocate may contain content
  64638. ** that is required in the event of a rollback. In this case, do
  64639. ** not set the no-content flag. This causes the pager to load and journal
  64640. ** the current page content before overwriting it.
  64641. **
  64642. ** Note that the pager will not actually attempt to load or journal
  64643. ** content for any page that really does lie past the end of the database
  64644. ** file on disk. So the effects of disabling the no-content optimization
  64645. ** here are confined to those pages that lie between the end of the
  64646. ** database image and the end of the database file.
  64647. */
  64648. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  64649. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  64650. if( rc ) return rc;
  64651. pBt->nPage++;
  64652. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  64653. #ifndef SQLITE_OMIT_AUTOVACUUM
  64654. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  64655. /* If *pPgno refers to a pointer-map page, allocate two new pages
  64656. ** at the end of the file instead of one. The first allocated page
  64657. ** becomes a new pointer-map page, the second is used by the caller.
  64658. */
  64659. MemPage *pPg = 0;
  64660. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  64661. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  64662. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  64663. if( rc==SQLITE_OK ){
  64664. rc = sqlite3PagerWrite(pPg->pDbPage);
  64665. releasePage(pPg);
  64666. }
  64667. if( rc ) return rc;
  64668. pBt->nPage++;
  64669. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  64670. }
  64671. #endif
  64672. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  64673. *pPgno = pBt->nPage;
  64674. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  64675. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  64676. if( rc ) return rc;
  64677. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  64678. if( rc!=SQLITE_OK ){
  64679. releasePage(*ppPage);
  64680. *ppPage = 0;
  64681. }
  64682. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  64683. }
  64684. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  64685. end_allocate_page:
  64686. releasePage(pTrunk);
  64687. releasePage(pPrevTrunk);
  64688. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  64689. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  64690. return rc;
  64691. }
  64692. /*
  64693. ** This function is used to add page iPage to the database file free-list.
  64694. ** It is assumed that the page is not already a part of the free-list.
  64695. **
  64696. ** The value passed as the second argument to this function is optional.
  64697. ** If the caller happens to have a pointer to the MemPage object
  64698. ** corresponding to page iPage handy, it may pass it as the second value.
  64699. ** Otherwise, it may pass NULL.
  64700. **
  64701. ** If a pointer to a MemPage object is passed as the second argument,
  64702. ** its reference count is not altered by this function.
  64703. */
  64704. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  64705. MemPage *pTrunk = 0; /* Free-list trunk page */
  64706. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  64707. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  64708. MemPage *pPage; /* Page being freed. May be NULL. */
  64709. int rc; /* Return Code */
  64710. int nFree; /* Initial number of pages on free-list */
  64711. assert( sqlite3_mutex_held(pBt->mutex) );
  64712. assert( CORRUPT_DB || iPage>1 );
  64713. assert( !pMemPage || pMemPage->pgno==iPage );
  64714. if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
  64715. if( pMemPage ){
  64716. pPage = pMemPage;
  64717. sqlite3PagerRef(pPage->pDbPage);
  64718. }else{
  64719. pPage = btreePageLookup(pBt, iPage);
  64720. }
  64721. /* Increment the free page count on pPage1 */
  64722. rc = sqlite3PagerWrite(pPage1->pDbPage);
  64723. if( rc ) goto freepage_out;
  64724. nFree = get4byte(&pPage1->aData[36]);
  64725. put4byte(&pPage1->aData[36], nFree+1);
  64726. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  64727. /* If the secure_delete option is enabled, then
  64728. ** always fully overwrite deleted information with zeros.
  64729. */
  64730. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  64731. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  64732. ){
  64733. goto freepage_out;
  64734. }
  64735. memset(pPage->aData, 0, pPage->pBt->pageSize);
  64736. }
  64737. /* If the database supports auto-vacuum, write an entry in the pointer-map
  64738. ** to indicate that the page is free.
  64739. */
  64740. if( ISAUTOVACUUM ){
  64741. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  64742. if( rc ) goto freepage_out;
  64743. }
  64744. /* Now manipulate the actual database free-list structure. There are two
  64745. ** possibilities. If the free-list is currently empty, or if the first
  64746. ** trunk page in the free-list is full, then this page will become a
  64747. ** new free-list trunk page. Otherwise, it will become a leaf of the
  64748. ** first trunk page in the current free-list. This block tests if it
  64749. ** is possible to add the page as a new free-list leaf.
  64750. */
  64751. if( nFree!=0 ){
  64752. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  64753. iTrunk = get4byte(&pPage1->aData[32]);
  64754. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  64755. if( rc!=SQLITE_OK ){
  64756. goto freepage_out;
  64757. }
  64758. nLeaf = get4byte(&pTrunk->aData[4]);
  64759. assert( pBt->usableSize>32 );
  64760. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  64761. rc = SQLITE_CORRUPT_BKPT;
  64762. goto freepage_out;
  64763. }
  64764. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  64765. /* In this case there is room on the trunk page to insert the page
  64766. ** being freed as a new leaf.
  64767. **
  64768. ** Note that the trunk page is not really full until it contains
  64769. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  64770. ** coded. But due to a coding error in versions of SQLite prior to
  64771. ** 3.6.0, databases with freelist trunk pages holding more than
  64772. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  64773. ** to maintain backwards compatibility with older versions of SQLite,
  64774. ** we will continue to restrict the number of entries to usableSize/4 - 8
  64775. ** for now. At some point in the future (once everyone has upgraded
  64776. ** to 3.6.0 or later) we should consider fixing the conditional above
  64777. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  64778. **
  64779. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  64780. ** avoid using the last six entries in the freelist trunk page array in
  64781. ** order that database files created by newer versions of SQLite can be
  64782. ** read by older versions of SQLite.
  64783. */
  64784. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  64785. if( rc==SQLITE_OK ){
  64786. put4byte(&pTrunk->aData[4], nLeaf+1);
  64787. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  64788. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  64789. sqlite3PagerDontWrite(pPage->pDbPage);
  64790. }
  64791. rc = btreeSetHasContent(pBt, iPage);
  64792. }
  64793. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  64794. goto freepage_out;
  64795. }
  64796. }
  64797. /* If control flows to this point, then it was not possible to add the
  64798. ** the page being freed as a leaf page of the first trunk in the free-list.
  64799. ** Possibly because the free-list is empty, or possibly because the
  64800. ** first trunk in the free-list is full. Either way, the page being freed
  64801. ** will become the new first trunk page in the free-list.
  64802. */
  64803. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  64804. goto freepage_out;
  64805. }
  64806. rc = sqlite3PagerWrite(pPage->pDbPage);
  64807. if( rc!=SQLITE_OK ){
  64808. goto freepage_out;
  64809. }
  64810. put4byte(pPage->aData, iTrunk);
  64811. put4byte(&pPage->aData[4], 0);
  64812. put4byte(&pPage1->aData[32], iPage);
  64813. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  64814. freepage_out:
  64815. if( pPage ){
  64816. pPage->isInit = 0;
  64817. }
  64818. releasePage(pPage);
  64819. releasePage(pTrunk);
  64820. return rc;
  64821. }
  64822. static void freePage(MemPage *pPage, int *pRC){
  64823. if( (*pRC)==SQLITE_OK ){
  64824. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  64825. }
  64826. }
  64827. /*
  64828. ** Free any overflow pages associated with the given Cell. Store
  64829. ** size information about the cell in pInfo.
  64830. */
  64831. static int clearCell(
  64832. MemPage *pPage, /* The page that contains the Cell */
  64833. unsigned char *pCell, /* First byte of the Cell */
  64834. CellInfo *pInfo /* Size information about the cell */
  64835. ){
  64836. BtShared *pBt;
  64837. Pgno ovflPgno;
  64838. int rc;
  64839. int nOvfl;
  64840. u32 ovflPageSize;
  64841. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  64842. pPage->xParseCell(pPage, pCell, pInfo);
  64843. if( pInfo->nLocal==pInfo->nPayload ){
  64844. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  64845. }
  64846. testcase( pCell + pInfo->nSize == pPage->aDataEnd );
  64847. testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
  64848. if( pCell + pInfo->nSize > pPage->aDataEnd ){
  64849. /* Cell extends past end of page */
  64850. return SQLITE_CORRUPT_PAGE(pPage);
  64851. }
  64852. ovflPgno = get4byte(pCell + pInfo->nSize - 4);
  64853. pBt = pPage->pBt;
  64854. assert( pBt->usableSize > 4 );
  64855. ovflPageSize = pBt->usableSize - 4;
  64856. nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
  64857. assert( nOvfl>0 ||
  64858. (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
  64859. );
  64860. while( nOvfl-- ){
  64861. Pgno iNext = 0;
  64862. MemPage *pOvfl = 0;
  64863. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  64864. /* 0 is not a legal page number and page 1 cannot be an
  64865. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  64866. ** file the database must be corrupt. */
  64867. return SQLITE_CORRUPT_BKPT;
  64868. }
  64869. if( nOvfl ){
  64870. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  64871. if( rc ) return rc;
  64872. }
  64873. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  64874. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  64875. ){
  64876. /* There is no reason any cursor should have an outstanding reference
  64877. ** to an overflow page belonging to a cell that is being deleted/updated.
  64878. ** So if there exists more than one reference to this page, then it
  64879. ** must not really be an overflow page and the database must be corrupt.
  64880. ** It is helpful to detect this before calling freePage2(), as
  64881. ** freePage2() may zero the page contents if secure-delete mode is
  64882. ** enabled. If this 'overflow' page happens to be a page that the
  64883. ** caller is iterating through or using in some other way, this
  64884. ** can be problematic.
  64885. */
  64886. rc = SQLITE_CORRUPT_BKPT;
  64887. }else{
  64888. rc = freePage2(pBt, pOvfl, ovflPgno);
  64889. }
  64890. if( pOvfl ){
  64891. sqlite3PagerUnref(pOvfl->pDbPage);
  64892. }
  64893. if( rc ) return rc;
  64894. ovflPgno = iNext;
  64895. }
  64896. return SQLITE_OK;
  64897. }
  64898. /*
  64899. ** Create the byte sequence used to represent a cell on page pPage
  64900. ** and write that byte sequence into pCell[]. Overflow pages are
  64901. ** allocated and filled in as necessary. The calling procedure
  64902. ** is responsible for making sure sufficient space has been allocated
  64903. ** for pCell[].
  64904. **
  64905. ** Note that pCell does not necessary need to point to the pPage->aData
  64906. ** area. pCell might point to some temporary storage. The cell will
  64907. ** be constructed in this temporary area then copied into pPage->aData
  64908. ** later.
  64909. */
  64910. static int fillInCell(
  64911. MemPage *pPage, /* The page that contains the cell */
  64912. unsigned char *pCell, /* Complete text of the cell */
  64913. const BtreePayload *pX, /* Payload with which to construct the cell */
  64914. int *pnSize /* Write cell size here */
  64915. ){
  64916. int nPayload;
  64917. const u8 *pSrc;
  64918. int nSrc, n, rc, mn;
  64919. int spaceLeft;
  64920. MemPage *pToRelease;
  64921. unsigned char *pPrior;
  64922. unsigned char *pPayload;
  64923. BtShared *pBt;
  64924. Pgno pgnoOvfl;
  64925. int nHeader;
  64926. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  64927. /* pPage is not necessarily writeable since pCell might be auxiliary
  64928. ** buffer space that is separate from the pPage buffer area */
  64929. assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
  64930. || sqlite3PagerIswriteable(pPage->pDbPage) );
  64931. /* Fill in the header. */
  64932. nHeader = pPage->childPtrSize;
  64933. if( pPage->intKey ){
  64934. nPayload = pX->nData + pX->nZero;
  64935. pSrc = pX->pData;
  64936. nSrc = pX->nData;
  64937. assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
  64938. nHeader += putVarint32(&pCell[nHeader], nPayload);
  64939. nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
  64940. }else{
  64941. assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
  64942. nSrc = nPayload = (int)pX->nKey;
  64943. pSrc = pX->pKey;
  64944. nHeader += putVarint32(&pCell[nHeader], nPayload);
  64945. }
  64946. /* Fill in the payload */
  64947. pPayload = &pCell[nHeader];
  64948. if( nPayload<=pPage->maxLocal ){
  64949. /* This is the common case where everything fits on the btree page
  64950. ** and no overflow pages are required. */
  64951. n = nHeader + nPayload;
  64952. testcase( n==3 );
  64953. testcase( n==4 );
  64954. if( n<4 ) n = 4;
  64955. *pnSize = n;
  64956. assert( nSrc<=nPayload );
  64957. testcase( nSrc<nPayload );
  64958. memcpy(pPayload, pSrc, nSrc);
  64959. memset(pPayload+nSrc, 0, nPayload-nSrc);
  64960. return SQLITE_OK;
  64961. }
  64962. /* If we reach this point, it means that some of the content will need
  64963. ** to spill onto overflow pages.
  64964. */
  64965. mn = pPage->minLocal;
  64966. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  64967. testcase( n==pPage->maxLocal );
  64968. testcase( n==pPage->maxLocal+1 );
  64969. if( n > pPage->maxLocal ) n = mn;
  64970. spaceLeft = n;
  64971. *pnSize = n + nHeader + 4;
  64972. pPrior = &pCell[nHeader+n];
  64973. pToRelease = 0;
  64974. pgnoOvfl = 0;
  64975. pBt = pPage->pBt;
  64976. /* At this point variables should be set as follows:
  64977. **
  64978. ** nPayload Total payload size in bytes
  64979. ** pPayload Begin writing payload here
  64980. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  64981. ** that means content must spill into overflow pages.
  64982. ** *pnSize Size of the local cell (not counting overflow pages)
  64983. ** pPrior Where to write the pgno of the first overflow page
  64984. **
  64985. ** Use a call to btreeParseCellPtr() to verify that the values above
  64986. ** were computed correctly.
  64987. */
  64988. #ifdef SQLITE_DEBUG
  64989. {
  64990. CellInfo info;
  64991. pPage->xParseCell(pPage, pCell, &info);
  64992. assert( nHeader==(int)(info.pPayload - pCell) );
  64993. assert( info.nKey==pX->nKey );
  64994. assert( *pnSize == info.nSize );
  64995. assert( spaceLeft == info.nLocal );
  64996. }
  64997. #endif
  64998. /* Write the payload into the local Cell and any extra into overflow pages */
  64999. while( 1 ){
  65000. n = nPayload;
  65001. if( n>spaceLeft ) n = spaceLeft;
  65002. /* If pToRelease is not zero than pPayload points into the data area
  65003. ** of pToRelease. Make sure pToRelease is still writeable. */
  65004. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  65005. /* If pPayload is part of the data area of pPage, then make sure pPage
  65006. ** is still writeable */
  65007. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  65008. || sqlite3PagerIswriteable(pPage->pDbPage) );
  65009. if( nSrc>=n ){
  65010. memcpy(pPayload, pSrc, n);
  65011. }else if( nSrc>0 ){
  65012. n = nSrc;
  65013. memcpy(pPayload, pSrc, n);
  65014. }else{
  65015. memset(pPayload, 0, n);
  65016. }
  65017. nPayload -= n;
  65018. if( nPayload<=0 ) break;
  65019. pPayload += n;
  65020. pSrc += n;
  65021. nSrc -= n;
  65022. spaceLeft -= n;
  65023. if( spaceLeft==0 ){
  65024. MemPage *pOvfl = 0;
  65025. #ifndef SQLITE_OMIT_AUTOVACUUM
  65026. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  65027. if( pBt->autoVacuum ){
  65028. do{
  65029. pgnoOvfl++;
  65030. } while(
  65031. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  65032. );
  65033. }
  65034. #endif
  65035. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  65036. #ifndef SQLITE_OMIT_AUTOVACUUM
  65037. /* If the database supports auto-vacuum, and the second or subsequent
  65038. ** overflow page is being allocated, add an entry to the pointer-map
  65039. ** for that page now.
  65040. **
  65041. ** If this is the first overflow page, then write a partial entry
  65042. ** to the pointer-map. If we write nothing to this pointer-map slot,
  65043. ** then the optimistic overflow chain processing in clearCell()
  65044. ** may misinterpret the uninitialized values and delete the
  65045. ** wrong pages from the database.
  65046. */
  65047. if( pBt->autoVacuum && rc==SQLITE_OK ){
  65048. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  65049. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  65050. if( rc ){
  65051. releasePage(pOvfl);
  65052. }
  65053. }
  65054. #endif
  65055. if( rc ){
  65056. releasePage(pToRelease);
  65057. return rc;
  65058. }
  65059. /* If pToRelease is not zero than pPrior points into the data area
  65060. ** of pToRelease. Make sure pToRelease is still writeable. */
  65061. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  65062. /* If pPrior is part of the data area of pPage, then make sure pPage
  65063. ** is still writeable */
  65064. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  65065. || sqlite3PagerIswriteable(pPage->pDbPage) );
  65066. put4byte(pPrior, pgnoOvfl);
  65067. releasePage(pToRelease);
  65068. pToRelease = pOvfl;
  65069. pPrior = pOvfl->aData;
  65070. put4byte(pPrior, 0);
  65071. pPayload = &pOvfl->aData[4];
  65072. spaceLeft = pBt->usableSize - 4;
  65073. }
  65074. }
  65075. releasePage(pToRelease);
  65076. return SQLITE_OK;
  65077. }
  65078. /*
  65079. ** Remove the i-th cell from pPage. This routine effects pPage only.
  65080. ** The cell content is not freed or deallocated. It is assumed that
  65081. ** the cell content has been copied someplace else. This routine just
  65082. ** removes the reference to the cell from pPage.
  65083. **
  65084. ** "sz" must be the number of bytes in the cell.
  65085. */
  65086. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  65087. u32 pc; /* Offset to cell content of cell being deleted */
  65088. u8 *data; /* pPage->aData */
  65089. u8 *ptr; /* Used to move bytes around within data[] */
  65090. int rc; /* The return code */
  65091. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  65092. if( *pRC ) return;
  65093. assert( idx>=0 && idx<pPage->nCell );
  65094. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  65095. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  65096. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65097. data = pPage->aData;
  65098. ptr = &pPage->aCellIdx[2*idx];
  65099. pc = get2byte(ptr);
  65100. hdr = pPage->hdrOffset;
  65101. testcase( pc==get2byte(&data[hdr+5]) );
  65102. testcase( pc+sz==pPage->pBt->usableSize );
  65103. if( pc+sz > pPage->pBt->usableSize ){
  65104. *pRC = SQLITE_CORRUPT_BKPT;
  65105. return;
  65106. }
  65107. rc = freeSpace(pPage, pc, sz);
  65108. if( rc ){
  65109. *pRC = rc;
  65110. return;
  65111. }
  65112. pPage->nCell--;
  65113. if( pPage->nCell==0 ){
  65114. memset(&data[hdr+1], 0, 4);
  65115. data[hdr+7] = 0;
  65116. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  65117. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  65118. - pPage->childPtrSize - 8;
  65119. }else{
  65120. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  65121. put2byte(&data[hdr+3], pPage->nCell);
  65122. pPage->nFree += 2;
  65123. }
  65124. }
  65125. /*
  65126. ** Insert a new cell on pPage at cell index "i". pCell points to the
  65127. ** content of the cell.
  65128. **
  65129. ** If the cell content will fit on the page, then put it there. If it
  65130. ** will not fit, then make a copy of the cell content into pTemp if
  65131. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  65132. ** in pPage->apOvfl[] and make it point to the cell content (either
  65133. ** in pTemp or the original pCell) and also record its index.
  65134. ** Allocating a new entry in pPage->aCell[] implies that
  65135. ** pPage->nOverflow is incremented.
  65136. **
  65137. ** *pRC must be SQLITE_OK when this routine is called.
  65138. */
  65139. static void insertCell(
  65140. MemPage *pPage, /* Page into which we are copying */
  65141. int i, /* New cell becomes the i-th cell of the page */
  65142. u8 *pCell, /* Content of the new cell */
  65143. int sz, /* Bytes of content in pCell */
  65144. u8 *pTemp, /* Temp storage space for pCell, if needed */
  65145. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  65146. int *pRC /* Read and write return code from here */
  65147. ){
  65148. int idx = 0; /* Where to write new cell content in data[] */
  65149. int j; /* Loop counter */
  65150. u8 *data; /* The content of the whole page */
  65151. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  65152. assert( *pRC==SQLITE_OK );
  65153. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  65154. assert( MX_CELL(pPage->pBt)<=10921 );
  65155. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  65156. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  65157. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  65158. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65159. /* The cell should normally be sized correctly. However, when moving a
  65160. ** malformed cell from a leaf page to an interior page, if the cell size
  65161. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  65162. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  65163. ** the term after the || in the following assert(). */
  65164. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  65165. if( pPage->nOverflow || sz+2>pPage->nFree ){
  65166. if( pTemp ){
  65167. memcpy(pTemp, pCell, sz);
  65168. pCell = pTemp;
  65169. }
  65170. if( iChild ){
  65171. put4byte(pCell, iChild);
  65172. }
  65173. j = pPage->nOverflow++;
  65174. /* Comparison against ArraySize-1 since we hold back one extra slot
  65175. ** as a contingency. In other words, never need more than 3 overflow
  65176. ** slots but 4 are allocated, just to be safe. */
  65177. assert( j < ArraySize(pPage->apOvfl)-1 );
  65178. pPage->apOvfl[j] = pCell;
  65179. pPage->aiOvfl[j] = (u16)i;
  65180. /* When multiple overflows occur, they are always sequential and in
  65181. ** sorted order. This invariants arise because multiple overflows can
  65182. ** only occur when inserting divider cells into the parent page during
  65183. ** balancing, and the dividers are adjacent and sorted.
  65184. */
  65185. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  65186. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  65187. }else{
  65188. int rc = sqlite3PagerWrite(pPage->pDbPage);
  65189. if( rc!=SQLITE_OK ){
  65190. *pRC = rc;
  65191. return;
  65192. }
  65193. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  65194. data = pPage->aData;
  65195. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  65196. rc = allocateSpace(pPage, sz, &idx);
  65197. if( rc ){ *pRC = rc; return; }
  65198. /* The allocateSpace() routine guarantees the following properties
  65199. ** if it returns successfully */
  65200. assert( idx >= 0 );
  65201. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  65202. assert( idx+sz <= (int)pPage->pBt->usableSize );
  65203. pPage->nFree -= (u16)(2 + sz);
  65204. memcpy(&data[idx], pCell, sz);
  65205. if( iChild ){
  65206. put4byte(&data[idx], iChild);
  65207. }
  65208. pIns = pPage->aCellIdx + i*2;
  65209. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  65210. put2byte(pIns, idx);
  65211. pPage->nCell++;
  65212. /* increment the cell count */
  65213. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  65214. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
  65215. #ifndef SQLITE_OMIT_AUTOVACUUM
  65216. if( pPage->pBt->autoVacuum ){
  65217. /* The cell may contain a pointer to an overflow page. If so, write
  65218. ** the entry for the overflow page into the pointer map.
  65219. */
  65220. ptrmapPutOvflPtr(pPage, pCell, pRC);
  65221. }
  65222. #endif
  65223. }
  65224. }
  65225. /*
  65226. ** A CellArray object contains a cache of pointers and sizes for a
  65227. ** consecutive sequence of cells that might be held on multiple pages.
  65228. */
  65229. typedef struct CellArray CellArray;
  65230. struct CellArray {
  65231. int nCell; /* Number of cells in apCell[] */
  65232. MemPage *pRef; /* Reference page */
  65233. u8 **apCell; /* All cells begin balanced */
  65234. u16 *szCell; /* Local size of all cells in apCell[] */
  65235. };
  65236. /*
  65237. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  65238. ** computed.
  65239. */
  65240. static void populateCellCache(CellArray *p, int idx, int N){
  65241. assert( idx>=0 && idx+N<=p->nCell );
  65242. while( N>0 ){
  65243. assert( p->apCell[idx]!=0 );
  65244. if( p->szCell[idx]==0 ){
  65245. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  65246. }else{
  65247. assert( CORRUPT_DB ||
  65248. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  65249. }
  65250. idx++;
  65251. N--;
  65252. }
  65253. }
  65254. /*
  65255. ** Return the size of the Nth element of the cell array
  65256. */
  65257. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  65258. assert( N>=0 && N<p->nCell );
  65259. assert( p->szCell[N]==0 );
  65260. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  65261. return p->szCell[N];
  65262. }
  65263. static u16 cachedCellSize(CellArray *p, int N){
  65264. assert( N>=0 && N<p->nCell );
  65265. if( p->szCell[N] ) return p->szCell[N];
  65266. return computeCellSize(p, N);
  65267. }
  65268. /*
  65269. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  65270. ** szCell[] array contains the size in bytes of each cell. This function
  65271. ** replaces the current contents of page pPg with the contents of the cell
  65272. ** array.
  65273. **
  65274. ** Some of the cells in apCell[] may currently be stored in pPg. This
  65275. ** function works around problems caused by this by making a copy of any
  65276. ** such cells before overwriting the page data.
  65277. **
  65278. ** The MemPage.nFree field is invalidated by this function. It is the
  65279. ** responsibility of the caller to set it correctly.
  65280. */
  65281. static int rebuildPage(
  65282. MemPage *pPg, /* Edit this page */
  65283. int nCell, /* Final number of cells on page */
  65284. u8 **apCell, /* Array of cells */
  65285. u16 *szCell /* Array of cell sizes */
  65286. ){
  65287. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  65288. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  65289. const int usableSize = pPg->pBt->usableSize;
  65290. u8 * const pEnd = &aData[usableSize];
  65291. int i;
  65292. u8 *pCellptr = pPg->aCellIdx;
  65293. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  65294. u8 *pData;
  65295. i = get2byte(&aData[hdr+5]);
  65296. memcpy(&pTmp[i], &aData[i], usableSize - i);
  65297. pData = pEnd;
  65298. for(i=0; i<nCell; i++){
  65299. u8 *pCell = apCell[i];
  65300. if( SQLITE_WITHIN(pCell,aData,pEnd) ){
  65301. pCell = &pTmp[pCell - aData];
  65302. }
  65303. pData -= szCell[i];
  65304. put2byte(pCellptr, (pData - aData));
  65305. pCellptr += 2;
  65306. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  65307. memcpy(pData, pCell, szCell[i]);
  65308. assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  65309. testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
  65310. }
  65311. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  65312. pPg->nCell = nCell;
  65313. pPg->nOverflow = 0;
  65314. put2byte(&aData[hdr+1], 0);
  65315. put2byte(&aData[hdr+3], pPg->nCell);
  65316. put2byte(&aData[hdr+5], pData - aData);
  65317. aData[hdr+7] = 0x00;
  65318. return SQLITE_OK;
  65319. }
  65320. /*
  65321. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  65322. ** contains the size in bytes of each such cell. This function attempts to
  65323. ** add the cells stored in the array to page pPg. If it cannot (because
  65324. ** the page needs to be defragmented before the cells will fit), non-zero
  65325. ** is returned. Otherwise, if the cells are added successfully, zero is
  65326. ** returned.
  65327. **
  65328. ** Argument pCellptr points to the first entry in the cell-pointer array
  65329. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  65330. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  65331. ** cell in the array. It is the responsibility of the caller to ensure
  65332. ** that it is safe to overwrite this part of the cell-pointer array.
  65333. **
  65334. ** When this function is called, *ppData points to the start of the
  65335. ** content area on page pPg. If the size of the content area is extended,
  65336. ** *ppData is updated to point to the new start of the content area
  65337. ** before returning.
  65338. **
  65339. ** Finally, argument pBegin points to the byte immediately following the
  65340. ** end of the space required by this page for the cell-pointer area (for
  65341. ** all cells - not just those inserted by the current call). If the content
  65342. ** area must be extended to before this point in order to accomodate all
  65343. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  65344. */
  65345. static int pageInsertArray(
  65346. MemPage *pPg, /* Page to add cells to */
  65347. u8 *pBegin, /* End of cell-pointer array */
  65348. u8 **ppData, /* IN/OUT: Page content -area pointer */
  65349. u8 *pCellptr, /* Pointer to cell-pointer area */
  65350. int iFirst, /* Index of first cell to add */
  65351. int nCell, /* Number of cells to add to pPg */
  65352. CellArray *pCArray /* Array of cells */
  65353. ){
  65354. int i;
  65355. u8 *aData = pPg->aData;
  65356. u8 *pData = *ppData;
  65357. int iEnd = iFirst + nCell;
  65358. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  65359. for(i=iFirst; i<iEnd; i++){
  65360. int sz, rc;
  65361. u8 *pSlot;
  65362. sz = cachedCellSize(pCArray, i);
  65363. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  65364. if( (pData - pBegin)<sz ) return 1;
  65365. pData -= sz;
  65366. pSlot = pData;
  65367. }
  65368. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  65369. ** database. But they might for a corrupt database. Hence use memmove()
  65370. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  65371. assert( (pSlot+sz)<=pCArray->apCell[i]
  65372. || pSlot>=(pCArray->apCell[i]+sz)
  65373. || CORRUPT_DB );
  65374. memmove(pSlot, pCArray->apCell[i], sz);
  65375. put2byte(pCellptr, (pSlot - aData));
  65376. pCellptr += 2;
  65377. }
  65378. *ppData = pData;
  65379. return 0;
  65380. }
  65381. /*
  65382. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  65383. ** contains the size in bytes of each such cell. This function adds the
  65384. ** space associated with each cell in the array that is currently stored
  65385. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  65386. ** fields of the page are not updated.
  65387. **
  65388. ** This function returns the total number of cells added to the free-list.
  65389. */
  65390. static int pageFreeArray(
  65391. MemPage *pPg, /* Page to edit */
  65392. int iFirst, /* First cell to delete */
  65393. int nCell, /* Cells to delete */
  65394. CellArray *pCArray /* Array of cells */
  65395. ){
  65396. u8 * const aData = pPg->aData;
  65397. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  65398. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  65399. int nRet = 0;
  65400. int i;
  65401. int iEnd = iFirst + nCell;
  65402. u8 *pFree = 0;
  65403. int szFree = 0;
  65404. for(i=iFirst; i<iEnd; i++){
  65405. u8 *pCell = pCArray->apCell[i];
  65406. if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
  65407. int sz;
  65408. /* No need to use cachedCellSize() here. The sizes of all cells that
  65409. ** are to be freed have already been computing while deciding which
  65410. ** cells need freeing */
  65411. sz = pCArray->szCell[i]; assert( sz>0 );
  65412. if( pFree!=(pCell + sz) ){
  65413. if( pFree ){
  65414. assert( pFree>aData && (pFree - aData)<65536 );
  65415. freeSpace(pPg, (u16)(pFree - aData), szFree);
  65416. }
  65417. pFree = pCell;
  65418. szFree = sz;
  65419. if( pFree+sz>pEnd ) return 0;
  65420. }else{
  65421. pFree = pCell;
  65422. szFree += sz;
  65423. }
  65424. nRet++;
  65425. }
  65426. }
  65427. if( pFree ){
  65428. assert( pFree>aData && (pFree - aData)<65536 );
  65429. freeSpace(pPg, (u16)(pFree - aData), szFree);
  65430. }
  65431. return nRet;
  65432. }
  65433. /*
  65434. ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
  65435. ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
  65436. ** with apCell[iOld]. After balancing, this page should hold nNew cells
  65437. ** starting at apCell[iNew].
  65438. **
  65439. ** This routine makes the necessary adjustments to pPg so that it contains
  65440. ** the correct cells after being balanced.
  65441. **
  65442. ** The pPg->nFree field is invalid when this function returns. It is the
  65443. ** responsibility of the caller to set it correctly.
  65444. */
  65445. static int editPage(
  65446. MemPage *pPg, /* Edit this page */
  65447. int iOld, /* Index of first cell currently on page */
  65448. int iNew, /* Index of new first cell on page */
  65449. int nNew, /* Final number of cells on page */
  65450. CellArray *pCArray /* Array of cells and sizes */
  65451. ){
  65452. u8 * const aData = pPg->aData;
  65453. const int hdr = pPg->hdrOffset;
  65454. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  65455. int nCell = pPg->nCell; /* Cells stored on pPg */
  65456. u8 *pData;
  65457. u8 *pCellptr;
  65458. int i;
  65459. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  65460. int iNewEnd = iNew + nNew;
  65461. #ifdef SQLITE_DEBUG
  65462. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  65463. memcpy(pTmp, aData, pPg->pBt->usableSize);
  65464. #endif
  65465. /* Remove cells from the start and end of the page */
  65466. if( iOld<iNew ){
  65467. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  65468. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  65469. nCell -= nShift;
  65470. }
  65471. if( iNewEnd < iOldEnd ){
  65472. nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  65473. }
  65474. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  65475. if( pData<pBegin ) goto editpage_fail;
  65476. /* Add cells to the start of the page */
  65477. if( iNew<iOld ){
  65478. int nAdd = MIN(nNew,iOld-iNew);
  65479. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  65480. pCellptr = pPg->aCellIdx;
  65481. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  65482. if( pageInsertArray(
  65483. pPg, pBegin, &pData, pCellptr,
  65484. iNew, nAdd, pCArray
  65485. ) ) goto editpage_fail;
  65486. nCell += nAdd;
  65487. }
  65488. /* Add any overflow cells */
  65489. for(i=0; i<pPg->nOverflow; i++){
  65490. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  65491. if( iCell>=0 && iCell<nNew ){
  65492. pCellptr = &pPg->aCellIdx[iCell * 2];
  65493. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  65494. nCell++;
  65495. if( pageInsertArray(
  65496. pPg, pBegin, &pData, pCellptr,
  65497. iCell+iNew, 1, pCArray
  65498. ) ) goto editpage_fail;
  65499. }
  65500. }
  65501. /* Append cells to the end of the page */
  65502. pCellptr = &pPg->aCellIdx[nCell*2];
  65503. if( pageInsertArray(
  65504. pPg, pBegin, &pData, pCellptr,
  65505. iNew+nCell, nNew-nCell, pCArray
  65506. ) ) goto editpage_fail;
  65507. pPg->nCell = nNew;
  65508. pPg->nOverflow = 0;
  65509. put2byte(&aData[hdr+3], pPg->nCell);
  65510. put2byte(&aData[hdr+5], pData - aData);
  65511. #ifdef SQLITE_DEBUG
  65512. for(i=0; i<nNew && !CORRUPT_DB; i++){
  65513. u8 *pCell = pCArray->apCell[i+iNew];
  65514. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  65515. if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
  65516. pCell = &pTmp[pCell - aData];
  65517. }
  65518. assert( 0==memcmp(pCell, &aData[iOff],
  65519. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  65520. }
  65521. #endif
  65522. return SQLITE_OK;
  65523. editpage_fail:
  65524. /* Unable to edit this page. Rebuild it from scratch instead. */
  65525. populateCellCache(pCArray, iNew, nNew);
  65526. return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
  65527. }
  65528. /*
  65529. ** The following parameters determine how many adjacent pages get involved
  65530. ** in a balancing operation. NN is the number of neighbors on either side
  65531. ** of the page that participate in the balancing operation. NB is the
  65532. ** total number of pages that participate, including the target page and
  65533. ** NN neighbors on either side.
  65534. **
  65535. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  65536. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  65537. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  65538. ** The value of NN appears to give the best results overall.
  65539. */
  65540. #define NN 1 /* Number of neighbors on either side of pPage */
  65541. #define NB (NN*2+1) /* Total pages involved in the balance */
  65542. #ifndef SQLITE_OMIT_QUICKBALANCE
  65543. /*
  65544. ** This version of balance() handles the common special case where
  65545. ** a new entry is being inserted on the extreme right-end of the
  65546. ** tree, in other words, when the new entry will become the largest
  65547. ** entry in the tree.
  65548. **
  65549. ** Instead of trying to balance the 3 right-most leaf pages, just add
  65550. ** a new page to the right-hand side and put the one new entry in
  65551. ** that page. This leaves the right side of the tree somewhat
  65552. ** unbalanced. But odds are that we will be inserting new entries
  65553. ** at the end soon afterwards so the nearly empty page will quickly
  65554. ** fill up. On average.
  65555. **
  65556. ** pPage is the leaf page which is the right-most page in the tree.
  65557. ** pParent is its parent. pPage must have a single overflow entry
  65558. ** which is also the right-most entry on the page.
  65559. **
  65560. ** The pSpace buffer is used to store a temporary copy of the divider
  65561. ** cell that will be inserted into pParent. Such a cell consists of a 4
  65562. ** byte page number followed by a variable length integer. In other
  65563. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  65564. ** least 13 bytes in size.
  65565. */
  65566. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  65567. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  65568. MemPage *pNew; /* Newly allocated page */
  65569. int rc; /* Return Code */
  65570. Pgno pgnoNew; /* Page number of pNew */
  65571. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65572. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  65573. assert( pPage->nOverflow==1 );
  65574. /* This error condition is now caught prior to reaching this function */
  65575. if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
  65576. /* Allocate a new page. This page will become the right-sibling of
  65577. ** pPage. Make the parent page writable, so that the new divider cell
  65578. ** may be inserted. If both these operations are successful, proceed.
  65579. */
  65580. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  65581. if( rc==SQLITE_OK ){
  65582. u8 *pOut = &pSpace[4];
  65583. u8 *pCell = pPage->apOvfl[0];
  65584. u16 szCell = pPage->xCellSize(pPage, pCell);
  65585. u8 *pStop;
  65586. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  65587. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  65588. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  65589. rc = rebuildPage(pNew, 1, &pCell, &szCell);
  65590. if( NEVER(rc) ) return rc;
  65591. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  65592. /* If this is an auto-vacuum database, update the pointer map
  65593. ** with entries for the new page, and any pointer from the
  65594. ** cell on the page to an overflow page. If either of these
  65595. ** operations fails, the return code is set, but the contents
  65596. ** of the parent page are still manipulated by thh code below.
  65597. ** That is Ok, at this point the parent page is guaranteed to
  65598. ** be marked as dirty. Returning an error code will cause a
  65599. ** rollback, undoing any changes made to the parent page.
  65600. */
  65601. if( ISAUTOVACUUM ){
  65602. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  65603. if( szCell>pNew->minLocal ){
  65604. ptrmapPutOvflPtr(pNew, pCell, &rc);
  65605. }
  65606. }
  65607. /* Create a divider cell to insert into pParent. The divider cell
  65608. ** consists of a 4-byte page number (the page number of pPage) and
  65609. ** a variable length key value (which must be the same value as the
  65610. ** largest key on pPage).
  65611. **
  65612. ** To find the largest key value on pPage, first find the right-most
  65613. ** cell on pPage. The first two fields of this cell are the
  65614. ** record-length (a variable length integer at most 32-bits in size)
  65615. ** and the key value (a variable length integer, may have any value).
  65616. ** The first of the while(...) loops below skips over the record-length
  65617. ** field. The second while(...) loop copies the key value from the
  65618. ** cell on pPage into the pSpace buffer.
  65619. */
  65620. pCell = findCell(pPage, pPage->nCell-1);
  65621. pStop = &pCell[9];
  65622. while( (*(pCell++)&0x80) && pCell<pStop );
  65623. pStop = &pCell[9];
  65624. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  65625. /* Insert the new divider cell into pParent. */
  65626. if( rc==SQLITE_OK ){
  65627. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  65628. 0, pPage->pgno, &rc);
  65629. }
  65630. /* Set the right-child pointer of pParent to point to the new page. */
  65631. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  65632. /* Release the reference to the new page. */
  65633. releasePage(pNew);
  65634. }
  65635. return rc;
  65636. }
  65637. #endif /* SQLITE_OMIT_QUICKBALANCE */
  65638. #if 0
  65639. /*
  65640. ** This function does not contribute anything to the operation of SQLite.
  65641. ** it is sometimes activated temporarily while debugging code responsible
  65642. ** for setting pointer-map entries.
  65643. */
  65644. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  65645. int i, j;
  65646. for(i=0; i<nPage; i++){
  65647. Pgno n;
  65648. u8 e;
  65649. MemPage *pPage = apPage[i];
  65650. BtShared *pBt = pPage->pBt;
  65651. assert( pPage->isInit );
  65652. for(j=0; j<pPage->nCell; j++){
  65653. CellInfo info;
  65654. u8 *z;
  65655. z = findCell(pPage, j);
  65656. pPage->xParseCell(pPage, z, &info);
  65657. if( info.nLocal<info.nPayload ){
  65658. Pgno ovfl = get4byte(&z[info.nSize-4]);
  65659. ptrmapGet(pBt, ovfl, &e, &n);
  65660. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  65661. }
  65662. if( !pPage->leaf ){
  65663. Pgno child = get4byte(z);
  65664. ptrmapGet(pBt, child, &e, &n);
  65665. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  65666. }
  65667. }
  65668. if( !pPage->leaf ){
  65669. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  65670. ptrmapGet(pBt, child, &e, &n);
  65671. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  65672. }
  65673. }
  65674. return 1;
  65675. }
  65676. #endif
  65677. /*
  65678. ** This function is used to copy the contents of the b-tree node stored
  65679. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  65680. ** the pointer-map entries for each child page are updated so that the
  65681. ** parent page stored in the pointer map is page pTo. If pFrom contained
  65682. ** any cells with overflow page pointers, then the corresponding pointer
  65683. ** map entries are also updated so that the parent page is page pTo.
  65684. **
  65685. ** If pFrom is currently carrying any overflow cells (entries in the
  65686. ** MemPage.apOvfl[] array), they are not copied to pTo.
  65687. **
  65688. ** Before returning, page pTo is reinitialized using btreeInitPage().
  65689. **
  65690. ** The performance of this function is not critical. It is only used by
  65691. ** the balance_shallower() and balance_deeper() procedures, neither of
  65692. ** which are called often under normal circumstances.
  65693. */
  65694. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  65695. if( (*pRC)==SQLITE_OK ){
  65696. BtShared * const pBt = pFrom->pBt;
  65697. u8 * const aFrom = pFrom->aData;
  65698. u8 * const aTo = pTo->aData;
  65699. int const iFromHdr = pFrom->hdrOffset;
  65700. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  65701. int rc;
  65702. int iData;
  65703. assert( pFrom->isInit );
  65704. assert( pFrom->nFree>=iToHdr );
  65705. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  65706. /* Copy the b-tree node content from page pFrom to page pTo. */
  65707. iData = get2byte(&aFrom[iFromHdr+5]);
  65708. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  65709. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  65710. /* Reinitialize page pTo so that the contents of the MemPage structure
  65711. ** match the new data. The initialization of pTo can actually fail under
  65712. ** fairly obscure circumstances, even though it is a copy of initialized
  65713. ** page pFrom.
  65714. */
  65715. pTo->isInit = 0;
  65716. rc = btreeInitPage(pTo);
  65717. if( rc!=SQLITE_OK ){
  65718. *pRC = rc;
  65719. return;
  65720. }
  65721. /* If this is an auto-vacuum database, update the pointer-map entries
  65722. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  65723. */
  65724. if( ISAUTOVACUUM ){
  65725. *pRC = setChildPtrmaps(pTo);
  65726. }
  65727. }
  65728. }
  65729. /*
  65730. ** This routine redistributes cells on the iParentIdx'th child of pParent
  65731. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  65732. ** same amount of free space. Usually a single sibling on either side of the
  65733. ** page are used in the balancing, though both siblings might come from one
  65734. ** side if the page is the first or last child of its parent. If the page
  65735. ** has fewer than 2 siblings (something which can only happen if the page
  65736. ** is a root page or a child of a root page) then all available siblings
  65737. ** participate in the balancing.
  65738. **
  65739. ** The number of siblings of the page might be increased or decreased by
  65740. ** one or two in an effort to keep pages nearly full but not over full.
  65741. **
  65742. ** Note that when this routine is called, some of the cells on the page
  65743. ** might not actually be stored in MemPage.aData[]. This can happen
  65744. ** if the page is overfull. This routine ensures that all cells allocated
  65745. ** to the page and its siblings fit into MemPage.aData[] before returning.
  65746. **
  65747. ** In the course of balancing the page and its siblings, cells may be
  65748. ** inserted into or removed from the parent page (pParent). Doing so
  65749. ** may cause the parent page to become overfull or underfull. If this
  65750. ** happens, it is the responsibility of the caller to invoke the correct
  65751. ** balancing routine to fix this problem (see the balance() routine).
  65752. **
  65753. ** If this routine fails for any reason, it might leave the database
  65754. ** in a corrupted state. So if this routine fails, the database should
  65755. ** be rolled back.
  65756. **
  65757. ** The third argument to this function, aOvflSpace, is a pointer to a
  65758. ** buffer big enough to hold one page. If while inserting cells into the parent
  65759. ** page (pParent) the parent page becomes overfull, this buffer is
  65760. ** used to store the parent's overflow cells. Because this function inserts
  65761. ** a maximum of four divider cells into the parent page, and the maximum
  65762. ** size of a cell stored within an internal node is always less than 1/4
  65763. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  65764. ** enough for all overflow cells.
  65765. **
  65766. ** If aOvflSpace is set to a null pointer, this function returns
  65767. ** SQLITE_NOMEM.
  65768. */
  65769. static int balance_nonroot(
  65770. MemPage *pParent, /* Parent page of siblings being balanced */
  65771. int iParentIdx, /* Index of "the page" in pParent */
  65772. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  65773. int isRoot, /* True if pParent is a root-page */
  65774. int bBulk /* True if this call is part of a bulk load */
  65775. ){
  65776. BtShared *pBt; /* The whole database */
  65777. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  65778. int nNew = 0; /* Number of pages in apNew[] */
  65779. int nOld; /* Number of pages in apOld[] */
  65780. int i, j, k; /* Loop counters */
  65781. int nxDiv; /* Next divider slot in pParent->aCell[] */
  65782. int rc = SQLITE_OK; /* The return code */
  65783. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  65784. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  65785. int usableSpace; /* Bytes in pPage beyond the header */
  65786. int pageFlags; /* Value of pPage->aData[0] */
  65787. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  65788. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  65789. int szScratch; /* Size of scratch memory requested */
  65790. MemPage *apOld[NB]; /* pPage and up to two siblings */
  65791. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  65792. u8 *pRight; /* Location in parent of right-sibling pointer */
  65793. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  65794. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  65795. int cntOld[NB+2]; /* Old index in b.apCell[] */
  65796. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  65797. u8 *aSpace1; /* Space for copies of dividers cells */
  65798. Pgno pgno; /* Temp var to store a page number in */
  65799. u8 abDone[NB+2]; /* True after i'th new page is populated */
  65800. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  65801. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  65802. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  65803. CellArray b; /* Parsed information on cells being balanced */
  65804. memset(abDone, 0, sizeof(abDone));
  65805. b.nCell = 0;
  65806. b.apCell = 0;
  65807. pBt = pParent->pBt;
  65808. assert( sqlite3_mutex_held(pBt->mutex) );
  65809. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  65810. #if 0
  65811. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  65812. #endif
  65813. /* At this point pParent may have at most one overflow cell. And if
  65814. ** this overflow cell is present, it must be the cell with
  65815. ** index iParentIdx. This scenario comes about when this function
  65816. ** is called (indirectly) from sqlite3BtreeDelete().
  65817. */
  65818. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  65819. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  65820. if( !aOvflSpace ){
  65821. return SQLITE_NOMEM_BKPT;
  65822. }
  65823. /* Find the sibling pages to balance. Also locate the cells in pParent
  65824. ** that divide the siblings. An attempt is made to find NN siblings on
  65825. ** either side of pPage. More siblings are taken from one side, however,
  65826. ** if there are fewer than NN siblings on the other side. If pParent
  65827. ** has NB or fewer children then all children of pParent are taken.
  65828. **
  65829. ** This loop also drops the divider cells from the parent page. This
  65830. ** way, the remainder of the function does not have to deal with any
  65831. ** overflow cells in the parent page, since if any existed they will
  65832. ** have already been removed.
  65833. */
  65834. i = pParent->nOverflow + pParent->nCell;
  65835. if( i<2 ){
  65836. nxDiv = 0;
  65837. }else{
  65838. assert( bBulk==0 || bBulk==1 );
  65839. if( iParentIdx==0 ){
  65840. nxDiv = 0;
  65841. }else if( iParentIdx==i ){
  65842. nxDiv = i-2+bBulk;
  65843. }else{
  65844. nxDiv = iParentIdx-1;
  65845. }
  65846. i = 2-bBulk;
  65847. }
  65848. nOld = i+1;
  65849. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  65850. pRight = &pParent->aData[pParent->hdrOffset+8];
  65851. }else{
  65852. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  65853. }
  65854. pgno = get4byte(pRight);
  65855. while( 1 ){
  65856. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  65857. if( rc ){
  65858. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  65859. goto balance_cleanup;
  65860. }
  65861. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  65862. if( (i--)==0 ) break;
  65863. if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
  65864. apDiv[i] = pParent->apOvfl[0];
  65865. pgno = get4byte(apDiv[i]);
  65866. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  65867. pParent->nOverflow = 0;
  65868. }else{
  65869. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  65870. pgno = get4byte(apDiv[i]);
  65871. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  65872. /* Drop the cell from the parent page. apDiv[i] still points to
  65873. ** the cell within the parent, even though it has been dropped.
  65874. ** This is safe because dropping a cell only overwrites the first
  65875. ** four bytes of it, and this function does not need the first
  65876. ** four bytes of the divider cell. So the pointer is safe to use
  65877. ** later on.
  65878. **
  65879. ** But not if we are in secure-delete mode. In secure-delete mode,
  65880. ** the dropCell() routine will overwrite the entire cell with zeroes.
  65881. ** In this case, temporarily copy the cell into the aOvflSpace[]
  65882. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  65883. ** is allocated. */
  65884. if( pBt->btsFlags & BTS_FAST_SECURE ){
  65885. int iOff;
  65886. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  65887. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  65888. rc = SQLITE_CORRUPT_BKPT;
  65889. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  65890. goto balance_cleanup;
  65891. }else{
  65892. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  65893. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  65894. }
  65895. }
  65896. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  65897. }
  65898. }
  65899. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  65900. ** alignment */
  65901. nMaxCells = (nMaxCells + 3)&~3;
  65902. /*
  65903. ** Allocate space for memory structures
  65904. */
  65905. szScratch =
  65906. nMaxCells*sizeof(u8*) /* b.apCell */
  65907. + nMaxCells*sizeof(u16) /* b.szCell */
  65908. + pBt->pageSize; /* aSpace1 */
  65909. assert( szScratch<=6*(int)pBt->pageSize );
  65910. b.apCell = sqlite3StackAllocRaw(0, szScratch );
  65911. if( b.apCell==0 ){
  65912. rc = SQLITE_NOMEM_BKPT;
  65913. goto balance_cleanup;
  65914. }
  65915. b.szCell = (u16*)&b.apCell[nMaxCells];
  65916. aSpace1 = (u8*)&b.szCell[nMaxCells];
  65917. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  65918. /*
  65919. ** Load pointers to all cells on sibling pages and the divider cells
  65920. ** into the local b.apCell[] array. Make copies of the divider cells
  65921. ** into space obtained from aSpace1[]. The divider cells have already
  65922. ** been removed from pParent.
  65923. **
  65924. ** If the siblings are on leaf pages, then the child pointers of the
  65925. ** divider cells are stripped from the cells before they are copied
  65926. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  65927. ** child pointers. If siblings are not leaves, then all cell in
  65928. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  65929. ** are alike.
  65930. **
  65931. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  65932. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  65933. */
  65934. b.pRef = apOld[0];
  65935. leafCorrection = b.pRef->leaf*4;
  65936. leafData = b.pRef->intKeyLeaf;
  65937. for(i=0; i<nOld; i++){
  65938. MemPage *pOld = apOld[i];
  65939. int limit = pOld->nCell;
  65940. u8 *aData = pOld->aData;
  65941. u16 maskPage = pOld->maskPage;
  65942. u8 *piCell = aData + pOld->cellOffset;
  65943. u8 *piEnd;
  65944. /* Verify that all sibling pages are of the same "type" (table-leaf,
  65945. ** table-interior, index-leaf, or index-interior).
  65946. */
  65947. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  65948. rc = SQLITE_CORRUPT_BKPT;
  65949. goto balance_cleanup;
  65950. }
  65951. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  65952. ** contains overflow cells, include them in the b.apCell[] array
  65953. ** in the correct spot.
  65954. **
  65955. ** Note that when there are multiple overflow cells, it is always the
  65956. ** case that they are sequential and adjacent. This invariant arises
  65957. ** because multiple overflows can only occurs when inserting divider
  65958. ** cells into a parent on a prior balance, and divider cells are always
  65959. ** adjacent and are inserted in order. There is an assert() tagged
  65960. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  65961. ** invariant.
  65962. **
  65963. ** This must be done in advance. Once the balance starts, the cell
  65964. ** offset section of the btree page will be overwritten and we will no
  65965. ** long be able to find the cells if a pointer to each cell is not saved
  65966. ** first.
  65967. */
  65968. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
  65969. if( pOld->nOverflow>0 ){
  65970. limit = pOld->aiOvfl[0];
  65971. for(j=0; j<limit; j++){
  65972. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  65973. piCell += 2;
  65974. b.nCell++;
  65975. }
  65976. for(k=0; k<pOld->nOverflow; k++){
  65977. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  65978. b.apCell[b.nCell] = pOld->apOvfl[k];
  65979. b.nCell++;
  65980. }
  65981. }
  65982. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  65983. while( piCell<piEnd ){
  65984. assert( b.nCell<nMaxCells );
  65985. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  65986. piCell += 2;
  65987. b.nCell++;
  65988. }
  65989. cntOld[i] = b.nCell;
  65990. if( i<nOld-1 && !leafData){
  65991. u16 sz = (u16)szNew[i];
  65992. u8 *pTemp;
  65993. assert( b.nCell<nMaxCells );
  65994. b.szCell[b.nCell] = sz;
  65995. pTemp = &aSpace1[iSpace1];
  65996. iSpace1 += sz;
  65997. assert( sz<=pBt->maxLocal+23 );
  65998. assert( iSpace1 <= (int)pBt->pageSize );
  65999. memcpy(pTemp, apDiv[i], sz);
  66000. b.apCell[b.nCell] = pTemp+leafCorrection;
  66001. assert( leafCorrection==0 || leafCorrection==4 );
  66002. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  66003. if( !pOld->leaf ){
  66004. assert( leafCorrection==0 );
  66005. assert( pOld->hdrOffset==0 );
  66006. /* The right pointer of the child page pOld becomes the left
  66007. ** pointer of the divider cell */
  66008. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  66009. }else{
  66010. assert( leafCorrection==4 );
  66011. while( b.szCell[b.nCell]<4 ){
  66012. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  66013. ** does exist, pad it with 0x00 bytes. */
  66014. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  66015. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  66016. aSpace1[iSpace1++] = 0x00;
  66017. b.szCell[b.nCell]++;
  66018. }
  66019. }
  66020. b.nCell++;
  66021. }
  66022. }
  66023. /*
  66024. ** Figure out the number of pages needed to hold all b.nCell cells.
  66025. ** Store this number in "k". Also compute szNew[] which is the total
  66026. ** size of all cells on the i-th page and cntNew[] which is the index
  66027. ** in b.apCell[] of the cell that divides page i from page i+1.
  66028. ** cntNew[k] should equal b.nCell.
  66029. **
  66030. ** Values computed by this block:
  66031. **
  66032. ** k: The total number of sibling pages
  66033. ** szNew[i]: Spaced used on the i-th sibling page.
  66034. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  66035. ** the right of the i-th sibling page.
  66036. ** usableSpace: Number of bytes of space available on each sibling.
  66037. **
  66038. */
  66039. usableSpace = pBt->usableSize - 12 + leafCorrection;
  66040. for(i=0; i<nOld; i++){
  66041. MemPage *p = apOld[i];
  66042. szNew[i] = usableSpace - p->nFree;
  66043. for(j=0; j<p->nOverflow; j++){
  66044. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  66045. }
  66046. cntNew[i] = cntOld[i];
  66047. }
  66048. k = nOld;
  66049. for(i=0; i<k; i++){
  66050. int sz;
  66051. while( szNew[i]>usableSpace ){
  66052. if( i+1>=k ){
  66053. k = i+2;
  66054. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  66055. szNew[k-1] = 0;
  66056. cntNew[k-1] = b.nCell;
  66057. }
  66058. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  66059. szNew[i] -= sz;
  66060. if( !leafData ){
  66061. if( cntNew[i]<b.nCell ){
  66062. sz = 2 + cachedCellSize(&b, cntNew[i]);
  66063. }else{
  66064. sz = 0;
  66065. }
  66066. }
  66067. szNew[i+1] += sz;
  66068. cntNew[i]--;
  66069. }
  66070. while( cntNew[i]<b.nCell ){
  66071. sz = 2 + cachedCellSize(&b, cntNew[i]);
  66072. if( szNew[i]+sz>usableSpace ) break;
  66073. szNew[i] += sz;
  66074. cntNew[i]++;
  66075. if( !leafData ){
  66076. if( cntNew[i]<b.nCell ){
  66077. sz = 2 + cachedCellSize(&b, cntNew[i]);
  66078. }else{
  66079. sz = 0;
  66080. }
  66081. }
  66082. szNew[i+1] -= sz;
  66083. }
  66084. if( cntNew[i]>=b.nCell ){
  66085. k = i+1;
  66086. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  66087. rc = SQLITE_CORRUPT_BKPT;
  66088. goto balance_cleanup;
  66089. }
  66090. }
  66091. /*
  66092. ** The packing computed by the previous block is biased toward the siblings
  66093. ** on the left side (siblings with smaller keys). The left siblings are
  66094. ** always nearly full, while the right-most sibling might be nearly empty.
  66095. ** The next block of code attempts to adjust the packing of siblings to
  66096. ** get a better balance.
  66097. **
  66098. ** This adjustment is more than an optimization. The packing above might
  66099. ** be so out of balance as to be illegal. For example, the right-most
  66100. ** sibling might be completely empty. This adjustment is not optional.
  66101. */
  66102. for(i=k-1; i>0; i--){
  66103. int szRight = szNew[i]; /* Size of sibling on the right */
  66104. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  66105. int r; /* Index of right-most cell in left sibling */
  66106. int d; /* Index of first cell to the left of right sibling */
  66107. r = cntNew[i-1] - 1;
  66108. d = r + 1 - leafData;
  66109. (void)cachedCellSize(&b, d);
  66110. do{
  66111. assert( d<nMaxCells );
  66112. assert( r<nMaxCells );
  66113. (void)cachedCellSize(&b, r);
  66114. if( szRight!=0
  66115. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
  66116. break;
  66117. }
  66118. szRight += b.szCell[d] + 2;
  66119. szLeft -= b.szCell[r] + 2;
  66120. cntNew[i-1] = r;
  66121. r--;
  66122. d--;
  66123. }while( r>=0 );
  66124. szNew[i] = szRight;
  66125. szNew[i-1] = szLeft;
  66126. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  66127. rc = SQLITE_CORRUPT_BKPT;
  66128. goto balance_cleanup;
  66129. }
  66130. }
  66131. /* Sanity check: For a non-corrupt database file one of the follwing
  66132. ** must be true:
  66133. ** (1) We found one or more cells (cntNew[0])>0), or
  66134. ** (2) pPage is a virtual root page. A virtual root page is when
  66135. ** the real root page is page 1 and we are the only child of
  66136. ** that page.
  66137. */
  66138. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  66139. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  66140. apOld[0]->pgno, apOld[0]->nCell,
  66141. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  66142. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  66143. ));
  66144. /*
  66145. ** Allocate k new pages. Reuse old pages where possible.
  66146. */
  66147. pageFlags = apOld[0]->aData[0];
  66148. for(i=0; i<k; i++){
  66149. MemPage *pNew;
  66150. if( i<nOld ){
  66151. pNew = apNew[i] = apOld[i];
  66152. apOld[i] = 0;
  66153. rc = sqlite3PagerWrite(pNew->pDbPage);
  66154. nNew++;
  66155. if( rc ) goto balance_cleanup;
  66156. }else{
  66157. assert( i>0 );
  66158. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  66159. if( rc ) goto balance_cleanup;
  66160. zeroPage(pNew, pageFlags);
  66161. apNew[i] = pNew;
  66162. nNew++;
  66163. cntOld[i] = b.nCell;
  66164. /* Set the pointer-map entry for the new sibling page. */
  66165. if( ISAUTOVACUUM ){
  66166. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  66167. if( rc!=SQLITE_OK ){
  66168. goto balance_cleanup;
  66169. }
  66170. }
  66171. }
  66172. }
  66173. /*
  66174. ** Reassign page numbers so that the new pages are in ascending order.
  66175. ** This helps to keep entries in the disk file in order so that a scan
  66176. ** of the table is closer to a linear scan through the file. That in turn
  66177. ** helps the operating system to deliver pages from the disk more rapidly.
  66178. **
  66179. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  66180. ** than (NB+2) (a small constant), that should not be a problem.
  66181. **
  66182. ** When NB==3, this one optimization makes the database about 25% faster
  66183. ** for large insertions and deletions.
  66184. */
  66185. for(i=0; i<nNew; i++){
  66186. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  66187. aPgFlags[i] = apNew[i]->pDbPage->flags;
  66188. for(j=0; j<i; j++){
  66189. if( aPgno[j]==aPgno[i] ){
  66190. /* This branch is taken if the set of sibling pages somehow contains
  66191. ** duplicate entries. This can happen if the database is corrupt.
  66192. ** It would be simpler to detect this as part of the loop below, but
  66193. ** we do the detection here in order to avoid populating the pager
  66194. ** cache with two separate objects associated with the same
  66195. ** page number. */
  66196. assert( CORRUPT_DB );
  66197. rc = SQLITE_CORRUPT_BKPT;
  66198. goto balance_cleanup;
  66199. }
  66200. }
  66201. }
  66202. for(i=0; i<nNew; i++){
  66203. int iBest = 0; /* aPgno[] index of page number to use */
  66204. for(j=1; j<nNew; j++){
  66205. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  66206. }
  66207. pgno = aPgOrder[iBest];
  66208. aPgOrder[iBest] = 0xffffffff;
  66209. if( iBest!=i ){
  66210. if( iBest>i ){
  66211. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  66212. }
  66213. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  66214. apNew[i]->pgno = pgno;
  66215. }
  66216. }
  66217. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  66218. "%d(%d nc=%d) %d(%d nc=%d)\n",
  66219. apNew[0]->pgno, szNew[0], cntNew[0],
  66220. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  66221. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  66222. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  66223. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  66224. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  66225. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  66226. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  66227. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  66228. ));
  66229. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  66230. put4byte(pRight, apNew[nNew-1]->pgno);
  66231. /* If the sibling pages are not leaves, ensure that the right-child pointer
  66232. ** of the right-most new sibling page is set to the value that was
  66233. ** originally in the same field of the right-most old sibling page. */
  66234. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  66235. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  66236. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  66237. }
  66238. /* Make any required updates to pointer map entries associated with
  66239. ** cells stored on sibling pages following the balance operation. Pointer
  66240. ** map entries associated with divider cells are set by the insertCell()
  66241. ** routine. The associated pointer map entries are:
  66242. **
  66243. ** a) if the cell contains a reference to an overflow chain, the
  66244. ** entry associated with the first page in the overflow chain, and
  66245. **
  66246. ** b) if the sibling pages are not leaves, the child page associated
  66247. ** with the cell.
  66248. **
  66249. ** If the sibling pages are not leaves, then the pointer map entry
  66250. ** associated with the right-child of each sibling may also need to be
  66251. ** updated. This happens below, after the sibling pages have been
  66252. ** populated, not here.
  66253. */
  66254. if( ISAUTOVACUUM ){
  66255. MemPage *pNew = apNew[0];
  66256. u8 *aOld = pNew->aData;
  66257. int cntOldNext = pNew->nCell + pNew->nOverflow;
  66258. int usableSize = pBt->usableSize;
  66259. int iNew = 0;
  66260. int iOld = 0;
  66261. for(i=0; i<b.nCell; i++){
  66262. u8 *pCell = b.apCell[i];
  66263. if( i==cntOldNext ){
  66264. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  66265. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  66266. aOld = pOld->aData;
  66267. }
  66268. if( i==cntNew[iNew] ){
  66269. pNew = apNew[++iNew];
  66270. if( !leafData ) continue;
  66271. }
  66272. /* Cell pCell is destined for new sibling page pNew. Originally, it
  66273. ** was either part of sibling page iOld (possibly an overflow cell),
  66274. ** or else the divider cell to the left of sibling page iOld. So,
  66275. ** if sibling page iOld had the same page number as pNew, and if
  66276. ** pCell really was a part of sibling page iOld (not a divider or
  66277. ** overflow cell), we can skip updating the pointer map entries. */
  66278. if( iOld>=nNew
  66279. || pNew->pgno!=aPgno[iOld]
  66280. || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
  66281. ){
  66282. if( !leafCorrection ){
  66283. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  66284. }
  66285. if( cachedCellSize(&b,i)>pNew->minLocal ){
  66286. ptrmapPutOvflPtr(pNew, pCell, &rc);
  66287. }
  66288. if( rc ) goto balance_cleanup;
  66289. }
  66290. }
  66291. }
  66292. /* Insert new divider cells into pParent. */
  66293. for(i=0; i<nNew-1; i++){
  66294. u8 *pCell;
  66295. u8 *pTemp;
  66296. int sz;
  66297. MemPage *pNew = apNew[i];
  66298. j = cntNew[i];
  66299. assert( j<nMaxCells );
  66300. assert( b.apCell[j]!=0 );
  66301. pCell = b.apCell[j];
  66302. sz = b.szCell[j] + leafCorrection;
  66303. pTemp = &aOvflSpace[iOvflSpace];
  66304. if( !pNew->leaf ){
  66305. memcpy(&pNew->aData[8], pCell, 4);
  66306. }else if( leafData ){
  66307. /* If the tree is a leaf-data tree, and the siblings are leaves,
  66308. ** then there is no divider cell in b.apCell[]. Instead, the divider
  66309. ** cell consists of the integer key for the right-most cell of
  66310. ** the sibling-page assembled above only.
  66311. */
  66312. CellInfo info;
  66313. j--;
  66314. pNew->xParseCell(pNew, b.apCell[j], &info);
  66315. pCell = pTemp;
  66316. sz = 4 + putVarint(&pCell[4], info.nKey);
  66317. pTemp = 0;
  66318. }else{
  66319. pCell -= 4;
  66320. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  66321. ** previously stored on a leaf node, and its reported size was 4
  66322. ** bytes, then it may actually be smaller than this
  66323. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  66324. ** any cell). But it is important to pass the correct size to
  66325. ** insertCell(), so reparse the cell now.
  66326. **
  66327. ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
  66328. ** and WITHOUT ROWID tables with exactly one column which is the
  66329. ** primary key.
  66330. */
  66331. if( b.szCell[j]==4 ){
  66332. assert(leafCorrection==4);
  66333. sz = pParent->xCellSize(pParent, pCell);
  66334. }
  66335. }
  66336. iOvflSpace += sz;
  66337. assert( sz<=pBt->maxLocal+23 );
  66338. assert( iOvflSpace <= (int)pBt->pageSize );
  66339. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  66340. if( rc!=SQLITE_OK ) goto balance_cleanup;
  66341. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  66342. }
  66343. /* Now update the actual sibling pages. The order in which they are updated
  66344. ** is important, as this code needs to avoid disrupting any page from which
  66345. ** cells may still to be read. In practice, this means:
  66346. **
  66347. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  66348. ** then it is not safe to update page apNew[iPg] until after
  66349. ** the left-hand sibling apNew[iPg-1] has been updated.
  66350. **
  66351. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  66352. ** then it is not safe to update page apNew[iPg] until after
  66353. ** the right-hand sibling apNew[iPg+1] has been updated.
  66354. **
  66355. ** If neither of the above apply, the page is safe to update.
  66356. **
  66357. ** The iPg value in the following loop starts at nNew-1 goes down
  66358. ** to 0, then back up to nNew-1 again, thus making two passes over
  66359. ** the pages. On the initial downward pass, only condition (1) above
  66360. ** needs to be tested because (2) will always be true from the previous
  66361. ** step. On the upward pass, both conditions are always true, so the
  66362. ** upwards pass simply processes pages that were missed on the downward
  66363. ** pass.
  66364. */
  66365. for(i=1-nNew; i<nNew; i++){
  66366. int iPg = i<0 ? -i : i;
  66367. assert( iPg>=0 && iPg<nNew );
  66368. if( abDone[iPg] ) continue; /* Skip pages already processed */
  66369. if( i>=0 /* On the upwards pass, or... */
  66370. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  66371. ){
  66372. int iNew;
  66373. int iOld;
  66374. int nNewCell;
  66375. /* Verify condition (1): If cells are moving left, update iPg
  66376. ** only after iPg-1 has already been updated. */
  66377. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  66378. /* Verify condition (2): If cells are moving right, update iPg
  66379. ** only after iPg+1 has already been updated. */
  66380. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  66381. if( iPg==0 ){
  66382. iNew = iOld = 0;
  66383. nNewCell = cntNew[0];
  66384. }else{
  66385. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  66386. iNew = cntNew[iPg-1] + !leafData;
  66387. nNewCell = cntNew[iPg] - iNew;
  66388. }
  66389. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  66390. if( rc ) goto balance_cleanup;
  66391. abDone[iPg]++;
  66392. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  66393. assert( apNew[iPg]->nOverflow==0 );
  66394. assert( apNew[iPg]->nCell==nNewCell );
  66395. }
  66396. }
  66397. /* All pages have been processed exactly once */
  66398. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  66399. assert( nOld>0 );
  66400. assert( nNew>0 );
  66401. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  66402. /* The root page of the b-tree now contains no cells. The only sibling
  66403. ** page is the right-child of the parent. Copy the contents of the
  66404. ** child page into the parent, decreasing the overall height of the
  66405. ** b-tree structure by one. This is described as the "balance-shallower"
  66406. ** sub-algorithm in some documentation.
  66407. **
  66408. ** If this is an auto-vacuum database, the call to copyNodeContent()
  66409. ** sets all pointer-map entries corresponding to database image pages
  66410. ** for which the pointer is stored within the content being copied.
  66411. **
  66412. ** It is critical that the child page be defragmented before being
  66413. ** copied into the parent, because if the parent is page 1 then it will
  66414. ** by smaller than the child due to the database header, and so all the
  66415. ** free space needs to be up front.
  66416. */
  66417. assert( nNew==1 || CORRUPT_DB );
  66418. rc = defragmentPage(apNew[0], -1);
  66419. testcase( rc!=SQLITE_OK );
  66420. assert( apNew[0]->nFree ==
  66421. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  66422. || rc!=SQLITE_OK
  66423. );
  66424. copyNodeContent(apNew[0], pParent, &rc);
  66425. freePage(apNew[0], &rc);
  66426. }else if( ISAUTOVACUUM && !leafCorrection ){
  66427. /* Fix the pointer map entries associated with the right-child of each
  66428. ** sibling page. All other pointer map entries have already been taken
  66429. ** care of. */
  66430. for(i=0; i<nNew; i++){
  66431. u32 key = get4byte(&apNew[i]->aData[8]);
  66432. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  66433. }
  66434. }
  66435. assert( pParent->isInit );
  66436. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  66437. nOld, nNew, b.nCell));
  66438. /* Free any old pages that were not reused as new pages.
  66439. */
  66440. for(i=nNew; i<nOld; i++){
  66441. freePage(apOld[i], &rc);
  66442. }
  66443. #if 0
  66444. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  66445. /* The ptrmapCheckPages() contains assert() statements that verify that
  66446. ** all pointer map pages are set correctly. This is helpful while
  66447. ** debugging. This is usually disabled because a corrupt database may
  66448. ** cause an assert() statement to fail. */
  66449. ptrmapCheckPages(apNew, nNew);
  66450. ptrmapCheckPages(&pParent, 1);
  66451. }
  66452. #endif
  66453. /*
  66454. ** Cleanup before returning.
  66455. */
  66456. balance_cleanup:
  66457. sqlite3StackFree(0, b.apCell);
  66458. for(i=0; i<nOld; i++){
  66459. releasePage(apOld[i]);
  66460. }
  66461. for(i=0; i<nNew; i++){
  66462. releasePage(apNew[i]);
  66463. }
  66464. return rc;
  66465. }
  66466. /*
  66467. ** This function is called when the root page of a b-tree structure is
  66468. ** overfull (has one or more overflow pages).
  66469. **
  66470. ** A new child page is allocated and the contents of the current root
  66471. ** page, including overflow cells, are copied into the child. The root
  66472. ** page is then overwritten to make it an empty page with the right-child
  66473. ** pointer pointing to the new page.
  66474. **
  66475. ** Before returning, all pointer-map entries corresponding to pages
  66476. ** that the new child-page now contains pointers to are updated. The
  66477. ** entry corresponding to the new right-child pointer of the root
  66478. ** page is also updated.
  66479. **
  66480. ** If successful, *ppChild is set to contain a reference to the child
  66481. ** page and SQLITE_OK is returned. In this case the caller is required
  66482. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  66483. ** an error code is returned and *ppChild is set to 0.
  66484. */
  66485. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  66486. int rc; /* Return value from subprocedures */
  66487. MemPage *pChild = 0; /* Pointer to a new child page */
  66488. Pgno pgnoChild = 0; /* Page number of the new child page */
  66489. BtShared *pBt = pRoot->pBt; /* The BTree */
  66490. assert( pRoot->nOverflow>0 );
  66491. assert( sqlite3_mutex_held(pBt->mutex) );
  66492. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  66493. ** page that will become the new right-child of pPage. Copy the contents
  66494. ** of the node stored on pRoot into the new child page.
  66495. */
  66496. rc = sqlite3PagerWrite(pRoot->pDbPage);
  66497. if( rc==SQLITE_OK ){
  66498. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  66499. copyNodeContent(pRoot, pChild, &rc);
  66500. if( ISAUTOVACUUM ){
  66501. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  66502. }
  66503. }
  66504. if( rc ){
  66505. *ppChild = 0;
  66506. releasePage(pChild);
  66507. return rc;
  66508. }
  66509. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  66510. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  66511. assert( pChild->nCell==pRoot->nCell );
  66512. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  66513. /* Copy the overflow cells from pRoot to pChild */
  66514. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  66515. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  66516. memcpy(pChild->apOvfl, pRoot->apOvfl,
  66517. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  66518. pChild->nOverflow = pRoot->nOverflow;
  66519. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  66520. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  66521. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  66522. *ppChild = pChild;
  66523. return SQLITE_OK;
  66524. }
  66525. /*
  66526. ** The page that pCur currently points to has just been modified in
  66527. ** some way. This function figures out if this modification means the
  66528. ** tree needs to be balanced, and if so calls the appropriate balancing
  66529. ** routine. Balancing routines are:
  66530. **
  66531. ** balance_quick()
  66532. ** balance_deeper()
  66533. ** balance_nonroot()
  66534. */
  66535. static int balance(BtCursor *pCur){
  66536. int rc = SQLITE_OK;
  66537. const int nMin = pCur->pBt->usableSize * 2 / 3;
  66538. u8 aBalanceQuickSpace[13];
  66539. u8 *pFree = 0;
  66540. VVA_ONLY( int balance_quick_called = 0 );
  66541. VVA_ONLY( int balance_deeper_called = 0 );
  66542. do {
  66543. int iPage = pCur->iPage;
  66544. MemPage *pPage = pCur->pPage;
  66545. if( iPage==0 ){
  66546. if( pPage->nOverflow ){
  66547. /* The root page of the b-tree is overfull. In this case call the
  66548. ** balance_deeper() function to create a new child for the root-page
  66549. ** and copy the current contents of the root-page to it. The
  66550. ** next iteration of the do-loop will balance the child page.
  66551. */
  66552. assert( balance_deeper_called==0 );
  66553. VVA_ONLY( balance_deeper_called++ );
  66554. rc = balance_deeper(pPage, &pCur->apPage[1]);
  66555. if( rc==SQLITE_OK ){
  66556. pCur->iPage = 1;
  66557. pCur->ix = 0;
  66558. pCur->aiIdx[0] = 0;
  66559. pCur->apPage[0] = pPage;
  66560. pCur->pPage = pCur->apPage[1];
  66561. assert( pCur->pPage->nOverflow );
  66562. }
  66563. }else{
  66564. break;
  66565. }
  66566. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  66567. break;
  66568. }else{
  66569. MemPage * const pParent = pCur->apPage[iPage-1];
  66570. int const iIdx = pCur->aiIdx[iPage-1];
  66571. rc = sqlite3PagerWrite(pParent->pDbPage);
  66572. if( rc==SQLITE_OK ){
  66573. #ifndef SQLITE_OMIT_QUICKBALANCE
  66574. if( pPage->intKeyLeaf
  66575. && pPage->nOverflow==1
  66576. && pPage->aiOvfl[0]==pPage->nCell
  66577. && pParent->pgno!=1
  66578. && pParent->nCell==iIdx
  66579. ){
  66580. /* Call balance_quick() to create a new sibling of pPage on which
  66581. ** to store the overflow cell. balance_quick() inserts a new cell
  66582. ** into pParent, which may cause pParent overflow. If this
  66583. ** happens, the next iteration of the do-loop will balance pParent
  66584. ** use either balance_nonroot() or balance_deeper(). Until this
  66585. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  66586. ** buffer.
  66587. **
  66588. ** The purpose of the following assert() is to check that only a
  66589. ** single call to balance_quick() is made for each call to this
  66590. ** function. If this were not verified, a subtle bug involving reuse
  66591. ** of the aBalanceQuickSpace[] might sneak in.
  66592. */
  66593. assert( balance_quick_called==0 );
  66594. VVA_ONLY( balance_quick_called++ );
  66595. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  66596. }else
  66597. #endif
  66598. {
  66599. /* In this case, call balance_nonroot() to redistribute cells
  66600. ** between pPage and up to 2 of its sibling pages. This involves
  66601. ** modifying the contents of pParent, which may cause pParent to
  66602. ** become overfull or underfull. The next iteration of the do-loop
  66603. ** will balance the parent page to correct this.
  66604. **
  66605. ** If the parent page becomes overfull, the overflow cell or cells
  66606. ** are stored in the pSpace buffer allocated immediately below.
  66607. ** A subsequent iteration of the do-loop will deal with this by
  66608. ** calling balance_nonroot() (balance_deeper() may be called first,
  66609. ** but it doesn't deal with overflow cells - just moves them to a
  66610. ** different page). Once this subsequent call to balance_nonroot()
  66611. ** has completed, it is safe to release the pSpace buffer used by
  66612. ** the previous call, as the overflow cell data will have been
  66613. ** copied either into the body of a database page or into the new
  66614. ** pSpace buffer passed to the latter call to balance_nonroot().
  66615. */
  66616. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  66617. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  66618. pCur->hints&BTREE_BULKLOAD);
  66619. if( pFree ){
  66620. /* If pFree is not NULL, it points to the pSpace buffer used
  66621. ** by a previous call to balance_nonroot(). Its contents are
  66622. ** now stored either on real database pages or within the
  66623. ** new pSpace buffer, so it may be safely freed here. */
  66624. sqlite3PageFree(pFree);
  66625. }
  66626. /* The pSpace buffer will be freed after the next call to
  66627. ** balance_nonroot(), or just before this function returns, whichever
  66628. ** comes first. */
  66629. pFree = pSpace;
  66630. }
  66631. }
  66632. pPage->nOverflow = 0;
  66633. /* The next iteration of the do-loop balances the parent page. */
  66634. releasePage(pPage);
  66635. pCur->iPage--;
  66636. assert( pCur->iPage>=0 );
  66637. pCur->pPage = pCur->apPage[pCur->iPage];
  66638. }
  66639. }while( rc==SQLITE_OK );
  66640. if( pFree ){
  66641. sqlite3PageFree(pFree);
  66642. }
  66643. return rc;
  66644. }
  66645. /* Overwrite content from pX into pDest. Only do the write if the
  66646. ** content is different from what is already there.
  66647. */
  66648. static int btreeOverwriteContent(
  66649. MemPage *pPage, /* MemPage on which writing will occur */
  66650. u8 *pDest, /* Pointer to the place to start writing */
  66651. const BtreePayload *pX, /* Source of data to write */
  66652. int iOffset, /* Offset of first byte to write */
  66653. int iAmt /* Number of bytes to be written */
  66654. ){
  66655. int nData = pX->nData - iOffset;
  66656. if( nData<=0 ){
  66657. /* Overwritting with zeros */
  66658. int i;
  66659. for(i=0; i<iAmt && pDest[i]==0; i++){}
  66660. if( i<iAmt ){
  66661. int rc = sqlite3PagerWrite(pPage->pDbPage);
  66662. if( rc ) return rc;
  66663. memset(pDest + i, 0, iAmt - i);
  66664. }
  66665. }else{
  66666. if( nData<iAmt ){
  66667. /* Mixed read data and zeros at the end. Make a recursive call
  66668. ** to write the zeros then fall through to write the real data */
  66669. int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
  66670. iAmt-nData);
  66671. if( rc ) return rc;
  66672. iAmt = nData;
  66673. }
  66674. if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
  66675. int rc = sqlite3PagerWrite(pPage->pDbPage);
  66676. if( rc ) return rc;
  66677. memcpy(pDest, ((u8*)pX->pData) + iOffset, iAmt);
  66678. }
  66679. }
  66680. return SQLITE_OK;
  66681. }
  66682. /*
  66683. ** Overwrite the cell that cursor pCur is pointing to with fresh content
  66684. ** contained in pX.
  66685. */
  66686. static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
  66687. int iOffset; /* Next byte of pX->pData to write */
  66688. int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
  66689. int rc; /* Return code */
  66690. MemPage *pPage = pCur->pPage; /* Page being written */
  66691. BtShared *pBt; /* Btree */
  66692. Pgno ovflPgno; /* Next overflow page to write */
  66693. u32 ovflPageSize; /* Size to write on overflow page */
  66694. if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd ){
  66695. return SQLITE_CORRUPT_BKPT;
  66696. }
  66697. /* Overwrite the local portion first */
  66698. rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
  66699. 0, pCur->info.nLocal);
  66700. if( rc ) return rc;
  66701. if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
  66702. /* Now overwrite the overflow pages */
  66703. iOffset = pCur->info.nLocal;
  66704. assert( nTotal>=0 );
  66705. assert( iOffset>=0 );
  66706. ovflPgno = get4byte(pCur->info.pPayload + iOffset);
  66707. pBt = pPage->pBt;
  66708. ovflPageSize = pBt->usableSize - 4;
  66709. do{
  66710. rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
  66711. if( rc ) return rc;
  66712. if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
  66713. rc = SQLITE_CORRUPT_BKPT;
  66714. }else{
  66715. if( iOffset+ovflPageSize<(u32)nTotal ){
  66716. ovflPgno = get4byte(pPage->aData);
  66717. }else{
  66718. ovflPageSize = nTotal - iOffset;
  66719. }
  66720. rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
  66721. iOffset, ovflPageSize);
  66722. }
  66723. sqlite3PagerUnref(pPage->pDbPage);
  66724. if( rc ) return rc;
  66725. iOffset += ovflPageSize;
  66726. }while( iOffset<nTotal );
  66727. return SQLITE_OK;
  66728. }
  66729. /*
  66730. ** Insert a new record into the BTree. The content of the new record
  66731. ** is described by the pX object. The pCur cursor is used only to
  66732. ** define what table the record should be inserted into, and is left
  66733. ** pointing at a random location.
  66734. **
  66735. ** For a table btree (used for rowid tables), only the pX.nKey value of
  66736. ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
  66737. ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
  66738. ** hold the content of the row.
  66739. **
  66740. ** For an index btree (used for indexes and WITHOUT ROWID tables), the
  66741. ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
  66742. ** pX.pData,nData,nZero fields must be zero.
  66743. **
  66744. ** If the seekResult parameter is non-zero, then a successful call to
  66745. ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
  66746. ** been performed. In other words, if seekResult!=0 then the cursor
  66747. ** is currently pointing to a cell that will be adjacent to the cell
  66748. ** to be inserted. If seekResult<0 then pCur points to a cell that is
  66749. ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
  66750. ** that is larger than (pKey,nKey).
  66751. **
  66752. ** If seekResult==0, that means pCur is pointing at some unknown location.
  66753. ** In that case, this routine must seek the cursor to the correct insertion
  66754. ** point for (pKey,nKey) before doing the insertion. For index btrees,
  66755. ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
  66756. ** key values and pX->aMem can be used instead of pX->pKey to avoid having
  66757. ** to decode the key.
  66758. */
  66759. SQLITE_PRIVATE int sqlite3BtreeInsert(
  66760. BtCursor *pCur, /* Insert data into the table of this cursor */
  66761. const BtreePayload *pX, /* Content of the row to be inserted */
  66762. int flags, /* True if this is likely an append */
  66763. int seekResult /* Result of prior MovetoUnpacked() call */
  66764. ){
  66765. int rc;
  66766. int loc = seekResult; /* -1: before desired location +1: after */
  66767. int szNew = 0;
  66768. int idx;
  66769. MemPage *pPage;
  66770. Btree *p = pCur->pBtree;
  66771. BtShared *pBt = p->pBt;
  66772. unsigned char *oldCell;
  66773. unsigned char *newCell = 0;
  66774. assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
  66775. if( pCur->eState==CURSOR_FAULT ){
  66776. assert( pCur->skipNext!=SQLITE_OK );
  66777. return pCur->skipNext;
  66778. }
  66779. assert( cursorOwnsBtShared(pCur) );
  66780. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  66781. && pBt->inTransaction==TRANS_WRITE
  66782. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  66783. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  66784. /* Assert that the caller has been consistent. If this cursor was opened
  66785. ** expecting an index b-tree, then the caller should be inserting blob
  66786. ** keys with no associated data. If the cursor was opened expecting an
  66787. ** intkey table, the caller should be inserting integer keys with a
  66788. ** blob of associated data. */
  66789. assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
  66790. /* Save the positions of any other cursors open on this table.
  66791. **
  66792. ** In some cases, the call to btreeMoveto() below is a no-op. For
  66793. ** example, when inserting data into a table with auto-generated integer
  66794. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  66795. ** integer key to use. It then calls this function to actually insert the
  66796. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  66797. ** that the cursor is already where it needs to be and returns without
  66798. ** doing any work. To avoid thwarting these optimizations, it is important
  66799. ** not to clear the cursor here.
  66800. */
  66801. if( pCur->curFlags & BTCF_Multiple ){
  66802. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  66803. if( rc ) return rc;
  66804. }
  66805. if( pCur->pKeyInfo==0 ){
  66806. assert( pX->pKey==0 );
  66807. /* If this is an insert into a table b-tree, invalidate any incrblob
  66808. ** cursors open on the row being replaced */
  66809. invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
  66810. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  66811. ** to a row with the same key as the new entry being inserted.
  66812. */
  66813. #ifdef SQLITE_DEBUG
  66814. if( flags & BTREE_SAVEPOSITION ){
  66815. assert( pCur->curFlags & BTCF_ValidNKey );
  66816. assert( pX->nKey==pCur->info.nKey );
  66817. assert( pCur->info.nSize!=0 );
  66818. assert( loc==0 );
  66819. }
  66820. #endif
  66821. /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
  66822. ** that the cursor is not pointing to a row to be overwritten.
  66823. ** So do a complete check.
  66824. */
  66825. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
  66826. /* The cursor is pointing to the entry that is to be
  66827. ** overwritten */
  66828. assert( pX->nData>=0 && pX->nZero>=0 );
  66829. if( pCur->info.nSize!=0
  66830. && pCur->info.nPayload==(u32)pX->nData+pX->nZero
  66831. ){
  66832. /* New entry is the same size as the old. Do an overwrite */
  66833. return btreeOverwriteCell(pCur, pX);
  66834. }
  66835. assert( loc==0 );
  66836. }else if( loc==0 ){
  66837. /* The cursor is *not* pointing to the cell to be overwritten, nor
  66838. ** to an adjacent cell. Move the cursor so that it is pointing either
  66839. ** to the cell to be overwritten or an adjacent cell.
  66840. */
  66841. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
  66842. if( rc ) return rc;
  66843. }
  66844. }else{
  66845. /* This is an index or a WITHOUT ROWID table */
  66846. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  66847. ** to a row with the same key as the new entry being inserted.
  66848. */
  66849. assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
  66850. /* If the cursor is not already pointing either to the cell to be
  66851. ** overwritten, or if a new cell is being inserted, if the cursor is
  66852. ** not pointing to an immediately adjacent cell, then move the cursor
  66853. ** so that it does.
  66854. */
  66855. if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
  66856. if( pX->nMem ){
  66857. UnpackedRecord r;
  66858. r.pKeyInfo = pCur->pKeyInfo;
  66859. r.aMem = pX->aMem;
  66860. r.nField = pX->nMem;
  66861. r.default_rc = 0;
  66862. r.errCode = 0;
  66863. r.r1 = 0;
  66864. r.r2 = 0;
  66865. r.eqSeen = 0;
  66866. rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
  66867. }else{
  66868. rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
  66869. }
  66870. if( rc ) return rc;
  66871. }
  66872. /* If the cursor is currently pointing to an entry to be overwritten
  66873. ** and the new content is the same as as the old, then use the
  66874. ** overwrite optimization.
  66875. */
  66876. if( loc==0 ){
  66877. getCellInfo(pCur);
  66878. if( pCur->info.nKey==pX->nKey ){
  66879. BtreePayload x2;
  66880. x2.pData = pX->pKey;
  66881. x2.nData = pX->nKey;
  66882. x2.nZero = 0;
  66883. return btreeOverwriteCell(pCur, &x2);
  66884. }
  66885. }
  66886. }
  66887. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  66888. pPage = pCur->pPage;
  66889. assert( pPage->intKey || pX->nKey>=0 );
  66890. assert( pPage->leaf || !pPage->intKey );
  66891. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  66892. pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
  66893. loc==0 ? "overwrite" : "new entry"));
  66894. assert( pPage->isInit );
  66895. newCell = pBt->pTmpSpace;
  66896. assert( newCell!=0 );
  66897. rc = fillInCell(pPage, newCell, pX, &szNew);
  66898. if( rc ) goto end_insert;
  66899. assert( szNew==pPage->xCellSize(pPage, newCell) );
  66900. assert( szNew <= MX_CELL_SIZE(pBt) );
  66901. idx = pCur->ix;
  66902. if( loc==0 ){
  66903. CellInfo info;
  66904. assert( idx<pPage->nCell );
  66905. rc = sqlite3PagerWrite(pPage->pDbPage);
  66906. if( rc ){
  66907. goto end_insert;
  66908. }
  66909. oldCell = findCell(pPage, idx);
  66910. if( !pPage->leaf ){
  66911. memcpy(newCell, oldCell, 4);
  66912. }
  66913. rc = clearCell(pPage, oldCell, &info);
  66914. if( info.nSize==szNew && info.nLocal==info.nPayload
  66915. && (!ISAUTOVACUUM || szNew<pPage->minLocal)
  66916. ){
  66917. /* Overwrite the old cell with the new if they are the same size.
  66918. ** We could also try to do this if the old cell is smaller, then add
  66919. ** the leftover space to the free list. But experiments show that
  66920. ** doing that is no faster then skipping this optimization and just
  66921. ** calling dropCell() and insertCell().
  66922. **
  66923. ** This optimization cannot be used on an autovacuum database if the
  66924. ** new entry uses overflow pages, as the insertCell() call below is
  66925. ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
  66926. assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
  66927. if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  66928. memcpy(oldCell, newCell, szNew);
  66929. return SQLITE_OK;
  66930. }
  66931. dropCell(pPage, idx, info.nSize, &rc);
  66932. if( rc ) goto end_insert;
  66933. }else if( loc<0 && pPage->nCell>0 ){
  66934. assert( pPage->leaf );
  66935. idx = ++pCur->ix;
  66936. pCur->curFlags &= ~BTCF_ValidNKey;
  66937. }else{
  66938. assert( pPage->leaf );
  66939. }
  66940. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  66941. assert( pPage->nOverflow==0 || rc==SQLITE_OK );
  66942. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  66943. /* If no error has occurred and pPage has an overflow cell, call balance()
  66944. ** to redistribute the cells within the tree. Since balance() may move
  66945. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  66946. ** variables.
  66947. **
  66948. ** Previous versions of SQLite called moveToRoot() to move the cursor
  66949. ** back to the root page as balance() used to invalidate the contents
  66950. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  66951. ** set the cursor state to "invalid". This makes common insert operations
  66952. ** slightly faster.
  66953. **
  66954. ** There is a subtle but important optimization here too. When inserting
  66955. ** multiple records into an intkey b-tree using a single cursor (as can
  66956. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  66957. ** is advantageous to leave the cursor pointing to the last entry in
  66958. ** the b-tree if possible. If the cursor is left pointing to the last
  66959. ** entry in the table, and the next row inserted has an integer key
  66960. ** larger than the largest existing key, it is possible to insert the
  66961. ** row without seeking the cursor. This can be a big performance boost.
  66962. */
  66963. pCur->info.nSize = 0;
  66964. if( pPage->nOverflow ){
  66965. assert( rc==SQLITE_OK );
  66966. pCur->curFlags &= ~(BTCF_ValidNKey);
  66967. rc = balance(pCur);
  66968. /* Must make sure nOverflow is reset to zero even if the balance()
  66969. ** fails. Internal data structure corruption will result otherwise.
  66970. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  66971. ** from trying to save the current position of the cursor. */
  66972. pCur->pPage->nOverflow = 0;
  66973. pCur->eState = CURSOR_INVALID;
  66974. if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
  66975. btreeReleaseAllCursorPages(pCur);
  66976. if( pCur->pKeyInfo ){
  66977. assert( pCur->pKey==0 );
  66978. pCur->pKey = sqlite3Malloc( pX->nKey );
  66979. if( pCur->pKey==0 ){
  66980. rc = SQLITE_NOMEM;
  66981. }else{
  66982. memcpy(pCur->pKey, pX->pKey, pX->nKey);
  66983. }
  66984. }
  66985. pCur->eState = CURSOR_REQUIRESEEK;
  66986. pCur->nKey = pX->nKey;
  66987. }
  66988. }
  66989. assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
  66990. end_insert:
  66991. return rc;
  66992. }
  66993. /*
  66994. ** Delete the entry that the cursor is pointing to.
  66995. **
  66996. ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
  66997. ** the cursor is left pointing at an arbitrary location after the delete.
  66998. ** But if that bit is set, then the cursor is left in a state such that
  66999. ** the next call to BtreeNext() or BtreePrev() moves it to the same row
  67000. ** as it would have been on if the call to BtreeDelete() had been omitted.
  67001. **
  67002. ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
  67003. ** associated with a single table entry and its indexes. Only one of those
  67004. ** deletes is considered the "primary" delete. The primary delete occurs
  67005. ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
  67006. ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
  67007. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
  67008. ** but which might be used by alternative storage engines.
  67009. */
  67010. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
  67011. Btree *p = pCur->pBtree;
  67012. BtShared *pBt = p->pBt;
  67013. int rc; /* Return code */
  67014. MemPage *pPage; /* Page to delete cell from */
  67015. unsigned char *pCell; /* Pointer to cell to delete */
  67016. int iCellIdx; /* Index of cell to delete */
  67017. int iCellDepth; /* Depth of node containing pCell */
  67018. CellInfo info; /* Size of the cell being deleted */
  67019. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  67020. u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
  67021. assert( cursorOwnsBtShared(pCur) );
  67022. assert( pBt->inTransaction==TRANS_WRITE );
  67023. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  67024. assert( pCur->curFlags & BTCF_WriteFlag );
  67025. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  67026. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  67027. assert( pCur->ix<pCur->pPage->nCell );
  67028. assert( pCur->eState==CURSOR_VALID );
  67029. assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
  67030. iCellDepth = pCur->iPage;
  67031. iCellIdx = pCur->ix;
  67032. pPage = pCur->pPage;
  67033. pCell = findCell(pPage, iCellIdx);
  67034. /* If the bPreserve flag is set to true, then the cursor position must
  67035. ** be preserved following this delete operation. If the current delete
  67036. ** will cause a b-tree rebalance, then this is done by saving the cursor
  67037. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  67038. ** returning.
  67039. **
  67040. ** Or, if the current delete will not cause a rebalance, then the cursor
  67041. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  67042. ** before or after the deleted entry. In this case set bSkipnext to true. */
  67043. if( bPreserve ){
  67044. if( !pPage->leaf
  67045. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  67046. ){
  67047. /* A b-tree rebalance will be required after deleting this entry.
  67048. ** Save the cursor key. */
  67049. rc = saveCursorKey(pCur);
  67050. if( rc ) return rc;
  67051. }else{
  67052. bSkipnext = 1;
  67053. }
  67054. }
  67055. /* If the page containing the entry to delete is not a leaf page, move
  67056. ** the cursor to the largest entry in the tree that is smaller than
  67057. ** the entry being deleted. This cell will replace the cell being deleted
  67058. ** from the internal node. The 'previous' entry is used for this instead
  67059. ** of the 'next' entry, as the previous entry is always a part of the
  67060. ** sub-tree headed by the child page of the cell being deleted. This makes
  67061. ** balancing the tree following the delete operation easier. */
  67062. if( !pPage->leaf ){
  67063. rc = sqlite3BtreePrevious(pCur, 0);
  67064. assert( rc!=SQLITE_DONE );
  67065. if( rc ) return rc;
  67066. }
  67067. /* Save the positions of any other cursors open on this table before
  67068. ** making any modifications. */
  67069. if( pCur->curFlags & BTCF_Multiple ){
  67070. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  67071. if( rc ) return rc;
  67072. }
  67073. /* If this is a delete operation to remove a row from a table b-tree,
  67074. ** invalidate any incrblob cursors open on the row being deleted. */
  67075. if( pCur->pKeyInfo==0 ){
  67076. invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
  67077. }
  67078. /* Make the page containing the entry to be deleted writable. Then free any
  67079. ** overflow pages associated with the entry and finally remove the cell
  67080. ** itself from within the page. */
  67081. rc = sqlite3PagerWrite(pPage->pDbPage);
  67082. if( rc ) return rc;
  67083. rc = clearCell(pPage, pCell, &info);
  67084. dropCell(pPage, iCellIdx, info.nSize, &rc);
  67085. if( rc ) return rc;
  67086. /* If the cell deleted was not located on a leaf page, then the cursor
  67087. ** is currently pointing to the largest entry in the sub-tree headed
  67088. ** by the child-page of the cell that was just deleted from an internal
  67089. ** node. The cell from the leaf node needs to be moved to the internal
  67090. ** node to replace the deleted cell. */
  67091. if( !pPage->leaf ){
  67092. MemPage *pLeaf = pCur->pPage;
  67093. int nCell;
  67094. Pgno n;
  67095. unsigned char *pTmp;
  67096. if( iCellDepth<pCur->iPage-1 ){
  67097. n = pCur->apPage[iCellDepth+1]->pgno;
  67098. }else{
  67099. n = pCur->pPage->pgno;
  67100. }
  67101. pCell = findCell(pLeaf, pLeaf->nCell-1);
  67102. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  67103. nCell = pLeaf->xCellSize(pLeaf, pCell);
  67104. assert( MX_CELL_SIZE(pBt) >= nCell );
  67105. pTmp = pBt->pTmpSpace;
  67106. assert( pTmp!=0 );
  67107. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  67108. if( rc==SQLITE_OK ){
  67109. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  67110. }
  67111. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  67112. if( rc ) return rc;
  67113. }
  67114. /* Balance the tree. If the entry deleted was located on a leaf page,
  67115. ** then the cursor still points to that page. In this case the first
  67116. ** call to balance() repairs the tree, and the if(...) condition is
  67117. ** never true.
  67118. **
  67119. ** Otherwise, if the entry deleted was on an internal node page, then
  67120. ** pCur is pointing to the leaf page from which a cell was removed to
  67121. ** replace the cell deleted from the internal node. This is slightly
  67122. ** tricky as the leaf node may be underfull, and the internal node may
  67123. ** be either under or overfull. In this case run the balancing algorithm
  67124. ** on the leaf node first. If the balance proceeds far enough up the
  67125. ** tree that we can be sure that any problem in the internal node has
  67126. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  67127. ** walk the cursor up the tree to the internal node and balance it as
  67128. ** well. */
  67129. rc = balance(pCur);
  67130. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  67131. releasePageNotNull(pCur->pPage);
  67132. pCur->iPage--;
  67133. while( pCur->iPage>iCellDepth ){
  67134. releasePage(pCur->apPage[pCur->iPage--]);
  67135. }
  67136. pCur->pPage = pCur->apPage[pCur->iPage];
  67137. rc = balance(pCur);
  67138. }
  67139. if( rc==SQLITE_OK ){
  67140. if( bSkipnext ){
  67141. assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
  67142. assert( pPage==pCur->pPage || CORRUPT_DB );
  67143. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  67144. pCur->eState = CURSOR_SKIPNEXT;
  67145. if( iCellIdx>=pPage->nCell ){
  67146. pCur->skipNext = -1;
  67147. pCur->ix = pPage->nCell-1;
  67148. }else{
  67149. pCur->skipNext = 1;
  67150. }
  67151. }else{
  67152. rc = moveToRoot(pCur);
  67153. if( bPreserve ){
  67154. btreeReleaseAllCursorPages(pCur);
  67155. pCur->eState = CURSOR_REQUIRESEEK;
  67156. }
  67157. if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
  67158. }
  67159. }
  67160. return rc;
  67161. }
  67162. /*
  67163. ** Create a new BTree table. Write into *piTable the page
  67164. ** number for the root page of the new table.
  67165. **
  67166. ** The type of type is determined by the flags parameter. Only the
  67167. ** following values of flags are currently in use. Other values for
  67168. ** flags might not work:
  67169. **
  67170. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  67171. ** BTREE_ZERODATA Used for SQL indices
  67172. */
  67173. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  67174. BtShared *pBt = p->pBt;
  67175. MemPage *pRoot;
  67176. Pgno pgnoRoot;
  67177. int rc;
  67178. int ptfFlags; /* Page-type flage for the root page of new table */
  67179. assert( sqlite3BtreeHoldsMutex(p) );
  67180. assert( pBt->inTransaction==TRANS_WRITE );
  67181. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  67182. #ifdef SQLITE_OMIT_AUTOVACUUM
  67183. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  67184. if( rc ){
  67185. return rc;
  67186. }
  67187. #else
  67188. if( pBt->autoVacuum ){
  67189. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  67190. MemPage *pPageMove; /* The page to move to. */
  67191. /* Creating a new table may probably require moving an existing database
  67192. ** to make room for the new tables root page. In case this page turns
  67193. ** out to be an overflow page, delete all overflow page-map caches
  67194. ** held by open cursors.
  67195. */
  67196. invalidateAllOverflowCache(pBt);
  67197. /* Read the value of meta[3] from the database to determine where the
  67198. ** root page of the new table should go. meta[3] is the largest root-page
  67199. ** created so far, so the new root-page is (meta[3]+1).
  67200. */
  67201. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  67202. pgnoRoot++;
  67203. /* The new root-page may not be allocated on a pointer-map page, or the
  67204. ** PENDING_BYTE page.
  67205. */
  67206. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  67207. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  67208. pgnoRoot++;
  67209. }
  67210. assert( pgnoRoot>=3 || CORRUPT_DB );
  67211. testcase( pgnoRoot<3 );
  67212. /* Allocate a page. The page that currently resides at pgnoRoot will
  67213. ** be moved to the allocated page (unless the allocated page happens
  67214. ** to reside at pgnoRoot).
  67215. */
  67216. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  67217. if( rc!=SQLITE_OK ){
  67218. return rc;
  67219. }
  67220. if( pgnoMove!=pgnoRoot ){
  67221. /* pgnoRoot is the page that will be used for the root-page of
  67222. ** the new table (assuming an error did not occur). But we were
  67223. ** allocated pgnoMove. If required (i.e. if it was not allocated
  67224. ** by extending the file), the current page at position pgnoMove
  67225. ** is already journaled.
  67226. */
  67227. u8 eType = 0;
  67228. Pgno iPtrPage = 0;
  67229. /* Save the positions of any open cursors. This is required in
  67230. ** case they are holding a reference to an xFetch reference
  67231. ** corresponding to page pgnoRoot. */
  67232. rc = saveAllCursors(pBt, 0, 0);
  67233. releasePage(pPageMove);
  67234. if( rc!=SQLITE_OK ){
  67235. return rc;
  67236. }
  67237. /* Move the page currently at pgnoRoot to pgnoMove. */
  67238. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  67239. if( rc!=SQLITE_OK ){
  67240. return rc;
  67241. }
  67242. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  67243. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  67244. rc = SQLITE_CORRUPT_BKPT;
  67245. }
  67246. if( rc!=SQLITE_OK ){
  67247. releasePage(pRoot);
  67248. return rc;
  67249. }
  67250. assert( eType!=PTRMAP_ROOTPAGE );
  67251. assert( eType!=PTRMAP_FREEPAGE );
  67252. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  67253. releasePage(pRoot);
  67254. /* Obtain the page at pgnoRoot */
  67255. if( rc!=SQLITE_OK ){
  67256. return rc;
  67257. }
  67258. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  67259. if( rc!=SQLITE_OK ){
  67260. return rc;
  67261. }
  67262. rc = sqlite3PagerWrite(pRoot->pDbPage);
  67263. if( rc!=SQLITE_OK ){
  67264. releasePage(pRoot);
  67265. return rc;
  67266. }
  67267. }else{
  67268. pRoot = pPageMove;
  67269. }
  67270. /* Update the pointer-map and meta-data with the new root-page number. */
  67271. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  67272. if( rc ){
  67273. releasePage(pRoot);
  67274. return rc;
  67275. }
  67276. /* When the new root page was allocated, page 1 was made writable in
  67277. ** order either to increase the database filesize, or to decrement the
  67278. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  67279. */
  67280. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  67281. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  67282. if( NEVER(rc) ){
  67283. releasePage(pRoot);
  67284. return rc;
  67285. }
  67286. }else{
  67287. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  67288. if( rc ) return rc;
  67289. }
  67290. #endif
  67291. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  67292. if( createTabFlags & BTREE_INTKEY ){
  67293. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  67294. }else{
  67295. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  67296. }
  67297. zeroPage(pRoot, ptfFlags);
  67298. sqlite3PagerUnref(pRoot->pDbPage);
  67299. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  67300. *piTable = (int)pgnoRoot;
  67301. return SQLITE_OK;
  67302. }
  67303. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  67304. int rc;
  67305. sqlite3BtreeEnter(p);
  67306. rc = btreeCreateTable(p, piTable, flags);
  67307. sqlite3BtreeLeave(p);
  67308. return rc;
  67309. }
  67310. /*
  67311. ** Erase the given database page and all its children. Return
  67312. ** the page to the freelist.
  67313. */
  67314. static int clearDatabasePage(
  67315. BtShared *pBt, /* The BTree that contains the table */
  67316. Pgno pgno, /* Page number to clear */
  67317. int freePageFlag, /* Deallocate page if true */
  67318. int *pnChange /* Add number of Cells freed to this counter */
  67319. ){
  67320. MemPage *pPage;
  67321. int rc;
  67322. unsigned char *pCell;
  67323. int i;
  67324. int hdr;
  67325. CellInfo info;
  67326. assert( sqlite3_mutex_held(pBt->mutex) );
  67327. if( pgno>btreePagecount(pBt) ){
  67328. return SQLITE_CORRUPT_BKPT;
  67329. }
  67330. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  67331. if( rc ) return rc;
  67332. if( pPage->bBusy ){
  67333. rc = SQLITE_CORRUPT_BKPT;
  67334. goto cleardatabasepage_out;
  67335. }
  67336. pPage->bBusy = 1;
  67337. hdr = pPage->hdrOffset;
  67338. for(i=0; i<pPage->nCell; i++){
  67339. pCell = findCell(pPage, i);
  67340. if( !pPage->leaf ){
  67341. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  67342. if( rc ) goto cleardatabasepage_out;
  67343. }
  67344. rc = clearCell(pPage, pCell, &info);
  67345. if( rc ) goto cleardatabasepage_out;
  67346. }
  67347. if( !pPage->leaf ){
  67348. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  67349. if( rc ) goto cleardatabasepage_out;
  67350. }else if( pnChange ){
  67351. assert( pPage->intKey || CORRUPT_DB );
  67352. testcase( !pPage->intKey );
  67353. *pnChange += pPage->nCell;
  67354. }
  67355. if( freePageFlag ){
  67356. freePage(pPage, &rc);
  67357. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  67358. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  67359. }
  67360. cleardatabasepage_out:
  67361. pPage->bBusy = 0;
  67362. releasePage(pPage);
  67363. return rc;
  67364. }
  67365. /*
  67366. ** Delete all information from a single table in the database. iTable is
  67367. ** the page number of the root of the table. After this routine returns,
  67368. ** the root page is empty, but still exists.
  67369. **
  67370. ** This routine will fail with SQLITE_LOCKED if there are any open
  67371. ** read cursors on the table. Open write cursors are moved to the
  67372. ** root of the table.
  67373. **
  67374. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  67375. ** integer value pointed to by pnChange is incremented by the number of
  67376. ** entries in the table.
  67377. */
  67378. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  67379. int rc;
  67380. BtShared *pBt = p->pBt;
  67381. sqlite3BtreeEnter(p);
  67382. assert( p->inTrans==TRANS_WRITE );
  67383. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  67384. if( SQLITE_OK==rc ){
  67385. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  67386. ** is the root of a table b-tree - if it is not, the following call is
  67387. ** a no-op). */
  67388. invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
  67389. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  67390. }
  67391. sqlite3BtreeLeave(p);
  67392. return rc;
  67393. }
  67394. /*
  67395. ** Delete all information from the single table that pCur is open on.
  67396. **
  67397. ** This routine only work for pCur on an ephemeral table.
  67398. */
  67399. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  67400. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  67401. }
  67402. /*
  67403. ** Erase all information in a table and add the root of the table to
  67404. ** the freelist. Except, the root of the principle table (the one on
  67405. ** page 1) is never added to the freelist.
  67406. **
  67407. ** This routine will fail with SQLITE_LOCKED if there are any open
  67408. ** cursors on the table.
  67409. **
  67410. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  67411. ** root page in the database file, then the last root page
  67412. ** in the database file is moved into the slot formerly occupied by
  67413. ** iTable and that last slot formerly occupied by the last root page
  67414. ** is added to the freelist instead of iTable. In this say, all
  67415. ** root pages are kept at the beginning of the database file, which
  67416. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  67417. ** page number that used to be the last root page in the file before
  67418. ** the move. If no page gets moved, *piMoved is set to 0.
  67419. ** The last root page is recorded in meta[3] and the value of
  67420. ** meta[3] is updated by this procedure.
  67421. */
  67422. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  67423. int rc;
  67424. MemPage *pPage = 0;
  67425. BtShared *pBt = p->pBt;
  67426. assert( sqlite3BtreeHoldsMutex(p) );
  67427. assert( p->inTrans==TRANS_WRITE );
  67428. assert( iTable>=2 );
  67429. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  67430. if( rc ) return rc;
  67431. rc = sqlite3BtreeClearTable(p, iTable, 0);
  67432. if( rc ){
  67433. releasePage(pPage);
  67434. return rc;
  67435. }
  67436. *piMoved = 0;
  67437. #ifdef SQLITE_OMIT_AUTOVACUUM
  67438. freePage(pPage, &rc);
  67439. releasePage(pPage);
  67440. #else
  67441. if( pBt->autoVacuum ){
  67442. Pgno maxRootPgno;
  67443. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  67444. if( iTable==maxRootPgno ){
  67445. /* If the table being dropped is the table with the largest root-page
  67446. ** number in the database, put the root page on the free list.
  67447. */
  67448. freePage(pPage, &rc);
  67449. releasePage(pPage);
  67450. if( rc!=SQLITE_OK ){
  67451. return rc;
  67452. }
  67453. }else{
  67454. /* The table being dropped does not have the largest root-page
  67455. ** number in the database. So move the page that does into the
  67456. ** gap left by the deleted root-page.
  67457. */
  67458. MemPage *pMove;
  67459. releasePage(pPage);
  67460. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  67461. if( rc!=SQLITE_OK ){
  67462. return rc;
  67463. }
  67464. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  67465. releasePage(pMove);
  67466. if( rc!=SQLITE_OK ){
  67467. return rc;
  67468. }
  67469. pMove = 0;
  67470. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  67471. freePage(pMove, &rc);
  67472. releasePage(pMove);
  67473. if( rc!=SQLITE_OK ){
  67474. return rc;
  67475. }
  67476. *piMoved = maxRootPgno;
  67477. }
  67478. /* Set the new 'max-root-page' value in the database header. This
  67479. ** is the old value less one, less one more if that happens to
  67480. ** be a root-page number, less one again if that is the
  67481. ** PENDING_BYTE_PAGE.
  67482. */
  67483. maxRootPgno--;
  67484. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  67485. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  67486. maxRootPgno--;
  67487. }
  67488. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  67489. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  67490. }else{
  67491. freePage(pPage, &rc);
  67492. releasePage(pPage);
  67493. }
  67494. #endif
  67495. return rc;
  67496. }
  67497. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  67498. int rc;
  67499. sqlite3BtreeEnter(p);
  67500. rc = btreeDropTable(p, iTable, piMoved);
  67501. sqlite3BtreeLeave(p);
  67502. return rc;
  67503. }
  67504. /*
  67505. ** This function may only be called if the b-tree connection already
  67506. ** has a read or write transaction open on the database.
  67507. **
  67508. ** Read the meta-information out of a database file. Meta[0]
  67509. ** is the number of free pages currently in the database. Meta[1]
  67510. ** through meta[15] are available for use by higher layers. Meta[0]
  67511. ** is read-only, the others are read/write.
  67512. **
  67513. ** The schema layer numbers meta values differently. At the schema
  67514. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  67515. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  67516. **
  67517. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  67518. ** of reading the value out of the header, it instead loads the "DataVersion"
  67519. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  67520. ** database file. It is a number computed by the pager. But its access
  67521. ** pattern is the same as header meta values, and so it is convenient to
  67522. ** read it from this routine.
  67523. */
  67524. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  67525. BtShared *pBt = p->pBt;
  67526. sqlite3BtreeEnter(p);
  67527. assert( p->inTrans>TRANS_NONE );
  67528. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  67529. assert( pBt->pPage1 );
  67530. assert( idx>=0 && idx<=15 );
  67531. if( idx==BTREE_DATA_VERSION ){
  67532. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  67533. }else{
  67534. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  67535. }
  67536. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  67537. ** database, mark the database as read-only. */
  67538. #ifdef SQLITE_OMIT_AUTOVACUUM
  67539. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  67540. pBt->btsFlags |= BTS_READ_ONLY;
  67541. }
  67542. #endif
  67543. sqlite3BtreeLeave(p);
  67544. }
  67545. /*
  67546. ** Write meta-information back into the database. Meta[0] is
  67547. ** read-only and may not be written.
  67548. */
  67549. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  67550. BtShared *pBt = p->pBt;
  67551. unsigned char *pP1;
  67552. int rc;
  67553. assert( idx>=1 && idx<=15 );
  67554. sqlite3BtreeEnter(p);
  67555. assert( p->inTrans==TRANS_WRITE );
  67556. assert( pBt->pPage1!=0 );
  67557. pP1 = pBt->pPage1->aData;
  67558. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  67559. if( rc==SQLITE_OK ){
  67560. put4byte(&pP1[36 + idx*4], iMeta);
  67561. #ifndef SQLITE_OMIT_AUTOVACUUM
  67562. if( idx==BTREE_INCR_VACUUM ){
  67563. assert( pBt->autoVacuum || iMeta==0 );
  67564. assert( iMeta==0 || iMeta==1 );
  67565. pBt->incrVacuum = (u8)iMeta;
  67566. }
  67567. #endif
  67568. }
  67569. sqlite3BtreeLeave(p);
  67570. return rc;
  67571. }
  67572. #ifndef SQLITE_OMIT_BTREECOUNT
  67573. /*
  67574. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  67575. ** number of entries in the b-tree and write the result to *pnEntry.
  67576. **
  67577. ** SQLITE_OK is returned if the operation is successfully executed.
  67578. ** Otherwise, if an error is encountered (i.e. an IO error or database
  67579. ** corruption) an SQLite error code is returned.
  67580. */
  67581. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  67582. i64 nEntry = 0; /* Value to return in *pnEntry */
  67583. int rc; /* Return code */
  67584. rc = moveToRoot(pCur);
  67585. if( rc==SQLITE_EMPTY ){
  67586. *pnEntry = 0;
  67587. return SQLITE_OK;
  67588. }
  67589. /* Unless an error occurs, the following loop runs one iteration for each
  67590. ** page in the B-Tree structure (not including overflow pages).
  67591. */
  67592. while( rc==SQLITE_OK ){
  67593. int iIdx; /* Index of child node in parent */
  67594. MemPage *pPage; /* Current page of the b-tree */
  67595. /* If this is a leaf page or the tree is not an int-key tree, then
  67596. ** this page contains countable entries. Increment the entry counter
  67597. ** accordingly.
  67598. */
  67599. pPage = pCur->pPage;
  67600. if( pPage->leaf || !pPage->intKey ){
  67601. nEntry += pPage->nCell;
  67602. }
  67603. /* pPage is a leaf node. This loop navigates the cursor so that it
  67604. ** points to the first interior cell that it points to the parent of
  67605. ** the next page in the tree that has not yet been visited. The
  67606. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  67607. ** of the page, or to the number of cells in the page if the next page
  67608. ** to visit is the right-child of its parent.
  67609. **
  67610. ** If all pages in the tree have been visited, return SQLITE_OK to the
  67611. ** caller.
  67612. */
  67613. if( pPage->leaf ){
  67614. do {
  67615. if( pCur->iPage==0 ){
  67616. /* All pages of the b-tree have been visited. Return successfully. */
  67617. *pnEntry = nEntry;
  67618. return moveToRoot(pCur);
  67619. }
  67620. moveToParent(pCur);
  67621. }while ( pCur->ix>=pCur->pPage->nCell );
  67622. pCur->ix++;
  67623. pPage = pCur->pPage;
  67624. }
  67625. /* Descend to the child node of the cell that the cursor currently
  67626. ** points at. This is the right-child if (iIdx==pPage->nCell).
  67627. */
  67628. iIdx = pCur->ix;
  67629. if( iIdx==pPage->nCell ){
  67630. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  67631. }else{
  67632. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  67633. }
  67634. }
  67635. /* An error has occurred. Return an error code. */
  67636. return rc;
  67637. }
  67638. #endif
  67639. /*
  67640. ** Return the pager associated with a BTree. This routine is used for
  67641. ** testing and debugging only.
  67642. */
  67643. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  67644. return p->pBt->pPager;
  67645. }
  67646. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  67647. /*
  67648. ** Append a message to the error message string.
  67649. */
  67650. static void checkAppendMsg(
  67651. IntegrityCk *pCheck,
  67652. const char *zFormat,
  67653. ...
  67654. ){
  67655. va_list ap;
  67656. if( !pCheck->mxErr ) return;
  67657. pCheck->mxErr--;
  67658. pCheck->nErr++;
  67659. va_start(ap, zFormat);
  67660. if( pCheck->errMsg.nChar ){
  67661. sqlite3_str_append(&pCheck->errMsg, "\n", 1);
  67662. }
  67663. if( pCheck->zPfx ){
  67664. sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
  67665. }
  67666. sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
  67667. va_end(ap);
  67668. if( pCheck->errMsg.accError==SQLITE_NOMEM ){
  67669. pCheck->mallocFailed = 1;
  67670. }
  67671. }
  67672. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  67673. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  67674. /*
  67675. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  67676. ** corresponds to page iPg is already set.
  67677. */
  67678. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  67679. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  67680. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  67681. }
  67682. /*
  67683. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  67684. */
  67685. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  67686. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  67687. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  67688. }
  67689. /*
  67690. ** Add 1 to the reference count for page iPage. If this is the second
  67691. ** reference to the page, add an error message to pCheck->zErrMsg.
  67692. ** Return 1 if there are 2 or more references to the page and 0 if
  67693. ** if this is the first reference to the page.
  67694. **
  67695. ** Also check that the page number is in bounds.
  67696. */
  67697. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  67698. if( iPage>pCheck->nPage || iPage==0 ){
  67699. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  67700. return 1;
  67701. }
  67702. if( getPageReferenced(pCheck, iPage) ){
  67703. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  67704. return 1;
  67705. }
  67706. setPageReferenced(pCheck, iPage);
  67707. return 0;
  67708. }
  67709. #ifndef SQLITE_OMIT_AUTOVACUUM
  67710. /*
  67711. ** Check that the entry in the pointer-map for page iChild maps to
  67712. ** page iParent, pointer type ptrType. If not, append an error message
  67713. ** to pCheck.
  67714. */
  67715. static void checkPtrmap(
  67716. IntegrityCk *pCheck, /* Integrity check context */
  67717. Pgno iChild, /* Child page number */
  67718. u8 eType, /* Expected pointer map type */
  67719. Pgno iParent /* Expected pointer map parent page number */
  67720. ){
  67721. int rc;
  67722. u8 ePtrmapType;
  67723. Pgno iPtrmapParent;
  67724. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  67725. if( rc!=SQLITE_OK ){
  67726. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  67727. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  67728. return;
  67729. }
  67730. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  67731. checkAppendMsg(pCheck,
  67732. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  67733. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  67734. }
  67735. }
  67736. #endif
  67737. /*
  67738. ** Check the integrity of the freelist or of an overflow page list.
  67739. ** Verify that the number of pages on the list is N.
  67740. */
  67741. static void checkList(
  67742. IntegrityCk *pCheck, /* Integrity checking context */
  67743. int isFreeList, /* True for a freelist. False for overflow page list */
  67744. int iPage, /* Page number for first page in the list */
  67745. int N /* Expected number of pages in the list */
  67746. ){
  67747. int i;
  67748. int expected = N;
  67749. int nErrAtStart = pCheck->nErr;
  67750. while( iPage!=0 && pCheck->mxErr ){
  67751. DbPage *pOvflPage;
  67752. unsigned char *pOvflData;
  67753. if( checkRef(pCheck, iPage) ) break;
  67754. N--;
  67755. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
  67756. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  67757. break;
  67758. }
  67759. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  67760. if( isFreeList ){
  67761. int n = get4byte(&pOvflData[4]);
  67762. #ifndef SQLITE_OMIT_AUTOVACUUM
  67763. if( pCheck->pBt->autoVacuum ){
  67764. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  67765. }
  67766. #endif
  67767. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  67768. checkAppendMsg(pCheck,
  67769. "freelist leaf count too big on page %d", iPage);
  67770. N--;
  67771. }else{
  67772. for(i=0; i<n; i++){
  67773. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  67774. #ifndef SQLITE_OMIT_AUTOVACUUM
  67775. if( pCheck->pBt->autoVacuum ){
  67776. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  67777. }
  67778. #endif
  67779. checkRef(pCheck, iFreePage);
  67780. }
  67781. N -= n;
  67782. }
  67783. }
  67784. #ifndef SQLITE_OMIT_AUTOVACUUM
  67785. else{
  67786. /* If this database supports auto-vacuum and iPage is not the last
  67787. ** page in this overflow list, check that the pointer-map entry for
  67788. ** the following page matches iPage.
  67789. */
  67790. if( pCheck->pBt->autoVacuum && N>0 ){
  67791. i = get4byte(pOvflData);
  67792. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  67793. }
  67794. }
  67795. #endif
  67796. iPage = get4byte(pOvflData);
  67797. sqlite3PagerUnref(pOvflPage);
  67798. }
  67799. if( N && nErrAtStart==pCheck->nErr ){
  67800. checkAppendMsg(pCheck,
  67801. "%s is %d but should be %d",
  67802. isFreeList ? "size" : "overflow list length",
  67803. expected-N, expected);
  67804. }
  67805. }
  67806. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  67807. /*
  67808. ** An implementation of a min-heap.
  67809. **
  67810. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  67811. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  67812. ** and aHeap[N*2+1].
  67813. **
  67814. ** The heap property is this: Every node is less than or equal to both
  67815. ** of its daughter nodes. A consequence of the heap property is that the
  67816. ** root node aHeap[1] is always the minimum value currently in the heap.
  67817. **
  67818. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  67819. ** the heap, preserving the heap property. The btreeHeapPull() routine
  67820. ** removes the root element from the heap (the minimum value in the heap)
  67821. ** and then moves other nodes around as necessary to preserve the heap
  67822. ** property.
  67823. **
  67824. ** This heap is used for cell overlap and coverage testing. Each u32
  67825. ** entry represents the span of a cell or freeblock on a btree page.
  67826. ** The upper 16 bits are the index of the first byte of a range and the
  67827. ** lower 16 bits are the index of the last byte of that range.
  67828. */
  67829. static void btreeHeapInsert(u32 *aHeap, u32 x){
  67830. u32 j, i = ++aHeap[0];
  67831. aHeap[i] = x;
  67832. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  67833. x = aHeap[j];
  67834. aHeap[j] = aHeap[i];
  67835. aHeap[i] = x;
  67836. i = j;
  67837. }
  67838. }
  67839. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  67840. u32 j, i, x;
  67841. if( (x = aHeap[0])==0 ) return 0;
  67842. *pOut = aHeap[1];
  67843. aHeap[1] = aHeap[x];
  67844. aHeap[x] = 0xffffffff;
  67845. aHeap[0]--;
  67846. i = 1;
  67847. while( (j = i*2)<=aHeap[0] ){
  67848. if( aHeap[j]>aHeap[j+1] ) j++;
  67849. if( aHeap[i]<aHeap[j] ) break;
  67850. x = aHeap[i];
  67851. aHeap[i] = aHeap[j];
  67852. aHeap[j] = x;
  67853. i = j;
  67854. }
  67855. return 1;
  67856. }
  67857. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  67858. /*
  67859. ** Do various sanity checks on a single page of a tree. Return
  67860. ** the tree depth. Root pages return 0. Parents of root pages
  67861. ** return 1, and so forth.
  67862. **
  67863. ** These checks are done:
  67864. **
  67865. ** 1. Make sure that cells and freeblocks do not overlap
  67866. ** but combine to completely cover the page.
  67867. ** 2. Make sure integer cell keys are in order.
  67868. ** 3. Check the integrity of overflow pages.
  67869. ** 4. Recursively call checkTreePage on all children.
  67870. ** 5. Verify that the depth of all children is the same.
  67871. */
  67872. static int checkTreePage(
  67873. IntegrityCk *pCheck, /* Context for the sanity check */
  67874. int iPage, /* Page number of the page to check */
  67875. i64 *piMinKey, /* Write minimum integer primary key here */
  67876. i64 maxKey /* Error if integer primary key greater than this */
  67877. ){
  67878. MemPage *pPage = 0; /* The page being analyzed */
  67879. int i; /* Loop counter */
  67880. int rc; /* Result code from subroutine call */
  67881. int depth = -1, d2; /* Depth of a subtree */
  67882. int pgno; /* Page number */
  67883. int nFrag; /* Number of fragmented bytes on the page */
  67884. int hdr; /* Offset to the page header */
  67885. int cellStart; /* Offset to the start of the cell pointer array */
  67886. int nCell; /* Number of cells */
  67887. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  67888. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  67889. ** False if IPK must be strictly less than maxKey */
  67890. u8 *data; /* Page content */
  67891. u8 *pCell; /* Cell content */
  67892. u8 *pCellIdx; /* Next element of the cell pointer array */
  67893. BtShared *pBt; /* The BtShared object that owns pPage */
  67894. u32 pc; /* Address of a cell */
  67895. u32 usableSize; /* Usable size of the page */
  67896. u32 contentOffset; /* Offset to the start of the cell content area */
  67897. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  67898. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  67899. const char *saved_zPfx = pCheck->zPfx;
  67900. int saved_v1 = pCheck->v1;
  67901. int saved_v2 = pCheck->v2;
  67902. u8 savedIsInit = 0;
  67903. /* Check that the page exists
  67904. */
  67905. pBt = pCheck->pBt;
  67906. usableSize = pBt->usableSize;
  67907. if( iPage==0 ) return 0;
  67908. if( checkRef(pCheck, iPage) ) return 0;
  67909. pCheck->zPfx = "Page %d: ";
  67910. pCheck->v1 = iPage;
  67911. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  67912. checkAppendMsg(pCheck,
  67913. "unable to get the page. error code=%d", rc);
  67914. goto end_of_check;
  67915. }
  67916. /* Clear MemPage.isInit to make sure the corruption detection code in
  67917. ** btreeInitPage() is executed. */
  67918. savedIsInit = pPage->isInit;
  67919. pPage->isInit = 0;
  67920. if( (rc = btreeInitPage(pPage))!=0 ){
  67921. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  67922. checkAppendMsg(pCheck,
  67923. "btreeInitPage() returns error code %d", rc);
  67924. goto end_of_check;
  67925. }
  67926. data = pPage->aData;
  67927. hdr = pPage->hdrOffset;
  67928. /* Set up for cell analysis */
  67929. pCheck->zPfx = "On tree page %d cell %d: ";
  67930. contentOffset = get2byteNotZero(&data[hdr+5]);
  67931. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  67932. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  67933. ** number of cells on the page. */
  67934. nCell = get2byte(&data[hdr+3]);
  67935. assert( pPage->nCell==nCell );
  67936. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  67937. ** immediately follows the b-tree page header. */
  67938. cellStart = hdr + 12 - 4*pPage->leaf;
  67939. assert( pPage->aCellIdx==&data[cellStart] );
  67940. pCellIdx = &data[cellStart + 2*(nCell-1)];
  67941. if( !pPage->leaf ){
  67942. /* Analyze the right-child page of internal pages */
  67943. pgno = get4byte(&data[hdr+8]);
  67944. #ifndef SQLITE_OMIT_AUTOVACUUM
  67945. if( pBt->autoVacuum ){
  67946. pCheck->zPfx = "On page %d at right child: ";
  67947. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  67948. }
  67949. #endif
  67950. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  67951. keyCanBeEqual = 0;
  67952. }else{
  67953. /* For leaf pages, the coverage check will occur in the same loop
  67954. ** as the other cell checks, so initialize the heap. */
  67955. heap = pCheck->heap;
  67956. heap[0] = 0;
  67957. }
  67958. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  67959. ** integer offsets to the cell contents. */
  67960. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  67961. CellInfo info;
  67962. /* Check cell size */
  67963. pCheck->v2 = i;
  67964. assert( pCellIdx==&data[cellStart + i*2] );
  67965. pc = get2byteAligned(pCellIdx);
  67966. pCellIdx -= 2;
  67967. if( pc<contentOffset || pc>usableSize-4 ){
  67968. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  67969. pc, contentOffset, usableSize-4);
  67970. doCoverageCheck = 0;
  67971. continue;
  67972. }
  67973. pCell = &data[pc];
  67974. pPage->xParseCell(pPage, pCell, &info);
  67975. if( pc+info.nSize>usableSize ){
  67976. checkAppendMsg(pCheck, "Extends off end of page");
  67977. doCoverageCheck = 0;
  67978. continue;
  67979. }
  67980. /* Check for integer primary key out of range */
  67981. if( pPage->intKey ){
  67982. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  67983. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  67984. }
  67985. maxKey = info.nKey;
  67986. keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
  67987. }
  67988. /* Check the content overflow list */
  67989. if( info.nPayload>info.nLocal ){
  67990. int nPage; /* Number of pages on the overflow chain */
  67991. Pgno pgnoOvfl; /* First page of the overflow chain */
  67992. assert( pc + info.nSize - 4 <= usableSize );
  67993. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  67994. pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
  67995. #ifndef SQLITE_OMIT_AUTOVACUUM
  67996. if( pBt->autoVacuum ){
  67997. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  67998. }
  67999. #endif
  68000. checkList(pCheck, 0, pgnoOvfl, nPage);
  68001. }
  68002. if( !pPage->leaf ){
  68003. /* Check sanity of left child page for internal pages */
  68004. pgno = get4byte(pCell);
  68005. #ifndef SQLITE_OMIT_AUTOVACUUM
  68006. if( pBt->autoVacuum ){
  68007. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  68008. }
  68009. #endif
  68010. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  68011. keyCanBeEqual = 0;
  68012. if( d2!=depth ){
  68013. checkAppendMsg(pCheck, "Child page depth differs");
  68014. depth = d2;
  68015. }
  68016. }else{
  68017. /* Populate the coverage-checking heap for leaf pages */
  68018. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  68019. }
  68020. }
  68021. *piMinKey = maxKey;
  68022. /* Check for complete coverage of the page
  68023. */
  68024. pCheck->zPfx = 0;
  68025. if( doCoverageCheck && pCheck->mxErr>0 ){
  68026. /* For leaf pages, the min-heap has already been initialized and the
  68027. ** cells have already been inserted. But for internal pages, that has
  68028. ** not yet been done, so do it now */
  68029. if( !pPage->leaf ){
  68030. heap = pCheck->heap;
  68031. heap[0] = 0;
  68032. for(i=nCell-1; i>=0; i--){
  68033. u32 size;
  68034. pc = get2byteAligned(&data[cellStart+i*2]);
  68035. size = pPage->xCellSize(pPage, &data[pc]);
  68036. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  68037. }
  68038. }
  68039. /* Add the freeblocks to the min-heap
  68040. **
  68041. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  68042. ** is the offset of the first freeblock, or zero if there are no
  68043. ** freeblocks on the page.
  68044. */
  68045. i = get2byte(&data[hdr+1]);
  68046. while( i>0 ){
  68047. int size, j;
  68048. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  68049. size = get2byte(&data[i+2]);
  68050. assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
  68051. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  68052. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  68053. ** big-endian integer which is the offset in the b-tree page of the next
  68054. ** freeblock in the chain, or zero if the freeblock is the last on the
  68055. ** chain. */
  68056. j = get2byte(&data[i]);
  68057. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  68058. ** increasing offset. */
  68059. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  68060. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  68061. i = j;
  68062. }
  68063. /* Analyze the min-heap looking for overlap between cells and/or
  68064. ** freeblocks, and counting the number of untracked bytes in nFrag.
  68065. **
  68066. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  68067. ** There is an implied first entry the covers the page header, the cell
  68068. ** pointer index, and the gap between the cell pointer index and the start
  68069. ** of cell content.
  68070. **
  68071. ** The loop below pulls entries from the min-heap in order and compares
  68072. ** the start_address against the previous end_address. If there is an
  68073. ** overlap, that means bytes are used multiple times. If there is a gap,
  68074. ** that gap is added to the fragmentation count.
  68075. */
  68076. nFrag = 0;
  68077. prev = contentOffset - 1; /* Implied first min-heap entry */
  68078. while( btreeHeapPull(heap,&x) ){
  68079. if( (prev&0xffff)>=(x>>16) ){
  68080. checkAppendMsg(pCheck,
  68081. "Multiple uses for byte %u of page %d", x>>16, iPage);
  68082. break;
  68083. }else{
  68084. nFrag += (x>>16) - (prev&0xffff) - 1;
  68085. prev = x;
  68086. }
  68087. }
  68088. nFrag += usableSize - (prev&0xffff) - 1;
  68089. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  68090. ** is stored in the fifth field of the b-tree page header.
  68091. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  68092. ** number of fragmented free bytes within the cell content area.
  68093. */
  68094. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  68095. checkAppendMsg(pCheck,
  68096. "Fragmentation of %d bytes reported as %d on page %d",
  68097. nFrag, data[hdr+7], iPage);
  68098. }
  68099. }
  68100. end_of_check:
  68101. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  68102. releasePage(pPage);
  68103. pCheck->zPfx = saved_zPfx;
  68104. pCheck->v1 = saved_v1;
  68105. pCheck->v2 = saved_v2;
  68106. return depth+1;
  68107. }
  68108. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  68109. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  68110. /*
  68111. ** This routine does a complete check of the given BTree file. aRoot[] is
  68112. ** an array of pages numbers were each page number is the root page of
  68113. ** a table. nRoot is the number of entries in aRoot.
  68114. **
  68115. ** A read-only or read-write transaction must be opened before calling
  68116. ** this function.
  68117. **
  68118. ** Write the number of error seen in *pnErr. Except for some memory
  68119. ** allocation errors, an error message held in memory obtained from
  68120. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  68121. ** returned. If a memory allocation error occurs, NULL is returned.
  68122. */
  68123. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  68124. Btree *p, /* The btree to be checked */
  68125. int *aRoot, /* An array of root pages numbers for individual trees */
  68126. int nRoot, /* Number of entries in aRoot[] */
  68127. int mxErr, /* Stop reporting errors after this many */
  68128. int *pnErr /* Write number of errors seen to this variable */
  68129. ){
  68130. Pgno i;
  68131. IntegrityCk sCheck;
  68132. BtShared *pBt = p->pBt;
  68133. int savedDbFlags = pBt->db->flags;
  68134. char zErr[100];
  68135. VVA_ONLY( int nRef );
  68136. sqlite3BtreeEnter(p);
  68137. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  68138. VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
  68139. assert( nRef>=0 );
  68140. sCheck.pBt = pBt;
  68141. sCheck.pPager = pBt->pPager;
  68142. sCheck.nPage = btreePagecount(sCheck.pBt);
  68143. sCheck.mxErr = mxErr;
  68144. sCheck.nErr = 0;
  68145. sCheck.mallocFailed = 0;
  68146. sCheck.zPfx = 0;
  68147. sCheck.v1 = 0;
  68148. sCheck.v2 = 0;
  68149. sCheck.aPgRef = 0;
  68150. sCheck.heap = 0;
  68151. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  68152. sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
  68153. if( sCheck.nPage==0 ){
  68154. goto integrity_ck_cleanup;
  68155. }
  68156. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  68157. if( !sCheck.aPgRef ){
  68158. sCheck.mallocFailed = 1;
  68159. goto integrity_ck_cleanup;
  68160. }
  68161. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  68162. if( sCheck.heap==0 ){
  68163. sCheck.mallocFailed = 1;
  68164. goto integrity_ck_cleanup;
  68165. }
  68166. i = PENDING_BYTE_PAGE(pBt);
  68167. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  68168. /* Check the integrity of the freelist
  68169. */
  68170. sCheck.zPfx = "Main freelist: ";
  68171. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  68172. get4byte(&pBt->pPage1->aData[36]));
  68173. sCheck.zPfx = 0;
  68174. /* Check all the tables.
  68175. */
  68176. #ifndef SQLITE_OMIT_AUTOVACUUM
  68177. if( pBt->autoVacuum ){
  68178. int mx = 0;
  68179. int mxInHdr;
  68180. for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
  68181. mxInHdr = get4byte(&pBt->pPage1->aData[52]);
  68182. if( mx!=mxInHdr ){
  68183. checkAppendMsg(&sCheck,
  68184. "max rootpage (%d) disagrees with header (%d)",
  68185. mx, mxInHdr
  68186. );
  68187. }
  68188. }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
  68189. checkAppendMsg(&sCheck,
  68190. "incremental_vacuum enabled with a max rootpage of zero"
  68191. );
  68192. }
  68193. #endif
  68194. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  68195. pBt->db->flags &= ~SQLITE_CellSizeCk;
  68196. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  68197. i64 notUsed;
  68198. if( aRoot[i]==0 ) continue;
  68199. #ifndef SQLITE_OMIT_AUTOVACUUM
  68200. if( pBt->autoVacuum && aRoot[i]>1 ){
  68201. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  68202. }
  68203. #endif
  68204. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  68205. }
  68206. pBt->db->flags = savedDbFlags;
  68207. /* Make sure every page in the file is referenced
  68208. */
  68209. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  68210. #ifdef SQLITE_OMIT_AUTOVACUUM
  68211. if( getPageReferenced(&sCheck, i)==0 ){
  68212. checkAppendMsg(&sCheck, "Page %d is never used", i);
  68213. }
  68214. #else
  68215. /* If the database supports auto-vacuum, make sure no tables contain
  68216. ** references to pointer-map pages.
  68217. */
  68218. if( getPageReferenced(&sCheck, i)==0 &&
  68219. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  68220. checkAppendMsg(&sCheck, "Page %d is never used", i);
  68221. }
  68222. if( getPageReferenced(&sCheck, i)!=0 &&
  68223. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  68224. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  68225. }
  68226. #endif
  68227. }
  68228. /* Clean up and report errors.
  68229. */
  68230. integrity_ck_cleanup:
  68231. sqlite3PageFree(sCheck.heap);
  68232. sqlite3_free(sCheck.aPgRef);
  68233. if( sCheck.mallocFailed ){
  68234. sqlite3_str_reset(&sCheck.errMsg);
  68235. sCheck.nErr++;
  68236. }
  68237. *pnErr = sCheck.nErr;
  68238. if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
  68239. /* Make sure this analysis did not leave any unref() pages. */
  68240. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  68241. sqlite3BtreeLeave(p);
  68242. return sqlite3StrAccumFinish(&sCheck.errMsg);
  68243. }
  68244. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  68245. /*
  68246. ** Return the full pathname of the underlying database file. Return
  68247. ** an empty string if the database is in-memory or a TEMP database.
  68248. **
  68249. ** The pager filename is invariant as long as the pager is
  68250. ** open so it is safe to access without the BtShared mutex.
  68251. */
  68252. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  68253. assert( p->pBt->pPager!=0 );
  68254. return sqlite3PagerFilename(p->pBt->pPager, 1);
  68255. }
  68256. /*
  68257. ** Return the pathname of the journal file for this database. The return
  68258. ** value of this routine is the same regardless of whether the journal file
  68259. ** has been created or not.
  68260. **
  68261. ** The pager journal filename is invariant as long as the pager is
  68262. ** open so it is safe to access without the BtShared mutex.
  68263. */
  68264. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  68265. assert( p->pBt->pPager!=0 );
  68266. return sqlite3PagerJournalname(p->pBt->pPager);
  68267. }
  68268. /*
  68269. ** Return non-zero if a transaction is active.
  68270. */
  68271. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  68272. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  68273. return (p && (p->inTrans==TRANS_WRITE));
  68274. }
  68275. #ifndef SQLITE_OMIT_WAL
  68276. /*
  68277. ** Run a checkpoint on the Btree passed as the first argument.
  68278. **
  68279. ** Return SQLITE_LOCKED if this or any other connection has an open
  68280. ** transaction on the shared-cache the argument Btree is connected to.
  68281. **
  68282. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  68283. */
  68284. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  68285. int rc = SQLITE_OK;
  68286. if( p ){
  68287. BtShared *pBt = p->pBt;
  68288. sqlite3BtreeEnter(p);
  68289. if( pBt->inTransaction!=TRANS_NONE ){
  68290. rc = SQLITE_LOCKED;
  68291. }else{
  68292. rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
  68293. }
  68294. sqlite3BtreeLeave(p);
  68295. }
  68296. return rc;
  68297. }
  68298. #endif
  68299. /*
  68300. ** Return non-zero if a read (or write) transaction is active.
  68301. */
  68302. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  68303. assert( p );
  68304. assert( sqlite3_mutex_held(p->db->mutex) );
  68305. return p->inTrans!=TRANS_NONE;
  68306. }
  68307. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  68308. assert( p );
  68309. assert( sqlite3_mutex_held(p->db->mutex) );
  68310. return p->nBackup!=0;
  68311. }
  68312. /*
  68313. ** This function returns a pointer to a blob of memory associated with
  68314. ** a single shared-btree. The memory is used by client code for its own
  68315. ** purposes (for example, to store a high-level schema associated with
  68316. ** the shared-btree). The btree layer manages reference counting issues.
  68317. **
  68318. ** The first time this is called on a shared-btree, nBytes bytes of memory
  68319. ** are allocated, zeroed, and returned to the caller. For each subsequent
  68320. ** call the nBytes parameter is ignored and a pointer to the same blob
  68321. ** of memory returned.
  68322. **
  68323. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  68324. ** allocated, a null pointer is returned. If the blob has already been
  68325. ** allocated, it is returned as normal.
  68326. **
  68327. ** Just before the shared-btree is closed, the function passed as the
  68328. ** xFree argument when the memory allocation was made is invoked on the
  68329. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  68330. ** on the memory, the btree layer does that.
  68331. */
  68332. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  68333. BtShared *pBt = p->pBt;
  68334. sqlite3BtreeEnter(p);
  68335. if( !pBt->pSchema && nBytes ){
  68336. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  68337. pBt->xFreeSchema = xFree;
  68338. }
  68339. sqlite3BtreeLeave(p);
  68340. return pBt->pSchema;
  68341. }
  68342. /*
  68343. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  68344. ** btree as the argument handle holds an exclusive lock on the
  68345. ** sqlite_master table. Otherwise SQLITE_OK.
  68346. */
  68347. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  68348. int rc;
  68349. assert( sqlite3_mutex_held(p->db->mutex) );
  68350. sqlite3BtreeEnter(p);
  68351. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  68352. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  68353. sqlite3BtreeLeave(p);
  68354. return rc;
  68355. }
  68356. #ifndef SQLITE_OMIT_SHARED_CACHE
  68357. /*
  68358. ** Obtain a lock on the table whose root page is iTab. The
  68359. ** lock is a write lock if isWritelock is true or a read lock
  68360. ** if it is false.
  68361. */
  68362. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  68363. int rc = SQLITE_OK;
  68364. assert( p->inTrans!=TRANS_NONE );
  68365. if( p->sharable ){
  68366. u8 lockType = READ_LOCK + isWriteLock;
  68367. assert( READ_LOCK+1==WRITE_LOCK );
  68368. assert( isWriteLock==0 || isWriteLock==1 );
  68369. sqlite3BtreeEnter(p);
  68370. rc = querySharedCacheTableLock(p, iTab, lockType);
  68371. if( rc==SQLITE_OK ){
  68372. rc = setSharedCacheTableLock(p, iTab, lockType);
  68373. }
  68374. sqlite3BtreeLeave(p);
  68375. }
  68376. return rc;
  68377. }
  68378. #endif
  68379. #ifndef SQLITE_OMIT_INCRBLOB
  68380. /*
  68381. ** Argument pCsr must be a cursor opened for writing on an
  68382. ** INTKEY table currently pointing at a valid table entry.
  68383. ** This function modifies the data stored as part of that entry.
  68384. **
  68385. ** Only the data content may only be modified, it is not possible to
  68386. ** change the length of the data stored. If this function is called with
  68387. ** parameters that attempt to write past the end of the existing data,
  68388. ** no modifications are made and SQLITE_CORRUPT is returned.
  68389. */
  68390. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  68391. int rc;
  68392. assert( cursorOwnsBtShared(pCsr) );
  68393. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  68394. assert( pCsr->curFlags & BTCF_Incrblob );
  68395. rc = restoreCursorPosition(pCsr);
  68396. if( rc!=SQLITE_OK ){
  68397. return rc;
  68398. }
  68399. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  68400. if( pCsr->eState!=CURSOR_VALID ){
  68401. return SQLITE_ABORT;
  68402. }
  68403. /* Save the positions of all other cursors open on this table. This is
  68404. ** required in case any of them are holding references to an xFetch
  68405. ** version of the b-tree page modified by the accessPayload call below.
  68406. **
  68407. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  68408. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  68409. ** saveAllCursors can only return SQLITE_OK.
  68410. */
  68411. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  68412. assert( rc==SQLITE_OK );
  68413. /* Check some assumptions:
  68414. ** (a) the cursor is open for writing,
  68415. ** (b) there is a read/write transaction open,
  68416. ** (c) the connection holds a write-lock on the table (if required),
  68417. ** (d) there are no conflicting read-locks, and
  68418. ** (e) the cursor points at a valid row of an intKey table.
  68419. */
  68420. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  68421. return SQLITE_READONLY;
  68422. }
  68423. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  68424. && pCsr->pBt->inTransaction==TRANS_WRITE );
  68425. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  68426. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  68427. assert( pCsr->pPage->intKey );
  68428. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  68429. }
  68430. /*
  68431. ** Mark this cursor as an incremental blob cursor.
  68432. */
  68433. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  68434. pCur->curFlags |= BTCF_Incrblob;
  68435. pCur->pBtree->hasIncrblobCur = 1;
  68436. }
  68437. #endif
  68438. /*
  68439. ** Set both the "read version" (single byte at byte offset 18) and
  68440. ** "write version" (single byte at byte offset 19) fields in the database
  68441. ** header to iVersion.
  68442. */
  68443. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  68444. BtShared *pBt = pBtree->pBt;
  68445. int rc; /* Return code */
  68446. assert( iVersion==1 || iVersion==2 );
  68447. /* If setting the version fields to 1, do not automatically open the
  68448. ** WAL connection, even if the version fields are currently set to 2.
  68449. */
  68450. pBt->btsFlags &= ~BTS_NO_WAL;
  68451. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  68452. rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
  68453. if( rc==SQLITE_OK ){
  68454. u8 *aData = pBt->pPage1->aData;
  68455. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  68456. rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
  68457. if( rc==SQLITE_OK ){
  68458. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  68459. if( rc==SQLITE_OK ){
  68460. aData[18] = (u8)iVersion;
  68461. aData[19] = (u8)iVersion;
  68462. }
  68463. }
  68464. }
  68465. }
  68466. pBt->btsFlags &= ~BTS_NO_WAL;
  68467. return rc;
  68468. }
  68469. /*
  68470. ** Return true if the cursor has a hint specified. This routine is
  68471. ** only used from within assert() statements
  68472. */
  68473. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  68474. return (pCsr->hints & mask)!=0;
  68475. }
  68476. /*
  68477. ** Return true if the given Btree is read-only.
  68478. */
  68479. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  68480. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  68481. }
  68482. /*
  68483. ** Return the size of the header added to each page by this module.
  68484. */
  68485. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  68486. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  68487. /*
  68488. ** Return true if the Btree passed as the only argument is sharable.
  68489. */
  68490. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  68491. return p->sharable;
  68492. }
  68493. /*
  68494. ** Return the number of connections to the BtShared object accessed by
  68495. ** the Btree handle passed as the only argument. For private caches
  68496. ** this is always 1. For shared caches it may be 1 or greater.
  68497. */
  68498. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
  68499. testcase( p->sharable );
  68500. return p->pBt->nRef;
  68501. }
  68502. #endif
  68503. /************** End of btree.c ***********************************************/
  68504. /************** Begin file backup.c ******************************************/
  68505. /*
  68506. ** 2009 January 28
  68507. **
  68508. ** The author disclaims copyright to this source code. In place of
  68509. ** a legal notice, here is a blessing:
  68510. **
  68511. ** May you do good and not evil.
  68512. ** May you find forgiveness for yourself and forgive others.
  68513. ** May you share freely, never taking more than you give.
  68514. **
  68515. *************************************************************************
  68516. ** This file contains the implementation of the sqlite3_backup_XXX()
  68517. ** API functions and the related features.
  68518. */
  68519. /* #include "sqliteInt.h" */
  68520. /* #include "btreeInt.h" */
  68521. /*
  68522. ** Structure allocated for each backup operation.
  68523. */
  68524. struct sqlite3_backup {
  68525. sqlite3* pDestDb; /* Destination database handle */
  68526. Btree *pDest; /* Destination b-tree file */
  68527. u32 iDestSchema; /* Original schema cookie in destination */
  68528. int bDestLocked; /* True once a write-transaction is open on pDest */
  68529. Pgno iNext; /* Page number of the next source page to copy */
  68530. sqlite3* pSrcDb; /* Source database handle */
  68531. Btree *pSrc; /* Source b-tree file */
  68532. int rc; /* Backup process error code */
  68533. /* These two variables are set by every call to backup_step(). They are
  68534. ** read by calls to backup_remaining() and backup_pagecount().
  68535. */
  68536. Pgno nRemaining; /* Number of pages left to copy */
  68537. Pgno nPagecount; /* Total number of pages to copy */
  68538. int isAttached; /* True once backup has been registered with pager */
  68539. sqlite3_backup *pNext; /* Next backup associated with source pager */
  68540. };
  68541. /*
  68542. ** THREAD SAFETY NOTES:
  68543. **
  68544. ** Once it has been created using backup_init(), a single sqlite3_backup
  68545. ** structure may be accessed via two groups of thread-safe entry points:
  68546. **
  68547. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  68548. ** backup_finish(). Both these functions obtain the source database
  68549. ** handle mutex and the mutex associated with the source BtShared
  68550. ** structure, in that order.
  68551. **
  68552. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  68553. ** invoked by the pager layer to report various state changes in
  68554. ** the page cache associated with the source database. The mutex
  68555. ** associated with the source database BtShared structure will always
  68556. ** be held when either of these functions are invoked.
  68557. **
  68558. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  68559. ** backup_pagecount() are not thread-safe functions. If they are called
  68560. ** while some other thread is calling backup_step() or backup_finish(),
  68561. ** the values returned may be invalid. There is no way for a call to
  68562. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  68563. ** or backup_pagecount().
  68564. **
  68565. ** Depending on the SQLite configuration, the database handles and/or
  68566. ** the Btree objects may have their own mutexes that require locking.
  68567. ** Non-sharable Btrees (in-memory databases for example), do not have
  68568. ** associated mutexes.
  68569. */
  68570. /*
  68571. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  68572. ** in connection handle pDb. If such a database cannot be found, return
  68573. ** a NULL pointer and write an error message to pErrorDb.
  68574. **
  68575. ** If the "temp" database is requested, it may need to be opened by this
  68576. ** function. If an error occurs while doing so, return 0 and write an
  68577. ** error message to pErrorDb.
  68578. */
  68579. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  68580. int i = sqlite3FindDbName(pDb, zDb);
  68581. if( i==1 ){
  68582. Parse sParse;
  68583. int rc = 0;
  68584. memset(&sParse, 0, sizeof(sParse));
  68585. sParse.db = pDb;
  68586. if( sqlite3OpenTempDatabase(&sParse) ){
  68587. sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
  68588. rc = SQLITE_ERROR;
  68589. }
  68590. sqlite3DbFree(pErrorDb, sParse.zErrMsg);
  68591. sqlite3ParserReset(&sParse);
  68592. if( rc ){
  68593. return 0;
  68594. }
  68595. }
  68596. if( i<0 ){
  68597. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  68598. return 0;
  68599. }
  68600. return pDb->aDb[i].pBt;
  68601. }
  68602. /*
  68603. ** Attempt to set the page size of the destination to match the page size
  68604. ** of the source.
  68605. */
  68606. static int setDestPgsz(sqlite3_backup *p){
  68607. int rc;
  68608. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  68609. return rc;
  68610. }
  68611. /*
  68612. ** Check that there is no open read-transaction on the b-tree passed as the
  68613. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  68614. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  68615. ** message in database handle db.
  68616. */
  68617. static int checkReadTransaction(sqlite3 *db, Btree *p){
  68618. if( sqlite3BtreeIsInReadTrans(p) ){
  68619. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  68620. return SQLITE_ERROR;
  68621. }
  68622. return SQLITE_OK;
  68623. }
  68624. /*
  68625. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  68626. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  68627. ** a pointer to the new sqlite3_backup object.
  68628. **
  68629. ** If an error occurs, NULL is returned and an error code and error message
  68630. ** stored in database handle pDestDb.
  68631. */
  68632. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  68633. sqlite3* pDestDb, /* Database to write to */
  68634. const char *zDestDb, /* Name of database within pDestDb */
  68635. sqlite3* pSrcDb, /* Database connection to read from */
  68636. const char *zSrcDb /* Name of database within pSrcDb */
  68637. ){
  68638. sqlite3_backup *p; /* Value to return */
  68639. #ifdef SQLITE_ENABLE_API_ARMOR
  68640. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  68641. (void)SQLITE_MISUSE_BKPT;
  68642. return 0;
  68643. }
  68644. #endif
  68645. /* Lock the source database handle. The destination database
  68646. ** handle is not locked in this routine, but it is locked in
  68647. ** sqlite3_backup_step(). The user is required to ensure that no
  68648. ** other thread accesses the destination handle for the duration
  68649. ** of the backup operation. Any attempt to use the destination
  68650. ** database connection while a backup is in progress may cause
  68651. ** a malfunction or a deadlock.
  68652. */
  68653. sqlite3_mutex_enter(pSrcDb->mutex);
  68654. sqlite3_mutex_enter(pDestDb->mutex);
  68655. if( pSrcDb==pDestDb ){
  68656. sqlite3ErrorWithMsg(
  68657. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  68658. );
  68659. p = 0;
  68660. }else {
  68661. /* Allocate space for a new sqlite3_backup object...
  68662. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  68663. ** call to sqlite3_backup_init() and is destroyed by a call to
  68664. ** sqlite3_backup_finish(). */
  68665. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  68666. if( !p ){
  68667. sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
  68668. }
  68669. }
  68670. /* If the allocation succeeded, populate the new object. */
  68671. if( p ){
  68672. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  68673. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  68674. p->pDestDb = pDestDb;
  68675. p->pSrcDb = pSrcDb;
  68676. p->iNext = 1;
  68677. p->isAttached = 0;
  68678. if( 0==p->pSrc || 0==p->pDest
  68679. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  68680. ){
  68681. /* One (or both) of the named databases did not exist or an OOM
  68682. ** error was hit. Or there is a transaction open on the destination
  68683. ** database. The error has already been written into the pDestDb
  68684. ** handle. All that is left to do here is free the sqlite3_backup
  68685. ** structure. */
  68686. sqlite3_free(p);
  68687. p = 0;
  68688. }
  68689. }
  68690. if( p ){
  68691. p->pSrc->nBackup++;
  68692. }
  68693. sqlite3_mutex_leave(pDestDb->mutex);
  68694. sqlite3_mutex_leave(pSrcDb->mutex);
  68695. return p;
  68696. }
  68697. /*
  68698. ** Argument rc is an SQLite error code. Return true if this error is
  68699. ** considered fatal if encountered during a backup operation. All errors
  68700. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  68701. */
  68702. static int isFatalError(int rc){
  68703. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  68704. }
  68705. /*
  68706. ** Parameter zSrcData points to a buffer containing the data for
  68707. ** page iSrcPg from the source database. Copy this data into the
  68708. ** destination database.
  68709. */
  68710. static int backupOnePage(
  68711. sqlite3_backup *p, /* Backup handle */
  68712. Pgno iSrcPg, /* Source database page to backup */
  68713. const u8 *zSrcData, /* Source database page data */
  68714. int bUpdate /* True for an update, false otherwise */
  68715. ){
  68716. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  68717. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  68718. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  68719. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  68720. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  68721. #ifdef SQLITE_HAS_CODEC
  68722. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  68723. ** guaranteed that the shared-mutex is held by this thread, handle
  68724. ** p->pSrc may not actually be the owner. */
  68725. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  68726. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  68727. #endif
  68728. int rc = SQLITE_OK;
  68729. i64 iOff;
  68730. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  68731. assert( p->bDestLocked );
  68732. assert( !isFatalError(p->rc) );
  68733. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  68734. assert( zSrcData );
  68735. /* Catch the case where the destination is an in-memory database and the
  68736. ** page sizes of the source and destination differ.
  68737. */
  68738. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  68739. rc = SQLITE_READONLY;
  68740. }
  68741. #ifdef SQLITE_HAS_CODEC
  68742. /* Backup is not possible if the page size of the destination is changing
  68743. ** and a codec is in use.
  68744. */
  68745. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  68746. rc = SQLITE_READONLY;
  68747. }
  68748. /* Backup is not possible if the number of bytes of reserve space differ
  68749. ** between source and destination. If there is a difference, try to
  68750. ** fix the destination to agree with the source. If that is not possible,
  68751. ** then the backup cannot proceed.
  68752. */
  68753. if( nSrcReserve!=nDestReserve ){
  68754. u32 newPgsz = nSrcPgsz;
  68755. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  68756. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  68757. }
  68758. #endif
  68759. /* This loop runs once for each destination page spanned by the source
  68760. ** page. For each iteration, variable iOff is set to the byte offset
  68761. ** of the destination page.
  68762. */
  68763. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  68764. DbPage *pDestPg = 0;
  68765. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  68766. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  68767. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
  68768. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  68769. ){
  68770. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  68771. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  68772. u8 *zOut = &zDestData[iOff%nDestPgsz];
  68773. /* Copy the data from the source page into the destination page.
  68774. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  68775. ** and the pager code use this trick (clearing the first byte
  68776. ** of the page 'extra' space to invalidate the Btree layers
  68777. ** cached parse of the page). MemPage.isInit is marked
  68778. ** "MUST BE FIRST" for this purpose.
  68779. */
  68780. memcpy(zOut, zIn, nCopy);
  68781. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  68782. if( iOff==0 && bUpdate==0 ){
  68783. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  68784. }
  68785. }
  68786. sqlite3PagerUnref(pDestPg);
  68787. }
  68788. return rc;
  68789. }
  68790. /*
  68791. ** If pFile is currently larger than iSize bytes, then truncate it to
  68792. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  68793. ** this function is a no-op.
  68794. **
  68795. ** Return SQLITE_OK if everything is successful, or an SQLite error
  68796. ** code if an error occurs.
  68797. */
  68798. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  68799. i64 iCurrent;
  68800. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  68801. if( rc==SQLITE_OK && iCurrent>iSize ){
  68802. rc = sqlite3OsTruncate(pFile, iSize);
  68803. }
  68804. return rc;
  68805. }
  68806. /*
  68807. ** Register this backup object with the associated source pager for
  68808. ** callbacks when pages are changed or the cache invalidated.
  68809. */
  68810. static void attachBackupObject(sqlite3_backup *p){
  68811. sqlite3_backup **pp;
  68812. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  68813. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  68814. p->pNext = *pp;
  68815. *pp = p;
  68816. p->isAttached = 1;
  68817. }
  68818. /*
  68819. ** Copy nPage pages from the source b-tree to the destination.
  68820. */
  68821. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  68822. int rc;
  68823. int destMode; /* Destination journal mode */
  68824. int pgszSrc = 0; /* Source page size */
  68825. int pgszDest = 0; /* Destination page size */
  68826. #ifdef SQLITE_ENABLE_API_ARMOR
  68827. if( p==0 ) return SQLITE_MISUSE_BKPT;
  68828. #endif
  68829. sqlite3_mutex_enter(p->pSrcDb->mutex);
  68830. sqlite3BtreeEnter(p->pSrc);
  68831. if( p->pDestDb ){
  68832. sqlite3_mutex_enter(p->pDestDb->mutex);
  68833. }
  68834. rc = p->rc;
  68835. if( !isFatalError(rc) ){
  68836. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  68837. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  68838. int ii; /* Iterator variable */
  68839. int nSrcPage = -1; /* Size of source db in pages */
  68840. int bCloseTrans = 0; /* True if src db requires unlocking */
  68841. /* If the source pager is currently in a write-transaction, return
  68842. ** SQLITE_BUSY immediately.
  68843. */
  68844. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  68845. rc = SQLITE_BUSY;
  68846. }else{
  68847. rc = SQLITE_OK;
  68848. }
  68849. /* If there is no open read-transaction on the source database, open
  68850. ** one now. If a transaction is opened here, then it will be closed
  68851. ** before this function exits.
  68852. */
  68853. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  68854. rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
  68855. bCloseTrans = 1;
  68856. }
  68857. /* If the destination database has not yet been locked (i.e. if this
  68858. ** is the first call to backup_step() for the current backup operation),
  68859. ** try to set its page size to the same as the source database. This
  68860. ** is especially important on ZipVFS systems, as in that case it is
  68861. ** not possible to create a database file that uses one page size by
  68862. ** writing to it with another. */
  68863. if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
  68864. rc = SQLITE_NOMEM;
  68865. }
  68866. /* Lock the destination database, if it is not locked already. */
  68867. if( SQLITE_OK==rc && p->bDestLocked==0
  68868. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
  68869. (int*)&p->iDestSchema))
  68870. ){
  68871. p->bDestLocked = 1;
  68872. }
  68873. /* Do not allow backup if the destination database is in WAL mode
  68874. ** and the page sizes are different between source and destination */
  68875. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  68876. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  68877. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  68878. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  68879. rc = SQLITE_READONLY;
  68880. }
  68881. /* Now that there is a read-lock on the source database, query the
  68882. ** source pager for the number of pages in the database.
  68883. */
  68884. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  68885. assert( nSrcPage>=0 );
  68886. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  68887. const Pgno iSrcPg = p->iNext; /* Source page number */
  68888. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  68889. DbPage *pSrcPg; /* Source page object */
  68890. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
  68891. if( rc==SQLITE_OK ){
  68892. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  68893. sqlite3PagerUnref(pSrcPg);
  68894. }
  68895. }
  68896. p->iNext++;
  68897. }
  68898. if( rc==SQLITE_OK ){
  68899. p->nPagecount = nSrcPage;
  68900. p->nRemaining = nSrcPage+1-p->iNext;
  68901. if( p->iNext>(Pgno)nSrcPage ){
  68902. rc = SQLITE_DONE;
  68903. }else if( !p->isAttached ){
  68904. attachBackupObject(p);
  68905. }
  68906. }
  68907. /* Update the schema version field in the destination database. This
  68908. ** is to make sure that the schema-version really does change in
  68909. ** the case where the source and destination databases have the
  68910. ** same schema version.
  68911. */
  68912. if( rc==SQLITE_DONE ){
  68913. if( nSrcPage==0 ){
  68914. rc = sqlite3BtreeNewDb(p->pDest);
  68915. nSrcPage = 1;
  68916. }
  68917. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  68918. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  68919. }
  68920. if( rc==SQLITE_OK ){
  68921. if( p->pDestDb ){
  68922. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  68923. }
  68924. if( destMode==PAGER_JOURNALMODE_WAL ){
  68925. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  68926. }
  68927. }
  68928. if( rc==SQLITE_OK ){
  68929. int nDestTruncate;
  68930. /* Set nDestTruncate to the final number of pages in the destination
  68931. ** database. The complication here is that the destination page
  68932. ** size may be different to the source page size.
  68933. **
  68934. ** If the source page size is smaller than the destination page size,
  68935. ** round up. In this case the call to sqlite3OsTruncate() below will
  68936. ** fix the size of the file. However it is important to call
  68937. ** sqlite3PagerTruncateImage() here so that any pages in the
  68938. ** destination file that lie beyond the nDestTruncate page mark are
  68939. ** journalled by PagerCommitPhaseOne() before they are destroyed
  68940. ** by the file truncation.
  68941. */
  68942. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  68943. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  68944. if( pgszSrc<pgszDest ){
  68945. int ratio = pgszDest/pgszSrc;
  68946. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  68947. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  68948. nDestTruncate--;
  68949. }
  68950. }else{
  68951. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  68952. }
  68953. assert( nDestTruncate>0 );
  68954. if( pgszSrc<pgszDest ){
  68955. /* If the source page-size is smaller than the destination page-size,
  68956. ** two extra things may need to happen:
  68957. **
  68958. ** * The destination may need to be truncated, and
  68959. **
  68960. ** * Data stored on the pages immediately following the
  68961. ** pending-byte page in the source database may need to be
  68962. ** copied into the destination database.
  68963. */
  68964. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  68965. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  68966. Pgno iPg;
  68967. int nDstPage;
  68968. i64 iOff;
  68969. i64 iEnd;
  68970. assert( pFile );
  68971. assert( nDestTruncate==0
  68972. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  68973. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  68974. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  68975. ));
  68976. /* This block ensures that all data required to recreate the original
  68977. ** database has been stored in the journal for pDestPager and the
  68978. ** journal synced to disk. So at this point we may safely modify
  68979. ** the database file in any way, knowing that if a power failure
  68980. ** occurs, the original database will be reconstructed from the
  68981. ** journal file. */
  68982. sqlite3PagerPagecount(pDestPager, &nDstPage);
  68983. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  68984. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  68985. DbPage *pPg;
  68986. rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
  68987. if( rc==SQLITE_OK ){
  68988. rc = sqlite3PagerWrite(pPg);
  68989. sqlite3PagerUnref(pPg);
  68990. }
  68991. }
  68992. }
  68993. if( rc==SQLITE_OK ){
  68994. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  68995. }
  68996. /* Write the extra pages and truncate the database file as required */
  68997. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  68998. for(
  68999. iOff=PENDING_BYTE+pgszSrc;
  69000. rc==SQLITE_OK && iOff<iEnd;
  69001. iOff+=pgszSrc
  69002. ){
  69003. PgHdr *pSrcPg = 0;
  69004. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  69005. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
  69006. if( rc==SQLITE_OK ){
  69007. u8 *zData = sqlite3PagerGetData(pSrcPg);
  69008. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  69009. }
  69010. sqlite3PagerUnref(pSrcPg);
  69011. }
  69012. if( rc==SQLITE_OK ){
  69013. rc = backupTruncateFile(pFile, iSize);
  69014. }
  69015. /* Sync the database file to disk. */
  69016. if( rc==SQLITE_OK ){
  69017. rc = sqlite3PagerSync(pDestPager, 0);
  69018. }
  69019. }else{
  69020. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  69021. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  69022. }
  69023. /* Finish committing the transaction to the destination database. */
  69024. if( SQLITE_OK==rc
  69025. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  69026. ){
  69027. rc = SQLITE_DONE;
  69028. }
  69029. }
  69030. }
  69031. /* If bCloseTrans is true, then this function opened a read transaction
  69032. ** on the source database. Close the read transaction here. There is
  69033. ** no need to check the return values of the btree methods here, as
  69034. ** "committing" a read-only transaction cannot fail.
  69035. */
  69036. if( bCloseTrans ){
  69037. TESTONLY( int rc2 );
  69038. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  69039. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  69040. assert( rc2==SQLITE_OK );
  69041. }
  69042. if( rc==SQLITE_IOERR_NOMEM ){
  69043. rc = SQLITE_NOMEM_BKPT;
  69044. }
  69045. p->rc = rc;
  69046. }
  69047. if( p->pDestDb ){
  69048. sqlite3_mutex_leave(p->pDestDb->mutex);
  69049. }
  69050. sqlite3BtreeLeave(p->pSrc);
  69051. sqlite3_mutex_leave(p->pSrcDb->mutex);
  69052. return rc;
  69053. }
  69054. /*
  69055. ** Release all resources associated with an sqlite3_backup* handle.
  69056. */
  69057. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  69058. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  69059. sqlite3 *pSrcDb; /* Source database connection */
  69060. int rc; /* Value to return */
  69061. /* Enter the mutexes */
  69062. if( p==0 ) return SQLITE_OK;
  69063. pSrcDb = p->pSrcDb;
  69064. sqlite3_mutex_enter(pSrcDb->mutex);
  69065. sqlite3BtreeEnter(p->pSrc);
  69066. if( p->pDestDb ){
  69067. sqlite3_mutex_enter(p->pDestDb->mutex);
  69068. }
  69069. /* Detach this backup from the source pager. */
  69070. if( p->pDestDb ){
  69071. p->pSrc->nBackup--;
  69072. }
  69073. if( p->isAttached ){
  69074. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  69075. while( *pp!=p ){
  69076. pp = &(*pp)->pNext;
  69077. }
  69078. *pp = p->pNext;
  69079. }
  69080. /* If a transaction is still open on the Btree, roll it back. */
  69081. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  69082. /* Set the error code of the destination database handle. */
  69083. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  69084. if( p->pDestDb ){
  69085. sqlite3Error(p->pDestDb, rc);
  69086. /* Exit the mutexes and free the backup context structure. */
  69087. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  69088. }
  69089. sqlite3BtreeLeave(p->pSrc);
  69090. if( p->pDestDb ){
  69091. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  69092. ** call to sqlite3_backup_init() and is destroyed by a call to
  69093. ** sqlite3_backup_finish(). */
  69094. sqlite3_free(p);
  69095. }
  69096. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  69097. return rc;
  69098. }
  69099. /*
  69100. ** Return the number of pages still to be backed up as of the most recent
  69101. ** call to sqlite3_backup_step().
  69102. */
  69103. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  69104. #ifdef SQLITE_ENABLE_API_ARMOR
  69105. if( p==0 ){
  69106. (void)SQLITE_MISUSE_BKPT;
  69107. return 0;
  69108. }
  69109. #endif
  69110. return p->nRemaining;
  69111. }
  69112. /*
  69113. ** Return the total number of pages in the source database as of the most
  69114. ** recent call to sqlite3_backup_step().
  69115. */
  69116. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  69117. #ifdef SQLITE_ENABLE_API_ARMOR
  69118. if( p==0 ){
  69119. (void)SQLITE_MISUSE_BKPT;
  69120. return 0;
  69121. }
  69122. #endif
  69123. return p->nPagecount;
  69124. }
  69125. /*
  69126. ** This function is called after the contents of page iPage of the
  69127. ** source database have been modified. If page iPage has already been
  69128. ** copied into the destination database, then the data written to the
  69129. ** destination is now invalidated. The destination copy of iPage needs
  69130. ** to be updated with the new data before the backup operation is
  69131. ** complete.
  69132. **
  69133. ** It is assumed that the mutex associated with the BtShared object
  69134. ** corresponding to the source database is held when this function is
  69135. ** called.
  69136. */
  69137. static SQLITE_NOINLINE void backupUpdate(
  69138. sqlite3_backup *p,
  69139. Pgno iPage,
  69140. const u8 *aData
  69141. ){
  69142. assert( p!=0 );
  69143. do{
  69144. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  69145. if( !isFatalError(p->rc) && iPage<p->iNext ){
  69146. /* The backup process p has already copied page iPage. But now it
  69147. ** has been modified by a transaction on the source pager. Copy
  69148. ** the new data into the backup.
  69149. */
  69150. int rc;
  69151. assert( p->pDestDb );
  69152. sqlite3_mutex_enter(p->pDestDb->mutex);
  69153. rc = backupOnePage(p, iPage, aData, 1);
  69154. sqlite3_mutex_leave(p->pDestDb->mutex);
  69155. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  69156. if( rc!=SQLITE_OK ){
  69157. p->rc = rc;
  69158. }
  69159. }
  69160. }while( (p = p->pNext)!=0 );
  69161. }
  69162. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  69163. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  69164. }
  69165. /*
  69166. ** Restart the backup process. This is called when the pager layer
  69167. ** detects that the database has been modified by an external database
  69168. ** connection. In this case there is no way of knowing which of the
  69169. ** pages that have been copied into the destination database are still
  69170. ** valid and which are not, so the entire process needs to be restarted.
  69171. **
  69172. ** It is assumed that the mutex associated with the BtShared object
  69173. ** corresponding to the source database is held when this function is
  69174. ** called.
  69175. */
  69176. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  69177. sqlite3_backup *p; /* Iterator variable */
  69178. for(p=pBackup; p; p=p->pNext){
  69179. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  69180. p->iNext = 1;
  69181. }
  69182. }
  69183. #ifndef SQLITE_OMIT_VACUUM
  69184. /*
  69185. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  69186. ** must be active for both files.
  69187. **
  69188. ** The size of file pTo may be reduced by this operation. If anything
  69189. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  69190. ** transaction is committed before returning.
  69191. */
  69192. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  69193. int rc;
  69194. sqlite3_file *pFd; /* File descriptor for database pTo */
  69195. sqlite3_backup b;
  69196. sqlite3BtreeEnter(pTo);
  69197. sqlite3BtreeEnter(pFrom);
  69198. assert( sqlite3BtreeIsInTrans(pTo) );
  69199. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  69200. if( pFd->pMethods ){
  69201. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  69202. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  69203. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  69204. if( rc ) goto copy_finished;
  69205. }
  69206. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  69207. ** to 0. This is used by the implementations of sqlite3_backup_step()
  69208. ** and sqlite3_backup_finish() to detect that they are being called
  69209. ** from this function, not directly by the user.
  69210. */
  69211. memset(&b, 0, sizeof(b));
  69212. b.pSrcDb = pFrom->db;
  69213. b.pSrc = pFrom;
  69214. b.pDest = pTo;
  69215. b.iNext = 1;
  69216. #ifdef SQLITE_HAS_CODEC
  69217. sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
  69218. #endif
  69219. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  69220. ** file. By passing this as the number of pages to copy to
  69221. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  69222. ** within a single call (unless an error occurs). The assert() statement
  69223. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  69224. ** or an error code. */
  69225. sqlite3_backup_step(&b, 0x7FFFFFFF);
  69226. assert( b.rc!=SQLITE_OK );
  69227. rc = sqlite3_backup_finish(&b);
  69228. if( rc==SQLITE_OK ){
  69229. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  69230. }else{
  69231. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  69232. }
  69233. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  69234. copy_finished:
  69235. sqlite3BtreeLeave(pFrom);
  69236. sqlite3BtreeLeave(pTo);
  69237. return rc;
  69238. }
  69239. #endif /* SQLITE_OMIT_VACUUM */
  69240. /************** End of backup.c **********************************************/
  69241. /************** Begin file vdbemem.c *****************************************/
  69242. /*
  69243. ** 2004 May 26
  69244. **
  69245. ** The author disclaims copyright to this source code. In place of
  69246. ** a legal notice, here is a blessing:
  69247. **
  69248. ** May you do good and not evil.
  69249. ** May you find forgiveness for yourself and forgive others.
  69250. ** May you share freely, never taking more than you give.
  69251. **
  69252. *************************************************************************
  69253. **
  69254. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  69255. ** stores a single value in the VDBE. Mem is an opaque structure visible
  69256. ** only within the VDBE. Interface routines refer to a Mem using the
  69257. ** name sqlite_value
  69258. */
  69259. /* #include "sqliteInt.h" */
  69260. /* #include "vdbeInt.h" */
  69261. #ifdef SQLITE_DEBUG
  69262. /*
  69263. ** Check invariants on a Mem object.
  69264. **
  69265. ** This routine is intended for use inside of assert() statements, like
  69266. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  69267. */
  69268. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  69269. /* If MEM_Dyn is set then Mem.xDel!=0.
  69270. ** Mem.xDel might not be initialized if MEM_Dyn is clear.
  69271. */
  69272. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  69273. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  69274. ** ensure that if Mem.szMalloc>0 then it is safe to do
  69275. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  69276. ** That saves a few cycles in inner loops. */
  69277. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  69278. /* Cannot be both MEM_Int and MEM_Real at the same time */
  69279. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  69280. if( p->flags & MEM_Null ){
  69281. /* Cannot be both MEM_Null and some other type */
  69282. assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
  69283. /* If MEM_Null is set, then either the value is a pure NULL (the usual
  69284. ** case) or it is a pointer set using sqlite3_bind_pointer() or
  69285. ** sqlite3_result_pointer(). If a pointer, then MEM_Term must also be
  69286. ** set.
  69287. */
  69288. if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
  69289. /* This is a pointer type. There may be a flag to indicate what to
  69290. ** do with the pointer. */
  69291. assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  69292. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  69293. ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
  69294. /* No other bits set */
  69295. assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype
  69296. |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
  69297. }else{
  69298. /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
  69299. ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
  69300. }
  69301. }else{
  69302. /* The MEM_Cleared bit is only allowed on NULLs */
  69303. assert( (p->flags & MEM_Cleared)==0 );
  69304. }
  69305. /* The szMalloc field holds the correct memory allocation size */
  69306. assert( p->szMalloc==0
  69307. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  69308. /* If p holds a string or blob, the Mem.z must point to exactly
  69309. ** one of the following:
  69310. **
  69311. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  69312. ** (2) Memory to be freed using Mem.xDel
  69313. ** (3) An ephemeral string or blob
  69314. ** (4) A static string or blob
  69315. */
  69316. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  69317. assert(
  69318. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  69319. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  69320. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  69321. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  69322. );
  69323. }
  69324. return 1;
  69325. }
  69326. #endif
  69327. #ifdef SQLITE_DEBUG
  69328. /*
  69329. ** Check that string value of pMem agrees with its integer or real value.
  69330. **
  69331. ** A single int or real value always converts to the same strings. But
  69332. ** many different strings can be converted into the same int or real.
  69333. ** If a table contains a numeric value and an index is based on the
  69334. ** corresponding string value, then it is important that the string be
  69335. ** derived from the numeric value, not the other way around, to ensure
  69336. ** that the index and table are consistent. See ticket
  69337. ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
  69338. ** an example.
  69339. **
  69340. ** This routine looks at pMem to verify that if it has both a numeric
  69341. ** representation and a string representation then the string rep has
  69342. ** been derived from the numeric and not the other way around. It returns
  69343. ** true if everything is ok and false if there is a problem.
  69344. **
  69345. ** This routine is for use inside of assert() statements only.
  69346. */
  69347. SQLITE_PRIVATE int sqlite3VdbeMemConsistentDualRep(Mem *p){
  69348. char zBuf[100];
  69349. char *z;
  69350. int i, j, incr;
  69351. if( (p->flags & MEM_Str)==0 ) return 1;
  69352. if( (p->flags & (MEM_Int|MEM_Real))==0 ) return 1;
  69353. if( p->flags & MEM_Int ){
  69354. sqlite3_snprintf(sizeof(zBuf),zBuf,"%lld",p->u.i);
  69355. }else{
  69356. sqlite3_snprintf(sizeof(zBuf),zBuf,"%!.15g",p->u.r);
  69357. }
  69358. z = p->z;
  69359. i = j = 0;
  69360. incr = 1;
  69361. if( p->enc!=SQLITE_UTF8 ){
  69362. incr = 2;
  69363. if( p->enc==SQLITE_UTF16BE ) z++;
  69364. }
  69365. while( zBuf[j] ){
  69366. if( zBuf[j++]!=z[i] ) return 0;
  69367. i += incr;
  69368. }
  69369. return 1;
  69370. }
  69371. #endif /* SQLITE_DEBUG */
  69372. /*
  69373. ** If pMem is an object with a valid string representation, this routine
  69374. ** ensures the internal encoding for the string representation is
  69375. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  69376. **
  69377. ** If pMem is not a string object, or the encoding of the string
  69378. ** representation is already stored using the requested encoding, then this
  69379. ** routine is a no-op.
  69380. **
  69381. ** SQLITE_OK is returned if the conversion is successful (or not required).
  69382. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  69383. ** between formats.
  69384. */
  69385. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  69386. #ifndef SQLITE_OMIT_UTF16
  69387. int rc;
  69388. #endif
  69389. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  69390. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  69391. || desiredEnc==SQLITE_UTF16BE );
  69392. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  69393. return SQLITE_OK;
  69394. }
  69395. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69396. #ifdef SQLITE_OMIT_UTF16
  69397. return SQLITE_ERROR;
  69398. #else
  69399. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  69400. ** then the encoding of the value may not have changed.
  69401. */
  69402. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  69403. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  69404. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  69405. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  69406. return rc;
  69407. #endif
  69408. }
  69409. /*
  69410. ** Make sure pMem->z points to a writable allocation of at least
  69411. ** min(n,32) bytes.
  69412. **
  69413. ** If the bPreserve argument is true, then copy of the content of
  69414. ** pMem->z into the new allocation. pMem must be either a string or
  69415. ** blob if bPreserve is true. If bPreserve is false, any prior content
  69416. ** in pMem->z is discarded.
  69417. */
  69418. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  69419. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  69420. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  69421. testcase( pMem->db==0 );
  69422. /* If the bPreserve flag is set to true, then the memory cell must already
  69423. ** contain a valid string or blob value. */
  69424. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  69425. testcase( bPreserve && pMem->z==0 );
  69426. assert( pMem->szMalloc==0
  69427. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  69428. if( n<32 ) n = 32;
  69429. if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
  69430. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  69431. bPreserve = 0;
  69432. }else{
  69433. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  69434. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  69435. }
  69436. if( pMem->zMalloc==0 ){
  69437. sqlite3VdbeMemSetNull(pMem);
  69438. pMem->z = 0;
  69439. pMem->szMalloc = 0;
  69440. return SQLITE_NOMEM_BKPT;
  69441. }else{
  69442. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  69443. }
  69444. if( bPreserve && pMem->z ){
  69445. assert( pMem->z!=pMem->zMalloc );
  69446. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  69447. }
  69448. if( (pMem->flags&MEM_Dyn)!=0 ){
  69449. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  69450. pMem->xDel((void *)(pMem->z));
  69451. }
  69452. pMem->z = pMem->zMalloc;
  69453. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  69454. return SQLITE_OK;
  69455. }
  69456. /*
  69457. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  69458. ** If pMem->zMalloc already meets or exceeds the requested size, this
  69459. ** routine is a no-op.
  69460. **
  69461. ** Any prior string or blob content in the pMem object may be discarded.
  69462. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  69463. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  69464. ** values are preserved.
  69465. **
  69466. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  69467. ** if unable to complete the resizing.
  69468. */
  69469. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  69470. assert( szNew>0 );
  69471. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  69472. if( pMem->szMalloc<szNew ){
  69473. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  69474. }
  69475. assert( (pMem->flags & MEM_Dyn)==0 );
  69476. pMem->z = pMem->zMalloc;
  69477. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  69478. return SQLITE_OK;
  69479. }
  69480. /*
  69481. ** It is already known that pMem contains an unterminated string.
  69482. ** Add the zero terminator.
  69483. */
  69484. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  69485. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  69486. return SQLITE_NOMEM_BKPT;
  69487. }
  69488. pMem->z[pMem->n] = 0;
  69489. pMem->z[pMem->n+1] = 0;
  69490. pMem->flags |= MEM_Term;
  69491. return SQLITE_OK;
  69492. }
  69493. /*
  69494. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  69495. ** MEM.zMalloc, where it can be safely written.
  69496. **
  69497. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  69498. */
  69499. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  69500. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69501. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  69502. if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
  69503. if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
  69504. if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
  69505. int rc = vdbeMemAddTerminator(pMem);
  69506. if( rc ) return rc;
  69507. }
  69508. }
  69509. pMem->flags &= ~MEM_Ephem;
  69510. #ifdef SQLITE_DEBUG
  69511. pMem->pScopyFrom = 0;
  69512. #endif
  69513. return SQLITE_OK;
  69514. }
  69515. /*
  69516. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  69517. ** blob stored in dynamically allocated space.
  69518. */
  69519. #ifndef SQLITE_OMIT_INCRBLOB
  69520. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  69521. int nByte;
  69522. assert( pMem->flags & MEM_Zero );
  69523. assert( pMem->flags&MEM_Blob );
  69524. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  69525. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69526. /* Set nByte to the number of bytes required to store the expanded blob. */
  69527. nByte = pMem->n + pMem->u.nZero;
  69528. if( nByte<=0 ){
  69529. nByte = 1;
  69530. }
  69531. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  69532. return SQLITE_NOMEM_BKPT;
  69533. }
  69534. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  69535. pMem->n += pMem->u.nZero;
  69536. pMem->flags &= ~(MEM_Zero|MEM_Term);
  69537. return SQLITE_OK;
  69538. }
  69539. #endif
  69540. /*
  69541. ** Make sure the given Mem is \u0000 terminated.
  69542. */
  69543. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  69544. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69545. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  69546. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  69547. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  69548. return SQLITE_OK; /* Nothing to do */
  69549. }else{
  69550. return vdbeMemAddTerminator(pMem);
  69551. }
  69552. }
  69553. /*
  69554. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  69555. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  69556. ** is a no-op.
  69557. **
  69558. ** Existing representations MEM_Int and MEM_Real are invalidated if
  69559. ** bForce is true but are retained if bForce is false.
  69560. **
  69561. ** A MEM_Null value will never be passed to this function. This function is
  69562. ** used for converting values to text for returning to the user (i.e. via
  69563. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  69564. ** keys are strings. In the former case a NULL pointer is returned the
  69565. ** user and the latter is an internal programming error.
  69566. */
  69567. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  69568. int fg = pMem->flags;
  69569. const int nByte = 32;
  69570. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69571. assert( !(fg&MEM_Zero) );
  69572. assert( !(fg&(MEM_Str|MEM_Blob)) );
  69573. assert( fg&(MEM_Int|MEM_Real) );
  69574. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  69575. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  69576. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  69577. pMem->enc = 0;
  69578. return SQLITE_NOMEM_BKPT;
  69579. }
  69580. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  69581. ** string representation of the value. Then, if the required encoding
  69582. ** is UTF-16le or UTF-16be do a translation.
  69583. **
  69584. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  69585. */
  69586. if( fg & MEM_Int ){
  69587. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  69588. }else{
  69589. assert( fg & MEM_Real );
  69590. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  69591. }
  69592. assert( pMem->z!=0 );
  69593. pMem->n = sqlite3Strlen30NN(pMem->z);
  69594. pMem->enc = SQLITE_UTF8;
  69595. pMem->flags |= MEM_Str|MEM_Term;
  69596. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  69597. sqlite3VdbeChangeEncoding(pMem, enc);
  69598. return SQLITE_OK;
  69599. }
  69600. /*
  69601. ** Memory cell pMem contains the context of an aggregate function.
  69602. ** This routine calls the finalize method for that function. The
  69603. ** result of the aggregate is stored back into pMem.
  69604. **
  69605. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  69606. ** otherwise.
  69607. */
  69608. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  69609. sqlite3_context ctx;
  69610. Mem t;
  69611. assert( pFunc!=0 );
  69612. assert( pFunc->xFinalize!=0 );
  69613. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  69614. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69615. memset(&ctx, 0, sizeof(ctx));
  69616. memset(&t, 0, sizeof(t));
  69617. t.flags = MEM_Null;
  69618. t.db = pMem->db;
  69619. ctx.pOut = &t;
  69620. ctx.pMem = pMem;
  69621. ctx.pFunc = pFunc;
  69622. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  69623. assert( (pMem->flags & MEM_Dyn)==0 );
  69624. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  69625. memcpy(pMem, &t, sizeof(t));
  69626. return ctx.isError;
  69627. }
  69628. /*
  69629. ** Memory cell pAccum contains the context of an aggregate function.
  69630. ** This routine calls the xValue method for that function and stores
  69631. ** the results in memory cell pMem.
  69632. **
  69633. ** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK
  69634. ** otherwise.
  69635. */
  69636. #ifndef SQLITE_OMIT_WINDOWFUNC
  69637. SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
  69638. sqlite3_context ctx;
  69639. Mem t;
  69640. assert( pFunc!=0 );
  69641. assert( pFunc->xValue!=0 );
  69642. assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
  69643. assert( pAccum->db==0 || sqlite3_mutex_held(pAccum->db->mutex) );
  69644. memset(&ctx, 0, sizeof(ctx));
  69645. memset(&t, 0, sizeof(t));
  69646. t.flags = MEM_Null;
  69647. t.db = pAccum->db;
  69648. sqlite3VdbeMemSetNull(pOut);
  69649. ctx.pOut = pOut;
  69650. ctx.pMem = pAccum;
  69651. ctx.pFunc = pFunc;
  69652. pFunc->xValue(&ctx);
  69653. return ctx.isError;
  69654. }
  69655. #endif /* SQLITE_OMIT_WINDOWFUNC */
  69656. /*
  69657. ** If the memory cell contains a value that must be freed by
  69658. ** invoking the external callback in Mem.xDel, then this routine
  69659. ** will free that value. It also sets Mem.flags to MEM_Null.
  69660. **
  69661. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  69662. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  69663. ** entry point for releasing Mem resources.
  69664. */
  69665. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  69666. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  69667. assert( VdbeMemDynamic(p) );
  69668. if( p->flags&MEM_Agg ){
  69669. sqlite3VdbeMemFinalize(p, p->u.pDef);
  69670. assert( (p->flags & MEM_Agg)==0 );
  69671. testcase( p->flags & MEM_Dyn );
  69672. }
  69673. if( p->flags&MEM_Dyn ){
  69674. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  69675. p->xDel((void *)p->z);
  69676. }
  69677. p->flags = MEM_Null;
  69678. }
  69679. /*
  69680. ** Release memory held by the Mem p, both external memory cleared
  69681. ** by p->xDel and memory in p->zMalloc.
  69682. **
  69683. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  69684. ** the unusual case where there really is memory in p that needs
  69685. ** to be freed.
  69686. */
  69687. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  69688. if( VdbeMemDynamic(p) ){
  69689. vdbeMemClearExternAndSetNull(p);
  69690. }
  69691. if( p->szMalloc ){
  69692. sqlite3DbFreeNN(p->db, p->zMalloc);
  69693. p->szMalloc = 0;
  69694. }
  69695. p->z = 0;
  69696. }
  69697. /*
  69698. ** Release any memory resources held by the Mem. Both the memory that is
  69699. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  69700. **
  69701. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  69702. ** reset a Mem back to its minimum memory utilization.
  69703. **
  69704. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  69705. ** prior to inserting new content into the Mem.
  69706. */
  69707. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  69708. assert( sqlite3VdbeCheckMemInvariants(p) );
  69709. if( VdbeMemDynamic(p) || p->szMalloc ){
  69710. vdbeMemClear(p);
  69711. }
  69712. }
  69713. /*
  69714. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  69715. ** If the double is out of range of a 64-bit signed integer then
  69716. ** return the closest available 64-bit signed integer.
  69717. */
  69718. static SQLITE_NOINLINE i64 doubleToInt64(double r){
  69719. #ifdef SQLITE_OMIT_FLOATING_POINT
  69720. /* When floating-point is omitted, double and int64 are the same thing */
  69721. return r;
  69722. #else
  69723. /*
  69724. ** Many compilers we encounter do not define constants for the
  69725. ** minimum and maximum 64-bit integers, or they define them
  69726. ** inconsistently. And many do not understand the "LL" notation.
  69727. ** So we define our own static constants here using nothing
  69728. ** larger than a 32-bit integer constant.
  69729. */
  69730. static const i64 maxInt = LARGEST_INT64;
  69731. static const i64 minInt = SMALLEST_INT64;
  69732. if( r<=(double)minInt ){
  69733. return minInt;
  69734. }else if( r>=(double)maxInt ){
  69735. return maxInt;
  69736. }else{
  69737. return (i64)r;
  69738. }
  69739. #endif
  69740. }
  69741. /*
  69742. ** Return some kind of integer value which is the best we can do
  69743. ** at representing the value that *pMem describes as an integer.
  69744. ** If pMem is an integer, then the value is exact. If pMem is
  69745. ** a floating-point then the value returned is the integer part.
  69746. ** If pMem is a string or blob, then we make an attempt to convert
  69747. ** it into an integer and return that. If pMem represents an
  69748. ** an SQL-NULL value, return 0.
  69749. **
  69750. ** If pMem represents a string value, its encoding might be changed.
  69751. */
  69752. static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
  69753. i64 value = 0;
  69754. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  69755. return value;
  69756. }
  69757. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  69758. int flags;
  69759. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69760. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  69761. flags = pMem->flags;
  69762. if( flags & MEM_Int ){
  69763. return pMem->u.i;
  69764. }else if( flags & MEM_Real ){
  69765. return doubleToInt64(pMem->u.r);
  69766. }else if( flags & (MEM_Str|MEM_Blob) ){
  69767. assert( pMem->z || pMem->n==0 );
  69768. return memIntValue(pMem);
  69769. }else{
  69770. return 0;
  69771. }
  69772. }
  69773. /*
  69774. ** Return the best representation of pMem that we can get into a
  69775. ** double. If pMem is already a double or an integer, return its
  69776. ** value. If it is a string or blob, try to convert it to a double.
  69777. ** If it is a NULL, return 0.0.
  69778. */
  69779. static SQLITE_NOINLINE double memRealValue(Mem *pMem){
  69780. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  69781. double val = (double)0;
  69782. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  69783. return val;
  69784. }
  69785. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  69786. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69787. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  69788. if( pMem->flags & MEM_Real ){
  69789. return pMem->u.r;
  69790. }else if( pMem->flags & MEM_Int ){
  69791. return (double)pMem->u.i;
  69792. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  69793. return memRealValue(pMem);
  69794. }else{
  69795. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  69796. return (double)0;
  69797. }
  69798. }
  69799. /*
  69800. ** Return 1 if pMem represents true, and return 0 if pMem represents false.
  69801. ** Return the value ifNull if pMem is NULL.
  69802. */
  69803. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
  69804. if( pMem->flags & MEM_Int ) return pMem->u.i!=0;
  69805. if( pMem->flags & MEM_Null ) return ifNull;
  69806. return sqlite3VdbeRealValue(pMem)!=0.0;
  69807. }
  69808. /*
  69809. ** The MEM structure is already a MEM_Real. Try to also make it a
  69810. ** MEM_Int if we can.
  69811. */
  69812. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  69813. i64 ix;
  69814. assert( pMem->flags & MEM_Real );
  69815. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  69816. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69817. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  69818. ix = doubleToInt64(pMem->u.r);
  69819. /* Only mark the value as an integer if
  69820. **
  69821. ** (1) the round-trip conversion real->int->real is a no-op, and
  69822. ** (2) The integer is neither the largest nor the smallest
  69823. ** possible integer (ticket #3922)
  69824. **
  69825. ** The second and third terms in the following conditional enforces
  69826. ** the second condition under the assumption that addition overflow causes
  69827. ** values to wrap around.
  69828. */
  69829. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  69830. pMem->u.i = ix;
  69831. MemSetTypeFlag(pMem, MEM_Int);
  69832. }
  69833. }
  69834. /*
  69835. ** Convert pMem to type integer. Invalidate any prior representations.
  69836. */
  69837. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  69838. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69839. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  69840. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  69841. pMem->u.i = sqlite3VdbeIntValue(pMem);
  69842. MemSetTypeFlag(pMem, MEM_Int);
  69843. return SQLITE_OK;
  69844. }
  69845. /*
  69846. ** Convert pMem so that it is of type MEM_Real.
  69847. ** Invalidate any prior representations.
  69848. */
  69849. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  69850. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69851. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  69852. pMem->u.r = sqlite3VdbeRealValue(pMem);
  69853. MemSetTypeFlag(pMem, MEM_Real);
  69854. return SQLITE_OK;
  69855. }
  69856. /* Compare a floating point value to an integer. Return true if the two
  69857. ** values are the same within the precision of the floating point value.
  69858. **
  69859. ** For some versions of GCC on 32-bit machines, if you do the more obvious
  69860. ** comparison of "r1==(double)i" you sometimes get an answer of false even
  69861. ** though the r1 and (double)i values are bit-for-bit the same.
  69862. */
  69863. static int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
  69864. double r2 = (double)i;
  69865. return memcmp(&r1, &r2, sizeof(r1))==0;
  69866. }
  69867. /*
  69868. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  69869. ** Invalidate any prior representations.
  69870. **
  69871. ** Every effort is made to force the conversion, even if the input
  69872. ** is a string that does not look completely like a number. Convert
  69873. ** as much of the string as we can and ignore the rest.
  69874. */
  69875. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  69876. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  69877. int rc;
  69878. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  69879. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69880. rc = sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc);
  69881. if( rc==0 ){
  69882. MemSetTypeFlag(pMem, MEM_Int);
  69883. }else{
  69884. i64 i = pMem->u.i;
  69885. sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
  69886. if( rc==1 && sqlite3RealSameAsInt(pMem->u.r, i) ){
  69887. pMem->u.i = i;
  69888. MemSetTypeFlag(pMem, MEM_Int);
  69889. }else{
  69890. MemSetTypeFlag(pMem, MEM_Real);
  69891. }
  69892. }
  69893. }
  69894. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  69895. pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
  69896. return SQLITE_OK;
  69897. }
  69898. /*
  69899. ** Cast the datatype of the value in pMem according to the affinity
  69900. ** "aff". Casting is different from applying affinity in that a cast
  69901. ** is forced. In other words, the value is converted into the desired
  69902. ** affinity even if that results in loss of data. This routine is
  69903. ** used (for example) to implement the SQL "cast()" operator.
  69904. */
  69905. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  69906. if( pMem->flags & MEM_Null ) return;
  69907. switch( aff ){
  69908. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  69909. if( (pMem->flags & MEM_Blob)==0 ){
  69910. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  69911. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  69912. if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
  69913. }else{
  69914. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  69915. }
  69916. break;
  69917. }
  69918. case SQLITE_AFF_NUMERIC: {
  69919. sqlite3VdbeMemNumerify(pMem);
  69920. break;
  69921. }
  69922. case SQLITE_AFF_INTEGER: {
  69923. sqlite3VdbeMemIntegerify(pMem);
  69924. break;
  69925. }
  69926. case SQLITE_AFF_REAL: {
  69927. sqlite3VdbeMemRealify(pMem);
  69928. break;
  69929. }
  69930. default: {
  69931. assert( aff==SQLITE_AFF_TEXT );
  69932. assert( MEM_Str==(MEM_Blob>>3) );
  69933. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  69934. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  69935. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  69936. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  69937. break;
  69938. }
  69939. }
  69940. }
  69941. /*
  69942. ** Initialize bulk memory to be a consistent Mem object.
  69943. **
  69944. ** The minimum amount of initialization feasible is performed.
  69945. */
  69946. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  69947. assert( (flags & ~MEM_TypeMask)==0 );
  69948. pMem->flags = flags;
  69949. pMem->db = db;
  69950. pMem->szMalloc = 0;
  69951. }
  69952. /*
  69953. ** Delete any previous value and set the value stored in *pMem to NULL.
  69954. **
  69955. ** This routine calls the Mem.xDel destructor to dispose of values that
  69956. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  69957. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  69958. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  69959. **
  69960. ** Use this routine to reset the Mem prior to insert a new value.
  69961. **
  69962. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  69963. */
  69964. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  69965. if( VdbeMemDynamic(pMem) ){
  69966. vdbeMemClearExternAndSetNull(pMem);
  69967. }else{
  69968. pMem->flags = MEM_Null;
  69969. }
  69970. }
  69971. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  69972. sqlite3VdbeMemSetNull((Mem*)p);
  69973. }
  69974. /*
  69975. ** Delete any previous value and set the value to be a BLOB of length
  69976. ** n containing all zeros.
  69977. */
  69978. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  69979. sqlite3VdbeMemRelease(pMem);
  69980. pMem->flags = MEM_Blob|MEM_Zero;
  69981. pMem->n = 0;
  69982. if( n<0 ) n = 0;
  69983. pMem->u.nZero = n;
  69984. pMem->enc = SQLITE_UTF8;
  69985. pMem->z = 0;
  69986. }
  69987. /*
  69988. ** The pMem is known to contain content that needs to be destroyed prior
  69989. ** to a value change. So invoke the destructor, then set the value to
  69990. ** a 64-bit integer.
  69991. */
  69992. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  69993. sqlite3VdbeMemSetNull(pMem);
  69994. pMem->u.i = val;
  69995. pMem->flags = MEM_Int;
  69996. }
  69997. /*
  69998. ** Delete any previous value and set the value stored in *pMem to val,
  69999. ** manifest type INTEGER.
  70000. */
  70001. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  70002. if( VdbeMemDynamic(pMem) ){
  70003. vdbeReleaseAndSetInt64(pMem, val);
  70004. }else{
  70005. pMem->u.i = val;
  70006. pMem->flags = MEM_Int;
  70007. }
  70008. }
  70009. /* A no-op destructor */
  70010. SQLITE_PRIVATE void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
  70011. /*
  70012. ** Set the value stored in *pMem should already be a NULL.
  70013. ** Also store a pointer to go with it.
  70014. */
  70015. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
  70016. Mem *pMem,
  70017. void *pPtr,
  70018. const char *zPType,
  70019. void (*xDestructor)(void*)
  70020. ){
  70021. assert( pMem->flags==MEM_Null );
  70022. pMem->u.zPType = zPType ? zPType : "";
  70023. pMem->z = pPtr;
  70024. pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
  70025. pMem->eSubtype = 'p';
  70026. pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
  70027. }
  70028. #ifndef SQLITE_OMIT_FLOATING_POINT
  70029. /*
  70030. ** Delete any previous value and set the value stored in *pMem to val,
  70031. ** manifest type REAL.
  70032. */
  70033. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  70034. sqlite3VdbeMemSetNull(pMem);
  70035. if( !sqlite3IsNaN(val) ){
  70036. pMem->u.r = val;
  70037. pMem->flags = MEM_Real;
  70038. }
  70039. }
  70040. #endif
  70041. #ifdef SQLITE_DEBUG
  70042. /*
  70043. ** Return true if the Mem holds a RowSet object. This routine is intended
  70044. ** for use inside of assert() statements.
  70045. */
  70046. SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem *pMem){
  70047. return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
  70048. && pMem->xDel==sqlite3RowSetDelete;
  70049. }
  70050. #endif
  70051. /*
  70052. ** Delete any previous value and set the value of pMem to be an
  70053. ** empty boolean index.
  70054. **
  70055. ** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation
  70056. ** error occurs.
  70057. */
  70058. SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem *pMem){
  70059. sqlite3 *db = pMem->db;
  70060. RowSet *p;
  70061. assert( db!=0 );
  70062. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70063. sqlite3VdbeMemRelease(pMem);
  70064. p = sqlite3RowSetInit(db);
  70065. if( p==0 ) return SQLITE_NOMEM;
  70066. pMem->z = (char*)p;
  70067. pMem->flags = MEM_Blob|MEM_Dyn;
  70068. pMem->xDel = sqlite3RowSetDelete;
  70069. return SQLITE_OK;
  70070. }
  70071. /*
  70072. ** Return true if the Mem object contains a TEXT or BLOB that is
  70073. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  70074. */
  70075. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  70076. assert( p->db!=0 );
  70077. if( p->flags & (MEM_Str|MEM_Blob) ){
  70078. int n = p->n;
  70079. if( p->flags & MEM_Zero ){
  70080. n += p->u.nZero;
  70081. }
  70082. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  70083. }
  70084. return 0;
  70085. }
  70086. #ifdef SQLITE_DEBUG
  70087. /*
  70088. ** This routine prepares a memory cell for modification by breaking
  70089. ** its link to a shallow copy and by marking any current shallow
  70090. ** copies of this cell as invalid.
  70091. **
  70092. ** This is used for testing and debugging only - to make sure shallow
  70093. ** copies are not misused.
  70094. */
  70095. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  70096. int i;
  70097. Mem *pX;
  70098. for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
  70099. if( pX->pScopyFrom==pMem ){
  70100. /* If pX is marked as a shallow copy of pMem, then verify that
  70101. ** no significant changes have been made to pX since the OP_SCopy.
  70102. ** A significant change would indicated a missed call to this
  70103. ** function for pX. Minor changes, such as adding or removing a
  70104. ** dual type, are allowed, as long as the underlying value is the
  70105. ** same. */
  70106. u16 mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
  70107. assert( (mFlags&MEM_Int)==0 || pMem->u.i==pX->u.i );
  70108. assert( (mFlags&MEM_Real)==0 || pMem->u.r==pX->u.r );
  70109. assert( (mFlags&MEM_Str)==0 || (pMem->n==pX->n && pMem->z==pX->z) );
  70110. assert( (mFlags&MEM_Blob)==0 || sqlite3BlobCompare(pMem,pX)==0 );
  70111. /* pMem is the register that is changing. But also mark pX as
  70112. ** undefined so that we can quickly detect the shallow-copy error */
  70113. pX->flags = MEM_Undefined;
  70114. pX->pScopyFrom = 0;
  70115. }
  70116. }
  70117. pMem->pScopyFrom = 0;
  70118. }
  70119. #endif /* SQLITE_DEBUG */
  70120. /*
  70121. ** Make an shallow copy of pFrom into pTo. Prior contents of
  70122. ** pTo are freed. The pFrom->z field is not duplicated. If
  70123. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  70124. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  70125. */
  70126. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  70127. vdbeMemClearExternAndSetNull(pTo);
  70128. assert( !VdbeMemDynamic(pTo) );
  70129. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  70130. }
  70131. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  70132. assert( !sqlite3VdbeMemIsRowSet(pFrom) );
  70133. assert( pTo->db==pFrom->db );
  70134. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  70135. memcpy(pTo, pFrom, MEMCELLSIZE);
  70136. if( (pFrom->flags&MEM_Static)==0 ){
  70137. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  70138. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  70139. pTo->flags |= srcType;
  70140. }
  70141. }
  70142. /*
  70143. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  70144. ** freed before the copy is made.
  70145. */
  70146. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  70147. int rc = SQLITE_OK;
  70148. assert( !sqlite3VdbeMemIsRowSet(pFrom) );
  70149. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  70150. memcpy(pTo, pFrom, MEMCELLSIZE);
  70151. pTo->flags &= ~MEM_Dyn;
  70152. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  70153. if( 0==(pFrom->flags&MEM_Static) ){
  70154. pTo->flags |= MEM_Ephem;
  70155. rc = sqlite3VdbeMemMakeWriteable(pTo);
  70156. }
  70157. }
  70158. return rc;
  70159. }
  70160. /*
  70161. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  70162. ** freed. If pFrom contains ephemeral data, a copy is made.
  70163. **
  70164. ** pFrom contains an SQL NULL when this routine returns.
  70165. */
  70166. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  70167. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  70168. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  70169. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  70170. sqlite3VdbeMemRelease(pTo);
  70171. memcpy(pTo, pFrom, sizeof(Mem));
  70172. pFrom->flags = MEM_Null;
  70173. pFrom->szMalloc = 0;
  70174. }
  70175. /*
  70176. ** Change the value of a Mem to be a string or a BLOB.
  70177. **
  70178. ** The memory management strategy depends on the value of the xDel
  70179. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  70180. ** string is copied into a (possibly existing) buffer managed by the
  70181. ** Mem structure. Otherwise, any existing buffer is freed and the
  70182. ** pointer copied.
  70183. **
  70184. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  70185. ** size limit) then no memory allocation occurs. If the string can be
  70186. ** stored without allocating memory, then it is. If a memory allocation
  70187. ** is required to store the string, then value of pMem is unchanged. In
  70188. ** either case, SQLITE_TOOBIG is returned.
  70189. */
  70190. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  70191. Mem *pMem, /* Memory cell to set to string value */
  70192. const char *z, /* String pointer */
  70193. int n, /* Bytes in string, or negative */
  70194. u8 enc, /* Encoding of z. 0 for BLOBs */
  70195. void (*xDel)(void*) /* Destructor function */
  70196. ){
  70197. int nByte = n; /* New value for pMem->n */
  70198. int iLimit; /* Maximum allowed string or blob size */
  70199. u16 flags = 0; /* New value for pMem->flags */
  70200. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70201. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70202. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  70203. if( !z ){
  70204. sqlite3VdbeMemSetNull(pMem);
  70205. return SQLITE_OK;
  70206. }
  70207. if( pMem->db ){
  70208. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  70209. }else{
  70210. iLimit = SQLITE_MAX_LENGTH;
  70211. }
  70212. flags = (enc==0?MEM_Blob:MEM_Str);
  70213. if( nByte<0 ){
  70214. assert( enc!=0 );
  70215. if( enc==SQLITE_UTF8 ){
  70216. nByte = 0x7fffffff & (int)strlen(z);
  70217. if( nByte>iLimit ) nByte = iLimit+1;
  70218. }else{
  70219. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  70220. }
  70221. flags |= MEM_Term;
  70222. }
  70223. /* The following block sets the new values of Mem.z and Mem.xDel. It
  70224. ** also sets a flag in local variable "flags" to indicate the memory
  70225. ** management (one of MEM_Dyn or MEM_Static).
  70226. */
  70227. if( xDel==SQLITE_TRANSIENT ){
  70228. int nAlloc = nByte;
  70229. if( flags&MEM_Term ){
  70230. nAlloc += (enc==SQLITE_UTF8?1:2);
  70231. }
  70232. if( nByte>iLimit ){
  70233. return SQLITE_TOOBIG;
  70234. }
  70235. testcase( nAlloc==0 );
  70236. testcase( nAlloc==31 );
  70237. testcase( nAlloc==32 );
  70238. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  70239. return SQLITE_NOMEM_BKPT;
  70240. }
  70241. memcpy(pMem->z, z, nAlloc);
  70242. }else if( xDel==SQLITE_DYNAMIC ){
  70243. sqlite3VdbeMemRelease(pMem);
  70244. pMem->zMalloc = pMem->z = (char *)z;
  70245. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  70246. }else{
  70247. sqlite3VdbeMemRelease(pMem);
  70248. pMem->z = (char *)z;
  70249. pMem->xDel = xDel;
  70250. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  70251. }
  70252. pMem->n = nByte;
  70253. pMem->flags = flags;
  70254. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  70255. #ifndef SQLITE_OMIT_UTF16
  70256. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  70257. return SQLITE_NOMEM_BKPT;
  70258. }
  70259. #endif
  70260. if( nByte>iLimit ){
  70261. return SQLITE_TOOBIG;
  70262. }
  70263. return SQLITE_OK;
  70264. }
  70265. /*
  70266. ** Move data out of a btree key or data field and into a Mem structure.
  70267. ** The data is payload from the entry that pCur is currently pointing
  70268. ** to. offset and amt determine what portion of the data or key to retrieve.
  70269. ** The result is written into the pMem element.
  70270. **
  70271. ** The pMem object must have been initialized. This routine will use
  70272. ** pMem->zMalloc to hold the content from the btree, if possible. New
  70273. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  70274. ** is responsible for making sure that the pMem object is eventually
  70275. ** destroyed.
  70276. **
  70277. ** If this routine fails for any reason (malloc returns NULL or unable
  70278. ** to read from the disk) then the pMem is left in an inconsistent state.
  70279. */
  70280. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  70281. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  70282. u32 offset, /* Offset from the start of data to return bytes from. */
  70283. u32 amt, /* Number of bytes to return. */
  70284. Mem *pMem /* OUT: Return data in this Mem structure. */
  70285. ){
  70286. int rc;
  70287. pMem->flags = MEM_Null;
  70288. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
  70289. rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
  70290. if( rc==SQLITE_OK ){
  70291. pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
  70292. pMem->flags = MEM_Blob;
  70293. pMem->n = (int)amt;
  70294. }else{
  70295. sqlite3VdbeMemRelease(pMem);
  70296. }
  70297. }
  70298. return rc;
  70299. }
  70300. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  70301. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  70302. u32 offset, /* Offset from the start of data to return bytes from. */
  70303. u32 amt, /* Number of bytes to return. */
  70304. Mem *pMem /* OUT: Return data in this Mem structure. */
  70305. ){
  70306. char *zData; /* Data from the btree layer */
  70307. u32 available = 0; /* Number of bytes available on the local btree page */
  70308. int rc = SQLITE_OK; /* Return code */
  70309. assert( sqlite3BtreeCursorIsValid(pCur) );
  70310. assert( !VdbeMemDynamic(pMem) );
  70311. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  70312. ** that both the BtShared and database handle mutexes are held. */
  70313. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70314. zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
  70315. assert( zData!=0 );
  70316. if( offset+amt<=available ){
  70317. pMem->z = &zData[offset];
  70318. pMem->flags = MEM_Blob|MEM_Ephem;
  70319. pMem->n = (int)amt;
  70320. }else{
  70321. rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
  70322. }
  70323. return rc;
  70324. }
  70325. /*
  70326. ** The pVal argument is known to be a value other than NULL.
  70327. ** Convert it into a string with encoding enc and return a pointer
  70328. ** to a zero-terminated version of that string.
  70329. */
  70330. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  70331. assert( pVal!=0 );
  70332. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  70333. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  70334. assert( !sqlite3VdbeMemIsRowSet(pVal) );
  70335. assert( (pVal->flags & (MEM_Null))==0 );
  70336. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  70337. if( ExpandBlob(pVal) ) return 0;
  70338. pVal->flags |= MEM_Str;
  70339. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  70340. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  70341. }
  70342. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  70343. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  70344. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  70345. return 0;
  70346. }
  70347. }
  70348. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  70349. }else{
  70350. sqlite3VdbeMemStringify(pVal, enc, 0);
  70351. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  70352. }
  70353. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  70354. || pVal->db->mallocFailed );
  70355. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  70356. assert( sqlite3VdbeMemConsistentDualRep(pVal) );
  70357. return pVal->z;
  70358. }else{
  70359. return 0;
  70360. }
  70361. }
  70362. /* This function is only available internally, it is not part of the
  70363. ** external API. It works in a similar way to sqlite3_value_text(),
  70364. ** except the data returned is in the encoding specified by the second
  70365. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  70366. ** SQLITE_UTF8.
  70367. **
  70368. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  70369. ** If that is the case, then the result must be aligned on an even byte
  70370. ** boundary.
  70371. */
  70372. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  70373. if( !pVal ) return 0;
  70374. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  70375. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  70376. assert( !sqlite3VdbeMemIsRowSet(pVal) );
  70377. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  70378. assert( sqlite3VdbeMemConsistentDualRep(pVal) );
  70379. return pVal->z;
  70380. }
  70381. if( pVal->flags&MEM_Null ){
  70382. return 0;
  70383. }
  70384. return valueToText(pVal, enc);
  70385. }
  70386. /*
  70387. ** Create a new sqlite3_value object.
  70388. */
  70389. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  70390. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  70391. if( p ){
  70392. p->flags = MEM_Null;
  70393. p->db = db;
  70394. }
  70395. return p;
  70396. }
  70397. /*
  70398. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  70399. ** valueNew(). See comments above valueNew() for details.
  70400. */
  70401. struct ValueNewStat4Ctx {
  70402. Parse *pParse;
  70403. Index *pIdx;
  70404. UnpackedRecord **ppRec;
  70405. int iVal;
  70406. };
  70407. /*
  70408. ** Allocate and return a pointer to a new sqlite3_value object. If
  70409. ** the second argument to this function is NULL, the object is allocated
  70410. ** by calling sqlite3ValueNew().
  70411. **
  70412. ** Otherwise, if the second argument is non-zero, then this function is
  70413. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  70414. ** already been allocated, allocate the UnpackedRecord structure that
  70415. ** that function will return to its caller here. Then return a pointer to
  70416. ** an sqlite3_value within the UnpackedRecord.a[] array.
  70417. */
  70418. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  70419. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  70420. if( p ){
  70421. UnpackedRecord *pRec = p->ppRec[0];
  70422. if( pRec==0 ){
  70423. Index *pIdx = p->pIdx; /* Index being probed */
  70424. int nByte; /* Bytes of space to allocate */
  70425. int i; /* Counter variable */
  70426. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  70427. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  70428. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  70429. if( pRec ){
  70430. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  70431. if( pRec->pKeyInfo ){
  70432. assert( pRec->pKeyInfo->nAllField==nCol );
  70433. assert( pRec->pKeyInfo->enc==ENC(db) );
  70434. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  70435. for(i=0; i<nCol; i++){
  70436. pRec->aMem[i].flags = MEM_Null;
  70437. pRec->aMem[i].db = db;
  70438. }
  70439. }else{
  70440. sqlite3DbFreeNN(db, pRec);
  70441. pRec = 0;
  70442. }
  70443. }
  70444. if( pRec==0 ) return 0;
  70445. p->ppRec[0] = pRec;
  70446. }
  70447. pRec->nField = p->iVal+1;
  70448. return &pRec->aMem[p->iVal];
  70449. }
  70450. #else
  70451. UNUSED_PARAMETER(p);
  70452. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  70453. return sqlite3ValueNew(db);
  70454. }
  70455. /*
  70456. ** The expression object indicated by the second argument is guaranteed
  70457. ** to be a scalar SQL function. If
  70458. **
  70459. ** * all function arguments are SQL literals,
  70460. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  70461. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  70462. **
  70463. ** then this routine attempts to invoke the SQL function. Assuming no
  70464. ** error occurs, output parameter (*ppVal) is set to point to a value
  70465. ** object containing the result before returning SQLITE_OK.
  70466. **
  70467. ** Affinity aff is applied to the result of the function before returning.
  70468. ** If the result is a text value, the sqlite3_value object uses encoding
  70469. ** enc.
  70470. **
  70471. ** If the conditions above are not met, this function returns SQLITE_OK
  70472. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  70473. ** NULL and an SQLite error code returned.
  70474. */
  70475. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  70476. static int valueFromFunction(
  70477. sqlite3 *db, /* The database connection */
  70478. Expr *p, /* The expression to evaluate */
  70479. u8 enc, /* Encoding to use */
  70480. u8 aff, /* Affinity to use */
  70481. sqlite3_value **ppVal, /* Write the new value here */
  70482. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  70483. ){
  70484. sqlite3_context ctx; /* Context object for function invocation */
  70485. sqlite3_value **apVal = 0; /* Function arguments */
  70486. int nVal = 0; /* Size of apVal[] array */
  70487. FuncDef *pFunc = 0; /* Function definition */
  70488. sqlite3_value *pVal = 0; /* New value */
  70489. int rc = SQLITE_OK; /* Return code */
  70490. ExprList *pList = 0; /* Function arguments */
  70491. int i; /* Iterator variable */
  70492. assert( pCtx!=0 );
  70493. assert( (p->flags & EP_TokenOnly)==0 );
  70494. pList = p->x.pList;
  70495. if( pList ) nVal = pList->nExpr;
  70496. pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
  70497. assert( pFunc );
  70498. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  70499. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  70500. ){
  70501. return SQLITE_OK;
  70502. }
  70503. if( pList ){
  70504. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  70505. if( apVal==0 ){
  70506. rc = SQLITE_NOMEM_BKPT;
  70507. goto value_from_function_out;
  70508. }
  70509. for(i=0; i<nVal; i++){
  70510. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  70511. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  70512. }
  70513. }
  70514. pVal = valueNew(db, pCtx);
  70515. if( pVal==0 ){
  70516. rc = SQLITE_NOMEM_BKPT;
  70517. goto value_from_function_out;
  70518. }
  70519. assert( pCtx->pParse->rc==SQLITE_OK );
  70520. memset(&ctx, 0, sizeof(ctx));
  70521. ctx.pOut = pVal;
  70522. ctx.pFunc = pFunc;
  70523. pFunc->xSFunc(&ctx, nVal, apVal);
  70524. if( ctx.isError ){
  70525. rc = ctx.isError;
  70526. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  70527. }else{
  70528. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  70529. assert( rc==SQLITE_OK );
  70530. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  70531. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  70532. rc = SQLITE_TOOBIG;
  70533. pCtx->pParse->nErr++;
  70534. }
  70535. }
  70536. pCtx->pParse->rc = rc;
  70537. value_from_function_out:
  70538. if( rc!=SQLITE_OK ){
  70539. pVal = 0;
  70540. }
  70541. if( apVal ){
  70542. for(i=0; i<nVal; i++){
  70543. sqlite3ValueFree(apVal[i]);
  70544. }
  70545. sqlite3DbFreeNN(db, apVal);
  70546. }
  70547. *ppVal = pVal;
  70548. return rc;
  70549. }
  70550. #else
  70551. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  70552. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  70553. /*
  70554. ** Extract a value from the supplied expression in the manner described
  70555. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  70556. ** using valueNew().
  70557. **
  70558. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  70559. ** has been allocated, it is freed before returning. Or, if pCtx is not
  70560. ** NULL, it is assumed that the caller will free any allocated object
  70561. ** in all cases.
  70562. */
  70563. static int valueFromExpr(
  70564. sqlite3 *db, /* The database connection */
  70565. Expr *pExpr, /* The expression to evaluate */
  70566. u8 enc, /* Encoding to use */
  70567. u8 affinity, /* Affinity to use */
  70568. sqlite3_value **ppVal, /* Write the new value here */
  70569. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  70570. ){
  70571. int op;
  70572. char *zVal = 0;
  70573. sqlite3_value *pVal = 0;
  70574. int negInt = 1;
  70575. const char *zNeg = "";
  70576. int rc = SQLITE_OK;
  70577. assert( pExpr!=0 );
  70578. while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
  70579. #if defined(SQLITE_ENABLE_STAT3_OR_STAT4)
  70580. if( op==TK_REGISTER ) op = pExpr->op2;
  70581. #else
  70582. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  70583. #endif
  70584. /* Compressed expressions only appear when parsing the DEFAULT clause
  70585. ** on a table column definition, and hence only when pCtx==0. This
  70586. ** check ensures that an EP_TokenOnly expression is never passed down
  70587. ** into valueFromFunction(). */
  70588. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  70589. if( op==TK_CAST ){
  70590. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  70591. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  70592. testcase( rc!=SQLITE_OK );
  70593. if( *ppVal ){
  70594. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  70595. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  70596. }
  70597. return rc;
  70598. }
  70599. /* Handle negative integers in a single step. This is needed in the
  70600. ** case when the value is -9223372036854775808.
  70601. */
  70602. if( op==TK_UMINUS
  70603. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  70604. pExpr = pExpr->pLeft;
  70605. op = pExpr->op;
  70606. negInt = -1;
  70607. zNeg = "-";
  70608. }
  70609. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  70610. pVal = valueNew(db, pCtx);
  70611. if( pVal==0 ) goto no_mem;
  70612. if( ExprHasProperty(pExpr, EP_IntValue) ){
  70613. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  70614. }else{
  70615. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  70616. if( zVal==0 ) goto no_mem;
  70617. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  70618. }
  70619. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  70620. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  70621. }else{
  70622. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  70623. }
  70624. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  70625. if( enc!=SQLITE_UTF8 ){
  70626. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  70627. }
  70628. }else if( op==TK_UMINUS ) {
  70629. /* This branch happens for multiple negative signs. Ex: -(-5) */
  70630. if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
  70631. && pVal!=0
  70632. ){
  70633. sqlite3VdbeMemNumerify(pVal);
  70634. if( pVal->flags & MEM_Real ){
  70635. pVal->u.r = -pVal->u.r;
  70636. }else if( pVal->u.i==SMALLEST_INT64 ){
  70637. pVal->u.r = -(double)SMALLEST_INT64;
  70638. MemSetTypeFlag(pVal, MEM_Real);
  70639. }else{
  70640. pVal->u.i = -pVal->u.i;
  70641. }
  70642. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  70643. }
  70644. }else if( op==TK_NULL ){
  70645. pVal = valueNew(db, pCtx);
  70646. if( pVal==0 ) goto no_mem;
  70647. sqlite3VdbeMemNumerify(pVal);
  70648. }
  70649. #ifndef SQLITE_OMIT_BLOB_LITERAL
  70650. else if( op==TK_BLOB ){
  70651. int nVal;
  70652. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  70653. assert( pExpr->u.zToken[1]=='\'' );
  70654. pVal = valueNew(db, pCtx);
  70655. if( !pVal ) goto no_mem;
  70656. zVal = &pExpr->u.zToken[2];
  70657. nVal = sqlite3Strlen30(zVal)-1;
  70658. assert( zVal[nVal]=='\'' );
  70659. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  70660. 0, SQLITE_DYNAMIC);
  70661. }
  70662. #endif
  70663. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  70664. else if( op==TK_FUNCTION && pCtx!=0 ){
  70665. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  70666. }
  70667. #endif
  70668. else if( op==TK_TRUEFALSE ){
  70669. pVal = valueNew(db, pCtx);
  70670. pVal->flags = MEM_Int;
  70671. pVal->u.i = pExpr->u.zToken[4]==0;
  70672. }
  70673. *ppVal = pVal;
  70674. return rc;
  70675. no_mem:
  70676. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  70677. if( pCtx==0 || pCtx->pParse->nErr==0 )
  70678. #endif
  70679. sqlite3OomFault(db);
  70680. sqlite3DbFree(db, zVal);
  70681. assert( *ppVal==0 );
  70682. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  70683. if( pCtx==0 ) sqlite3ValueFree(pVal);
  70684. #else
  70685. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  70686. #endif
  70687. return SQLITE_NOMEM_BKPT;
  70688. }
  70689. /*
  70690. ** Create a new sqlite3_value object, containing the value of pExpr.
  70691. **
  70692. ** This only works for very simple expressions that consist of one constant
  70693. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  70694. ** be converted directly into a value, then the value is allocated and
  70695. ** a pointer written to *ppVal. The caller is responsible for deallocating
  70696. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  70697. ** cannot be converted to a value, then *ppVal is set to NULL.
  70698. */
  70699. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  70700. sqlite3 *db, /* The database connection */
  70701. Expr *pExpr, /* The expression to evaluate */
  70702. u8 enc, /* Encoding to use */
  70703. u8 affinity, /* Affinity to use */
  70704. sqlite3_value **ppVal /* Write the new value here */
  70705. ){
  70706. return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
  70707. }
  70708. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  70709. /*
  70710. ** The implementation of the sqlite_record() function. This function accepts
  70711. ** a single argument of any type. The return value is a formatted database
  70712. ** record (a blob) containing the argument value.
  70713. **
  70714. ** This is used to convert the value stored in the 'sample' column of the
  70715. ** sqlite_stat3 table to the record format SQLite uses internally.
  70716. */
  70717. static void recordFunc(
  70718. sqlite3_context *context,
  70719. int argc,
  70720. sqlite3_value **argv
  70721. ){
  70722. const int file_format = 1;
  70723. u32 iSerial; /* Serial type */
  70724. int nSerial; /* Bytes of space for iSerial as varint */
  70725. u32 nVal; /* Bytes of space required for argv[0] */
  70726. int nRet;
  70727. sqlite3 *db;
  70728. u8 *aRet;
  70729. UNUSED_PARAMETER( argc );
  70730. iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
  70731. nSerial = sqlite3VarintLen(iSerial);
  70732. db = sqlite3_context_db_handle(context);
  70733. nRet = 1 + nSerial + nVal;
  70734. aRet = sqlite3DbMallocRawNN(db, nRet);
  70735. if( aRet==0 ){
  70736. sqlite3_result_error_nomem(context);
  70737. }else{
  70738. aRet[0] = nSerial+1;
  70739. putVarint32(&aRet[1], iSerial);
  70740. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  70741. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  70742. sqlite3DbFreeNN(db, aRet);
  70743. }
  70744. }
  70745. /*
  70746. ** Register built-in functions used to help read ANALYZE data.
  70747. */
  70748. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  70749. static FuncDef aAnalyzeTableFuncs[] = {
  70750. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  70751. };
  70752. sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
  70753. }
  70754. /*
  70755. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  70756. **
  70757. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  70758. ** pAlloc if one does not exist and the new value is added to the
  70759. ** UnpackedRecord object.
  70760. **
  70761. ** A value is extracted in the following cases:
  70762. **
  70763. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  70764. **
  70765. ** * The expression is a bound variable, and this is a reprepare, or
  70766. **
  70767. ** * The expression is a literal value.
  70768. **
  70769. ** On success, *ppVal is made to point to the extracted value. The caller
  70770. ** is responsible for ensuring that the value is eventually freed.
  70771. */
  70772. static int stat4ValueFromExpr(
  70773. Parse *pParse, /* Parse context */
  70774. Expr *pExpr, /* The expression to extract a value from */
  70775. u8 affinity, /* Affinity to use */
  70776. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  70777. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  70778. ){
  70779. int rc = SQLITE_OK;
  70780. sqlite3_value *pVal = 0;
  70781. sqlite3 *db = pParse->db;
  70782. /* Skip over any TK_COLLATE nodes */
  70783. pExpr = sqlite3ExprSkipCollate(pExpr);
  70784. assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
  70785. if( !pExpr ){
  70786. pVal = valueNew(db, pAlloc);
  70787. if( pVal ){
  70788. sqlite3VdbeMemSetNull((Mem*)pVal);
  70789. }
  70790. }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  70791. Vdbe *v;
  70792. int iBindVar = pExpr->iColumn;
  70793. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  70794. if( (v = pParse->pReprepare)!=0 ){
  70795. pVal = valueNew(db, pAlloc);
  70796. if( pVal ){
  70797. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  70798. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  70799. pVal->db = pParse->db;
  70800. }
  70801. }
  70802. }else{
  70803. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  70804. }
  70805. assert( pVal==0 || pVal->db==db );
  70806. *ppVal = pVal;
  70807. return rc;
  70808. }
  70809. /*
  70810. ** This function is used to allocate and populate UnpackedRecord
  70811. ** structures intended to be compared against sample index keys stored
  70812. ** in the sqlite_stat4 table.
  70813. **
  70814. ** A single call to this function populates zero or more fields of the
  70815. ** record starting with field iVal (fields are numbered from left to
  70816. ** right starting with 0). A single field is populated if:
  70817. **
  70818. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  70819. **
  70820. ** * The expression is a bound variable, and this is a reprepare, or
  70821. **
  70822. ** * The sqlite3ValueFromExpr() function is able to extract a value
  70823. ** from the expression (i.e. the expression is a literal value).
  70824. **
  70825. ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
  70826. ** vector components that match either of the two latter criteria listed
  70827. ** above.
  70828. **
  70829. ** Before any value is appended to the record, the affinity of the
  70830. ** corresponding column within index pIdx is applied to it. Before
  70831. ** this function returns, output parameter *pnExtract is set to the
  70832. ** number of values appended to the record.
  70833. **
  70834. ** When this function is called, *ppRec must either point to an object
  70835. ** allocated by an earlier call to this function, or must be NULL. If it
  70836. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  70837. ** is allocated (and *ppRec set to point to it) before returning.
  70838. **
  70839. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  70840. ** error if a value cannot be extracted from pExpr. If an error does
  70841. ** occur, an SQLite error code is returned.
  70842. */
  70843. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  70844. Parse *pParse, /* Parse context */
  70845. Index *pIdx, /* Index being probed */
  70846. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  70847. Expr *pExpr, /* The expression to extract a value from */
  70848. int nElem, /* Maximum number of values to append */
  70849. int iVal, /* Array element to populate */
  70850. int *pnExtract /* OUT: Values appended to the record */
  70851. ){
  70852. int rc = SQLITE_OK;
  70853. int nExtract = 0;
  70854. if( pExpr==0 || pExpr->op!=TK_SELECT ){
  70855. int i;
  70856. struct ValueNewStat4Ctx alloc;
  70857. alloc.pParse = pParse;
  70858. alloc.pIdx = pIdx;
  70859. alloc.ppRec = ppRec;
  70860. for(i=0; i<nElem; i++){
  70861. sqlite3_value *pVal = 0;
  70862. Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
  70863. u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
  70864. alloc.iVal = iVal+i;
  70865. rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
  70866. if( !pVal ) break;
  70867. nExtract++;
  70868. }
  70869. }
  70870. *pnExtract = nExtract;
  70871. return rc;
  70872. }
  70873. /*
  70874. ** Attempt to extract a value from expression pExpr using the methods
  70875. ** as described for sqlite3Stat4ProbeSetValue() above.
  70876. **
  70877. ** If successful, set *ppVal to point to a new value object and return
  70878. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  70879. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  70880. ** does occur, return an SQLite error code. The final value of *ppVal
  70881. ** is undefined in this case.
  70882. */
  70883. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  70884. Parse *pParse, /* Parse context */
  70885. Expr *pExpr, /* The expression to extract a value from */
  70886. u8 affinity, /* Affinity to use */
  70887. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  70888. ){
  70889. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  70890. }
  70891. /*
  70892. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  70893. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  70894. ** sqlite3_value object is allocated.
  70895. **
  70896. ** If *ppVal is initially NULL then the caller is responsible for
  70897. ** ensuring that the value written into *ppVal is eventually freed.
  70898. */
  70899. SQLITE_PRIVATE int sqlite3Stat4Column(
  70900. sqlite3 *db, /* Database handle */
  70901. const void *pRec, /* Pointer to buffer containing record */
  70902. int nRec, /* Size of buffer pRec in bytes */
  70903. int iCol, /* Column to extract */
  70904. sqlite3_value **ppVal /* OUT: Extracted value */
  70905. ){
  70906. u32 t = 0; /* a column type code */
  70907. int nHdr; /* Size of the header in the record */
  70908. int iHdr; /* Next unread header byte */
  70909. int iField; /* Next unread data byte */
  70910. int szField = 0; /* Size of the current data field */
  70911. int i; /* Column index */
  70912. u8 *a = (u8*)pRec; /* Typecast byte array */
  70913. Mem *pMem = *ppVal; /* Write result into this Mem object */
  70914. assert( iCol>0 );
  70915. iHdr = getVarint32(a, nHdr);
  70916. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  70917. iField = nHdr;
  70918. for(i=0; i<=iCol; i++){
  70919. iHdr += getVarint32(&a[iHdr], t);
  70920. testcase( iHdr==nHdr );
  70921. testcase( iHdr==nHdr+1 );
  70922. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  70923. szField = sqlite3VdbeSerialTypeLen(t);
  70924. iField += szField;
  70925. }
  70926. testcase( iField==nRec );
  70927. testcase( iField==nRec+1 );
  70928. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  70929. if( pMem==0 ){
  70930. pMem = *ppVal = sqlite3ValueNew(db);
  70931. if( pMem==0 ) return SQLITE_NOMEM_BKPT;
  70932. }
  70933. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  70934. pMem->enc = ENC(db);
  70935. return SQLITE_OK;
  70936. }
  70937. /*
  70938. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  70939. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  70940. ** the object.
  70941. */
  70942. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  70943. if( pRec ){
  70944. int i;
  70945. int nCol = pRec->pKeyInfo->nAllField;
  70946. Mem *aMem = pRec->aMem;
  70947. sqlite3 *db = aMem[0].db;
  70948. for(i=0; i<nCol; i++){
  70949. sqlite3VdbeMemRelease(&aMem[i]);
  70950. }
  70951. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  70952. sqlite3DbFreeNN(db, pRec);
  70953. }
  70954. }
  70955. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  70956. /*
  70957. ** Change the string value of an sqlite3_value object
  70958. */
  70959. SQLITE_PRIVATE void sqlite3ValueSetStr(
  70960. sqlite3_value *v, /* Value to be set */
  70961. int n, /* Length of string z */
  70962. const void *z, /* Text of the new string */
  70963. u8 enc, /* Encoding to use */
  70964. void (*xDel)(void*) /* Destructor for the string */
  70965. ){
  70966. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  70967. }
  70968. /*
  70969. ** Free an sqlite3_value object
  70970. */
  70971. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  70972. if( !v ) return;
  70973. sqlite3VdbeMemRelease((Mem *)v);
  70974. sqlite3DbFreeNN(((Mem*)v)->db, v);
  70975. }
  70976. /*
  70977. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  70978. ** sqlite3_value object assuming that it uses the encoding "enc".
  70979. ** The valueBytes() routine is a helper function.
  70980. */
  70981. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  70982. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  70983. }
  70984. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  70985. Mem *p = (Mem*)pVal;
  70986. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  70987. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  70988. return p->n;
  70989. }
  70990. if( (p->flags & MEM_Blob)!=0 ){
  70991. if( p->flags & MEM_Zero ){
  70992. return p->n + p->u.nZero;
  70993. }else{
  70994. return p->n;
  70995. }
  70996. }
  70997. if( p->flags & MEM_Null ) return 0;
  70998. return valueBytes(pVal, enc);
  70999. }
  71000. /************** End of vdbemem.c *********************************************/
  71001. /************** Begin file vdbeaux.c *****************************************/
  71002. /*
  71003. ** 2003 September 6
  71004. **
  71005. ** The author disclaims copyright to this source code. In place of
  71006. ** a legal notice, here is a blessing:
  71007. **
  71008. ** May you do good and not evil.
  71009. ** May you find forgiveness for yourself and forgive others.
  71010. ** May you share freely, never taking more than you give.
  71011. **
  71012. *************************************************************************
  71013. ** This file contains code used for creating, destroying, and populating
  71014. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  71015. */
  71016. /* #include "sqliteInt.h" */
  71017. /* #include "vdbeInt.h" */
  71018. /*
  71019. ** Create a new virtual database engine.
  71020. */
  71021. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  71022. sqlite3 *db = pParse->db;
  71023. Vdbe *p;
  71024. p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
  71025. if( p==0 ) return 0;
  71026. memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
  71027. p->db = db;
  71028. if( db->pVdbe ){
  71029. db->pVdbe->pPrev = p;
  71030. }
  71031. p->pNext = db->pVdbe;
  71032. p->pPrev = 0;
  71033. db->pVdbe = p;
  71034. p->magic = VDBE_MAGIC_INIT;
  71035. p->pParse = pParse;
  71036. pParse->pVdbe = p;
  71037. assert( pParse->aLabel==0 );
  71038. assert( pParse->nLabel==0 );
  71039. assert( pParse->nOpAlloc==0 );
  71040. assert( pParse->szOpAlloc==0 );
  71041. sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
  71042. return p;
  71043. }
  71044. /*
  71045. ** Change the error string stored in Vdbe.zErrMsg
  71046. */
  71047. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  71048. va_list ap;
  71049. sqlite3DbFree(p->db, p->zErrMsg);
  71050. va_start(ap, zFormat);
  71051. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  71052. va_end(ap);
  71053. }
  71054. /*
  71055. ** Remember the SQL string for a prepared statement.
  71056. */
  71057. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
  71058. if( p==0 ) return;
  71059. p->prepFlags = prepFlags;
  71060. if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
  71061. p->expmask = 0;
  71062. }
  71063. assert( p->zSql==0 );
  71064. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  71065. #ifdef SQLITE_ENABLE_NORMALIZE
  71066. assert( p->zNormSql==0 );
  71067. if( p->zSql && (prepFlags & SQLITE_PREPARE_NORMALIZE)!=0 ){
  71068. sqlite3Normalize(p, p->zSql, n, prepFlags);
  71069. assert( p->zNormSql!=0 || p->db->mallocFailed );
  71070. }
  71071. #endif
  71072. }
  71073. /*
  71074. ** Swap all content between two VDBE structures.
  71075. */
  71076. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  71077. Vdbe tmp, *pTmp;
  71078. char *zTmp;
  71079. assert( pA->db==pB->db );
  71080. tmp = *pA;
  71081. *pA = *pB;
  71082. *pB = tmp;
  71083. pTmp = pA->pNext;
  71084. pA->pNext = pB->pNext;
  71085. pB->pNext = pTmp;
  71086. pTmp = pA->pPrev;
  71087. pA->pPrev = pB->pPrev;
  71088. pB->pPrev = pTmp;
  71089. zTmp = pA->zSql;
  71090. pA->zSql = pB->zSql;
  71091. pB->zSql = zTmp;
  71092. #ifdef SQLITE_ENABLE_NORMALIZE
  71093. zTmp = pA->zNormSql;
  71094. pA->zNormSql = pB->zNormSql;
  71095. pB->zNormSql = zTmp;
  71096. #endif
  71097. pB->expmask = pA->expmask;
  71098. pB->prepFlags = pA->prepFlags;
  71099. memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
  71100. pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
  71101. }
  71102. /*
  71103. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  71104. ** than its current size. nOp is guaranteed to be less than or equal
  71105. ** to 1024/sizeof(Op).
  71106. **
  71107. ** If an out-of-memory error occurs while resizing the array, return
  71108. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  71109. ** unchanged (this is so that any opcodes already allocated can be
  71110. ** correctly deallocated along with the rest of the Vdbe).
  71111. */
  71112. static int growOpArray(Vdbe *v, int nOp){
  71113. VdbeOp *pNew;
  71114. Parse *p = v->pParse;
  71115. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  71116. ** more frequent reallocs and hence provide more opportunities for
  71117. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  71118. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  71119. ** by the minimum* amount required until the size reaches 512. Normal
  71120. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  71121. ** size of the op array or add 1KB of space, whichever is smaller. */
  71122. #ifdef SQLITE_TEST_REALLOC_STRESS
  71123. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  71124. #else
  71125. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  71126. UNUSED_PARAMETER(nOp);
  71127. #endif
  71128. /* Ensure that the size of a VDBE does not grow too large */
  71129. if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
  71130. sqlite3OomFault(p->db);
  71131. return SQLITE_NOMEM;
  71132. }
  71133. assert( nOp<=(1024/sizeof(Op)) );
  71134. assert( nNew>=(p->nOpAlloc+nOp) );
  71135. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  71136. if( pNew ){
  71137. p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
  71138. p->nOpAlloc = p->szOpAlloc/sizeof(Op);
  71139. v->aOp = pNew;
  71140. }
  71141. return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
  71142. }
  71143. #ifdef SQLITE_DEBUG
  71144. /* This routine is just a convenient place to set a breakpoint that will
  71145. ** fire after each opcode is inserted and displayed using
  71146. ** "PRAGMA vdbe_addoptrace=on".
  71147. */
  71148. static void test_addop_breakpoint(void){
  71149. static int n = 0;
  71150. n++;
  71151. }
  71152. #endif
  71153. /*
  71154. ** Add a new instruction to the list of instructions current in the
  71155. ** VDBE. Return the address of the new instruction.
  71156. **
  71157. ** Parameters:
  71158. **
  71159. ** p Pointer to the VDBE
  71160. **
  71161. ** op The opcode for this instruction
  71162. **
  71163. ** p1, p2, p3 Operands
  71164. **
  71165. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  71166. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  71167. ** operand.
  71168. */
  71169. static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
  71170. assert( p->pParse->nOpAlloc<=p->nOp );
  71171. if( growOpArray(p, 1) ) return 1;
  71172. assert( p->pParse->nOpAlloc>p->nOp );
  71173. return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  71174. }
  71175. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  71176. int i;
  71177. VdbeOp *pOp;
  71178. i = p->nOp;
  71179. assert( p->magic==VDBE_MAGIC_INIT );
  71180. assert( op>=0 && op<0xff );
  71181. if( p->pParse->nOpAlloc<=i ){
  71182. return growOp3(p, op, p1, p2, p3);
  71183. }
  71184. p->nOp++;
  71185. pOp = &p->aOp[i];
  71186. pOp->opcode = (u8)op;
  71187. pOp->p5 = 0;
  71188. pOp->p1 = p1;
  71189. pOp->p2 = p2;
  71190. pOp->p3 = p3;
  71191. pOp->p4.p = 0;
  71192. pOp->p4type = P4_NOTUSED;
  71193. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  71194. pOp->zComment = 0;
  71195. #endif
  71196. #ifdef SQLITE_DEBUG
  71197. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  71198. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  71199. test_addop_breakpoint();
  71200. }
  71201. #endif
  71202. #ifdef VDBE_PROFILE
  71203. pOp->cycles = 0;
  71204. pOp->cnt = 0;
  71205. #endif
  71206. #ifdef SQLITE_VDBE_COVERAGE
  71207. pOp->iSrcLine = 0;
  71208. #endif
  71209. return i;
  71210. }
  71211. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  71212. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  71213. }
  71214. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  71215. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  71216. }
  71217. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  71218. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  71219. }
  71220. /* Generate code for an unconditional jump to instruction iDest
  71221. */
  71222. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  71223. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  71224. }
  71225. /* Generate code to cause the string zStr to be loaded into
  71226. ** register iDest
  71227. */
  71228. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  71229. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  71230. }
  71231. /*
  71232. ** Generate code that initializes multiple registers to string or integer
  71233. ** constants. The registers begin with iDest and increase consecutively.
  71234. ** One register is initialized for each characgter in zTypes[]. For each
  71235. ** "s" character in zTypes[], the register is a string if the argument is
  71236. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  71237. ** in zTypes[], the register is initialized to an integer.
  71238. **
  71239. ** If the input string does not end with "X" then an OP_ResultRow instruction
  71240. ** is generated for the values inserted.
  71241. */
  71242. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  71243. va_list ap;
  71244. int i;
  71245. char c;
  71246. va_start(ap, zTypes);
  71247. for(i=0; (c = zTypes[i])!=0; i++){
  71248. if( c=='s' ){
  71249. const char *z = va_arg(ap, const char*);
  71250. sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
  71251. }else if( c=='i' ){
  71252. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
  71253. }else{
  71254. goto skip_op_resultrow;
  71255. }
  71256. }
  71257. sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
  71258. skip_op_resultrow:
  71259. va_end(ap);
  71260. }
  71261. /*
  71262. ** Add an opcode that includes the p4 value as a pointer.
  71263. */
  71264. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  71265. Vdbe *p, /* Add the opcode to this VM */
  71266. int op, /* The new opcode */
  71267. int p1, /* The P1 operand */
  71268. int p2, /* The P2 operand */
  71269. int p3, /* The P3 operand */
  71270. const char *zP4, /* The P4 operand */
  71271. int p4type /* P4 operand type */
  71272. ){
  71273. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  71274. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  71275. return addr;
  71276. }
  71277. /*
  71278. ** Add an opcode that includes the p4 value with a P4_INT64 or
  71279. ** P4_REAL type.
  71280. */
  71281. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  71282. Vdbe *p, /* Add the opcode to this VM */
  71283. int op, /* The new opcode */
  71284. int p1, /* The P1 operand */
  71285. int p2, /* The P2 operand */
  71286. int p3, /* The P3 operand */
  71287. const u8 *zP4, /* The P4 operand */
  71288. int p4type /* P4 operand type */
  71289. ){
  71290. char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
  71291. if( p4copy ) memcpy(p4copy, zP4, 8);
  71292. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  71293. }
  71294. #ifndef SQLITE_OMIT_EXPLAIN
  71295. /*
  71296. ** Return the address of the current EXPLAIN QUERY PLAN baseline.
  71297. ** 0 means "none".
  71298. */
  71299. SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse *pParse){
  71300. VdbeOp *pOp;
  71301. if( pParse->addrExplain==0 ) return 0;
  71302. pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
  71303. return pOp->p2;
  71304. }
  71305. /*
  71306. ** Add a new OP_Explain opcode.
  71307. **
  71308. ** If the bPush flag is true, then make this opcode the parent for
  71309. ** subsequent Explains until sqlite3VdbeExplainPop() is called.
  71310. */
  71311. SQLITE_PRIVATE void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
  71312. if( pParse->explain==2 ){
  71313. char *zMsg;
  71314. Vdbe *v;
  71315. va_list ap;
  71316. int iThis;
  71317. va_start(ap, zFmt);
  71318. zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
  71319. va_end(ap);
  71320. v = pParse->pVdbe;
  71321. iThis = v->nOp;
  71322. sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
  71323. zMsg, P4_DYNAMIC);
  71324. if( bPush) pParse->addrExplain = iThis;
  71325. }
  71326. }
  71327. /*
  71328. ** Pop the EXPLAIN QUERY PLAN stack one level.
  71329. */
  71330. SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){
  71331. pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
  71332. }
  71333. #endif /* SQLITE_OMIT_EXPLAIN */
  71334. /*
  71335. ** Add an OP_ParseSchema opcode. This routine is broken out from
  71336. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  71337. ** as having been used.
  71338. **
  71339. ** The zWhere string must have been obtained from sqlite3_malloc().
  71340. ** This routine will take ownership of the allocated memory.
  71341. */
  71342. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  71343. int j;
  71344. sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  71345. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  71346. }
  71347. /*
  71348. ** Add an opcode that includes the p4 value as an integer.
  71349. */
  71350. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  71351. Vdbe *p, /* Add the opcode to this VM */
  71352. int op, /* The new opcode */
  71353. int p1, /* The P1 operand */
  71354. int p2, /* The P2 operand */
  71355. int p3, /* The P3 operand */
  71356. int p4 /* The P4 operand as an integer */
  71357. ){
  71358. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  71359. if( p->db->mallocFailed==0 ){
  71360. VdbeOp *pOp = &p->aOp[addr];
  71361. pOp->p4type = P4_INT32;
  71362. pOp->p4.i = p4;
  71363. }
  71364. return addr;
  71365. }
  71366. /* Insert the end of a co-routine
  71367. */
  71368. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
  71369. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  71370. /* Clear the temporary register cache, thereby ensuring that each
  71371. ** co-routine has its own independent set of registers, because co-routines
  71372. ** might expect their registers to be preserved across an OP_Yield, and
  71373. ** that could cause problems if two or more co-routines are using the same
  71374. ** temporary register.
  71375. */
  71376. v->pParse->nTempReg = 0;
  71377. v->pParse->nRangeReg = 0;
  71378. }
  71379. /*
  71380. ** Create a new symbolic label for an instruction that has yet to be
  71381. ** coded. The symbolic label is really just a negative number. The
  71382. ** label can be used as the P2 value of an operation. Later, when
  71383. ** the label is resolved to a specific address, the VDBE will scan
  71384. ** through its operation list and change all values of P2 which match
  71385. ** the label into the resolved address.
  71386. **
  71387. ** The VDBE knows that a P2 value is a label because labels are
  71388. ** always negative and P2 values are suppose to be non-negative.
  71389. ** Hence, a negative P2 value is a label that has yet to be resolved.
  71390. **
  71391. ** Zero is returned if a malloc() fails.
  71392. */
  71393. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  71394. Parse *p = v->pParse;
  71395. int i = p->nLabel++;
  71396. assert( v->magic==VDBE_MAGIC_INIT );
  71397. if( (i & (i-1))==0 ){
  71398. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  71399. (i*2+1)*sizeof(p->aLabel[0]));
  71400. }
  71401. if( p->aLabel ){
  71402. p->aLabel[i] = -1;
  71403. }
  71404. return ADDR(i);
  71405. }
  71406. /*
  71407. ** Resolve label "x" to be the address of the next instruction to
  71408. ** be inserted. The parameter "x" must have been obtained from
  71409. ** a prior call to sqlite3VdbeMakeLabel().
  71410. */
  71411. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  71412. Parse *p = v->pParse;
  71413. int j = ADDR(x);
  71414. assert( v->magic==VDBE_MAGIC_INIT );
  71415. assert( j<p->nLabel );
  71416. assert( j>=0 );
  71417. if( p->aLabel ){
  71418. #ifdef SQLITE_DEBUG
  71419. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  71420. printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
  71421. }
  71422. #endif
  71423. assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
  71424. p->aLabel[j] = v->nOp;
  71425. }
  71426. }
  71427. /*
  71428. ** Mark the VDBE as one that can only be run one time.
  71429. */
  71430. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  71431. p->runOnlyOnce = 1;
  71432. }
  71433. /*
  71434. ** Mark the VDBE as one that can only be run multiple times.
  71435. */
  71436. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
  71437. p->runOnlyOnce = 0;
  71438. }
  71439. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  71440. /*
  71441. ** The following type and function are used to iterate through all opcodes
  71442. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  71443. ** invoke directly or indirectly. It should be used as follows:
  71444. **
  71445. ** Op *pOp;
  71446. ** VdbeOpIter sIter;
  71447. **
  71448. ** memset(&sIter, 0, sizeof(sIter));
  71449. ** sIter.v = v; // v is of type Vdbe*
  71450. ** while( (pOp = opIterNext(&sIter)) ){
  71451. ** // Do something with pOp
  71452. ** }
  71453. ** sqlite3DbFree(v->db, sIter.apSub);
  71454. **
  71455. */
  71456. typedef struct VdbeOpIter VdbeOpIter;
  71457. struct VdbeOpIter {
  71458. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  71459. SubProgram **apSub; /* Array of subprograms */
  71460. int nSub; /* Number of entries in apSub */
  71461. int iAddr; /* Address of next instruction to return */
  71462. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  71463. };
  71464. static Op *opIterNext(VdbeOpIter *p){
  71465. Vdbe *v = p->v;
  71466. Op *pRet = 0;
  71467. Op *aOp;
  71468. int nOp;
  71469. if( p->iSub<=p->nSub ){
  71470. if( p->iSub==0 ){
  71471. aOp = v->aOp;
  71472. nOp = v->nOp;
  71473. }else{
  71474. aOp = p->apSub[p->iSub-1]->aOp;
  71475. nOp = p->apSub[p->iSub-1]->nOp;
  71476. }
  71477. assert( p->iAddr<nOp );
  71478. pRet = &aOp[p->iAddr];
  71479. p->iAddr++;
  71480. if( p->iAddr==nOp ){
  71481. p->iSub++;
  71482. p->iAddr = 0;
  71483. }
  71484. if( pRet->p4type==P4_SUBPROGRAM ){
  71485. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  71486. int j;
  71487. for(j=0; j<p->nSub; j++){
  71488. if( p->apSub[j]==pRet->p4.pProgram ) break;
  71489. }
  71490. if( j==p->nSub ){
  71491. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  71492. if( !p->apSub ){
  71493. pRet = 0;
  71494. }else{
  71495. p->apSub[p->nSub++] = pRet->p4.pProgram;
  71496. }
  71497. }
  71498. }
  71499. }
  71500. return pRet;
  71501. }
  71502. /*
  71503. ** Check if the program stored in the VM associated with pParse may
  71504. ** throw an ABORT exception (causing the statement, but not entire transaction
  71505. ** to be rolled back). This condition is true if the main program or any
  71506. ** sub-programs contains any of the following:
  71507. **
  71508. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  71509. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  71510. ** * OP_Destroy
  71511. ** * OP_VUpdate
  71512. ** * OP_VRename
  71513. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  71514. ** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
  71515. ** (for CREATE TABLE AS SELECT ...)
  71516. **
  71517. ** Then check that the value of Parse.mayAbort is true if an
  71518. ** ABORT may be thrown, or false otherwise. Return true if it does
  71519. ** match, or false otherwise. This function is intended to be used as
  71520. ** part of an assert statement in the compiler. Similar to:
  71521. **
  71522. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  71523. */
  71524. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  71525. int hasAbort = 0;
  71526. int hasFkCounter = 0;
  71527. int hasCreateTable = 0;
  71528. int hasInitCoroutine = 0;
  71529. Op *pOp;
  71530. VdbeOpIter sIter;
  71531. memset(&sIter, 0, sizeof(sIter));
  71532. sIter.v = v;
  71533. while( (pOp = opIterNext(&sIter))!=0 ){
  71534. int opcode = pOp->opcode;
  71535. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  71536. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  71537. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  71538. ){
  71539. hasAbort = 1;
  71540. break;
  71541. }
  71542. if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
  71543. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  71544. #ifndef SQLITE_OMIT_FOREIGN_KEY
  71545. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  71546. hasFkCounter = 1;
  71547. }
  71548. #endif
  71549. }
  71550. sqlite3DbFree(v->db, sIter.apSub);
  71551. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  71552. ** If malloc failed, then the while() loop above may not have iterated
  71553. ** through all opcodes and hasAbort may be set incorrectly. Return
  71554. ** true for this case to prevent the assert() in the callers frame
  71555. ** from failing. */
  71556. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  71557. || (hasCreateTable && hasInitCoroutine) );
  71558. }
  71559. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  71560. #ifdef SQLITE_DEBUG
  71561. /*
  71562. ** Increment the nWrite counter in the VDBE if the cursor is not an
  71563. ** ephemeral cursor, or if the cursor argument is NULL.
  71564. */
  71565. SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
  71566. if( pC==0
  71567. || (pC->eCurType!=CURTYPE_SORTER
  71568. && pC->eCurType!=CURTYPE_PSEUDO
  71569. && !pC->isEphemeral)
  71570. ){
  71571. p->nWrite++;
  71572. }
  71573. }
  71574. #endif
  71575. #ifdef SQLITE_DEBUG
  71576. /*
  71577. ** Assert if an Abort at this point in time might result in a corrupt
  71578. ** database.
  71579. */
  71580. SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){
  71581. assert( p->nWrite==0 || p->usesStmtJournal );
  71582. }
  71583. #endif
  71584. /*
  71585. ** This routine is called after all opcodes have been inserted. It loops
  71586. ** through all the opcodes and fixes up some details.
  71587. **
  71588. ** (1) For each jump instruction with a negative P2 value (a label)
  71589. ** resolve the P2 value to an actual address.
  71590. **
  71591. ** (2) Compute the maximum number of arguments used by any SQL function
  71592. ** and store that value in *pMaxFuncArgs.
  71593. **
  71594. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  71595. ** indicate what the prepared statement actually does.
  71596. **
  71597. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  71598. **
  71599. ** (5) Reclaim the memory allocated for storing labels.
  71600. **
  71601. ** This routine will only function correctly if the mkopcodeh.tcl generator
  71602. ** script numbers the opcodes correctly. Changes to this routine must be
  71603. ** coordinated with changes to mkopcodeh.tcl.
  71604. */
  71605. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  71606. int nMaxArgs = *pMaxFuncArgs;
  71607. Op *pOp;
  71608. Parse *pParse = p->pParse;
  71609. int *aLabel = pParse->aLabel;
  71610. p->readOnly = 1;
  71611. p->bIsReader = 0;
  71612. pOp = &p->aOp[p->nOp-1];
  71613. while(1){
  71614. /* Only JUMP opcodes and the short list of special opcodes in the switch
  71615. ** below need to be considered. The mkopcodeh.tcl generator script groups
  71616. ** all these opcodes together near the front of the opcode list. Skip
  71617. ** any opcode that does not need processing by virtual of the fact that
  71618. ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
  71619. */
  71620. if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
  71621. /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
  71622. ** cases from this switch! */
  71623. switch( pOp->opcode ){
  71624. case OP_Transaction: {
  71625. if( pOp->p2!=0 ) p->readOnly = 0;
  71626. /* fall thru */
  71627. }
  71628. case OP_AutoCommit:
  71629. case OP_Savepoint: {
  71630. p->bIsReader = 1;
  71631. break;
  71632. }
  71633. #ifndef SQLITE_OMIT_WAL
  71634. case OP_Checkpoint:
  71635. #endif
  71636. case OP_Vacuum:
  71637. case OP_JournalMode: {
  71638. p->readOnly = 0;
  71639. p->bIsReader = 1;
  71640. break;
  71641. }
  71642. case OP_Next:
  71643. case OP_SorterNext: {
  71644. pOp->p4.xAdvance = sqlite3BtreeNext;
  71645. pOp->p4type = P4_ADVANCE;
  71646. /* The code generator never codes any of these opcodes as a jump
  71647. ** to a label. They are always coded as a jump backwards to a
  71648. ** known address */
  71649. assert( pOp->p2>=0 );
  71650. break;
  71651. }
  71652. case OP_Prev: {
  71653. pOp->p4.xAdvance = sqlite3BtreePrevious;
  71654. pOp->p4type = P4_ADVANCE;
  71655. /* The code generator never codes any of these opcodes as a jump
  71656. ** to a label. They are always coded as a jump backwards to a
  71657. ** known address */
  71658. assert( pOp->p2>=0 );
  71659. break;
  71660. }
  71661. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71662. case OP_VUpdate: {
  71663. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  71664. break;
  71665. }
  71666. case OP_VFilter: {
  71667. int n;
  71668. assert( (pOp - p->aOp) >= 3 );
  71669. assert( pOp[-1].opcode==OP_Integer );
  71670. n = pOp[-1].p1;
  71671. if( n>nMaxArgs ) nMaxArgs = n;
  71672. /* Fall through into the default case */
  71673. }
  71674. #endif
  71675. default: {
  71676. if( pOp->p2<0 ){
  71677. /* The mkopcodeh.tcl script has so arranged things that the only
  71678. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  71679. ** have non-negative values for P2. */
  71680. assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
  71681. assert( ADDR(pOp->p2)<pParse->nLabel );
  71682. pOp->p2 = aLabel[ADDR(pOp->p2)];
  71683. }
  71684. break;
  71685. }
  71686. }
  71687. /* The mkopcodeh.tcl script has so arranged things that the only
  71688. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  71689. ** have non-negative values for P2. */
  71690. assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
  71691. }
  71692. if( pOp==p->aOp ) break;
  71693. pOp--;
  71694. }
  71695. sqlite3DbFree(p->db, pParse->aLabel);
  71696. pParse->aLabel = 0;
  71697. pParse->nLabel = 0;
  71698. *pMaxFuncArgs = nMaxArgs;
  71699. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  71700. }
  71701. /*
  71702. ** Return the address of the next instruction to be inserted.
  71703. */
  71704. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  71705. assert( p->magic==VDBE_MAGIC_INIT );
  71706. return p->nOp;
  71707. }
  71708. /*
  71709. ** Verify that at least N opcode slots are available in p without
  71710. ** having to malloc for more space (except when compiled using
  71711. ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
  71712. ** to verify that certain calls to sqlite3VdbeAddOpList() can never
  71713. ** fail due to a OOM fault and hence that the return value from
  71714. ** sqlite3VdbeAddOpList() will always be non-NULL.
  71715. */
  71716. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  71717. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
  71718. assert( p->nOp + N <= p->pParse->nOpAlloc );
  71719. }
  71720. #endif
  71721. /*
  71722. ** Verify that the VM passed as the only argument does not contain
  71723. ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
  71724. ** by code in pragma.c to ensure that the implementation of certain
  71725. ** pragmas comports with the flags specified in the mkpragmatab.tcl
  71726. ** script.
  71727. */
  71728. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  71729. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
  71730. int i;
  71731. for(i=0; i<p->nOp; i++){
  71732. assert( p->aOp[i].opcode!=OP_ResultRow );
  71733. }
  71734. }
  71735. #endif
  71736. /*
  71737. ** Generate code (a single OP_Abortable opcode) that will
  71738. ** verify that the VDBE program can safely call Abort in the current
  71739. ** context.
  71740. */
  71741. #if defined(SQLITE_DEBUG)
  71742. SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
  71743. if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
  71744. }
  71745. #endif
  71746. /*
  71747. ** This function returns a pointer to the array of opcodes associated with
  71748. ** the Vdbe passed as the first argument. It is the callers responsibility
  71749. ** to arrange for the returned array to be eventually freed using the
  71750. ** vdbeFreeOpArray() function.
  71751. **
  71752. ** Before returning, *pnOp is set to the number of entries in the returned
  71753. ** array. Also, *pnMaxArg is set to the larger of its current value and
  71754. ** the number of entries in the Vdbe.apArg[] array required to execute the
  71755. ** returned program.
  71756. */
  71757. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  71758. VdbeOp *aOp = p->aOp;
  71759. assert( aOp && !p->db->mallocFailed );
  71760. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  71761. assert( DbMaskAllZero(p->btreeMask) );
  71762. resolveP2Values(p, pnMaxArg);
  71763. *pnOp = p->nOp;
  71764. p->aOp = 0;
  71765. return aOp;
  71766. }
  71767. /*
  71768. ** Add a whole list of operations to the operation stack. Return a
  71769. ** pointer to the first operation inserted.
  71770. **
  71771. ** Non-zero P2 arguments to jump instructions are automatically adjusted
  71772. ** so that the jump target is relative to the first operation inserted.
  71773. */
  71774. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
  71775. Vdbe *p, /* Add opcodes to the prepared statement */
  71776. int nOp, /* Number of opcodes to add */
  71777. VdbeOpList const *aOp, /* The opcodes to be added */
  71778. int iLineno /* Source-file line number of first opcode */
  71779. ){
  71780. int i;
  71781. VdbeOp *pOut, *pFirst;
  71782. assert( nOp>0 );
  71783. assert( p->magic==VDBE_MAGIC_INIT );
  71784. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  71785. return 0;
  71786. }
  71787. pFirst = pOut = &p->aOp[p->nOp];
  71788. for(i=0; i<nOp; i++, aOp++, pOut++){
  71789. pOut->opcode = aOp->opcode;
  71790. pOut->p1 = aOp->p1;
  71791. pOut->p2 = aOp->p2;
  71792. assert( aOp->p2>=0 );
  71793. if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
  71794. pOut->p2 += p->nOp;
  71795. }
  71796. pOut->p3 = aOp->p3;
  71797. pOut->p4type = P4_NOTUSED;
  71798. pOut->p4.p = 0;
  71799. pOut->p5 = 0;
  71800. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  71801. pOut->zComment = 0;
  71802. #endif
  71803. #ifdef SQLITE_VDBE_COVERAGE
  71804. pOut->iSrcLine = iLineno+i;
  71805. #else
  71806. (void)iLineno;
  71807. #endif
  71808. #ifdef SQLITE_DEBUG
  71809. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  71810. sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
  71811. }
  71812. #endif
  71813. }
  71814. p->nOp += nOp;
  71815. return pFirst;
  71816. }
  71817. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  71818. /*
  71819. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  71820. */
  71821. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  71822. Vdbe *p, /* VM to add scanstatus() to */
  71823. int addrExplain, /* Address of OP_Explain (or 0) */
  71824. int addrLoop, /* Address of loop counter */
  71825. int addrVisit, /* Address of rows visited counter */
  71826. LogEst nEst, /* Estimated number of output rows */
  71827. const char *zName /* Name of table or index being scanned */
  71828. ){
  71829. int nByte = (p->nScan+1) * sizeof(ScanStatus);
  71830. ScanStatus *aNew;
  71831. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  71832. if( aNew ){
  71833. ScanStatus *pNew = &aNew[p->nScan++];
  71834. pNew->addrExplain = addrExplain;
  71835. pNew->addrLoop = addrLoop;
  71836. pNew->addrVisit = addrVisit;
  71837. pNew->nEst = nEst;
  71838. pNew->zName = sqlite3DbStrDup(p->db, zName);
  71839. p->aScan = aNew;
  71840. }
  71841. }
  71842. #endif
  71843. /*
  71844. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  71845. ** for a specific instruction.
  71846. */
  71847. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
  71848. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  71849. }
  71850. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  71851. sqlite3VdbeGetOp(p,addr)->p1 = val;
  71852. }
  71853. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  71854. sqlite3VdbeGetOp(p,addr)->p2 = val;
  71855. }
  71856. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  71857. sqlite3VdbeGetOp(p,addr)->p3 = val;
  71858. }
  71859. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
  71860. assert( p->nOp>0 || p->db->mallocFailed );
  71861. if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
  71862. }
  71863. /*
  71864. ** Change the P2 operand of instruction addr so that it points to
  71865. ** the address of the next instruction to be coded.
  71866. */
  71867. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  71868. sqlite3VdbeChangeP2(p, addr, p->nOp);
  71869. }
  71870. /*
  71871. ** If the input FuncDef structure is ephemeral, then free it. If
  71872. ** the FuncDef is not ephermal, then do nothing.
  71873. */
  71874. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  71875. if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  71876. sqlite3DbFreeNN(db, pDef);
  71877. }
  71878. }
  71879. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  71880. /*
  71881. ** Delete a P4 value if necessary.
  71882. */
  71883. static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
  71884. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  71885. sqlite3DbFreeNN(db, p);
  71886. }
  71887. static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
  71888. freeEphemeralFunction(db, p->pFunc);
  71889. sqlite3DbFreeNN(db, p);
  71890. }
  71891. static void freeP4(sqlite3 *db, int p4type, void *p4){
  71892. assert( db );
  71893. switch( p4type ){
  71894. case P4_FUNCCTX: {
  71895. freeP4FuncCtx(db, (sqlite3_context*)p4);
  71896. break;
  71897. }
  71898. case P4_REAL:
  71899. case P4_INT64:
  71900. case P4_DYNAMIC:
  71901. case P4_DYNBLOB:
  71902. case P4_INTARRAY: {
  71903. sqlite3DbFree(db, p4);
  71904. break;
  71905. }
  71906. case P4_KEYINFO: {
  71907. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  71908. break;
  71909. }
  71910. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  71911. case P4_EXPR: {
  71912. sqlite3ExprDelete(db, (Expr*)p4);
  71913. break;
  71914. }
  71915. #endif
  71916. case P4_FUNCDEF: {
  71917. freeEphemeralFunction(db, (FuncDef*)p4);
  71918. break;
  71919. }
  71920. case P4_MEM: {
  71921. if( db->pnBytesFreed==0 ){
  71922. sqlite3ValueFree((sqlite3_value*)p4);
  71923. }else{
  71924. freeP4Mem(db, (Mem*)p4);
  71925. }
  71926. break;
  71927. }
  71928. case P4_VTAB : {
  71929. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  71930. break;
  71931. }
  71932. }
  71933. }
  71934. /*
  71935. ** Free the space allocated for aOp and any p4 values allocated for the
  71936. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  71937. ** nOp entries.
  71938. */
  71939. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  71940. if( aOp ){
  71941. Op *pOp;
  71942. for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
  71943. if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
  71944. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  71945. sqlite3DbFree(db, pOp->zComment);
  71946. #endif
  71947. }
  71948. sqlite3DbFreeNN(db, aOp);
  71949. }
  71950. }
  71951. /*
  71952. ** Link the SubProgram object passed as the second argument into the linked
  71953. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  71954. ** objects when the VM is no longer required.
  71955. */
  71956. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  71957. p->pNext = pVdbe->pProgram;
  71958. pVdbe->pProgram = p;
  71959. }
  71960. /*
  71961. ** Change the opcode at addr into OP_Noop
  71962. */
  71963. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  71964. VdbeOp *pOp;
  71965. if( p->db->mallocFailed ) return 0;
  71966. assert( addr>=0 && addr<p->nOp );
  71967. pOp = &p->aOp[addr];
  71968. freeP4(p->db, pOp->p4type, pOp->p4.p);
  71969. pOp->p4type = P4_NOTUSED;
  71970. pOp->p4.z = 0;
  71971. pOp->opcode = OP_Noop;
  71972. return 1;
  71973. }
  71974. /*
  71975. ** If the last opcode is "op" and it is not a jump destination,
  71976. ** then remove it. Return true if and only if an opcode was removed.
  71977. */
  71978. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  71979. if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
  71980. return sqlite3VdbeChangeToNoop(p, p->nOp-1);
  71981. }else{
  71982. return 0;
  71983. }
  71984. }
  71985. /*
  71986. ** Change the value of the P4 operand for a specific instruction.
  71987. ** This routine is useful when a large program is loaded from a
  71988. ** static array using sqlite3VdbeAddOpList but we want to make a
  71989. ** few minor changes to the program.
  71990. **
  71991. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  71992. ** the string is made into memory obtained from sqlite3_malloc().
  71993. ** A value of n==0 means copy bytes of zP4 up to and including the
  71994. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  71995. **
  71996. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  71997. ** to a string or structure that is guaranteed to exist for the lifetime of
  71998. ** the Vdbe. In these cases we can just copy the pointer.
  71999. **
  72000. ** If addr<0 then change P4 on the most recently inserted instruction.
  72001. */
  72002. static void SQLITE_NOINLINE vdbeChangeP4Full(
  72003. Vdbe *p,
  72004. Op *pOp,
  72005. const char *zP4,
  72006. int n
  72007. ){
  72008. if( pOp->p4type ){
  72009. freeP4(p->db, pOp->p4type, pOp->p4.p);
  72010. pOp->p4type = 0;
  72011. pOp->p4.p = 0;
  72012. }
  72013. if( n<0 ){
  72014. sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
  72015. }else{
  72016. if( n==0 ) n = sqlite3Strlen30(zP4);
  72017. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  72018. pOp->p4type = P4_DYNAMIC;
  72019. }
  72020. }
  72021. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  72022. Op *pOp;
  72023. sqlite3 *db;
  72024. assert( p!=0 );
  72025. db = p->db;
  72026. assert( p->magic==VDBE_MAGIC_INIT );
  72027. assert( p->aOp!=0 || db->mallocFailed );
  72028. if( db->mallocFailed ){
  72029. if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
  72030. return;
  72031. }
  72032. assert( p->nOp>0 );
  72033. assert( addr<p->nOp );
  72034. if( addr<0 ){
  72035. addr = p->nOp - 1;
  72036. }
  72037. pOp = &p->aOp[addr];
  72038. if( n>=0 || pOp->p4type ){
  72039. vdbeChangeP4Full(p, pOp, zP4, n);
  72040. return;
  72041. }
  72042. if( n==P4_INT32 ){
  72043. /* Note: this cast is safe, because the origin data point was an int
  72044. ** that was cast to a (const char *). */
  72045. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  72046. pOp->p4type = P4_INT32;
  72047. }else if( zP4!=0 ){
  72048. assert( n<0 );
  72049. pOp->p4.p = (void*)zP4;
  72050. pOp->p4type = (signed char)n;
  72051. if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
  72052. }
  72053. }
  72054. /*
  72055. ** Change the P4 operand of the most recently coded instruction
  72056. ** to the value defined by the arguments. This is a high-speed
  72057. ** version of sqlite3VdbeChangeP4().
  72058. **
  72059. ** The P4 operand must not have been previously defined. And the new
  72060. ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
  72061. ** those cases.
  72062. */
  72063. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
  72064. VdbeOp *pOp;
  72065. assert( n!=P4_INT32 && n!=P4_VTAB );
  72066. assert( n<=0 );
  72067. if( p->db->mallocFailed ){
  72068. freeP4(p->db, n, pP4);
  72069. }else{
  72070. assert( pP4!=0 );
  72071. assert( p->nOp>0 );
  72072. pOp = &p->aOp[p->nOp-1];
  72073. assert( pOp->p4type==P4_NOTUSED );
  72074. pOp->p4type = n;
  72075. pOp->p4.p = pP4;
  72076. }
  72077. }
  72078. /*
  72079. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  72080. ** index given.
  72081. */
  72082. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  72083. Vdbe *v = pParse->pVdbe;
  72084. KeyInfo *pKeyInfo;
  72085. assert( v!=0 );
  72086. assert( pIdx!=0 );
  72087. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
  72088. if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  72089. }
  72090. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  72091. /*
  72092. ** Change the comment on the most recently coded instruction. Or
  72093. ** insert a No-op and add the comment to that new instruction. This
  72094. ** makes the code easier to read during debugging. None of this happens
  72095. ** in a production build.
  72096. */
  72097. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  72098. assert( p->nOp>0 || p->aOp==0 );
  72099. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  72100. if( p->nOp ){
  72101. assert( p->aOp );
  72102. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  72103. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  72104. }
  72105. }
  72106. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  72107. va_list ap;
  72108. if( p ){
  72109. va_start(ap, zFormat);
  72110. vdbeVComment(p, zFormat, ap);
  72111. va_end(ap);
  72112. }
  72113. }
  72114. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  72115. va_list ap;
  72116. if( p ){
  72117. sqlite3VdbeAddOp0(p, OP_Noop);
  72118. va_start(ap, zFormat);
  72119. vdbeVComment(p, zFormat, ap);
  72120. va_end(ap);
  72121. }
  72122. }
  72123. #endif /* NDEBUG */
  72124. #ifdef SQLITE_VDBE_COVERAGE
  72125. /*
  72126. ** Set the value if the iSrcLine field for the previously coded instruction.
  72127. */
  72128. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  72129. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  72130. }
  72131. #endif /* SQLITE_VDBE_COVERAGE */
  72132. /*
  72133. ** Return the opcode for a given address. If the address is -1, then
  72134. ** return the most recently inserted opcode.
  72135. **
  72136. ** If a memory allocation error has occurred prior to the calling of this
  72137. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  72138. ** is readable but not writable, though it is cast to a writable value.
  72139. ** The return of a dummy opcode allows the call to continue functioning
  72140. ** after an OOM fault without having to check to see if the return from
  72141. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  72142. ** dummy will never be written to. This is verified by code inspection and
  72143. ** by running with Valgrind.
  72144. */
  72145. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  72146. /* C89 specifies that the constant "dummy" will be initialized to all
  72147. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  72148. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  72149. assert( p->magic==VDBE_MAGIC_INIT );
  72150. if( addr<0 ){
  72151. addr = p->nOp - 1;
  72152. }
  72153. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  72154. if( p->db->mallocFailed ){
  72155. return (VdbeOp*)&dummy;
  72156. }else{
  72157. return &p->aOp[addr];
  72158. }
  72159. }
  72160. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  72161. /*
  72162. ** Return an integer value for one of the parameters to the opcode pOp
  72163. ** determined by character c.
  72164. */
  72165. static int translateP(char c, const Op *pOp){
  72166. if( c=='1' ) return pOp->p1;
  72167. if( c=='2' ) return pOp->p2;
  72168. if( c=='3' ) return pOp->p3;
  72169. if( c=='4' ) return pOp->p4.i;
  72170. return pOp->p5;
  72171. }
  72172. /*
  72173. ** Compute a string for the "comment" field of a VDBE opcode listing.
  72174. **
  72175. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  72176. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  72177. ** absence of other comments, this synopsis becomes the comment on the opcode.
  72178. ** Some translation occurs:
  72179. **
  72180. ** "PX" -> "r[X]"
  72181. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  72182. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  72183. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  72184. */
  72185. static int displayComment(
  72186. const Op *pOp, /* The opcode to be commented */
  72187. const char *zP4, /* Previously obtained value for P4 */
  72188. char *zTemp, /* Write result here */
  72189. int nTemp /* Space available in zTemp[] */
  72190. ){
  72191. const char *zOpName;
  72192. const char *zSynopsis;
  72193. int nOpName;
  72194. int ii, jj;
  72195. char zAlt[50];
  72196. zOpName = sqlite3OpcodeName(pOp->opcode);
  72197. nOpName = sqlite3Strlen30(zOpName);
  72198. if( zOpName[nOpName+1] ){
  72199. int seenCom = 0;
  72200. char c;
  72201. zSynopsis = zOpName += nOpName + 1;
  72202. if( strncmp(zSynopsis,"IF ",3)==0 ){
  72203. if( pOp->p5 & SQLITE_STOREP2 ){
  72204. sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
  72205. }else{
  72206. sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
  72207. }
  72208. zSynopsis = zAlt;
  72209. }
  72210. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  72211. if( c=='P' ){
  72212. c = zSynopsis[++ii];
  72213. if( c=='4' ){
  72214. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  72215. }else if( c=='X' ){
  72216. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  72217. seenCom = 1;
  72218. }else{
  72219. int v1 = translateP(c, pOp);
  72220. int v2;
  72221. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  72222. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  72223. ii += 3;
  72224. jj += sqlite3Strlen30(zTemp+jj);
  72225. v2 = translateP(zSynopsis[ii], pOp);
  72226. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  72227. ii += 2;
  72228. v2++;
  72229. }
  72230. if( v2>1 ){
  72231. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  72232. }
  72233. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  72234. ii += 4;
  72235. }
  72236. }
  72237. jj += sqlite3Strlen30(zTemp+jj);
  72238. }else{
  72239. zTemp[jj++] = c;
  72240. }
  72241. }
  72242. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  72243. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  72244. jj += sqlite3Strlen30(zTemp+jj);
  72245. }
  72246. if( jj<nTemp ) zTemp[jj] = 0;
  72247. }else if( pOp->zComment ){
  72248. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  72249. jj = sqlite3Strlen30(zTemp);
  72250. }else{
  72251. zTemp[0] = 0;
  72252. jj = 0;
  72253. }
  72254. return jj;
  72255. }
  72256. #endif /* SQLITE_DEBUG */
  72257. #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
  72258. /*
  72259. ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
  72260. ** that can be displayed in the P4 column of EXPLAIN output.
  72261. */
  72262. static void displayP4Expr(StrAccum *p, Expr *pExpr){
  72263. const char *zOp = 0;
  72264. switch( pExpr->op ){
  72265. case TK_STRING:
  72266. sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
  72267. break;
  72268. case TK_INTEGER:
  72269. sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
  72270. break;
  72271. case TK_NULL:
  72272. sqlite3_str_appendf(p, "NULL");
  72273. break;
  72274. case TK_REGISTER: {
  72275. sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
  72276. break;
  72277. }
  72278. case TK_COLUMN: {
  72279. if( pExpr->iColumn<0 ){
  72280. sqlite3_str_appendf(p, "rowid");
  72281. }else{
  72282. sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
  72283. }
  72284. break;
  72285. }
  72286. case TK_LT: zOp = "LT"; break;
  72287. case TK_LE: zOp = "LE"; break;
  72288. case TK_GT: zOp = "GT"; break;
  72289. case TK_GE: zOp = "GE"; break;
  72290. case TK_NE: zOp = "NE"; break;
  72291. case TK_EQ: zOp = "EQ"; break;
  72292. case TK_IS: zOp = "IS"; break;
  72293. case TK_ISNOT: zOp = "ISNOT"; break;
  72294. case TK_AND: zOp = "AND"; break;
  72295. case TK_OR: zOp = "OR"; break;
  72296. case TK_PLUS: zOp = "ADD"; break;
  72297. case TK_STAR: zOp = "MUL"; break;
  72298. case TK_MINUS: zOp = "SUB"; break;
  72299. case TK_REM: zOp = "REM"; break;
  72300. case TK_BITAND: zOp = "BITAND"; break;
  72301. case TK_BITOR: zOp = "BITOR"; break;
  72302. case TK_SLASH: zOp = "DIV"; break;
  72303. case TK_LSHIFT: zOp = "LSHIFT"; break;
  72304. case TK_RSHIFT: zOp = "RSHIFT"; break;
  72305. case TK_CONCAT: zOp = "CONCAT"; break;
  72306. case TK_UMINUS: zOp = "MINUS"; break;
  72307. case TK_UPLUS: zOp = "PLUS"; break;
  72308. case TK_BITNOT: zOp = "BITNOT"; break;
  72309. case TK_NOT: zOp = "NOT"; break;
  72310. case TK_ISNULL: zOp = "ISNULL"; break;
  72311. case TK_NOTNULL: zOp = "NOTNULL"; break;
  72312. default:
  72313. sqlite3_str_appendf(p, "%s", "expr");
  72314. break;
  72315. }
  72316. if( zOp ){
  72317. sqlite3_str_appendf(p, "%s(", zOp);
  72318. displayP4Expr(p, pExpr->pLeft);
  72319. if( pExpr->pRight ){
  72320. sqlite3_str_append(p, ",", 1);
  72321. displayP4Expr(p, pExpr->pRight);
  72322. }
  72323. sqlite3_str_append(p, ")", 1);
  72324. }
  72325. }
  72326. #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
  72327. #if VDBE_DISPLAY_P4
  72328. /*
  72329. ** Compute a string that describes the P4 parameter for an opcode.
  72330. ** Use zTemp for any required temporary buffer space.
  72331. */
  72332. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  72333. char *zP4 = zTemp;
  72334. StrAccum x;
  72335. assert( nTemp>=20 );
  72336. sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
  72337. switch( pOp->p4type ){
  72338. case P4_KEYINFO: {
  72339. int j;
  72340. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  72341. assert( pKeyInfo->aSortOrder!=0 );
  72342. sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
  72343. for(j=0; j<pKeyInfo->nKeyField; j++){
  72344. CollSeq *pColl = pKeyInfo->aColl[j];
  72345. const char *zColl = pColl ? pColl->zName : "";
  72346. if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
  72347. sqlite3_str_appendf(&x, ",%s%s",
  72348. pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
  72349. }
  72350. sqlite3_str_append(&x, ")", 1);
  72351. break;
  72352. }
  72353. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  72354. case P4_EXPR: {
  72355. displayP4Expr(&x, pOp->p4.pExpr);
  72356. break;
  72357. }
  72358. #endif
  72359. case P4_COLLSEQ: {
  72360. CollSeq *pColl = pOp->p4.pColl;
  72361. sqlite3_str_appendf(&x, "(%.20s)", pColl->zName);
  72362. break;
  72363. }
  72364. case P4_FUNCDEF: {
  72365. FuncDef *pDef = pOp->p4.pFunc;
  72366. sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  72367. break;
  72368. }
  72369. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  72370. case P4_FUNCCTX: {
  72371. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  72372. sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  72373. break;
  72374. }
  72375. #endif
  72376. case P4_INT64: {
  72377. sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
  72378. break;
  72379. }
  72380. case P4_INT32: {
  72381. sqlite3_str_appendf(&x, "%d", pOp->p4.i);
  72382. break;
  72383. }
  72384. case P4_REAL: {
  72385. sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
  72386. break;
  72387. }
  72388. case P4_MEM: {
  72389. Mem *pMem = pOp->p4.pMem;
  72390. if( pMem->flags & MEM_Str ){
  72391. zP4 = pMem->z;
  72392. }else if( pMem->flags & MEM_Int ){
  72393. sqlite3_str_appendf(&x, "%lld", pMem->u.i);
  72394. }else if( pMem->flags & MEM_Real ){
  72395. sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
  72396. }else if( pMem->flags & MEM_Null ){
  72397. zP4 = "NULL";
  72398. }else{
  72399. assert( pMem->flags & MEM_Blob );
  72400. zP4 = "(blob)";
  72401. }
  72402. break;
  72403. }
  72404. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72405. case P4_VTAB: {
  72406. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  72407. sqlite3_str_appendf(&x, "vtab:%p", pVtab);
  72408. break;
  72409. }
  72410. #endif
  72411. case P4_INTARRAY: {
  72412. int i;
  72413. int *ai = pOp->p4.ai;
  72414. int n = ai[0]; /* The first element of an INTARRAY is always the
  72415. ** count of the number of elements to follow */
  72416. for(i=1; i<=n; i++){
  72417. sqlite3_str_appendf(&x, ",%d", ai[i]);
  72418. }
  72419. zTemp[0] = '[';
  72420. sqlite3_str_append(&x, "]", 1);
  72421. break;
  72422. }
  72423. case P4_SUBPROGRAM: {
  72424. sqlite3_str_appendf(&x, "program");
  72425. break;
  72426. }
  72427. case P4_DYNBLOB:
  72428. case P4_ADVANCE: {
  72429. zTemp[0] = 0;
  72430. break;
  72431. }
  72432. case P4_TABLE: {
  72433. sqlite3_str_appendf(&x, "%s", pOp->p4.pTab->zName);
  72434. break;
  72435. }
  72436. default: {
  72437. zP4 = pOp->p4.z;
  72438. if( zP4==0 ){
  72439. zP4 = zTemp;
  72440. zTemp[0] = 0;
  72441. }
  72442. }
  72443. }
  72444. sqlite3StrAccumFinish(&x);
  72445. assert( zP4!=0 );
  72446. return zP4;
  72447. }
  72448. #endif /* VDBE_DISPLAY_P4 */
  72449. /*
  72450. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  72451. **
  72452. ** The prepared statements need to know in advance the complete set of
  72453. ** attached databases that will be use. A mask of these databases
  72454. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  72455. ** p->btreeMask of databases that will require a lock.
  72456. */
  72457. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  72458. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  72459. assert( i<(int)sizeof(p->btreeMask)*8 );
  72460. DbMaskSet(p->btreeMask, i);
  72461. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  72462. DbMaskSet(p->lockMask, i);
  72463. }
  72464. }
  72465. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  72466. /*
  72467. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  72468. ** this routine obtains the mutex associated with each BtShared structure
  72469. ** that may be accessed by the VM passed as an argument. In doing so it also
  72470. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  72471. ** that the correct busy-handler callback is invoked if required.
  72472. **
  72473. ** If SQLite is not threadsafe but does support shared-cache mode, then
  72474. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  72475. ** of all of BtShared structures accessible via the database handle
  72476. ** associated with the VM.
  72477. **
  72478. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  72479. ** function is a no-op.
  72480. **
  72481. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  72482. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  72483. ** corresponding to btrees that use shared cache. Then the runtime of
  72484. ** this routine is N*N. But as N is rarely more than 1, this should not
  72485. ** be a problem.
  72486. */
  72487. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  72488. int i;
  72489. sqlite3 *db;
  72490. Db *aDb;
  72491. int nDb;
  72492. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  72493. db = p->db;
  72494. aDb = db->aDb;
  72495. nDb = db->nDb;
  72496. for(i=0; i<nDb; i++){
  72497. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  72498. sqlite3BtreeEnter(aDb[i].pBt);
  72499. }
  72500. }
  72501. }
  72502. #endif
  72503. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  72504. /*
  72505. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  72506. */
  72507. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  72508. int i;
  72509. sqlite3 *db;
  72510. Db *aDb;
  72511. int nDb;
  72512. db = p->db;
  72513. aDb = db->aDb;
  72514. nDb = db->nDb;
  72515. for(i=0; i<nDb; i++){
  72516. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  72517. sqlite3BtreeLeave(aDb[i].pBt);
  72518. }
  72519. }
  72520. }
  72521. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  72522. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  72523. vdbeLeave(p);
  72524. }
  72525. #endif
  72526. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  72527. /*
  72528. ** Print a single opcode. This routine is used for debugging only.
  72529. */
  72530. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
  72531. char *zP4;
  72532. char zPtr[50];
  72533. char zCom[100];
  72534. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  72535. if( pOut==0 ) pOut = stdout;
  72536. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  72537. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  72538. displayComment(pOp, zP4, zCom, sizeof(zCom));
  72539. #else
  72540. zCom[0] = 0;
  72541. #endif
  72542. /* NB: The sqlite3OpcodeName() function is implemented by code created
  72543. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  72544. ** information from the vdbe.c source text */
  72545. fprintf(pOut, zFormat1, pc,
  72546. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  72547. zCom
  72548. );
  72549. fflush(pOut);
  72550. }
  72551. #endif
  72552. /*
  72553. ** Initialize an array of N Mem element.
  72554. */
  72555. static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
  72556. while( (N--)>0 ){
  72557. p->db = db;
  72558. p->flags = flags;
  72559. p->szMalloc = 0;
  72560. #ifdef SQLITE_DEBUG
  72561. p->pScopyFrom = 0;
  72562. #endif
  72563. p++;
  72564. }
  72565. }
  72566. /*
  72567. ** Release an array of N Mem elements
  72568. */
  72569. static void releaseMemArray(Mem *p, int N){
  72570. if( p && N ){
  72571. Mem *pEnd = &p[N];
  72572. sqlite3 *db = p->db;
  72573. if( db->pnBytesFreed ){
  72574. do{
  72575. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  72576. }while( (++p)<pEnd );
  72577. return;
  72578. }
  72579. do{
  72580. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  72581. assert( sqlite3VdbeCheckMemInvariants(p) );
  72582. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  72583. ** that takes advantage of the fact that the memory cell value is
  72584. ** being set to NULL after releasing any dynamic resources.
  72585. **
  72586. ** The justification for duplicating code is that according to
  72587. ** callgrind, this causes a certain test case to hit the CPU 4.7
  72588. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  72589. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  72590. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  72591. ** with no indexes using a single prepared INSERT statement, bind()
  72592. ** and reset(). Inserts are grouped into a transaction.
  72593. */
  72594. testcase( p->flags & MEM_Agg );
  72595. testcase( p->flags & MEM_Dyn );
  72596. testcase( p->xDel==sqlite3VdbeFrameMemDel );
  72597. if( p->flags&(MEM_Agg|MEM_Dyn) ){
  72598. sqlite3VdbeMemRelease(p);
  72599. }else if( p->szMalloc ){
  72600. sqlite3DbFreeNN(db, p->zMalloc);
  72601. p->szMalloc = 0;
  72602. }
  72603. p->flags = MEM_Undefined;
  72604. }while( (++p)<pEnd );
  72605. }
  72606. }
  72607. #ifdef SQLITE_DEBUG
  72608. /*
  72609. ** Verify that pFrame is a valid VdbeFrame pointer. Return true if it is
  72610. ** and false if something is wrong.
  72611. **
  72612. ** This routine is intended for use inside of assert() statements only.
  72613. */
  72614. SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
  72615. if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
  72616. return 1;
  72617. }
  72618. #endif
  72619. /*
  72620. ** This is a destructor on a Mem object (which is really an sqlite3_value)
  72621. ** that deletes the Frame object that is attached to it as a blob.
  72622. **
  72623. ** This routine does not delete the Frame right away. It merely adds the
  72624. ** frame to a list of frames to be deleted when the Vdbe halts.
  72625. */
  72626. SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void *pArg){
  72627. VdbeFrame *pFrame = (VdbeFrame*)pArg;
  72628. assert( sqlite3VdbeFrameIsValid(pFrame) );
  72629. pFrame->pParent = pFrame->v->pDelFrame;
  72630. pFrame->v->pDelFrame = pFrame;
  72631. }
  72632. /*
  72633. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  72634. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  72635. */
  72636. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  72637. int i;
  72638. Mem *aMem = VdbeFrameMem(p);
  72639. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  72640. assert( sqlite3VdbeFrameIsValid(p) );
  72641. for(i=0; i<p->nChildCsr; i++){
  72642. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  72643. }
  72644. releaseMemArray(aMem, p->nChildMem);
  72645. sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
  72646. sqlite3DbFree(p->v->db, p);
  72647. }
  72648. #ifndef SQLITE_OMIT_EXPLAIN
  72649. /*
  72650. ** Give a listing of the program in the virtual machine.
  72651. **
  72652. ** The interface is the same as sqlite3VdbeExec(). But instead of
  72653. ** running the code, it invokes the callback once for each instruction.
  72654. ** This feature is used to implement "EXPLAIN".
  72655. **
  72656. ** When p->explain==1, each instruction is listed. When
  72657. ** p->explain==2, only OP_Explain instructions are listed and these
  72658. ** are shown in a different format. p->explain==2 is used to implement
  72659. ** EXPLAIN QUERY PLAN.
  72660. ** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
  72661. ** are also shown, so that the boundaries between the main program and
  72662. ** each trigger are clear.
  72663. **
  72664. ** When p->explain==1, first the main program is listed, then each of
  72665. ** the trigger subprograms are listed one by one.
  72666. */
  72667. SQLITE_PRIVATE int sqlite3VdbeList(
  72668. Vdbe *p /* The VDBE */
  72669. ){
  72670. int nRow; /* Stop when row count reaches this */
  72671. int nSub = 0; /* Number of sub-vdbes seen so far */
  72672. SubProgram **apSub = 0; /* Array of sub-vdbes */
  72673. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  72674. sqlite3 *db = p->db; /* The database connection */
  72675. int i; /* Loop counter */
  72676. int rc = SQLITE_OK; /* Return code */
  72677. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  72678. int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
  72679. Op *pOp = 0;
  72680. assert( p->explain );
  72681. assert( p->magic==VDBE_MAGIC_RUN );
  72682. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  72683. /* Even though this opcode does not use dynamic strings for
  72684. ** the result, result columns may become dynamic if the user calls
  72685. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  72686. */
  72687. releaseMemArray(pMem, 8);
  72688. p->pResultSet = 0;
  72689. if( p->rc==SQLITE_NOMEM ){
  72690. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  72691. ** sqlite3_column_text16() failed. */
  72692. sqlite3OomFault(db);
  72693. return SQLITE_ERROR;
  72694. }
  72695. /* When the number of output rows reaches nRow, that means the
  72696. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  72697. ** nRow is the sum of the number of rows in the main program, plus
  72698. ** the sum of the number of rows in all trigger subprograms encountered
  72699. ** so far. The nRow value will increase as new trigger subprograms are
  72700. ** encountered, but p->pc will eventually catch up to nRow.
  72701. */
  72702. nRow = p->nOp;
  72703. if( bListSubprogs ){
  72704. /* The first 8 memory cells are used for the result set. So we will
  72705. ** commandeer the 9th cell to use as storage for an array of pointers
  72706. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  72707. ** cells. */
  72708. assert( p->nMem>9 );
  72709. pSub = &p->aMem[9];
  72710. if( pSub->flags&MEM_Blob ){
  72711. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  72712. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  72713. nSub = pSub->n/sizeof(Vdbe*);
  72714. apSub = (SubProgram **)pSub->z;
  72715. }
  72716. for(i=0; i<nSub; i++){
  72717. nRow += apSub[i]->nOp;
  72718. }
  72719. }
  72720. while(1){ /* Loop exits via break */
  72721. i = p->pc++;
  72722. if( i>=nRow ){
  72723. p->rc = SQLITE_OK;
  72724. rc = SQLITE_DONE;
  72725. break;
  72726. }
  72727. if( i<p->nOp ){
  72728. /* The output line number is small enough that we are still in the
  72729. ** main program. */
  72730. pOp = &p->aOp[i];
  72731. }else{
  72732. /* We are currently listing subprograms. Figure out which one and
  72733. ** pick up the appropriate opcode. */
  72734. int j;
  72735. i -= p->nOp;
  72736. for(j=0; i>=apSub[j]->nOp; j++){
  72737. i -= apSub[j]->nOp;
  72738. }
  72739. pOp = &apSub[j]->aOp[i];
  72740. }
  72741. /* When an OP_Program opcode is encounter (the only opcode that has
  72742. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  72743. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  72744. ** has not already been seen.
  72745. */
  72746. if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
  72747. int nByte = (nSub+1)*sizeof(SubProgram*);
  72748. int j;
  72749. for(j=0; j<nSub; j++){
  72750. if( apSub[j]==pOp->p4.pProgram ) break;
  72751. }
  72752. if( j==nSub ){
  72753. p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
  72754. if( p->rc!=SQLITE_OK ){
  72755. rc = SQLITE_ERROR;
  72756. break;
  72757. }
  72758. apSub = (SubProgram **)pSub->z;
  72759. apSub[nSub++] = pOp->p4.pProgram;
  72760. pSub->flags |= MEM_Blob;
  72761. pSub->n = nSub*sizeof(SubProgram*);
  72762. nRow += pOp->p4.pProgram->nOp;
  72763. }
  72764. }
  72765. if( p->explain<2 ) break;
  72766. if( pOp->opcode==OP_Explain ) break;
  72767. if( pOp->opcode==OP_Init && p->pc>1 ) break;
  72768. }
  72769. if( rc==SQLITE_OK ){
  72770. if( db->u1.isInterrupted ){
  72771. p->rc = SQLITE_INTERRUPT;
  72772. rc = SQLITE_ERROR;
  72773. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  72774. }else{
  72775. char *zP4;
  72776. if( p->explain==1 ){
  72777. pMem->flags = MEM_Int;
  72778. pMem->u.i = i; /* Program counter */
  72779. pMem++;
  72780. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  72781. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  72782. assert( pMem->z!=0 );
  72783. pMem->n = sqlite3Strlen30(pMem->z);
  72784. pMem->enc = SQLITE_UTF8;
  72785. pMem++;
  72786. }
  72787. pMem->flags = MEM_Int;
  72788. pMem->u.i = pOp->p1; /* P1 */
  72789. pMem++;
  72790. pMem->flags = MEM_Int;
  72791. pMem->u.i = pOp->p2; /* P2 */
  72792. pMem++;
  72793. pMem->flags = MEM_Int;
  72794. pMem->u.i = pOp->p3; /* P3 */
  72795. pMem++;
  72796. if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
  72797. assert( p->db->mallocFailed );
  72798. return SQLITE_ERROR;
  72799. }
  72800. pMem->flags = MEM_Str|MEM_Term;
  72801. zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
  72802. if( zP4!=pMem->z ){
  72803. pMem->n = 0;
  72804. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  72805. }else{
  72806. assert( pMem->z!=0 );
  72807. pMem->n = sqlite3Strlen30(pMem->z);
  72808. pMem->enc = SQLITE_UTF8;
  72809. }
  72810. pMem++;
  72811. if( p->explain==1 ){
  72812. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  72813. assert( p->db->mallocFailed );
  72814. return SQLITE_ERROR;
  72815. }
  72816. pMem->flags = MEM_Str|MEM_Term;
  72817. pMem->n = 2;
  72818. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  72819. pMem->enc = SQLITE_UTF8;
  72820. pMem++;
  72821. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  72822. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  72823. assert( p->db->mallocFailed );
  72824. return SQLITE_ERROR;
  72825. }
  72826. pMem->flags = MEM_Str|MEM_Term;
  72827. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  72828. pMem->enc = SQLITE_UTF8;
  72829. #else
  72830. pMem->flags = MEM_Null; /* Comment */
  72831. #endif
  72832. }
  72833. p->nResColumn = 8 - 4*(p->explain-1);
  72834. p->pResultSet = &p->aMem[1];
  72835. p->rc = SQLITE_OK;
  72836. rc = SQLITE_ROW;
  72837. }
  72838. }
  72839. return rc;
  72840. }
  72841. #endif /* SQLITE_OMIT_EXPLAIN */
  72842. #ifdef SQLITE_DEBUG
  72843. /*
  72844. ** Print the SQL that was used to generate a VDBE program.
  72845. */
  72846. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  72847. const char *z = 0;
  72848. if( p->zSql ){
  72849. z = p->zSql;
  72850. }else if( p->nOp>=1 ){
  72851. const VdbeOp *pOp = &p->aOp[0];
  72852. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  72853. z = pOp->p4.z;
  72854. while( sqlite3Isspace(*z) ) z++;
  72855. }
  72856. }
  72857. if( z ) printf("SQL: [%s]\n", z);
  72858. }
  72859. #endif
  72860. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  72861. /*
  72862. ** Print an IOTRACE message showing SQL content.
  72863. */
  72864. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  72865. int nOp = p->nOp;
  72866. VdbeOp *pOp;
  72867. if( sqlite3IoTrace==0 ) return;
  72868. if( nOp<1 ) return;
  72869. pOp = &p->aOp[0];
  72870. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  72871. int i, j;
  72872. char z[1000];
  72873. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  72874. for(i=0; sqlite3Isspace(z[i]); i++){}
  72875. for(j=0; z[i]; i++){
  72876. if( sqlite3Isspace(z[i]) ){
  72877. if( z[i-1]!=' ' ){
  72878. z[j++] = ' ';
  72879. }
  72880. }else{
  72881. z[j++] = z[i];
  72882. }
  72883. }
  72884. z[j] = 0;
  72885. sqlite3IoTrace("SQL %s\n", z);
  72886. }
  72887. }
  72888. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  72889. /* An instance of this object describes bulk memory available for use
  72890. ** by subcomponents of a prepared statement. Space is allocated out
  72891. ** of a ReusableSpace object by the allocSpace() routine below.
  72892. */
  72893. struct ReusableSpace {
  72894. u8 *pSpace; /* Available memory */
  72895. int nFree; /* Bytes of available memory */
  72896. int nNeeded; /* Total bytes that could not be allocated */
  72897. };
  72898. /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
  72899. ** from the ReusableSpace object. Return a pointer to the allocated
  72900. ** memory on success. If insufficient memory is available in the
  72901. ** ReusableSpace object, increase the ReusableSpace.nNeeded
  72902. ** value by the amount needed and return NULL.
  72903. **
  72904. ** If pBuf is not initially NULL, that means that the memory has already
  72905. ** been allocated by a prior call to this routine, so just return a copy
  72906. ** of pBuf and leave ReusableSpace unchanged.
  72907. **
  72908. ** This allocator is employed to repurpose unused slots at the end of the
  72909. ** opcode array of prepared state for other memory needs of the prepared
  72910. ** statement.
  72911. */
  72912. static void *allocSpace(
  72913. struct ReusableSpace *p, /* Bulk memory available for allocation */
  72914. void *pBuf, /* Pointer to a prior allocation */
  72915. int nByte /* Bytes of memory needed */
  72916. ){
  72917. assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
  72918. if( pBuf==0 ){
  72919. nByte = ROUND8(nByte);
  72920. if( nByte <= p->nFree ){
  72921. p->nFree -= nByte;
  72922. pBuf = &p->pSpace[p->nFree];
  72923. }else{
  72924. p->nNeeded += nByte;
  72925. }
  72926. }
  72927. assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
  72928. return pBuf;
  72929. }
  72930. /*
  72931. ** Rewind the VDBE back to the beginning in preparation for
  72932. ** running it.
  72933. */
  72934. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  72935. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  72936. int i;
  72937. #endif
  72938. assert( p!=0 );
  72939. assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
  72940. /* There should be at least one opcode.
  72941. */
  72942. assert( p->nOp>0 );
  72943. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  72944. p->magic = VDBE_MAGIC_RUN;
  72945. #ifdef SQLITE_DEBUG
  72946. for(i=0; i<p->nMem; i++){
  72947. assert( p->aMem[i].db==p->db );
  72948. }
  72949. #endif
  72950. p->pc = -1;
  72951. p->rc = SQLITE_OK;
  72952. p->errorAction = OE_Abort;
  72953. p->nChange = 0;
  72954. p->cacheCtr = 1;
  72955. p->minWriteFileFormat = 255;
  72956. p->iStatement = 0;
  72957. p->nFkConstraint = 0;
  72958. #ifdef VDBE_PROFILE
  72959. for(i=0; i<p->nOp; i++){
  72960. p->aOp[i].cnt = 0;
  72961. p->aOp[i].cycles = 0;
  72962. }
  72963. #endif
  72964. }
  72965. /*
  72966. ** Prepare a virtual machine for execution for the first time after
  72967. ** creating the virtual machine. This involves things such
  72968. ** as allocating registers and initializing the program counter.
  72969. ** After the VDBE has be prepped, it can be executed by one or more
  72970. ** calls to sqlite3VdbeExec().
  72971. **
  72972. ** This function may be called exactly once on each virtual machine.
  72973. ** After this routine is called the VM has been "packaged" and is ready
  72974. ** to run. After this routine is called, further calls to
  72975. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  72976. ** the Vdbe from the Parse object that helped generate it so that the
  72977. ** the Vdbe becomes an independent entity and the Parse object can be
  72978. ** destroyed.
  72979. **
  72980. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  72981. ** to its initial state after it has been run.
  72982. */
  72983. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  72984. Vdbe *p, /* The VDBE */
  72985. Parse *pParse /* Parsing context */
  72986. ){
  72987. sqlite3 *db; /* The database connection */
  72988. int nVar; /* Number of parameters */
  72989. int nMem; /* Number of VM memory registers */
  72990. int nCursor; /* Number of cursors required */
  72991. int nArg; /* Number of arguments in subprograms */
  72992. int n; /* Loop counter */
  72993. struct ReusableSpace x; /* Reusable bulk memory */
  72994. assert( p!=0 );
  72995. assert( p->nOp>0 );
  72996. assert( pParse!=0 );
  72997. assert( p->magic==VDBE_MAGIC_INIT );
  72998. assert( pParse==p->pParse );
  72999. db = p->db;
  73000. assert( db->mallocFailed==0 );
  73001. nVar = pParse->nVar;
  73002. nMem = pParse->nMem;
  73003. nCursor = pParse->nTab;
  73004. nArg = pParse->nMaxArg;
  73005. /* Each cursor uses a memory cell. The first cursor (cursor 0) can
  73006. ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
  73007. ** space at the end of aMem[] for cursors 1 and greater.
  73008. ** See also: allocateCursor().
  73009. */
  73010. nMem += nCursor;
  73011. if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
  73012. /* Figure out how much reusable memory is available at the end of the
  73013. ** opcode array. This extra memory will be reallocated for other elements
  73014. ** of the prepared statement.
  73015. */
  73016. n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
  73017. x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
  73018. assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
  73019. x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
  73020. assert( x.nFree>=0 );
  73021. assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
  73022. resolveP2Values(p, &nArg);
  73023. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  73024. if( pParse->explain && nMem<10 ){
  73025. nMem = 10;
  73026. }
  73027. p->expired = 0;
  73028. /* Memory for registers, parameters, cursor, etc, is allocated in one or two
  73029. ** passes. On the first pass, we try to reuse unused memory at the
  73030. ** end of the opcode array. If we are unable to satisfy all memory
  73031. ** requirements by reusing the opcode array tail, then the second
  73032. ** pass will fill in the remainder using a fresh memory allocation.
  73033. **
  73034. ** This two-pass approach that reuses as much memory as possible from
  73035. ** the leftover memory at the end of the opcode array. This can significantly
  73036. ** reduce the amount of memory held by a prepared statement.
  73037. */
  73038. do {
  73039. x.nNeeded = 0;
  73040. p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
  73041. p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
  73042. p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
  73043. p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
  73044. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73045. p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
  73046. #endif
  73047. if( x.nNeeded==0 ) break;
  73048. x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
  73049. x.nFree = x.nNeeded;
  73050. }while( !db->mallocFailed );
  73051. p->pVList = pParse->pVList;
  73052. pParse->pVList = 0;
  73053. p->explain = pParse->explain;
  73054. if( db->mallocFailed ){
  73055. p->nVar = 0;
  73056. p->nCursor = 0;
  73057. p->nMem = 0;
  73058. }else{
  73059. p->nCursor = nCursor;
  73060. p->nVar = (ynVar)nVar;
  73061. initMemArray(p->aVar, nVar, db, MEM_Null);
  73062. p->nMem = nMem;
  73063. initMemArray(p->aMem, nMem, db, MEM_Undefined);
  73064. memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
  73065. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73066. memset(p->anExec, 0, p->nOp*sizeof(i64));
  73067. #endif
  73068. }
  73069. sqlite3VdbeRewind(p);
  73070. }
  73071. /*
  73072. ** Close a VDBE cursor and release all the resources that cursor
  73073. ** happens to hold.
  73074. */
  73075. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  73076. if( pCx==0 ){
  73077. return;
  73078. }
  73079. assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
  73080. switch( pCx->eCurType ){
  73081. case CURTYPE_SORTER: {
  73082. sqlite3VdbeSorterClose(p->db, pCx);
  73083. break;
  73084. }
  73085. case CURTYPE_BTREE: {
  73086. if( pCx->isEphemeral ){
  73087. if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
  73088. /* The pCx->pCursor will be close automatically, if it exists, by
  73089. ** the call above. */
  73090. }else{
  73091. assert( pCx->uc.pCursor!=0 );
  73092. sqlite3BtreeCloseCursor(pCx->uc.pCursor);
  73093. }
  73094. break;
  73095. }
  73096. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73097. case CURTYPE_VTAB: {
  73098. sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
  73099. const sqlite3_module *pModule = pVCur->pVtab->pModule;
  73100. assert( pVCur->pVtab->nRef>0 );
  73101. pVCur->pVtab->nRef--;
  73102. pModule->xClose(pVCur);
  73103. break;
  73104. }
  73105. #endif
  73106. }
  73107. }
  73108. /*
  73109. ** Close all cursors in the current frame.
  73110. */
  73111. static void closeCursorsInFrame(Vdbe *p){
  73112. if( p->apCsr ){
  73113. int i;
  73114. for(i=0; i<p->nCursor; i++){
  73115. VdbeCursor *pC = p->apCsr[i];
  73116. if( pC ){
  73117. sqlite3VdbeFreeCursor(p, pC);
  73118. p->apCsr[i] = 0;
  73119. }
  73120. }
  73121. }
  73122. }
  73123. /*
  73124. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  73125. ** is used, for example, when a trigger sub-program is halted to restore
  73126. ** control to the main program.
  73127. */
  73128. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  73129. Vdbe *v = pFrame->v;
  73130. closeCursorsInFrame(v);
  73131. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73132. v->anExec = pFrame->anExec;
  73133. #endif
  73134. v->aOp = pFrame->aOp;
  73135. v->nOp = pFrame->nOp;
  73136. v->aMem = pFrame->aMem;
  73137. v->nMem = pFrame->nMem;
  73138. v->apCsr = pFrame->apCsr;
  73139. v->nCursor = pFrame->nCursor;
  73140. v->db->lastRowid = pFrame->lastRowid;
  73141. v->nChange = pFrame->nChange;
  73142. v->db->nChange = pFrame->nDbChange;
  73143. sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
  73144. v->pAuxData = pFrame->pAuxData;
  73145. pFrame->pAuxData = 0;
  73146. return pFrame->pc;
  73147. }
  73148. /*
  73149. ** Close all cursors.
  73150. **
  73151. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  73152. ** cell array. This is necessary as the memory cell array may contain
  73153. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  73154. ** open cursors.
  73155. */
  73156. static void closeAllCursors(Vdbe *p){
  73157. if( p->pFrame ){
  73158. VdbeFrame *pFrame;
  73159. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  73160. sqlite3VdbeFrameRestore(pFrame);
  73161. p->pFrame = 0;
  73162. p->nFrame = 0;
  73163. }
  73164. assert( p->nFrame==0 );
  73165. closeCursorsInFrame(p);
  73166. if( p->aMem ){
  73167. releaseMemArray(p->aMem, p->nMem);
  73168. }
  73169. while( p->pDelFrame ){
  73170. VdbeFrame *pDel = p->pDelFrame;
  73171. p->pDelFrame = pDel->pParent;
  73172. sqlite3VdbeFrameDelete(pDel);
  73173. }
  73174. /* Delete any auxdata allocations made by the VM */
  73175. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
  73176. assert( p->pAuxData==0 );
  73177. }
  73178. /*
  73179. ** Set the number of result columns that will be returned by this SQL
  73180. ** statement. This is now set at compile time, rather than during
  73181. ** execution of the vdbe program so that sqlite3_column_count() can
  73182. ** be called on an SQL statement before sqlite3_step().
  73183. */
  73184. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  73185. int n;
  73186. sqlite3 *db = p->db;
  73187. if( p->nResColumn ){
  73188. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  73189. sqlite3DbFree(db, p->aColName);
  73190. }
  73191. n = nResColumn*COLNAME_N;
  73192. p->nResColumn = (u16)nResColumn;
  73193. p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
  73194. if( p->aColName==0 ) return;
  73195. initMemArray(p->aColName, n, db, MEM_Null);
  73196. }
  73197. /*
  73198. ** Set the name of the idx'th column to be returned by the SQL statement.
  73199. ** zName must be a pointer to a nul terminated string.
  73200. **
  73201. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  73202. **
  73203. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  73204. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  73205. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  73206. */
  73207. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  73208. Vdbe *p, /* Vdbe being configured */
  73209. int idx, /* Index of column zName applies to */
  73210. int var, /* One of the COLNAME_* constants */
  73211. const char *zName, /* Pointer to buffer containing name */
  73212. void (*xDel)(void*) /* Memory management strategy for zName */
  73213. ){
  73214. int rc;
  73215. Mem *pColName;
  73216. assert( idx<p->nResColumn );
  73217. assert( var<COLNAME_N );
  73218. if( p->db->mallocFailed ){
  73219. assert( !zName || xDel!=SQLITE_DYNAMIC );
  73220. return SQLITE_NOMEM_BKPT;
  73221. }
  73222. assert( p->aColName!=0 );
  73223. pColName = &(p->aColName[idx+var*p->nResColumn]);
  73224. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  73225. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  73226. return rc;
  73227. }
  73228. /*
  73229. ** A read or write transaction may or may not be active on database handle
  73230. ** db. If a transaction is active, commit it. If there is a
  73231. ** write-transaction spanning more than one database file, this routine
  73232. ** takes care of the master journal trickery.
  73233. */
  73234. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  73235. int i;
  73236. int nTrans = 0; /* Number of databases with an active write-transaction
  73237. ** that are candidates for a two-phase commit using a
  73238. ** master-journal */
  73239. int rc = SQLITE_OK;
  73240. int needXcommit = 0;
  73241. #ifdef SQLITE_OMIT_VIRTUALTABLE
  73242. /* With this option, sqlite3VtabSync() is defined to be simply
  73243. ** SQLITE_OK so p is not used.
  73244. */
  73245. UNUSED_PARAMETER(p);
  73246. #endif
  73247. /* Before doing anything else, call the xSync() callback for any
  73248. ** virtual module tables written in this transaction. This has to
  73249. ** be done before determining whether a master journal file is
  73250. ** required, as an xSync() callback may add an attached database
  73251. ** to the transaction.
  73252. */
  73253. rc = sqlite3VtabSync(db, p);
  73254. /* This loop determines (a) if the commit hook should be invoked and
  73255. ** (b) how many database files have open write transactions, not
  73256. ** including the temp database. (b) is important because if more than
  73257. ** one database file has an open write transaction, a master journal
  73258. ** file is required for an atomic commit.
  73259. */
  73260. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  73261. Btree *pBt = db->aDb[i].pBt;
  73262. if( sqlite3BtreeIsInTrans(pBt) ){
  73263. /* Whether or not a database might need a master journal depends upon
  73264. ** its journal mode (among other things). This matrix determines which
  73265. ** journal modes use a master journal and which do not */
  73266. static const u8 aMJNeeded[] = {
  73267. /* DELETE */ 1,
  73268. /* PERSIST */ 1,
  73269. /* OFF */ 0,
  73270. /* TRUNCATE */ 1,
  73271. /* MEMORY */ 0,
  73272. /* WAL */ 0
  73273. };
  73274. Pager *pPager; /* Pager associated with pBt */
  73275. needXcommit = 1;
  73276. sqlite3BtreeEnter(pBt);
  73277. pPager = sqlite3BtreePager(pBt);
  73278. if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
  73279. && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
  73280. && sqlite3PagerIsMemdb(pPager)==0
  73281. ){
  73282. assert( i!=1 );
  73283. nTrans++;
  73284. }
  73285. rc = sqlite3PagerExclusiveLock(pPager);
  73286. sqlite3BtreeLeave(pBt);
  73287. }
  73288. }
  73289. if( rc!=SQLITE_OK ){
  73290. return rc;
  73291. }
  73292. /* If there are any write-transactions at all, invoke the commit hook */
  73293. if( needXcommit && db->xCommitCallback ){
  73294. rc = db->xCommitCallback(db->pCommitArg);
  73295. if( rc ){
  73296. return SQLITE_CONSTRAINT_COMMITHOOK;
  73297. }
  73298. }
  73299. /* The simple case - no more than one database file (not counting the
  73300. ** TEMP database) has a transaction active. There is no need for the
  73301. ** master-journal.
  73302. **
  73303. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  73304. ** string, it means the main database is :memory: or a temp file. In
  73305. ** that case we do not support atomic multi-file commits, so use the
  73306. ** simple case then too.
  73307. */
  73308. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  73309. || nTrans<=1
  73310. ){
  73311. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  73312. Btree *pBt = db->aDb[i].pBt;
  73313. if( pBt ){
  73314. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  73315. }
  73316. }
  73317. /* Do the commit only if all databases successfully complete phase 1.
  73318. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  73319. ** IO error while deleting or truncating a journal file. It is unlikely,
  73320. ** but could happen. In this case abandon processing and return the error.
  73321. */
  73322. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  73323. Btree *pBt = db->aDb[i].pBt;
  73324. if( pBt ){
  73325. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  73326. }
  73327. }
  73328. if( rc==SQLITE_OK ){
  73329. sqlite3VtabCommit(db);
  73330. }
  73331. }
  73332. /* The complex case - There is a multi-file write-transaction active.
  73333. ** This requires a master journal file to ensure the transaction is
  73334. ** committed atomically.
  73335. */
  73336. #ifndef SQLITE_OMIT_DISKIO
  73337. else{
  73338. sqlite3_vfs *pVfs = db->pVfs;
  73339. char *zMaster = 0; /* File-name for the master journal */
  73340. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  73341. sqlite3_file *pMaster = 0;
  73342. i64 offset = 0;
  73343. int res;
  73344. int retryCount = 0;
  73345. int nMainFile;
  73346. /* Select a master journal file name */
  73347. nMainFile = sqlite3Strlen30(zMainFile);
  73348. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  73349. if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
  73350. do {
  73351. u32 iRandom;
  73352. if( retryCount ){
  73353. if( retryCount>100 ){
  73354. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  73355. sqlite3OsDelete(pVfs, zMaster, 0);
  73356. break;
  73357. }else if( retryCount==1 ){
  73358. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  73359. }
  73360. }
  73361. retryCount++;
  73362. sqlite3_randomness(sizeof(iRandom), &iRandom);
  73363. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  73364. (iRandom>>8)&0xffffff, iRandom&0xff);
  73365. /* The antipenultimate character of the master journal name must
  73366. ** be "9" to avoid name collisions when using 8+3 filenames. */
  73367. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  73368. sqlite3FileSuffix3(zMainFile, zMaster);
  73369. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  73370. }while( rc==SQLITE_OK && res );
  73371. if( rc==SQLITE_OK ){
  73372. /* Open the master journal. */
  73373. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  73374. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  73375. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  73376. );
  73377. }
  73378. if( rc!=SQLITE_OK ){
  73379. sqlite3DbFree(db, zMaster);
  73380. return rc;
  73381. }
  73382. /* Write the name of each database file in the transaction into the new
  73383. ** master journal file. If an error occurs at this point close
  73384. ** and delete the master journal file. All the individual journal files
  73385. ** still have 'null' as the master journal pointer, so they will roll
  73386. ** back independently if a failure occurs.
  73387. */
  73388. for(i=0; i<db->nDb; i++){
  73389. Btree *pBt = db->aDb[i].pBt;
  73390. if( sqlite3BtreeIsInTrans(pBt) ){
  73391. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  73392. if( zFile==0 ){
  73393. continue; /* Ignore TEMP and :memory: databases */
  73394. }
  73395. assert( zFile[0]!=0 );
  73396. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  73397. offset += sqlite3Strlen30(zFile)+1;
  73398. if( rc!=SQLITE_OK ){
  73399. sqlite3OsCloseFree(pMaster);
  73400. sqlite3OsDelete(pVfs, zMaster, 0);
  73401. sqlite3DbFree(db, zMaster);
  73402. return rc;
  73403. }
  73404. }
  73405. }
  73406. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  73407. ** flag is set this is not required.
  73408. */
  73409. if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  73410. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  73411. ){
  73412. sqlite3OsCloseFree(pMaster);
  73413. sqlite3OsDelete(pVfs, zMaster, 0);
  73414. sqlite3DbFree(db, zMaster);
  73415. return rc;
  73416. }
  73417. /* Sync all the db files involved in the transaction. The same call
  73418. ** sets the master journal pointer in each individual journal. If
  73419. ** an error occurs here, do not delete the master journal file.
  73420. **
  73421. ** If the error occurs during the first call to
  73422. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  73423. ** master journal file will be orphaned. But we cannot delete it,
  73424. ** in case the master journal file name was written into the journal
  73425. ** file before the failure occurred.
  73426. */
  73427. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  73428. Btree *pBt = db->aDb[i].pBt;
  73429. if( pBt ){
  73430. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  73431. }
  73432. }
  73433. sqlite3OsCloseFree(pMaster);
  73434. assert( rc!=SQLITE_BUSY );
  73435. if( rc!=SQLITE_OK ){
  73436. sqlite3DbFree(db, zMaster);
  73437. return rc;
  73438. }
  73439. /* Delete the master journal file. This commits the transaction. After
  73440. ** doing this the directory is synced again before any individual
  73441. ** transaction files are deleted.
  73442. */
  73443. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  73444. sqlite3DbFree(db, zMaster);
  73445. zMaster = 0;
  73446. if( rc ){
  73447. return rc;
  73448. }
  73449. /* All files and directories have already been synced, so the following
  73450. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  73451. ** deleting or truncating journals. If something goes wrong while
  73452. ** this is happening we don't really care. The integrity of the
  73453. ** transaction is already guaranteed, but some stray 'cold' journals
  73454. ** may be lying around. Returning an error code won't help matters.
  73455. */
  73456. disable_simulated_io_errors();
  73457. sqlite3BeginBenignMalloc();
  73458. for(i=0; i<db->nDb; i++){
  73459. Btree *pBt = db->aDb[i].pBt;
  73460. if( pBt ){
  73461. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  73462. }
  73463. }
  73464. sqlite3EndBenignMalloc();
  73465. enable_simulated_io_errors();
  73466. sqlite3VtabCommit(db);
  73467. }
  73468. #endif
  73469. return rc;
  73470. }
  73471. /*
  73472. ** This routine checks that the sqlite3.nVdbeActive count variable
  73473. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  73474. ** currently active. An assertion fails if the two counts do not match.
  73475. ** This is an internal self-check only - it is not an essential processing
  73476. ** step.
  73477. **
  73478. ** This is a no-op if NDEBUG is defined.
  73479. */
  73480. #ifndef NDEBUG
  73481. static void checkActiveVdbeCnt(sqlite3 *db){
  73482. Vdbe *p;
  73483. int cnt = 0;
  73484. int nWrite = 0;
  73485. int nRead = 0;
  73486. p = db->pVdbe;
  73487. while( p ){
  73488. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  73489. cnt++;
  73490. if( p->readOnly==0 ) nWrite++;
  73491. if( p->bIsReader ) nRead++;
  73492. }
  73493. p = p->pNext;
  73494. }
  73495. assert( cnt==db->nVdbeActive );
  73496. assert( nWrite==db->nVdbeWrite );
  73497. assert( nRead==db->nVdbeRead );
  73498. }
  73499. #else
  73500. #define checkActiveVdbeCnt(x)
  73501. #endif
  73502. /*
  73503. ** If the Vdbe passed as the first argument opened a statement-transaction,
  73504. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  73505. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  73506. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  73507. ** statement transaction is committed.
  73508. **
  73509. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  73510. ** Otherwise SQLITE_OK.
  73511. */
  73512. static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
  73513. sqlite3 *const db = p->db;
  73514. int rc = SQLITE_OK;
  73515. int i;
  73516. const int iSavepoint = p->iStatement-1;
  73517. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  73518. assert( db->nStatement>0 );
  73519. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  73520. for(i=0; i<db->nDb; i++){
  73521. int rc2 = SQLITE_OK;
  73522. Btree *pBt = db->aDb[i].pBt;
  73523. if( pBt ){
  73524. if( eOp==SAVEPOINT_ROLLBACK ){
  73525. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  73526. }
  73527. if( rc2==SQLITE_OK ){
  73528. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  73529. }
  73530. if( rc==SQLITE_OK ){
  73531. rc = rc2;
  73532. }
  73533. }
  73534. }
  73535. db->nStatement--;
  73536. p->iStatement = 0;
  73537. if( rc==SQLITE_OK ){
  73538. if( eOp==SAVEPOINT_ROLLBACK ){
  73539. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  73540. }
  73541. if( rc==SQLITE_OK ){
  73542. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  73543. }
  73544. }
  73545. /* If the statement transaction is being rolled back, also restore the
  73546. ** database handles deferred constraint counter to the value it had when
  73547. ** the statement transaction was opened. */
  73548. if( eOp==SAVEPOINT_ROLLBACK ){
  73549. db->nDeferredCons = p->nStmtDefCons;
  73550. db->nDeferredImmCons = p->nStmtDefImmCons;
  73551. }
  73552. return rc;
  73553. }
  73554. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  73555. if( p->db->nStatement && p->iStatement ){
  73556. return vdbeCloseStatement(p, eOp);
  73557. }
  73558. return SQLITE_OK;
  73559. }
  73560. /*
  73561. ** This function is called when a transaction opened by the database
  73562. ** handle associated with the VM passed as an argument is about to be
  73563. ** committed. If there are outstanding deferred foreign key constraint
  73564. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  73565. **
  73566. ** If there are outstanding FK violations and this function returns
  73567. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  73568. ** and write an error message to it. Then return SQLITE_ERROR.
  73569. */
  73570. #ifndef SQLITE_OMIT_FOREIGN_KEY
  73571. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  73572. sqlite3 *db = p->db;
  73573. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  73574. || (!deferred && p->nFkConstraint>0)
  73575. ){
  73576. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  73577. p->errorAction = OE_Abort;
  73578. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  73579. return SQLITE_ERROR;
  73580. }
  73581. return SQLITE_OK;
  73582. }
  73583. #endif
  73584. /*
  73585. ** This routine is called the when a VDBE tries to halt. If the VDBE
  73586. ** has made changes and is in autocommit mode, then commit those
  73587. ** changes. If a rollback is needed, then do the rollback.
  73588. **
  73589. ** This routine is the only way to move the state of a VM from
  73590. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  73591. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  73592. **
  73593. ** Return an error code. If the commit could not complete because of
  73594. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  73595. ** means the close did not happen and needs to be repeated.
  73596. */
  73597. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  73598. int rc; /* Used to store transient return codes */
  73599. sqlite3 *db = p->db;
  73600. /* This function contains the logic that determines if a statement or
  73601. ** transaction will be committed or rolled back as a result of the
  73602. ** execution of this virtual machine.
  73603. **
  73604. ** If any of the following errors occur:
  73605. **
  73606. ** SQLITE_NOMEM
  73607. ** SQLITE_IOERR
  73608. ** SQLITE_FULL
  73609. ** SQLITE_INTERRUPT
  73610. **
  73611. ** Then the internal cache might have been left in an inconsistent
  73612. ** state. We need to rollback the statement transaction, if there is
  73613. ** one, or the complete transaction if there is no statement transaction.
  73614. */
  73615. if( p->magic!=VDBE_MAGIC_RUN ){
  73616. return SQLITE_OK;
  73617. }
  73618. if( db->mallocFailed ){
  73619. p->rc = SQLITE_NOMEM_BKPT;
  73620. }
  73621. closeAllCursors(p);
  73622. checkActiveVdbeCnt(db);
  73623. /* No commit or rollback needed if the program never started or if the
  73624. ** SQL statement does not read or write a database file. */
  73625. if( p->pc>=0 && p->bIsReader ){
  73626. int mrc; /* Primary error code from p->rc */
  73627. int eStatementOp = 0;
  73628. int isSpecialError; /* Set to true if a 'special' error */
  73629. /* Lock all btrees used by the statement */
  73630. sqlite3VdbeEnter(p);
  73631. /* Check for one of the special errors */
  73632. mrc = p->rc & 0xff;
  73633. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  73634. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  73635. if( isSpecialError ){
  73636. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  73637. ** no rollback is necessary. Otherwise, at least a savepoint
  73638. ** transaction must be rolled back to restore the database to a
  73639. ** consistent state.
  73640. **
  73641. ** Even if the statement is read-only, it is important to perform
  73642. ** a statement or transaction rollback operation. If the error
  73643. ** occurred while writing to the journal, sub-journal or database
  73644. ** file as part of an effort to free up cache space (see function
  73645. ** pagerStress() in pager.c), the rollback is required to restore
  73646. ** the pager to a consistent state.
  73647. */
  73648. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  73649. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  73650. eStatementOp = SAVEPOINT_ROLLBACK;
  73651. }else{
  73652. /* We are forced to roll back the active transaction. Before doing
  73653. ** so, abort any other statements this handle currently has active.
  73654. */
  73655. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  73656. sqlite3CloseSavepoints(db);
  73657. db->autoCommit = 1;
  73658. p->nChange = 0;
  73659. }
  73660. }
  73661. }
  73662. /* Check for immediate foreign key violations. */
  73663. if( p->rc==SQLITE_OK ){
  73664. sqlite3VdbeCheckFk(p, 0);
  73665. }
  73666. /* If the auto-commit flag is set and this is the only active writer
  73667. ** VM, then we do either a commit or rollback of the current transaction.
  73668. **
  73669. ** Note: This block also runs if one of the special errors handled
  73670. ** above has occurred.
  73671. */
  73672. if( !sqlite3VtabInSync(db)
  73673. && db->autoCommit
  73674. && db->nVdbeWrite==(p->readOnly==0)
  73675. ){
  73676. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  73677. rc = sqlite3VdbeCheckFk(p, 1);
  73678. if( rc!=SQLITE_OK ){
  73679. if( NEVER(p->readOnly) ){
  73680. sqlite3VdbeLeave(p);
  73681. return SQLITE_ERROR;
  73682. }
  73683. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  73684. }else{
  73685. /* The auto-commit flag is true, the vdbe program was successful
  73686. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  73687. ** key constraints to hold up the transaction. This means a commit
  73688. ** is required. */
  73689. rc = vdbeCommit(db, p);
  73690. }
  73691. if( rc==SQLITE_BUSY && p->readOnly ){
  73692. sqlite3VdbeLeave(p);
  73693. return SQLITE_BUSY;
  73694. }else if( rc!=SQLITE_OK ){
  73695. p->rc = rc;
  73696. sqlite3RollbackAll(db, SQLITE_OK);
  73697. p->nChange = 0;
  73698. }else{
  73699. db->nDeferredCons = 0;
  73700. db->nDeferredImmCons = 0;
  73701. db->flags &= ~SQLITE_DeferFKs;
  73702. sqlite3CommitInternalChanges(db);
  73703. }
  73704. }else{
  73705. sqlite3RollbackAll(db, SQLITE_OK);
  73706. p->nChange = 0;
  73707. }
  73708. db->nStatement = 0;
  73709. }else if( eStatementOp==0 ){
  73710. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  73711. eStatementOp = SAVEPOINT_RELEASE;
  73712. }else if( p->errorAction==OE_Abort ){
  73713. eStatementOp = SAVEPOINT_ROLLBACK;
  73714. }else{
  73715. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  73716. sqlite3CloseSavepoints(db);
  73717. db->autoCommit = 1;
  73718. p->nChange = 0;
  73719. }
  73720. }
  73721. /* If eStatementOp is non-zero, then a statement transaction needs to
  73722. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  73723. ** do so. If this operation returns an error, and the current statement
  73724. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  73725. ** current statement error code.
  73726. */
  73727. if( eStatementOp ){
  73728. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  73729. if( rc ){
  73730. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  73731. p->rc = rc;
  73732. sqlite3DbFree(db, p->zErrMsg);
  73733. p->zErrMsg = 0;
  73734. }
  73735. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  73736. sqlite3CloseSavepoints(db);
  73737. db->autoCommit = 1;
  73738. p->nChange = 0;
  73739. }
  73740. }
  73741. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  73742. ** has been rolled back, update the database connection change-counter.
  73743. */
  73744. if( p->changeCntOn ){
  73745. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  73746. sqlite3VdbeSetChanges(db, p->nChange);
  73747. }else{
  73748. sqlite3VdbeSetChanges(db, 0);
  73749. }
  73750. p->nChange = 0;
  73751. }
  73752. /* Release the locks */
  73753. sqlite3VdbeLeave(p);
  73754. }
  73755. /* We have successfully halted and closed the VM. Record this fact. */
  73756. if( p->pc>=0 ){
  73757. db->nVdbeActive--;
  73758. if( !p->readOnly ) db->nVdbeWrite--;
  73759. if( p->bIsReader ) db->nVdbeRead--;
  73760. assert( db->nVdbeActive>=db->nVdbeRead );
  73761. assert( db->nVdbeRead>=db->nVdbeWrite );
  73762. assert( db->nVdbeWrite>=0 );
  73763. }
  73764. p->magic = VDBE_MAGIC_HALT;
  73765. checkActiveVdbeCnt(db);
  73766. if( db->mallocFailed ){
  73767. p->rc = SQLITE_NOMEM_BKPT;
  73768. }
  73769. /* If the auto-commit flag is set to true, then any locks that were held
  73770. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  73771. ** to invoke any required unlock-notify callbacks.
  73772. */
  73773. if( db->autoCommit ){
  73774. sqlite3ConnectionUnlocked(db);
  73775. }
  73776. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  73777. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  73778. }
  73779. /*
  73780. ** Each VDBE holds the result of the most recent sqlite3_step() call
  73781. ** in p->rc. This routine sets that result back to SQLITE_OK.
  73782. */
  73783. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  73784. p->rc = SQLITE_OK;
  73785. }
  73786. /*
  73787. ** Copy the error code and error message belonging to the VDBE passed
  73788. ** as the first argument to its database handle (so that they will be
  73789. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  73790. **
  73791. ** This function does not clear the VDBE error code or message, just
  73792. ** copies them to the database handle.
  73793. */
  73794. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  73795. sqlite3 *db = p->db;
  73796. int rc = p->rc;
  73797. if( p->zErrMsg ){
  73798. db->bBenignMalloc++;
  73799. sqlite3BeginBenignMalloc();
  73800. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  73801. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  73802. sqlite3EndBenignMalloc();
  73803. db->bBenignMalloc--;
  73804. }else if( db->pErr ){
  73805. sqlite3ValueSetNull(db->pErr);
  73806. }
  73807. db->errCode = rc;
  73808. return rc;
  73809. }
  73810. #ifdef SQLITE_ENABLE_SQLLOG
  73811. /*
  73812. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  73813. ** invoke it.
  73814. */
  73815. static void vdbeInvokeSqllog(Vdbe *v){
  73816. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  73817. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  73818. assert( v->db->init.busy==0 );
  73819. if( zExpanded ){
  73820. sqlite3GlobalConfig.xSqllog(
  73821. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  73822. );
  73823. sqlite3DbFree(v->db, zExpanded);
  73824. }
  73825. }
  73826. }
  73827. #else
  73828. # define vdbeInvokeSqllog(x)
  73829. #endif
  73830. /*
  73831. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  73832. ** Write any error messages into *pzErrMsg. Return the result code.
  73833. **
  73834. ** After this routine is run, the VDBE should be ready to be executed
  73835. ** again.
  73836. **
  73837. ** To look at it another way, this routine resets the state of the
  73838. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  73839. ** VDBE_MAGIC_INIT.
  73840. */
  73841. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  73842. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  73843. int i;
  73844. #endif
  73845. sqlite3 *db;
  73846. db = p->db;
  73847. /* If the VM did not run to completion or if it encountered an
  73848. ** error, then it might not have been halted properly. So halt
  73849. ** it now.
  73850. */
  73851. sqlite3VdbeHalt(p);
  73852. /* If the VDBE has been run even partially, then transfer the error code
  73853. ** and error message from the VDBE into the main database structure. But
  73854. ** if the VDBE has just been set to run but has not actually executed any
  73855. ** instructions yet, leave the main database error information unchanged.
  73856. */
  73857. if( p->pc>=0 ){
  73858. vdbeInvokeSqllog(p);
  73859. sqlite3VdbeTransferError(p);
  73860. if( p->runOnlyOnce ) p->expired = 1;
  73861. }else if( p->rc && p->expired ){
  73862. /* The expired flag was set on the VDBE before the first call
  73863. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  73864. ** called), set the database error in this case as well.
  73865. */
  73866. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  73867. }
  73868. /* Reset register contents and reclaim error message memory.
  73869. */
  73870. #ifdef SQLITE_DEBUG
  73871. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  73872. ** Vdbe.aMem[] arrays have already been cleaned up. */
  73873. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  73874. if( p->aMem ){
  73875. for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  73876. }
  73877. #endif
  73878. sqlite3DbFree(db, p->zErrMsg);
  73879. p->zErrMsg = 0;
  73880. p->pResultSet = 0;
  73881. #ifdef SQLITE_DEBUG
  73882. p->nWrite = 0;
  73883. #endif
  73884. /* Save profiling information from this VDBE run.
  73885. */
  73886. #ifdef VDBE_PROFILE
  73887. {
  73888. FILE *out = fopen("vdbe_profile.out", "a");
  73889. if( out ){
  73890. fprintf(out, "---- ");
  73891. for(i=0; i<p->nOp; i++){
  73892. fprintf(out, "%02x", p->aOp[i].opcode);
  73893. }
  73894. fprintf(out, "\n");
  73895. if( p->zSql ){
  73896. char c, pc = 0;
  73897. fprintf(out, "-- ");
  73898. for(i=0; (c = p->zSql[i])!=0; i++){
  73899. if( pc=='\n' ) fprintf(out, "-- ");
  73900. putc(c, out);
  73901. pc = c;
  73902. }
  73903. if( pc!='\n' ) fprintf(out, "\n");
  73904. }
  73905. for(i=0; i<p->nOp; i++){
  73906. char zHdr[100];
  73907. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  73908. p->aOp[i].cnt,
  73909. p->aOp[i].cycles,
  73910. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  73911. );
  73912. fprintf(out, "%s", zHdr);
  73913. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  73914. }
  73915. fclose(out);
  73916. }
  73917. }
  73918. #endif
  73919. p->magic = VDBE_MAGIC_RESET;
  73920. return p->rc & db->errMask;
  73921. }
  73922. /*
  73923. ** Clean up and delete a VDBE after execution. Return an integer which is
  73924. ** the result code. Write any error message text into *pzErrMsg.
  73925. */
  73926. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  73927. int rc = SQLITE_OK;
  73928. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  73929. rc = sqlite3VdbeReset(p);
  73930. assert( (rc & p->db->errMask)==rc );
  73931. }
  73932. sqlite3VdbeDelete(p);
  73933. return rc;
  73934. }
  73935. /*
  73936. ** If parameter iOp is less than zero, then invoke the destructor for
  73937. ** all auxiliary data pointers currently cached by the VM passed as
  73938. ** the first argument.
  73939. **
  73940. ** Or, if iOp is greater than or equal to zero, then the destructor is
  73941. ** only invoked for those auxiliary data pointers created by the user
  73942. ** function invoked by the OP_Function opcode at instruction iOp of
  73943. ** VM pVdbe, and only then if:
  73944. **
  73945. ** * the associated function parameter is the 32nd or later (counting
  73946. ** from left to right), or
  73947. **
  73948. ** * the corresponding bit in argument mask is clear (where the first
  73949. ** function parameter corresponds to bit 0 etc.).
  73950. */
  73951. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
  73952. while( *pp ){
  73953. AuxData *pAux = *pp;
  73954. if( (iOp<0)
  73955. || (pAux->iAuxOp==iOp
  73956. && pAux->iAuxArg>=0
  73957. && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
  73958. ){
  73959. testcase( pAux->iAuxArg==31 );
  73960. if( pAux->xDeleteAux ){
  73961. pAux->xDeleteAux(pAux->pAux);
  73962. }
  73963. *pp = pAux->pNextAux;
  73964. sqlite3DbFree(db, pAux);
  73965. }else{
  73966. pp= &pAux->pNextAux;
  73967. }
  73968. }
  73969. }
  73970. /*
  73971. ** Free all memory associated with the Vdbe passed as the second argument,
  73972. ** except for object itself, which is preserved.
  73973. **
  73974. ** The difference between this function and sqlite3VdbeDelete() is that
  73975. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  73976. ** the database connection and frees the object itself.
  73977. */
  73978. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  73979. SubProgram *pSub, *pNext;
  73980. assert( p->db==0 || p->db==db );
  73981. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  73982. for(pSub=p->pProgram; pSub; pSub=pNext){
  73983. pNext = pSub->pNext;
  73984. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  73985. sqlite3DbFree(db, pSub);
  73986. }
  73987. if( p->magic!=VDBE_MAGIC_INIT ){
  73988. releaseMemArray(p->aVar, p->nVar);
  73989. sqlite3DbFree(db, p->pVList);
  73990. sqlite3DbFree(db, p->pFree);
  73991. }
  73992. vdbeFreeOpArray(db, p->aOp, p->nOp);
  73993. sqlite3DbFree(db, p->aColName);
  73994. sqlite3DbFree(db, p->zSql);
  73995. #ifdef SQLITE_ENABLE_NORMALIZE
  73996. sqlite3DbFree(db, p->zNormSql);
  73997. #endif
  73998. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73999. {
  74000. int i;
  74001. for(i=0; i<p->nScan; i++){
  74002. sqlite3DbFree(db, p->aScan[i].zName);
  74003. }
  74004. sqlite3DbFree(db, p->aScan);
  74005. }
  74006. #endif
  74007. }
  74008. /*
  74009. ** Delete an entire VDBE.
  74010. */
  74011. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  74012. sqlite3 *db;
  74013. assert( p!=0 );
  74014. db = p->db;
  74015. assert( sqlite3_mutex_held(db->mutex) );
  74016. sqlite3VdbeClearObject(db, p);
  74017. if( p->pPrev ){
  74018. p->pPrev->pNext = p->pNext;
  74019. }else{
  74020. assert( db->pVdbe==p );
  74021. db->pVdbe = p->pNext;
  74022. }
  74023. if( p->pNext ){
  74024. p->pNext->pPrev = p->pPrev;
  74025. }
  74026. p->magic = VDBE_MAGIC_DEAD;
  74027. p->db = 0;
  74028. sqlite3DbFreeNN(db, p);
  74029. }
  74030. /*
  74031. ** The cursor "p" has a pending seek operation that has not yet been
  74032. ** carried out. Seek the cursor now. If an error occurs, return
  74033. ** the appropriate error code.
  74034. */
  74035. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  74036. int res, rc;
  74037. #ifdef SQLITE_TEST
  74038. extern int sqlite3_search_count;
  74039. #endif
  74040. assert( p->deferredMoveto );
  74041. assert( p->isTable );
  74042. assert( p->eCurType==CURTYPE_BTREE );
  74043. rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
  74044. if( rc ) return rc;
  74045. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  74046. #ifdef SQLITE_TEST
  74047. sqlite3_search_count++;
  74048. #endif
  74049. p->deferredMoveto = 0;
  74050. p->cacheStatus = CACHE_STALE;
  74051. return SQLITE_OK;
  74052. }
  74053. /*
  74054. ** Something has moved cursor "p" out of place. Maybe the row it was
  74055. ** pointed to was deleted out from under it. Or maybe the btree was
  74056. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  74057. ** is supposed to be pointing. If the row was deleted out from under the
  74058. ** cursor, set the cursor to point to a NULL row.
  74059. */
  74060. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  74061. int isDifferentRow, rc;
  74062. assert( p->eCurType==CURTYPE_BTREE );
  74063. assert( p->uc.pCursor!=0 );
  74064. assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
  74065. rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
  74066. p->cacheStatus = CACHE_STALE;
  74067. if( isDifferentRow ) p->nullRow = 1;
  74068. return rc;
  74069. }
  74070. /*
  74071. ** Check to ensure that the cursor is valid. Restore the cursor
  74072. ** if need be. Return any I/O error from the restore operation.
  74073. */
  74074. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  74075. assert( p->eCurType==CURTYPE_BTREE );
  74076. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  74077. return handleMovedCursor(p);
  74078. }
  74079. return SQLITE_OK;
  74080. }
  74081. /*
  74082. ** Make sure the cursor p is ready to read or write the row to which it
  74083. ** was last positioned. Return an error code if an OOM fault or I/O error
  74084. ** prevents us from positioning the cursor to its correct position.
  74085. **
  74086. ** If a MoveTo operation is pending on the given cursor, then do that
  74087. ** MoveTo now. If no move is pending, check to see if the row has been
  74088. ** deleted out from under the cursor and if it has, mark the row as
  74089. ** a NULL row.
  74090. **
  74091. ** If the cursor is already pointing to the correct row and that row has
  74092. ** not been deleted out from under the cursor, then this routine is a no-op.
  74093. */
  74094. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
  74095. VdbeCursor *p = *pp;
  74096. assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
  74097. if( p->deferredMoveto ){
  74098. int iMap;
  74099. if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
  74100. *pp = p->pAltCursor;
  74101. *piCol = iMap - 1;
  74102. return SQLITE_OK;
  74103. }
  74104. return handleDeferredMoveto(p);
  74105. }
  74106. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  74107. return handleMovedCursor(p);
  74108. }
  74109. return SQLITE_OK;
  74110. }
  74111. /*
  74112. ** The following functions:
  74113. **
  74114. ** sqlite3VdbeSerialType()
  74115. ** sqlite3VdbeSerialTypeLen()
  74116. ** sqlite3VdbeSerialLen()
  74117. ** sqlite3VdbeSerialPut()
  74118. ** sqlite3VdbeSerialGet()
  74119. **
  74120. ** encapsulate the code that serializes values for storage in SQLite
  74121. ** data and index records. Each serialized value consists of a
  74122. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  74123. ** integer, stored as a varint.
  74124. **
  74125. ** In an SQLite index record, the serial type is stored directly before
  74126. ** the blob of data that it corresponds to. In a table record, all serial
  74127. ** types are stored at the start of the record, and the blobs of data at
  74128. ** the end. Hence these functions allow the caller to handle the
  74129. ** serial-type and data blob separately.
  74130. **
  74131. ** The following table describes the various storage classes for data:
  74132. **
  74133. ** serial type bytes of data type
  74134. ** -------------- --------------- ---------------
  74135. ** 0 0 NULL
  74136. ** 1 1 signed integer
  74137. ** 2 2 signed integer
  74138. ** 3 3 signed integer
  74139. ** 4 4 signed integer
  74140. ** 5 6 signed integer
  74141. ** 6 8 signed integer
  74142. ** 7 8 IEEE float
  74143. ** 8 0 Integer constant 0
  74144. ** 9 0 Integer constant 1
  74145. ** 10,11 reserved for expansion
  74146. ** N>=12 and even (N-12)/2 BLOB
  74147. ** N>=13 and odd (N-13)/2 text
  74148. **
  74149. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  74150. ** of SQLite will not understand those serial types.
  74151. */
  74152. /*
  74153. ** Return the serial-type for the value stored in pMem.
  74154. */
  74155. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
  74156. int flags = pMem->flags;
  74157. u32 n;
  74158. assert( pLen!=0 );
  74159. if( flags&MEM_Null ){
  74160. *pLen = 0;
  74161. return 0;
  74162. }
  74163. if( flags&MEM_Int ){
  74164. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  74165. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  74166. i64 i = pMem->u.i;
  74167. u64 u;
  74168. if( i<0 ){
  74169. u = ~i;
  74170. }else{
  74171. u = i;
  74172. }
  74173. if( u<=127 ){
  74174. if( (i&1)==i && file_format>=4 ){
  74175. *pLen = 0;
  74176. return 8+(u32)u;
  74177. }else{
  74178. *pLen = 1;
  74179. return 1;
  74180. }
  74181. }
  74182. if( u<=32767 ){ *pLen = 2; return 2; }
  74183. if( u<=8388607 ){ *pLen = 3; return 3; }
  74184. if( u<=2147483647 ){ *pLen = 4; return 4; }
  74185. if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
  74186. *pLen = 8;
  74187. return 6;
  74188. }
  74189. if( flags&MEM_Real ){
  74190. *pLen = 8;
  74191. return 7;
  74192. }
  74193. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  74194. assert( pMem->n>=0 );
  74195. n = (u32)pMem->n;
  74196. if( flags & MEM_Zero ){
  74197. n += pMem->u.nZero;
  74198. }
  74199. *pLen = n;
  74200. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  74201. }
  74202. /*
  74203. ** The sizes for serial types less than 128
  74204. */
  74205. static const u8 sqlite3SmallTypeSizes[] = {
  74206. /* 0 1 2 3 4 5 6 7 8 9 */
  74207. /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
  74208. /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  74209. /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  74210. /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  74211. /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
  74212. /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
  74213. /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
  74214. /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
  74215. /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
  74216. /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
  74217. /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
  74218. /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
  74219. /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
  74220. };
  74221. /*
  74222. ** Return the length of the data corresponding to the supplied serial-type.
  74223. */
  74224. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  74225. if( serial_type>=128 ){
  74226. return (serial_type-12)/2;
  74227. }else{
  74228. assert( serial_type<12
  74229. || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
  74230. return sqlite3SmallTypeSizes[serial_type];
  74231. }
  74232. }
  74233. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
  74234. assert( serial_type<128 );
  74235. return sqlite3SmallTypeSizes[serial_type];
  74236. }
  74237. /*
  74238. ** If we are on an architecture with mixed-endian floating
  74239. ** points (ex: ARM7) then swap the lower 4 bytes with the
  74240. ** upper 4 bytes. Return the result.
  74241. **
  74242. ** For most architectures, this is a no-op.
  74243. **
  74244. ** (later): It is reported to me that the mixed-endian problem
  74245. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  74246. ** that early versions of GCC stored the two words of a 64-bit
  74247. ** float in the wrong order. And that error has been propagated
  74248. ** ever since. The blame is not necessarily with GCC, though.
  74249. ** GCC might have just copying the problem from a prior compiler.
  74250. ** I am also told that newer versions of GCC that follow a different
  74251. ** ABI get the byte order right.
  74252. **
  74253. ** Developers using SQLite on an ARM7 should compile and run their
  74254. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  74255. ** enabled, some asserts below will ensure that the byte order of
  74256. ** floating point values is correct.
  74257. **
  74258. ** (2007-08-30) Frank van Vugt has studied this problem closely
  74259. ** and has send his findings to the SQLite developers. Frank
  74260. ** writes that some Linux kernels offer floating point hardware
  74261. ** emulation that uses only 32-bit mantissas instead of a full
  74262. ** 48-bits as required by the IEEE standard. (This is the
  74263. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  74264. ** byte swapping becomes very complicated. To avoid problems,
  74265. ** the necessary byte swapping is carried out using a 64-bit integer
  74266. ** rather than a 64-bit float. Frank assures us that the code here
  74267. ** works for him. We, the developers, have no way to independently
  74268. ** verify this, but Frank seems to know what he is talking about
  74269. ** so we trust him.
  74270. */
  74271. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  74272. static u64 floatSwap(u64 in){
  74273. union {
  74274. u64 r;
  74275. u32 i[2];
  74276. } u;
  74277. u32 t;
  74278. u.r = in;
  74279. t = u.i[0];
  74280. u.i[0] = u.i[1];
  74281. u.i[1] = t;
  74282. return u.r;
  74283. }
  74284. # define swapMixedEndianFloat(X) X = floatSwap(X)
  74285. #else
  74286. # define swapMixedEndianFloat(X)
  74287. #endif
  74288. /*
  74289. ** Write the serialized data blob for the value stored in pMem into
  74290. ** buf. It is assumed that the caller has allocated sufficient space.
  74291. ** Return the number of bytes written.
  74292. **
  74293. ** nBuf is the amount of space left in buf[]. The caller is responsible
  74294. ** for allocating enough space to buf[] to hold the entire field, exclusive
  74295. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  74296. **
  74297. ** Return the number of bytes actually written into buf[]. The number
  74298. ** of bytes in the zero-filled tail is included in the return value only
  74299. ** if those bytes were zeroed in buf[].
  74300. */
  74301. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  74302. u32 len;
  74303. /* Integer and Real */
  74304. if( serial_type<=7 && serial_type>0 ){
  74305. u64 v;
  74306. u32 i;
  74307. if( serial_type==7 ){
  74308. assert( sizeof(v)==sizeof(pMem->u.r) );
  74309. memcpy(&v, &pMem->u.r, sizeof(v));
  74310. swapMixedEndianFloat(v);
  74311. }else{
  74312. v = pMem->u.i;
  74313. }
  74314. len = i = sqlite3SmallTypeSizes[serial_type];
  74315. assert( i>0 );
  74316. do{
  74317. buf[--i] = (u8)(v&0xFF);
  74318. v >>= 8;
  74319. }while( i );
  74320. return len;
  74321. }
  74322. /* String or blob */
  74323. if( serial_type>=12 ){
  74324. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  74325. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  74326. len = pMem->n;
  74327. if( len>0 ) memcpy(buf, pMem->z, len);
  74328. return len;
  74329. }
  74330. /* NULL or constants 0 or 1 */
  74331. return 0;
  74332. }
  74333. /* Input "x" is a sequence of unsigned characters that represent a
  74334. ** big-endian integer. Return the equivalent native integer
  74335. */
  74336. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  74337. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  74338. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  74339. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  74340. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  74341. /*
  74342. ** Deserialize the data blob pointed to by buf as serial type serial_type
  74343. ** and store the result in pMem. Return the number of bytes read.
  74344. **
  74345. ** This function is implemented as two separate routines for performance.
  74346. ** The few cases that require local variables are broken out into a separate
  74347. ** routine so that in most cases the overhead of moving the stack pointer
  74348. ** is avoided.
  74349. */
  74350. static u32 SQLITE_NOINLINE serialGet(
  74351. const unsigned char *buf, /* Buffer to deserialize from */
  74352. u32 serial_type, /* Serial type to deserialize */
  74353. Mem *pMem /* Memory cell to write value into */
  74354. ){
  74355. u64 x = FOUR_BYTE_UINT(buf);
  74356. u32 y = FOUR_BYTE_UINT(buf+4);
  74357. x = (x<<32) + y;
  74358. if( serial_type==6 ){
  74359. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  74360. ** twos-complement integer. */
  74361. pMem->u.i = *(i64*)&x;
  74362. pMem->flags = MEM_Int;
  74363. testcase( pMem->u.i<0 );
  74364. }else{
  74365. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  74366. ** floating point number. */
  74367. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  74368. /* Verify that integers and floating point values use the same
  74369. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  74370. ** defined that 64-bit floating point values really are mixed
  74371. ** endian.
  74372. */
  74373. static const u64 t1 = ((u64)0x3ff00000)<<32;
  74374. static const double r1 = 1.0;
  74375. u64 t2 = t1;
  74376. swapMixedEndianFloat(t2);
  74377. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  74378. #endif
  74379. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  74380. swapMixedEndianFloat(x);
  74381. memcpy(&pMem->u.r, &x, sizeof(x));
  74382. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  74383. }
  74384. return 8;
  74385. }
  74386. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  74387. const unsigned char *buf, /* Buffer to deserialize from */
  74388. u32 serial_type, /* Serial type to deserialize */
  74389. Mem *pMem /* Memory cell to write value into */
  74390. ){
  74391. switch( serial_type ){
  74392. case 10: { /* Internal use only: NULL with virtual table
  74393. ** UPDATE no-change flag set */
  74394. pMem->flags = MEM_Null|MEM_Zero;
  74395. pMem->n = 0;
  74396. pMem->u.nZero = 0;
  74397. break;
  74398. }
  74399. case 11: /* Reserved for future use */
  74400. case 0: { /* Null */
  74401. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  74402. pMem->flags = MEM_Null;
  74403. break;
  74404. }
  74405. case 1: {
  74406. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  74407. ** integer. */
  74408. pMem->u.i = ONE_BYTE_INT(buf);
  74409. pMem->flags = MEM_Int;
  74410. testcase( pMem->u.i<0 );
  74411. return 1;
  74412. }
  74413. case 2: { /* 2-byte signed integer */
  74414. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  74415. ** twos-complement integer. */
  74416. pMem->u.i = TWO_BYTE_INT(buf);
  74417. pMem->flags = MEM_Int;
  74418. testcase( pMem->u.i<0 );
  74419. return 2;
  74420. }
  74421. case 3: { /* 3-byte signed integer */
  74422. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  74423. ** twos-complement integer. */
  74424. pMem->u.i = THREE_BYTE_INT(buf);
  74425. pMem->flags = MEM_Int;
  74426. testcase( pMem->u.i<0 );
  74427. return 3;
  74428. }
  74429. case 4: { /* 4-byte signed integer */
  74430. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  74431. ** twos-complement integer. */
  74432. pMem->u.i = FOUR_BYTE_INT(buf);
  74433. #ifdef __HP_cc
  74434. /* Work around a sign-extension bug in the HP compiler for HP/UX */
  74435. if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
  74436. #endif
  74437. pMem->flags = MEM_Int;
  74438. testcase( pMem->u.i<0 );
  74439. return 4;
  74440. }
  74441. case 5: { /* 6-byte signed integer */
  74442. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  74443. ** twos-complement integer. */
  74444. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  74445. pMem->flags = MEM_Int;
  74446. testcase( pMem->u.i<0 );
  74447. return 6;
  74448. }
  74449. case 6: /* 8-byte signed integer */
  74450. case 7: { /* IEEE floating point */
  74451. /* These use local variables, so do them in a separate routine
  74452. ** to avoid having to move the frame pointer in the common case */
  74453. return serialGet(buf,serial_type,pMem);
  74454. }
  74455. case 8: /* Integer 0 */
  74456. case 9: { /* Integer 1 */
  74457. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  74458. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  74459. pMem->u.i = serial_type-8;
  74460. pMem->flags = MEM_Int;
  74461. return 0;
  74462. }
  74463. default: {
  74464. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  74465. ** length.
  74466. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  74467. ** (N-13)/2 bytes in length. */
  74468. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  74469. pMem->z = (char *)buf;
  74470. pMem->n = (serial_type-12)/2;
  74471. pMem->flags = aFlag[serial_type&1];
  74472. return pMem->n;
  74473. }
  74474. }
  74475. return 0;
  74476. }
  74477. /*
  74478. ** This routine is used to allocate sufficient space for an UnpackedRecord
  74479. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  74480. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  74481. **
  74482. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  74483. ** the unaligned buffer passed via the second and third arguments (presumably
  74484. ** stack space). If the former, then *ppFree is set to a pointer that should
  74485. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  74486. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  74487. ** before returning.
  74488. **
  74489. ** If an OOM error occurs, NULL is returned.
  74490. */
  74491. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  74492. KeyInfo *pKeyInfo /* Description of the record */
  74493. ){
  74494. UnpackedRecord *p; /* Unpacked record to return */
  74495. int nByte; /* Number of bytes required for *p */
  74496. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
  74497. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  74498. if( !p ) return 0;
  74499. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  74500. assert( pKeyInfo->aSortOrder!=0 );
  74501. p->pKeyInfo = pKeyInfo;
  74502. p->nField = pKeyInfo->nKeyField + 1;
  74503. return p;
  74504. }
  74505. /*
  74506. ** Given the nKey-byte encoding of a record in pKey[], populate the
  74507. ** UnpackedRecord structure indicated by the fourth argument with the
  74508. ** contents of the decoded record.
  74509. */
  74510. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  74511. KeyInfo *pKeyInfo, /* Information about the record format */
  74512. int nKey, /* Size of the binary record */
  74513. const void *pKey, /* The binary record */
  74514. UnpackedRecord *p /* Populate this structure before returning. */
  74515. ){
  74516. const unsigned char *aKey = (const unsigned char *)pKey;
  74517. int d;
  74518. u32 idx; /* Offset in aKey[] to read from */
  74519. u16 u; /* Unsigned loop counter */
  74520. u32 szHdr;
  74521. Mem *pMem = p->aMem;
  74522. p->default_rc = 0;
  74523. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  74524. idx = getVarint32(aKey, szHdr);
  74525. d = szHdr;
  74526. u = 0;
  74527. while( idx<szHdr && d<=nKey ){
  74528. u32 serial_type;
  74529. idx += getVarint32(&aKey[idx], serial_type);
  74530. pMem->enc = pKeyInfo->enc;
  74531. pMem->db = pKeyInfo->db;
  74532. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  74533. pMem->szMalloc = 0;
  74534. pMem->z = 0;
  74535. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  74536. pMem++;
  74537. if( (++u)>=p->nField ) break;
  74538. }
  74539. assert( u<=pKeyInfo->nKeyField + 1 );
  74540. p->nField = u;
  74541. }
  74542. #ifdef SQLITE_DEBUG
  74543. /*
  74544. ** This function compares two index or table record keys in the same way
  74545. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  74546. ** this function deserializes and compares values using the
  74547. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  74548. ** in assert() statements to ensure that the optimized code in
  74549. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  74550. **
  74551. ** Return true if the result of comparison is equivalent to desiredResult.
  74552. ** Return false if there is a disagreement.
  74553. */
  74554. static int vdbeRecordCompareDebug(
  74555. int nKey1, const void *pKey1, /* Left key */
  74556. const UnpackedRecord *pPKey2, /* Right key */
  74557. int desiredResult /* Correct answer */
  74558. ){
  74559. u32 d1; /* Offset into aKey[] of next data element */
  74560. u32 idx1; /* Offset into aKey[] of next header element */
  74561. u32 szHdr1; /* Number of bytes in header */
  74562. int i = 0;
  74563. int rc = 0;
  74564. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  74565. KeyInfo *pKeyInfo;
  74566. Mem mem1;
  74567. pKeyInfo = pPKey2->pKeyInfo;
  74568. if( pKeyInfo->db==0 ) return 1;
  74569. mem1.enc = pKeyInfo->enc;
  74570. mem1.db = pKeyInfo->db;
  74571. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  74572. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  74573. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  74574. ** We could initialize it, as shown here, to silence those complaints.
  74575. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  74576. ** the unnecessary initialization has a measurable negative performance
  74577. ** impact, since this routine is a very high runner. And so, we choose
  74578. ** to ignore the compiler warnings and leave this variable uninitialized.
  74579. */
  74580. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  74581. idx1 = getVarint32(aKey1, szHdr1);
  74582. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  74583. d1 = szHdr1;
  74584. assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
  74585. assert( pKeyInfo->aSortOrder!=0 );
  74586. assert( pKeyInfo->nKeyField>0 );
  74587. assert( idx1<=szHdr1 || CORRUPT_DB );
  74588. do{
  74589. u32 serial_type1;
  74590. /* Read the serial types for the next element in each key. */
  74591. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  74592. /* Verify that there is enough key space remaining to avoid
  74593. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  74594. ** always be greater than or equal to the amount of required key space.
  74595. ** Use that approximation to avoid the more expensive call to
  74596. ** sqlite3VdbeSerialTypeLen() in the common case.
  74597. */
  74598. if( d1+serial_type1+2>(u32)nKey1
  74599. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  74600. ){
  74601. break;
  74602. }
  74603. /* Extract the values to be compared.
  74604. */
  74605. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  74606. /* Do the comparison
  74607. */
  74608. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  74609. if( rc!=0 ){
  74610. assert( mem1.szMalloc==0 ); /* See comment below */
  74611. if( pKeyInfo->aSortOrder[i] ){
  74612. rc = -rc; /* Invert the result for DESC sort order. */
  74613. }
  74614. goto debugCompareEnd;
  74615. }
  74616. i++;
  74617. }while( idx1<szHdr1 && i<pPKey2->nField );
  74618. /* No memory allocation is ever used on mem1. Prove this using
  74619. ** the following assert(). If the assert() fails, it indicates a
  74620. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  74621. */
  74622. assert( mem1.szMalloc==0 );
  74623. /* rc==0 here means that one of the keys ran out of fields and
  74624. ** all the fields up to that point were equal. Return the default_rc
  74625. ** value. */
  74626. rc = pPKey2->default_rc;
  74627. debugCompareEnd:
  74628. if( desiredResult==0 && rc==0 ) return 1;
  74629. if( desiredResult<0 && rc<0 ) return 1;
  74630. if( desiredResult>0 && rc>0 ) return 1;
  74631. if( CORRUPT_DB ) return 1;
  74632. if( pKeyInfo->db->mallocFailed ) return 1;
  74633. return 0;
  74634. }
  74635. #endif
  74636. #ifdef SQLITE_DEBUG
  74637. /*
  74638. ** Count the number of fields (a.k.a. columns) in the record given by
  74639. ** pKey,nKey. The verify that this count is less than or equal to the
  74640. ** limit given by pKeyInfo->nAllField.
  74641. **
  74642. ** If this constraint is not satisfied, it means that the high-speed
  74643. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  74644. ** not work correctly. If this assert() ever fires, it probably means
  74645. ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
  74646. ** incorrectly.
  74647. */
  74648. static void vdbeAssertFieldCountWithinLimits(
  74649. int nKey, const void *pKey, /* The record to verify */
  74650. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  74651. ){
  74652. int nField = 0;
  74653. u32 szHdr;
  74654. u32 idx;
  74655. u32 notUsed;
  74656. const unsigned char *aKey = (const unsigned char*)pKey;
  74657. if( CORRUPT_DB ) return;
  74658. idx = getVarint32(aKey, szHdr);
  74659. assert( nKey>=0 );
  74660. assert( szHdr<=(u32)nKey );
  74661. while( idx<szHdr ){
  74662. idx += getVarint32(aKey+idx, notUsed);
  74663. nField++;
  74664. }
  74665. assert( nField <= pKeyInfo->nAllField );
  74666. }
  74667. #else
  74668. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  74669. #endif
  74670. /*
  74671. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  74672. ** using the collation sequence pColl. As usual, return a negative , zero
  74673. ** or positive value if *pMem1 is less than, equal to or greater than
  74674. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  74675. */
  74676. static int vdbeCompareMemString(
  74677. const Mem *pMem1,
  74678. const Mem *pMem2,
  74679. const CollSeq *pColl,
  74680. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  74681. ){
  74682. if( pMem1->enc==pColl->enc ){
  74683. /* The strings are already in the correct encoding. Call the
  74684. ** comparison function directly */
  74685. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  74686. }else{
  74687. int rc;
  74688. const void *v1, *v2;
  74689. Mem c1;
  74690. Mem c2;
  74691. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  74692. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  74693. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  74694. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  74695. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  74696. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  74697. if( (v1==0 || v2==0) ){
  74698. if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
  74699. rc = 0;
  74700. }else{
  74701. rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
  74702. }
  74703. sqlite3VdbeMemRelease(&c1);
  74704. sqlite3VdbeMemRelease(&c2);
  74705. return rc;
  74706. }
  74707. }
  74708. /*
  74709. ** The input pBlob is guaranteed to be a Blob that is not marked
  74710. ** with MEM_Zero. Return true if it could be a zero-blob.
  74711. */
  74712. static int isAllZero(const char *z, int n){
  74713. int i;
  74714. for(i=0; i<n; i++){
  74715. if( z[i] ) return 0;
  74716. }
  74717. return 1;
  74718. }
  74719. /*
  74720. ** Compare two blobs. Return negative, zero, or positive if the first
  74721. ** is less than, equal to, or greater than the second, respectively.
  74722. ** If one blob is a prefix of the other, then the shorter is the lessor.
  74723. */
  74724. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  74725. int c;
  74726. int n1 = pB1->n;
  74727. int n2 = pB2->n;
  74728. /* It is possible to have a Blob value that has some non-zero content
  74729. ** followed by zero content. But that only comes up for Blobs formed
  74730. ** by the OP_MakeRecord opcode, and such Blobs never get passed into
  74731. ** sqlite3MemCompare(). */
  74732. assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
  74733. assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
  74734. if( (pB1->flags|pB2->flags) & MEM_Zero ){
  74735. if( pB1->flags & pB2->flags & MEM_Zero ){
  74736. return pB1->u.nZero - pB2->u.nZero;
  74737. }else if( pB1->flags & MEM_Zero ){
  74738. if( !isAllZero(pB2->z, pB2->n) ) return -1;
  74739. return pB1->u.nZero - n2;
  74740. }else{
  74741. if( !isAllZero(pB1->z, pB1->n) ) return +1;
  74742. return n1 - pB2->u.nZero;
  74743. }
  74744. }
  74745. c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
  74746. if( c ) return c;
  74747. return n1 - n2;
  74748. }
  74749. /*
  74750. ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
  74751. ** number. Return negative, zero, or positive if the first (i64) is less than,
  74752. ** equal to, or greater than the second (double).
  74753. */
  74754. static int sqlite3IntFloatCompare(i64 i, double r){
  74755. if( sizeof(LONGDOUBLE_TYPE)>8 ){
  74756. LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
  74757. if( x<r ) return -1;
  74758. if( x>r ) return +1;
  74759. return 0;
  74760. }else{
  74761. i64 y;
  74762. double s;
  74763. if( r<-9223372036854775808.0 ) return +1;
  74764. if( r>=9223372036854775808.0 ) return -1;
  74765. y = (i64)r;
  74766. if( i<y ) return -1;
  74767. if( i>y ) return +1;
  74768. s = (double)i;
  74769. if( s<r ) return -1;
  74770. if( s>r ) return +1;
  74771. return 0;
  74772. }
  74773. }
  74774. /*
  74775. ** Compare the values contained by the two memory cells, returning
  74776. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  74777. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  74778. ** and reals) sorted numerically, followed by text ordered by the collating
  74779. ** sequence pColl and finally blob's ordered by memcmp().
  74780. **
  74781. ** Two NULL values are considered equal by this function.
  74782. */
  74783. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  74784. int f1, f2;
  74785. int combined_flags;
  74786. f1 = pMem1->flags;
  74787. f2 = pMem2->flags;
  74788. combined_flags = f1|f2;
  74789. assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
  74790. /* If one value is NULL, it is less than the other. If both values
  74791. ** are NULL, return 0.
  74792. */
  74793. if( combined_flags&MEM_Null ){
  74794. return (f2&MEM_Null) - (f1&MEM_Null);
  74795. }
  74796. /* At least one of the two values is a number
  74797. */
  74798. if( combined_flags&(MEM_Int|MEM_Real) ){
  74799. if( (f1 & f2 & MEM_Int)!=0 ){
  74800. if( pMem1->u.i < pMem2->u.i ) return -1;
  74801. if( pMem1->u.i > pMem2->u.i ) return +1;
  74802. return 0;
  74803. }
  74804. if( (f1 & f2 & MEM_Real)!=0 ){
  74805. if( pMem1->u.r < pMem2->u.r ) return -1;
  74806. if( pMem1->u.r > pMem2->u.r ) return +1;
  74807. return 0;
  74808. }
  74809. if( (f1&MEM_Int)!=0 ){
  74810. if( (f2&MEM_Real)!=0 ){
  74811. return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
  74812. }else{
  74813. return -1;
  74814. }
  74815. }
  74816. if( (f1&MEM_Real)!=0 ){
  74817. if( (f2&MEM_Int)!=0 ){
  74818. return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
  74819. }else{
  74820. return -1;
  74821. }
  74822. }
  74823. return +1;
  74824. }
  74825. /* If one value is a string and the other is a blob, the string is less.
  74826. ** If both are strings, compare using the collating functions.
  74827. */
  74828. if( combined_flags&MEM_Str ){
  74829. if( (f1 & MEM_Str)==0 ){
  74830. return 1;
  74831. }
  74832. if( (f2 & MEM_Str)==0 ){
  74833. return -1;
  74834. }
  74835. assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
  74836. assert( pMem1->enc==SQLITE_UTF8 ||
  74837. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  74838. /* The collation sequence must be defined at this point, even if
  74839. ** the user deletes the collation sequence after the vdbe program is
  74840. ** compiled (this was not always the case).
  74841. */
  74842. assert( !pColl || pColl->xCmp );
  74843. if( pColl ){
  74844. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  74845. }
  74846. /* If a NULL pointer was passed as the collate function, fall through
  74847. ** to the blob case and use memcmp(). */
  74848. }
  74849. /* Both values must be blobs. Compare using memcmp(). */
  74850. return sqlite3BlobCompare(pMem1, pMem2);
  74851. }
  74852. /*
  74853. ** The first argument passed to this function is a serial-type that
  74854. ** corresponds to an integer - all values between 1 and 9 inclusive
  74855. ** except 7. The second points to a buffer containing an integer value
  74856. ** serialized according to serial_type. This function deserializes
  74857. ** and returns the value.
  74858. */
  74859. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  74860. u32 y;
  74861. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  74862. switch( serial_type ){
  74863. case 0:
  74864. case 1:
  74865. testcase( aKey[0]&0x80 );
  74866. return ONE_BYTE_INT(aKey);
  74867. case 2:
  74868. testcase( aKey[0]&0x80 );
  74869. return TWO_BYTE_INT(aKey);
  74870. case 3:
  74871. testcase( aKey[0]&0x80 );
  74872. return THREE_BYTE_INT(aKey);
  74873. case 4: {
  74874. testcase( aKey[0]&0x80 );
  74875. y = FOUR_BYTE_UINT(aKey);
  74876. return (i64)*(int*)&y;
  74877. }
  74878. case 5: {
  74879. testcase( aKey[0]&0x80 );
  74880. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  74881. }
  74882. case 6: {
  74883. u64 x = FOUR_BYTE_UINT(aKey);
  74884. testcase( aKey[0]&0x80 );
  74885. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  74886. return (i64)*(i64*)&x;
  74887. }
  74888. }
  74889. return (serial_type - 8);
  74890. }
  74891. /*
  74892. ** This function compares the two table rows or index records
  74893. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  74894. ** or positive integer if key1 is less than, equal to or
  74895. ** greater than key2. The {nKey1, pKey1} key must be a blob
  74896. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  74897. ** key must be a parsed key such as obtained from
  74898. ** sqlite3VdbeParseRecord.
  74899. **
  74900. ** If argument bSkip is non-zero, it is assumed that the caller has already
  74901. ** determined that the first fields of the keys are equal.
  74902. **
  74903. ** Key1 and Key2 do not have to contain the same number of fields. If all
  74904. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  74905. ** returned.
  74906. **
  74907. ** If database corruption is discovered, set pPKey2->errCode to
  74908. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  74909. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  74910. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  74911. */
  74912. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  74913. int nKey1, const void *pKey1, /* Left key */
  74914. UnpackedRecord *pPKey2, /* Right key */
  74915. int bSkip /* If true, skip the first field */
  74916. ){
  74917. u32 d1; /* Offset into aKey[] of next data element */
  74918. int i; /* Index of next field to compare */
  74919. u32 szHdr1; /* Size of record header in bytes */
  74920. u32 idx1; /* Offset of first type in header */
  74921. int rc = 0; /* Return value */
  74922. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  74923. KeyInfo *pKeyInfo;
  74924. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  74925. Mem mem1;
  74926. /* If bSkip is true, then the caller has already determined that the first
  74927. ** two elements in the keys are equal. Fix the various stack variables so
  74928. ** that this routine begins comparing at the second field. */
  74929. if( bSkip ){
  74930. u32 s1;
  74931. idx1 = 1 + getVarint32(&aKey1[1], s1);
  74932. szHdr1 = aKey1[0];
  74933. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  74934. i = 1;
  74935. pRhs++;
  74936. }else{
  74937. idx1 = getVarint32(aKey1, szHdr1);
  74938. d1 = szHdr1;
  74939. if( d1>(unsigned)nKey1 ){
  74940. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  74941. return 0; /* Corruption */
  74942. }
  74943. i = 0;
  74944. }
  74945. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  74946. assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
  74947. || CORRUPT_DB );
  74948. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  74949. assert( pPKey2->pKeyInfo->nKeyField>0 );
  74950. assert( idx1<=szHdr1 || CORRUPT_DB );
  74951. do{
  74952. u32 serial_type;
  74953. /* RHS is an integer */
  74954. if( pRhs->flags & MEM_Int ){
  74955. serial_type = aKey1[idx1];
  74956. testcase( serial_type==12 );
  74957. if( serial_type>=10 ){
  74958. rc = +1;
  74959. }else if( serial_type==0 ){
  74960. rc = -1;
  74961. }else if( serial_type==7 ){
  74962. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  74963. rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
  74964. }else{
  74965. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  74966. i64 rhs = pRhs->u.i;
  74967. if( lhs<rhs ){
  74968. rc = -1;
  74969. }else if( lhs>rhs ){
  74970. rc = +1;
  74971. }
  74972. }
  74973. }
  74974. /* RHS is real */
  74975. else if( pRhs->flags & MEM_Real ){
  74976. serial_type = aKey1[idx1];
  74977. if( serial_type>=10 ){
  74978. /* Serial types 12 or greater are strings and blobs (greater than
  74979. ** numbers). Types 10 and 11 are currently "reserved for future
  74980. ** use", so it doesn't really matter what the results of comparing
  74981. ** them to numberic values are. */
  74982. rc = +1;
  74983. }else if( serial_type==0 ){
  74984. rc = -1;
  74985. }else{
  74986. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  74987. if( serial_type==7 ){
  74988. if( mem1.u.r<pRhs->u.r ){
  74989. rc = -1;
  74990. }else if( mem1.u.r>pRhs->u.r ){
  74991. rc = +1;
  74992. }
  74993. }else{
  74994. rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
  74995. }
  74996. }
  74997. }
  74998. /* RHS is a string */
  74999. else if( pRhs->flags & MEM_Str ){
  75000. getVarint32(&aKey1[idx1], serial_type);
  75001. testcase( serial_type==12 );
  75002. if( serial_type<12 ){
  75003. rc = -1;
  75004. }else if( !(serial_type & 0x01) ){
  75005. rc = +1;
  75006. }else{
  75007. mem1.n = (serial_type - 12) / 2;
  75008. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  75009. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  75010. if( (d1+mem1.n) > (unsigned)nKey1 ){
  75011. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  75012. return 0; /* Corruption */
  75013. }else if( (pKeyInfo = pPKey2->pKeyInfo)->aColl[i] ){
  75014. mem1.enc = pKeyInfo->enc;
  75015. mem1.db = pKeyInfo->db;
  75016. mem1.flags = MEM_Str;
  75017. mem1.z = (char*)&aKey1[d1];
  75018. rc = vdbeCompareMemString(
  75019. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  75020. );
  75021. }else{
  75022. int nCmp = MIN(mem1.n, pRhs->n);
  75023. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  75024. if( rc==0 ) rc = mem1.n - pRhs->n;
  75025. }
  75026. }
  75027. }
  75028. /* RHS is a blob */
  75029. else if( pRhs->flags & MEM_Blob ){
  75030. assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
  75031. getVarint32(&aKey1[idx1], serial_type);
  75032. testcase( serial_type==12 );
  75033. if( serial_type<12 || (serial_type & 0x01) ){
  75034. rc = -1;
  75035. }else{
  75036. int nStr = (serial_type - 12) / 2;
  75037. testcase( (d1+nStr)==(unsigned)nKey1 );
  75038. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  75039. if( (d1+nStr) > (unsigned)nKey1 ){
  75040. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  75041. return 0; /* Corruption */
  75042. }else if( pRhs->flags & MEM_Zero ){
  75043. if( !isAllZero((const char*)&aKey1[d1],nStr) ){
  75044. rc = 1;
  75045. }else{
  75046. rc = nStr - pRhs->u.nZero;
  75047. }
  75048. }else{
  75049. int nCmp = MIN(nStr, pRhs->n);
  75050. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  75051. if( rc==0 ) rc = nStr - pRhs->n;
  75052. }
  75053. }
  75054. }
  75055. /* RHS is null */
  75056. else{
  75057. serial_type = aKey1[idx1];
  75058. rc = (serial_type!=0);
  75059. }
  75060. if( rc!=0 ){
  75061. if( pPKey2->pKeyInfo->aSortOrder[i] ){
  75062. rc = -rc;
  75063. }
  75064. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  75065. assert( mem1.szMalloc==0 ); /* See comment below */
  75066. return rc;
  75067. }
  75068. i++;
  75069. if( i==pPKey2->nField ) break;
  75070. pRhs++;
  75071. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  75072. idx1 += sqlite3VarintLen(serial_type);
  75073. }while( idx1<(unsigned)szHdr1 && d1<=(unsigned)nKey1 );
  75074. /* No memory allocation is ever used on mem1. Prove this using
  75075. ** the following assert(). If the assert() fails, it indicates a
  75076. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  75077. assert( mem1.szMalloc==0 );
  75078. /* rc==0 here means that one or both of the keys ran out of fields and
  75079. ** all the fields up to that point were equal. Return the default_rc
  75080. ** value. */
  75081. assert( CORRUPT_DB
  75082. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  75083. || pPKey2->pKeyInfo->db->mallocFailed
  75084. );
  75085. pPKey2->eqSeen = 1;
  75086. return pPKey2->default_rc;
  75087. }
  75088. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  75089. int nKey1, const void *pKey1, /* Left key */
  75090. UnpackedRecord *pPKey2 /* Right key */
  75091. ){
  75092. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  75093. }
  75094. /*
  75095. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  75096. ** that (a) the first field of pPKey2 is an integer, and (b) the
  75097. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  75098. ** byte (i.e. is less than 128).
  75099. **
  75100. ** To avoid concerns about buffer overreads, this routine is only used
  75101. ** on schemas where the maximum valid header size is 63 bytes or less.
  75102. */
  75103. static int vdbeRecordCompareInt(
  75104. int nKey1, const void *pKey1, /* Left key */
  75105. UnpackedRecord *pPKey2 /* Right key */
  75106. ){
  75107. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  75108. int serial_type = ((const u8*)pKey1)[1];
  75109. int res;
  75110. u32 y;
  75111. u64 x;
  75112. i64 v;
  75113. i64 lhs;
  75114. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  75115. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  75116. switch( serial_type ){
  75117. case 1: { /* 1-byte signed integer */
  75118. lhs = ONE_BYTE_INT(aKey);
  75119. testcase( lhs<0 );
  75120. break;
  75121. }
  75122. case 2: { /* 2-byte signed integer */
  75123. lhs = TWO_BYTE_INT(aKey);
  75124. testcase( lhs<0 );
  75125. break;
  75126. }
  75127. case 3: { /* 3-byte signed integer */
  75128. lhs = THREE_BYTE_INT(aKey);
  75129. testcase( lhs<0 );
  75130. break;
  75131. }
  75132. case 4: { /* 4-byte signed integer */
  75133. y = FOUR_BYTE_UINT(aKey);
  75134. lhs = (i64)*(int*)&y;
  75135. testcase( lhs<0 );
  75136. break;
  75137. }
  75138. case 5: { /* 6-byte signed integer */
  75139. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  75140. testcase( lhs<0 );
  75141. break;
  75142. }
  75143. case 6: { /* 8-byte signed integer */
  75144. x = FOUR_BYTE_UINT(aKey);
  75145. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  75146. lhs = *(i64*)&x;
  75147. testcase( lhs<0 );
  75148. break;
  75149. }
  75150. case 8:
  75151. lhs = 0;
  75152. break;
  75153. case 9:
  75154. lhs = 1;
  75155. break;
  75156. /* This case could be removed without changing the results of running
  75157. ** this code. Including it causes gcc to generate a faster switch
  75158. ** statement (since the range of switch targets now starts at zero and
  75159. ** is contiguous) but does not cause any duplicate code to be generated
  75160. ** (as gcc is clever enough to combine the two like cases). Other
  75161. ** compilers might be similar. */
  75162. case 0: case 7:
  75163. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  75164. default:
  75165. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  75166. }
  75167. v = pPKey2->aMem[0].u.i;
  75168. if( v>lhs ){
  75169. res = pPKey2->r1;
  75170. }else if( v<lhs ){
  75171. res = pPKey2->r2;
  75172. }else if( pPKey2->nField>1 ){
  75173. /* The first fields of the two keys are equal. Compare the trailing
  75174. ** fields. */
  75175. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  75176. }else{
  75177. /* The first fields of the two keys are equal and there are no trailing
  75178. ** fields. Return pPKey2->default_rc in this case. */
  75179. res = pPKey2->default_rc;
  75180. pPKey2->eqSeen = 1;
  75181. }
  75182. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  75183. return res;
  75184. }
  75185. /*
  75186. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  75187. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  75188. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  75189. ** at the start of (pKey1/nKey1) fits in a single byte.
  75190. */
  75191. static int vdbeRecordCompareString(
  75192. int nKey1, const void *pKey1, /* Left key */
  75193. UnpackedRecord *pPKey2 /* Right key */
  75194. ){
  75195. const u8 *aKey1 = (const u8*)pKey1;
  75196. int serial_type;
  75197. int res;
  75198. assert( pPKey2->aMem[0].flags & MEM_Str );
  75199. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  75200. getVarint32(&aKey1[1], serial_type);
  75201. if( serial_type<12 ){
  75202. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  75203. }else if( !(serial_type & 0x01) ){
  75204. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  75205. }else{
  75206. int nCmp;
  75207. int nStr;
  75208. int szHdr = aKey1[0];
  75209. nStr = (serial_type-12) / 2;
  75210. if( (szHdr + nStr) > nKey1 ){
  75211. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  75212. return 0; /* Corruption */
  75213. }
  75214. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  75215. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  75216. if( res==0 ){
  75217. res = nStr - pPKey2->aMem[0].n;
  75218. if( res==0 ){
  75219. if( pPKey2->nField>1 ){
  75220. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  75221. }else{
  75222. res = pPKey2->default_rc;
  75223. pPKey2->eqSeen = 1;
  75224. }
  75225. }else if( res>0 ){
  75226. res = pPKey2->r2;
  75227. }else{
  75228. res = pPKey2->r1;
  75229. }
  75230. }else if( res>0 ){
  75231. res = pPKey2->r2;
  75232. }else{
  75233. res = pPKey2->r1;
  75234. }
  75235. }
  75236. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  75237. || CORRUPT_DB
  75238. || pPKey2->pKeyInfo->db->mallocFailed
  75239. );
  75240. return res;
  75241. }
  75242. /*
  75243. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  75244. ** suitable for comparing serialized records to the unpacked record passed
  75245. ** as the only argument.
  75246. */
  75247. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  75248. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  75249. ** that the size-of-header varint that occurs at the start of each record
  75250. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  75251. ** also assumes that it is safe to overread a buffer by at least the
  75252. ** maximum possible legal header size plus 8 bytes. Because there is
  75253. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  75254. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  75255. ** limit the size of the header to 64 bytes in cases where the first field
  75256. ** is an integer.
  75257. **
  75258. ** The easiest way to enforce this limit is to consider only records with
  75259. ** 13 fields or less. If the first field is an integer, the maximum legal
  75260. ** header size is (12*5 + 1 + 1) bytes. */
  75261. if( p->pKeyInfo->nAllField<=13 ){
  75262. int flags = p->aMem[0].flags;
  75263. if( p->pKeyInfo->aSortOrder[0] ){
  75264. p->r1 = 1;
  75265. p->r2 = -1;
  75266. }else{
  75267. p->r1 = -1;
  75268. p->r2 = 1;
  75269. }
  75270. if( (flags & MEM_Int) ){
  75271. return vdbeRecordCompareInt;
  75272. }
  75273. testcase( flags & MEM_Real );
  75274. testcase( flags & MEM_Null );
  75275. testcase( flags & MEM_Blob );
  75276. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  75277. assert( flags & MEM_Str );
  75278. return vdbeRecordCompareString;
  75279. }
  75280. }
  75281. return sqlite3VdbeRecordCompare;
  75282. }
  75283. /*
  75284. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  75285. ** Read the rowid (the last field in the record) and store it in *rowid.
  75286. ** Return SQLITE_OK if everything works, or an error code otherwise.
  75287. **
  75288. ** pCur might be pointing to text obtained from a corrupt database file.
  75289. ** So the content cannot be trusted. Do appropriate checks on the content.
  75290. */
  75291. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  75292. i64 nCellKey = 0;
  75293. int rc;
  75294. u32 szHdr; /* Size of the header */
  75295. u32 typeRowid; /* Serial type of the rowid */
  75296. u32 lenRowid; /* Size of the rowid */
  75297. Mem m, v;
  75298. /* Get the size of the index entry. Only indices entries of less
  75299. ** than 2GiB are support - anything large must be database corruption.
  75300. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  75301. ** this code can safely assume that nCellKey is 32-bits
  75302. */
  75303. assert( sqlite3BtreeCursorIsValid(pCur) );
  75304. nCellKey = sqlite3BtreePayloadSize(pCur);
  75305. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  75306. /* Read in the complete content of the index entry */
  75307. sqlite3VdbeMemInit(&m, db, 0);
  75308. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  75309. if( rc ){
  75310. return rc;
  75311. }
  75312. /* The index entry must begin with a header size */
  75313. (void)getVarint32((u8*)m.z, szHdr);
  75314. testcase( szHdr==3 );
  75315. testcase( szHdr==m.n );
  75316. testcase( szHdr>0x7fffffff );
  75317. assert( m.n>=0 );
  75318. if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
  75319. goto idx_rowid_corruption;
  75320. }
  75321. /* The last field of the index should be an integer - the ROWID.
  75322. ** Verify that the last entry really is an integer. */
  75323. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  75324. testcase( typeRowid==1 );
  75325. testcase( typeRowid==2 );
  75326. testcase( typeRowid==3 );
  75327. testcase( typeRowid==4 );
  75328. testcase( typeRowid==5 );
  75329. testcase( typeRowid==6 );
  75330. testcase( typeRowid==8 );
  75331. testcase( typeRowid==9 );
  75332. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  75333. goto idx_rowid_corruption;
  75334. }
  75335. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  75336. testcase( (u32)m.n==szHdr+lenRowid );
  75337. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  75338. goto idx_rowid_corruption;
  75339. }
  75340. /* Fetch the integer off the end of the index record */
  75341. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  75342. *rowid = v.u.i;
  75343. sqlite3VdbeMemRelease(&m);
  75344. return SQLITE_OK;
  75345. /* Jump here if database corruption is detected after m has been
  75346. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  75347. idx_rowid_corruption:
  75348. testcase( m.szMalloc!=0 );
  75349. sqlite3VdbeMemRelease(&m);
  75350. return SQLITE_CORRUPT_BKPT;
  75351. }
  75352. /*
  75353. ** Compare the key of the index entry that cursor pC is pointing to against
  75354. ** the key string in pUnpacked. Write into *pRes a number
  75355. ** that is negative, zero, or positive if pC is less than, equal to,
  75356. ** or greater than pUnpacked. Return SQLITE_OK on success.
  75357. **
  75358. ** pUnpacked is either created without a rowid or is truncated so that it
  75359. ** omits the rowid at the end. The rowid at the end of the index entry
  75360. ** is ignored as well. Hence, this routine only compares the prefixes
  75361. ** of the keys prior to the final rowid, not the entire key.
  75362. */
  75363. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  75364. sqlite3 *db, /* Database connection */
  75365. VdbeCursor *pC, /* The cursor to compare against */
  75366. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  75367. int *res /* Write the comparison result here */
  75368. ){
  75369. i64 nCellKey = 0;
  75370. int rc;
  75371. BtCursor *pCur;
  75372. Mem m;
  75373. assert( pC->eCurType==CURTYPE_BTREE );
  75374. pCur = pC->uc.pCursor;
  75375. assert( sqlite3BtreeCursorIsValid(pCur) );
  75376. nCellKey = sqlite3BtreePayloadSize(pCur);
  75377. /* nCellKey will always be between 0 and 0xffffffff because of the way
  75378. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  75379. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  75380. *res = 0;
  75381. return SQLITE_CORRUPT_BKPT;
  75382. }
  75383. sqlite3VdbeMemInit(&m, db, 0);
  75384. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  75385. if( rc ){
  75386. return rc;
  75387. }
  75388. *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
  75389. sqlite3VdbeMemRelease(&m);
  75390. return SQLITE_OK;
  75391. }
  75392. /*
  75393. ** This routine sets the value to be returned by subsequent calls to
  75394. ** sqlite3_changes() on the database handle 'db'.
  75395. */
  75396. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  75397. assert( sqlite3_mutex_held(db->mutex) );
  75398. db->nChange = nChange;
  75399. db->nTotalChange += nChange;
  75400. }
  75401. /*
  75402. ** Set a flag in the vdbe to update the change counter when it is finalised
  75403. ** or reset.
  75404. */
  75405. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  75406. v->changeCntOn = 1;
  75407. }
  75408. /*
  75409. ** Mark every prepared statement associated with a database connection
  75410. ** as expired.
  75411. **
  75412. ** An expired statement means that recompilation of the statement is
  75413. ** recommend. Statements expire when things happen that make their
  75414. ** programs obsolete. Removing user-defined functions or collating
  75415. ** sequences, or changing an authorization function are the types of
  75416. ** things that make prepared statements obsolete.
  75417. **
  75418. ** If iCode is 1, then expiration is advisory. The statement should
  75419. ** be reprepared before being restarted, but if it is already running
  75420. ** it is allowed to run to completion.
  75421. **
  75422. ** Internally, this function just sets the Vdbe.expired flag on all
  75423. ** prepared statements. The flag is set to 1 for an immediate expiration
  75424. ** and set to 2 for an advisory expiration.
  75425. */
  75426. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
  75427. Vdbe *p;
  75428. for(p = db->pVdbe; p; p=p->pNext){
  75429. p->expired = iCode+1;
  75430. }
  75431. }
  75432. /*
  75433. ** Return the database associated with the Vdbe.
  75434. */
  75435. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  75436. return v->db;
  75437. }
  75438. /*
  75439. ** Return the SQLITE_PREPARE flags for a Vdbe.
  75440. */
  75441. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
  75442. return v->prepFlags;
  75443. }
  75444. /*
  75445. ** Return a pointer to an sqlite3_value structure containing the value bound
  75446. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  75447. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  75448. ** constants) to the value before returning it.
  75449. **
  75450. ** The returned value must be freed by the caller using sqlite3ValueFree().
  75451. */
  75452. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  75453. assert( iVar>0 );
  75454. if( v ){
  75455. Mem *pMem = &v->aVar[iVar-1];
  75456. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  75457. if( 0==(pMem->flags & MEM_Null) ){
  75458. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  75459. if( pRet ){
  75460. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  75461. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  75462. }
  75463. return pRet;
  75464. }
  75465. }
  75466. return 0;
  75467. }
  75468. /*
  75469. ** Configure SQL variable iVar so that binding a new value to it signals
  75470. ** to sqlite3_reoptimize() that re-preparing the statement may result
  75471. ** in a better query plan.
  75472. */
  75473. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  75474. assert( iVar>0 );
  75475. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  75476. if( iVar>=32 ){
  75477. v->expmask |= 0x80000000;
  75478. }else{
  75479. v->expmask |= ((u32)1 << (iVar-1));
  75480. }
  75481. }
  75482. /*
  75483. ** Cause a function to throw an error if it was call from OP_PureFunc
  75484. ** rather than OP_Function.
  75485. **
  75486. ** OP_PureFunc means that the function must be deterministic, and should
  75487. ** throw an error if it is given inputs that would make it non-deterministic.
  75488. ** This routine is invoked by date/time functions that use non-deterministic
  75489. ** features such as 'now'.
  75490. */
  75491. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
  75492. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  75493. if( pCtx->pVdbe==0 ) return 1;
  75494. #endif
  75495. if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
  75496. sqlite3_result_error(pCtx,
  75497. "non-deterministic function in index expression or CHECK constraint",
  75498. -1);
  75499. return 0;
  75500. }
  75501. return 1;
  75502. }
  75503. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75504. /*
  75505. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  75506. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  75507. ** in memory obtained from sqlite3DbMalloc).
  75508. */
  75509. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  75510. if( pVtab->zErrMsg ){
  75511. sqlite3 *db = p->db;
  75512. sqlite3DbFree(db, p->zErrMsg);
  75513. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  75514. sqlite3_free(pVtab->zErrMsg);
  75515. pVtab->zErrMsg = 0;
  75516. }
  75517. }
  75518. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75519. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  75520. /*
  75521. ** If the second argument is not NULL, release any allocations associated
  75522. ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
  75523. ** structure itself, using sqlite3DbFree().
  75524. **
  75525. ** This function is used to free UnpackedRecord structures allocated by
  75526. ** the vdbeUnpackRecord() function found in vdbeapi.c.
  75527. */
  75528. static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
  75529. if( p ){
  75530. int i;
  75531. for(i=0; i<nField; i++){
  75532. Mem *pMem = &p->aMem[i];
  75533. if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
  75534. }
  75535. sqlite3DbFreeNN(db, p);
  75536. }
  75537. }
  75538. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  75539. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  75540. /*
  75541. ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
  75542. ** then cursor passed as the second argument should point to the row about
  75543. ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
  75544. ** the required value will be read from the row the cursor points to.
  75545. */
  75546. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
  75547. Vdbe *v, /* Vdbe pre-update hook is invoked by */
  75548. VdbeCursor *pCsr, /* Cursor to grab old.* values from */
  75549. int op, /* SQLITE_INSERT, UPDATE or DELETE */
  75550. const char *zDb, /* Database name */
  75551. Table *pTab, /* Modified table */
  75552. i64 iKey1, /* Initial key value */
  75553. int iReg /* Register for new.* record */
  75554. ){
  75555. sqlite3 *db = v->db;
  75556. i64 iKey2;
  75557. PreUpdate preupdate;
  75558. const char *zTbl = pTab->zName;
  75559. static const u8 fakeSortOrder = 0;
  75560. assert( db->pPreUpdate==0 );
  75561. memset(&preupdate, 0, sizeof(PreUpdate));
  75562. if( HasRowid(pTab)==0 ){
  75563. iKey1 = iKey2 = 0;
  75564. preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
  75565. }else{
  75566. if( op==SQLITE_UPDATE ){
  75567. iKey2 = v->aMem[iReg].u.i;
  75568. }else{
  75569. iKey2 = iKey1;
  75570. }
  75571. }
  75572. assert( pCsr->nField==pTab->nCol
  75573. || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
  75574. );
  75575. preupdate.v = v;
  75576. preupdate.pCsr = pCsr;
  75577. preupdate.op = op;
  75578. preupdate.iNewReg = iReg;
  75579. preupdate.keyinfo.db = db;
  75580. preupdate.keyinfo.enc = ENC(db);
  75581. preupdate.keyinfo.nKeyField = pTab->nCol;
  75582. preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
  75583. preupdate.iKey1 = iKey1;
  75584. preupdate.iKey2 = iKey2;
  75585. preupdate.pTab = pTab;
  75586. db->pPreUpdate = &preupdate;
  75587. db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
  75588. db->pPreUpdate = 0;
  75589. sqlite3DbFree(db, preupdate.aRecord);
  75590. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
  75591. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
  75592. if( preupdate.aNew ){
  75593. int i;
  75594. for(i=0; i<pCsr->nField; i++){
  75595. sqlite3VdbeMemRelease(&preupdate.aNew[i]);
  75596. }
  75597. sqlite3DbFreeNN(db, preupdate.aNew);
  75598. }
  75599. }
  75600. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  75601. /************** End of vdbeaux.c *********************************************/
  75602. /************** Begin file vdbeapi.c *****************************************/
  75603. /*
  75604. ** 2004 May 26
  75605. **
  75606. ** The author disclaims copyright to this source code. In place of
  75607. ** a legal notice, here is a blessing:
  75608. **
  75609. ** May you do good and not evil.
  75610. ** May you find forgiveness for yourself and forgive others.
  75611. ** May you share freely, never taking more than you give.
  75612. **
  75613. *************************************************************************
  75614. **
  75615. ** This file contains code use to implement APIs that are part of the
  75616. ** VDBE.
  75617. */
  75618. /* #include "sqliteInt.h" */
  75619. /* #include "vdbeInt.h" */
  75620. #ifndef SQLITE_OMIT_DEPRECATED
  75621. /*
  75622. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  75623. ** to be recompiled. A statement needs to be recompiled whenever the
  75624. ** execution environment changes in a way that would alter the program
  75625. ** that sqlite3_prepare() generates. For example, if new functions or
  75626. ** collating sequences are registered or if an authorizer function is
  75627. ** added or changed.
  75628. */
  75629. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  75630. Vdbe *p = (Vdbe*)pStmt;
  75631. return p==0 || p->expired;
  75632. }
  75633. #endif
  75634. /*
  75635. ** Check on a Vdbe to make sure it has not been finalized. Log
  75636. ** an error and return true if it has been finalized (or is otherwise
  75637. ** invalid). Return false if it is ok.
  75638. */
  75639. static int vdbeSafety(Vdbe *p){
  75640. if( p->db==0 ){
  75641. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  75642. return 1;
  75643. }else{
  75644. return 0;
  75645. }
  75646. }
  75647. static int vdbeSafetyNotNull(Vdbe *p){
  75648. if( p==0 ){
  75649. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  75650. return 1;
  75651. }else{
  75652. return vdbeSafety(p);
  75653. }
  75654. }
  75655. #ifndef SQLITE_OMIT_TRACE
  75656. /*
  75657. ** Invoke the profile callback. This routine is only called if we already
  75658. ** know that the profile callback is defined and needs to be invoked.
  75659. */
  75660. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  75661. sqlite3_int64 iNow;
  75662. sqlite3_int64 iElapse;
  75663. assert( p->startTime>0 );
  75664. assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
  75665. assert( db->init.busy==0 );
  75666. assert( p->zSql!=0 );
  75667. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  75668. iElapse = (iNow - p->startTime)*1000000;
  75669. if( db->xProfile ){
  75670. db->xProfile(db->pProfileArg, p->zSql, iElapse);
  75671. }
  75672. if( db->mTrace & SQLITE_TRACE_PROFILE ){
  75673. db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
  75674. }
  75675. p->startTime = 0;
  75676. }
  75677. /*
  75678. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  75679. ** is needed, and it invokes the callback if it is needed.
  75680. */
  75681. # define checkProfileCallback(DB,P) \
  75682. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  75683. #else
  75684. # define checkProfileCallback(DB,P) /*no-op*/
  75685. #endif
  75686. /*
  75687. ** The following routine destroys a virtual machine that is created by
  75688. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  75689. ** success/failure code that describes the result of executing the virtual
  75690. ** machine.
  75691. **
  75692. ** This routine sets the error code and string returned by
  75693. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  75694. */
  75695. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  75696. int rc;
  75697. if( pStmt==0 ){
  75698. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  75699. ** pointer is a harmless no-op. */
  75700. rc = SQLITE_OK;
  75701. }else{
  75702. Vdbe *v = (Vdbe*)pStmt;
  75703. sqlite3 *db = v->db;
  75704. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  75705. sqlite3_mutex_enter(db->mutex);
  75706. checkProfileCallback(db, v);
  75707. rc = sqlite3VdbeFinalize(v);
  75708. rc = sqlite3ApiExit(db, rc);
  75709. sqlite3LeaveMutexAndCloseZombie(db);
  75710. }
  75711. return rc;
  75712. }
  75713. /*
  75714. ** Terminate the current execution of an SQL statement and reset it
  75715. ** back to its starting state so that it can be reused. A success code from
  75716. ** the prior execution is returned.
  75717. **
  75718. ** This routine sets the error code and string returned by
  75719. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  75720. */
  75721. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  75722. int rc;
  75723. if( pStmt==0 ){
  75724. rc = SQLITE_OK;
  75725. }else{
  75726. Vdbe *v = (Vdbe*)pStmt;
  75727. sqlite3 *db = v->db;
  75728. sqlite3_mutex_enter(db->mutex);
  75729. checkProfileCallback(db, v);
  75730. rc = sqlite3VdbeReset(v);
  75731. sqlite3VdbeRewind(v);
  75732. assert( (rc & (db->errMask))==rc );
  75733. rc = sqlite3ApiExit(db, rc);
  75734. sqlite3_mutex_leave(db->mutex);
  75735. }
  75736. return rc;
  75737. }
  75738. /*
  75739. ** Set all the parameters in the compiled SQL statement to NULL.
  75740. */
  75741. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  75742. int i;
  75743. int rc = SQLITE_OK;
  75744. Vdbe *p = (Vdbe*)pStmt;
  75745. #if SQLITE_THREADSAFE
  75746. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  75747. #endif
  75748. sqlite3_mutex_enter(mutex);
  75749. for(i=0; i<p->nVar; i++){
  75750. sqlite3VdbeMemRelease(&p->aVar[i]);
  75751. p->aVar[i].flags = MEM_Null;
  75752. }
  75753. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  75754. if( p->expmask ){
  75755. p->expired = 1;
  75756. }
  75757. sqlite3_mutex_leave(mutex);
  75758. return rc;
  75759. }
  75760. /**************************** sqlite3_value_ *******************************
  75761. ** The following routines extract information from a Mem or sqlite3_value
  75762. ** structure.
  75763. */
  75764. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  75765. Mem *p = (Mem*)pVal;
  75766. if( p->flags & (MEM_Blob|MEM_Str) ){
  75767. if( ExpandBlob(p)!=SQLITE_OK ){
  75768. assert( p->flags==MEM_Null && p->z==0 );
  75769. return 0;
  75770. }
  75771. p->flags |= MEM_Blob;
  75772. return p->n ? p->z : 0;
  75773. }else{
  75774. return sqlite3_value_text(pVal);
  75775. }
  75776. }
  75777. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  75778. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  75779. }
  75780. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  75781. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  75782. }
  75783. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  75784. return sqlite3VdbeRealValue((Mem*)pVal);
  75785. }
  75786. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  75787. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  75788. }
  75789. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  75790. return sqlite3VdbeIntValue((Mem*)pVal);
  75791. }
  75792. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
  75793. Mem *pMem = (Mem*)pVal;
  75794. return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
  75795. }
  75796. SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
  75797. Mem *p = (Mem*)pVal;
  75798. if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
  75799. (MEM_Null|MEM_Term|MEM_Subtype)
  75800. && zPType!=0
  75801. && p->eSubtype=='p'
  75802. && strcmp(p->u.zPType, zPType)==0
  75803. ){
  75804. return (void*)p->z;
  75805. }else{
  75806. return 0;
  75807. }
  75808. }
  75809. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  75810. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  75811. }
  75812. #ifndef SQLITE_OMIT_UTF16
  75813. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  75814. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  75815. }
  75816. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  75817. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  75818. }
  75819. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  75820. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  75821. }
  75822. #endif /* SQLITE_OMIT_UTF16 */
  75823. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  75824. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  75825. ** point number string BLOB NULL
  75826. */
  75827. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  75828. static const u8 aType[] = {
  75829. SQLITE_BLOB, /* 0x00 */
  75830. SQLITE_NULL, /* 0x01 */
  75831. SQLITE_TEXT, /* 0x02 */
  75832. SQLITE_NULL, /* 0x03 */
  75833. SQLITE_INTEGER, /* 0x04 */
  75834. SQLITE_NULL, /* 0x05 */
  75835. SQLITE_INTEGER, /* 0x06 */
  75836. SQLITE_NULL, /* 0x07 */
  75837. SQLITE_FLOAT, /* 0x08 */
  75838. SQLITE_NULL, /* 0x09 */
  75839. SQLITE_FLOAT, /* 0x0a */
  75840. SQLITE_NULL, /* 0x0b */
  75841. SQLITE_INTEGER, /* 0x0c */
  75842. SQLITE_NULL, /* 0x0d */
  75843. SQLITE_INTEGER, /* 0x0e */
  75844. SQLITE_NULL, /* 0x0f */
  75845. SQLITE_BLOB, /* 0x10 */
  75846. SQLITE_NULL, /* 0x11 */
  75847. SQLITE_TEXT, /* 0x12 */
  75848. SQLITE_NULL, /* 0x13 */
  75849. SQLITE_INTEGER, /* 0x14 */
  75850. SQLITE_NULL, /* 0x15 */
  75851. SQLITE_INTEGER, /* 0x16 */
  75852. SQLITE_NULL, /* 0x17 */
  75853. SQLITE_FLOAT, /* 0x18 */
  75854. SQLITE_NULL, /* 0x19 */
  75855. SQLITE_FLOAT, /* 0x1a */
  75856. SQLITE_NULL, /* 0x1b */
  75857. SQLITE_INTEGER, /* 0x1c */
  75858. SQLITE_NULL, /* 0x1d */
  75859. SQLITE_INTEGER, /* 0x1e */
  75860. SQLITE_NULL, /* 0x1f */
  75861. };
  75862. return aType[pVal->flags&MEM_AffMask];
  75863. }
  75864. /* Return true if a parameter to xUpdate represents an unchanged column */
  75865. SQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){
  75866. return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
  75867. }
  75868. /* Make a copy of an sqlite3_value object
  75869. */
  75870. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
  75871. sqlite3_value *pNew;
  75872. if( pOrig==0 ) return 0;
  75873. pNew = sqlite3_malloc( sizeof(*pNew) );
  75874. if( pNew==0 ) return 0;
  75875. memset(pNew, 0, sizeof(*pNew));
  75876. memcpy(pNew, pOrig, MEMCELLSIZE);
  75877. pNew->flags &= ~MEM_Dyn;
  75878. pNew->db = 0;
  75879. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  75880. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  75881. pNew->flags |= MEM_Ephem;
  75882. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  75883. sqlite3ValueFree(pNew);
  75884. pNew = 0;
  75885. }
  75886. }
  75887. return pNew;
  75888. }
  75889. /* Destroy an sqlite3_value object previously obtained from
  75890. ** sqlite3_value_dup().
  75891. */
  75892. SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
  75893. sqlite3ValueFree(pOld);
  75894. }
  75895. /**************************** sqlite3_result_ *******************************
  75896. ** The following routines are used by user-defined functions to specify
  75897. ** the function result.
  75898. **
  75899. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  75900. ** result as a string or blob but if the string or blob is too large, it
  75901. ** then sets the error code to SQLITE_TOOBIG
  75902. **
  75903. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  75904. ** on value P is not going to be used and need to be destroyed.
  75905. */
  75906. static void setResultStrOrError(
  75907. sqlite3_context *pCtx, /* Function context */
  75908. const char *z, /* String pointer */
  75909. int n, /* Bytes in string, or negative */
  75910. u8 enc, /* Encoding of z. 0 for BLOBs */
  75911. void (*xDel)(void*) /* Destructor function */
  75912. ){
  75913. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  75914. sqlite3_result_error_toobig(pCtx);
  75915. }
  75916. }
  75917. static int invokeValueDestructor(
  75918. const void *p, /* Value to destroy */
  75919. void (*xDel)(void*), /* The destructor */
  75920. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  75921. ){
  75922. assert( xDel!=SQLITE_DYNAMIC );
  75923. if( xDel==0 ){
  75924. /* noop */
  75925. }else if( xDel==SQLITE_TRANSIENT ){
  75926. /* noop */
  75927. }else{
  75928. xDel((void*)p);
  75929. }
  75930. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  75931. return SQLITE_TOOBIG;
  75932. }
  75933. SQLITE_API void sqlite3_result_blob(
  75934. sqlite3_context *pCtx,
  75935. const void *z,
  75936. int n,
  75937. void (*xDel)(void *)
  75938. ){
  75939. assert( n>=0 );
  75940. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75941. setResultStrOrError(pCtx, z, n, 0, xDel);
  75942. }
  75943. SQLITE_API void sqlite3_result_blob64(
  75944. sqlite3_context *pCtx,
  75945. const void *z,
  75946. sqlite3_uint64 n,
  75947. void (*xDel)(void *)
  75948. ){
  75949. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75950. assert( xDel!=SQLITE_DYNAMIC );
  75951. if( n>0x7fffffff ){
  75952. (void)invokeValueDestructor(z, xDel, pCtx);
  75953. }else{
  75954. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  75955. }
  75956. }
  75957. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  75958. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75959. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  75960. }
  75961. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  75962. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75963. pCtx->isError = SQLITE_ERROR;
  75964. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  75965. }
  75966. #ifndef SQLITE_OMIT_UTF16
  75967. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  75968. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75969. pCtx->isError = SQLITE_ERROR;
  75970. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  75971. }
  75972. #endif
  75973. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  75974. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75975. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  75976. }
  75977. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  75978. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75979. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  75980. }
  75981. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  75982. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75983. sqlite3VdbeMemSetNull(pCtx->pOut);
  75984. }
  75985. SQLITE_API void sqlite3_result_pointer(
  75986. sqlite3_context *pCtx,
  75987. void *pPtr,
  75988. const char *zPType,
  75989. void (*xDestructor)(void*)
  75990. ){
  75991. Mem *pOut = pCtx->pOut;
  75992. assert( sqlite3_mutex_held(pOut->db->mutex) );
  75993. sqlite3VdbeMemRelease(pOut);
  75994. pOut->flags = MEM_Null;
  75995. sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
  75996. }
  75997. SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  75998. Mem *pOut = pCtx->pOut;
  75999. assert( sqlite3_mutex_held(pOut->db->mutex) );
  76000. pOut->eSubtype = eSubtype & 0xff;
  76001. pOut->flags |= MEM_Subtype;
  76002. }
  76003. SQLITE_API void sqlite3_result_text(
  76004. sqlite3_context *pCtx,
  76005. const char *z,
  76006. int n,
  76007. void (*xDel)(void *)
  76008. ){
  76009. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76010. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  76011. }
  76012. SQLITE_API void sqlite3_result_text64(
  76013. sqlite3_context *pCtx,
  76014. const char *z,
  76015. sqlite3_uint64 n,
  76016. void (*xDel)(void *),
  76017. unsigned char enc
  76018. ){
  76019. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76020. assert( xDel!=SQLITE_DYNAMIC );
  76021. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  76022. if( n>0x7fffffff ){
  76023. (void)invokeValueDestructor(z, xDel, pCtx);
  76024. }else{
  76025. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  76026. }
  76027. }
  76028. #ifndef SQLITE_OMIT_UTF16
  76029. SQLITE_API void sqlite3_result_text16(
  76030. sqlite3_context *pCtx,
  76031. const void *z,
  76032. int n,
  76033. void (*xDel)(void *)
  76034. ){
  76035. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76036. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  76037. }
  76038. SQLITE_API void sqlite3_result_text16be(
  76039. sqlite3_context *pCtx,
  76040. const void *z,
  76041. int n,
  76042. void (*xDel)(void *)
  76043. ){
  76044. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76045. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  76046. }
  76047. SQLITE_API void sqlite3_result_text16le(
  76048. sqlite3_context *pCtx,
  76049. const void *z,
  76050. int n,
  76051. void (*xDel)(void *)
  76052. ){
  76053. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76054. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  76055. }
  76056. #endif /* SQLITE_OMIT_UTF16 */
  76057. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  76058. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76059. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  76060. }
  76061. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  76062. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76063. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  76064. }
  76065. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  76066. Mem *pOut = pCtx->pOut;
  76067. assert( sqlite3_mutex_held(pOut->db->mutex) );
  76068. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  76069. return SQLITE_TOOBIG;
  76070. }
  76071. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  76072. return SQLITE_OK;
  76073. }
  76074. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  76075. pCtx->isError = errCode ? errCode : -1;
  76076. #ifdef SQLITE_DEBUG
  76077. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  76078. #endif
  76079. if( pCtx->pOut->flags & MEM_Null ){
  76080. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  76081. SQLITE_UTF8, SQLITE_STATIC);
  76082. }
  76083. }
  76084. /* Force an SQLITE_TOOBIG error. */
  76085. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  76086. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76087. pCtx->isError = SQLITE_TOOBIG;
  76088. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  76089. SQLITE_UTF8, SQLITE_STATIC);
  76090. }
  76091. /* An SQLITE_NOMEM error. */
  76092. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  76093. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76094. sqlite3VdbeMemSetNull(pCtx->pOut);
  76095. pCtx->isError = SQLITE_NOMEM_BKPT;
  76096. sqlite3OomFault(pCtx->pOut->db);
  76097. }
  76098. /*
  76099. ** This function is called after a transaction has been committed. It
  76100. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  76101. */
  76102. static int doWalCallbacks(sqlite3 *db){
  76103. int rc = SQLITE_OK;
  76104. #ifndef SQLITE_OMIT_WAL
  76105. int i;
  76106. for(i=0; i<db->nDb; i++){
  76107. Btree *pBt = db->aDb[i].pBt;
  76108. if( pBt ){
  76109. int nEntry;
  76110. sqlite3BtreeEnter(pBt);
  76111. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  76112. sqlite3BtreeLeave(pBt);
  76113. if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
  76114. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
  76115. }
  76116. }
  76117. }
  76118. #endif
  76119. return rc;
  76120. }
  76121. /*
  76122. ** Execute the statement pStmt, either until a row of data is ready, the
  76123. ** statement is completely executed or an error occurs.
  76124. **
  76125. ** This routine implements the bulk of the logic behind the sqlite_step()
  76126. ** API. The only thing omitted is the automatic recompile if a
  76127. ** schema change has occurred. That detail is handled by the
  76128. ** outer sqlite3_step() wrapper procedure.
  76129. */
  76130. static int sqlite3Step(Vdbe *p){
  76131. sqlite3 *db;
  76132. int rc;
  76133. assert(p);
  76134. if( p->magic!=VDBE_MAGIC_RUN ){
  76135. /* We used to require that sqlite3_reset() be called before retrying
  76136. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  76137. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  76138. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  76139. ** This "automatic-reset" change is not technically an incompatibility,
  76140. ** since any application that receives an SQLITE_MISUSE is broken by
  76141. ** definition.
  76142. **
  76143. ** Nevertheless, some published applications that were originally written
  76144. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  76145. ** returns, and those were broken by the automatic-reset change. As a
  76146. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  76147. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  76148. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  76149. ** or SQLITE_BUSY error.
  76150. */
  76151. #ifdef SQLITE_OMIT_AUTORESET
  76152. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  76153. sqlite3_reset((sqlite3_stmt*)p);
  76154. }else{
  76155. return SQLITE_MISUSE_BKPT;
  76156. }
  76157. #else
  76158. sqlite3_reset((sqlite3_stmt*)p);
  76159. #endif
  76160. }
  76161. /* Check that malloc() has not failed. If it has, return early. */
  76162. db = p->db;
  76163. if( db->mallocFailed ){
  76164. p->rc = SQLITE_NOMEM;
  76165. return SQLITE_NOMEM_BKPT;
  76166. }
  76167. if( p->pc<=0 && p->expired ){
  76168. p->rc = SQLITE_SCHEMA;
  76169. rc = SQLITE_ERROR;
  76170. goto end_of_step;
  76171. }
  76172. if( p->pc<0 ){
  76173. /* If there are no other statements currently running, then
  76174. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  76175. ** from interrupting a statement that has not yet started.
  76176. */
  76177. if( db->nVdbeActive==0 ){
  76178. db->u1.isInterrupted = 0;
  76179. }
  76180. assert( db->nVdbeWrite>0 || db->autoCommit==0
  76181. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  76182. );
  76183. #ifndef SQLITE_OMIT_TRACE
  76184. if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
  76185. && !db->init.busy && p->zSql ){
  76186. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  76187. }else{
  76188. assert( p->startTime==0 );
  76189. }
  76190. #endif
  76191. db->nVdbeActive++;
  76192. if( p->readOnly==0 ) db->nVdbeWrite++;
  76193. if( p->bIsReader ) db->nVdbeRead++;
  76194. p->pc = 0;
  76195. }
  76196. #ifdef SQLITE_DEBUG
  76197. p->rcApp = SQLITE_OK;
  76198. #endif
  76199. #ifndef SQLITE_OMIT_EXPLAIN
  76200. if( p->explain ){
  76201. rc = sqlite3VdbeList(p);
  76202. }else
  76203. #endif /* SQLITE_OMIT_EXPLAIN */
  76204. {
  76205. db->nVdbeExec++;
  76206. rc = sqlite3VdbeExec(p);
  76207. db->nVdbeExec--;
  76208. }
  76209. #ifndef SQLITE_OMIT_TRACE
  76210. /* If the statement completed successfully, invoke the profile callback */
  76211. if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
  76212. #endif
  76213. if( rc==SQLITE_DONE && db->autoCommit ){
  76214. assert( p->rc==SQLITE_OK );
  76215. p->rc = doWalCallbacks(db);
  76216. if( p->rc!=SQLITE_OK ){
  76217. rc = SQLITE_ERROR;
  76218. }
  76219. }
  76220. db->errCode = rc;
  76221. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  76222. p->rc = SQLITE_NOMEM_BKPT;
  76223. }
  76224. end_of_step:
  76225. /* At this point local variable rc holds the value that should be
  76226. ** returned if this statement was compiled using the legacy
  76227. ** sqlite3_prepare() interface. According to the docs, this can only
  76228. ** be one of the values in the first assert() below. Variable p->rc
  76229. ** contains the value that would be returned if sqlite3_finalize()
  76230. ** were called on statement p.
  76231. */
  76232. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  76233. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  76234. );
  76235. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  76236. if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
  76237. && rc!=SQLITE_ROW
  76238. && rc!=SQLITE_DONE
  76239. ){
  76240. /* If this statement was prepared using saved SQL and an
  76241. ** error has occurred, then return the error code in p->rc to the
  76242. ** caller. Set the error code in the database handle to the same value.
  76243. */
  76244. rc = sqlite3VdbeTransferError(p);
  76245. }
  76246. return (rc&db->errMask);
  76247. }
  76248. /*
  76249. ** This is the top-level implementation of sqlite3_step(). Call
  76250. ** sqlite3Step() to do most of the work. If a schema error occurs,
  76251. ** call sqlite3Reprepare() and try again.
  76252. */
  76253. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  76254. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  76255. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  76256. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  76257. sqlite3 *db; /* The database connection */
  76258. if( vdbeSafetyNotNull(v) ){
  76259. return SQLITE_MISUSE_BKPT;
  76260. }
  76261. db = v->db;
  76262. sqlite3_mutex_enter(db->mutex);
  76263. v->doingRerun = 0;
  76264. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  76265. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  76266. int savedPc = v->pc;
  76267. rc = sqlite3Reprepare(v);
  76268. if( rc!=SQLITE_OK ){
  76269. /* This case occurs after failing to recompile an sql statement.
  76270. ** The error message from the SQL compiler has already been loaded
  76271. ** into the database handle. This block copies the error message
  76272. ** from the database handle into the statement and sets the statement
  76273. ** program counter to 0 to ensure that when the statement is
  76274. ** finalized or reset the parser error message is available via
  76275. ** sqlite3_errmsg() and sqlite3_errcode().
  76276. */
  76277. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  76278. sqlite3DbFree(db, v->zErrMsg);
  76279. if( !db->mallocFailed ){
  76280. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  76281. v->rc = rc = sqlite3ApiExit(db, rc);
  76282. } else {
  76283. v->zErrMsg = 0;
  76284. v->rc = rc = SQLITE_NOMEM_BKPT;
  76285. }
  76286. break;
  76287. }
  76288. sqlite3_reset(pStmt);
  76289. if( savedPc>=0 ) v->doingRerun = 1;
  76290. assert( v->expired==0 );
  76291. }
  76292. sqlite3_mutex_leave(db->mutex);
  76293. return rc;
  76294. }
  76295. /*
  76296. ** Extract the user data from a sqlite3_context structure and return a
  76297. ** pointer to it.
  76298. */
  76299. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  76300. assert( p && p->pFunc );
  76301. return p->pFunc->pUserData;
  76302. }
  76303. /*
  76304. ** Extract the user data from a sqlite3_context structure and return a
  76305. ** pointer to it.
  76306. **
  76307. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  76308. ** returns a copy of the pointer to the database connection (the 1st
  76309. ** parameter) of the sqlite3_create_function() and
  76310. ** sqlite3_create_function16() routines that originally registered the
  76311. ** application defined function.
  76312. */
  76313. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  76314. assert( p && p->pOut );
  76315. return p->pOut->db;
  76316. }
  76317. /*
  76318. ** If this routine is invoked from within an xColumn method of a virtual
  76319. ** table, then it returns true if and only if the the call is during an
  76320. ** UPDATE operation and the value of the column will not be modified
  76321. ** by the UPDATE.
  76322. **
  76323. ** If this routine is called from any context other than within the
  76324. ** xColumn method of a virtual table, then the return value is meaningless
  76325. ** and arbitrary.
  76326. **
  76327. ** Virtual table implements might use this routine to optimize their
  76328. ** performance by substituting a NULL result, or some other light-weight
  76329. ** value, as a signal to the xUpdate routine that the column is unchanged.
  76330. */
  76331. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
  76332. assert( p );
  76333. return sqlite3_value_nochange(p->pOut);
  76334. }
  76335. /*
  76336. ** Return the current time for a statement. If the current time
  76337. ** is requested more than once within the same run of a single prepared
  76338. ** statement, the exact same time is returned for each invocation regardless
  76339. ** of the amount of time that elapses between invocations. In other words,
  76340. ** the time returned is always the time of the first call.
  76341. */
  76342. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  76343. int rc;
  76344. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  76345. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  76346. assert( p->pVdbe!=0 );
  76347. #else
  76348. sqlite3_int64 iTime = 0;
  76349. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  76350. #endif
  76351. if( *piTime==0 ){
  76352. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  76353. if( rc ) *piTime = 0;
  76354. }
  76355. return *piTime;
  76356. }
  76357. /*
  76358. ** Create a new aggregate context for p and return a pointer to
  76359. ** its pMem->z element.
  76360. */
  76361. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  76362. Mem *pMem = p->pMem;
  76363. assert( (pMem->flags & MEM_Agg)==0 );
  76364. if( nByte<=0 ){
  76365. sqlite3VdbeMemSetNull(pMem);
  76366. pMem->z = 0;
  76367. }else{
  76368. sqlite3VdbeMemClearAndResize(pMem, nByte);
  76369. pMem->flags = MEM_Agg;
  76370. pMem->u.pDef = p->pFunc;
  76371. if( pMem->z ){
  76372. memset(pMem->z, 0, nByte);
  76373. }
  76374. }
  76375. return (void*)pMem->z;
  76376. }
  76377. /*
  76378. ** Allocate or return the aggregate context for a user function. A new
  76379. ** context is allocated on the first call. Subsequent calls return the
  76380. ** same context that was returned on prior calls.
  76381. */
  76382. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  76383. assert( p && p->pFunc && p->pFunc->xFinalize );
  76384. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  76385. testcase( nByte<0 );
  76386. if( (p->pMem->flags & MEM_Agg)==0 ){
  76387. return createAggContext(p, nByte);
  76388. }else{
  76389. return (void*)p->pMem->z;
  76390. }
  76391. }
  76392. /*
  76393. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  76394. ** the user-function defined by pCtx.
  76395. **
  76396. ** The left-most argument is 0.
  76397. **
  76398. ** Undocumented behavior: If iArg is negative then access a cache of
  76399. ** auxiliary data pointers that is available to all functions within a
  76400. ** single prepared statement. The iArg values must match.
  76401. */
  76402. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  76403. AuxData *pAuxData;
  76404. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76405. #if SQLITE_ENABLE_STAT3_OR_STAT4
  76406. if( pCtx->pVdbe==0 ) return 0;
  76407. #else
  76408. assert( pCtx->pVdbe!=0 );
  76409. #endif
  76410. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  76411. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  76412. return pAuxData->pAux;
  76413. }
  76414. }
  76415. return 0;
  76416. }
  76417. /*
  76418. ** Set the auxiliary data pointer and delete function, for the iArg'th
  76419. ** argument to the user-function defined by pCtx. Any previous value is
  76420. ** deleted by calling the delete function specified when it was set.
  76421. **
  76422. ** The left-most argument is 0.
  76423. **
  76424. ** Undocumented behavior: If iArg is negative then make the data available
  76425. ** to all functions within the current prepared statement using iArg as an
  76426. ** access code.
  76427. */
  76428. SQLITE_API void sqlite3_set_auxdata(
  76429. sqlite3_context *pCtx,
  76430. int iArg,
  76431. void *pAux,
  76432. void (*xDelete)(void*)
  76433. ){
  76434. AuxData *pAuxData;
  76435. Vdbe *pVdbe = pCtx->pVdbe;
  76436. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76437. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76438. if( pVdbe==0 ) goto failed;
  76439. #else
  76440. assert( pVdbe!=0 );
  76441. #endif
  76442. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  76443. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  76444. break;
  76445. }
  76446. }
  76447. if( pAuxData==0 ){
  76448. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  76449. if( !pAuxData ) goto failed;
  76450. pAuxData->iAuxOp = pCtx->iOp;
  76451. pAuxData->iAuxArg = iArg;
  76452. pAuxData->pNextAux = pVdbe->pAuxData;
  76453. pVdbe->pAuxData = pAuxData;
  76454. if( pCtx->isError==0 ) pCtx->isError = -1;
  76455. }else if( pAuxData->xDeleteAux ){
  76456. pAuxData->xDeleteAux(pAuxData->pAux);
  76457. }
  76458. pAuxData->pAux = pAux;
  76459. pAuxData->xDeleteAux = xDelete;
  76460. return;
  76461. failed:
  76462. if( xDelete ){
  76463. xDelete(pAux);
  76464. }
  76465. }
  76466. #ifndef SQLITE_OMIT_DEPRECATED
  76467. /*
  76468. ** Return the number of times the Step function of an aggregate has been
  76469. ** called.
  76470. **
  76471. ** This function is deprecated. Do not use it for new code. It is
  76472. ** provide only to avoid breaking legacy code. New aggregate function
  76473. ** implementations should keep their own counts within their aggregate
  76474. ** context.
  76475. */
  76476. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  76477. assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
  76478. return p->pMem->n;
  76479. }
  76480. #endif
  76481. /*
  76482. ** Return the number of columns in the result set for the statement pStmt.
  76483. */
  76484. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  76485. Vdbe *pVm = (Vdbe *)pStmt;
  76486. return pVm ? pVm->nResColumn : 0;
  76487. }
  76488. /*
  76489. ** Return the number of values available from the current row of the
  76490. ** currently executing statement pStmt.
  76491. */
  76492. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  76493. Vdbe *pVm = (Vdbe *)pStmt;
  76494. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  76495. return pVm->nResColumn;
  76496. }
  76497. /*
  76498. ** Return a pointer to static memory containing an SQL NULL value.
  76499. */
  76500. static const Mem *columnNullValue(void){
  76501. /* Even though the Mem structure contains an element
  76502. ** of type i64, on certain architectures (x86) with certain compiler
  76503. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  76504. ** instead of an 8-byte one. This all works fine, except that when
  76505. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  76506. ** that a Mem structure is located on an 8-byte boundary. To prevent
  76507. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  76508. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  76509. ** __attribute__((aligned(8))) macro. */
  76510. static const Mem nullMem
  76511. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  76512. __attribute__((aligned(8)))
  76513. #endif
  76514. = {
  76515. /* .u = */ {0},
  76516. /* .flags = */ (u16)MEM_Null,
  76517. /* .enc = */ (u8)0,
  76518. /* .eSubtype = */ (u8)0,
  76519. /* .n = */ (int)0,
  76520. /* .z = */ (char*)0,
  76521. /* .zMalloc = */ (char*)0,
  76522. /* .szMalloc = */ (int)0,
  76523. /* .uTemp = */ (u32)0,
  76524. /* .db = */ (sqlite3*)0,
  76525. /* .xDel = */ (void(*)(void*))0,
  76526. #ifdef SQLITE_DEBUG
  76527. /* .pScopyFrom = */ (Mem*)0,
  76528. /* .mScopyFlags= */ 0,
  76529. #endif
  76530. };
  76531. return &nullMem;
  76532. }
  76533. /*
  76534. ** Check to see if column iCol of the given statement is valid. If
  76535. ** it is, return a pointer to the Mem for the value of that column.
  76536. ** If iCol is not valid, return a pointer to a Mem which has a value
  76537. ** of NULL.
  76538. */
  76539. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  76540. Vdbe *pVm;
  76541. Mem *pOut;
  76542. pVm = (Vdbe *)pStmt;
  76543. if( pVm==0 ) return (Mem*)columnNullValue();
  76544. assert( pVm->db );
  76545. sqlite3_mutex_enter(pVm->db->mutex);
  76546. if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  76547. pOut = &pVm->pResultSet[i];
  76548. }else{
  76549. sqlite3Error(pVm->db, SQLITE_RANGE);
  76550. pOut = (Mem*)columnNullValue();
  76551. }
  76552. return pOut;
  76553. }
  76554. /*
  76555. ** This function is called after invoking an sqlite3_value_XXX function on a
  76556. ** column value (i.e. a value returned by evaluating an SQL expression in the
  76557. ** select list of a SELECT statement) that may cause a malloc() failure. If
  76558. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  76559. ** code of statement pStmt set to SQLITE_NOMEM.
  76560. **
  76561. ** Specifically, this is called from within:
  76562. **
  76563. ** sqlite3_column_int()
  76564. ** sqlite3_column_int64()
  76565. ** sqlite3_column_text()
  76566. ** sqlite3_column_text16()
  76567. ** sqlite3_column_real()
  76568. ** sqlite3_column_bytes()
  76569. ** sqlite3_column_bytes16()
  76570. ** sqiite3_column_blob()
  76571. */
  76572. static void columnMallocFailure(sqlite3_stmt *pStmt)
  76573. {
  76574. /* If malloc() failed during an encoding conversion within an
  76575. ** sqlite3_column_XXX API, then set the return code of the statement to
  76576. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  76577. ** and _finalize() will return NOMEM.
  76578. */
  76579. Vdbe *p = (Vdbe *)pStmt;
  76580. if( p ){
  76581. assert( p->db!=0 );
  76582. assert( sqlite3_mutex_held(p->db->mutex) );
  76583. p->rc = sqlite3ApiExit(p->db, p->rc);
  76584. sqlite3_mutex_leave(p->db->mutex);
  76585. }
  76586. }
  76587. /**************************** sqlite3_column_ *******************************
  76588. ** The following routines are used to access elements of the current row
  76589. ** in the result set.
  76590. */
  76591. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  76592. const void *val;
  76593. val = sqlite3_value_blob( columnMem(pStmt,i) );
  76594. /* Even though there is no encoding conversion, value_blob() might
  76595. ** need to call malloc() to expand the result of a zeroblob()
  76596. ** expression.
  76597. */
  76598. columnMallocFailure(pStmt);
  76599. return val;
  76600. }
  76601. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  76602. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  76603. columnMallocFailure(pStmt);
  76604. return val;
  76605. }
  76606. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  76607. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  76608. columnMallocFailure(pStmt);
  76609. return val;
  76610. }
  76611. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  76612. double val = sqlite3_value_double( columnMem(pStmt,i) );
  76613. columnMallocFailure(pStmt);
  76614. return val;
  76615. }
  76616. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  76617. int val = sqlite3_value_int( columnMem(pStmt,i) );
  76618. columnMallocFailure(pStmt);
  76619. return val;
  76620. }
  76621. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  76622. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  76623. columnMallocFailure(pStmt);
  76624. return val;
  76625. }
  76626. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  76627. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  76628. columnMallocFailure(pStmt);
  76629. return val;
  76630. }
  76631. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  76632. Mem *pOut = columnMem(pStmt, i);
  76633. if( pOut->flags&MEM_Static ){
  76634. pOut->flags &= ~MEM_Static;
  76635. pOut->flags |= MEM_Ephem;
  76636. }
  76637. columnMallocFailure(pStmt);
  76638. return (sqlite3_value *)pOut;
  76639. }
  76640. #ifndef SQLITE_OMIT_UTF16
  76641. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  76642. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  76643. columnMallocFailure(pStmt);
  76644. return val;
  76645. }
  76646. #endif /* SQLITE_OMIT_UTF16 */
  76647. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  76648. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  76649. columnMallocFailure(pStmt);
  76650. return iType;
  76651. }
  76652. /*
  76653. ** Convert the N-th element of pStmt->pColName[] into a string using
  76654. ** xFunc() then return that string. If N is out of range, return 0.
  76655. **
  76656. ** There are up to 5 names for each column. useType determines which
  76657. ** name is returned. Here are the names:
  76658. **
  76659. ** 0 The column name as it should be displayed for output
  76660. ** 1 The datatype name for the column
  76661. ** 2 The name of the database that the column derives from
  76662. ** 3 The name of the table that the column derives from
  76663. ** 4 The name of the table column that the result column derives from
  76664. **
  76665. ** If the result is not a simple column reference (if it is an expression
  76666. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  76667. */
  76668. static const void *columnName(
  76669. sqlite3_stmt *pStmt,
  76670. int N,
  76671. const void *(*xFunc)(Mem*),
  76672. int useType
  76673. ){
  76674. const void *ret;
  76675. Vdbe *p;
  76676. int n;
  76677. sqlite3 *db;
  76678. #ifdef SQLITE_ENABLE_API_ARMOR
  76679. if( pStmt==0 ){
  76680. (void)SQLITE_MISUSE_BKPT;
  76681. return 0;
  76682. }
  76683. #endif
  76684. ret = 0;
  76685. p = (Vdbe *)pStmt;
  76686. db = p->db;
  76687. assert( db!=0 );
  76688. n = sqlite3_column_count(pStmt);
  76689. if( N<n && N>=0 ){
  76690. N += useType*n;
  76691. sqlite3_mutex_enter(db->mutex);
  76692. assert( db->mallocFailed==0 );
  76693. ret = xFunc(&p->aColName[N]);
  76694. /* A malloc may have failed inside of the xFunc() call. If this
  76695. ** is the case, clear the mallocFailed flag and return NULL.
  76696. */
  76697. if( db->mallocFailed ){
  76698. sqlite3OomClear(db);
  76699. ret = 0;
  76700. }
  76701. sqlite3_mutex_leave(db->mutex);
  76702. }
  76703. return ret;
  76704. }
  76705. /*
  76706. ** Return the name of the Nth column of the result set returned by SQL
  76707. ** statement pStmt.
  76708. */
  76709. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  76710. return columnName(
  76711. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  76712. }
  76713. #ifndef SQLITE_OMIT_UTF16
  76714. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  76715. return columnName(
  76716. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  76717. }
  76718. #endif
  76719. /*
  76720. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  76721. ** not define OMIT_DECLTYPE.
  76722. */
  76723. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  76724. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  76725. and SQLITE_ENABLE_COLUMN_METADATA"
  76726. #endif
  76727. #ifndef SQLITE_OMIT_DECLTYPE
  76728. /*
  76729. ** Return the column declaration type (if applicable) of the 'i'th column
  76730. ** of the result set of SQL statement pStmt.
  76731. */
  76732. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  76733. return columnName(
  76734. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  76735. }
  76736. #ifndef SQLITE_OMIT_UTF16
  76737. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  76738. return columnName(
  76739. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  76740. }
  76741. #endif /* SQLITE_OMIT_UTF16 */
  76742. #endif /* SQLITE_OMIT_DECLTYPE */
  76743. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  76744. /*
  76745. ** Return the name of the database from which a result column derives.
  76746. ** NULL is returned if the result column is an expression or constant or
  76747. ** anything else which is not an unambiguous reference to a database column.
  76748. */
  76749. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  76750. return columnName(
  76751. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  76752. }
  76753. #ifndef SQLITE_OMIT_UTF16
  76754. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  76755. return columnName(
  76756. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  76757. }
  76758. #endif /* SQLITE_OMIT_UTF16 */
  76759. /*
  76760. ** Return the name of the table from which a result column derives.
  76761. ** NULL is returned if the result column is an expression or constant or
  76762. ** anything else which is not an unambiguous reference to a database column.
  76763. */
  76764. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  76765. return columnName(
  76766. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  76767. }
  76768. #ifndef SQLITE_OMIT_UTF16
  76769. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  76770. return columnName(
  76771. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  76772. }
  76773. #endif /* SQLITE_OMIT_UTF16 */
  76774. /*
  76775. ** Return the name of the table column from which a result column derives.
  76776. ** NULL is returned if the result column is an expression or constant or
  76777. ** anything else which is not an unambiguous reference to a database column.
  76778. */
  76779. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  76780. return columnName(
  76781. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  76782. }
  76783. #ifndef SQLITE_OMIT_UTF16
  76784. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  76785. return columnName(
  76786. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  76787. }
  76788. #endif /* SQLITE_OMIT_UTF16 */
  76789. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  76790. /******************************* sqlite3_bind_ ***************************
  76791. **
  76792. ** Routines used to attach values to wildcards in a compiled SQL statement.
  76793. */
  76794. /*
  76795. ** Unbind the value bound to variable i in virtual machine p. This is the
  76796. ** the same as binding a NULL value to the column. If the "i" parameter is
  76797. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  76798. **
  76799. ** A successful evaluation of this routine acquires the mutex on p.
  76800. ** the mutex is released if any kind of error occurs.
  76801. **
  76802. ** The error code stored in database p->db is overwritten with the return
  76803. ** value in any case.
  76804. */
  76805. static int vdbeUnbind(Vdbe *p, int i){
  76806. Mem *pVar;
  76807. if( vdbeSafetyNotNull(p) ){
  76808. return SQLITE_MISUSE_BKPT;
  76809. }
  76810. sqlite3_mutex_enter(p->db->mutex);
  76811. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  76812. sqlite3Error(p->db, SQLITE_MISUSE);
  76813. sqlite3_mutex_leave(p->db->mutex);
  76814. sqlite3_log(SQLITE_MISUSE,
  76815. "bind on a busy prepared statement: [%s]", p->zSql);
  76816. return SQLITE_MISUSE_BKPT;
  76817. }
  76818. if( i<1 || i>p->nVar ){
  76819. sqlite3Error(p->db, SQLITE_RANGE);
  76820. sqlite3_mutex_leave(p->db->mutex);
  76821. return SQLITE_RANGE;
  76822. }
  76823. i--;
  76824. pVar = &p->aVar[i];
  76825. sqlite3VdbeMemRelease(pVar);
  76826. pVar->flags = MEM_Null;
  76827. sqlite3Error(p->db, SQLITE_OK);
  76828. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  76829. ** binding a new value to this variable invalidates the current query plan.
  76830. **
  76831. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  76832. ** parameter in the WHERE clause might influence the choice of query plan
  76833. ** for a statement, then the statement will be automatically recompiled,
  76834. ** as if there had been a schema change, on the first sqlite3_step() call
  76835. ** following any change to the bindings of that parameter.
  76836. */
  76837. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  76838. if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
  76839. p->expired = 1;
  76840. }
  76841. return SQLITE_OK;
  76842. }
  76843. /*
  76844. ** Bind a text or BLOB value.
  76845. */
  76846. static int bindText(
  76847. sqlite3_stmt *pStmt, /* The statement to bind against */
  76848. int i, /* Index of the parameter to bind */
  76849. const void *zData, /* Pointer to the data to be bound */
  76850. int nData, /* Number of bytes of data to be bound */
  76851. void (*xDel)(void*), /* Destructor for the data */
  76852. u8 encoding /* Encoding for the data */
  76853. ){
  76854. Vdbe *p = (Vdbe *)pStmt;
  76855. Mem *pVar;
  76856. int rc;
  76857. rc = vdbeUnbind(p, i);
  76858. if( rc==SQLITE_OK ){
  76859. if( zData!=0 ){
  76860. pVar = &p->aVar[i-1];
  76861. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  76862. if( rc==SQLITE_OK && encoding!=0 ){
  76863. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  76864. }
  76865. if( rc ){
  76866. sqlite3Error(p->db, rc);
  76867. rc = sqlite3ApiExit(p->db, rc);
  76868. }
  76869. }
  76870. sqlite3_mutex_leave(p->db->mutex);
  76871. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  76872. xDel((void*)zData);
  76873. }
  76874. return rc;
  76875. }
  76876. /*
  76877. ** Bind a blob value to an SQL statement variable.
  76878. */
  76879. SQLITE_API int sqlite3_bind_blob(
  76880. sqlite3_stmt *pStmt,
  76881. int i,
  76882. const void *zData,
  76883. int nData,
  76884. void (*xDel)(void*)
  76885. ){
  76886. #ifdef SQLITE_ENABLE_API_ARMOR
  76887. if( nData<0 ) return SQLITE_MISUSE_BKPT;
  76888. #endif
  76889. return bindText(pStmt, i, zData, nData, xDel, 0);
  76890. }
  76891. SQLITE_API int sqlite3_bind_blob64(
  76892. sqlite3_stmt *pStmt,
  76893. int i,
  76894. const void *zData,
  76895. sqlite3_uint64 nData,
  76896. void (*xDel)(void*)
  76897. ){
  76898. assert( xDel!=SQLITE_DYNAMIC );
  76899. if( nData>0x7fffffff ){
  76900. return invokeValueDestructor(zData, xDel, 0);
  76901. }else{
  76902. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  76903. }
  76904. }
  76905. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  76906. int rc;
  76907. Vdbe *p = (Vdbe *)pStmt;
  76908. rc = vdbeUnbind(p, i);
  76909. if( rc==SQLITE_OK ){
  76910. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  76911. sqlite3_mutex_leave(p->db->mutex);
  76912. }
  76913. return rc;
  76914. }
  76915. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  76916. return sqlite3_bind_int64(p, i, (i64)iValue);
  76917. }
  76918. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  76919. int rc;
  76920. Vdbe *p = (Vdbe *)pStmt;
  76921. rc = vdbeUnbind(p, i);
  76922. if( rc==SQLITE_OK ){
  76923. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  76924. sqlite3_mutex_leave(p->db->mutex);
  76925. }
  76926. return rc;
  76927. }
  76928. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  76929. int rc;
  76930. Vdbe *p = (Vdbe*)pStmt;
  76931. rc = vdbeUnbind(p, i);
  76932. if( rc==SQLITE_OK ){
  76933. sqlite3_mutex_leave(p->db->mutex);
  76934. }
  76935. return rc;
  76936. }
  76937. SQLITE_API int sqlite3_bind_pointer(
  76938. sqlite3_stmt *pStmt,
  76939. int i,
  76940. void *pPtr,
  76941. const char *zPTtype,
  76942. void (*xDestructor)(void*)
  76943. ){
  76944. int rc;
  76945. Vdbe *p = (Vdbe*)pStmt;
  76946. rc = vdbeUnbind(p, i);
  76947. if( rc==SQLITE_OK ){
  76948. sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
  76949. sqlite3_mutex_leave(p->db->mutex);
  76950. }else if( xDestructor ){
  76951. xDestructor(pPtr);
  76952. }
  76953. return rc;
  76954. }
  76955. SQLITE_API int sqlite3_bind_text(
  76956. sqlite3_stmt *pStmt,
  76957. int i,
  76958. const char *zData,
  76959. int nData,
  76960. void (*xDel)(void*)
  76961. ){
  76962. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  76963. }
  76964. SQLITE_API int sqlite3_bind_text64(
  76965. sqlite3_stmt *pStmt,
  76966. int i,
  76967. const char *zData,
  76968. sqlite3_uint64 nData,
  76969. void (*xDel)(void*),
  76970. unsigned char enc
  76971. ){
  76972. assert( xDel!=SQLITE_DYNAMIC );
  76973. if( nData>0x7fffffff ){
  76974. return invokeValueDestructor(zData, xDel, 0);
  76975. }else{
  76976. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  76977. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  76978. }
  76979. }
  76980. #ifndef SQLITE_OMIT_UTF16
  76981. SQLITE_API int sqlite3_bind_text16(
  76982. sqlite3_stmt *pStmt,
  76983. int i,
  76984. const void *zData,
  76985. int nData,
  76986. void (*xDel)(void*)
  76987. ){
  76988. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  76989. }
  76990. #endif /* SQLITE_OMIT_UTF16 */
  76991. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  76992. int rc;
  76993. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  76994. case SQLITE_INTEGER: {
  76995. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  76996. break;
  76997. }
  76998. case SQLITE_FLOAT: {
  76999. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  77000. break;
  77001. }
  77002. case SQLITE_BLOB: {
  77003. if( pValue->flags & MEM_Zero ){
  77004. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  77005. }else{
  77006. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  77007. }
  77008. break;
  77009. }
  77010. case SQLITE_TEXT: {
  77011. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  77012. pValue->enc);
  77013. break;
  77014. }
  77015. default: {
  77016. rc = sqlite3_bind_null(pStmt, i);
  77017. break;
  77018. }
  77019. }
  77020. return rc;
  77021. }
  77022. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  77023. int rc;
  77024. Vdbe *p = (Vdbe *)pStmt;
  77025. rc = vdbeUnbind(p, i);
  77026. if( rc==SQLITE_OK ){
  77027. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  77028. sqlite3_mutex_leave(p->db->mutex);
  77029. }
  77030. return rc;
  77031. }
  77032. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  77033. int rc;
  77034. Vdbe *p = (Vdbe *)pStmt;
  77035. sqlite3_mutex_enter(p->db->mutex);
  77036. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  77037. rc = SQLITE_TOOBIG;
  77038. }else{
  77039. assert( (n & 0x7FFFFFFF)==n );
  77040. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  77041. }
  77042. rc = sqlite3ApiExit(p->db, rc);
  77043. sqlite3_mutex_leave(p->db->mutex);
  77044. return rc;
  77045. }
  77046. /*
  77047. ** Return the number of wildcards that can be potentially bound to.
  77048. ** This routine is added to support DBD::SQLite.
  77049. */
  77050. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  77051. Vdbe *p = (Vdbe*)pStmt;
  77052. return p ? p->nVar : 0;
  77053. }
  77054. /*
  77055. ** Return the name of a wildcard parameter. Return NULL if the index
  77056. ** is out of range or if the wildcard is unnamed.
  77057. **
  77058. ** The result is always UTF-8.
  77059. */
  77060. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  77061. Vdbe *p = (Vdbe*)pStmt;
  77062. if( p==0 ) return 0;
  77063. return sqlite3VListNumToName(p->pVList, i);
  77064. }
  77065. /*
  77066. ** Given a wildcard parameter name, return the index of the variable
  77067. ** with that name. If there is no variable with the given name,
  77068. ** return 0.
  77069. */
  77070. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  77071. if( p==0 || zName==0 ) return 0;
  77072. return sqlite3VListNameToNum(p->pVList, zName, nName);
  77073. }
  77074. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  77075. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  77076. }
  77077. /*
  77078. ** Transfer all bindings from the first statement over to the second.
  77079. */
  77080. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  77081. Vdbe *pFrom = (Vdbe*)pFromStmt;
  77082. Vdbe *pTo = (Vdbe*)pToStmt;
  77083. int i;
  77084. assert( pTo->db==pFrom->db );
  77085. assert( pTo->nVar==pFrom->nVar );
  77086. sqlite3_mutex_enter(pTo->db->mutex);
  77087. for(i=0; i<pFrom->nVar; i++){
  77088. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  77089. }
  77090. sqlite3_mutex_leave(pTo->db->mutex);
  77091. return SQLITE_OK;
  77092. }
  77093. #ifndef SQLITE_OMIT_DEPRECATED
  77094. /*
  77095. ** Deprecated external interface. Internal/core SQLite code
  77096. ** should call sqlite3TransferBindings.
  77097. **
  77098. ** It is misuse to call this routine with statements from different
  77099. ** database connections. But as this is a deprecated interface, we
  77100. ** will not bother to check for that condition.
  77101. **
  77102. ** If the two statements contain a different number of bindings, then
  77103. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  77104. ** SQLITE_OK is returned.
  77105. */
  77106. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  77107. Vdbe *pFrom = (Vdbe*)pFromStmt;
  77108. Vdbe *pTo = (Vdbe*)pToStmt;
  77109. if( pFrom->nVar!=pTo->nVar ){
  77110. return SQLITE_ERROR;
  77111. }
  77112. assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
  77113. if( pTo->expmask ){
  77114. pTo->expired = 1;
  77115. }
  77116. assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
  77117. if( pFrom->expmask ){
  77118. pFrom->expired = 1;
  77119. }
  77120. return sqlite3TransferBindings(pFromStmt, pToStmt);
  77121. }
  77122. #endif
  77123. /*
  77124. ** Return the sqlite3* database handle to which the prepared statement given
  77125. ** in the argument belongs. This is the same database handle that was
  77126. ** the first argument to the sqlite3_prepare() that was used to create
  77127. ** the statement in the first place.
  77128. */
  77129. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  77130. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  77131. }
  77132. /*
  77133. ** Return true if the prepared statement is guaranteed to not modify the
  77134. ** database.
  77135. */
  77136. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  77137. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  77138. }
  77139. /*
  77140. ** Return true if the prepared statement is in need of being reset.
  77141. */
  77142. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  77143. Vdbe *v = (Vdbe*)pStmt;
  77144. return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
  77145. }
  77146. /*
  77147. ** Return a pointer to the next prepared statement after pStmt associated
  77148. ** with database connection pDb. If pStmt is NULL, return the first
  77149. ** prepared statement for the database connection. Return NULL if there
  77150. ** are no more.
  77151. */
  77152. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  77153. sqlite3_stmt *pNext;
  77154. #ifdef SQLITE_ENABLE_API_ARMOR
  77155. if( !sqlite3SafetyCheckOk(pDb) ){
  77156. (void)SQLITE_MISUSE_BKPT;
  77157. return 0;
  77158. }
  77159. #endif
  77160. sqlite3_mutex_enter(pDb->mutex);
  77161. if( pStmt==0 ){
  77162. pNext = (sqlite3_stmt*)pDb->pVdbe;
  77163. }else{
  77164. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  77165. }
  77166. sqlite3_mutex_leave(pDb->mutex);
  77167. return pNext;
  77168. }
  77169. /*
  77170. ** Return the value of a status counter for a prepared statement
  77171. */
  77172. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  77173. Vdbe *pVdbe = (Vdbe*)pStmt;
  77174. u32 v;
  77175. #ifdef SQLITE_ENABLE_API_ARMOR
  77176. if( !pStmt
  77177. || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
  77178. ){
  77179. (void)SQLITE_MISUSE_BKPT;
  77180. return 0;
  77181. }
  77182. #endif
  77183. if( op==SQLITE_STMTSTATUS_MEMUSED ){
  77184. sqlite3 *db = pVdbe->db;
  77185. sqlite3_mutex_enter(db->mutex);
  77186. v = 0;
  77187. db->pnBytesFreed = (int*)&v;
  77188. sqlite3VdbeClearObject(db, pVdbe);
  77189. sqlite3DbFree(db, pVdbe);
  77190. db->pnBytesFreed = 0;
  77191. sqlite3_mutex_leave(db->mutex);
  77192. }else{
  77193. v = pVdbe->aCounter[op];
  77194. if( resetFlag ) pVdbe->aCounter[op] = 0;
  77195. }
  77196. return (int)v;
  77197. }
  77198. /*
  77199. ** Return the SQL associated with a prepared statement
  77200. */
  77201. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  77202. Vdbe *p = (Vdbe *)pStmt;
  77203. return p ? p->zSql : 0;
  77204. }
  77205. /*
  77206. ** Return the SQL associated with a prepared statement with
  77207. ** bound parameters expanded. Space to hold the returned string is
  77208. ** obtained from sqlite3_malloc(). The caller is responsible for
  77209. ** freeing the returned string by passing it to sqlite3_free().
  77210. **
  77211. ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
  77212. ** expanded bound parameters.
  77213. */
  77214. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
  77215. #ifdef SQLITE_OMIT_TRACE
  77216. return 0;
  77217. #else
  77218. char *z = 0;
  77219. const char *zSql = sqlite3_sql(pStmt);
  77220. if( zSql ){
  77221. Vdbe *p = (Vdbe *)pStmt;
  77222. sqlite3_mutex_enter(p->db->mutex);
  77223. z = sqlite3VdbeExpandSql(p, zSql);
  77224. sqlite3_mutex_leave(p->db->mutex);
  77225. }
  77226. return z;
  77227. #endif
  77228. }
  77229. #ifdef SQLITE_ENABLE_NORMALIZE
  77230. /*
  77231. ** Return the normalized SQL associated with a prepared statement.
  77232. */
  77233. SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
  77234. Vdbe *p = (Vdbe *)pStmt;
  77235. return p ? p->zNormSql : 0;
  77236. }
  77237. #endif /* SQLITE_ENABLE_NORMALIZE */
  77238. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77239. /*
  77240. ** Allocate and populate an UnpackedRecord structure based on the serialized
  77241. ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
  77242. ** if successful, or a NULL pointer if an OOM error is encountered.
  77243. */
  77244. static UnpackedRecord *vdbeUnpackRecord(
  77245. KeyInfo *pKeyInfo,
  77246. int nKey,
  77247. const void *pKey
  77248. ){
  77249. UnpackedRecord *pRet; /* Return value */
  77250. pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  77251. if( pRet ){
  77252. memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
  77253. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
  77254. }
  77255. return pRet;
  77256. }
  77257. /*
  77258. ** This function is called from within a pre-update callback to retrieve
  77259. ** a field of the row currently being updated or deleted.
  77260. */
  77261. SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  77262. PreUpdate *p = db->pPreUpdate;
  77263. Mem *pMem;
  77264. int rc = SQLITE_OK;
  77265. /* Test that this call is being made from within an SQLITE_DELETE or
  77266. ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
  77267. if( !p || p->op==SQLITE_INSERT ){
  77268. rc = SQLITE_MISUSE_BKPT;
  77269. goto preupdate_old_out;
  77270. }
  77271. if( p->pPk ){
  77272. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  77273. }
  77274. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  77275. rc = SQLITE_RANGE;
  77276. goto preupdate_old_out;
  77277. }
  77278. /* If the old.* record has not yet been loaded into memory, do so now. */
  77279. if( p->pUnpacked==0 ){
  77280. u32 nRec;
  77281. u8 *aRec;
  77282. nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
  77283. aRec = sqlite3DbMallocRaw(db, nRec);
  77284. if( !aRec ) goto preupdate_old_out;
  77285. rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
  77286. if( rc==SQLITE_OK ){
  77287. p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
  77288. if( !p->pUnpacked ) rc = SQLITE_NOMEM;
  77289. }
  77290. if( rc!=SQLITE_OK ){
  77291. sqlite3DbFree(db, aRec);
  77292. goto preupdate_old_out;
  77293. }
  77294. p->aRecord = aRec;
  77295. }
  77296. pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
  77297. if( iIdx==p->pTab->iPKey ){
  77298. sqlite3VdbeMemSetInt64(pMem, p->iKey1);
  77299. }else if( iIdx>=p->pUnpacked->nField ){
  77300. *ppValue = (sqlite3_value *)columnNullValue();
  77301. }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
  77302. if( pMem->flags & MEM_Int ){
  77303. sqlite3VdbeMemRealify(pMem);
  77304. }
  77305. }
  77306. preupdate_old_out:
  77307. sqlite3Error(db, rc);
  77308. return sqlite3ApiExit(db, rc);
  77309. }
  77310. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  77311. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77312. /*
  77313. ** This function is called from within a pre-update callback to retrieve
  77314. ** the number of columns in the row being updated, deleted or inserted.
  77315. */
  77316. SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
  77317. PreUpdate *p = db->pPreUpdate;
  77318. return (p ? p->keyinfo.nKeyField : 0);
  77319. }
  77320. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  77321. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77322. /*
  77323. ** This function is designed to be called from within a pre-update callback
  77324. ** only. It returns zero if the change that caused the callback was made
  77325. ** immediately by a user SQL statement. Or, if the change was made by a
  77326. ** trigger program, it returns the number of trigger programs currently
  77327. ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
  77328. ** top-level trigger etc.).
  77329. **
  77330. ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
  77331. ** or SET DEFAULT action is considered a trigger.
  77332. */
  77333. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
  77334. PreUpdate *p = db->pPreUpdate;
  77335. return (p ? p->v->nFrame : 0);
  77336. }
  77337. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  77338. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77339. /*
  77340. ** This function is called from within a pre-update callback to retrieve
  77341. ** a field of the row currently being updated or inserted.
  77342. */
  77343. SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  77344. PreUpdate *p = db->pPreUpdate;
  77345. int rc = SQLITE_OK;
  77346. Mem *pMem;
  77347. if( !p || p->op==SQLITE_DELETE ){
  77348. rc = SQLITE_MISUSE_BKPT;
  77349. goto preupdate_new_out;
  77350. }
  77351. if( p->pPk && p->op!=SQLITE_UPDATE ){
  77352. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  77353. }
  77354. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  77355. rc = SQLITE_RANGE;
  77356. goto preupdate_new_out;
  77357. }
  77358. if( p->op==SQLITE_INSERT ){
  77359. /* For an INSERT, memory cell p->iNewReg contains the serialized record
  77360. ** that is being inserted. Deserialize it. */
  77361. UnpackedRecord *pUnpack = p->pNewUnpacked;
  77362. if( !pUnpack ){
  77363. Mem *pData = &p->v->aMem[p->iNewReg];
  77364. rc = ExpandBlob(pData);
  77365. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  77366. pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
  77367. if( !pUnpack ){
  77368. rc = SQLITE_NOMEM;
  77369. goto preupdate_new_out;
  77370. }
  77371. p->pNewUnpacked = pUnpack;
  77372. }
  77373. pMem = &pUnpack->aMem[iIdx];
  77374. if( iIdx==p->pTab->iPKey ){
  77375. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  77376. }else if( iIdx>=pUnpack->nField ){
  77377. pMem = (sqlite3_value *)columnNullValue();
  77378. }
  77379. }else{
  77380. /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
  77381. ** value. Make a copy of the cell contents and return a pointer to it.
  77382. ** It is not safe to return a pointer to the memory cell itself as the
  77383. ** caller may modify the value text encoding.
  77384. */
  77385. assert( p->op==SQLITE_UPDATE );
  77386. if( !p->aNew ){
  77387. p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
  77388. if( !p->aNew ){
  77389. rc = SQLITE_NOMEM;
  77390. goto preupdate_new_out;
  77391. }
  77392. }
  77393. assert( iIdx>=0 && iIdx<p->pCsr->nField );
  77394. pMem = &p->aNew[iIdx];
  77395. if( pMem->flags==0 ){
  77396. if( iIdx==p->pTab->iPKey ){
  77397. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  77398. }else{
  77399. rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
  77400. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  77401. }
  77402. }
  77403. }
  77404. *ppValue = pMem;
  77405. preupdate_new_out:
  77406. sqlite3Error(db, rc);
  77407. return sqlite3ApiExit(db, rc);
  77408. }
  77409. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  77410. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  77411. /*
  77412. ** Return status data for a single loop within query pStmt.
  77413. */
  77414. SQLITE_API int sqlite3_stmt_scanstatus(
  77415. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  77416. int idx, /* Index of loop to report on */
  77417. int iScanStatusOp, /* Which metric to return */
  77418. void *pOut /* OUT: Write the answer here */
  77419. ){
  77420. Vdbe *p = (Vdbe*)pStmt;
  77421. ScanStatus *pScan;
  77422. if( idx<0 || idx>=p->nScan ) return 1;
  77423. pScan = &p->aScan[idx];
  77424. switch( iScanStatusOp ){
  77425. case SQLITE_SCANSTAT_NLOOP: {
  77426. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  77427. break;
  77428. }
  77429. case SQLITE_SCANSTAT_NVISIT: {
  77430. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  77431. break;
  77432. }
  77433. case SQLITE_SCANSTAT_EST: {
  77434. double r = 1.0;
  77435. LogEst x = pScan->nEst;
  77436. while( x<100 ){
  77437. x += 10;
  77438. r *= 0.5;
  77439. }
  77440. *(double*)pOut = r*sqlite3LogEstToInt(x);
  77441. break;
  77442. }
  77443. case SQLITE_SCANSTAT_NAME: {
  77444. *(const char**)pOut = pScan->zName;
  77445. break;
  77446. }
  77447. case SQLITE_SCANSTAT_EXPLAIN: {
  77448. if( pScan->addrExplain ){
  77449. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  77450. }else{
  77451. *(const char**)pOut = 0;
  77452. }
  77453. break;
  77454. }
  77455. case SQLITE_SCANSTAT_SELECTID: {
  77456. if( pScan->addrExplain ){
  77457. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  77458. }else{
  77459. *(int*)pOut = -1;
  77460. }
  77461. break;
  77462. }
  77463. default: {
  77464. return 1;
  77465. }
  77466. }
  77467. return 0;
  77468. }
  77469. /*
  77470. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  77471. */
  77472. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  77473. Vdbe *p = (Vdbe*)pStmt;
  77474. memset(p->anExec, 0, p->nOp * sizeof(i64));
  77475. }
  77476. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  77477. /************** End of vdbeapi.c *********************************************/
  77478. /************** Begin file vdbetrace.c ***************************************/
  77479. /*
  77480. ** 2009 November 25
  77481. **
  77482. ** The author disclaims copyright to this source code. In place of
  77483. ** a legal notice, here is a blessing:
  77484. **
  77485. ** May you do good and not evil.
  77486. ** May you find forgiveness for yourself and forgive others.
  77487. ** May you share freely, never taking more than you give.
  77488. **
  77489. *************************************************************************
  77490. **
  77491. ** This file contains code used to insert the values of host parameters
  77492. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  77493. **
  77494. ** The Vdbe parse-tree explainer is also found here.
  77495. */
  77496. /* #include "sqliteInt.h" */
  77497. /* #include "vdbeInt.h" */
  77498. #ifndef SQLITE_OMIT_TRACE
  77499. /*
  77500. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  77501. ** bytes in this text up to but excluding the first character in
  77502. ** a host parameter. If the text contains no host parameters, return
  77503. ** the total number of bytes in the text.
  77504. */
  77505. static int findNextHostParameter(const char *zSql, int *pnToken){
  77506. int tokenType;
  77507. int nTotal = 0;
  77508. int n;
  77509. *pnToken = 0;
  77510. while( zSql[0] ){
  77511. n = sqlite3GetToken((u8*)zSql, &tokenType);
  77512. assert( n>0 && tokenType!=TK_ILLEGAL );
  77513. if( tokenType==TK_VARIABLE ){
  77514. *pnToken = n;
  77515. break;
  77516. }
  77517. nTotal += n;
  77518. zSql += n;
  77519. }
  77520. return nTotal;
  77521. }
  77522. /*
  77523. ** This function returns a pointer to a nul-terminated string in memory
  77524. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  77525. ** string contains a copy of zRawSql but with host parameters expanded to
  77526. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  77527. ** then the returned string holds a copy of zRawSql with "-- " prepended
  77528. ** to each line of text.
  77529. **
  77530. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  77531. ** then long strings and blobs are truncated to that many bytes. This
  77532. ** can be used to prevent unreasonably large trace strings when dealing
  77533. ** with large (multi-megabyte) strings and blobs.
  77534. **
  77535. ** The calling function is responsible for making sure the memory returned
  77536. ** is eventually freed.
  77537. **
  77538. ** ALGORITHM: Scan the input string looking for host parameters in any of
  77539. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  77540. ** string literals, quoted identifier names, and comments. For text forms,
  77541. ** the host parameter index is found by scanning the prepared
  77542. ** statement for the corresponding OP_Variable opcode. Once the host
  77543. ** parameter index is known, locate the value in p->aVar[]. Then render
  77544. ** the value as a literal in place of the host parameter name.
  77545. */
  77546. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  77547. Vdbe *p, /* The prepared statement being evaluated */
  77548. const char *zRawSql /* Raw text of the SQL statement */
  77549. ){
  77550. sqlite3 *db; /* The database connection */
  77551. int idx = 0; /* Index of a host parameter */
  77552. int nextIndex = 1; /* Index of next ? host parameter */
  77553. int n; /* Length of a token prefix */
  77554. int nToken; /* Length of the parameter token */
  77555. int i; /* Loop counter */
  77556. Mem *pVar; /* Value of a host parameter */
  77557. StrAccum out; /* Accumulate the output here */
  77558. #ifndef SQLITE_OMIT_UTF16
  77559. Mem utf8; /* Used to convert UTF16 into UTF8 for display */
  77560. #endif
  77561. char zBase[100]; /* Initial working space */
  77562. db = p->db;
  77563. sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
  77564. db->aLimit[SQLITE_LIMIT_LENGTH]);
  77565. if( db->nVdbeExec>1 ){
  77566. while( *zRawSql ){
  77567. const char *zStart = zRawSql;
  77568. while( *(zRawSql++)!='\n' && *zRawSql );
  77569. sqlite3_str_append(&out, "-- ", 3);
  77570. assert( (zRawSql - zStart) > 0 );
  77571. sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));
  77572. }
  77573. }else if( p->nVar==0 ){
  77574. sqlite3_str_append(&out, zRawSql, sqlite3Strlen30(zRawSql));
  77575. }else{
  77576. while( zRawSql[0] ){
  77577. n = findNextHostParameter(zRawSql, &nToken);
  77578. assert( n>0 );
  77579. sqlite3_str_append(&out, zRawSql, n);
  77580. zRawSql += n;
  77581. assert( zRawSql[0] || nToken==0 );
  77582. if( nToken==0 ) break;
  77583. if( zRawSql[0]=='?' ){
  77584. if( nToken>1 ){
  77585. assert( sqlite3Isdigit(zRawSql[1]) );
  77586. sqlite3GetInt32(&zRawSql[1], &idx);
  77587. }else{
  77588. idx = nextIndex;
  77589. }
  77590. }else{
  77591. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  77592. zRawSql[0]=='@' || zRawSql[0]=='#' );
  77593. testcase( zRawSql[0]==':' );
  77594. testcase( zRawSql[0]=='$' );
  77595. testcase( zRawSql[0]=='@' );
  77596. testcase( zRawSql[0]=='#' );
  77597. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  77598. assert( idx>0 );
  77599. }
  77600. zRawSql += nToken;
  77601. nextIndex = idx + 1;
  77602. assert( idx>0 && idx<=p->nVar );
  77603. pVar = &p->aVar[idx-1];
  77604. if( pVar->flags & MEM_Null ){
  77605. sqlite3_str_append(&out, "NULL", 4);
  77606. }else if( pVar->flags & MEM_Int ){
  77607. sqlite3_str_appendf(&out, "%lld", pVar->u.i);
  77608. }else if( pVar->flags & MEM_Real ){
  77609. sqlite3_str_appendf(&out, "%!.15g", pVar->u.r);
  77610. }else if( pVar->flags & MEM_Str ){
  77611. int nOut; /* Number of bytes of the string text to include in output */
  77612. #ifndef SQLITE_OMIT_UTF16
  77613. u8 enc = ENC(db);
  77614. if( enc!=SQLITE_UTF8 ){
  77615. memset(&utf8, 0, sizeof(utf8));
  77616. utf8.db = db;
  77617. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  77618. if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
  77619. out.accError = SQLITE_NOMEM;
  77620. out.nAlloc = 0;
  77621. }
  77622. pVar = &utf8;
  77623. }
  77624. #endif
  77625. nOut = pVar->n;
  77626. #ifdef SQLITE_TRACE_SIZE_LIMIT
  77627. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  77628. nOut = SQLITE_TRACE_SIZE_LIMIT;
  77629. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  77630. }
  77631. #endif
  77632. sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
  77633. #ifdef SQLITE_TRACE_SIZE_LIMIT
  77634. if( nOut<pVar->n ){
  77635. sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
  77636. }
  77637. #endif
  77638. #ifndef SQLITE_OMIT_UTF16
  77639. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  77640. #endif
  77641. }else if( pVar->flags & MEM_Zero ){
  77642. sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero);
  77643. }else{
  77644. int nOut; /* Number of bytes of the blob to include in output */
  77645. assert( pVar->flags & MEM_Blob );
  77646. sqlite3_str_append(&out, "x'", 2);
  77647. nOut = pVar->n;
  77648. #ifdef SQLITE_TRACE_SIZE_LIMIT
  77649. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  77650. #endif
  77651. for(i=0; i<nOut; i++){
  77652. sqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff);
  77653. }
  77654. sqlite3_str_append(&out, "'", 1);
  77655. #ifdef SQLITE_TRACE_SIZE_LIMIT
  77656. if( nOut<pVar->n ){
  77657. sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
  77658. }
  77659. #endif
  77660. }
  77661. }
  77662. }
  77663. if( out.accError ) sqlite3_str_reset(&out);
  77664. return sqlite3StrAccumFinish(&out);
  77665. }
  77666. #endif /* #ifndef SQLITE_OMIT_TRACE */
  77667. /************** End of vdbetrace.c *******************************************/
  77668. /************** Begin file vdbe.c ********************************************/
  77669. /*
  77670. ** 2001 September 15
  77671. **
  77672. ** The author disclaims copyright to this source code. In place of
  77673. ** a legal notice, here is a blessing:
  77674. **
  77675. ** May you do good and not evil.
  77676. ** May you find forgiveness for yourself and forgive others.
  77677. ** May you share freely, never taking more than you give.
  77678. **
  77679. *************************************************************************
  77680. ** The code in this file implements the function that runs the
  77681. ** bytecode of a prepared statement.
  77682. **
  77683. ** Various scripts scan this source file in order to generate HTML
  77684. ** documentation, headers files, or other derived files. The formatting
  77685. ** of the code in this file is, therefore, important. See other comments
  77686. ** in this file for details. If in doubt, do not deviate from existing
  77687. ** commenting and indentation practices when changing or adding code.
  77688. */
  77689. /* #include "sqliteInt.h" */
  77690. /* #include "vdbeInt.h" */
  77691. /*
  77692. ** Invoke this macro on memory cells just prior to changing the
  77693. ** value of the cell. This macro verifies that shallow copies are
  77694. ** not misused. A shallow copy of a string or blob just copies a
  77695. ** pointer to the string or blob, not the content. If the original
  77696. ** is changed while the copy is still in use, the string or blob might
  77697. ** be changed out from under the copy. This macro verifies that nothing
  77698. ** like that ever happens.
  77699. */
  77700. #ifdef SQLITE_DEBUG
  77701. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  77702. #else
  77703. # define memAboutToChange(P,M)
  77704. #endif
  77705. /*
  77706. ** The following global variable is incremented every time a cursor
  77707. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  77708. ** procedures use this information to make sure that indices are
  77709. ** working correctly. This variable has no function other than to
  77710. ** help verify the correct operation of the library.
  77711. */
  77712. #ifdef SQLITE_TEST
  77713. SQLITE_API int sqlite3_search_count = 0;
  77714. #endif
  77715. /*
  77716. ** When this global variable is positive, it gets decremented once before
  77717. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  77718. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  77719. **
  77720. ** This facility is used for testing purposes only. It does not function
  77721. ** in an ordinary build.
  77722. */
  77723. #ifdef SQLITE_TEST
  77724. SQLITE_API int sqlite3_interrupt_count = 0;
  77725. #endif
  77726. /*
  77727. ** The next global variable is incremented each type the OP_Sort opcode
  77728. ** is executed. The test procedures use this information to make sure that
  77729. ** sorting is occurring or not occurring at appropriate times. This variable
  77730. ** has no function other than to help verify the correct operation of the
  77731. ** library.
  77732. */
  77733. #ifdef SQLITE_TEST
  77734. SQLITE_API int sqlite3_sort_count = 0;
  77735. #endif
  77736. /*
  77737. ** The next global variable records the size of the largest MEM_Blob
  77738. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  77739. ** use this information to make sure that the zero-blob functionality
  77740. ** is working correctly. This variable has no function other than to
  77741. ** help verify the correct operation of the library.
  77742. */
  77743. #ifdef SQLITE_TEST
  77744. SQLITE_API int sqlite3_max_blobsize = 0;
  77745. static void updateMaxBlobsize(Mem *p){
  77746. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  77747. sqlite3_max_blobsize = p->n;
  77748. }
  77749. }
  77750. #endif
  77751. /*
  77752. ** This macro evaluates to true if either the update hook or the preupdate
  77753. ** hook are enabled for database connect DB.
  77754. */
  77755. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77756. # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
  77757. #else
  77758. # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
  77759. #endif
  77760. /*
  77761. ** The next global variable is incremented each time the OP_Found opcode
  77762. ** is executed. This is used to test whether or not the foreign key
  77763. ** operation implemented using OP_FkIsZero is working. This variable
  77764. ** has no function other than to help verify the correct operation of the
  77765. ** library.
  77766. */
  77767. #ifdef SQLITE_TEST
  77768. SQLITE_API int sqlite3_found_count = 0;
  77769. #endif
  77770. /*
  77771. ** Test a register to see if it exceeds the current maximum blob size.
  77772. ** If it does, record the new maximum blob size.
  77773. */
  77774. #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
  77775. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  77776. #else
  77777. # define UPDATE_MAX_BLOBSIZE(P)
  77778. #endif
  77779. /*
  77780. ** Invoke the VDBE coverage callback, if that callback is defined. This
  77781. ** feature is used for test suite validation only and does not appear an
  77782. ** production builds.
  77783. **
  77784. ** M is an integer between 2 and 4. 2 indicates a ordinary two-way
  77785. ** branch (I=0 means fall through and I=1 means taken). 3 indicates
  77786. ** a 3-way branch where the third way is when one of the operands is
  77787. ** NULL. 4 indicates the OP_Jump instruction which has three destinations
  77788. ** depending on whether the first operand is less than, equal to, or greater
  77789. ** than the second.
  77790. **
  77791. ** iSrcLine is the source code line (from the __LINE__ macro) that
  77792. ** generated the VDBE instruction combined with flag bits. The source
  77793. ** code line number is in the lower 24 bits of iSrcLine and the upper
  77794. ** 8 bytes are flags. The lower three bits of the flags indicate
  77795. ** values for I that should never occur. For example, if the branch is
  77796. ** always taken, the flags should be 0x05 since the fall-through and
  77797. ** alternate branch are never taken. If a branch is never taken then
  77798. ** flags should be 0x06 since only the fall-through approach is allowed.
  77799. **
  77800. ** Bit 0x04 of the flags indicates an OP_Jump opcode that is only
  77801. ** interested in equal or not-equal. In other words, I==0 and I==2
  77802. ** should be treated the same.
  77803. **
  77804. ** Since only a line number is retained, not the filename, this macro
  77805. ** only works for amalgamation builds. But that is ok, since these macros
  77806. ** should be no-ops except for special builds used to measure test coverage.
  77807. */
  77808. #if !defined(SQLITE_VDBE_COVERAGE)
  77809. # define VdbeBranchTaken(I,M)
  77810. #else
  77811. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  77812. static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){
  77813. u8 mNever;
  77814. assert( I<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */
  77815. assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
  77816. assert( I<M ); /* I can only be 2 if M is 3 or 4 */
  77817. /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */
  77818. I = 1<<I;
  77819. /* The upper 8 bits of iSrcLine are flags. The lower three bits of
  77820. ** the flags indicate directions that the branch can never go. If
  77821. ** a branch really does go in one of those directions, assert right
  77822. ** away. */
  77823. mNever = iSrcLine >> 24;
  77824. assert( (I & mNever)==0 );
  77825. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  77826. I |= mNever;
  77827. if( M==2 ) I |= 0x04;
  77828. if( M==4 ){
  77829. I |= 0x08;
  77830. if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/
  77831. }
  77832. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  77833. iSrcLine&0xffffff, I, M);
  77834. }
  77835. #endif
  77836. /*
  77837. ** Convert the given register into a string if it isn't one
  77838. ** already. Return non-zero if a malloc() fails.
  77839. */
  77840. #define Stringify(P, enc) \
  77841. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  77842. { goto no_mem; }
  77843. /*
  77844. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  77845. ** a pointer to a dynamically allocated string where some other entity
  77846. ** is responsible for deallocating that string. Because the register
  77847. ** does not control the string, it might be deleted without the register
  77848. ** knowing it.
  77849. **
  77850. ** This routine converts an ephemeral string into a dynamically allocated
  77851. ** string that the register itself controls. In other words, it
  77852. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  77853. */
  77854. #define Deephemeralize(P) \
  77855. if( ((P)->flags&MEM_Ephem)!=0 \
  77856. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  77857. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  77858. #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
  77859. /*
  77860. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  77861. ** if we run out of memory.
  77862. */
  77863. static VdbeCursor *allocateCursor(
  77864. Vdbe *p, /* The virtual machine */
  77865. int iCur, /* Index of the new VdbeCursor */
  77866. int nField, /* Number of fields in the table or index */
  77867. int iDb, /* Database the cursor belongs to, or -1 */
  77868. u8 eCurType /* Type of the new cursor */
  77869. ){
  77870. /* Find the memory cell that will be used to store the blob of memory
  77871. ** required for this VdbeCursor structure. It is convenient to use a
  77872. ** vdbe memory cell to manage the memory allocation required for a
  77873. ** VdbeCursor structure for the following reasons:
  77874. **
  77875. ** * Sometimes cursor numbers are used for a couple of different
  77876. ** purposes in a vdbe program. The different uses might require
  77877. ** different sized allocations. Memory cells provide growable
  77878. ** allocations.
  77879. **
  77880. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  77881. ** be freed lazily via the sqlite3_release_memory() API. This
  77882. ** minimizes the number of malloc calls made by the system.
  77883. **
  77884. ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
  77885. ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
  77886. ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
  77887. */
  77888. Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
  77889. int nByte;
  77890. VdbeCursor *pCx = 0;
  77891. nByte =
  77892. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  77893. (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
  77894. assert( iCur>=0 && iCur<p->nCursor );
  77895. if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
  77896. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  77897. p->apCsr[iCur] = 0;
  77898. }
  77899. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  77900. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  77901. memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
  77902. pCx->eCurType = eCurType;
  77903. pCx->iDb = iDb;
  77904. pCx->nField = nField;
  77905. pCx->aOffset = &pCx->aType[nField];
  77906. if( eCurType==CURTYPE_BTREE ){
  77907. pCx->uc.pCursor = (BtCursor*)
  77908. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  77909. sqlite3BtreeCursorZero(pCx->uc.pCursor);
  77910. }
  77911. }
  77912. return pCx;
  77913. }
  77914. /*
  77915. ** Try to convert a value into a numeric representation if we can
  77916. ** do so without loss of information. In other words, if the string
  77917. ** looks like a number, convert it into a number. If it does not
  77918. ** look like a number, leave it alone.
  77919. **
  77920. ** If the bTryForInt flag is true, then extra effort is made to give
  77921. ** an integer representation. Strings that look like floating point
  77922. ** values but which have no fractional component (example: '48.00')
  77923. ** will have a MEM_Int representation when bTryForInt is true.
  77924. **
  77925. ** If bTryForInt is false, then if the input string contains a decimal
  77926. ** point or exponential notation, the result is only MEM_Real, even
  77927. ** if there is an exact integer representation of the quantity.
  77928. */
  77929. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  77930. double rValue;
  77931. i64 iValue;
  77932. u8 enc = pRec->enc;
  77933. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  77934. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  77935. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  77936. pRec->u.i = iValue;
  77937. pRec->flags |= MEM_Int;
  77938. }else{
  77939. pRec->u.r = rValue;
  77940. pRec->flags |= MEM_Real;
  77941. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  77942. }
  77943. /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
  77944. ** string representation after computing a numeric equivalent, because the
  77945. ** string representation might not be the canonical representation for the
  77946. ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
  77947. pRec->flags &= ~MEM_Str;
  77948. }
  77949. /*
  77950. ** Processing is determine by the affinity parameter:
  77951. **
  77952. ** SQLITE_AFF_INTEGER:
  77953. ** SQLITE_AFF_REAL:
  77954. ** SQLITE_AFF_NUMERIC:
  77955. ** Try to convert pRec to an integer representation or a
  77956. ** floating-point representation if an integer representation
  77957. ** is not possible. Note that the integer representation is
  77958. ** always preferred, even if the affinity is REAL, because
  77959. ** an integer representation is more space efficient on disk.
  77960. **
  77961. ** SQLITE_AFF_TEXT:
  77962. ** Convert pRec to a text representation.
  77963. **
  77964. ** SQLITE_AFF_BLOB:
  77965. ** No-op. pRec is unchanged.
  77966. */
  77967. static void applyAffinity(
  77968. Mem *pRec, /* The value to apply affinity to */
  77969. char affinity, /* The affinity to be applied */
  77970. u8 enc /* Use this text encoding */
  77971. ){
  77972. if( affinity>=SQLITE_AFF_NUMERIC ){
  77973. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  77974. || affinity==SQLITE_AFF_NUMERIC );
  77975. if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  77976. if( (pRec->flags & MEM_Real)==0 ){
  77977. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  77978. }else{
  77979. sqlite3VdbeIntegerAffinity(pRec);
  77980. }
  77981. }
  77982. }else if( affinity==SQLITE_AFF_TEXT ){
  77983. /* Only attempt the conversion to TEXT if there is an integer or real
  77984. ** representation (blob and NULL do not get converted) but no string
  77985. ** representation. It would be harmless to repeat the conversion if
  77986. ** there is already a string rep, but it is pointless to waste those
  77987. ** CPU cycles. */
  77988. if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
  77989. if( (pRec->flags&(MEM_Real|MEM_Int)) ){
  77990. sqlite3VdbeMemStringify(pRec, enc, 1);
  77991. }
  77992. }
  77993. pRec->flags &= ~(MEM_Real|MEM_Int);
  77994. }
  77995. }
  77996. /*
  77997. ** Try to convert the type of a function argument or a result column
  77998. ** into a numeric representation. Use either INTEGER or REAL whichever
  77999. ** is appropriate. But only do the conversion if it is possible without
  78000. ** loss of information and return the revised type of the argument.
  78001. */
  78002. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  78003. int eType = sqlite3_value_type(pVal);
  78004. if( eType==SQLITE_TEXT ){
  78005. Mem *pMem = (Mem*)pVal;
  78006. applyNumericAffinity(pMem, 0);
  78007. eType = sqlite3_value_type(pVal);
  78008. }
  78009. return eType;
  78010. }
  78011. /*
  78012. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  78013. ** not the internal Mem* type.
  78014. */
  78015. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  78016. sqlite3_value *pVal,
  78017. u8 affinity,
  78018. u8 enc
  78019. ){
  78020. applyAffinity((Mem *)pVal, affinity, enc);
  78021. }
  78022. /*
  78023. ** pMem currently only holds a string type (or maybe a BLOB that we can
  78024. ** interpret as a string if we want to). Compute its corresponding
  78025. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  78026. ** accordingly.
  78027. */
  78028. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  78029. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  78030. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  78031. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  78032. return 0;
  78033. }
  78034. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
  78035. return MEM_Int;
  78036. }
  78037. return MEM_Real;
  78038. }
  78039. /*
  78040. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  78041. ** none.
  78042. **
  78043. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  78044. ** But it does set pMem->u.r and pMem->u.i appropriately.
  78045. */
  78046. static u16 numericType(Mem *pMem){
  78047. if( pMem->flags & (MEM_Int|MEM_Real) ){
  78048. return pMem->flags & (MEM_Int|MEM_Real);
  78049. }
  78050. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  78051. return computeNumericType(pMem);
  78052. }
  78053. return 0;
  78054. }
  78055. #ifdef SQLITE_DEBUG
  78056. /*
  78057. ** Write a nice string representation of the contents of cell pMem
  78058. ** into buffer zBuf, length nBuf.
  78059. */
  78060. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  78061. char *zCsr = zBuf;
  78062. int f = pMem->flags;
  78063. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  78064. if( f&MEM_Blob ){
  78065. int i;
  78066. char c;
  78067. if( f & MEM_Dyn ){
  78068. c = 'z';
  78069. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  78070. }else if( f & MEM_Static ){
  78071. c = 't';
  78072. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  78073. }else if( f & MEM_Ephem ){
  78074. c = 'e';
  78075. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  78076. }else{
  78077. c = 's';
  78078. }
  78079. *(zCsr++) = c;
  78080. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  78081. zCsr += sqlite3Strlen30(zCsr);
  78082. for(i=0; i<16 && i<pMem->n; i++){
  78083. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  78084. zCsr += sqlite3Strlen30(zCsr);
  78085. }
  78086. for(i=0; i<16 && i<pMem->n; i++){
  78087. char z = pMem->z[i];
  78088. if( z<32 || z>126 ) *zCsr++ = '.';
  78089. else *zCsr++ = z;
  78090. }
  78091. *(zCsr++) = ']';
  78092. if( f & MEM_Zero ){
  78093. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  78094. zCsr += sqlite3Strlen30(zCsr);
  78095. }
  78096. *zCsr = '\0';
  78097. }else if( f & MEM_Str ){
  78098. int j, k;
  78099. zBuf[0] = ' ';
  78100. if( f & MEM_Dyn ){
  78101. zBuf[1] = 'z';
  78102. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  78103. }else if( f & MEM_Static ){
  78104. zBuf[1] = 't';
  78105. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  78106. }else if( f & MEM_Ephem ){
  78107. zBuf[1] = 'e';
  78108. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  78109. }else{
  78110. zBuf[1] = 's';
  78111. }
  78112. k = 2;
  78113. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  78114. k += sqlite3Strlen30(&zBuf[k]);
  78115. zBuf[k++] = '[';
  78116. for(j=0; j<15 && j<pMem->n; j++){
  78117. u8 c = pMem->z[j];
  78118. if( c>=0x20 && c<0x7f ){
  78119. zBuf[k++] = c;
  78120. }else{
  78121. zBuf[k++] = '.';
  78122. }
  78123. }
  78124. zBuf[k++] = ']';
  78125. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  78126. k += sqlite3Strlen30(&zBuf[k]);
  78127. zBuf[k++] = 0;
  78128. }
  78129. }
  78130. #endif
  78131. #ifdef SQLITE_DEBUG
  78132. /*
  78133. ** Print the value of a register for tracing purposes:
  78134. */
  78135. static void memTracePrint(Mem *p){
  78136. if( p->flags & MEM_Undefined ){
  78137. printf(" undefined");
  78138. }else if( p->flags & MEM_Null ){
  78139. printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
  78140. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  78141. printf(" si:%lld", p->u.i);
  78142. }else if( p->flags & MEM_Int ){
  78143. printf(" i:%lld", p->u.i);
  78144. #ifndef SQLITE_OMIT_FLOATING_POINT
  78145. }else if( p->flags & MEM_Real ){
  78146. printf(" r:%g", p->u.r);
  78147. #endif
  78148. }else if( sqlite3VdbeMemIsRowSet(p) ){
  78149. printf(" (rowset)");
  78150. }else{
  78151. char zBuf[200];
  78152. sqlite3VdbeMemPrettyPrint(p, zBuf);
  78153. printf(" %s", zBuf);
  78154. }
  78155. if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
  78156. }
  78157. static void registerTrace(int iReg, Mem *p){
  78158. printf("REG[%d] = ", iReg);
  78159. memTracePrint(p);
  78160. printf("\n");
  78161. sqlite3VdbeCheckMemInvariants(p);
  78162. }
  78163. #endif
  78164. #ifdef SQLITE_DEBUG
  78165. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  78166. #else
  78167. # define REGISTER_TRACE(R,M)
  78168. #endif
  78169. #ifdef VDBE_PROFILE
  78170. /*
  78171. ** hwtime.h contains inline assembler code for implementing
  78172. ** high-performance timing routines.
  78173. */
  78174. /************** Include hwtime.h in the middle of vdbe.c *********************/
  78175. /************** Begin file hwtime.h ******************************************/
  78176. /*
  78177. ** 2008 May 27
  78178. **
  78179. ** The author disclaims copyright to this source code. In place of
  78180. ** a legal notice, here is a blessing:
  78181. **
  78182. ** May you do good and not evil.
  78183. ** May you find forgiveness for yourself and forgive others.
  78184. ** May you share freely, never taking more than you give.
  78185. **
  78186. ******************************************************************************
  78187. **
  78188. ** This file contains inline asm code for retrieving "high-performance"
  78189. ** counters for x86 class CPUs.
  78190. */
  78191. #ifndef SQLITE_HWTIME_H
  78192. #define SQLITE_HWTIME_H
  78193. /*
  78194. ** The following routine only works on pentium-class (or newer) processors.
  78195. ** It uses the RDTSC opcode to read the cycle count value out of the
  78196. ** processor and returns that value. This can be used for high-res
  78197. ** profiling.
  78198. */
  78199. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  78200. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  78201. #if defined(__GNUC__)
  78202. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  78203. unsigned int lo, hi;
  78204. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  78205. return (sqlite_uint64)hi << 32 | lo;
  78206. }
  78207. #elif defined(_MSC_VER)
  78208. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  78209. __asm {
  78210. rdtsc
  78211. ret ; return value at EDX:EAX
  78212. }
  78213. }
  78214. #endif
  78215. #elif (defined(__GNUC__) && defined(__x86_64__))
  78216. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  78217. unsigned long val;
  78218. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  78219. return val;
  78220. }
  78221. #elif (defined(__GNUC__) && defined(__ppc__))
  78222. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  78223. unsigned long long retval;
  78224. unsigned long junk;
  78225. __asm__ __volatile__ ("\n\
  78226. 1: mftbu %1\n\
  78227. mftb %L0\n\
  78228. mftbu %0\n\
  78229. cmpw %0,%1\n\
  78230. bne 1b"
  78231. : "=r" (retval), "=r" (junk));
  78232. return retval;
  78233. }
  78234. #else
  78235. #error Need implementation of sqlite3Hwtime() for your platform.
  78236. /*
  78237. ** To compile without implementing sqlite3Hwtime() for your platform,
  78238. ** you can remove the above #error and use the following
  78239. ** stub function. You will lose timing support for many
  78240. ** of the debugging and testing utilities, but it should at
  78241. ** least compile and run.
  78242. */
  78243. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  78244. #endif
  78245. #endif /* !defined(SQLITE_HWTIME_H) */
  78246. /************** End of hwtime.h **********************************************/
  78247. /************** Continuing where we left off in vdbe.c ***********************/
  78248. #endif
  78249. #ifndef NDEBUG
  78250. /*
  78251. ** This function is only called from within an assert() expression. It
  78252. ** checks that the sqlite3.nTransaction variable is correctly set to
  78253. ** the number of non-transaction savepoints currently in the
  78254. ** linked list starting at sqlite3.pSavepoint.
  78255. **
  78256. ** Usage:
  78257. **
  78258. ** assert( checkSavepointCount(db) );
  78259. */
  78260. static int checkSavepointCount(sqlite3 *db){
  78261. int n = 0;
  78262. Savepoint *p;
  78263. for(p=db->pSavepoint; p; p=p->pNext) n++;
  78264. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  78265. return 1;
  78266. }
  78267. #endif
  78268. /*
  78269. ** Return the register of pOp->p2 after first preparing it to be
  78270. ** overwritten with an integer value.
  78271. */
  78272. static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
  78273. sqlite3VdbeMemSetNull(pOut);
  78274. pOut->flags = MEM_Int;
  78275. return pOut;
  78276. }
  78277. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  78278. Mem *pOut;
  78279. assert( pOp->p2>0 );
  78280. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  78281. pOut = &p->aMem[pOp->p2];
  78282. memAboutToChange(p, pOut);
  78283. if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
  78284. return out2PrereleaseWithClear(pOut);
  78285. }else{
  78286. pOut->flags = MEM_Int;
  78287. return pOut;
  78288. }
  78289. }
  78290. /*
  78291. ** Execute as much of a VDBE program as we can.
  78292. ** This is the core of sqlite3_step().
  78293. */
  78294. SQLITE_PRIVATE int sqlite3VdbeExec(
  78295. Vdbe *p /* The VDBE */
  78296. ){
  78297. Op *aOp = p->aOp; /* Copy of p->aOp */
  78298. Op *pOp = aOp; /* Current operation */
  78299. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  78300. Op *pOrigOp; /* Value of pOp at the top of the loop */
  78301. #endif
  78302. #ifdef SQLITE_DEBUG
  78303. int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
  78304. #endif
  78305. int rc = SQLITE_OK; /* Value to return */
  78306. sqlite3 *db = p->db; /* The database */
  78307. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  78308. u8 encoding = ENC(db); /* The database encoding */
  78309. int iCompare = 0; /* Result of last comparison */
  78310. unsigned nVmStep = 0; /* Number of virtual machine steps */
  78311. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  78312. unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
  78313. #endif
  78314. Mem *aMem = p->aMem; /* Copy of p->aMem */
  78315. Mem *pIn1 = 0; /* 1st input operand */
  78316. Mem *pIn2 = 0; /* 2nd input operand */
  78317. Mem *pIn3 = 0; /* 3rd input operand */
  78318. Mem *pOut = 0; /* Output operand */
  78319. #ifdef VDBE_PROFILE
  78320. u64 start; /* CPU clock count at start of opcode */
  78321. #endif
  78322. /*** INSERT STACK UNION HERE ***/
  78323. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  78324. sqlite3VdbeEnter(p);
  78325. if( p->rc==SQLITE_NOMEM ){
  78326. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  78327. ** sqlite3_column_text16() failed. */
  78328. goto no_mem;
  78329. }
  78330. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  78331. assert( p->bIsReader || p->readOnly!=0 );
  78332. p->iCurrentTime = 0;
  78333. assert( p->explain==0 );
  78334. p->pResultSet = 0;
  78335. db->busyHandler.nBusy = 0;
  78336. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  78337. sqlite3VdbeIOTraceSql(p);
  78338. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  78339. if( db->xProgress ){
  78340. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  78341. assert( 0 < db->nProgressOps );
  78342. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  78343. }else{
  78344. nProgressLimit = 0xffffffff;
  78345. }
  78346. #endif
  78347. #ifdef SQLITE_DEBUG
  78348. sqlite3BeginBenignMalloc();
  78349. if( p->pc==0
  78350. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  78351. ){
  78352. int i;
  78353. int once = 1;
  78354. sqlite3VdbePrintSql(p);
  78355. if( p->db->flags & SQLITE_VdbeListing ){
  78356. printf("VDBE Program Listing:\n");
  78357. for(i=0; i<p->nOp; i++){
  78358. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  78359. }
  78360. }
  78361. if( p->db->flags & SQLITE_VdbeEQP ){
  78362. for(i=0; i<p->nOp; i++){
  78363. if( aOp[i].opcode==OP_Explain ){
  78364. if( once ) printf("VDBE Query Plan:\n");
  78365. printf("%s\n", aOp[i].p4.z);
  78366. once = 0;
  78367. }
  78368. }
  78369. }
  78370. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  78371. }
  78372. sqlite3EndBenignMalloc();
  78373. #endif
  78374. for(pOp=&aOp[p->pc]; 1; pOp++){
  78375. /* Errors are detected by individual opcodes, with an immediate
  78376. ** jumps to abort_due_to_error. */
  78377. assert( rc==SQLITE_OK );
  78378. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  78379. #ifdef VDBE_PROFILE
  78380. start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  78381. #endif
  78382. nVmStep++;
  78383. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  78384. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  78385. #endif
  78386. /* Only allow tracing if SQLITE_DEBUG is defined.
  78387. */
  78388. #ifdef SQLITE_DEBUG
  78389. if( db->flags & SQLITE_VdbeTrace ){
  78390. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  78391. }
  78392. #endif
  78393. /* Check to see if we need to simulate an interrupt. This only happens
  78394. ** if we have a special test build.
  78395. */
  78396. #ifdef SQLITE_TEST
  78397. if( sqlite3_interrupt_count>0 ){
  78398. sqlite3_interrupt_count--;
  78399. if( sqlite3_interrupt_count==0 ){
  78400. sqlite3_interrupt(db);
  78401. }
  78402. }
  78403. #endif
  78404. /* Sanity checking on other operands */
  78405. #ifdef SQLITE_DEBUG
  78406. {
  78407. u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
  78408. if( (opProperty & OPFLG_IN1)!=0 ){
  78409. assert( pOp->p1>0 );
  78410. assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
  78411. assert( memIsValid(&aMem[pOp->p1]) );
  78412. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  78413. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  78414. }
  78415. if( (opProperty & OPFLG_IN2)!=0 ){
  78416. assert( pOp->p2>0 );
  78417. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  78418. assert( memIsValid(&aMem[pOp->p2]) );
  78419. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  78420. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  78421. }
  78422. if( (opProperty & OPFLG_IN3)!=0 ){
  78423. assert( pOp->p3>0 );
  78424. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  78425. assert( memIsValid(&aMem[pOp->p3]) );
  78426. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  78427. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  78428. }
  78429. if( (opProperty & OPFLG_OUT2)!=0 ){
  78430. assert( pOp->p2>0 );
  78431. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  78432. memAboutToChange(p, &aMem[pOp->p2]);
  78433. }
  78434. if( (opProperty & OPFLG_OUT3)!=0 ){
  78435. assert( pOp->p3>0 );
  78436. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  78437. memAboutToChange(p, &aMem[pOp->p3]);
  78438. }
  78439. }
  78440. #endif
  78441. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  78442. pOrigOp = pOp;
  78443. #endif
  78444. switch( pOp->opcode ){
  78445. /*****************************************************************************
  78446. ** What follows is a massive switch statement where each case implements a
  78447. ** separate instruction in the virtual machine. If we follow the usual
  78448. ** indentation conventions, each case should be indented by 6 spaces. But
  78449. ** that is a lot of wasted space on the left margin. So the code within
  78450. ** the switch statement will break with convention and be flush-left. Another
  78451. ** big comment (similar to this one) will mark the point in the code where
  78452. ** we transition back to normal indentation.
  78453. **
  78454. ** The formatting of each case is important. The makefile for SQLite
  78455. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  78456. ** file looking for lines that begin with "case OP_". The opcodes.h files
  78457. ** will be filled with #defines that give unique integer values to each
  78458. ** opcode and the opcodes.c file is filled with an array of strings where
  78459. ** each string is the symbolic name for the corresponding opcode. If the
  78460. ** case statement is followed by a comment of the form "/# same as ... #/"
  78461. ** that comment is used to determine the particular value of the opcode.
  78462. **
  78463. ** Other keywords in the comment that follows each case are used to
  78464. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  78465. ** Keywords include: in1, in2, in3, out2, out3. See
  78466. ** the mkopcodeh.awk script for additional information.
  78467. **
  78468. ** Documentation about VDBE opcodes is generated by scanning this file
  78469. ** for lines of that contain "Opcode:". That line and all subsequent
  78470. ** comment lines are used in the generation of the opcode.html documentation
  78471. ** file.
  78472. **
  78473. ** SUMMARY:
  78474. **
  78475. ** Formatting is important to scripts that scan this file.
  78476. ** Do not deviate from the formatting style currently in use.
  78477. **
  78478. *****************************************************************************/
  78479. /* Opcode: Goto * P2 * * *
  78480. **
  78481. ** An unconditional jump to address P2.
  78482. ** The next instruction executed will be
  78483. ** the one at index P2 from the beginning of
  78484. ** the program.
  78485. **
  78486. ** The P1 parameter is not actually used by this opcode. However, it
  78487. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  78488. ** that this Goto is the bottom of a loop and that the lines from P2 down
  78489. ** to the current line should be indented for EXPLAIN output.
  78490. */
  78491. case OP_Goto: { /* jump */
  78492. jump_to_p2_and_check_for_interrupt:
  78493. pOp = &aOp[pOp->p2 - 1];
  78494. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  78495. ** OP_VNext, or OP_SorterNext) all jump here upon
  78496. ** completion. Check to see if sqlite3_interrupt() has been called
  78497. ** or if the progress callback needs to be invoked.
  78498. **
  78499. ** This code uses unstructured "goto" statements and does not look clean.
  78500. ** But that is not due to sloppy coding habits. The code is written this
  78501. ** way for performance, to avoid having to run the interrupt and progress
  78502. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  78503. ** faster according to "valgrind --tool=cachegrind" */
  78504. check_for_interrupt:
  78505. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  78506. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  78507. /* Call the progress callback if it is configured and the required number
  78508. ** of VDBE ops have been executed (either since this invocation of
  78509. ** sqlite3VdbeExec() or since last time the progress callback was called).
  78510. ** If the progress callback returns non-zero, exit the virtual machine with
  78511. ** a return code SQLITE_ABORT.
  78512. */
  78513. if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
  78514. assert( db->nProgressOps!=0 );
  78515. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  78516. if( db->xProgress(db->pProgressArg) ){
  78517. rc = SQLITE_INTERRUPT;
  78518. goto abort_due_to_error;
  78519. }
  78520. }
  78521. #endif
  78522. break;
  78523. }
  78524. /* Opcode: Gosub P1 P2 * * *
  78525. **
  78526. ** Write the current address onto register P1
  78527. ** and then jump to address P2.
  78528. */
  78529. case OP_Gosub: { /* jump */
  78530. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  78531. pIn1 = &aMem[pOp->p1];
  78532. assert( VdbeMemDynamic(pIn1)==0 );
  78533. memAboutToChange(p, pIn1);
  78534. pIn1->flags = MEM_Int;
  78535. pIn1->u.i = (int)(pOp-aOp);
  78536. REGISTER_TRACE(pOp->p1, pIn1);
  78537. /* Most jump operations do a goto to this spot in order to update
  78538. ** the pOp pointer. */
  78539. jump_to_p2:
  78540. pOp = &aOp[pOp->p2 - 1];
  78541. break;
  78542. }
  78543. /* Opcode: Return P1 * * * *
  78544. **
  78545. ** Jump to the next instruction after the address in register P1. After
  78546. ** the jump, register P1 becomes undefined.
  78547. */
  78548. case OP_Return: { /* in1 */
  78549. pIn1 = &aMem[pOp->p1];
  78550. assert( pIn1->flags==MEM_Int );
  78551. pOp = &aOp[pIn1->u.i];
  78552. pIn1->flags = MEM_Undefined;
  78553. break;
  78554. }
  78555. /* Opcode: InitCoroutine P1 P2 P3 * *
  78556. **
  78557. ** Set up register P1 so that it will Yield to the coroutine
  78558. ** located at address P3.
  78559. **
  78560. ** If P2!=0 then the coroutine implementation immediately follows
  78561. ** this opcode. So jump over the coroutine implementation to
  78562. ** address P2.
  78563. **
  78564. ** See also: EndCoroutine
  78565. */
  78566. case OP_InitCoroutine: { /* jump */
  78567. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  78568. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  78569. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  78570. pOut = &aMem[pOp->p1];
  78571. assert( !VdbeMemDynamic(pOut) );
  78572. pOut->u.i = pOp->p3 - 1;
  78573. pOut->flags = MEM_Int;
  78574. if( pOp->p2 ) goto jump_to_p2;
  78575. break;
  78576. }
  78577. /* Opcode: EndCoroutine P1 * * * *
  78578. **
  78579. ** The instruction at the address in register P1 is a Yield.
  78580. ** Jump to the P2 parameter of that Yield.
  78581. ** After the jump, register P1 becomes undefined.
  78582. **
  78583. ** See also: InitCoroutine
  78584. */
  78585. case OP_EndCoroutine: { /* in1 */
  78586. VdbeOp *pCaller;
  78587. pIn1 = &aMem[pOp->p1];
  78588. assert( pIn1->flags==MEM_Int );
  78589. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  78590. pCaller = &aOp[pIn1->u.i];
  78591. assert( pCaller->opcode==OP_Yield );
  78592. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  78593. pOp = &aOp[pCaller->p2 - 1];
  78594. pIn1->flags = MEM_Undefined;
  78595. break;
  78596. }
  78597. /* Opcode: Yield P1 P2 * * *
  78598. **
  78599. ** Swap the program counter with the value in register P1. This
  78600. ** has the effect of yielding to a coroutine.
  78601. **
  78602. ** If the coroutine that is launched by this instruction ends with
  78603. ** Yield or Return then continue to the next instruction. But if
  78604. ** the coroutine launched by this instruction ends with
  78605. ** EndCoroutine, then jump to P2 rather than continuing with the
  78606. ** next instruction.
  78607. **
  78608. ** See also: InitCoroutine
  78609. */
  78610. case OP_Yield: { /* in1, jump */
  78611. int pcDest;
  78612. pIn1 = &aMem[pOp->p1];
  78613. assert( VdbeMemDynamic(pIn1)==0 );
  78614. pIn1->flags = MEM_Int;
  78615. pcDest = (int)pIn1->u.i;
  78616. pIn1->u.i = (int)(pOp - aOp);
  78617. REGISTER_TRACE(pOp->p1, pIn1);
  78618. pOp = &aOp[pcDest];
  78619. break;
  78620. }
  78621. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  78622. ** Synopsis: if r[P3]=null halt
  78623. **
  78624. ** Check the value in register P3. If it is NULL then Halt using
  78625. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  78626. ** value in register P3 is not NULL, then this routine is a no-op.
  78627. ** The P5 parameter should be 1.
  78628. */
  78629. case OP_HaltIfNull: { /* in3 */
  78630. pIn3 = &aMem[pOp->p3];
  78631. #ifdef SQLITE_DEBUG
  78632. if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
  78633. #endif
  78634. if( (pIn3->flags & MEM_Null)==0 ) break;
  78635. /* Fall through into OP_Halt */
  78636. }
  78637. /* Opcode: Halt P1 P2 * P4 P5
  78638. **
  78639. ** Exit immediately. All open cursors, etc are closed
  78640. ** automatically.
  78641. **
  78642. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  78643. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  78644. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  78645. ** whether or not to rollback the current transaction. Do not rollback
  78646. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  78647. ** then back out all changes that have occurred during this execution of the
  78648. ** VDBE, but do not rollback the transaction.
  78649. **
  78650. ** If P4 is not null then it is an error message string.
  78651. **
  78652. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  78653. **
  78654. ** 0: (no change)
  78655. ** 1: NOT NULL contraint failed: P4
  78656. ** 2: UNIQUE constraint failed: P4
  78657. ** 3: CHECK constraint failed: P4
  78658. ** 4: FOREIGN KEY constraint failed: P4
  78659. **
  78660. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  78661. ** omitted.
  78662. **
  78663. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  78664. ** every program. So a jump past the last instruction of the program
  78665. ** is the same as executing Halt.
  78666. */
  78667. case OP_Halt: {
  78668. VdbeFrame *pFrame;
  78669. int pcx;
  78670. pcx = (int)(pOp - aOp);
  78671. #ifdef SQLITE_DEBUG
  78672. if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
  78673. #endif
  78674. if( pOp->p1==SQLITE_OK && p->pFrame ){
  78675. /* Halt the sub-program. Return control to the parent frame. */
  78676. pFrame = p->pFrame;
  78677. p->pFrame = pFrame->pParent;
  78678. p->nFrame--;
  78679. sqlite3VdbeSetChanges(db, p->nChange);
  78680. pcx = sqlite3VdbeFrameRestore(pFrame);
  78681. if( pOp->p2==OE_Ignore ){
  78682. /* Instruction pcx is the OP_Program that invoked the sub-program
  78683. ** currently being halted. If the p2 instruction of this OP_Halt
  78684. ** instruction is set to OE_Ignore, then the sub-program is throwing
  78685. ** an IGNORE exception. In this case jump to the address specified
  78686. ** as the p2 of the calling OP_Program. */
  78687. pcx = p->aOp[pcx].p2-1;
  78688. }
  78689. aOp = p->aOp;
  78690. aMem = p->aMem;
  78691. pOp = &aOp[pcx];
  78692. break;
  78693. }
  78694. p->rc = pOp->p1;
  78695. p->errorAction = (u8)pOp->p2;
  78696. p->pc = pcx;
  78697. assert( pOp->p5<=4 );
  78698. if( p->rc ){
  78699. if( pOp->p5 ){
  78700. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  78701. "FOREIGN KEY" };
  78702. testcase( pOp->p5==1 );
  78703. testcase( pOp->p5==2 );
  78704. testcase( pOp->p5==3 );
  78705. testcase( pOp->p5==4 );
  78706. sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
  78707. if( pOp->p4.z ){
  78708. p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
  78709. }
  78710. }else{
  78711. sqlite3VdbeError(p, "%s", pOp->p4.z);
  78712. }
  78713. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
  78714. }
  78715. rc = sqlite3VdbeHalt(p);
  78716. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  78717. if( rc==SQLITE_BUSY ){
  78718. p->rc = SQLITE_BUSY;
  78719. }else{
  78720. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  78721. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  78722. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  78723. }
  78724. goto vdbe_return;
  78725. }
  78726. /* Opcode: Integer P1 P2 * * *
  78727. ** Synopsis: r[P2]=P1
  78728. **
  78729. ** The 32-bit integer value P1 is written into register P2.
  78730. */
  78731. case OP_Integer: { /* out2 */
  78732. pOut = out2Prerelease(p, pOp);
  78733. pOut->u.i = pOp->p1;
  78734. break;
  78735. }
  78736. /* Opcode: Int64 * P2 * P4 *
  78737. ** Synopsis: r[P2]=P4
  78738. **
  78739. ** P4 is a pointer to a 64-bit integer value.
  78740. ** Write that value into register P2.
  78741. */
  78742. case OP_Int64: { /* out2 */
  78743. pOut = out2Prerelease(p, pOp);
  78744. assert( pOp->p4.pI64!=0 );
  78745. pOut->u.i = *pOp->p4.pI64;
  78746. break;
  78747. }
  78748. #ifndef SQLITE_OMIT_FLOATING_POINT
  78749. /* Opcode: Real * P2 * P4 *
  78750. ** Synopsis: r[P2]=P4
  78751. **
  78752. ** P4 is a pointer to a 64-bit floating point value.
  78753. ** Write that value into register P2.
  78754. */
  78755. case OP_Real: { /* same as TK_FLOAT, out2 */
  78756. pOut = out2Prerelease(p, pOp);
  78757. pOut->flags = MEM_Real;
  78758. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  78759. pOut->u.r = *pOp->p4.pReal;
  78760. break;
  78761. }
  78762. #endif
  78763. /* Opcode: String8 * P2 * P4 *
  78764. ** Synopsis: r[P2]='P4'
  78765. **
  78766. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  78767. ** into a String opcode before it is executed for the first time. During
  78768. ** this transformation, the length of string P4 is computed and stored
  78769. ** as the P1 parameter.
  78770. */
  78771. case OP_String8: { /* same as TK_STRING, out2 */
  78772. assert( pOp->p4.z!=0 );
  78773. pOut = out2Prerelease(p, pOp);
  78774. pOp->opcode = OP_String;
  78775. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  78776. #ifndef SQLITE_OMIT_UTF16
  78777. if( encoding!=SQLITE_UTF8 ){
  78778. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  78779. assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
  78780. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  78781. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  78782. assert( VdbeMemDynamic(pOut)==0 );
  78783. pOut->szMalloc = 0;
  78784. pOut->flags |= MEM_Static;
  78785. if( pOp->p4type==P4_DYNAMIC ){
  78786. sqlite3DbFree(db, pOp->p4.z);
  78787. }
  78788. pOp->p4type = P4_DYNAMIC;
  78789. pOp->p4.z = pOut->z;
  78790. pOp->p1 = pOut->n;
  78791. }
  78792. testcase( rc==SQLITE_TOOBIG );
  78793. #endif
  78794. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  78795. goto too_big;
  78796. }
  78797. assert( rc==SQLITE_OK );
  78798. /* Fall through to the next case, OP_String */
  78799. }
  78800. /* Opcode: String P1 P2 P3 P4 P5
  78801. ** Synopsis: r[P2]='P4' (len=P1)
  78802. **
  78803. ** The string value P4 of length P1 (bytes) is stored in register P2.
  78804. **
  78805. ** If P3 is not zero and the content of register P3 is equal to P5, then
  78806. ** the datatype of the register P2 is converted to BLOB. The content is
  78807. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  78808. ** of a string, as if it had been CAST. In other words:
  78809. **
  78810. ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
  78811. */
  78812. case OP_String: { /* out2 */
  78813. assert( pOp->p4.z!=0 );
  78814. pOut = out2Prerelease(p, pOp);
  78815. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  78816. pOut->z = pOp->p4.z;
  78817. pOut->n = pOp->p1;
  78818. pOut->enc = encoding;
  78819. UPDATE_MAX_BLOBSIZE(pOut);
  78820. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  78821. if( pOp->p3>0 ){
  78822. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  78823. pIn3 = &aMem[pOp->p3];
  78824. assert( pIn3->flags & MEM_Int );
  78825. if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  78826. }
  78827. #endif
  78828. break;
  78829. }
  78830. /* Opcode: Null P1 P2 P3 * *
  78831. ** Synopsis: r[P2..P3]=NULL
  78832. **
  78833. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  78834. ** NULL into register P3 and every register in between P2 and P3. If P3
  78835. ** is less than P2 (typically P3 is zero) then only register P2 is
  78836. ** set to NULL.
  78837. **
  78838. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  78839. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  78840. ** OP_Ne or OP_Eq.
  78841. */
  78842. case OP_Null: { /* out2 */
  78843. int cnt;
  78844. u16 nullFlag;
  78845. pOut = out2Prerelease(p, pOp);
  78846. cnt = pOp->p3-pOp->p2;
  78847. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  78848. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  78849. pOut->n = 0;
  78850. #ifdef SQLITE_DEBUG
  78851. pOut->uTemp = 0;
  78852. #endif
  78853. while( cnt>0 ){
  78854. pOut++;
  78855. memAboutToChange(p, pOut);
  78856. sqlite3VdbeMemSetNull(pOut);
  78857. pOut->flags = nullFlag;
  78858. pOut->n = 0;
  78859. cnt--;
  78860. }
  78861. break;
  78862. }
  78863. /* Opcode: SoftNull P1 * * * *
  78864. ** Synopsis: r[P1]=NULL
  78865. **
  78866. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  78867. ** instruction, but do not free any string or blob memory associated with
  78868. ** the register, so that if the value was a string or blob that was
  78869. ** previously copied using OP_SCopy, the copies will continue to be valid.
  78870. */
  78871. case OP_SoftNull: {
  78872. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  78873. pOut = &aMem[pOp->p1];
  78874. pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
  78875. break;
  78876. }
  78877. /* Opcode: Blob P1 P2 * P4 *
  78878. ** Synopsis: r[P2]=P4 (len=P1)
  78879. **
  78880. ** P4 points to a blob of data P1 bytes long. Store this
  78881. ** blob in register P2.
  78882. */
  78883. case OP_Blob: { /* out2 */
  78884. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  78885. pOut = out2Prerelease(p, pOp);
  78886. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  78887. pOut->enc = encoding;
  78888. UPDATE_MAX_BLOBSIZE(pOut);
  78889. break;
  78890. }
  78891. /* Opcode: Variable P1 P2 * P4 *
  78892. ** Synopsis: r[P2]=parameter(P1,P4)
  78893. **
  78894. ** Transfer the values of bound parameter P1 into register P2
  78895. **
  78896. ** If the parameter is named, then its name appears in P4.
  78897. ** The P4 value is used by sqlite3_bind_parameter_name().
  78898. */
  78899. case OP_Variable: { /* out2 */
  78900. Mem *pVar; /* Value being transferred */
  78901. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  78902. assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
  78903. pVar = &p->aVar[pOp->p1 - 1];
  78904. if( sqlite3VdbeMemTooBig(pVar) ){
  78905. goto too_big;
  78906. }
  78907. pOut = &aMem[pOp->p2];
  78908. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  78909. UPDATE_MAX_BLOBSIZE(pOut);
  78910. break;
  78911. }
  78912. /* Opcode: Move P1 P2 P3 * *
  78913. ** Synopsis: r[P2@P3]=r[P1@P3]
  78914. **
  78915. ** Move the P3 values in register P1..P1+P3-1 over into
  78916. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  78917. ** left holding a NULL. It is an error for register ranges
  78918. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  78919. ** for P3 to be less than 1.
  78920. */
  78921. case OP_Move: {
  78922. int n; /* Number of registers left to copy */
  78923. int p1; /* Register to copy from */
  78924. int p2; /* Register to copy to */
  78925. n = pOp->p3;
  78926. p1 = pOp->p1;
  78927. p2 = pOp->p2;
  78928. assert( n>0 && p1>0 && p2>0 );
  78929. assert( p1+n<=p2 || p2+n<=p1 );
  78930. pIn1 = &aMem[p1];
  78931. pOut = &aMem[p2];
  78932. do{
  78933. assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
  78934. assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
  78935. assert( memIsValid(pIn1) );
  78936. memAboutToChange(p, pOut);
  78937. sqlite3VdbeMemMove(pOut, pIn1);
  78938. #ifdef SQLITE_DEBUG
  78939. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  78940. pOut->pScopyFrom += pOp->p2 - p1;
  78941. }
  78942. #endif
  78943. Deephemeralize(pOut);
  78944. REGISTER_TRACE(p2++, pOut);
  78945. pIn1++;
  78946. pOut++;
  78947. }while( --n );
  78948. break;
  78949. }
  78950. /* Opcode: Copy P1 P2 P3 * *
  78951. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  78952. **
  78953. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  78954. **
  78955. ** This instruction makes a deep copy of the value. A duplicate
  78956. ** is made of any string or blob constant. See also OP_SCopy.
  78957. */
  78958. case OP_Copy: {
  78959. int n;
  78960. n = pOp->p3;
  78961. pIn1 = &aMem[pOp->p1];
  78962. pOut = &aMem[pOp->p2];
  78963. assert( pOut!=pIn1 );
  78964. while( 1 ){
  78965. memAboutToChange(p, pOut);
  78966. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  78967. Deephemeralize(pOut);
  78968. #ifdef SQLITE_DEBUG
  78969. pOut->pScopyFrom = 0;
  78970. #endif
  78971. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  78972. if( (n--)==0 ) break;
  78973. pOut++;
  78974. pIn1++;
  78975. }
  78976. break;
  78977. }
  78978. /* Opcode: SCopy P1 P2 * * *
  78979. ** Synopsis: r[P2]=r[P1]
  78980. **
  78981. ** Make a shallow copy of register P1 into register P2.
  78982. **
  78983. ** This instruction makes a shallow copy of the value. If the value
  78984. ** is a string or blob, then the copy is only a pointer to the
  78985. ** original and hence if the original changes so will the copy.
  78986. ** Worse, if the original is deallocated, the copy becomes invalid.
  78987. ** Thus the program must guarantee that the original will not change
  78988. ** during the lifetime of the copy. Use OP_Copy to make a complete
  78989. ** copy.
  78990. */
  78991. case OP_SCopy: { /* out2 */
  78992. pIn1 = &aMem[pOp->p1];
  78993. pOut = &aMem[pOp->p2];
  78994. assert( pOut!=pIn1 );
  78995. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  78996. #ifdef SQLITE_DEBUG
  78997. pOut->pScopyFrom = pIn1;
  78998. pOut->mScopyFlags = pIn1->flags;
  78999. #endif
  79000. break;
  79001. }
  79002. /* Opcode: IntCopy P1 P2 * * *
  79003. ** Synopsis: r[P2]=r[P1]
  79004. **
  79005. ** Transfer the integer value held in register P1 into register P2.
  79006. **
  79007. ** This is an optimized version of SCopy that works only for integer
  79008. ** values.
  79009. */
  79010. case OP_IntCopy: { /* out2 */
  79011. pIn1 = &aMem[pOp->p1];
  79012. assert( (pIn1->flags & MEM_Int)!=0 );
  79013. pOut = &aMem[pOp->p2];
  79014. sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
  79015. break;
  79016. }
  79017. /* Opcode: ResultRow P1 P2 * * *
  79018. ** Synopsis: output=r[P1@P2]
  79019. **
  79020. ** The registers P1 through P1+P2-1 contain a single row of
  79021. ** results. This opcode causes the sqlite3_step() call to terminate
  79022. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  79023. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  79024. ** the result row.
  79025. */
  79026. case OP_ResultRow: {
  79027. Mem *pMem;
  79028. int i;
  79029. assert( p->nResColumn==pOp->p2 );
  79030. assert( pOp->p1>0 );
  79031. assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
  79032. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  79033. /* Run the progress counter just before returning.
  79034. */
  79035. if( db->xProgress!=0
  79036. && nVmStep>=nProgressLimit
  79037. && db->xProgress(db->pProgressArg)!=0
  79038. ){
  79039. rc = SQLITE_INTERRUPT;
  79040. goto abort_due_to_error;
  79041. }
  79042. #endif
  79043. /* If this statement has violated immediate foreign key constraints, do
  79044. ** not return the number of rows modified. And do not RELEASE the statement
  79045. ** transaction. It needs to be rolled back. */
  79046. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  79047. assert( db->flags&SQLITE_CountRows );
  79048. assert( p->usesStmtJournal );
  79049. goto abort_due_to_error;
  79050. }
  79051. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  79052. ** DML statements invoke this opcode to return the number of rows
  79053. ** modified to the user. This is the only way that a VM that
  79054. ** opens a statement transaction may invoke this opcode.
  79055. **
  79056. ** In case this is such a statement, close any statement transaction
  79057. ** opened by this VM before returning control to the user. This is to
  79058. ** ensure that statement-transactions are always nested, not overlapping.
  79059. ** If the open statement-transaction is not closed here, then the user
  79060. ** may step another VM that opens its own statement transaction. This
  79061. ** may lead to overlapping statement transactions.
  79062. **
  79063. ** The statement transaction is never a top-level transaction. Hence
  79064. ** the RELEASE call below can never fail.
  79065. */
  79066. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  79067. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  79068. assert( rc==SQLITE_OK );
  79069. /* Invalidate all ephemeral cursor row caches */
  79070. p->cacheCtr = (p->cacheCtr + 2)|1;
  79071. /* Make sure the results of the current row are \000 terminated
  79072. ** and have an assigned type. The results are de-ephemeralized as
  79073. ** a side effect.
  79074. */
  79075. pMem = p->pResultSet = &aMem[pOp->p1];
  79076. for(i=0; i<pOp->p2; i++){
  79077. assert( memIsValid(&pMem[i]) );
  79078. Deephemeralize(&pMem[i]);
  79079. assert( (pMem[i].flags & MEM_Ephem)==0
  79080. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  79081. sqlite3VdbeMemNulTerminate(&pMem[i]);
  79082. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  79083. }
  79084. if( db->mallocFailed ) goto no_mem;
  79085. if( db->mTrace & SQLITE_TRACE_ROW ){
  79086. db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
  79087. }
  79088. /* Return SQLITE_ROW
  79089. */
  79090. p->pc = (int)(pOp - aOp) + 1;
  79091. rc = SQLITE_ROW;
  79092. goto vdbe_return;
  79093. }
  79094. /* Opcode: Concat P1 P2 P3 * *
  79095. ** Synopsis: r[P3]=r[P2]+r[P1]
  79096. **
  79097. ** Add the text in register P1 onto the end of the text in
  79098. ** register P2 and store the result in register P3.
  79099. ** If either the P1 or P2 text are NULL then store NULL in P3.
  79100. **
  79101. ** P3 = P2 || P1
  79102. **
  79103. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  79104. ** if P3 is the same register as P2, the implementation is able
  79105. ** to avoid a memcpy().
  79106. */
  79107. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  79108. i64 nByte;
  79109. pIn1 = &aMem[pOp->p1];
  79110. pIn2 = &aMem[pOp->p2];
  79111. pOut = &aMem[pOp->p3];
  79112. assert( pIn1!=pOut );
  79113. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  79114. sqlite3VdbeMemSetNull(pOut);
  79115. break;
  79116. }
  79117. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  79118. Stringify(pIn1, encoding);
  79119. Stringify(pIn2, encoding);
  79120. nByte = pIn1->n + pIn2->n;
  79121. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  79122. goto too_big;
  79123. }
  79124. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  79125. goto no_mem;
  79126. }
  79127. MemSetTypeFlag(pOut, MEM_Str);
  79128. if( pOut!=pIn2 ){
  79129. memcpy(pOut->z, pIn2->z, pIn2->n);
  79130. }
  79131. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  79132. pOut->z[nByte]=0;
  79133. pOut->z[nByte+1] = 0;
  79134. pOut->flags |= MEM_Term;
  79135. pOut->n = (int)nByte;
  79136. pOut->enc = encoding;
  79137. UPDATE_MAX_BLOBSIZE(pOut);
  79138. break;
  79139. }
  79140. /* Opcode: Add P1 P2 P3 * *
  79141. ** Synopsis: r[P3]=r[P1]+r[P2]
  79142. **
  79143. ** Add the value in register P1 to the value in register P2
  79144. ** and store the result in register P3.
  79145. ** If either input is NULL, the result is NULL.
  79146. */
  79147. /* Opcode: Multiply P1 P2 P3 * *
  79148. ** Synopsis: r[P3]=r[P1]*r[P2]
  79149. **
  79150. **
  79151. ** Multiply the value in register P1 by the value in register P2
  79152. ** and store the result in register P3.
  79153. ** If either input is NULL, the result is NULL.
  79154. */
  79155. /* Opcode: Subtract P1 P2 P3 * *
  79156. ** Synopsis: r[P3]=r[P2]-r[P1]
  79157. **
  79158. ** Subtract the value in register P1 from the value in register P2
  79159. ** and store the result in register P3.
  79160. ** If either input is NULL, the result is NULL.
  79161. */
  79162. /* Opcode: Divide P1 P2 P3 * *
  79163. ** Synopsis: r[P3]=r[P2]/r[P1]
  79164. **
  79165. ** Divide the value in register P1 by the value in register P2
  79166. ** and store the result in register P3 (P3=P2/P1). If the value in
  79167. ** register P1 is zero, then the result is NULL. If either input is
  79168. ** NULL, the result is NULL.
  79169. */
  79170. /* Opcode: Remainder P1 P2 P3 * *
  79171. ** Synopsis: r[P3]=r[P2]%r[P1]
  79172. **
  79173. ** Compute the remainder after integer register P2 is divided by
  79174. ** register P1 and store the result in register P3.
  79175. ** If the value in register P1 is zero the result is NULL.
  79176. ** If either operand is NULL, the result is NULL.
  79177. */
  79178. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  79179. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  79180. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  79181. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  79182. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  79183. char bIntint; /* Started out as two integer operands */
  79184. u16 flags; /* Combined MEM_* flags from both inputs */
  79185. u16 type1; /* Numeric type of left operand */
  79186. u16 type2; /* Numeric type of right operand */
  79187. i64 iA; /* Integer value of left operand */
  79188. i64 iB; /* Integer value of right operand */
  79189. double rA; /* Real value of left operand */
  79190. double rB; /* Real value of right operand */
  79191. pIn1 = &aMem[pOp->p1];
  79192. type1 = numericType(pIn1);
  79193. pIn2 = &aMem[pOp->p2];
  79194. type2 = numericType(pIn2);
  79195. pOut = &aMem[pOp->p3];
  79196. flags = pIn1->flags | pIn2->flags;
  79197. if( (type1 & type2 & MEM_Int)!=0 ){
  79198. iA = pIn1->u.i;
  79199. iB = pIn2->u.i;
  79200. bIntint = 1;
  79201. switch( pOp->opcode ){
  79202. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  79203. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  79204. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  79205. case OP_Divide: {
  79206. if( iA==0 ) goto arithmetic_result_is_null;
  79207. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  79208. iB /= iA;
  79209. break;
  79210. }
  79211. default: {
  79212. if( iA==0 ) goto arithmetic_result_is_null;
  79213. if( iA==-1 ) iA = 1;
  79214. iB %= iA;
  79215. break;
  79216. }
  79217. }
  79218. pOut->u.i = iB;
  79219. MemSetTypeFlag(pOut, MEM_Int);
  79220. }else if( (flags & MEM_Null)!=0 ){
  79221. goto arithmetic_result_is_null;
  79222. }else{
  79223. bIntint = 0;
  79224. fp_math:
  79225. rA = sqlite3VdbeRealValue(pIn1);
  79226. rB = sqlite3VdbeRealValue(pIn2);
  79227. switch( pOp->opcode ){
  79228. case OP_Add: rB += rA; break;
  79229. case OP_Subtract: rB -= rA; break;
  79230. case OP_Multiply: rB *= rA; break;
  79231. case OP_Divide: {
  79232. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  79233. if( rA==(double)0 ) goto arithmetic_result_is_null;
  79234. rB /= rA;
  79235. break;
  79236. }
  79237. default: {
  79238. iA = (i64)rA;
  79239. iB = (i64)rB;
  79240. if( iA==0 ) goto arithmetic_result_is_null;
  79241. if( iA==-1 ) iA = 1;
  79242. rB = (double)(iB % iA);
  79243. break;
  79244. }
  79245. }
  79246. #ifdef SQLITE_OMIT_FLOATING_POINT
  79247. pOut->u.i = rB;
  79248. MemSetTypeFlag(pOut, MEM_Int);
  79249. #else
  79250. if( sqlite3IsNaN(rB) ){
  79251. goto arithmetic_result_is_null;
  79252. }
  79253. pOut->u.r = rB;
  79254. MemSetTypeFlag(pOut, MEM_Real);
  79255. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  79256. sqlite3VdbeIntegerAffinity(pOut);
  79257. }
  79258. #endif
  79259. }
  79260. break;
  79261. arithmetic_result_is_null:
  79262. sqlite3VdbeMemSetNull(pOut);
  79263. break;
  79264. }
  79265. /* Opcode: CollSeq P1 * * P4
  79266. **
  79267. ** P4 is a pointer to a CollSeq object. If the next call to a user function
  79268. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  79269. ** be returned. This is used by the built-in min(), max() and nullif()
  79270. ** functions.
  79271. **
  79272. ** If P1 is not zero, then it is a register that a subsequent min() or
  79273. ** max() aggregate will set to 1 if the current row is not the minimum or
  79274. ** maximum. The P1 register is initialized to 0 by this instruction.
  79275. **
  79276. ** The interface used by the implementation of the aforementioned functions
  79277. ** to retrieve the collation sequence set by this opcode is not available
  79278. ** publicly. Only built-in functions have access to this feature.
  79279. */
  79280. case OP_CollSeq: {
  79281. assert( pOp->p4type==P4_COLLSEQ );
  79282. if( pOp->p1 ){
  79283. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  79284. }
  79285. break;
  79286. }
  79287. /* Opcode: BitAnd P1 P2 P3 * *
  79288. ** Synopsis: r[P3]=r[P1]&r[P2]
  79289. **
  79290. ** Take the bit-wise AND of the values in register P1 and P2 and
  79291. ** store the result in register P3.
  79292. ** If either input is NULL, the result is NULL.
  79293. */
  79294. /* Opcode: BitOr P1 P2 P3 * *
  79295. ** Synopsis: r[P3]=r[P1]|r[P2]
  79296. **
  79297. ** Take the bit-wise OR of the values in register P1 and P2 and
  79298. ** store the result in register P3.
  79299. ** If either input is NULL, the result is NULL.
  79300. */
  79301. /* Opcode: ShiftLeft P1 P2 P3 * *
  79302. ** Synopsis: r[P3]=r[P2]<<r[P1]
  79303. **
  79304. ** Shift the integer value in register P2 to the left by the
  79305. ** number of bits specified by the integer in register P1.
  79306. ** Store the result in register P3.
  79307. ** If either input is NULL, the result is NULL.
  79308. */
  79309. /* Opcode: ShiftRight P1 P2 P3 * *
  79310. ** Synopsis: r[P3]=r[P2]>>r[P1]
  79311. **
  79312. ** Shift the integer value in register P2 to the right by the
  79313. ** number of bits specified by the integer in register P1.
  79314. ** Store the result in register P3.
  79315. ** If either input is NULL, the result is NULL.
  79316. */
  79317. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  79318. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  79319. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  79320. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  79321. i64 iA;
  79322. u64 uA;
  79323. i64 iB;
  79324. u8 op;
  79325. pIn1 = &aMem[pOp->p1];
  79326. pIn2 = &aMem[pOp->p2];
  79327. pOut = &aMem[pOp->p3];
  79328. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  79329. sqlite3VdbeMemSetNull(pOut);
  79330. break;
  79331. }
  79332. iA = sqlite3VdbeIntValue(pIn2);
  79333. iB = sqlite3VdbeIntValue(pIn1);
  79334. op = pOp->opcode;
  79335. if( op==OP_BitAnd ){
  79336. iA &= iB;
  79337. }else if( op==OP_BitOr ){
  79338. iA |= iB;
  79339. }else if( iB!=0 ){
  79340. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  79341. /* If shifting by a negative amount, shift in the other direction */
  79342. if( iB<0 ){
  79343. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  79344. op = 2*OP_ShiftLeft + 1 - op;
  79345. iB = iB>(-64) ? -iB : 64;
  79346. }
  79347. if( iB>=64 ){
  79348. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  79349. }else{
  79350. memcpy(&uA, &iA, sizeof(uA));
  79351. if( op==OP_ShiftLeft ){
  79352. uA <<= iB;
  79353. }else{
  79354. uA >>= iB;
  79355. /* Sign-extend on a right shift of a negative number */
  79356. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  79357. }
  79358. memcpy(&iA, &uA, sizeof(iA));
  79359. }
  79360. }
  79361. pOut->u.i = iA;
  79362. MemSetTypeFlag(pOut, MEM_Int);
  79363. break;
  79364. }
  79365. /* Opcode: AddImm P1 P2 * * *
  79366. ** Synopsis: r[P1]=r[P1]+P2
  79367. **
  79368. ** Add the constant P2 to the value in register P1.
  79369. ** The result is always an integer.
  79370. **
  79371. ** To force any register to be an integer, just add 0.
  79372. */
  79373. case OP_AddImm: { /* in1 */
  79374. pIn1 = &aMem[pOp->p1];
  79375. memAboutToChange(p, pIn1);
  79376. sqlite3VdbeMemIntegerify(pIn1);
  79377. pIn1->u.i += pOp->p2;
  79378. break;
  79379. }
  79380. /* Opcode: MustBeInt P1 P2 * * *
  79381. **
  79382. ** Force the value in register P1 to be an integer. If the value
  79383. ** in P1 is not an integer and cannot be converted into an integer
  79384. ** without data loss, then jump immediately to P2, or if P2==0
  79385. ** raise an SQLITE_MISMATCH exception.
  79386. */
  79387. case OP_MustBeInt: { /* jump, in1 */
  79388. pIn1 = &aMem[pOp->p1];
  79389. if( (pIn1->flags & MEM_Int)==0 ){
  79390. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  79391. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  79392. if( (pIn1->flags & MEM_Int)==0 ){
  79393. if( pOp->p2==0 ){
  79394. rc = SQLITE_MISMATCH;
  79395. goto abort_due_to_error;
  79396. }else{
  79397. goto jump_to_p2;
  79398. }
  79399. }
  79400. }
  79401. MemSetTypeFlag(pIn1, MEM_Int);
  79402. break;
  79403. }
  79404. #ifndef SQLITE_OMIT_FLOATING_POINT
  79405. /* Opcode: RealAffinity P1 * * * *
  79406. **
  79407. ** If register P1 holds an integer convert it to a real value.
  79408. **
  79409. ** This opcode is used when extracting information from a column that
  79410. ** has REAL affinity. Such column values may still be stored as
  79411. ** integers, for space efficiency, but after extraction we want them
  79412. ** to have only a real value.
  79413. */
  79414. case OP_RealAffinity: { /* in1 */
  79415. pIn1 = &aMem[pOp->p1];
  79416. if( pIn1->flags & MEM_Int ){
  79417. sqlite3VdbeMemRealify(pIn1);
  79418. }
  79419. break;
  79420. }
  79421. #endif
  79422. #ifndef SQLITE_OMIT_CAST
  79423. /* Opcode: Cast P1 P2 * * *
  79424. ** Synopsis: affinity(r[P1])
  79425. **
  79426. ** Force the value in register P1 to be the type defined by P2.
  79427. **
  79428. ** <ul>
  79429. ** <li> P2=='A' &rarr; BLOB
  79430. ** <li> P2=='B' &rarr; TEXT
  79431. ** <li> P2=='C' &rarr; NUMERIC
  79432. ** <li> P2=='D' &rarr; INTEGER
  79433. ** <li> P2=='E' &rarr; REAL
  79434. ** </ul>
  79435. **
  79436. ** A NULL value is not changed by this routine. It remains NULL.
  79437. */
  79438. case OP_Cast: { /* in1 */
  79439. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  79440. testcase( pOp->p2==SQLITE_AFF_TEXT );
  79441. testcase( pOp->p2==SQLITE_AFF_BLOB );
  79442. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  79443. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  79444. testcase( pOp->p2==SQLITE_AFF_REAL );
  79445. pIn1 = &aMem[pOp->p1];
  79446. memAboutToChange(p, pIn1);
  79447. rc = ExpandBlob(pIn1);
  79448. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  79449. UPDATE_MAX_BLOBSIZE(pIn1);
  79450. if( rc ) goto abort_due_to_error;
  79451. break;
  79452. }
  79453. #endif /* SQLITE_OMIT_CAST */
  79454. /* Opcode: Eq P1 P2 P3 P4 P5
  79455. ** Synopsis: IF r[P3]==r[P1]
  79456. **
  79457. ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
  79458. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
  79459. ** store the result of comparison in register P2.
  79460. **
  79461. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  79462. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  79463. ** to coerce both inputs according to this affinity before the
  79464. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  79465. ** affinity is used. Note that the affinity conversions are stored
  79466. ** back into the input registers P1 and P3. So this opcode can cause
  79467. ** persistent changes to registers P1 and P3.
  79468. **
  79469. ** Once any conversions have taken place, and neither value is NULL,
  79470. ** the values are compared. If both values are blobs then memcmp() is
  79471. ** used to determine the results of the comparison. If both values
  79472. ** are text, then the appropriate collating function specified in
  79473. ** P4 is used to do the comparison. If P4 is not specified then
  79474. ** memcmp() is used to compare text string. If both values are
  79475. ** numeric, then a numeric comparison is used. If the two values
  79476. ** are of different types, then numbers are considered less than
  79477. ** strings and strings are considered less than blobs.
  79478. **
  79479. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  79480. ** true or false and is never NULL. If both operands are NULL then the result
  79481. ** of comparison is true. If either operand is NULL then the result is false.
  79482. ** If neither operand is NULL the result is the same as it would be if
  79483. ** the SQLITE_NULLEQ flag were omitted from P5.
  79484. **
  79485. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  79486. ** content of r[P2] is only changed if the new value is NULL or 0 (false).
  79487. ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
  79488. */
  79489. /* Opcode: Ne P1 P2 P3 P4 P5
  79490. ** Synopsis: IF r[P3]!=r[P1]
  79491. **
  79492. ** This works just like the Eq opcode except that the jump is taken if
  79493. ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
  79494. ** additional information.
  79495. **
  79496. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  79497. ** content of r[P2] is only changed if the new value is NULL or 1 (true).
  79498. ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
  79499. */
  79500. /* Opcode: Lt P1 P2 P3 P4 P5
  79501. ** Synopsis: IF r[P3]<r[P1]
  79502. **
  79503. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  79504. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
  79505. ** the result of comparison (0 or 1 or NULL) into register P2.
  79506. **
  79507. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  79508. ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
  79509. ** bit is clear then fall through if either operand is NULL.
  79510. **
  79511. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  79512. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  79513. ** to coerce both inputs according to this affinity before the
  79514. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  79515. ** affinity is used. Note that the affinity conversions are stored
  79516. ** back into the input registers P1 and P3. So this opcode can cause
  79517. ** persistent changes to registers P1 and P3.
  79518. **
  79519. ** Once any conversions have taken place, and neither value is NULL,
  79520. ** the values are compared. If both values are blobs then memcmp() is
  79521. ** used to determine the results of the comparison. If both values
  79522. ** are text, then the appropriate collating function specified in
  79523. ** P4 is used to do the comparison. If P4 is not specified then
  79524. ** memcmp() is used to compare text string. If both values are
  79525. ** numeric, then a numeric comparison is used. If the two values
  79526. ** are of different types, then numbers are considered less than
  79527. ** strings and strings are considered less than blobs.
  79528. */
  79529. /* Opcode: Le P1 P2 P3 P4 P5
  79530. ** Synopsis: IF r[P3]<=r[P1]
  79531. **
  79532. ** This works just like the Lt opcode except that the jump is taken if
  79533. ** the content of register P3 is less than or equal to the content of
  79534. ** register P1. See the Lt opcode for additional information.
  79535. */
  79536. /* Opcode: Gt P1 P2 P3 P4 P5
  79537. ** Synopsis: IF r[P3]>r[P1]
  79538. **
  79539. ** This works just like the Lt opcode except that the jump is taken if
  79540. ** the content of register P3 is greater than the content of
  79541. ** register P1. See the Lt opcode for additional information.
  79542. */
  79543. /* Opcode: Ge P1 P2 P3 P4 P5
  79544. ** Synopsis: IF r[P3]>=r[P1]
  79545. **
  79546. ** This works just like the Lt opcode except that the jump is taken if
  79547. ** the content of register P3 is greater than or equal to the content of
  79548. ** register P1. See the Lt opcode for additional information.
  79549. */
  79550. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  79551. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  79552. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  79553. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  79554. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  79555. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  79556. int res, res2; /* Result of the comparison of pIn1 against pIn3 */
  79557. char affinity; /* Affinity to use for comparison */
  79558. u16 flags1; /* Copy of initial value of pIn1->flags */
  79559. u16 flags3; /* Copy of initial value of pIn3->flags */
  79560. pIn1 = &aMem[pOp->p1];
  79561. pIn3 = &aMem[pOp->p3];
  79562. flags1 = pIn1->flags;
  79563. flags3 = pIn3->flags;
  79564. if( (flags1 | flags3)&MEM_Null ){
  79565. /* One or both operands are NULL */
  79566. if( pOp->p5 & SQLITE_NULLEQ ){
  79567. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  79568. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  79569. ** or not both operands are null.
  79570. */
  79571. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  79572. assert( (flags1 & MEM_Cleared)==0 );
  79573. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  79574. if( (flags1&flags3&MEM_Null)!=0
  79575. && (flags3&MEM_Cleared)==0
  79576. ){
  79577. res = 0; /* Operands are equal */
  79578. }else{
  79579. res = 1; /* Operands are not equal */
  79580. }
  79581. }else{
  79582. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  79583. ** then the result is always NULL.
  79584. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  79585. */
  79586. if( pOp->p5 & SQLITE_STOREP2 ){
  79587. pOut = &aMem[pOp->p2];
  79588. iCompare = 1; /* Operands are not equal */
  79589. memAboutToChange(p, pOut);
  79590. MemSetTypeFlag(pOut, MEM_Null);
  79591. REGISTER_TRACE(pOp->p2, pOut);
  79592. }else{
  79593. VdbeBranchTaken(2,3);
  79594. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  79595. goto jump_to_p2;
  79596. }
  79597. }
  79598. break;
  79599. }
  79600. }else{
  79601. /* Neither operand is NULL. Do a comparison. */
  79602. affinity = pOp->p5 & SQLITE_AFF_MASK;
  79603. if( affinity>=SQLITE_AFF_NUMERIC ){
  79604. if( (flags1 | flags3)&MEM_Str ){
  79605. if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  79606. applyNumericAffinity(pIn1,0);
  79607. assert( flags3==pIn3->flags );
  79608. /* testcase( flags3!=pIn3->flags );
  79609. ** this used to be possible with pIn1==pIn3, but not since
  79610. ** the column cache was removed. The following assignment
  79611. ** is essentially a no-op. But, it provides defense-in-depth
  79612. ** in case our analysis is incorrect, so it is left in. */
  79613. flags3 = pIn3->flags;
  79614. }
  79615. if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  79616. applyNumericAffinity(pIn3,0);
  79617. }
  79618. }
  79619. /* Handle the common case of integer comparison here, as an
  79620. ** optimization, to avoid a call to sqlite3MemCompare() */
  79621. if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
  79622. if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
  79623. if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
  79624. res = 0;
  79625. goto compare_op;
  79626. }
  79627. }else if( affinity==SQLITE_AFF_TEXT ){
  79628. if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
  79629. testcase( pIn1->flags & MEM_Int );
  79630. testcase( pIn1->flags & MEM_Real );
  79631. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  79632. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  79633. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  79634. assert( pIn1!=pIn3 );
  79635. }
  79636. if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
  79637. testcase( pIn3->flags & MEM_Int );
  79638. testcase( pIn3->flags & MEM_Real );
  79639. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  79640. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  79641. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  79642. }
  79643. }
  79644. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  79645. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  79646. }
  79647. compare_op:
  79648. /* At this point, res is negative, zero, or positive if reg[P1] is
  79649. ** less than, equal to, or greater than reg[P3], respectively. Compute
  79650. ** the answer to this operator in res2, depending on what the comparison
  79651. ** operator actually is. The next block of code depends on the fact
  79652. ** that the 6 comparison operators are consecutive integers in this
  79653. ** order: NE, EQ, GT, LE, LT, GE */
  79654. assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
  79655. assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
  79656. if( res<0 ){ /* ne, eq, gt, le, lt, ge */
  79657. static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
  79658. res2 = aLTb[pOp->opcode - OP_Ne];
  79659. }else if( res==0 ){
  79660. static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
  79661. res2 = aEQb[pOp->opcode - OP_Ne];
  79662. }else{
  79663. static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
  79664. res2 = aGTb[pOp->opcode - OP_Ne];
  79665. }
  79666. /* Undo any changes made by applyAffinity() to the input registers. */
  79667. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  79668. pIn1->flags = flags1;
  79669. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  79670. pIn3->flags = flags3;
  79671. if( pOp->p5 & SQLITE_STOREP2 ){
  79672. pOut = &aMem[pOp->p2];
  79673. iCompare = res;
  79674. if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
  79675. /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
  79676. ** and prevents OP_Ne from overwriting NULL with 0. This flag
  79677. ** is only used in contexts where either:
  79678. ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
  79679. ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
  79680. ** Therefore it is not necessary to check the content of r[P2] for
  79681. ** NULL. */
  79682. assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
  79683. assert( res2==0 || res2==1 );
  79684. testcase( res2==0 && pOp->opcode==OP_Eq );
  79685. testcase( res2==1 && pOp->opcode==OP_Eq );
  79686. testcase( res2==0 && pOp->opcode==OP_Ne );
  79687. testcase( res2==1 && pOp->opcode==OP_Ne );
  79688. if( (pOp->opcode==OP_Eq)==res2 ) break;
  79689. }
  79690. memAboutToChange(p, pOut);
  79691. MemSetTypeFlag(pOut, MEM_Int);
  79692. pOut->u.i = res2;
  79693. REGISTER_TRACE(pOp->p2, pOut);
  79694. }else{
  79695. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  79696. if( res2 ){
  79697. goto jump_to_p2;
  79698. }
  79699. }
  79700. break;
  79701. }
  79702. /* Opcode: ElseNotEq * P2 * * *
  79703. **
  79704. ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
  79705. ** If result of an OP_Eq comparison on the same two operands
  79706. ** would have be NULL or false (0), then then jump to P2.
  79707. ** If the result of an OP_Eq comparison on the two previous operands
  79708. ** would have been true (1), then fall through.
  79709. */
  79710. case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
  79711. assert( pOp>aOp );
  79712. assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
  79713. assert( pOp[-1].p5 & SQLITE_STOREP2 );
  79714. VdbeBranchTaken(iCompare!=0, 2);
  79715. if( iCompare!=0 ) goto jump_to_p2;
  79716. break;
  79717. }
  79718. /* Opcode: Permutation * * * P4 *
  79719. **
  79720. ** Set the permutation used by the OP_Compare operator in the next
  79721. ** instruction. The permutation is stored in the P4 operand.
  79722. **
  79723. ** The permutation is only valid until the next OP_Compare that has
  79724. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  79725. ** occur immediately prior to the OP_Compare.
  79726. **
  79727. ** The first integer in the P4 integer array is the length of the array
  79728. ** and does not become part of the permutation.
  79729. */
  79730. case OP_Permutation: {
  79731. assert( pOp->p4type==P4_INTARRAY );
  79732. assert( pOp->p4.ai );
  79733. assert( pOp[1].opcode==OP_Compare );
  79734. assert( pOp[1].p5 & OPFLAG_PERMUTE );
  79735. break;
  79736. }
  79737. /* Opcode: Compare P1 P2 P3 P4 P5
  79738. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  79739. **
  79740. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  79741. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  79742. ** the comparison for use by the next OP_Jump instruct.
  79743. **
  79744. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  79745. ** determined by the most recent OP_Permutation operator. If the
  79746. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  79747. ** order.
  79748. **
  79749. ** P4 is a KeyInfo structure that defines collating sequences and sort
  79750. ** orders for the comparison. The permutation applies to registers
  79751. ** only. The KeyInfo elements are used sequentially.
  79752. **
  79753. ** The comparison is a sort comparison, so NULLs compare equal,
  79754. ** NULLs are less than numbers, numbers are less than strings,
  79755. ** and strings are less than blobs.
  79756. */
  79757. case OP_Compare: {
  79758. int n;
  79759. int i;
  79760. int p1;
  79761. int p2;
  79762. const KeyInfo *pKeyInfo;
  79763. int idx;
  79764. CollSeq *pColl; /* Collating sequence to use on this term */
  79765. int bRev; /* True for DESCENDING sort order */
  79766. int *aPermute; /* The permutation */
  79767. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
  79768. aPermute = 0;
  79769. }else{
  79770. assert( pOp>aOp );
  79771. assert( pOp[-1].opcode==OP_Permutation );
  79772. assert( pOp[-1].p4type==P4_INTARRAY );
  79773. aPermute = pOp[-1].p4.ai + 1;
  79774. assert( aPermute!=0 );
  79775. }
  79776. n = pOp->p3;
  79777. pKeyInfo = pOp->p4.pKeyInfo;
  79778. assert( n>0 );
  79779. assert( pKeyInfo!=0 );
  79780. p1 = pOp->p1;
  79781. p2 = pOp->p2;
  79782. #ifdef SQLITE_DEBUG
  79783. if( aPermute ){
  79784. int k, mx = 0;
  79785. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  79786. assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
  79787. assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
  79788. }else{
  79789. assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
  79790. assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
  79791. }
  79792. #endif /* SQLITE_DEBUG */
  79793. for(i=0; i<n; i++){
  79794. idx = aPermute ? aPermute[i] : i;
  79795. assert( memIsValid(&aMem[p1+idx]) );
  79796. assert( memIsValid(&aMem[p2+idx]) );
  79797. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  79798. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  79799. assert( i<pKeyInfo->nKeyField );
  79800. pColl = pKeyInfo->aColl[i];
  79801. bRev = pKeyInfo->aSortOrder[i];
  79802. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  79803. if( iCompare ){
  79804. if( bRev ) iCompare = -iCompare;
  79805. break;
  79806. }
  79807. }
  79808. break;
  79809. }
  79810. /* Opcode: Jump P1 P2 P3 * *
  79811. **
  79812. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  79813. ** in the most recent OP_Compare instruction the P1 vector was less than
  79814. ** equal to, or greater than the P2 vector, respectively.
  79815. */
  79816. case OP_Jump: { /* jump */
  79817. if( iCompare<0 ){
  79818. VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
  79819. }else if( iCompare==0 ){
  79820. VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
  79821. }else{
  79822. VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
  79823. }
  79824. break;
  79825. }
  79826. /* Opcode: And P1 P2 P3 * *
  79827. ** Synopsis: r[P3]=(r[P1] && r[P2])
  79828. **
  79829. ** Take the logical AND of the values in registers P1 and P2 and
  79830. ** write the result into register P3.
  79831. **
  79832. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  79833. ** the other input is NULL. A NULL and true or two NULLs give
  79834. ** a NULL output.
  79835. */
  79836. /* Opcode: Or P1 P2 P3 * *
  79837. ** Synopsis: r[P3]=(r[P1] || r[P2])
  79838. **
  79839. ** Take the logical OR of the values in register P1 and P2 and
  79840. ** store the answer in register P3.
  79841. **
  79842. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  79843. ** even if the other input is NULL. A NULL and false or two NULLs
  79844. ** give a NULL output.
  79845. */
  79846. case OP_And: /* same as TK_AND, in1, in2, out3 */
  79847. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  79848. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  79849. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  79850. v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
  79851. v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
  79852. if( pOp->opcode==OP_And ){
  79853. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  79854. v1 = and_logic[v1*3+v2];
  79855. }else{
  79856. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  79857. v1 = or_logic[v1*3+v2];
  79858. }
  79859. pOut = &aMem[pOp->p3];
  79860. if( v1==2 ){
  79861. MemSetTypeFlag(pOut, MEM_Null);
  79862. }else{
  79863. pOut->u.i = v1;
  79864. MemSetTypeFlag(pOut, MEM_Int);
  79865. }
  79866. break;
  79867. }
  79868. /* Opcode: IsTrue P1 P2 P3 P4 *
  79869. ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
  79870. **
  79871. ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
  79872. ** IS NOT FALSE operators.
  79873. **
  79874. ** Interpret the value in register P1 as a boolean value. Store that
  79875. ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
  79876. ** NULL, then the P3 is stored in register P2. Invert the answer if P4
  79877. ** is 1.
  79878. **
  79879. ** The logic is summarized like this:
  79880. **
  79881. ** <ul>
  79882. ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
  79883. ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
  79884. ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
  79885. ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
  79886. ** </ul>
  79887. */
  79888. case OP_IsTrue: { /* in1, out2 */
  79889. assert( pOp->p4type==P4_INT32 );
  79890. assert( pOp->p4.i==0 || pOp->p4.i==1 );
  79891. assert( pOp->p3==0 || pOp->p3==1 );
  79892. sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
  79893. sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
  79894. break;
  79895. }
  79896. /* Opcode: Not P1 P2 * * *
  79897. ** Synopsis: r[P2]= !r[P1]
  79898. **
  79899. ** Interpret the value in register P1 as a boolean value. Store the
  79900. ** boolean complement in register P2. If the value in register P1 is
  79901. ** NULL, then a NULL is stored in P2.
  79902. */
  79903. case OP_Not: { /* same as TK_NOT, in1, out2 */
  79904. pIn1 = &aMem[pOp->p1];
  79905. pOut = &aMem[pOp->p2];
  79906. if( (pIn1->flags & MEM_Null)==0 ){
  79907. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
  79908. }else{
  79909. sqlite3VdbeMemSetNull(pOut);
  79910. }
  79911. break;
  79912. }
  79913. /* Opcode: BitNot P1 P2 * * *
  79914. ** Synopsis: r[P2]= ~r[P1]
  79915. **
  79916. ** Interpret the content of register P1 as an integer. Store the
  79917. ** ones-complement of the P1 value into register P2. If P1 holds
  79918. ** a NULL then store a NULL in P2.
  79919. */
  79920. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  79921. pIn1 = &aMem[pOp->p1];
  79922. pOut = &aMem[pOp->p2];
  79923. sqlite3VdbeMemSetNull(pOut);
  79924. if( (pIn1->flags & MEM_Null)==0 ){
  79925. pOut->flags = MEM_Int;
  79926. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  79927. }
  79928. break;
  79929. }
  79930. /* Opcode: Once P1 P2 * * *
  79931. **
  79932. ** Fall through to the next instruction the first time this opcode is
  79933. ** encountered on each invocation of the byte-code program. Jump to P2
  79934. ** on the second and all subsequent encounters during the same invocation.
  79935. **
  79936. ** Top-level programs determine first invocation by comparing the P1
  79937. ** operand against the P1 operand on the OP_Init opcode at the beginning
  79938. ** of the program. If the P1 values differ, then fall through and make
  79939. ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
  79940. ** the same then take the jump.
  79941. **
  79942. ** For subprograms, there is a bitmask in the VdbeFrame that determines
  79943. ** whether or not the jump should be taken. The bitmask is necessary
  79944. ** because the self-altering code trick does not work for recursive
  79945. ** triggers.
  79946. */
  79947. case OP_Once: { /* jump */
  79948. u32 iAddr; /* Address of this instruction */
  79949. assert( p->aOp[0].opcode==OP_Init );
  79950. if( p->pFrame ){
  79951. iAddr = (int)(pOp - p->aOp);
  79952. if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
  79953. VdbeBranchTaken(1, 2);
  79954. goto jump_to_p2;
  79955. }
  79956. p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
  79957. }else{
  79958. if( p->aOp[0].p1==pOp->p1 ){
  79959. VdbeBranchTaken(1, 2);
  79960. goto jump_to_p2;
  79961. }
  79962. }
  79963. VdbeBranchTaken(0, 2);
  79964. pOp->p1 = p->aOp[0].p1;
  79965. break;
  79966. }
  79967. /* Opcode: If P1 P2 P3 * *
  79968. **
  79969. ** Jump to P2 if the value in register P1 is true. The value
  79970. ** is considered true if it is numeric and non-zero. If the value
  79971. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  79972. */
  79973. case OP_If: { /* jump, in1 */
  79974. int c;
  79975. c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
  79976. VdbeBranchTaken(c!=0, 2);
  79977. if( c ) goto jump_to_p2;
  79978. break;
  79979. }
  79980. /* Opcode: IfNot P1 P2 P3 * *
  79981. **
  79982. ** Jump to P2 if the value in register P1 is False. The value
  79983. ** is considered false if it has a numeric value of zero. If the value
  79984. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  79985. */
  79986. case OP_IfNot: { /* jump, in1 */
  79987. int c;
  79988. c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
  79989. VdbeBranchTaken(c!=0, 2);
  79990. if( c ) goto jump_to_p2;
  79991. break;
  79992. }
  79993. /* Opcode: IsNull P1 P2 * * *
  79994. ** Synopsis: if r[P1]==NULL goto P2
  79995. **
  79996. ** Jump to P2 if the value in register P1 is NULL.
  79997. */
  79998. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  79999. pIn1 = &aMem[pOp->p1];
  80000. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  80001. if( (pIn1->flags & MEM_Null)!=0 ){
  80002. goto jump_to_p2;
  80003. }
  80004. break;
  80005. }
  80006. /* Opcode: NotNull P1 P2 * * *
  80007. ** Synopsis: if r[P1]!=NULL goto P2
  80008. **
  80009. ** Jump to P2 if the value in register P1 is not NULL.
  80010. */
  80011. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  80012. pIn1 = &aMem[pOp->p1];
  80013. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  80014. if( (pIn1->flags & MEM_Null)==0 ){
  80015. goto jump_to_p2;
  80016. }
  80017. break;
  80018. }
  80019. /* Opcode: IfNullRow P1 P2 P3 * *
  80020. ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
  80021. **
  80022. ** Check the cursor P1 to see if it is currently pointing at a NULL row.
  80023. ** If it is, then set register P3 to NULL and jump immediately to P2.
  80024. ** If P1 is not on a NULL row, then fall through without making any
  80025. ** changes.
  80026. */
  80027. case OP_IfNullRow: { /* jump */
  80028. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80029. assert( p->apCsr[pOp->p1]!=0 );
  80030. if( p->apCsr[pOp->p1]->nullRow ){
  80031. sqlite3VdbeMemSetNull(aMem + pOp->p3);
  80032. goto jump_to_p2;
  80033. }
  80034. break;
  80035. }
  80036. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  80037. /* Opcode: Offset P1 P2 P3 * *
  80038. ** Synopsis: r[P3] = sqlite_offset(P1)
  80039. **
  80040. ** Store in register r[P3] the byte offset into the database file that is the
  80041. ** start of the payload for the record at which that cursor P1 is currently
  80042. ** pointing.
  80043. **
  80044. ** P2 is the column number for the argument to the sqlite_offset() function.
  80045. ** This opcode does not use P2 itself, but the P2 value is used by the
  80046. ** code generator. The P1, P2, and P3 operands to this opcode are the
  80047. ** same as for OP_Column.
  80048. **
  80049. ** This opcode is only available if SQLite is compiled with the
  80050. ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
  80051. */
  80052. case OP_Offset: { /* out3 */
  80053. VdbeCursor *pC; /* The VDBE cursor */
  80054. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80055. pC = p->apCsr[pOp->p1];
  80056. pOut = &p->aMem[pOp->p3];
  80057. if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
  80058. sqlite3VdbeMemSetNull(pOut);
  80059. }else{
  80060. sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
  80061. }
  80062. break;
  80063. }
  80064. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  80065. /* Opcode: Column P1 P2 P3 P4 P5
  80066. ** Synopsis: r[P3]=PX
  80067. **
  80068. ** Interpret the data that cursor P1 points to as a structure built using
  80069. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  80070. ** information about the format of the data.) Extract the P2-th column
  80071. ** from this record. If there are less that (P2+1)
  80072. ** values in the record, extract a NULL.
  80073. **
  80074. ** The value extracted is stored in register P3.
  80075. **
  80076. ** If the record contains fewer than P2 fields, then extract a NULL. Or,
  80077. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  80078. ** the result.
  80079. **
  80080. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  80081. ** then the cache of the cursor is reset prior to extracting the column.
  80082. ** The first OP_Column against a pseudo-table after the value of the content
  80083. ** register has changed should have this bit set.
  80084. **
  80085. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
  80086. ** the result is guaranteed to only be used as the argument of a length()
  80087. ** or typeof() function, respectively. The loading of large blobs can be
  80088. ** skipped for length() and all content loading can be skipped for typeof().
  80089. */
  80090. case OP_Column: {
  80091. int p2; /* column number to retrieve */
  80092. VdbeCursor *pC; /* The VDBE cursor */
  80093. BtCursor *pCrsr; /* The BTree cursor */
  80094. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  80095. int len; /* The length of the serialized data for the column */
  80096. int i; /* Loop counter */
  80097. Mem *pDest; /* Where to write the extracted value */
  80098. Mem sMem; /* For storing the record being decoded */
  80099. const u8 *zData; /* Part of the record being decoded */
  80100. const u8 *zHdr; /* Next unparsed byte of the header */
  80101. const u8 *zEndHdr; /* Pointer to first byte after the header */
  80102. u64 offset64; /* 64-bit offset */
  80103. u32 t; /* A type code from the record header */
  80104. Mem *pReg; /* PseudoTable input register */
  80105. pC = p->apCsr[pOp->p1];
  80106. p2 = pOp->p2;
  80107. /* If the cursor cache is stale (meaning it is not currently point at
  80108. ** the correct row) then bring it up-to-date by doing the necessary
  80109. ** B-Tree seek. */
  80110. rc = sqlite3VdbeCursorMoveto(&pC, &p2);
  80111. if( rc ) goto abort_due_to_error;
  80112. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  80113. pDest = &aMem[pOp->p3];
  80114. memAboutToChange(p, pDest);
  80115. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80116. assert( pC!=0 );
  80117. assert( p2<pC->nField );
  80118. aOffset = pC->aOffset;
  80119. assert( pC->eCurType!=CURTYPE_VTAB );
  80120. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  80121. assert( pC->eCurType!=CURTYPE_SORTER );
  80122. if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
  80123. if( pC->nullRow ){
  80124. if( pC->eCurType==CURTYPE_PSEUDO ){
  80125. /* For the special case of as pseudo-cursor, the seekResult field
  80126. ** identifies the register that holds the record */
  80127. assert( pC->seekResult>0 );
  80128. pReg = &aMem[pC->seekResult];
  80129. assert( pReg->flags & MEM_Blob );
  80130. assert( memIsValid(pReg) );
  80131. pC->payloadSize = pC->szRow = pReg->n;
  80132. pC->aRow = (u8*)pReg->z;
  80133. }else{
  80134. sqlite3VdbeMemSetNull(pDest);
  80135. goto op_column_out;
  80136. }
  80137. }else{
  80138. pCrsr = pC->uc.pCursor;
  80139. assert( pC->eCurType==CURTYPE_BTREE );
  80140. assert( pCrsr );
  80141. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  80142. pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
  80143. pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
  80144. assert( pC->szRow<=pC->payloadSize );
  80145. assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
  80146. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  80147. goto too_big;
  80148. }
  80149. }
  80150. pC->cacheStatus = p->cacheCtr;
  80151. pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
  80152. pC->nHdrParsed = 0;
  80153. if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
  80154. /* pC->aRow does not have to hold the entire row, but it does at least
  80155. ** need to cover the header of the record. If pC->aRow does not contain
  80156. ** the complete header, then set it to zero, forcing the header to be
  80157. ** dynamically allocated. */
  80158. pC->aRow = 0;
  80159. pC->szRow = 0;
  80160. /* Make sure a corrupt database has not given us an oversize header.
  80161. ** Do this now to avoid an oversize memory allocation.
  80162. **
  80163. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  80164. ** types use so much data space that there can only be 4096 and 32 of
  80165. ** them, respectively. So the maximum header length results from a
  80166. ** 3-byte type for each of the maximum of 32768 columns plus three
  80167. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  80168. */
  80169. if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
  80170. goto op_column_corrupt;
  80171. }
  80172. }else{
  80173. /* This is an optimization. By skipping over the first few tests
  80174. ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
  80175. ** measurable performance gain.
  80176. **
  80177. ** This branch is taken even if aOffset[0]==0. Such a record is never
  80178. ** generated by SQLite, and could be considered corruption, but we
  80179. ** accept it for historical reasons. When aOffset[0]==0, the code this
  80180. ** branch jumps to reads past the end of the record, but never more
  80181. ** than a few bytes. Even if the record occurs at the end of the page
  80182. ** content area, the "page header" comes after the page content and so
  80183. ** this overread is harmless. Similar overreads can occur for a corrupt
  80184. ** database file.
  80185. */
  80186. zData = pC->aRow;
  80187. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  80188. testcase( aOffset[0]==0 );
  80189. goto op_column_read_header;
  80190. }
  80191. }
  80192. /* Make sure at least the first p2+1 entries of the header have been
  80193. ** parsed and valid information is in aOffset[] and pC->aType[].
  80194. */
  80195. if( pC->nHdrParsed<=p2 ){
  80196. /* If there is more header available for parsing in the record, try
  80197. ** to extract additional fields up through the p2+1-th field
  80198. */
  80199. if( pC->iHdrOffset<aOffset[0] ){
  80200. /* Make sure zData points to enough of the record to cover the header. */
  80201. if( pC->aRow==0 ){
  80202. memset(&sMem, 0, sizeof(sMem));
  80203. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
  80204. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  80205. zData = (u8*)sMem.z;
  80206. }else{
  80207. zData = pC->aRow;
  80208. }
  80209. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  80210. op_column_read_header:
  80211. i = pC->nHdrParsed;
  80212. offset64 = aOffset[i];
  80213. zHdr = zData + pC->iHdrOffset;
  80214. zEndHdr = zData + aOffset[0];
  80215. testcase( zHdr>=zEndHdr );
  80216. do{
  80217. if( (t = zHdr[0])<0x80 ){
  80218. zHdr++;
  80219. offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
  80220. }else{
  80221. zHdr += sqlite3GetVarint32(zHdr, &t);
  80222. offset64 += sqlite3VdbeSerialTypeLen(t);
  80223. }
  80224. pC->aType[i++] = t;
  80225. aOffset[i] = (u32)(offset64 & 0xffffffff);
  80226. }while( i<=p2 && zHdr<zEndHdr );
  80227. /* The record is corrupt if any of the following are true:
  80228. ** (1) the bytes of the header extend past the declared header size
  80229. ** (2) the entire header was used but not all data was used
  80230. ** (3) the end of the data extends beyond the end of the record.
  80231. */
  80232. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
  80233. || (offset64 > pC->payloadSize)
  80234. ){
  80235. if( aOffset[0]==0 ){
  80236. i = 0;
  80237. zHdr = zEndHdr;
  80238. }else{
  80239. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  80240. goto op_column_corrupt;
  80241. }
  80242. }
  80243. pC->nHdrParsed = i;
  80244. pC->iHdrOffset = (u32)(zHdr - zData);
  80245. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  80246. }else{
  80247. t = 0;
  80248. }
  80249. /* If after trying to extract new entries from the header, nHdrParsed is
  80250. ** still not up to p2, that means that the record has fewer than p2
  80251. ** columns. So the result will be either the default value or a NULL.
  80252. */
  80253. if( pC->nHdrParsed<=p2 ){
  80254. if( pOp->p4type==P4_MEM ){
  80255. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  80256. }else{
  80257. sqlite3VdbeMemSetNull(pDest);
  80258. }
  80259. goto op_column_out;
  80260. }
  80261. }else{
  80262. t = pC->aType[p2];
  80263. }
  80264. /* Extract the content for the p2+1-th column. Control can only
  80265. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  80266. ** all valid.
  80267. */
  80268. assert( p2<pC->nHdrParsed );
  80269. assert( rc==SQLITE_OK );
  80270. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  80271. if( VdbeMemDynamic(pDest) ){
  80272. sqlite3VdbeMemSetNull(pDest);
  80273. }
  80274. assert( t==pC->aType[p2] );
  80275. if( pC->szRow>=aOffset[p2+1] ){
  80276. /* This is the common case where the desired content fits on the original
  80277. ** page - where the content is not on an overflow page */
  80278. zData = pC->aRow + aOffset[p2];
  80279. if( t<12 ){
  80280. sqlite3VdbeSerialGet(zData, t, pDest);
  80281. }else{
  80282. /* If the column value is a string, we need a persistent value, not
  80283. ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
  80284. ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
  80285. */
  80286. static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
  80287. pDest->n = len = (t-12)/2;
  80288. pDest->enc = encoding;
  80289. if( pDest->szMalloc < len+2 ){
  80290. pDest->flags = MEM_Null;
  80291. if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
  80292. }else{
  80293. pDest->z = pDest->zMalloc;
  80294. }
  80295. memcpy(pDest->z, zData, len);
  80296. pDest->z[len] = 0;
  80297. pDest->z[len+1] = 0;
  80298. pDest->flags = aFlag[t&1];
  80299. }
  80300. }else{
  80301. pDest->enc = encoding;
  80302. /* This branch happens only when content is on overflow pages */
  80303. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  80304. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  80305. || (len = sqlite3VdbeSerialTypeLen(t))==0
  80306. ){
  80307. /* Content is irrelevant for
  80308. ** 1. the typeof() function,
  80309. ** 2. the length(X) function if X is a blob, and
  80310. ** 3. if the content length is zero.
  80311. ** So we might as well use bogus content rather than reading
  80312. ** content from disk.
  80313. **
  80314. ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
  80315. ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
  80316. ** read up to 16. So 16 bytes of bogus content is supplied.
  80317. */
  80318. static u8 aZero[16]; /* This is the bogus content */
  80319. sqlite3VdbeSerialGet(aZero, t, pDest);
  80320. }else{
  80321. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
  80322. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  80323. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  80324. pDest->flags &= ~MEM_Ephem;
  80325. }
  80326. }
  80327. op_column_out:
  80328. UPDATE_MAX_BLOBSIZE(pDest);
  80329. REGISTER_TRACE(pOp->p3, pDest);
  80330. break;
  80331. op_column_corrupt:
  80332. if( aOp[0].p3>0 ){
  80333. pOp = &aOp[aOp[0].p3-1];
  80334. break;
  80335. }else{
  80336. rc = SQLITE_CORRUPT_BKPT;
  80337. goto abort_due_to_error;
  80338. }
  80339. }
  80340. /* Opcode: Affinity P1 P2 * P4 *
  80341. ** Synopsis: affinity(r[P1@P2])
  80342. **
  80343. ** Apply affinities to a range of P2 registers starting with P1.
  80344. **
  80345. ** P4 is a string that is P2 characters long. The N-th character of the
  80346. ** string indicates the column affinity that should be used for the N-th
  80347. ** memory cell in the range.
  80348. */
  80349. case OP_Affinity: {
  80350. const char *zAffinity; /* The affinity to be applied */
  80351. zAffinity = pOp->p4.z;
  80352. assert( zAffinity!=0 );
  80353. assert( pOp->p2>0 );
  80354. assert( zAffinity[pOp->p2]==0 );
  80355. pIn1 = &aMem[pOp->p1];
  80356. do{
  80357. assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
  80358. assert( memIsValid(pIn1) );
  80359. applyAffinity(pIn1, *(zAffinity++), encoding);
  80360. pIn1++;
  80361. }while( zAffinity[0] );
  80362. break;
  80363. }
  80364. /* Opcode: MakeRecord P1 P2 P3 P4 *
  80365. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  80366. **
  80367. ** Convert P2 registers beginning with P1 into the [record format]
  80368. ** use as a data record in a database table or as a key
  80369. ** in an index. The OP_Column opcode can decode the record later.
  80370. **
  80371. ** P4 may be a string that is P2 characters long. The N-th character of the
  80372. ** string indicates the column affinity that should be used for the N-th
  80373. ** field of the index key.
  80374. **
  80375. ** The mapping from character to affinity is given by the SQLITE_AFF_
  80376. ** macros defined in sqliteInt.h.
  80377. **
  80378. ** If P4 is NULL then all index fields have the affinity BLOB.
  80379. */
  80380. case OP_MakeRecord: {
  80381. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  80382. Mem *pRec; /* The new record */
  80383. u64 nData; /* Number of bytes of data space */
  80384. int nHdr; /* Number of bytes of header space */
  80385. i64 nByte; /* Data space required for this record */
  80386. i64 nZero; /* Number of zero bytes at the end of the record */
  80387. int nVarint; /* Number of bytes in a varint */
  80388. u32 serial_type; /* Type field */
  80389. Mem *pData0; /* First field to be combined into the record */
  80390. Mem *pLast; /* Last field of the record */
  80391. int nField; /* Number of fields in the record */
  80392. char *zAffinity; /* The affinity string for the record */
  80393. int file_format; /* File format to use for encoding */
  80394. int i; /* Space used in zNewRecord[] header */
  80395. int j; /* Space used in zNewRecord[] content */
  80396. u32 len; /* Length of a field */
  80397. /* Assuming the record contains N fields, the record format looks
  80398. ** like this:
  80399. **
  80400. ** ------------------------------------------------------------------------
  80401. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  80402. ** ------------------------------------------------------------------------
  80403. **
  80404. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  80405. ** and so forth.
  80406. **
  80407. ** Each type field is a varint representing the serial type of the
  80408. ** corresponding data element (see sqlite3VdbeSerialType()). The
  80409. ** hdr-size field is also a varint which is the offset from the beginning
  80410. ** of the record to data0.
  80411. */
  80412. nData = 0; /* Number of bytes of data space */
  80413. nHdr = 0; /* Number of bytes of header space */
  80414. nZero = 0; /* Number of zero bytes at the end of the record */
  80415. nField = pOp->p1;
  80416. zAffinity = pOp->p4.z;
  80417. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
  80418. pData0 = &aMem[nField];
  80419. nField = pOp->p2;
  80420. pLast = &pData0[nField-1];
  80421. file_format = p->minWriteFileFormat;
  80422. /* Identify the output register */
  80423. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  80424. pOut = &aMem[pOp->p3];
  80425. memAboutToChange(p, pOut);
  80426. /* Apply the requested affinity to all inputs
  80427. */
  80428. assert( pData0<=pLast );
  80429. if( zAffinity ){
  80430. pRec = pData0;
  80431. do{
  80432. applyAffinity(pRec++, *(zAffinity++), encoding);
  80433. assert( zAffinity[0]==0 || pRec<=pLast );
  80434. }while( zAffinity[0] );
  80435. }
  80436. #ifdef SQLITE_ENABLE_NULL_TRIM
  80437. /* NULLs can be safely trimmed from the end of the record, as long as
  80438. ** as the schema format is 2 or more and none of the omitted columns
  80439. ** have a non-NULL default value. Also, the record must be left with
  80440. ** at least one field. If P5>0 then it will be one more than the
  80441. ** index of the right-most column with a non-NULL default value */
  80442. if( pOp->p5 ){
  80443. while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
  80444. pLast--;
  80445. nField--;
  80446. }
  80447. }
  80448. #endif
  80449. /* Loop through the elements that will make up the record to figure
  80450. ** out how much space is required for the new record.
  80451. */
  80452. pRec = pLast;
  80453. do{
  80454. assert( memIsValid(pRec) );
  80455. serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
  80456. if( pRec->flags & MEM_Zero ){
  80457. if( serial_type==0 ){
  80458. /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
  80459. ** table methods that never invoke sqlite3_result_xxxxx() while
  80460. ** computing an unchanging column value in an UPDATE statement.
  80461. ** Give such values a special internal-use-only serial-type of 10
  80462. ** so that they can be passed through to xUpdate and have
  80463. ** a true sqlite3_value_nochange(). */
  80464. assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
  80465. serial_type = 10;
  80466. }else if( nData ){
  80467. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  80468. }else{
  80469. nZero += pRec->u.nZero;
  80470. len -= pRec->u.nZero;
  80471. }
  80472. }
  80473. nData += len;
  80474. testcase( serial_type==127 );
  80475. testcase( serial_type==128 );
  80476. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  80477. pRec->uTemp = serial_type;
  80478. if( pRec==pData0 ) break;
  80479. pRec--;
  80480. }while(1);
  80481. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  80482. ** which determines the total number of bytes in the header. The varint
  80483. ** value is the size of the header in bytes including the size varint
  80484. ** itself. */
  80485. testcase( nHdr==126 );
  80486. testcase( nHdr==127 );
  80487. if( nHdr<=126 ){
  80488. /* The common case */
  80489. nHdr += 1;
  80490. }else{
  80491. /* Rare case of a really large header */
  80492. nVarint = sqlite3VarintLen(nHdr);
  80493. nHdr += nVarint;
  80494. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  80495. }
  80496. nByte = nHdr+nData;
  80497. /* Make sure the output register has a buffer large enough to store
  80498. ** the new record. The output register (pOp->p3) is not allowed to
  80499. ** be one of the input registers (because the following call to
  80500. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  80501. */
  80502. if( nByte+nZero<=pOut->szMalloc ){
  80503. /* The output register is already large enough to hold the record.
  80504. ** No error checks or buffer enlargement is required */
  80505. pOut->z = pOut->zMalloc;
  80506. }else{
  80507. /* Need to make sure that the output is not too big and then enlarge
  80508. ** the output register to hold the full result */
  80509. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  80510. goto too_big;
  80511. }
  80512. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  80513. goto no_mem;
  80514. }
  80515. }
  80516. zNewRecord = (u8 *)pOut->z;
  80517. /* Write the record */
  80518. i = putVarint32(zNewRecord, nHdr);
  80519. j = nHdr;
  80520. assert( pData0<=pLast );
  80521. pRec = pData0;
  80522. do{
  80523. serial_type = pRec->uTemp;
  80524. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  80525. ** additional varints, one per column. */
  80526. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  80527. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  80528. ** immediately follow the header. */
  80529. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  80530. }while( (++pRec)<=pLast );
  80531. assert( i==nHdr );
  80532. assert( j==nByte );
  80533. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  80534. pOut->n = (int)nByte;
  80535. pOut->flags = MEM_Blob;
  80536. if( nZero ){
  80537. pOut->u.nZero = nZero;
  80538. pOut->flags |= MEM_Zero;
  80539. }
  80540. REGISTER_TRACE(pOp->p3, pOut);
  80541. UPDATE_MAX_BLOBSIZE(pOut);
  80542. break;
  80543. }
  80544. /* Opcode: Count P1 P2 * * *
  80545. ** Synopsis: r[P2]=count()
  80546. **
  80547. ** Store the number of entries (an integer value) in the table or index
  80548. ** opened by cursor P1 in register P2
  80549. */
  80550. #ifndef SQLITE_OMIT_BTREECOUNT
  80551. case OP_Count: { /* out2 */
  80552. i64 nEntry;
  80553. BtCursor *pCrsr;
  80554. assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
  80555. pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
  80556. assert( pCrsr );
  80557. nEntry = 0; /* Not needed. Only used to silence a warning. */
  80558. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  80559. if( rc ) goto abort_due_to_error;
  80560. pOut = out2Prerelease(p, pOp);
  80561. pOut->u.i = nEntry;
  80562. break;
  80563. }
  80564. #endif
  80565. /* Opcode: Savepoint P1 * * P4 *
  80566. **
  80567. ** Open, release or rollback the savepoint named by parameter P4, depending
  80568. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  80569. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  80570. */
  80571. case OP_Savepoint: {
  80572. int p1; /* Value of P1 operand */
  80573. char *zName; /* Name of savepoint */
  80574. int nName;
  80575. Savepoint *pNew;
  80576. Savepoint *pSavepoint;
  80577. Savepoint *pTmp;
  80578. int iSavepoint;
  80579. int ii;
  80580. p1 = pOp->p1;
  80581. zName = pOp->p4.z;
  80582. /* Assert that the p1 parameter is valid. Also that if there is no open
  80583. ** transaction, then there cannot be any savepoints.
  80584. */
  80585. assert( db->pSavepoint==0 || db->autoCommit==0 );
  80586. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  80587. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  80588. assert( checkSavepointCount(db) );
  80589. assert( p->bIsReader );
  80590. if( p1==SAVEPOINT_BEGIN ){
  80591. if( db->nVdbeWrite>0 ){
  80592. /* A new savepoint cannot be created if there are active write
  80593. ** statements (i.e. open read/write incremental blob handles).
  80594. */
  80595. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  80596. rc = SQLITE_BUSY;
  80597. }else{
  80598. nName = sqlite3Strlen30(zName);
  80599. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80600. /* This call is Ok even if this savepoint is actually a transaction
  80601. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  80602. ** If this is a transaction savepoint being opened, it is guaranteed
  80603. ** that the db->aVTrans[] array is empty. */
  80604. assert( db->autoCommit==0 || db->nVTrans==0 );
  80605. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  80606. db->nStatement+db->nSavepoint);
  80607. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  80608. #endif
  80609. /* Create a new savepoint structure. */
  80610. pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
  80611. if( pNew ){
  80612. pNew->zName = (char *)&pNew[1];
  80613. memcpy(pNew->zName, zName, nName+1);
  80614. /* If there is no open transaction, then mark this as a special
  80615. ** "transaction savepoint". */
  80616. if( db->autoCommit ){
  80617. db->autoCommit = 0;
  80618. db->isTransactionSavepoint = 1;
  80619. }else{
  80620. db->nSavepoint++;
  80621. }
  80622. /* Link the new savepoint into the database handle's list. */
  80623. pNew->pNext = db->pSavepoint;
  80624. db->pSavepoint = pNew;
  80625. pNew->nDeferredCons = db->nDeferredCons;
  80626. pNew->nDeferredImmCons = db->nDeferredImmCons;
  80627. }
  80628. }
  80629. }else{
  80630. iSavepoint = 0;
  80631. /* Find the named savepoint. If there is no such savepoint, then an
  80632. ** an error is returned to the user. */
  80633. for(
  80634. pSavepoint = db->pSavepoint;
  80635. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  80636. pSavepoint = pSavepoint->pNext
  80637. ){
  80638. iSavepoint++;
  80639. }
  80640. if( !pSavepoint ){
  80641. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  80642. rc = SQLITE_ERROR;
  80643. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  80644. /* It is not possible to release (commit) a savepoint if there are
  80645. ** active write statements.
  80646. */
  80647. sqlite3VdbeError(p, "cannot release savepoint - "
  80648. "SQL statements in progress");
  80649. rc = SQLITE_BUSY;
  80650. }else{
  80651. /* Determine whether or not this is a transaction savepoint. If so,
  80652. ** and this is a RELEASE command, then the current transaction
  80653. ** is committed.
  80654. */
  80655. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  80656. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  80657. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  80658. goto vdbe_return;
  80659. }
  80660. db->autoCommit = 1;
  80661. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  80662. p->pc = (int)(pOp - aOp);
  80663. db->autoCommit = 0;
  80664. p->rc = rc = SQLITE_BUSY;
  80665. goto vdbe_return;
  80666. }
  80667. db->isTransactionSavepoint = 0;
  80668. rc = p->rc;
  80669. }else{
  80670. int isSchemaChange;
  80671. iSavepoint = db->nSavepoint - iSavepoint - 1;
  80672. if( p1==SAVEPOINT_ROLLBACK ){
  80673. isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
  80674. for(ii=0; ii<db->nDb; ii++){
  80675. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  80676. SQLITE_ABORT_ROLLBACK,
  80677. isSchemaChange==0);
  80678. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  80679. }
  80680. }else{
  80681. isSchemaChange = 0;
  80682. }
  80683. for(ii=0; ii<db->nDb; ii++){
  80684. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  80685. if( rc!=SQLITE_OK ){
  80686. goto abort_due_to_error;
  80687. }
  80688. }
  80689. if( isSchemaChange ){
  80690. sqlite3ExpirePreparedStatements(db, 0);
  80691. sqlite3ResetAllSchemasOfConnection(db);
  80692. db->mDbFlags |= DBFLAG_SchemaChange;
  80693. }
  80694. }
  80695. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  80696. ** savepoints nested inside of the savepoint being operated on. */
  80697. while( db->pSavepoint!=pSavepoint ){
  80698. pTmp = db->pSavepoint;
  80699. db->pSavepoint = pTmp->pNext;
  80700. sqlite3DbFree(db, pTmp);
  80701. db->nSavepoint--;
  80702. }
  80703. /* If it is a RELEASE, then destroy the savepoint being operated on
  80704. ** too. If it is a ROLLBACK TO, then set the number of deferred
  80705. ** constraint violations present in the database to the value stored
  80706. ** when the savepoint was created. */
  80707. if( p1==SAVEPOINT_RELEASE ){
  80708. assert( pSavepoint==db->pSavepoint );
  80709. db->pSavepoint = pSavepoint->pNext;
  80710. sqlite3DbFree(db, pSavepoint);
  80711. if( !isTransaction ){
  80712. db->nSavepoint--;
  80713. }
  80714. }else{
  80715. db->nDeferredCons = pSavepoint->nDeferredCons;
  80716. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  80717. }
  80718. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  80719. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  80720. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  80721. }
  80722. }
  80723. }
  80724. if( rc ) goto abort_due_to_error;
  80725. break;
  80726. }
  80727. /* Opcode: AutoCommit P1 P2 * * *
  80728. **
  80729. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  80730. ** back any currently active btree transactions. If there are any active
  80731. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  80732. ** there are active writing VMs or active VMs that use shared cache.
  80733. **
  80734. ** This instruction causes the VM to halt.
  80735. */
  80736. case OP_AutoCommit: {
  80737. int desiredAutoCommit;
  80738. int iRollback;
  80739. desiredAutoCommit = pOp->p1;
  80740. iRollback = pOp->p2;
  80741. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  80742. assert( desiredAutoCommit==1 || iRollback==0 );
  80743. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  80744. assert( p->bIsReader );
  80745. if( desiredAutoCommit!=db->autoCommit ){
  80746. if( iRollback ){
  80747. assert( desiredAutoCommit==1 );
  80748. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  80749. db->autoCommit = 1;
  80750. }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
  80751. /* If this instruction implements a COMMIT and other VMs are writing
  80752. ** return an error indicating that the other VMs must complete first.
  80753. */
  80754. sqlite3VdbeError(p, "cannot commit transaction - "
  80755. "SQL statements in progress");
  80756. rc = SQLITE_BUSY;
  80757. goto abort_due_to_error;
  80758. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  80759. goto vdbe_return;
  80760. }else{
  80761. db->autoCommit = (u8)desiredAutoCommit;
  80762. }
  80763. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  80764. p->pc = (int)(pOp - aOp);
  80765. db->autoCommit = (u8)(1-desiredAutoCommit);
  80766. p->rc = rc = SQLITE_BUSY;
  80767. goto vdbe_return;
  80768. }
  80769. assert( db->nStatement==0 );
  80770. sqlite3CloseSavepoints(db);
  80771. if( p->rc==SQLITE_OK ){
  80772. rc = SQLITE_DONE;
  80773. }else{
  80774. rc = SQLITE_ERROR;
  80775. }
  80776. goto vdbe_return;
  80777. }else{
  80778. sqlite3VdbeError(p,
  80779. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  80780. (iRollback)?"cannot rollback - no transaction is active":
  80781. "cannot commit - no transaction is active"));
  80782. rc = SQLITE_ERROR;
  80783. goto abort_due_to_error;
  80784. }
  80785. break;
  80786. }
  80787. /* Opcode: Transaction P1 P2 P3 P4 P5
  80788. **
  80789. ** Begin a transaction on database P1 if a transaction is not already
  80790. ** active.
  80791. ** If P2 is non-zero, then a write-transaction is started, or if a
  80792. ** read-transaction is already active, it is upgraded to a write-transaction.
  80793. ** If P2 is zero, then a read-transaction is started.
  80794. **
  80795. ** P1 is the index of the database file on which the transaction is
  80796. ** started. Index 0 is the main database file and index 1 is the
  80797. ** file used for temporary tables. Indices of 2 or more are used for
  80798. ** attached databases.
  80799. **
  80800. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  80801. ** true (this flag is set if the Vdbe may modify more than one row and may
  80802. ** throw an ABORT exception), a statement transaction may also be opened.
  80803. ** More specifically, a statement transaction is opened iff the database
  80804. ** connection is currently not in autocommit mode, or if there are other
  80805. ** active statements. A statement transaction allows the changes made by this
  80806. ** VDBE to be rolled back after an error without having to roll back the
  80807. ** entire transaction. If no error is encountered, the statement transaction
  80808. ** will automatically commit when the VDBE halts.
  80809. **
  80810. ** If P5!=0 then this opcode also checks the schema cookie against P3
  80811. ** and the schema generation counter against P4.
  80812. ** The cookie changes its value whenever the database schema changes.
  80813. ** This operation is used to detect when that the cookie has changed
  80814. ** and that the current process needs to reread the schema. If the schema
  80815. ** cookie in P3 differs from the schema cookie in the database header or
  80816. ** if the schema generation counter in P4 differs from the current
  80817. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  80818. ** halts. The sqlite3_step() wrapper function might then reprepare the
  80819. ** statement and rerun it from the beginning.
  80820. */
  80821. case OP_Transaction: {
  80822. Btree *pBt;
  80823. int iMeta = 0;
  80824. assert( p->bIsReader );
  80825. assert( p->readOnly==0 || pOp->p2==0 );
  80826. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  80827. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  80828. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  80829. rc = SQLITE_READONLY;
  80830. goto abort_due_to_error;
  80831. }
  80832. pBt = db->aDb[pOp->p1].pBt;
  80833. if( pBt ){
  80834. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
  80835. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  80836. testcase( rc==SQLITE_BUSY_RECOVERY );
  80837. if( rc!=SQLITE_OK ){
  80838. if( (rc&0xff)==SQLITE_BUSY ){
  80839. p->pc = (int)(pOp - aOp);
  80840. p->rc = rc;
  80841. goto vdbe_return;
  80842. }
  80843. goto abort_due_to_error;
  80844. }
  80845. if( pOp->p2 && p->usesStmtJournal
  80846. && (db->autoCommit==0 || db->nVdbeRead>1)
  80847. ){
  80848. assert( sqlite3BtreeIsInTrans(pBt) );
  80849. if( p->iStatement==0 ){
  80850. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  80851. db->nStatement++;
  80852. p->iStatement = db->nSavepoint + db->nStatement;
  80853. }
  80854. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  80855. if( rc==SQLITE_OK ){
  80856. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  80857. }
  80858. /* Store the current value of the database handles deferred constraint
  80859. ** counter. If the statement transaction needs to be rolled back,
  80860. ** the value of this counter needs to be restored too. */
  80861. p->nStmtDefCons = db->nDeferredCons;
  80862. p->nStmtDefImmCons = db->nDeferredImmCons;
  80863. }
  80864. }
  80865. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  80866. if( pOp->p5
  80867. && (iMeta!=pOp->p3
  80868. || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
  80869. ){
  80870. /*
  80871. ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
  80872. ** version is checked to ensure that the schema has not changed since the
  80873. ** SQL statement was prepared.
  80874. */
  80875. sqlite3DbFree(db, p->zErrMsg);
  80876. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  80877. /* If the schema-cookie from the database file matches the cookie
  80878. ** stored with the in-memory representation of the schema, do
  80879. ** not reload the schema from the database file.
  80880. **
  80881. ** If virtual-tables are in use, this is not just an optimization.
  80882. ** Often, v-tables store their data in other SQLite tables, which
  80883. ** are queried from within xNext() and other v-table methods using
  80884. ** prepared queries. If such a query is out-of-date, we do not want to
  80885. ** discard the database schema, as the user code implementing the
  80886. ** v-table would have to be ready for the sqlite3_vtab structure itself
  80887. ** to be invalidated whenever sqlite3_step() is called from within
  80888. ** a v-table method.
  80889. */
  80890. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  80891. sqlite3ResetOneSchema(db, pOp->p1);
  80892. }
  80893. p->expired = 1;
  80894. rc = SQLITE_SCHEMA;
  80895. }
  80896. if( rc ) goto abort_due_to_error;
  80897. break;
  80898. }
  80899. /* Opcode: ReadCookie P1 P2 P3 * *
  80900. **
  80901. ** Read cookie number P3 from database P1 and write it into register P2.
  80902. ** P3==1 is the schema version. P3==2 is the database format.
  80903. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  80904. ** the main database file and P1==1 is the database file used to store
  80905. ** temporary tables.
  80906. **
  80907. ** There must be a read-lock on the database (either a transaction
  80908. ** must be started or there must be an open cursor) before
  80909. ** executing this instruction.
  80910. */
  80911. case OP_ReadCookie: { /* out2 */
  80912. int iMeta;
  80913. int iDb;
  80914. int iCookie;
  80915. assert( p->bIsReader );
  80916. iDb = pOp->p1;
  80917. iCookie = pOp->p3;
  80918. assert( pOp->p3<SQLITE_N_BTREE_META );
  80919. assert( iDb>=0 && iDb<db->nDb );
  80920. assert( db->aDb[iDb].pBt!=0 );
  80921. assert( DbMaskTest(p->btreeMask, iDb) );
  80922. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  80923. pOut = out2Prerelease(p, pOp);
  80924. pOut->u.i = iMeta;
  80925. break;
  80926. }
  80927. /* Opcode: SetCookie P1 P2 P3 * *
  80928. **
  80929. ** Write the integer value P3 into cookie number P2 of database P1.
  80930. ** P2==1 is the schema version. P2==2 is the database format.
  80931. ** P2==3 is the recommended pager cache
  80932. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  80933. ** database file used to store temporary tables.
  80934. **
  80935. ** A transaction must be started before executing this opcode.
  80936. */
  80937. case OP_SetCookie: {
  80938. Db *pDb;
  80939. sqlite3VdbeIncrWriteCounter(p, 0);
  80940. assert( pOp->p2<SQLITE_N_BTREE_META );
  80941. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  80942. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  80943. assert( p->readOnly==0 );
  80944. pDb = &db->aDb[pOp->p1];
  80945. assert( pDb->pBt!=0 );
  80946. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  80947. /* See note about index shifting on OP_ReadCookie */
  80948. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
  80949. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  80950. /* When the schema cookie changes, record the new cookie internally */
  80951. pDb->pSchema->schema_cookie = pOp->p3;
  80952. db->mDbFlags |= DBFLAG_SchemaChange;
  80953. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  80954. /* Record changes in the file format */
  80955. pDb->pSchema->file_format = pOp->p3;
  80956. }
  80957. if( pOp->p1==1 ){
  80958. /* Invalidate all prepared statements whenever the TEMP database
  80959. ** schema is changed. Ticket #1644 */
  80960. sqlite3ExpirePreparedStatements(db, 0);
  80961. p->expired = 0;
  80962. }
  80963. if( rc ) goto abort_due_to_error;
  80964. break;
  80965. }
  80966. /* Opcode: OpenRead P1 P2 P3 P4 P5
  80967. ** Synopsis: root=P2 iDb=P3
  80968. **
  80969. ** Open a read-only cursor for the database table whose root page is
  80970. ** P2 in a database file. The database file is determined by P3.
  80971. ** P3==0 means the main database, P3==1 means the database used for
  80972. ** temporary tables, and P3>1 means used the corresponding attached
  80973. ** database. Give the new cursor an identifier of P1. The P1
  80974. ** values need not be contiguous but all P1 values should be small integers.
  80975. ** It is an error for P1 to be negative.
  80976. **
  80977. ** Allowed P5 bits:
  80978. ** <ul>
  80979. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  80980. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  80981. ** of OP_SeekLE/OP_IdxGT)
  80982. ** </ul>
  80983. **
  80984. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  80985. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  80986. ** object, then table being opened must be an [index b-tree] where the
  80987. ** KeyInfo object defines the content and collating
  80988. ** sequence of that index b-tree. Otherwise, if P4 is an integer
  80989. ** value, then the table being opened must be a [table b-tree] with a
  80990. ** number of columns no less than the value of P4.
  80991. **
  80992. ** See also: OpenWrite, ReopenIdx
  80993. */
  80994. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  80995. ** Synopsis: root=P2 iDb=P3
  80996. **
  80997. ** The ReopenIdx opcode works like OP_OpenRead except that it first
  80998. ** checks to see if the cursor on P1 is already open on the same
  80999. ** b-tree and if it is this opcode becomes a no-op. In other words,
  81000. ** if the cursor is already open, do not reopen it.
  81001. **
  81002. ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
  81003. ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
  81004. ** be the same as every other ReopenIdx or OpenRead for the same cursor
  81005. ** number.
  81006. **
  81007. ** Allowed P5 bits:
  81008. ** <ul>
  81009. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  81010. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  81011. ** of OP_SeekLE/OP_IdxGT)
  81012. ** </ul>
  81013. **
  81014. ** See also: OP_OpenRead, OP_OpenWrite
  81015. */
  81016. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  81017. ** Synopsis: root=P2 iDb=P3
  81018. **
  81019. ** Open a read/write cursor named P1 on the table or index whose root
  81020. ** page is P2 (or whose root page is held in register P2 if the
  81021. ** OPFLAG_P2ISREG bit is set in P5 - see below).
  81022. **
  81023. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  81024. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  81025. ** object, then table being opened must be an [index b-tree] where the
  81026. ** KeyInfo object defines the content and collating
  81027. ** sequence of that index b-tree. Otherwise, if P4 is an integer
  81028. ** value, then the table being opened must be a [table b-tree] with a
  81029. ** number of columns no less than the value of P4.
  81030. **
  81031. ** Allowed P5 bits:
  81032. ** <ul>
  81033. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  81034. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  81035. ** of OP_SeekLE/OP_IdxGT)
  81036. ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
  81037. ** and subsequently delete entries in an index btree. This is a
  81038. ** hint to the storage engine that the storage engine is allowed to
  81039. ** ignore. The hint is not used by the official SQLite b*tree storage
  81040. ** engine, but is used by COMDB2.
  81041. ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
  81042. ** as the root page, not the value of P2 itself.
  81043. ** </ul>
  81044. **
  81045. ** This instruction works like OpenRead except that it opens the cursor
  81046. ** in read/write mode.
  81047. **
  81048. ** See also: OP_OpenRead, OP_ReopenIdx
  81049. */
  81050. case OP_ReopenIdx: {
  81051. int nField;
  81052. KeyInfo *pKeyInfo;
  81053. int p2;
  81054. int iDb;
  81055. int wrFlag;
  81056. Btree *pX;
  81057. VdbeCursor *pCur;
  81058. Db *pDb;
  81059. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  81060. assert( pOp->p4type==P4_KEYINFO );
  81061. pCur = p->apCsr[pOp->p1];
  81062. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  81063. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  81064. goto open_cursor_set_hints;
  81065. }
  81066. /* If the cursor is not currently open or is open on a different
  81067. ** index, then fall through into OP_OpenRead to force a reopen */
  81068. case OP_OpenRead:
  81069. case OP_OpenWrite:
  81070. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  81071. assert( p->bIsReader );
  81072. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  81073. || p->readOnly==0 );
  81074. if( p->expired==1 ){
  81075. rc = SQLITE_ABORT_ROLLBACK;
  81076. goto abort_due_to_error;
  81077. }
  81078. nField = 0;
  81079. pKeyInfo = 0;
  81080. p2 = pOp->p2;
  81081. iDb = pOp->p3;
  81082. assert( iDb>=0 && iDb<db->nDb );
  81083. assert( DbMaskTest(p->btreeMask, iDb) );
  81084. pDb = &db->aDb[iDb];
  81085. pX = pDb->pBt;
  81086. assert( pX!=0 );
  81087. if( pOp->opcode==OP_OpenWrite ){
  81088. assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
  81089. wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
  81090. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81091. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  81092. p->minWriteFileFormat = pDb->pSchema->file_format;
  81093. }
  81094. }else{
  81095. wrFlag = 0;
  81096. }
  81097. if( pOp->p5 & OPFLAG_P2ISREG ){
  81098. assert( p2>0 );
  81099. assert( p2<=(p->nMem+1 - p->nCursor) );
  81100. assert( pOp->opcode==OP_OpenWrite );
  81101. pIn2 = &aMem[p2];
  81102. assert( memIsValid(pIn2) );
  81103. assert( (pIn2->flags & MEM_Int)!=0 );
  81104. sqlite3VdbeMemIntegerify(pIn2);
  81105. p2 = (int)pIn2->u.i;
  81106. /* The p2 value always comes from a prior OP_CreateBtree opcode and
  81107. ** that opcode will always set the p2 value to 2 or more or else fail.
  81108. ** If there were a failure, the prepared statement would have halted
  81109. ** before reaching this instruction. */
  81110. assert( p2>=2 );
  81111. }
  81112. if( pOp->p4type==P4_KEYINFO ){
  81113. pKeyInfo = pOp->p4.pKeyInfo;
  81114. assert( pKeyInfo->enc==ENC(db) );
  81115. assert( pKeyInfo->db==db );
  81116. nField = pKeyInfo->nAllField;
  81117. }else if( pOp->p4type==P4_INT32 ){
  81118. nField = pOp->p4.i;
  81119. }
  81120. assert( pOp->p1>=0 );
  81121. assert( nField>=0 );
  81122. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  81123. pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
  81124. if( pCur==0 ) goto no_mem;
  81125. pCur->nullRow = 1;
  81126. pCur->isOrdered = 1;
  81127. pCur->pgnoRoot = p2;
  81128. #ifdef SQLITE_DEBUG
  81129. pCur->wrFlag = wrFlag;
  81130. #endif
  81131. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
  81132. pCur->pKeyInfo = pKeyInfo;
  81133. /* Set the VdbeCursor.isTable variable. Previous versions of
  81134. ** SQLite used to check if the root-page flags were sane at this point
  81135. ** and report database corruption if they were not, but this check has
  81136. ** since moved into the btree layer. */
  81137. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  81138. open_cursor_set_hints:
  81139. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  81140. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  81141. testcase( pOp->p5 & OPFLAG_BULKCSR );
  81142. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  81143. testcase( pOp->p2 & OPFLAG_SEEKEQ );
  81144. #endif
  81145. sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
  81146. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  81147. if( rc ) goto abort_due_to_error;
  81148. break;
  81149. }
  81150. /* Opcode: OpenDup P1 P2 * * *
  81151. **
  81152. ** Open a new cursor P1 that points to the same ephemeral table as
  81153. ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
  81154. ** opcode. Only ephemeral cursors may be duplicated.
  81155. **
  81156. ** Duplicate ephemeral cursors are used for self-joins of materialized views.
  81157. */
  81158. case OP_OpenDup: {
  81159. VdbeCursor *pOrig; /* The original cursor to be duplicated */
  81160. VdbeCursor *pCx; /* The new cursor */
  81161. pOrig = p->apCsr[pOp->p2];
  81162. assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
  81163. pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
  81164. if( pCx==0 ) goto no_mem;
  81165. pCx->nullRow = 1;
  81166. pCx->isEphemeral = 1;
  81167. pCx->pKeyInfo = pOrig->pKeyInfo;
  81168. pCx->isTable = pOrig->isTable;
  81169. rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
  81170. pCx->pKeyInfo, pCx->uc.pCursor);
  81171. /* The sqlite3BtreeCursor() routine can only fail for the first cursor
  81172. ** opened for a database. Since there is already an open cursor when this
  81173. ** opcode is run, the sqlite3BtreeCursor() cannot fail */
  81174. assert( rc==SQLITE_OK );
  81175. break;
  81176. }
  81177. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  81178. ** Synopsis: nColumn=P2
  81179. **
  81180. ** Open a new cursor P1 to a transient table.
  81181. ** The cursor is always opened read/write even if
  81182. ** the main database is read-only. The ephemeral
  81183. ** table is deleted automatically when the cursor is closed.
  81184. **
  81185. ** P2 is the number of columns in the ephemeral table.
  81186. ** The cursor points to a BTree table if P4==0 and to a BTree index
  81187. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  81188. ** that defines the format of keys in the index.
  81189. **
  81190. ** The P5 parameter can be a mask of the BTREE_* flags defined
  81191. ** in btree.h. These flags control aspects of the operation of
  81192. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  81193. ** added automatically.
  81194. */
  81195. /* Opcode: OpenAutoindex P1 P2 * P4 *
  81196. ** Synopsis: nColumn=P2
  81197. **
  81198. ** This opcode works the same as OP_OpenEphemeral. It has a
  81199. ** different name to distinguish its use. Tables created using
  81200. ** by this opcode will be used for automatically created transient
  81201. ** indices in joins.
  81202. */
  81203. case OP_OpenAutoindex:
  81204. case OP_OpenEphemeral: {
  81205. VdbeCursor *pCx;
  81206. KeyInfo *pKeyInfo;
  81207. static const int vfsFlags =
  81208. SQLITE_OPEN_READWRITE |
  81209. SQLITE_OPEN_CREATE |
  81210. SQLITE_OPEN_EXCLUSIVE |
  81211. SQLITE_OPEN_DELETEONCLOSE |
  81212. SQLITE_OPEN_TRANSIENT_DB;
  81213. assert( pOp->p1>=0 );
  81214. assert( pOp->p2>=0 );
  81215. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
  81216. if( pCx==0 ) goto no_mem;
  81217. pCx->nullRow = 1;
  81218. pCx->isEphemeral = 1;
  81219. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
  81220. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  81221. if( rc==SQLITE_OK ){
  81222. rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
  81223. }
  81224. if( rc==SQLITE_OK ){
  81225. /* If a transient index is required, create it by calling
  81226. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  81227. ** opening it. If a transient table is required, just use the
  81228. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  81229. */
  81230. if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  81231. int pgno;
  81232. assert( pOp->p4type==P4_KEYINFO );
  81233. rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
  81234. if( rc==SQLITE_OK ){
  81235. assert( pgno==MASTER_ROOT+1 );
  81236. assert( pKeyInfo->db==db );
  81237. assert( pKeyInfo->enc==ENC(db) );
  81238. rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
  81239. pKeyInfo, pCx->uc.pCursor);
  81240. }
  81241. pCx->isTable = 0;
  81242. }else{
  81243. rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
  81244. 0, pCx->uc.pCursor);
  81245. pCx->isTable = 1;
  81246. }
  81247. }
  81248. if( rc ) goto abort_due_to_error;
  81249. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  81250. break;
  81251. }
  81252. /* Opcode: SorterOpen P1 P2 P3 P4 *
  81253. **
  81254. ** This opcode works like OP_OpenEphemeral except that it opens
  81255. ** a transient index that is specifically designed to sort large
  81256. ** tables using an external merge-sort algorithm.
  81257. **
  81258. ** If argument P3 is non-zero, then it indicates that the sorter may
  81259. ** assume that a stable sort considering the first P3 fields of each
  81260. ** key is sufficient to produce the required results.
  81261. */
  81262. case OP_SorterOpen: {
  81263. VdbeCursor *pCx;
  81264. assert( pOp->p1>=0 );
  81265. assert( pOp->p2>=0 );
  81266. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
  81267. if( pCx==0 ) goto no_mem;
  81268. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  81269. assert( pCx->pKeyInfo->db==db );
  81270. assert( pCx->pKeyInfo->enc==ENC(db) );
  81271. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  81272. if( rc ) goto abort_due_to_error;
  81273. break;
  81274. }
  81275. /* Opcode: SequenceTest P1 P2 * * *
  81276. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  81277. **
  81278. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  81279. ** to P2. Regardless of whether or not the jump is taken, increment the
  81280. ** the sequence value.
  81281. */
  81282. case OP_SequenceTest: {
  81283. VdbeCursor *pC;
  81284. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81285. pC = p->apCsr[pOp->p1];
  81286. assert( isSorter(pC) );
  81287. if( (pC->seqCount++)==0 ){
  81288. goto jump_to_p2;
  81289. }
  81290. break;
  81291. }
  81292. /* Opcode: OpenPseudo P1 P2 P3 * *
  81293. ** Synopsis: P3 columns in r[P2]
  81294. **
  81295. ** Open a new cursor that points to a fake table that contains a single
  81296. ** row of data. The content of that one row is the content of memory
  81297. ** register P2. In other words, cursor P1 becomes an alias for the
  81298. ** MEM_Blob content contained in register P2.
  81299. **
  81300. ** A pseudo-table created by this opcode is used to hold a single
  81301. ** row output from the sorter so that the row can be decomposed into
  81302. ** individual columns using the OP_Column opcode. The OP_Column opcode
  81303. ** is the only cursor opcode that works with a pseudo-table.
  81304. **
  81305. ** P3 is the number of fields in the records that will be stored by
  81306. ** the pseudo-table.
  81307. */
  81308. case OP_OpenPseudo: {
  81309. VdbeCursor *pCx;
  81310. assert( pOp->p1>=0 );
  81311. assert( pOp->p3>=0 );
  81312. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
  81313. if( pCx==0 ) goto no_mem;
  81314. pCx->nullRow = 1;
  81315. pCx->seekResult = pOp->p2;
  81316. pCx->isTable = 1;
  81317. /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
  81318. ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
  81319. ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
  81320. ** which is a performance optimization */
  81321. pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
  81322. assert( pOp->p5==0 );
  81323. break;
  81324. }
  81325. /* Opcode: Close P1 * * * *
  81326. **
  81327. ** Close a cursor previously opened as P1. If P1 is not
  81328. ** currently open, this instruction is a no-op.
  81329. */
  81330. case OP_Close: {
  81331. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81332. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  81333. p->apCsr[pOp->p1] = 0;
  81334. break;
  81335. }
  81336. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  81337. /* Opcode: ColumnsUsed P1 * * P4 *
  81338. **
  81339. ** This opcode (which only exists if SQLite was compiled with
  81340. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  81341. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  81342. ** (P4_INT64) in which the first 63 bits are one for each of the
  81343. ** first 63 columns of the table or index that are actually used
  81344. ** by the cursor. The high-order bit is set if any column after
  81345. ** the 64th is used.
  81346. */
  81347. case OP_ColumnsUsed: {
  81348. VdbeCursor *pC;
  81349. pC = p->apCsr[pOp->p1];
  81350. assert( pC->eCurType==CURTYPE_BTREE );
  81351. pC->maskUsed = *(u64*)pOp->p4.pI64;
  81352. break;
  81353. }
  81354. #endif
  81355. /* Opcode: SeekGE P1 P2 P3 P4 *
  81356. ** Synopsis: key=r[P3@P4]
  81357. **
  81358. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  81359. ** use the value in register P3 as the key. If cursor P1 refers
  81360. ** to an SQL index, then P3 is the first in an array of P4 registers
  81361. ** that are used as an unpacked index key.
  81362. **
  81363. ** Reposition cursor P1 so that it points to the smallest entry that
  81364. ** is greater than or equal to the key value. If there are no records
  81365. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  81366. **
  81367. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  81368. ** opcode will always land on a record that equally equals the key, or
  81369. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  81370. ** opcode must be followed by an IdxLE opcode with the same arguments.
  81371. ** The IdxLE opcode will be skipped if this opcode succeeds, but the
  81372. ** IdxLE opcode will be used on subsequent loop iterations.
  81373. **
  81374. ** This opcode leaves the cursor configured to move in forward order,
  81375. ** from the beginning toward the end. In other words, the cursor is
  81376. ** configured to use Next, not Prev.
  81377. **
  81378. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  81379. */
  81380. /* Opcode: SeekGT P1 P2 P3 P4 *
  81381. ** Synopsis: key=r[P3@P4]
  81382. **
  81383. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  81384. ** use the value in register P3 as a key. If cursor P1 refers
  81385. ** to an SQL index, then P3 is the first in an array of P4 registers
  81386. ** that are used as an unpacked index key.
  81387. **
  81388. ** Reposition cursor P1 so that it points to the smallest entry that
  81389. ** is greater than the key value. If there are no records greater than
  81390. ** the key and P2 is not zero, then jump to P2.
  81391. **
  81392. ** This opcode leaves the cursor configured to move in forward order,
  81393. ** from the beginning toward the end. In other words, the cursor is
  81394. ** configured to use Next, not Prev.
  81395. **
  81396. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  81397. */
  81398. /* Opcode: SeekLT P1 P2 P3 P4 *
  81399. ** Synopsis: key=r[P3@P4]
  81400. **
  81401. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  81402. ** use the value in register P3 as a key. If cursor P1 refers
  81403. ** to an SQL index, then P3 is the first in an array of P4 registers
  81404. ** that are used as an unpacked index key.
  81405. **
  81406. ** Reposition cursor P1 so that it points to the largest entry that
  81407. ** is less than the key value. If there are no records less than
  81408. ** the key and P2 is not zero, then jump to P2.
  81409. **
  81410. ** This opcode leaves the cursor configured to move in reverse order,
  81411. ** from the end toward the beginning. In other words, the cursor is
  81412. ** configured to use Prev, not Next.
  81413. **
  81414. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  81415. */
  81416. /* Opcode: SeekLE P1 P2 P3 P4 *
  81417. ** Synopsis: key=r[P3@P4]
  81418. **
  81419. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  81420. ** use the value in register P3 as a key. If cursor P1 refers
  81421. ** to an SQL index, then P3 is the first in an array of P4 registers
  81422. ** that are used as an unpacked index key.
  81423. **
  81424. ** Reposition cursor P1 so that it points to the largest entry that
  81425. ** is less than or equal to the key value. If there are no records
  81426. ** less than or equal to the key and P2 is not zero, then jump to P2.
  81427. **
  81428. ** This opcode leaves the cursor configured to move in reverse order,
  81429. ** from the end toward the beginning. In other words, the cursor is
  81430. ** configured to use Prev, not Next.
  81431. **
  81432. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  81433. ** opcode will always land on a record that equally equals the key, or
  81434. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  81435. ** opcode must be followed by an IdxGE opcode with the same arguments.
  81436. ** The IdxGE opcode will be skipped if this opcode succeeds, but the
  81437. ** IdxGE opcode will be used on subsequent loop iterations.
  81438. **
  81439. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  81440. */
  81441. case OP_SeekLT: /* jump, in3, group */
  81442. case OP_SeekLE: /* jump, in3, group */
  81443. case OP_SeekGE: /* jump, in3, group */
  81444. case OP_SeekGT: { /* jump, in3, group */
  81445. int res; /* Comparison result */
  81446. int oc; /* Opcode */
  81447. VdbeCursor *pC; /* The cursor to seek */
  81448. UnpackedRecord r; /* The key to seek for */
  81449. int nField; /* Number of columns or fields in the key */
  81450. i64 iKey; /* The rowid we are to seek to */
  81451. int eqOnly; /* Only interested in == results */
  81452. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81453. assert( pOp->p2!=0 );
  81454. pC = p->apCsr[pOp->p1];
  81455. assert( pC!=0 );
  81456. assert( pC->eCurType==CURTYPE_BTREE );
  81457. assert( OP_SeekLE == OP_SeekLT+1 );
  81458. assert( OP_SeekGE == OP_SeekLT+2 );
  81459. assert( OP_SeekGT == OP_SeekLT+3 );
  81460. assert( pC->isOrdered );
  81461. assert( pC->uc.pCursor!=0 );
  81462. oc = pOp->opcode;
  81463. eqOnly = 0;
  81464. pC->nullRow = 0;
  81465. #ifdef SQLITE_DEBUG
  81466. pC->seekOp = pOp->opcode;
  81467. #endif
  81468. if( pC->isTable ){
  81469. /* The BTREE_SEEK_EQ flag is only set on index cursors */
  81470. assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
  81471. || CORRUPT_DB );
  81472. /* The input value in P3 might be of any type: integer, real, string,
  81473. ** blob, or NULL. But it needs to be an integer before we can do
  81474. ** the seek, so convert it. */
  81475. pIn3 = &aMem[pOp->p3];
  81476. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  81477. applyNumericAffinity(pIn3, 0);
  81478. }
  81479. iKey = sqlite3VdbeIntValue(pIn3);
  81480. /* If the P3 value could not be converted into an integer without
  81481. ** loss of information, then special processing is required... */
  81482. if( (pIn3->flags & MEM_Int)==0 ){
  81483. if( (pIn3->flags & MEM_Real)==0 ){
  81484. /* If the P3 value cannot be converted into any kind of a number,
  81485. ** then the seek is not possible, so jump to P2 */
  81486. VdbeBranchTaken(1,2); goto jump_to_p2;
  81487. break;
  81488. }
  81489. /* If the approximation iKey is larger than the actual real search
  81490. ** term, substitute >= for > and < for <=. e.g. if the search term
  81491. ** is 4.9 and the integer approximation 5:
  81492. **
  81493. ** (x > 4.9) -> (x >= 5)
  81494. ** (x <= 4.9) -> (x < 5)
  81495. */
  81496. if( pIn3->u.r<(double)iKey ){
  81497. assert( OP_SeekGE==(OP_SeekGT-1) );
  81498. assert( OP_SeekLT==(OP_SeekLE-1) );
  81499. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  81500. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  81501. }
  81502. /* If the approximation iKey is smaller than the actual real search
  81503. ** term, substitute <= for < and > for >=. */
  81504. else if( pIn3->u.r>(double)iKey ){
  81505. assert( OP_SeekLE==(OP_SeekLT+1) );
  81506. assert( OP_SeekGT==(OP_SeekGE+1) );
  81507. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  81508. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  81509. }
  81510. }
  81511. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
  81512. pC->movetoTarget = iKey; /* Used by OP_Delete */
  81513. if( rc!=SQLITE_OK ){
  81514. goto abort_due_to_error;
  81515. }
  81516. }else{
  81517. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  81518. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  81519. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  81520. */
  81521. if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
  81522. eqOnly = 1;
  81523. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  81524. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  81525. assert( pOp[1].p1==pOp[0].p1 );
  81526. assert( pOp[1].p2==pOp[0].p2 );
  81527. assert( pOp[1].p3==pOp[0].p3 );
  81528. assert( pOp[1].p4.i==pOp[0].p4.i );
  81529. }
  81530. nField = pOp->p4.i;
  81531. assert( pOp->p4type==P4_INT32 );
  81532. assert( nField>0 );
  81533. r.pKeyInfo = pC->pKeyInfo;
  81534. r.nField = (u16)nField;
  81535. /* The next line of code computes as follows, only faster:
  81536. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  81537. ** r.default_rc = -1;
  81538. ** }else{
  81539. ** r.default_rc = +1;
  81540. ** }
  81541. */
  81542. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  81543. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  81544. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  81545. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  81546. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  81547. r.aMem = &aMem[pOp->p3];
  81548. #ifdef SQLITE_DEBUG
  81549. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  81550. #endif
  81551. r.eqSeen = 0;
  81552. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
  81553. if( rc!=SQLITE_OK ){
  81554. goto abort_due_to_error;
  81555. }
  81556. if( eqOnly && r.eqSeen==0 ){
  81557. assert( res!=0 );
  81558. goto seek_not_found;
  81559. }
  81560. }
  81561. pC->deferredMoveto = 0;
  81562. pC->cacheStatus = CACHE_STALE;
  81563. #ifdef SQLITE_TEST
  81564. sqlite3_search_count++;
  81565. #endif
  81566. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  81567. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  81568. res = 0;
  81569. rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
  81570. if( rc!=SQLITE_OK ){
  81571. if( rc==SQLITE_DONE ){
  81572. rc = SQLITE_OK;
  81573. res = 1;
  81574. }else{
  81575. goto abort_due_to_error;
  81576. }
  81577. }
  81578. }else{
  81579. res = 0;
  81580. }
  81581. }else{
  81582. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  81583. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  81584. res = 0;
  81585. rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
  81586. if( rc!=SQLITE_OK ){
  81587. if( rc==SQLITE_DONE ){
  81588. rc = SQLITE_OK;
  81589. res = 1;
  81590. }else{
  81591. goto abort_due_to_error;
  81592. }
  81593. }
  81594. }else{
  81595. /* res might be negative because the table is empty. Check to
  81596. ** see if this is the case.
  81597. */
  81598. res = sqlite3BtreeEof(pC->uc.pCursor);
  81599. }
  81600. }
  81601. seek_not_found:
  81602. assert( pOp->p2>0 );
  81603. VdbeBranchTaken(res!=0,2);
  81604. if( res ){
  81605. goto jump_to_p2;
  81606. }else if( eqOnly ){
  81607. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  81608. pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
  81609. }
  81610. break;
  81611. }
  81612. /* Opcode: SeekHit P1 P2 * * *
  81613. ** Synopsis: seekHit=P2
  81614. **
  81615. ** Set the seekHit flag on cursor P1 to the value in P2.
  81616. ** The seekHit flag is used by the IfNoHope opcode.
  81617. **
  81618. ** P1 must be a valid b-tree cursor. P2 must be a boolean value,
  81619. ** either 0 or 1.
  81620. */
  81621. case OP_SeekHit: {
  81622. VdbeCursor *pC;
  81623. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81624. pC = p->apCsr[pOp->p1];
  81625. assert( pC!=0 );
  81626. assert( pOp->p2==0 || pOp->p2==1 );
  81627. pC->seekHit = pOp->p2 & 1;
  81628. break;
  81629. }
  81630. /* Opcode: Found P1 P2 P3 P4 *
  81631. ** Synopsis: key=r[P3@P4]
  81632. **
  81633. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  81634. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  81635. ** record.
  81636. **
  81637. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  81638. ** is a prefix of any entry in P1 then a jump is made to P2 and
  81639. ** P1 is left pointing at the matching entry.
  81640. **
  81641. ** This operation leaves the cursor in a state where it can be
  81642. ** advanced in the forward direction. The Next instruction will work,
  81643. ** but not the Prev instruction.
  81644. **
  81645. ** See also: NotFound, NoConflict, NotExists. SeekGe
  81646. */
  81647. /* Opcode: NotFound P1 P2 P3 P4 *
  81648. ** Synopsis: key=r[P3@P4]
  81649. **
  81650. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  81651. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  81652. ** record.
  81653. **
  81654. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  81655. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  81656. ** does contain an entry whose prefix matches the P3/P4 record then control
  81657. ** falls through to the next instruction and P1 is left pointing at the
  81658. ** matching entry.
  81659. **
  81660. ** This operation leaves the cursor in a state where it cannot be
  81661. ** advanced in either direction. In other words, the Next and Prev
  81662. ** opcodes do not work after this operation.
  81663. **
  81664. ** See also: Found, NotExists, NoConflict, IfNoHope
  81665. */
  81666. /* Opcode: IfNoHope P1 P2 P3 P4 *
  81667. ** Synopsis: key=r[P3@P4]
  81668. **
  81669. ** Register P3 is the first of P4 registers that form an unpacked
  81670. ** record.
  81671. **
  81672. ** Cursor P1 is on an index btree. If the seekHit flag is set on P1, then
  81673. ** this opcode is a no-op. But if the seekHit flag of P1 is clear, then
  81674. ** check to see if there is any entry in P1 that matches the
  81675. ** prefix identified by P3 and P4. If no entry matches the prefix,
  81676. ** jump to P2. Otherwise fall through.
  81677. **
  81678. ** This opcode behaves like OP_NotFound if the seekHit
  81679. ** flag is clear and it behaves like OP_Noop if the seekHit flag is set.
  81680. **
  81681. ** This opcode is used in IN clause processing for a multi-column key.
  81682. ** If an IN clause is attached to an element of the key other than the
  81683. ** left-most element, and if there are no matches on the most recent
  81684. ** seek over the whole key, then it might be that one of the key element
  81685. ** to the left is prohibiting a match, and hence there is "no hope" of
  81686. ** any match regardless of how many IN clause elements are checked.
  81687. ** In such a case, we abandon the IN clause search early, using this
  81688. ** opcode. The opcode name comes from the fact that the
  81689. ** jump is taken if there is "no hope" of achieving a match.
  81690. **
  81691. ** See also: NotFound, SeekHit
  81692. */
  81693. /* Opcode: NoConflict P1 P2 P3 P4 *
  81694. ** Synopsis: key=r[P3@P4]
  81695. **
  81696. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  81697. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  81698. ** record.
  81699. **
  81700. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  81701. ** contains any NULL value, jump immediately to P2. If all terms of the
  81702. ** record are not-NULL then a check is done to determine if any row in the
  81703. ** P1 index btree has a matching key prefix. If there are no matches, jump
  81704. ** immediately to P2. If there is a match, fall through and leave the P1
  81705. ** cursor pointing to the matching row.
  81706. **
  81707. ** This opcode is similar to OP_NotFound with the exceptions that the
  81708. ** branch is always taken if any part of the search key input is NULL.
  81709. **
  81710. ** This operation leaves the cursor in a state where it cannot be
  81711. ** advanced in either direction. In other words, the Next and Prev
  81712. ** opcodes do not work after this operation.
  81713. **
  81714. ** See also: NotFound, Found, NotExists
  81715. */
  81716. case OP_IfNoHope: { /* jump, in3 */
  81717. VdbeCursor *pC;
  81718. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81719. pC = p->apCsr[pOp->p1];
  81720. assert( pC!=0 );
  81721. if( pC->seekHit ) break;
  81722. /* Fall through into OP_NotFound */
  81723. }
  81724. case OP_NoConflict: /* jump, in3 */
  81725. case OP_NotFound: /* jump, in3 */
  81726. case OP_Found: { /* jump, in3 */
  81727. int alreadyExists;
  81728. int takeJump;
  81729. int ii;
  81730. VdbeCursor *pC;
  81731. int res;
  81732. UnpackedRecord *pFree;
  81733. UnpackedRecord *pIdxKey;
  81734. UnpackedRecord r;
  81735. #ifdef SQLITE_TEST
  81736. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  81737. #endif
  81738. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81739. assert( pOp->p4type==P4_INT32 );
  81740. pC = p->apCsr[pOp->p1];
  81741. assert( pC!=0 );
  81742. #ifdef SQLITE_DEBUG
  81743. pC->seekOp = pOp->opcode;
  81744. #endif
  81745. pIn3 = &aMem[pOp->p3];
  81746. assert( pC->eCurType==CURTYPE_BTREE );
  81747. assert( pC->uc.pCursor!=0 );
  81748. assert( pC->isTable==0 );
  81749. if( pOp->p4.i>0 ){
  81750. r.pKeyInfo = pC->pKeyInfo;
  81751. r.nField = (u16)pOp->p4.i;
  81752. r.aMem = pIn3;
  81753. #ifdef SQLITE_DEBUG
  81754. for(ii=0; ii<r.nField; ii++){
  81755. assert( memIsValid(&r.aMem[ii]) );
  81756. assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
  81757. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  81758. }
  81759. #endif
  81760. pIdxKey = &r;
  81761. pFree = 0;
  81762. }else{
  81763. assert( pIn3->flags & MEM_Blob );
  81764. rc = ExpandBlob(pIn3);
  81765. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  81766. if( rc ) goto no_mem;
  81767. pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
  81768. if( pIdxKey==0 ) goto no_mem;
  81769. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  81770. }
  81771. pIdxKey->default_rc = 0;
  81772. takeJump = 0;
  81773. if( pOp->opcode==OP_NoConflict ){
  81774. /* For the OP_NoConflict opcode, take the jump if any of the
  81775. ** input fields are NULL, since any key with a NULL will not
  81776. ** conflict */
  81777. for(ii=0; ii<pIdxKey->nField; ii++){
  81778. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  81779. takeJump = 1;
  81780. break;
  81781. }
  81782. }
  81783. }
  81784. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
  81785. if( pFree ) sqlite3DbFreeNN(db, pFree);
  81786. if( rc!=SQLITE_OK ){
  81787. goto abort_due_to_error;
  81788. }
  81789. pC->seekResult = res;
  81790. alreadyExists = (res==0);
  81791. pC->nullRow = 1-alreadyExists;
  81792. pC->deferredMoveto = 0;
  81793. pC->cacheStatus = CACHE_STALE;
  81794. if( pOp->opcode==OP_Found ){
  81795. VdbeBranchTaken(alreadyExists!=0,2);
  81796. if( alreadyExists ) goto jump_to_p2;
  81797. }else{
  81798. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  81799. if( takeJump || !alreadyExists ) goto jump_to_p2;
  81800. }
  81801. break;
  81802. }
  81803. /* Opcode: SeekRowid P1 P2 P3 * *
  81804. ** Synopsis: intkey=r[P3]
  81805. **
  81806. ** P1 is the index of a cursor open on an SQL table btree (with integer
  81807. ** keys). If register P3 does not contain an integer or if P1 does not
  81808. ** contain a record with rowid P3 then jump immediately to P2.
  81809. ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
  81810. ** a record with rowid P3 then
  81811. ** leave the cursor pointing at that record and fall through to the next
  81812. ** instruction.
  81813. **
  81814. ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
  81815. ** the P3 register must be guaranteed to contain an integer value. With this
  81816. ** opcode, register P3 might not contain an integer.
  81817. **
  81818. ** The OP_NotFound opcode performs the same operation on index btrees
  81819. ** (with arbitrary multi-value keys).
  81820. **
  81821. ** This opcode leaves the cursor in a state where it cannot be advanced
  81822. ** in either direction. In other words, the Next and Prev opcodes will
  81823. ** not work following this opcode.
  81824. **
  81825. ** See also: Found, NotFound, NoConflict, SeekRowid
  81826. */
  81827. /* Opcode: NotExists P1 P2 P3 * *
  81828. ** Synopsis: intkey=r[P3]
  81829. **
  81830. ** P1 is the index of a cursor open on an SQL table btree (with integer
  81831. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  81832. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  81833. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  81834. ** leave the cursor pointing at that record and fall through to the next
  81835. ** instruction.
  81836. **
  81837. ** The OP_SeekRowid opcode performs the same operation but also allows the
  81838. ** P3 register to contain a non-integer value, in which case the jump is
  81839. ** always taken. This opcode requires that P3 always contain an integer.
  81840. **
  81841. ** The OP_NotFound opcode performs the same operation on index btrees
  81842. ** (with arbitrary multi-value keys).
  81843. **
  81844. ** This opcode leaves the cursor in a state where it cannot be advanced
  81845. ** in either direction. In other words, the Next and Prev opcodes will
  81846. ** not work following this opcode.
  81847. **
  81848. ** See also: Found, NotFound, NoConflict, SeekRowid
  81849. */
  81850. case OP_SeekRowid: { /* jump, in3 */
  81851. VdbeCursor *pC;
  81852. BtCursor *pCrsr;
  81853. int res;
  81854. u64 iKey;
  81855. pIn3 = &aMem[pOp->p3];
  81856. if( (pIn3->flags & MEM_Int)==0 ){
  81857. /* Make sure pIn3->u.i contains a valid integer representation of
  81858. ** the key value, but do not change the datatype of the register, as
  81859. ** other parts of the perpared statement might be depending on the
  81860. ** current datatype. */
  81861. u16 origFlags = pIn3->flags;
  81862. int isNotInt;
  81863. applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
  81864. isNotInt = (pIn3->flags & MEM_Int)==0;
  81865. pIn3->flags = origFlags;
  81866. if( isNotInt ) goto jump_to_p2;
  81867. }
  81868. /* Fall through into OP_NotExists */
  81869. case OP_NotExists: /* jump, in3 */
  81870. pIn3 = &aMem[pOp->p3];
  81871. assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
  81872. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81873. pC = p->apCsr[pOp->p1];
  81874. assert( pC!=0 );
  81875. #ifdef SQLITE_DEBUG
  81876. pC->seekOp = OP_SeekRowid;
  81877. #endif
  81878. assert( pC->isTable );
  81879. assert( pC->eCurType==CURTYPE_BTREE );
  81880. pCrsr = pC->uc.pCursor;
  81881. assert( pCrsr!=0 );
  81882. res = 0;
  81883. iKey = pIn3->u.i;
  81884. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  81885. assert( rc==SQLITE_OK || res==0 );
  81886. pC->movetoTarget = iKey; /* Used by OP_Delete */
  81887. pC->nullRow = 0;
  81888. pC->cacheStatus = CACHE_STALE;
  81889. pC->deferredMoveto = 0;
  81890. VdbeBranchTaken(res!=0,2);
  81891. pC->seekResult = res;
  81892. if( res!=0 ){
  81893. assert( rc==SQLITE_OK );
  81894. if( pOp->p2==0 ){
  81895. rc = SQLITE_CORRUPT_BKPT;
  81896. }else{
  81897. goto jump_to_p2;
  81898. }
  81899. }
  81900. if( rc ) goto abort_due_to_error;
  81901. break;
  81902. }
  81903. /* Opcode: Sequence P1 P2 * * *
  81904. ** Synopsis: r[P2]=cursor[P1].ctr++
  81905. **
  81906. ** Find the next available sequence number for cursor P1.
  81907. ** Write the sequence number into register P2.
  81908. ** The sequence number on the cursor is incremented after this
  81909. ** instruction.
  81910. */
  81911. case OP_Sequence: { /* out2 */
  81912. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81913. assert( p->apCsr[pOp->p1]!=0 );
  81914. assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
  81915. pOut = out2Prerelease(p, pOp);
  81916. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  81917. break;
  81918. }
  81919. /* Opcode: NewRowid P1 P2 P3 * *
  81920. ** Synopsis: r[P2]=rowid
  81921. **
  81922. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  81923. ** The record number is not previously used as a key in the database
  81924. ** table that cursor P1 points to. The new record number is written
  81925. ** written to register P2.
  81926. **
  81927. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  81928. ** the largest previously generated record number. No new record numbers are
  81929. ** allowed to be less than this value. When this value reaches its maximum,
  81930. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  81931. ** generated record number. This P3 mechanism is used to help implement the
  81932. ** AUTOINCREMENT feature.
  81933. */
  81934. case OP_NewRowid: { /* out2 */
  81935. i64 v; /* The new rowid */
  81936. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  81937. int res; /* Result of an sqlite3BtreeLast() */
  81938. int cnt; /* Counter to limit the number of searches */
  81939. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  81940. VdbeFrame *pFrame; /* Root frame of VDBE */
  81941. v = 0;
  81942. res = 0;
  81943. pOut = out2Prerelease(p, pOp);
  81944. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81945. pC = p->apCsr[pOp->p1];
  81946. assert( pC!=0 );
  81947. assert( pC->isTable );
  81948. assert( pC->eCurType==CURTYPE_BTREE );
  81949. assert( pC->uc.pCursor!=0 );
  81950. {
  81951. /* The next rowid or record number (different terms for the same
  81952. ** thing) is obtained in a two-step algorithm.
  81953. **
  81954. ** First we attempt to find the largest existing rowid and add one
  81955. ** to that. But if the largest existing rowid is already the maximum
  81956. ** positive integer, we have to fall through to the second
  81957. ** probabilistic algorithm
  81958. **
  81959. ** The second algorithm is to select a rowid at random and see if
  81960. ** it already exists in the table. If it does not exist, we have
  81961. ** succeeded. If the random rowid does exist, we select a new one
  81962. ** and try again, up to 100 times.
  81963. */
  81964. assert( pC->isTable );
  81965. #ifdef SQLITE_32BIT_ROWID
  81966. # define MAX_ROWID 0x7fffffff
  81967. #else
  81968. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  81969. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  81970. ** to provide the constant while making all compilers happy.
  81971. */
  81972. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  81973. #endif
  81974. if( !pC->useRandomRowid ){
  81975. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  81976. if( rc!=SQLITE_OK ){
  81977. goto abort_due_to_error;
  81978. }
  81979. if( res ){
  81980. v = 1; /* IMP: R-61914-48074 */
  81981. }else{
  81982. assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
  81983. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  81984. if( v>=MAX_ROWID ){
  81985. pC->useRandomRowid = 1;
  81986. }else{
  81987. v++; /* IMP: R-29538-34987 */
  81988. }
  81989. }
  81990. }
  81991. #ifndef SQLITE_OMIT_AUTOINCREMENT
  81992. if( pOp->p3 ){
  81993. /* Assert that P3 is a valid memory cell. */
  81994. assert( pOp->p3>0 );
  81995. if( p->pFrame ){
  81996. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  81997. /* Assert that P3 is a valid memory cell. */
  81998. assert( pOp->p3<=pFrame->nMem );
  81999. pMem = &pFrame->aMem[pOp->p3];
  82000. }else{
  82001. /* Assert that P3 is a valid memory cell. */
  82002. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  82003. pMem = &aMem[pOp->p3];
  82004. memAboutToChange(p, pMem);
  82005. }
  82006. assert( memIsValid(pMem) );
  82007. REGISTER_TRACE(pOp->p3, pMem);
  82008. sqlite3VdbeMemIntegerify(pMem);
  82009. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  82010. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  82011. rc = SQLITE_FULL; /* IMP: R-17817-00630 */
  82012. goto abort_due_to_error;
  82013. }
  82014. if( v<pMem->u.i+1 ){
  82015. v = pMem->u.i + 1;
  82016. }
  82017. pMem->u.i = v;
  82018. }
  82019. #endif
  82020. if( pC->useRandomRowid ){
  82021. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  82022. ** largest possible integer (9223372036854775807) then the database
  82023. ** engine starts picking positive candidate ROWIDs at random until
  82024. ** it finds one that is not previously used. */
  82025. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  82026. ** an AUTOINCREMENT table. */
  82027. cnt = 0;
  82028. do{
  82029. sqlite3_randomness(sizeof(v), &v);
  82030. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  82031. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
  82032. 0, &res))==SQLITE_OK)
  82033. && (res==0)
  82034. && (++cnt<100));
  82035. if( rc ) goto abort_due_to_error;
  82036. if( res==0 ){
  82037. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  82038. goto abort_due_to_error;
  82039. }
  82040. assert( v>0 ); /* EV: R-40812-03570 */
  82041. }
  82042. pC->deferredMoveto = 0;
  82043. pC->cacheStatus = CACHE_STALE;
  82044. }
  82045. pOut->u.i = v;
  82046. break;
  82047. }
  82048. /* Opcode: Insert P1 P2 P3 P4 P5
  82049. ** Synopsis: intkey=r[P3] data=r[P2]
  82050. **
  82051. ** Write an entry into the table of cursor P1. A new entry is
  82052. ** created if it doesn't already exist or the data for an existing
  82053. ** entry is overwritten. The data is the value MEM_Blob stored in register
  82054. ** number P2. The key is stored in register P3. The key must
  82055. ** be a MEM_Int.
  82056. **
  82057. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  82058. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  82059. ** then rowid is stored for subsequent return by the
  82060. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  82061. **
  82062. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  82063. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  82064. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  82065. ** seeks on the cursor or if the most recent seek used a key equal to P3.
  82066. **
  82067. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  82068. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  82069. ** is part of an INSERT operation. The difference is only important to
  82070. ** the update hook.
  82071. **
  82072. ** Parameter P4 may point to a Table structure, or may be NULL. If it is
  82073. ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
  82074. ** following a successful insert.
  82075. **
  82076. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  82077. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  82078. ** and register P2 becomes ephemeral. If the cursor is changed, the
  82079. ** value of register P2 will then change. Make sure this does not
  82080. ** cause any problems.)
  82081. **
  82082. ** This instruction only works on tables. The equivalent instruction
  82083. ** for indices is OP_IdxInsert.
  82084. */
  82085. /* Opcode: InsertInt P1 P2 P3 P4 P5
  82086. ** Synopsis: intkey=P3 data=r[P2]
  82087. **
  82088. ** This works exactly like OP_Insert except that the key is the
  82089. ** integer value P3, not the value of the integer stored in register P3.
  82090. */
  82091. case OP_Insert:
  82092. case OP_InsertInt: {
  82093. Mem *pData; /* MEM cell holding data for the record to be inserted */
  82094. Mem *pKey; /* MEM cell holding key for the record */
  82095. VdbeCursor *pC; /* Cursor to table into which insert is written */
  82096. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  82097. const char *zDb; /* database name - used by the update hook */
  82098. Table *pTab; /* Table structure - used by update and pre-update hooks */
  82099. BtreePayload x; /* Payload to be inserted */
  82100. pData = &aMem[pOp->p2];
  82101. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82102. assert( memIsValid(pData) );
  82103. pC = p->apCsr[pOp->p1];
  82104. assert( pC!=0 );
  82105. assert( pC->eCurType==CURTYPE_BTREE );
  82106. assert( pC->uc.pCursor!=0 );
  82107. assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
  82108. assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
  82109. REGISTER_TRACE(pOp->p2, pData);
  82110. sqlite3VdbeIncrWriteCounter(p, pC);
  82111. if( pOp->opcode==OP_Insert ){
  82112. pKey = &aMem[pOp->p3];
  82113. assert( pKey->flags & MEM_Int );
  82114. assert( memIsValid(pKey) );
  82115. REGISTER_TRACE(pOp->p3, pKey);
  82116. x.nKey = pKey->u.i;
  82117. }else{
  82118. assert( pOp->opcode==OP_InsertInt );
  82119. x.nKey = pOp->p3;
  82120. }
  82121. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  82122. assert( pC->iDb>=0 );
  82123. zDb = db->aDb[pC->iDb].zDbSName;
  82124. pTab = pOp->p4.pTab;
  82125. assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
  82126. }else{
  82127. pTab = 0;
  82128. zDb = 0; /* Not needed. Silence a compiler warning. */
  82129. }
  82130. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  82131. /* Invoke the pre-update hook, if any */
  82132. if( pTab ){
  82133. if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
  82134. sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
  82135. }
  82136. if( db->xUpdateCallback==0 || pTab->aCol==0 ){
  82137. /* Prevent post-update hook from running in cases when it should not */
  82138. pTab = 0;
  82139. }
  82140. }
  82141. if( pOp->p5 & OPFLAG_ISNOOP ) break;
  82142. #endif
  82143. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  82144. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
  82145. assert( pData->flags & (MEM_Blob|MEM_Str) );
  82146. x.pData = pData->z;
  82147. x.nData = pData->n;
  82148. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  82149. if( pData->flags & MEM_Zero ){
  82150. x.nZero = pData->u.nZero;
  82151. }else{
  82152. x.nZero = 0;
  82153. }
  82154. x.pKey = 0;
  82155. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  82156. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
  82157. );
  82158. pC->deferredMoveto = 0;
  82159. pC->cacheStatus = CACHE_STALE;
  82160. /* Invoke the update-hook if required. */
  82161. if( rc ) goto abort_due_to_error;
  82162. if( pTab ){
  82163. assert( db->xUpdateCallback!=0 );
  82164. assert( pTab->aCol!=0 );
  82165. db->xUpdateCallback(db->pUpdateArg,
  82166. (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
  82167. zDb, pTab->zName, x.nKey);
  82168. }
  82169. break;
  82170. }
  82171. /* Opcode: Delete P1 P2 P3 P4 P5
  82172. **
  82173. ** Delete the record at which the P1 cursor is currently pointing.
  82174. **
  82175. ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
  82176. ** the cursor will be left pointing at either the next or the previous
  82177. ** record in the table. If it is left pointing at the next record, then
  82178. ** the next Next instruction will be a no-op. As a result, in this case
  82179. ** it is ok to delete a record from within a Next loop. If
  82180. ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
  82181. ** left in an undefined state.
  82182. **
  82183. ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
  82184. ** delete one of several associated with deleting a table row and all its
  82185. ** associated index entries. Exactly one of those deletes is the "primary"
  82186. ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
  82187. ** marked with the AUXDELETE flag.
  82188. **
  82189. ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
  82190. ** change count is incremented (otherwise not).
  82191. **
  82192. ** P1 must not be pseudo-table. It has to be a real table with
  82193. ** multiple rows.
  82194. **
  82195. ** If P4 is not NULL then it points to a Table object. In this case either
  82196. ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
  82197. ** have been positioned using OP_NotFound prior to invoking this opcode in
  82198. ** this case. Specifically, if one is configured, the pre-update hook is
  82199. ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
  82200. ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
  82201. **
  82202. ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
  82203. ** of the memory cell that contains the value that the rowid of the row will
  82204. ** be set to by the update.
  82205. */
  82206. case OP_Delete: {
  82207. VdbeCursor *pC;
  82208. const char *zDb;
  82209. Table *pTab;
  82210. int opflags;
  82211. opflags = pOp->p2;
  82212. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82213. pC = p->apCsr[pOp->p1];
  82214. assert( pC!=0 );
  82215. assert( pC->eCurType==CURTYPE_BTREE );
  82216. assert( pC->uc.pCursor!=0 );
  82217. assert( pC->deferredMoveto==0 );
  82218. sqlite3VdbeIncrWriteCounter(p, pC);
  82219. #ifdef SQLITE_DEBUG
  82220. if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
  82221. /* If p5 is zero, the seek operation that positioned the cursor prior to
  82222. ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
  82223. ** the row that is being deleted */
  82224. i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  82225. assert( pC->movetoTarget==iKey );
  82226. }
  82227. #endif
  82228. /* If the update-hook or pre-update-hook will be invoked, set zDb to
  82229. ** the name of the db to pass as to it. Also set local pTab to a copy
  82230. ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
  82231. ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
  82232. ** VdbeCursor.movetoTarget to the current rowid. */
  82233. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  82234. assert( pC->iDb>=0 );
  82235. assert( pOp->p4.pTab!=0 );
  82236. zDb = db->aDb[pC->iDb].zDbSName;
  82237. pTab = pOp->p4.pTab;
  82238. if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
  82239. pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  82240. }
  82241. }else{
  82242. zDb = 0; /* Not needed. Silence a compiler warning. */
  82243. pTab = 0; /* Not needed. Silence a compiler warning. */
  82244. }
  82245. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  82246. /* Invoke the pre-update-hook if required. */
  82247. if( db->xPreUpdateCallback && pOp->p4.pTab ){
  82248. assert( !(opflags & OPFLAG_ISUPDATE)
  82249. || HasRowid(pTab)==0
  82250. || (aMem[pOp->p3].flags & MEM_Int)
  82251. );
  82252. sqlite3VdbePreUpdateHook(p, pC,
  82253. (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
  82254. zDb, pTab, pC->movetoTarget,
  82255. pOp->p3
  82256. );
  82257. }
  82258. if( opflags & OPFLAG_ISNOOP ) break;
  82259. #endif
  82260. /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
  82261. assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
  82262. assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
  82263. assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
  82264. #ifdef SQLITE_DEBUG
  82265. if( p->pFrame==0 ){
  82266. if( pC->isEphemeral==0
  82267. && (pOp->p5 & OPFLAG_AUXDELETE)==0
  82268. && (pC->wrFlag & OPFLAG_FORDELETE)==0
  82269. ){
  82270. nExtraDelete++;
  82271. }
  82272. if( pOp->p2 & OPFLAG_NCHANGE ){
  82273. nExtraDelete--;
  82274. }
  82275. }
  82276. #endif
  82277. rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
  82278. pC->cacheStatus = CACHE_STALE;
  82279. pC->seekResult = 0;
  82280. if( rc ) goto abort_due_to_error;
  82281. /* Invoke the update-hook if required. */
  82282. if( opflags & OPFLAG_NCHANGE ){
  82283. p->nChange++;
  82284. if( db->xUpdateCallback && HasRowid(pTab) ){
  82285. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
  82286. pC->movetoTarget);
  82287. assert( pC->iDb>=0 );
  82288. }
  82289. }
  82290. break;
  82291. }
  82292. /* Opcode: ResetCount * * * * *
  82293. **
  82294. ** The value of the change counter is copied to the database handle
  82295. ** change counter (returned by subsequent calls to sqlite3_changes()).
  82296. ** Then the VMs internal change counter resets to 0.
  82297. ** This is used by trigger programs.
  82298. */
  82299. case OP_ResetCount: {
  82300. sqlite3VdbeSetChanges(db, p->nChange);
  82301. p->nChange = 0;
  82302. break;
  82303. }
  82304. /* Opcode: SorterCompare P1 P2 P3 P4
  82305. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  82306. **
  82307. ** P1 is a sorter cursor. This instruction compares a prefix of the
  82308. ** record blob in register P3 against a prefix of the entry that
  82309. ** the sorter cursor currently points to. Only the first P4 fields
  82310. ** of r[P3] and the sorter record are compared.
  82311. **
  82312. ** If either P3 or the sorter contains a NULL in one of their significant
  82313. ** fields (not counting the P4 fields at the end which are ignored) then
  82314. ** the comparison is assumed to be equal.
  82315. **
  82316. ** Fall through to next instruction if the two records compare equal to
  82317. ** each other. Jump to P2 if they are different.
  82318. */
  82319. case OP_SorterCompare: {
  82320. VdbeCursor *pC;
  82321. int res;
  82322. int nKeyCol;
  82323. pC = p->apCsr[pOp->p1];
  82324. assert( isSorter(pC) );
  82325. assert( pOp->p4type==P4_INT32 );
  82326. pIn3 = &aMem[pOp->p3];
  82327. nKeyCol = pOp->p4.i;
  82328. res = 0;
  82329. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  82330. VdbeBranchTaken(res!=0,2);
  82331. if( rc ) goto abort_due_to_error;
  82332. if( res ) goto jump_to_p2;
  82333. break;
  82334. };
  82335. /* Opcode: SorterData P1 P2 P3 * *
  82336. ** Synopsis: r[P2]=data
  82337. **
  82338. ** Write into register P2 the current sorter data for sorter cursor P1.
  82339. ** Then clear the column header cache on cursor P3.
  82340. **
  82341. ** This opcode is normally use to move a record out of the sorter and into
  82342. ** a register that is the source for a pseudo-table cursor created using
  82343. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  82344. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  82345. ** us from having to issue a separate NullRow instruction to clear that cache.
  82346. */
  82347. case OP_SorterData: {
  82348. VdbeCursor *pC;
  82349. pOut = &aMem[pOp->p2];
  82350. pC = p->apCsr[pOp->p1];
  82351. assert( isSorter(pC) );
  82352. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  82353. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  82354. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82355. if( rc ) goto abort_due_to_error;
  82356. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  82357. break;
  82358. }
  82359. /* Opcode: RowData P1 P2 P3 * *
  82360. ** Synopsis: r[P2]=data
  82361. **
  82362. ** Write into register P2 the complete row content for the row at
  82363. ** which cursor P1 is currently pointing.
  82364. ** There is no interpretation of the data.
  82365. ** It is just copied onto the P2 register exactly as
  82366. ** it is found in the database file.
  82367. **
  82368. ** If cursor P1 is an index, then the content is the key of the row.
  82369. ** If cursor P2 is a table, then the content extracted is the data.
  82370. **
  82371. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  82372. ** of a real table, not a pseudo-table.
  82373. **
  82374. ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
  82375. ** into the database page. That means that the content of the output
  82376. ** register will be invalidated as soon as the cursor moves - including
  82377. ** moves caused by other cursors that "save" the current cursors
  82378. ** position in order that they can write to the same table. If P3==0
  82379. ** then a copy of the data is made into memory. P3!=0 is faster, but
  82380. ** P3==0 is safer.
  82381. **
  82382. ** If P3!=0 then the content of the P2 register is unsuitable for use
  82383. ** in OP_Result and any OP_Result will invalidate the P2 register content.
  82384. ** The P2 register content is invalidated by opcodes like OP_Function or
  82385. ** by any use of another cursor pointing to the same table.
  82386. */
  82387. case OP_RowData: {
  82388. VdbeCursor *pC;
  82389. BtCursor *pCrsr;
  82390. u32 n;
  82391. pOut = out2Prerelease(p, pOp);
  82392. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82393. pC = p->apCsr[pOp->p1];
  82394. assert( pC!=0 );
  82395. assert( pC->eCurType==CURTYPE_BTREE );
  82396. assert( isSorter(pC)==0 );
  82397. assert( pC->nullRow==0 );
  82398. assert( pC->uc.pCursor!=0 );
  82399. pCrsr = pC->uc.pCursor;
  82400. /* The OP_RowData opcodes always follow OP_NotExists or
  82401. ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
  82402. ** that might invalidate the cursor.
  82403. ** If this where not the case, on of the following assert()s
  82404. ** would fail. Should this ever change (because of changes in the code
  82405. ** generator) then the fix would be to insert a call to
  82406. ** sqlite3VdbeCursorMoveto().
  82407. */
  82408. assert( pC->deferredMoveto==0 );
  82409. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  82410. #if 0 /* Not required due to the previous to assert() statements */
  82411. rc = sqlite3VdbeCursorMoveto(pC);
  82412. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  82413. #endif
  82414. n = sqlite3BtreePayloadSize(pCrsr);
  82415. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  82416. goto too_big;
  82417. }
  82418. testcase( n==0 );
  82419. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
  82420. if( rc ) goto abort_due_to_error;
  82421. if( !pOp->p3 ) Deephemeralize(pOut);
  82422. UPDATE_MAX_BLOBSIZE(pOut);
  82423. REGISTER_TRACE(pOp->p2, pOut);
  82424. break;
  82425. }
  82426. /* Opcode: Rowid P1 P2 * * *
  82427. ** Synopsis: r[P2]=rowid
  82428. **
  82429. ** Store in register P2 an integer which is the key of the table entry that
  82430. ** P1 is currently point to.
  82431. **
  82432. ** P1 can be either an ordinary table or a virtual table. There used to
  82433. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  82434. ** one opcode now works for both table types.
  82435. */
  82436. case OP_Rowid: { /* out2 */
  82437. VdbeCursor *pC;
  82438. i64 v;
  82439. sqlite3_vtab *pVtab;
  82440. const sqlite3_module *pModule;
  82441. pOut = out2Prerelease(p, pOp);
  82442. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82443. pC = p->apCsr[pOp->p1];
  82444. assert( pC!=0 );
  82445. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  82446. if( pC->nullRow ){
  82447. pOut->flags = MEM_Null;
  82448. break;
  82449. }else if( pC->deferredMoveto ){
  82450. v = pC->movetoTarget;
  82451. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82452. }else if( pC->eCurType==CURTYPE_VTAB ){
  82453. assert( pC->uc.pVCur!=0 );
  82454. pVtab = pC->uc.pVCur->pVtab;
  82455. pModule = pVtab->pModule;
  82456. assert( pModule->xRowid );
  82457. rc = pModule->xRowid(pC->uc.pVCur, &v);
  82458. sqlite3VtabImportErrmsg(p, pVtab);
  82459. if( rc ) goto abort_due_to_error;
  82460. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  82461. }else{
  82462. assert( pC->eCurType==CURTYPE_BTREE );
  82463. assert( pC->uc.pCursor!=0 );
  82464. rc = sqlite3VdbeCursorRestore(pC);
  82465. if( rc ) goto abort_due_to_error;
  82466. if( pC->nullRow ){
  82467. pOut->flags = MEM_Null;
  82468. break;
  82469. }
  82470. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  82471. }
  82472. pOut->u.i = v;
  82473. break;
  82474. }
  82475. /* Opcode: NullRow P1 * * * *
  82476. **
  82477. ** Move the cursor P1 to a null row. Any OP_Column operations
  82478. ** that occur while the cursor is on the null row will always
  82479. ** write a NULL.
  82480. */
  82481. case OP_NullRow: {
  82482. VdbeCursor *pC;
  82483. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82484. pC = p->apCsr[pOp->p1];
  82485. assert( pC!=0 );
  82486. pC->nullRow = 1;
  82487. pC->cacheStatus = CACHE_STALE;
  82488. if( pC->eCurType==CURTYPE_BTREE ){
  82489. assert( pC->uc.pCursor!=0 );
  82490. sqlite3BtreeClearCursor(pC->uc.pCursor);
  82491. }
  82492. #ifdef SQLITE_DEBUG
  82493. if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
  82494. #endif
  82495. break;
  82496. }
  82497. /* Opcode: SeekEnd P1 * * * *
  82498. **
  82499. ** Position cursor P1 at the end of the btree for the purpose of
  82500. ** appending a new entry onto the btree.
  82501. **
  82502. ** It is assumed that the cursor is used only for appending and so
  82503. ** if the cursor is valid, then the cursor must already be pointing
  82504. ** at the end of the btree and so no changes are made to
  82505. ** the cursor.
  82506. */
  82507. /* Opcode: Last P1 P2 * * *
  82508. **
  82509. ** The next use of the Rowid or Column or Prev instruction for P1
  82510. ** will refer to the last entry in the database table or index.
  82511. ** If the table or index is empty and P2>0, then jump immediately to P2.
  82512. ** If P2 is 0 or if the table or index is not empty, fall through
  82513. ** to the following instruction.
  82514. **
  82515. ** This opcode leaves the cursor configured to move in reverse order,
  82516. ** from the end toward the beginning. In other words, the cursor is
  82517. ** configured to use Prev, not Next.
  82518. */
  82519. case OP_SeekEnd:
  82520. case OP_Last: { /* jump */
  82521. VdbeCursor *pC;
  82522. BtCursor *pCrsr;
  82523. int res;
  82524. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82525. pC = p->apCsr[pOp->p1];
  82526. assert( pC!=0 );
  82527. assert( pC->eCurType==CURTYPE_BTREE );
  82528. pCrsr = pC->uc.pCursor;
  82529. res = 0;
  82530. assert( pCrsr!=0 );
  82531. #ifdef SQLITE_DEBUG
  82532. pC->seekOp = pOp->opcode;
  82533. #endif
  82534. if( pOp->opcode==OP_SeekEnd ){
  82535. assert( pOp->p2==0 );
  82536. pC->seekResult = -1;
  82537. if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
  82538. break;
  82539. }
  82540. }
  82541. rc = sqlite3BtreeLast(pCrsr, &res);
  82542. pC->nullRow = (u8)res;
  82543. pC->deferredMoveto = 0;
  82544. pC->cacheStatus = CACHE_STALE;
  82545. if( rc ) goto abort_due_to_error;
  82546. if( pOp->p2>0 ){
  82547. VdbeBranchTaken(res!=0,2);
  82548. if( res ) goto jump_to_p2;
  82549. }
  82550. break;
  82551. }
  82552. /* Opcode: IfSmaller P1 P2 P3 * *
  82553. **
  82554. ** Estimate the number of rows in the table P1. Jump to P2 if that
  82555. ** estimate is less than approximately 2**(0.1*P3).
  82556. */
  82557. case OP_IfSmaller: { /* jump */
  82558. VdbeCursor *pC;
  82559. BtCursor *pCrsr;
  82560. int res;
  82561. i64 sz;
  82562. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82563. pC = p->apCsr[pOp->p1];
  82564. assert( pC!=0 );
  82565. pCrsr = pC->uc.pCursor;
  82566. assert( pCrsr );
  82567. rc = sqlite3BtreeFirst(pCrsr, &res);
  82568. if( rc ) goto abort_due_to_error;
  82569. if( res==0 ){
  82570. sz = sqlite3BtreeRowCountEst(pCrsr);
  82571. if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
  82572. }
  82573. VdbeBranchTaken(res!=0,2);
  82574. if( res ) goto jump_to_p2;
  82575. break;
  82576. }
  82577. /* Opcode: SorterSort P1 P2 * * *
  82578. **
  82579. ** After all records have been inserted into the Sorter object
  82580. ** identified by P1, invoke this opcode to actually do the sorting.
  82581. ** Jump to P2 if there are no records to be sorted.
  82582. **
  82583. ** This opcode is an alias for OP_Sort and OP_Rewind that is used
  82584. ** for Sorter objects.
  82585. */
  82586. /* Opcode: Sort P1 P2 * * *
  82587. **
  82588. ** This opcode does exactly the same thing as OP_Rewind except that
  82589. ** it increments an undocumented global variable used for testing.
  82590. **
  82591. ** Sorting is accomplished by writing records into a sorting index,
  82592. ** then rewinding that index and playing it back from beginning to
  82593. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  82594. ** rewinding so that the global variable will be incremented and
  82595. ** regression tests can determine whether or not the optimizer is
  82596. ** correctly optimizing out sorts.
  82597. */
  82598. case OP_SorterSort: /* jump */
  82599. case OP_Sort: { /* jump */
  82600. #ifdef SQLITE_TEST
  82601. sqlite3_sort_count++;
  82602. sqlite3_search_count--;
  82603. #endif
  82604. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  82605. /* Fall through into OP_Rewind */
  82606. }
  82607. /* Opcode: Rewind P1 P2 * * P5
  82608. **
  82609. ** The next use of the Rowid or Column or Next instruction for P1
  82610. ** will refer to the first entry in the database table or index.
  82611. ** If the table or index is empty, jump immediately to P2.
  82612. ** If the table or index is not empty, fall through to the following
  82613. ** instruction.
  82614. **
  82615. ** If P5 is non-zero and the table is not empty, then the "skip-next"
  82616. ** flag is set on the cursor so that the next OP_Next instruction
  82617. ** executed on it is a no-op.
  82618. **
  82619. ** This opcode leaves the cursor configured to move in forward order,
  82620. ** from the beginning toward the end. In other words, the cursor is
  82621. ** configured to use Next, not Prev.
  82622. */
  82623. case OP_Rewind: { /* jump */
  82624. VdbeCursor *pC;
  82625. BtCursor *pCrsr;
  82626. int res;
  82627. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82628. pC = p->apCsr[pOp->p1];
  82629. assert( pC!=0 );
  82630. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  82631. res = 1;
  82632. #ifdef SQLITE_DEBUG
  82633. pC->seekOp = OP_Rewind;
  82634. #endif
  82635. if( isSorter(pC) ){
  82636. rc = sqlite3VdbeSorterRewind(pC, &res);
  82637. }else{
  82638. assert( pC->eCurType==CURTYPE_BTREE );
  82639. pCrsr = pC->uc.pCursor;
  82640. assert( pCrsr );
  82641. rc = sqlite3BtreeFirst(pCrsr, &res);
  82642. #ifndef SQLITE_OMIT_WINDOWFUNC
  82643. if( pOp->p5 ) sqlite3BtreeSkipNext(pCrsr);
  82644. #endif
  82645. pC->deferredMoveto = 0;
  82646. pC->cacheStatus = CACHE_STALE;
  82647. }
  82648. if( rc ) goto abort_due_to_error;
  82649. pC->nullRow = (u8)res;
  82650. assert( pOp->p2>0 && pOp->p2<p->nOp );
  82651. VdbeBranchTaken(res!=0,2);
  82652. if( res ) goto jump_to_p2;
  82653. break;
  82654. }
  82655. /* Opcode: Next P1 P2 P3 P4 P5
  82656. **
  82657. ** Advance cursor P1 so that it points to the next key/data pair in its
  82658. ** table or index. If there are no more key/value pairs then fall through
  82659. ** to the following instruction. But if the cursor advance was successful,
  82660. ** jump immediately to P2.
  82661. **
  82662. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  82663. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  82664. ** to follow SeekLT, SeekLE, or OP_Last.
  82665. **
  82666. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  82667. ** been opened prior to this opcode or the program will segfault.
  82668. **
  82669. ** The P3 value is a hint to the btree implementation. If P3==1, that
  82670. ** means P1 is an SQL index and that this instruction could have been
  82671. ** omitted if that index had been unique. P3 is usually 0. P3 is
  82672. ** always either 0 or 1.
  82673. **
  82674. ** P4 is always of type P4_ADVANCE. The function pointer points to
  82675. ** sqlite3BtreeNext().
  82676. **
  82677. ** If P5 is positive and the jump is taken, then event counter
  82678. ** number P5-1 in the prepared statement is incremented.
  82679. **
  82680. ** See also: Prev
  82681. */
  82682. /* Opcode: Prev P1 P2 P3 P4 P5
  82683. **
  82684. ** Back up cursor P1 so that it points to the previous key/data pair in its
  82685. ** table or index. If there is no previous key/value pairs then fall through
  82686. ** to the following instruction. But if the cursor backup was successful,
  82687. ** jump immediately to P2.
  82688. **
  82689. **
  82690. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  82691. ** OP_Last opcode used to position the cursor. Prev is not allowed
  82692. ** to follow SeekGT, SeekGE, or OP_Rewind.
  82693. **
  82694. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  82695. ** not open then the behavior is undefined.
  82696. **
  82697. ** The P3 value is a hint to the btree implementation. If P3==1, that
  82698. ** means P1 is an SQL index and that this instruction could have been
  82699. ** omitted if that index had been unique. P3 is usually 0. P3 is
  82700. ** always either 0 or 1.
  82701. **
  82702. ** P4 is always of type P4_ADVANCE. The function pointer points to
  82703. ** sqlite3BtreePrevious().
  82704. **
  82705. ** If P5 is positive and the jump is taken, then event counter
  82706. ** number P5-1 in the prepared statement is incremented.
  82707. */
  82708. /* Opcode: SorterNext P1 P2 * * P5
  82709. **
  82710. ** This opcode works just like OP_Next except that P1 must be a
  82711. ** sorter object for which the OP_SorterSort opcode has been
  82712. ** invoked. This opcode advances the cursor to the next sorted
  82713. ** record, or jumps to P2 if there are no more sorted records.
  82714. */
  82715. case OP_SorterNext: { /* jump */
  82716. VdbeCursor *pC;
  82717. pC = p->apCsr[pOp->p1];
  82718. assert( isSorter(pC) );
  82719. rc = sqlite3VdbeSorterNext(db, pC);
  82720. goto next_tail;
  82721. case OP_Prev: /* jump */
  82722. case OP_Next: /* jump */
  82723. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82724. assert( pOp->p5<ArraySize(p->aCounter) );
  82725. pC = p->apCsr[pOp->p1];
  82726. assert( pC!=0 );
  82727. assert( pC->deferredMoveto==0 );
  82728. assert( pC->eCurType==CURTYPE_BTREE );
  82729. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  82730. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  82731. /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
  82732. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  82733. assert( pOp->opcode!=OP_Next
  82734. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  82735. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
  82736. || pC->seekOp==OP_NullRow);
  82737. assert( pOp->opcode!=OP_Prev
  82738. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  82739. || pC->seekOp==OP_Last
  82740. || pC->seekOp==OP_NullRow);
  82741. rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
  82742. next_tail:
  82743. pC->cacheStatus = CACHE_STALE;
  82744. VdbeBranchTaken(rc==SQLITE_OK,2);
  82745. if( rc==SQLITE_OK ){
  82746. pC->nullRow = 0;
  82747. p->aCounter[pOp->p5]++;
  82748. #ifdef SQLITE_TEST
  82749. sqlite3_search_count++;
  82750. #endif
  82751. goto jump_to_p2_and_check_for_interrupt;
  82752. }
  82753. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  82754. rc = SQLITE_OK;
  82755. pC->nullRow = 1;
  82756. goto check_for_interrupt;
  82757. }
  82758. /* Opcode: IdxInsert P1 P2 P3 P4 P5
  82759. ** Synopsis: key=r[P2]
  82760. **
  82761. ** Register P2 holds an SQL index key made using the
  82762. ** MakeRecord instructions. This opcode writes that key
  82763. ** into the index P1. Data for the entry is nil.
  82764. **
  82765. ** If P4 is not zero, then it is the number of values in the unpacked
  82766. ** key of reg(P2). In that case, P3 is the index of the first register
  82767. ** for the unpacked key. The availability of the unpacked key can sometimes
  82768. ** be an optimization.
  82769. **
  82770. ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
  82771. ** that this insert is likely to be an append.
  82772. **
  82773. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  82774. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  82775. ** then the change counter is unchanged.
  82776. **
  82777. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  82778. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  82779. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  82780. ** seeks on the cursor or if the most recent seek used a key equivalent
  82781. ** to P2.
  82782. **
  82783. ** This instruction only works for indices. The equivalent instruction
  82784. ** for tables is OP_Insert.
  82785. */
  82786. /* Opcode: SorterInsert P1 P2 * * *
  82787. ** Synopsis: key=r[P2]
  82788. **
  82789. ** Register P2 holds an SQL index key made using the
  82790. ** MakeRecord instructions. This opcode writes that key
  82791. ** into the sorter P1. Data for the entry is nil.
  82792. */
  82793. case OP_SorterInsert: /* in2 */
  82794. case OP_IdxInsert: { /* in2 */
  82795. VdbeCursor *pC;
  82796. BtreePayload x;
  82797. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82798. pC = p->apCsr[pOp->p1];
  82799. sqlite3VdbeIncrWriteCounter(p, pC);
  82800. assert( pC!=0 );
  82801. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  82802. pIn2 = &aMem[pOp->p2];
  82803. assert( pIn2->flags & MEM_Blob );
  82804. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  82805. assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
  82806. assert( pC->isTable==0 );
  82807. rc = ExpandBlob(pIn2);
  82808. if( rc ) goto abort_due_to_error;
  82809. if( pOp->opcode==OP_SorterInsert ){
  82810. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  82811. }else{
  82812. x.nKey = pIn2->n;
  82813. x.pKey = pIn2->z;
  82814. x.aMem = aMem + pOp->p3;
  82815. x.nMem = (u16)pOp->p4.i;
  82816. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  82817. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
  82818. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  82819. );
  82820. assert( pC->deferredMoveto==0 );
  82821. pC->cacheStatus = CACHE_STALE;
  82822. }
  82823. if( rc) goto abort_due_to_error;
  82824. break;
  82825. }
  82826. /* Opcode: IdxDelete P1 P2 P3 * *
  82827. ** Synopsis: key=r[P2@P3]
  82828. **
  82829. ** The content of P3 registers starting at register P2 form
  82830. ** an unpacked index key. This opcode removes that entry from the
  82831. ** index opened by cursor P1.
  82832. */
  82833. case OP_IdxDelete: {
  82834. VdbeCursor *pC;
  82835. BtCursor *pCrsr;
  82836. int res;
  82837. UnpackedRecord r;
  82838. assert( pOp->p3>0 );
  82839. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
  82840. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82841. pC = p->apCsr[pOp->p1];
  82842. assert( pC!=0 );
  82843. assert( pC->eCurType==CURTYPE_BTREE );
  82844. sqlite3VdbeIncrWriteCounter(p, pC);
  82845. pCrsr = pC->uc.pCursor;
  82846. assert( pCrsr!=0 );
  82847. assert( pOp->p5==0 );
  82848. r.pKeyInfo = pC->pKeyInfo;
  82849. r.nField = (u16)pOp->p3;
  82850. r.default_rc = 0;
  82851. r.aMem = &aMem[pOp->p2];
  82852. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  82853. if( rc ) goto abort_due_to_error;
  82854. if( res==0 ){
  82855. rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
  82856. if( rc ) goto abort_due_to_error;
  82857. }
  82858. assert( pC->deferredMoveto==0 );
  82859. pC->cacheStatus = CACHE_STALE;
  82860. pC->seekResult = 0;
  82861. break;
  82862. }
  82863. /* Opcode: DeferredSeek P1 * P3 P4 *
  82864. ** Synopsis: Move P3 to P1.rowid if needed
  82865. **
  82866. ** P1 is an open index cursor and P3 is a cursor on the corresponding
  82867. ** table. This opcode does a deferred seek of the P3 table cursor
  82868. ** to the row that corresponds to the current row of P1.
  82869. **
  82870. ** This is a deferred seek. Nothing actually happens until
  82871. ** the cursor is used to read a record. That way, if no reads
  82872. ** occur, no unnecessary I/O happens.
  82873. **
  82874. ** P4 may be an array of integers (type P4_INTARRAY) containing
  82875. ** one entry for each column in the P3 table. If array entry a(i)
  82876. ** is non-zero, then reading column a(i)-1 from cursor P3 is
  82877. ** equivalent to performing the deferred seek and then reading column i
  82878. ** from P1. This information is stored in P3 and used to redirect
  82879. ** reads against P3 over to P1, thus possibly avoiding the need to
  82880. ** seek and read cursor P3.
  82881. */
  82882. /* Opcode: IdxRowid P1 P2 * * *
  82883. ** Synopsis: r[P2]=rowid
  82884. **
  82885. ** Write into register P2 an integer which is the last entry in the record at
  82886. ** the end of the index key pointed to by cursor P1. This integer should be
  82887. ** the rowid of the table entry to which this index entry points.
  82888. **
  82889. ** See also: Rowid, MakeRecord.
  82890. */
  82891. case OP_DeferredSeek:
  82892. case OP_IdxRowid: { /* out2 */
  82893. VdbeCursor *pC; /* The P1 index cursor */
  82894. VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
  82895. i64 rowid; /* Rowid that P1 current points to */
  82896. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82897. pC = p->apCsr[pOp->p1];
  82898. assert( pC!=0 );
  82899. assert( pC->eCurType==CURTYPE_BTREE );
  82900. assert( pC->uc.pCursor!=0 );
  82901. assert( pC->isTable==0 );
  82902. assert( pC->deferredMoveto==0 );
  82903. assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
  82904. /* The IdxRowid and Seek opcodes are combined because of the commonality
  82905. ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
  82906. rc = sqlite3VdbeCursorRestore(pC);
  82907. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  82908. ** out from under the cursor. That will never happens for an IdxRowid
  82909. ** or Seek opcode */
  82910. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  82911. if( !pC->nullRow ){
  82912. rowid = 0; /* Not needed. Only used to silence a warning. */
  82913. rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
  82914. if( rc!=SQLITE_OK ){
  82915. goto abort_due_to_error;
  82916. }
  82917. if( pOp->opcode==OP_DeferredSeek ){
  82918. assert( pOp->p3>=0 && pOp->p3<p->nCursor );
  82919. pTabCur = p->apCsr[pOp->p3];
  82920. assert( pTabCur!=0 );
  82921. assert( pTabCur->eCurType==CURTYPE_BTREE );
  82922. assert( pTabCur->uc.pCursor!=0 );
  82923. assert( pTabCur->isTable );
  82924. pTabCur->nullRow = 0;
  82925. pTabCur->movetoTarget = rowid;
  82926. pTabCur->deferredMoveto = 1;
  82927. assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
  82928. pTabCur->aAltMap = pOp->p4.ai;
  82929. pTabCur->pAltCursor = pC;
  82930. }else{
  82931. pOut = out2Prerelease(p, pOp);
  82932. pOut->u.i = rowid;
  82933. }
  82934. }else{
  82935. assert( pOp->opcode==OP_IdxRowid );
  82936. sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
  82937. }
  82938. break;
  82939. }
  82940. /* Opcode: IdxGE P1 P2 P3 P4 P5
  82941. ** Synopsis: key=r[P3@P4]
  82942. **
  82943. ** The P4 register values beginning with P3 form an unpacked index
  82944. ** key that omits the PRIMARY KEY. Compare this key value against the index
  82945. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  82946. ** fields at the end.
  82947. **
  82948. ** If the P1 index entry is greater than or equal to the key value
  82949. ** then jump to P2. Otherwise fall through to the next instruction.
  82950. */
  82951. /* Opcode: IdxGT P1 P2 P3 P4 P5
  82952. ** Synopsis: key=r[P3@P4]
  82953. **
  82954. ** The P4 register values beginning with P3 form an unpacked index
  82955. ** key that omits the PRIMARY KEY. Compare this key value against the index
  82956. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  82957. ** fields at the end.
  82958. **
  82959. ** If the P1 index entry is greater than the key value
  82960. ** then jump to P2. Otherwise fall through to the next instruction.
  82961. */
  82962. /* Opcode: IdxLT P1 P2 P3 P4 P5
  82963. ** Synopsis: key=r[P3@P4]
  82964. **
  82965. ** The P4 register values beginning with P3 form an unpacked index
  82966. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  82967. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  82968. ** ROWID on the P1 index.
  82969. **
  82970. ** If the P1 index entry is less than the key value then jump to P2.
  82971. ** Otherwise fall through to the next instruction.
  82972. */
  82973. /* Opcode: IdxLE P1 P2 P3 P4 P5
  82974. ** Synopsis: key=r[P3@P4]
  82975. **
  82976. ** The P4 register values beginning with P3 form an unpacked index
  82977. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  82978. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  82979. ** ROWID on the P1 index.
  82980. **
  82981. ** If the P1 index entry is less than or equal to the key value then jump
  82982. ** to P2. Otherwise fall through to the next instruction.
  82983. */
  82984. case OP_IdxLE: /* jump */
  82985. case OP_IdxGT: /* jump */
  82986. case OP_IdxLT: /* jump */
  82987. case OP_IdxGE: { /* jump */
  82988. VdbeCursor *pC;
  82989. int res;
  82990. UnpackedRecord r;
  82991. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82992. pC = p->apCsr[pOp->p1];
  82993. assert( pC!=0 );
  82994. assert( pC->isOrdered );
  82995. assert( pC->eCurType==CURTYPE_BTREE );
  82996. assert( pC->uc.pCursor!=0);
  82997. assert( pC->deferredMoveto==0 );
  82998. assert( pOp->p5==0 || pOp->p5==1 );
  82999. assert( pOp->p4type==P4_INT32 );
  83000. r.pKeyInfo = pC->pKeyInfo;
  83001. r.nField = (u16)pOp->p4.i;
  83002. if( pOp->opcode<OP_IdxLT ){
  83003. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  83004. r.default_rc = -1;
  83005. }else{
  83006. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  83007. r.default_rc = 0;
  83008. }
  83009. r.aMem = &aMem[pOp->p3];
  83010. #ifdef SQLITE_DEBUG
  83011. {
  83012. int i;
  83013. for(i=0; i<r.nField; i++){
  83014. assert( memIsValid(&r.aMem[i]) );
  83015. REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
  83016. }
  83017. }
  83018. #endif
  83019. res = 0; /* Not needed. Only used to silence a warning. */
  83020. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  83021. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  83022. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  83023. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  83024. res = -res;
  83025. }else{
  83026. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  83027. res++;
  83028. }
  83029. VdbeBranchTaken(res>0,2);
  83030. if( rc ) goto abort_due_to_error;
  83031. if( res>0 ) goto jump_to_p2;
  83032. break;
  83033. }
  83034. /* Opcode: Destroy P1 P2 P3 * *
  83035. **
  83036. ** Delete an entire database table or index whose root page in the database
  83037. ** file is given by P1.
  83038. **
  83039. ** The table being destroyed is in the main database file if P3==0. If
  83040. ** P3==1 then the table to be clear is in the auxiliary database file
  83041. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  83042. **
  83043. ** If AUTOVACUUM is enabled then it is possible that another root page
  83044. ** might be moved into the newly deleted root page in order to keep all
  83045. ** root pages contiguous at the beginning of the database. The former
  83046. ** value of the root page that moved - its value before the move occurred -
  83047. ** is stored in register P2. If no page movement was required (because the
  83048. ** table being dropped was already the last one in the database) then a
  83049. ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
  83050. ** is stored in register P2.
  83051. **
  83052. ** This opcode throws an error if there are any active reader VMs when
  83053. ** it is invoked. This is done to avoid the difficulty associated with
  83054. ** updating existing cursors when a root page is moved in an AUTOVACUUM
  83055. ** database. This error is thrown even if the database is not an AUTOVACUUM
  83056. ** db in order to avoid introducing an incompatibility between autovacuum
  83057. ** and non-autovacuum modes.
  83058. **
  83059. ** See also: Clear
  83060. */
  83061. case OP_Destroy: { /* out2 */
  83062. int iMoved;
  83063. int iDb;
  83064. sqlite3VdbeIncrWriteCounter(p, 0);
  83065. assert( p->readOnly==0 );
  83066. assert( pOp->p1>1 );
  83067. pOut = out2Prerelease(p, pOp);
  83068. pOut->flags = MEM_Null;
  83069. if( db->nVdbeRead > db->nVDestroy+1 ){
  83070. rc = SQLITE_LOCKED;
  83071. p->errorAction = OE_Abort;
  83072. goto abort_due_to_error;
  83073. }else{
  83074. iDb = pOp->p3;
  83075. assert( DbMaskTest(p->btreeMask, iDb) );
  83076. iMoved = 0; /* Not needed. Only to silence a warning. */
  83077. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  83078. pOut->flags = MEM_Int;
  83079. pOut->u.i = iMoved;
  83080. if( rc ) goto abort_due_to_error;
  83081. #ifndef SQLITE_OMIT_AUTOVACUUM
  83082. if( iMoved!=0 ){
  83083. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  83084. /* All OP_Destroy operations occur on the same btree */
  83085. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  83086. resetSchemaOnFault = iDb+1;
  83087. }
  83088. #endif
  83089. }
  83090. break;
  83091. }
  83092. /* Opcode: Clear P1 P2 P3
  83093. **
  83094. ** Delete all contents of the database table or index whose root page
  83095. ** in the database file is given by P1. But, unlike Destroy, do not
  83096. ** remove the table or index from the database file.
  83097. **
  83098. ** The table being clear is in the main database file if P2==0. If
  83099. ** P2==1 then the table to be clear is in the auxiliary database file
  83100. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  83101. **
  83102. ** If the P3 value is non-zero, then the table referred to must be an
  83103. ** intkey table (an SQL table, not an index). In this case the row change
  83104. ** count is incremented by the number of rows in the table being cleared.
  83105. ** If P3 is greater than zero, then the value stored in register P3 is
  83106. ** also incremented by the number of rows in the table being cleared.
  83107. **
  83108. ** See also: Destroy
  83109. */
  83110. case OP_Clear: {
  83111. int nChange;
  83112. sqlite3VdbeIncrWriteCounter(p, 0);
  83113. nChange = 0;
  83114. assert( p->readOnly==0 );
  83115. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  83116. rc = sqlite3BtreeClearTable(
  83117. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  83118. );
  83119. if( pOp->p3 ){
  83120. p->nChange += nChange;
  83121. if( pOp->p3>0 ){
  83122. assert( memIsValid(&aMem[pOp->p3]) );
  83123. memAboutToChange(p, &aMem[pOp->p3]);
  83124. aMem[pOp->p3].u.i += nChange;
  83125. }
  83126. }
  83127. if( rc ) goto abort_due_to_error;
  83128. break;
  83129. }
  83130. /* Opcode: ResetSorter P1 * * * *
  83131. **
  83132. ** Delete all contents from the ephemeral table or sorter
  83133. ** that is open on cursor P1.
  83134. **
  83135. ** This opcode only works for cursors used for sorting and
  83136. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  83137. */
  83138. case OP_ResetSorter: {
  83139. VdbeCursor *pC;
  83140. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83141. pC = p->apCsr[pOp->p1];
  83142. assert( pC!=0 );
  83143. if( isSorter(pC) ){
  83144. sqlite3VdbeSorterReset(db, pC->uc.pSorter);
  83145. }else{
  83146. assert( pC->eCurType==CURTYPE_BTREE );
  83147. assert( pC->isEphemeral );
  83148. rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
  83149. if( rc ) goto abort_due_to_error;
  83150. }
  83151. break;
  83152. }
  83153. /* Opcode: CreateBtree P1 P2 P3 * *
  83154. ** Synopsis: r[P2]=root iDb=P1 flags=P3
  83155. **
  83156. ** Allocate a new b-tree in the main database file if P1==0 or in the
  83157. ** TEMP database file if P1==1 or in an attached database if
  83158. ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
  83159. ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
  83160. ** The root page number of the new b-tree is stored in register P2.
  83161. */
  83162. case OP_CreateBtree: { /* out2 */
  83163. int pgno;
  83164. Db *pDb;
  83165. sqlite3VdbeIncrWriteCounter(p, 0);
  83166. pOut = out2Prerelease(p, pOp);
  83167. pgno = 0;
  83168. assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
  83169. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  83170. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  83171. assert( p->readOnly==0 );
  83172. pDb = &db->aDb[pOp->p1];
  83173. assert( pDb->pBt!=0 );
  83174. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
  83175. if( rc ) goto abort_due_to_error;
  83176. pOut->u.i = pgno;
  83177. break;
  83178. }
  83179. /* Opcode: SqlExec * * * P4 *
  83180. **
  83181. ** Run the SQL statement or statements specified in the P4 string.
  83182. */
  83183. case OP_SqlExec: {
  83184. sqlite3VdbeIncrWriteCounter(p, 0);
  83185. db->nSqlExec++;
  83186. rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
  83187. db->nSqlExec--;
  83188. if( rc ) goto abort_due_to_error;
  83189. break;
  83190. }
  83191. /* Opcode: ParseSchema P1 * * P4 *
  83192. **
  83193. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  83194. ** that match the WHERE clause P4. If P4 is a NULL pointer, then the
  83195. ** entire schema for P1 is reparsed.
  83196. **
  83197. ** This opcode invokes the parser to create a new virtual machine,
  83198. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  83199. */
  83200. case OP_ParseSchema: {
  83201. int iDb;
  83202. const char *zMaster;
  83203. char *zSql;
  83204. InitData initData;
  83205. /* Any prepared statement that invokes this opcode will hold mutexes
  83206. ** on every btree. This is a prerequisite for invoking
  83207. ** sqlite3InitCallback().
  83208. */
  83209. #ifdef SQLITE_DEBUG
  83210. for(iDb=0; iDb<db->nDb; iDb++){
  83211. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  83212. }
  83213. #endif
  83214. iDb = pOp->p1;
  83215. assert( iDb>=0 && iDb<db->nDb );
  83216. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  83217. #ifndef SQLITE_OMIT_ALTERTABLE
  83218. if( pOp->p4.z==0 ){
  83219. sqlite3SchemaClear(db->aDb[iDb].pSchema);
  83220. db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
  83221. rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable);
  83222. db->mDbFlags |= DBFLAG_SchemaChange;
  83223. p->expired = 0;
  83224. }else
  83225. #endif
  83226. {
  83227. zMaster = MASTER_NAME;
  83228. initData.db = db;
  83229. initData.iDb = iDb;
  83230. initData.pzErrMsg = &p->zErrMsg;
  83231. initData.mInitFlags = 0;
  83232. zSql = sqlite3MPrintf(db,
  83233. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  83234. db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
  83235. if( zSql==0 ){
  83236. rc = SQLITE_NOMEM_BKPT;
  83237. }else{
  83238. assert( db->init.busy==0 );
  83239. db->init.busy = 1;
  83240. initData.rc = SQLITE_OK;
  83241. assert( !db->mallocFailed );
  83242. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  83243. if( rc==SQLITE_OK ) rc = initData.rc;
  83244. sqlite3DbFreeNN(db, zSql);
  83245. db->init.busy = 0;
  83246. }
  83247. }
  83248. if( rc ){
  83249. sqlite3ResetAllSchemasOfConnection(db);
  83250. if( rc==SQLITE_NOMEM ){
  83251. goto no_mem;
  83252. }
  83253. goto abort_due_to_error;
  83254. }
  83255. break;
  83256. }
  83257. #if !defined(SQLITE_OMIT_ANALYZE)
  83258. /* Opcode: LoadAnalysis P1 * * * *
  83259. **
  83260. ** Read the sqlite_stat1 table for database P1 and load the content
  83261. ** of that table into the internal index hash table. This will cause
  83262. ** the analysis to be used when preparing all subsequent queries.
  83263. */
  83264. case OP_LoadAnalysis: {
  83265. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  83266. rc = sqlite3AnalysisLoad(db, pOp->p1);
  83267. if( rc ) goto abort_due_to_error;
  83268. break;
  83269. }
  83270. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  83271. /* Opcode: DropTable P1 * * P4 *
  83272. **
  83273. ** Remove the internal (in-memory) data structures that describe
  83274. ** the table named P4 in database P1. This is called after a table
  83275. ** is dropped from disk (using the Destroy opcode) in order to keep
  83276. ** the internal representation of the
  83277. ** schema consistent with what is on disk.
  83278. */
  83279. case OP_DropTable: {
  83280. sqlite3VdbeIncrWriteCounter(p, 0);
  83281. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  83282. break;
  83283. }
  83284. /* Opcode: DropIndex P1 * * P4 *
  83285. **
  83286. ** Remove the internal (in-memory) data structures that describe
  83287. ** the index named P4 in database P1. This is called after an index
  83288. ** is dropped from disk (using the Destroy opcode)
  83289. ** in order to keep the internal representation of the
  83290. ** schema consistent with what is on disk.
  83291. */
  83292. case OP_DropIndex: {
  83293. sqlite3VdbeIncrWriteCounter(p, 0);
  83294. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  83295. break;
  83296. }
  83297. /* Opcode: DropTrigger P1 * * P4 *
  83298. **
  83299. ** Remove the internal (in-memory) data structures that describe
  83300. ** the trigger named P4 in database P1. This is called after a trigger
  83301. ** is dropped from disk (using the Destroy opcode) in order to keep
  83302. ** the internal representation of the
  83303. ** schema consistent with what is on disk.
  83304. */
  83305. case OP_DropTrigger: {
  83306. sqlite3VdbeIncrWriteCounter(p, 0);
  83307. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  83308. break;
  83309. }
  83310. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  83311. /* Opcode: IntegrityCk P1 P2 P3 P4 P5
  83312. **
  83313. ** Do an analysis of the currently open database. Store in
  83314. ** register P1 the text of an error message describing any problems.
  83315. ** If no problems are found, store a NULL in register P1.
  83316. **
  83317. ** The register P3 contains one less than the maximum number of allowed errors.
  83318. ** At most reg(P3) errors will be reported.
  83319. ** In other words, the analysis stops as soon as reg(P1) errors are
  83320. ** seen. Reg(P1) is updated with the number of errors remaining.
  83321. **
  83322. ** The root page numbers of all tables in the database are integers
  83323. ** stored in P4_INTARRAY argument.
  83324. **
  83325. ** If P5 is not zero, the check is done on the auxiliary database
  83326. ** file, not the main database file.
  83327. **
  83328. ** This opcode is used to implement the integrity_check pragma.
  83329. */
  83330. case OP_IntegrityCk: {
  83331. int nRoot; /* Number of tables to check. (Number of root pages.) */
  83332. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  83333. int nErr; /* Number of errors reported */
  83334. char *z; /* Text of the error report */
  83335. Mem *pnErr; /* Register keeping track of errors remaining */
  83336. assert( p->bIsReader );
  83337. nRoot = pOp->p2;
  83338. aRoot = pOp->p4.ai;
  83339. assert( nRoot>0 );
  83340. assert( aRoot[0]==nRoot );
  83341. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  83342. pnErr = &aMem[pOp->p3];
  83343. assert( (pnErr->flags & MEM_Int)!=0 );
  83344. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  83345. pIn1 = &aMem[pOp->p1];
  83346. assert( pOp->p5<db->nDb );
  83347. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  83348. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
  83349. (int)pnErr->u.i+1, &nErr);
  83350. sqlite3VdbeMemSetNull(pIn1);
  83351. if( nErr==0 ){
  83352. assert( z==0 );
  83353. }else if( z==0 ){
  83354. goto no_mem;
  83355. }else{
  83356. pnErr->u.i -= nErr-1;
  83357. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  83358. }
  83359. UPDATE_MAX_BLOBSIZE(pIn1);
  83360. sqlite3VdbeChangeEncoding(pIn1, encoding);
  83361. break;
  83362. }
  83363. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  83364. /* Opcode: RowSetAdd P1 P2 * * *
  83365. ** Synopsis: rowset(P1)=r[P2]
  83366. **
  83367. ** Insert the integer value held by register P2 into a RowSet object
  83368. ** held in register P1.
  83369. **
  83370. ** An assertion fails if P2 is not an integer.
  83371. */
  83372. case OP_RowSetAdd: { /* in1, in2 */
  83373. pIn1 = &aMem[pOp->p1];
  83374. pIn2 = &aMem[pOp->p2];
  83375. assert( (pIn2->flags & MEM_Int)!=0 );
  83376. if( (pIn1->flags & MEM_Blob)==0 ){
  83377. if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
  83378. }
  83379. assert( sqlite3VdbeMemIsRowSet(pIn1) );
  83380. sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
  83381. break;
  83382. }
  83383. /* Opcode: RowSetRead P1 P2 P3 * *
  83384. ** Synopsis: r[P3]=rowset(P1)
  83385. **
  83386. ** Extract the smallest value from the RowSet object in P1
  83387. ** and put that value into register P3.
  83388. ** Or, if RowSet object P1 is initially empty, leave P3
  83389. ** unchanged and jump to instruction P2.
  83390. */
  83391. case OP_RowSetRead: { /* jump, in1, out3 */
  83392. i64 val;
  83393. pIn1 = &aMem[pOp->p1];
  83394. assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
  83395. if( (pIn1->flags & MEM_Blob)==0
  83396. || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
  83397. ){
  83398. /* The boolean index is empty */
  83399. sqlite3VdbeMemSetNull(pIn1);
  83400. VdbeBranchTaken(1,2);
  83401. goto jump_to_p2_and_check_for_interrupt;
  83402. }else{
  83403. /* A value was pulled from the index */
  83404. VdbeBranchTaken(0,2);
  83405. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  83406. }
  83407. goto check_for_interrupt;
  83408. }
  83409. /* Opcode: RowSetTest P1 P2 P3 P4
  83410. ** Synopsis: if r[P3] in rowset(P1) goto P2
  83411. **
  83412. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  83413. ** contains a RowSet object and that RowSet object contains
  83414. ** the value held in P3, jump to register P2. Otherwise, insert the
  83415. ** integer in P3 into the RowSet and continue on to the
  83416. ** next opcode.
  83417. **
  83418. ** The RowSet object is optimized for the case where sets of integers
  83419. ** are inserted in distinct phases, which each set contains no duplicates.
  83420. ** Each set is identified by a unique P4 value. The first set
  83421. ** must have P4==0, the final set must have P4==-1, and for all other sets
  83422. ** must have P4>0.
  83423. **
  83424. ** This allows optimizations: (a) when P4==0 there is no need to test
  83425. ** the RowSet object for P3, as it is guaranteed not to contain it,
  83426. ** (b) when P4==-1 there is no need to insert the value, as it will
  83427. ** never be tested for, and (c) when a value that is part of set X is
  83428. ** inserted, there is no need to search to see if the same value was
  83429. ** previously inserted as part of set X (only if it was previously
  83430. ** inserted as part of some other set).
  83431. */
  83432. case OP_RowSetTest: { /* jump, in1, in3 */
  83433. int iSet;
  83434. int exists;
  83435. pIn1 = &aMem[pOp->p1];
  83436. pIn3 = &aMem[pOp->p3];
  83437. iSet = pOp->p4.i;
  83438. assert( pIn3->flags&MEM_Int );
  83439. /* If there is anything other than a rowset object in memory cell P1,
  83440. ** delete it now and initialize P1 with an empty rowset
  83441. */
  83442. if( (pIn1->flags & MEM_Blob)==0 ){
  83443. if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
  83444. }
  83445. assert( sqlite3VdbeMemIsRowSet(pIn1) );
  83446. assert( pOp->p4type==P4_INT32 );
  83447. assert( iSet==-1 || iSet>=0 );
  83448. if( iSet ){
  83449. exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
  83450. VdbeBranchTaken(exists!=0,2);
  83451. if( exists ) goto jump_to_p2;
  83452. }
  83453. if( iSet>=0 ){
  83454. sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
  83455. }
  83456. break;
  83457. }
  83458. #ifndef SQLITE_OMIT_TRIGGER
  83459. /* Opcode: Program P1 P2 P3 P4 P5
  83460. **
  83461. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  83462. **
  83463. ** P1 contains the address of the memory cell that contains the first memory
  83464. ** cell in an array of values used as arguments to the sub-program. P2
  83465. ** contains the address to jump to if the sub-program throws an IGNORE
  83466. ** exception using the RAISE() function. Register P3 contains the address
  83467. ** of a memory cell in this (the parent) VM that is used to allocate the
  83468. ** memory required by the sub-vdbe at runtime.
  83469. **
  83470. ** P4 is a pointer to the VM containing the trigger program.
  83471. **
  83472. ** If P5 is non-zero, then recursive program invocation is enabled.
  83473. */
  83474. case OP_Program: { /* jump */
  83475. int nMem; /* Number of memory registers for sub-program */
  83476. int nByte; /* Bytes of runtime space required for sub-program */
  83477. Mem *pRt; /* Register to allocate runtime space */
  83478. Mem *pMem; /* Used to iterate through memory cells */
  83479. Mem *pEnd; /* Last memory cell in new array */
  83480. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  83481. SubProgram *pProgram; /* Sub-program to execute */
  83482. void *t; /* Token identifying trigger */
  83483. pProgram = pOp->p4.pProgram;
  83484. pRt = &aMem[pOp->p3];
  83485. assert( pProgram->nOp>0 );
  83486. /* If the p5 flag is clear, then recursive invocation of triggers is
  83487. ** disabled for backwards compatibility (p5 is set if this sub-program
  83488. ** is really a trigger, not a foreign key action, and the flag set
  83489. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  83490. **
  83491. ** It is recursive invocation of triggers, at the SQL level, that is
  83492. ** disabled. In some cases a single trigger may generate more than one
  83493. ** SubProgram (if the trigger may be executed with more than one different
  83494. ** ON CONFLICT algorithm). SubProgram structures associated with a
  83495. ** single trigger all have the same value for the SubProgram.token
  83496. ** variable. */
  83497. if( pOp->p5 ){
  83498. t = pProgram->token;
  83499. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  83500. if( pFrame ) break;
  83501. }
  83502. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  83503. rc = SQLITE_ERROR;
  83504. sqlite3VdbeError(p, "too many levels of trigger recursion");
  83505. goto abort_due_to_error;
  83506. }
  83507. /* Register pRt is used to store the memory required to save the state
  83508. ** of the current program, and the memory required at runtime to execute
  83509. ** the trigger program. If this trigger has been fired before, then pRt
  83510. ** is already allocated. Otherwise, it must be initialized. */
  83511. if( (pRt->flags&MEM_Blob)==0 ){
  83512. /* SubProgram.nMem is set to the number of memory cells used by the
  83513. ** program stored in SubProgram.aOp. As well as these, one memory
  83514. ** cell is required for each cursor used by the program. Set local
  83515. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  83516. */
  83517. nMem = pProgram->nMem + pProgram->nCsr;
  83518. assert( nMem>0 );
  83519. if( pProgram->nCsr==0 ) nMem++;
  83520. nByte = ROUND8(sizeof(VdbeFrame))
  83521. + nMem * sizeof(Mem)
  83522. + pProgram->nCsr * sizeof(VdbeCursor*)
  83523. + (pProgram->nOp + 7)/8;
  83524. pFrame = sqlite3DbMallocZero(db, nByte);
  83525. if( !pFrame ){
  83526. goto no_mem;
  83527. }
  83528. sqlite3VdbeMemRelease(pRt);
  83529. pRt->flags = MEM_Blob|MEM_Dyn;
  83530. pRt->z = (char*)pFrame;
  83531. pRt->n = nByte;
  83532. pRt->xDel = sqlite3VdbeFrameMemDel;
  83533. pFrame->v = p;
  83534. pFrame->nChildMem = nMem;
  83535. pFrame->nChildCsr = pProgram->nCsr;
  83536. pFrame->pc = (int)(pOp - aOp);
  83537. pFrame->aMem = p->aMem;
  83538. pFrame->nMem = p->nMem;
  83539. pFrame->apCsr = p->apCsr;
  83540. pFrame->nCursor = p->nCursor;
  83541. pFrame->aOp = p->aOp;
  83542. pFrame->nOp = p->nOp;
  83543. pFrame->token = pProgram->token;
  83544. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  83545. pFrame->anExec = p->anExec;
  83546. #endif
  83547. #ifdef SQLITE_DEBUG
  83548. pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
  83549. #endif
  83550. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  83551. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  83552. pMem->flags = MEM_Undefined;
  83553. pMem->db = db;
  83554. }
  83555. }else{
  83556. pFrame = (VdbeFrame*)pRt->z;
  83557. assert( pRt->xDel==sqlite3VdbeFrameMemDel );
  83558. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
  83559. || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
  83560. assert( pProgram->nCsr==pFrame->nChildCsr );
  83561. assert( (int)(pOp - aOp)==pFrame->pc );
  83562. }
  83563. p->nFrame++;
  83564. pFrame->pParent = p->pFrame;
  83565. pFrame->lastRowid = db->lastRowid;
  83566. pFrame->nChange = p->nChange;
  83567. pFrame->nDbChange = p->db->nChange;
  83568. assert( pFrame->pAuxData==0 );
  83569. pFrame->pAuxData = p->pAuxData;
  83570. p->pAuxData = 0;
  83571. p->nChange = 0;
  83572. p->pFrame = pFrame;
  83573. p->aMem = aMem = VdbeFrameMem(pFrame);
  83574. p->nMem = pFrame->nChildMem;
  83575. p->nCursor = (u16)pFrame->nChildCsr;
  83576. p->apCsr = (VdbeCursor **)&aMem[p->nMem];
  83577. pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
  83578. memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
  83579. p->aOp = aOp = pProgram->aOp;
  83580. p->nOp = pProgram->nOp;
  83581. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  83582. p->anExec = 0;
  83583. #endif
  83584. pOp = &aOp[-1];
  83585. break;
  83586. }
  83587. /* Opcode: Param P1 P2 * * *
  83588. **
  83589. ** This opcode is only ever present in sub-programs called via the
  83590. ** OP_Program instruction. Copy a value currently stored in a memory
  83591. ** cell of the calling (parent) frame to cell P2 in the current frames
  83592. ** address space. This is used by trigger programs to access the new.*
  83593. ** and old.* values.
  83594. **
  83595. ** The address of the cell in the parent frame is determined by adding
  83596. ** the value of the P1 argument to the value of the P1 argument to the
  83597. ** calling OP_Program instruction.
  83598. */
  83599. case OP_Param: { /* out2 */
  83600. VdbeFrame *pFrame;
  83601. Mem *pIn;
  83602. pOut = out2Prerelease(p, pOp);
  83603. pFrame = p->pFrame;
  83604. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  83605. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  83606. break;
  83607. }
  83608. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  83609. #ifndef SQLITE_OMIT_FOREIGN_KEY
  83610. /* Opcode: FkCounter P1 P2 * * *
  83611. ** Synopsis: fkctr[P1]+=P2
  83612. **
  83613. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  83614. ** If P1 is non-zero, the database constraint counter is incremented
  83615. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  83616. ** statement counter is incremented (immediate foreign key constraints).
  83617. */
  83618. case OP_FkCounter: {
  83619. if( db->flags & SQLITE_DeferFKs ){
  83620. db->nDeferredImmCons += pOp->p2;
  83621. }else if( pOp->p1 ){
  83622. db->nDeferredCons += pOp->p2;
  83623. }else{
  83624. p->nFkConstraint += pOp->p2;
  83625. }
  83626. break;
  83627. }
  83628. /* Opcode: FkIfZero P1 P2 * * *
  83629. ** Synopsis: if fkctr[P1]==0 goto P2
  83630. **
  83631. ** This opcode tests if a foreign key constraint-counter is currently zero.
  83632. ** If so, jump to instruction P2. Otherwise, fall through to the next
  83633. ** instruction.
  83634. **
  83635. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  83636. ** is zero (the one that counts deferred constraint violations). If P1 is
  83637. ** zero, the jump is taken if the statement constraint-counter is zero
  83638. ** (immediate foreign key constraint violations).
  83639. */
  83640. case OP_FkIfZero: { /* jump */
  83641. if( pOp->p1 ){
  83642. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  83643. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  83644. }else{
  83645. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  83646. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  83647. }
  83648. break;
  83649. }
  83650. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  83651. #ifndef SQLITE_OMIT_AUTOINCREMENT
  83652. /* Opcode: MemMax P1 P2 * * *
  83653. ** Synopsis: r[P1]=max(r[P1],r[P2])
  83654. **
  83655. ** P1 is a register in the root frame of this VM (the root frame is
  83656. ** different from the current frame if this instruction is being executed
  83657. ** within a sub-program). Set the value of register P1 to the maximum of
  83658. ** its current value and the value in register P2.
  83659. **
  83660. ** This instruction throws an error if the memory cell is not initially
  83661. ** an integer.
  83662. */
  83663. case OP_MemMax: { /* in2 */
  83664. VdbeFrame *pFrame;
  83665. if( p->pFrame ){
  83666. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  83667. pIn1 = &pFrame->aMem[pOp->p1];
  83668. }else{
  83669. pIn1 = &aMem[pOp->p1];
  83670. }
  83671. assert( memIsValid(pIn1) );
  83672. sqlite3VdbeMemIntegerify(pIn1);
  83673. pIn2 = &aMem[pOp->p2];
  83674. sqlite3VdbeMemIntegerify(pIn2);
  83675. if( pIn1->u.i<pIn2->u.i){
  83676. pIn1->u.i = pIn2->u.i;
  83677. }
  83678. break;
  83679. }
  83680. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  83681. /* Opcode: IfPos P1 P2 P3 * *
  83682. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  83683. **
  83684. ** Register P1 must contain an integer.
  83685. ** If the value of register P1 is 1 or greater, subtract P3 from the
  83686. ** value in P1 and jump to P2.
  83687. **
  83688. ** If the initial value of register P1 is less than 1, then the
  83689. ** value is unchanged and control passes through to the next instruction.
  83690. */
  83691. case OP_IfPos: { /* jump, in1 */
  83692. pIn1 = &aMem[pOp->p1];
  83693. assert( pIn1->flags&MEM_Int );
  83694. VdbeBranchTaken( pIn1->u.i>0, 2);
  83695. if( pIn1->u.i>0 ){
  83696. pIn1->u.i -= pOp->p3;
  83697. goto jump_to_p2;
  83698. }
  83699. break;
  83700. }
  83701. /* Opcode: OffsetLimit P1 P2 P3 * *
  83702. ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
  83703. **
  83704. ** This opcode performs a commonly used computation associated with
  83705. ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
  83706. ** holds the offset counter. The opcode computes the combined value
  83707. ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
  83708. ** value computed is the total number of rows that will need to be
  83709. ** visited in order to complete the query.
  83710. **
  83711. ** If r[P3] is zero or negative, that means there is no OFFSET
  83712. ** and r[P2] is set to be the value of the LIMIT, r[P1].
  83713. **
  83714. ** if r[P1] is zero or negative, that means there is no LIMIT
  83715. ** and r[P2] is set to -1.
  83716. **
  83717. ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
  83718. */
  83719. case OP_OffsetLimit: { /* in1, out2, in3 */
  83720. i64 x;
  83721. pIn1 = &aMem[pOp->p1];
  83722. pIn3 = &aMem[pOp->p3];
  83723. pOut = out2Prerelease(p, pOp);
  83724. assert( pIn1->flags & MEM_Int );
  83725. assert( pIn3->flags & MEM_Int );
  83726. x = pIn1->u.i;
  83727. if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
  83728. /* If the LIMIT is less than or equal to zero, loop forever. This
  83729. ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
  83730. ** also loop forever. This is undocumented. In fact, one could argue
  83731. ** that the loop should terminate. But assuming 1 billion iterations
  83732. ** per second (far exceeding the capabilities of any current hardware)
  83733. ** it would take nearly 300 years to actually reach the limit. So
  83734. ** looping forever is a reasonable approximation. */
  83735. pOut->u.i = -1;
  83736. }else{
  83737. pOut->u.i = x;
  83738. }
  83739. break;
  83740. }
  83741. /* Opcode: IfNotZero P1 P2 * * *
  83742. ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
  83743. **
  83744. ** Register P1 must contain an integer. If the content of register P1 is
  83745. ** initially greater than zero, then decrement the value in register P1.
  83746. ** If it is non-zero (negative or positive) and then also jump to P2.
  83747. ** If register P1 is initially zero, leave it unchanged and fall through.
  83748. */
  83749. case OP_IfNotZero: { /* jump, in1 */
  83750. pIn1 = &aMem[pOp->p1];
  83751. assert( pIn1->flags&MEM_Int );
  83752. VdbeBranchTaken(pIn1->u.i<0, 2);
  83753. if( pIn1->u.i ){
  83754. if( pIn1->u.i>0 ) pIn1->u.i--;
  83755. goto jump_to_p2;
  83756. }
  83757. break;
  83758. }
  83759. /* Opcode: DecrJumpZero P1 P2 * * *
  83760. ** Synopsis: if (--r[P1])==0 goto P2
  83761. **
  83762. ** Register P1 must hold an integer. Decrement the value in P1
  83763. ** and jump to P2 if the new value is exactly zero.
  83764. */
  83765. case OP_DecrJumpZero: { /* jump, in1 */
  83766. pIn1 = &aMem[pOp->p1];
  83767. assert( pIn1->flags&MEM_Int );
  83768. if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
  83769. VdbeBranchTaken(pIn1->u.i==0, 2);
  83770. if( pIn1->u.i==0 ) goto jump_to_p2;
  83771. break;
  83772. }
  83773. /* Opcode: AggStep * P2 P3 P4 P5
  83774. ** Synopsis: accum=r[P3] step(r[P2@P5])
  83775. **
  83776. ** Execute the xStep function for an aggregate.
  83777. ** The function has P5 arguments. P4 is a pointer to the
  83778. ** FuncDef structure that specifies the function. Register P3 is the
  83779. ** accumulator.
  83780. **
  83781. ** The P5 arguments are taken from register P2 and its
  83782. ** successors.
  83783. */
  83784. /* Opcode: AggInverse * P2 P3 P4 P5
  83785. ** Synopsis: accum=r[P3] inverse(r[P2@P5])
  83786. **
  83787. ** Execute the xInverse function for an aggregate.
  83788. ** The function has P5 arguments. P4 is a pointer to the
  83789. ** FuncDef structure that specifies the function. Register P3 is the
  83790. ** accumulator.
  83791. **
  83792. ** The P5 arguments are taken from register P2 and its
  83793. ** successors.
  83794. */
  83795. /* Opcode: AggStep1 P1 P2 P3 P4 P5
  83796. ** Synopsis: accum=r[P3] step(r[P2@P5])
  83797. **
  83798. ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
  83799. ** aggregate. The function has P5 arguments. P4 is a pointer to the
  83800. ** FuncDef structure that specifies the function. Register P3 is the
  83801. ** accumulator.
  83802. **
  83803. ** The P5 arguments are taken from register P2 and its
  83804. ** successors.
  83805. **
  83806. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  83807. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  83808. ** the opcode is changed. In this way, the initialization of the
  83809. ** sqlite3_context only happens once, instead of on each call to the
  83810. ** step function.
  83811. */
  83812. case OP_AggInverse:
  83813. case OP_AggStep: {
  83814. int n;
  83815. sqlite3_context *pCtx;
  83816. assert( pOp->p4type==P4_FUNCDEF );
  83817. n = pOp->p5;
  83818. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  83819. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  83820. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  83821. pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
  83822. (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
  83823. if( pCtx==0 ) goto no_mem;
  83824. pCtx->pMem = 0;
  83825. pCtx->pOut = (Mem*)&(pCtx->argv[n]);
  83826. sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
  83827. pCtx->pFunc = pOp->p4.pFunc;
  83828. pCtx->iOp = (int)(pOp - aOp);
  83829. pCtx->pVdbe = p;
  83830. pCtx->skipFlag = 0;
  83831. pCtx->isError = 0;
  83832. pCtx->argc = n;
  83833. pOp->p4type = P4_FUNCCTX;
  83834. pOp->p4.pCtx = pCtx;
  83835. /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
  83836. assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
  83837. pOp->opcode = OP_AggStep1;
  83838. /* Fall through into OP_AggStep */
  83839. }
  83840. case OP_AggStep1: {
  83841. int i;
  83842. sqlite3_context *pCtx;
  83843. Mem *pMem;
  83844. assert( pOp->p4type==P4_FUNCCTX );
  83845. pCtx = pOp->p4.pCtx;
  83846. pMem = &aMem[pOp->p3];
  83847. #ifdef SQLITE_DEBUG
  83848. if( pOp->p1 ){
  83849. /* This is an OP_AggInverse call. Verify that xStep has always
  83850. ** been called at least once prior to any xInverse call. */
  83851. assert( pMem->uTemp==0x1122e0e3 );
  83852. }else{
  83853. /* This is an OP_AggStep call. Mark it as such. */
  83854. pMem->uTemp = 0x1122e0e3;
  83855. }
  83856. #endif
  83857. /* If this function is inside of a trigger, the register array in aMem[]
  83858. ** might change from one evaluation to the next. The next block of code
  83859. ** checks to see if the register array has changed, and if so it
  83860. ** reinitializes the relavant parts of the sqlite3_context object */
  83861. if( pCtx->pMem != pMem ){
  83862. pCtx->pMem = pMem;
  83863. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  83864. }
  83865. #ifdef SQLITE_DEBUG
  83866. for(i=0; i<pCtx->argc; i++){
  83867. assert( memIsValid(pCtx->argv[i]) );
  83868. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  83869. }
  83870. #endif
  83871. pMem->n++;
  83872. assert( pCtx->pOut->flags==MEM_Null );
  83873. assert( pCtx->isError==0 );
  83874. assert( pCtx->skipFlag==0 );
  83875. #ifndef SQLITE_OMIT_WINDOWFUNC
  83876. if( pOp->p1 ){
  83877. (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
  83878. }else
  83879. #endif
  83880. (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  83881. if( pCtx->isError ){
  83882. if( pCtx->isError>0 ){
  83883. sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
  83884. rc = pCtx->isError;
  83885. }
  83886. if( pCtx->skipFlag ){
  83887. assert( pOp[-1].opcode==OP_CollSeq );
  83888. i = pOp[-1].p1;
  83889. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  83890. pCtx->skipFlag = 0;
  83891. }
  83892. sqlite3VdbeMemRelease(pCtx->pOut);
  83893. pCtx->pOut->flags = MEM_Null;
  83894. pCtx->isError = 0;
  83895. if( rc ) goto abort_due_to_error;
  83896. }
  83897. assert( pCtx->pOut->flags==MEM_Null );
  83898. assert( pCtx->skipFlag==0 );
  83899. break;
  83900. }
  83901. /* Opcode: AggFinal P1 P2 * P4 *
  83902. ** Synopsis: accum=r[P1] N=P2
  83903. **
  83904. ** P1 is the memory location that is the accumulator for an aggregate
  83905. ** or window function. Execute the finalizer function
  83906. ** for an aggregate and store the result in P1.
  83907. **
  83908. ** P2 is the number of arguments that the step function takes and
  83909. ** P4 is a pointer to the FuncDef for this function. The P2
  83910. ** argument is not used by this opcode. It is only there to disambiguate
  83911. ** functions that can take varying numbers of arguments. The
  83912. ** P4 argument is only needed for the case where
  83913. ** the step function was not previously called.
  83914. */
  83915. /* Opcode: AggValue * P2 P3 P4 *
  83916. ** Synopsis: r[P3]=value N=P2
  83917. **
  83918. ** Invoke the xValue() function and store the result in register P3.
  83919. **
  83920. ** P2 is the number of arguments that the step function takes and
  83921. ** P4 is a pointer to the FuncDef for this function. The P2
  83922. ** argument is not used by this opcode. It is only there to disambiguate
  83923. ** functions that can take varying numbers of arguments. The
  83924. ** P4 argument is only needed for the case where
  83925. ** the step function was not previously called.
  83926. */
  83927. case OP_AggValue:
  83928. case OP_AggFinal: {
  83929. Mem *pMem;
  83930. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  83931. assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
  83932. pMem = &aMem[pOp->p1];
  83933. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  83934. #ifndef SQLITE_OMIT_WINDOWFUNC
  83935. if( pOp->p3 ){
  83936. rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
  83937. pMem = &aMem[pOp->p3];
  83938. }else
  83939. #endif
  83940. {
  83941. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  83942. }
  83943. if( rc ){
  83944. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  83945. goto abort_due_to_error;
  83946. }
  83947. sqlite3VdbeChangeEncoding(pMem, encoding);
  83948. UPDATE_MAX_BLOBSIZE(pMem);
  83949. if( sqlite3VdbeMemTooBig(pMem) ){
  83950. goto too_big;
  83951. }
  83952. break;
  83953. }
  83954. #ifndef SQLITE_OMIT_WAL
  83955. /* Opcode: Checkpoint P1 P2 P3 * *
  83956. **
  83957. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  83958. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  83959. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  83960. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  83961. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  83962. ** in the WAL that have been checkpointed after the checkpoint
  83963. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  83964. ** mem[P3+2] are initialized to -1.
  83965. */
  83966. case OP_Checkpoint: {
  83967. int i; /* Loop counter */
  83968. int aRes[3]; /* Results */
  83969. Mem *pMem; /* Write results here */
  83970. assert( p->readOnly==0 );
  83971. aRes[0] = 0;
  83972. aRes[1] = aRes[2] = -1;
  83973. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  83974. || pOp->p2==SQLITE_CHECKPOINT_FULL
  83975. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  83976. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  83977. );
  83978. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  83979. if( rc ){
  83980. if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
  83981. rc = SQLITE_OK;
  83982. aRes[0] = 1;
  83983. }
  83984. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  83985. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  83986. }
  83987. break;
  83988. };
  83989. #endif
  83990. #ifndef SQLITE_OMIT_PRAGMA
  83991. /* Opcode: JournalMode P1 P2 P3 * *
  83992. **
  83993. ** Change the journal mode of database P1 to P3. P3 must be one of the
  83994. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  83995. ** modes (delete, truncate, persist, off and memory), this is a simple
  83996. ** operation. No IO is required.
  83997. **
  83998. ** If changing into or out of WAL mode the procedure is more complicated.
  83999. **
  84000. ** Write a string containing the final journal-mode to register P2.
  84001. */
  84002. case OP_JournalMode: { /* out2 */
  84003. Btree *pBt; /* Btree to change journal mode of */
  84004. Pager *pPager; /* Pager associated with pBt */
  84005. int eNew; /* New journal mode */
  84006. int eOld; /* The old journal mode */
  84007. #ifndef SQLITE_OMIT_WAL
  84008. const char *zFilename; /* Name of database file for pPager */
  84009. #endif
  84010. pOut = out2Prerelease(p, pOp);
  84011. eNew = pOp->p3;
  84012. assert( eNew==PAGER_JOURNALMODE_DELETE
  84013. || eNew==PAGER_JOURNALMODE_TRUNCATE
  84014. || eNew==PAGER_JOURNALMODE_PERSIST
  84015. || eNew==PAGER_JOURNALMODE_OFF
  84016. || eNew==PAGER_JOURNALMODE_MEMORY
  84017. || eNew==PAGER_JOURNALMODE_WAL
  84018. || eNew==PAGER_JOURNALMODE_QUERY
  84019. );
  84020. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  84021. assert( p->readOnly==0 );
  84022. pBt = db->aDb[pOp->p1].pBt;
  84023. pPager = sqlite3BtreePager(pBt);
  84024. eOld = sqlite3PagerGetJournalMode(pPager);
  84025. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  84026. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  84027. #ifndef SQLITE_OMIT_WAL
  84028. zFilename = sqlite3PagerFilename(pPager, 1);
  84029. /* Do not allow a transition to journal_mode=WAL for a database
  84030. ** in temporary storage or if the VFS does not support shared memory
  84031. */
  84032. if( eNew==PAGER_JOURNALMODE_WAL
  84033. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  84034. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  84035. ){
  84036. eNew = eOld;
  84037. }
  84038. if( (eNew!=eOld)
  84039. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  84040. ){
  84041. if( !db->autoCommit || db->nVdbeRead>1 ){
  84042. rc = SQLITE_ERROR;
  84043. sqlite3VdbeError(p,
  84044. "cannot change %s wal mode from within a transaction",
  84045. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  84046. );
  84047. goto abort_due_to_error;
  84048. }else{
  84049. if( eOld==PAGER_JOURNALMODE_WAL ){
  84050. /* If leaving WAL mode, close the log file. If successful, the call
  84051. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  84052. ** file. An EXCLUSIVE lock may still be held on the database file
  84053. ** after a successful return.
  84054. */
  84055. rc = sqlite3PagerCloseWal(pPager, db);
  84056. if( rc==SQLITE_OK ){
  84057. sqlite3PagerSetJournalMode(pPager, eNew);
  84058. }
  84059. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  84060. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  84061. ** as an intermediate */
  84062. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  84063. }
  84064. /* Open a transaction on the database file. Regardless of the journal
  84065. ** mode, this transaction always uses a rollback journal.
  84066. */
  84067. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  84068. if( rc==SQLITE_OK ){
  84069. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  84070. }
  84071. }
  84072. }
  84073. #endif /* ifndef SQLITE_OMIT_WAL */
  84074. if( rc ) eNew = eOld;
  84075. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  84076. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  84077. pOut->z = (char *)sqlite3JournalModename(eNew);
  84078. pOut->n = sqlite3Strlen30(pOut->z);
  84079. pOut->enc = SQLITE_UTF8;
  84080. sqlite3VdbeChangeEncoding(pOut, encoding);
  84081. if( rc ) goto abort_due_to_error;
  84082. break;
  84083. };
  84084. #endif /* SQLITE_OMIT_PRAGMA */
  84085. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  84086. /* Opcode: Vacuum P1 * * * *
  84087. **
  84088. ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
  84089. ** for an attached database. The "temp" database may not be vacuumed.
  84090. */
  84091. case OP_Vacuum: {
  84092. assert( p->readOnly==0 );
  84093. rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
  84094. if( rc ) goto abort_due_to_error;
  84095. break;
  84096. }
  84097. #endif
  84098. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  84099. /* Opcode: IncrVacuum P1 P2 * * *
  84100. **
  84101. ** Perform a single step of the incremental vacuum procedure on
  84102. ** the P1 database. If the vacuum has finished, jump to instruction
  84103. ** P2. Otherwise, fall through to the next instruction.
  84104. */
  84105. case OP_IncrVacuum: { /* jump */
  84106. Btree *pBt;
  84107. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  84108. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  84109. assert( p->readOnly==0 );
  84110. pBt = db->aDb[pOp->p1].pBt;
  84111. rc = sqlite3BtreeIncrVacuum(pBt);
  84112. VdbeBranchTaken(rc==SQLITE_DONE,2);
  84113. if( rc ){
  84114. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  84115. rc = SQLITE_OK;
  84116. goto jump_to_p2;
  84117. }
  84118. break;
  84119. }
  84120. #endif
  84121. /* Opcode: Expire P1 P2 * * *
  84122. **
  84123. ** Cause precompiled statements to expire. When an expired statement
  84124. ** is executed using sqlite3_step() it will either automatically
  84125. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  84126. ** or it will fail with SQLITE_SCHEMA.
  84127. **
  84128. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  84129. ** then only the currently executing statement is expired.
  84130. **
  84131. ** If P2 is 0, then SQL statements are expired immediately. If P2 is 1,
  84132. ** then running SQL statements are allowed to continue to run to completion.
  84133. ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
  84134. ** that might help the statement run faster but which does not affect the
  84135. ** correctness of operation.
  84136. */
  84137. case OP_Expire: {
  84138. assert( pOp->p2==0 || pOp->p2==1 );
  84139. if( !pOp->p1 ){
  84140. sqlite3ExpirePreparedStatements(db, pOp->p2);
  84141. }else{
  84142. p->expired = pOp->p2+1;
  84143. }
  84144. break;
  84145. }
  84146. #ifndef SQLITE_OMIT_SHARED_CACHE
  84147. /* Opcode: TableLock P1 P2 P3 P4 *
  84148. ** Synopsis: iDb=P1 root=P2 write=P3
  84149. **
  84150. ** Obtain a lock on a particular table. This instruction is only used when
  84151. ** the shared-cache feature is enabled.
  84152. **
  84153. ** P1 is the index of the database in sqlite3.aDb[] of the database
  84154. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  84155. ** a write lock if P3==1.
  84156. **
  84157. ** P2 contains the root-page of the table to lock.
  84158. **
  84159. ** P4 contains a pointer to the name of the table being locked. This is only
  84160. ** used to generate an error message if the lock cannot be obtained.
  84161. */
  84162. case OP_TableLock: {
  84163. u8 isWriteLock = (u8)pOp->p3;
  84164. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
  84165. int p1 = pOp->p1;
  84166. assert( p1>=0 && p1<db->nDb );
  84167. assert( DbMaskTest(p->btreeMask, p1) );
  84168. assert( isWriteLock==0 || isWriteLock==1 );
  84169. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  84170. if( rc ){
  84171. if( (rc&0xFF)==SQLITE_LOCKED ){
  84172. const char *z = pOp->p4.z;
  84173. sqlite3VdbeError(p, "database table is locked: %s", z);
  84174. }
  84175. goto abort_due_to_error;
  84176. }
  84177. }
  84178. break;
  84179. }
  84180. #endif /* SQLITE_OMIT_SHARED_CACHE */
  84181. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84182. /* Opcode: VBegin * * * P4 *
  84183. **
  84184. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  84185. ** xBegin method for that table.
  84186. **
  84187. ** Also, whether or not P4 is set, check that this is not being called from
  84188. ** within a callback to a virtual table xSync() method. If it is, the error
  84189. ** code will be set to SQLITE_LOCKED.
  84190. */
  84191. case OP_VBegin: {
  84192. VTable *pVTab;
  84193. pVTab = pOp->p4.pVtab;
  84194. rc = sqlite3VtabBegin(db, pVTab);
  84195. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  84196. if( rc ) goto abort_due_to_error;
  84197. break;
  84198. }
  84199. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84200. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84201. /* Opcode: VCreate P1 P2 * * *
  84202. **
  84203. ** P2 is a register that holds the name of a virtual table in database
  84204. ** P1. Call the xCreate method for that table.
  84205. */
  84206. case OP_VCreate: {
  84207. Mem sMem; /* For storing the record being decoded */
  84208. const char *zTab; /* Name of the virtual table */
  84209. memset(&sMem, 0, sizeof(sMem));
  84210. sMem.db = db;
  84211. /* Because P2 is always a static string, it is impossible for the
  84212. ** sqlite3VdbeMemCopy() to fail */
  84213. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  84214. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  84215. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  84216. assert( rc==SQLITE_OK );
  84217. zTab = (const char*)sqlite3_value_text(&sMem);
  84218. assert( zTab || db->mallocFailed );
  84219. if( zTab ){
  84220. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  84221. }
  84222. sqlite3VdbeMemRelease(&sMem);
  84223. if( rc ) goto abort_due_to_error;
  84224. break;
  84225. }
  84226. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84227. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84228. /* Opcode: VDestroy P1 * * P4 *
  84229. **
  84230. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  84231. ** of that table.
  84232. */
  84233. case OP_VDestroy: {
  84234. db->nVDestroy++;
  84235. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  84236. db->nVDestroy--;
  84237. if( rc ) goto abort_due_to_error;
  84238. break;
  84239. }
  84240. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84241. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84242. /* Opcode: VOpen P1 * * P4 *
  84243. **
  84244. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  84245. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  84246. ** table and stores that cursor in P1.
  84247. */
  84248. case OP_VOpen: {
  84249. VdbeCursor *pCur;
  84250. sqlite3_vtab_cursor *pVCur;
  84251. sqlite3_vtab *pVtab;
  84252. const sqlite3_module *pModule;
  84253. assert( p->bIsReader );
  84254. pCur = 0;
  84255. pVCur = 0;
  84256. pVtab = pOp->p4.pVtab->pVtab;
  84257. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  84258. rc = SQLITE_LOCKED;
  84259. goto abort_due_to_error;
  84260. }
  84261. pModule = pVtab->pModule;
  84262. rc = pModule->xOpen(pVtab, &pVCur);
  84263. sqlite3VtabImportErrmsg(p, pVtab);
  84264. if( rc ) goto abort_due_to_error;
  84265. /* Initialize sqlite3_vtab_cursor base class */
  84266. pVCur->pVtab = pVtab;
  84267. /* Initialize vdbe cursor object */
  84268. pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
  84269. if( pCur ){
  84270. pCur->uc.pVCur = pVCur;
  84271. pVtab->nRef++;
  84272. }else{
  84273. assert( db->mallocFailed );
  84274. pModule->xClose(pVCur);
  84275. goto no_mem;
  84276. }
  84277. break;
  84278. }
  84279. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84280. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84281. /* Opcode: VFilter P1 P2 P3 P4 *
  84282. ** Synopsis: iplan=r[P3] zplan='P4'
  84283. **
  84284. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  84285. ** the filtered result set is empty.
  84286. **
  84287. ** P4 is either NULL or a string that was generated by the xBestIndex
  84288. ** method of the module. The interpretation of the P4 string is left
  84289. ** to the module implementation.
  84290. **
  84291. ** This opcode invokes the xFilter method on the virtual table specified
  84292. ** by P1. The integer query plan parameter to xFilter is stored in register
  84293. ** P3. Register P3+1 stores the argc parameter to be passed to the
  84294. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  84295. ** additional parameters which are passed to
  84296. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  84297. **
  84298. ** A jump is made to P2 if the result set after filtering would be empty.
  84299. */
  84300. case OP_VFilter: { /* jump */
  84301. int nArg;
  84302. int iQuery;
  84303. const sqlite3_module *pModule;
  84304. Mem *pQuery;
  84305. Mem *pArgc;
  84306. sqlite3_vtab_cursor *pVCur;
  84307. sqlite3_vtab *pVtab;
  84308. VdbeCursor *pCur;
  84309. int res;
  84310. int i;
  84311. Mem **apArg;
  84312. pQuery = &aMem[pOp->p3];
  84313. pArgc = &pQuery[1];
  84314. pCur = p->apCsr[pOp->p1];
  84315. assert( memIsValid(pQuery) );
  84316. REGISTER_TRACE(pOp->p3, pQuery);
  84317. assert( pCur->eCurType==CURTYPE_VTAB );
  84318. pVCur = pCur->uc.pVCur;
  84319. pVtab = pVCur->pVtab;
  84320. pModule = pVtab->pModule;
  84321. /* Grab the index number and argc parameters */
  84322. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  84323. nArg = (int)pArgc->u.i;
  84324. iQuery = (int)pQuery->u.i;
  84325. /* Invoke the xFilter method */
  84326. res = 0;
  84327. apArg = p->apArg;
  84328. for(i = 0; i<nArg; i++){
  84329. apArg[i] = &pArgc[i+1];
  84330. }
  84331. rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
  84332. sqlite3VtabImportErrmsg(p, pVtab);
  84333. if( rc ) goto abort_due_to_error;
  84334. res = pModule->xEof(pVCur);
  84335. pCur->nullRow = 0;
  84336. VdbeBranchTaken(res!=0,2);
  84337. if( res ) goto jump_to_p2;
  84338. break;
  84339. }
  84340. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84341. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84342. /* Opcode: VColumn P1 P2 P3 * P5
  84343. ** Synopsis: r[P3]=vcolumn(P2)
  84344. **
  84345. ** Store in register P3 the value of the P2-th column of
  84346. ** the current row of the virtual-table of cursor P1.
  84347. **
  84348. ** If the VColumn opcode is being used to fetch the value of
  84349. ** an unchanging column during an UPDATE operation, then the P5
  84350. ** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange()
  84351. ** function to return true inside the xColumn method of the virtual
  84352. ** table implementation. The P5 column might also contain other
  84353. ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
  84354. ** unused by OP_VColumn.
  84355. */
  84356. case OP_VColumn: {
  84357. sqlite3_vtab *pVtab;
  84358. const sqlite3_module *pModule;
  84359. Mem *pDest;
  84360. sqlite3_context sContext;
  84361. VdbeCursor *pCur = p->apCsr[pOp->p1];
  84362. assert( pCur->eCurType==CURTYPE_VTAB );
  84363. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  84364. pDest = &aMem[pOp->p3];
  84365. memAboutToChange(p, pDest);
  84366. if( pCur->nullRow ){
  84367. sqlite3VdbeMemSetNull(pDest);
  84368. break;
  84369. }
  84370. pVtab = pCur->uc.pVCur->pVtab;
  84371. pModule = pVtab->pModule;
  84372. assert( pModule->xColumn );
  84373. memset(&sContext, 0, sizeof(sContext));
  84374. sContext.pOut = pDest;
  84375. testcase( (pOp->p5 & OPFLAG_NOCHNG)==0 && pOp->p5!=0 );
  84376. if( pOp->p5 & OPFLAG_NOCHNG ){
  84377. sqlite3VdbeMemSetNull(pDest);
  84378. pDest->flags = MEM_Null|MEM_Zero;
  84379. pDest->u.nZero = 0;
  84380. }else{
  84381. MemSetTypeFlag(pDest, MEM_Null);
  84382. }
  84383. rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
  84384. sqlite3VtabImportErrmsg(p, pVtab);
  84385. if( sContext.isError>0 ){
  84386. sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
  84387. rc = sContext.isError;
  84388. }
  84389. sqlite3VdbeChangeEncoding(pDest, encoding);
  84390. REGISTER_TRACE(pOp->p3, pDest);
  84391. UPDATE_MAX_BLOBSIZE(pDest);
  84392. if( sqlite3VdbeMemTooBig(pDest) ){
  84393. goto too_big;
  84394. }
  84395. if( rc ) goto abort_due_to_error;
  84396. break;
  84397. }
  84398. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84399. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84400. /* Opcode: VNext P1 P2 * * *
  84401. **
  84402. ** Advance virtual table P1 to the next row in its result set and
  84403. ** jump to instruction P2. Or, if the virtual table has reached
  84404. ** the end of its result set, then fall through to the next instruction.
  84405. */
  84406. case OP_VNext: { /* jump */
  84407. sqlite3_vtab *pVtab;
  84408. const sqlite3_module *pModule;
  84409. int res;
  84410. VdbeCursor *pCur;
  84411. res = 0;
  84412. pCur = p->apCsr[pOp->p1];
  84413. assert( pCur->eCurType==CURTYPE_VTAB );
  84414. if( pCur->nullRow ){
  84415. break;
  84416. }
  84417. pVtab = pCur->uc.pVCur->pVtab;
  84418. pModule = pVtab->pModule;
  84419. assert( pModule->xNext );
  84420. /* Invoke the xNext() method of the module. There is no way for the
  84421. ** underlying implementation to return an error if one occurs during
  84422. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  84423. ** data is available) and the error code returned when xColumn or
  84424. ** some other method is next invoked on the save virtual table cursor.
  84425. */
  84426. rc = pModule->xNext(pCur->uc.pVCur);
  84427. sqlite3VtabImportErrmsg(p, pVtab);
  84428. if( rc ) goto abort_due_to_error;
  84429. res = pModule->xEof(pCur->uc.pVCur);
  84430. VdbeBranchTaken(!res,2);
  84431. if( !res ){
  84432. /* If there is data, jump to P2 */
  84433. goto jump_to_p2_and_check_for_interrupt;
  84434. }
  84435. goto check_for_interrupt;
  84436. }
  84437. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84438. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84439. /* Opcode: VRename P1 * * P4 *
  84440. **
  84441. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  84442. ** This opcode invokes the corresponding xRename method. The value
  84443. ** in register P1 is passed as the zName argument to the xRename method.
  84444. */
  84445. case OP_VRename: {
  84446. sqlite3_vtab *pVtab;
  84447. Mem *pName;
  84448. int isLegacy;
  84449. isLegacy = (db->flags & SQLITE_LegacyAlter);
  84450. db->flags |= SQLITE_LegacyAlter;
  84451. pVtab = pOp->p4.pVtab->pVtab;
  84452. pName = &aMem[pOp->p1];
  84453. assert( pVtab->pModule->xRename );
  84454. assert( memIsValid(pName) );
  84455. assert( p->readOnly==0 );
  84456. REGISTER_TRACE(pOp->p1, pName);
  84457. assert( pName->flags & MEM_Str );
  84458. testcase( pName->enc==SQLITE_UTF8 );
  84459. testcase( pName->enc==SQLITE_UTF16BE );
  84460. testcase( pName->enc==SQLITE_UTF16LE );
  84461. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  84462. if( rc ) goto abort_due_to_error;
  84463. rc = pVtab->pModule->xRename(pVtab, pName->z);
  84464. if( isLegacy==0 ) db->flags &= ~SQLITE_LegacyAlter;
  84465. sqlite3VtabImportErrmsg(p, pVtab);
  84466. p->expired = 0;
  84467. if( rc ) goto abort_due_to_error;
  84468. break;
  84469. }
  84470. #endif
  84471. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84472. /* Opcode: VUpdate P1 P2 P3 P4 P5
  84473. ** Synopsis: data=r[P3@P2]
  84474. **
  84475. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  84476. ** This opcode invokes the corresponding xUpdate method. P2 values
  84477. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  84478. ** invocation. The value in register (P3+P2-1) corresponds to the
  84479. ** p2th element of the argv array passed to xUpdate.
  84480. **
  84481. ** The xUpdate method will do a DELETE or an INSERT or both.
  84482. ** The argv[0] element (which corresponds to memory cell P3)
  84483. ** is the rowid of a row to delete. If argv[0] is NULL then no
  84484. ** deletion occurs. The argv[1] element is the rowid of the new
  84485. ** row. This can be NULL to have the virtual table select the new
  84486. ** rowid for itself. The subsequent elements in the array are
  84487. ** the values of columns in the new row.
  84488. **
  84489. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  84490. ** a row to delete.
  84491. **
  84492. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  84493. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  84494. ** is set to the value of the rowid for the row just inserted.
  84495. **
  84496. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  84497. ** apply in the case of a constraint failure on an insert or update.
  84498. */
  84499. case OP_VUpdate: {
  84500. sqlite3_vtab *pVtab;
  84501. const sqlite3_module *pModule;
  84502. int nArg;
  84503. int i;
  84504. sqlite_int64 rowid;
  84505. Mem **apArg;
  84506. Mem *pX;
  84507. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  84508. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  84509. );
  84510. assert( p->readOnly==0 );
  84511. if( db->mallocFailed ) goto no_mem;
  84512. sqlite3VdbeIncrWriteCounter(p, 0);
  84513. pVtab = pOp->p4.pVtab->pVtab;
  84514. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  84515. rc = SQLITE_LOCKED;
  84516. goto abort_due_to_error;
  84517. }
  84518. pModule = pVtab->pModule;
  84519. nArg = pOp->p2;
  84520. assert( pOp->p4type==P4_VTAB );
  84521. if( ALWAYS(pModule->xUpdate) ){
  84522. u8 vtabOnConflict = db->vtabOnConflict;
  84523. apArg = p->apArg;
  84524. pX = &aMem[pOp->p3];
  84525. for(i=0; i<nArg; i++){
  84526. assert( memIsValid(pX) );
  84527. memAboutToChange(p, pX);
  84528. apArg[i] = pX;
  84529. pX++;
  84530. }
  84531. db->vtabOnConflict = pOp->p5;
  84532. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  84533. db->vtabOnConflict = vtabOnConflict;
  84534. sqlite3VtabImportErrmsg(p, pVtab);
  84535. if( rc==SQLITE_OK && pOp->p1 ){
  84536. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  84537. db->lastRowid = rowid;
  84538. }
  84539. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  84540. if( pOp->p5==OE_Ignore ){
  84541. rc = SQLITE_OK;
  84542. }else{
  84543. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  84544. }
  84545. }else{
  84546. p->nChange++;
  84547. }
  84548. if( rc ) goto abort_due_to_error;
  84549. }
  84550. break;
  84551. }
  84552. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84553. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  84554. /* Opcode: Pagecount P1 P2 * * *
  84555. **
  84556. ** Write the current number of pages in database P1 to memory cell P2.
  84557. */
  84558. case OP_Pagecount: { /* out2 */
  84559. pOut = out2Prerelease(p, pOp);
  84560. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  84561. break;
  84562. }
  84563. #endif
  84564. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  84565. /* Opcode: MaxPgcnt P1 P2 P3 * *
  84566. **
  84567. ** Try to set the maximum page count for database P1 to the value in P3.
  84568. ** Do not let the maximum page count fall below the current page count and
  84569. ** do not change the maximum page count value if P3==0.
  84570. **
  84571. ** Store the maximum page count after the change in register P2.
  84572. */
  84573. case OP_MaxPgcnt: { /* out2 */
  84574. unsigned int newMax;
  84575. Btree *pBt;
  84576. pOut = out2Prerelease(p, pOp);
  84577. pBt = db->aDb[pOp->p1].pBt;
  84578. newMax = 0;
  84579. if( pOp->p3 ){
  84580. newMax = sqlite3BtreeLastPage(pBt);
  84581. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  84582. }
  84583. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  84584. break;
  84585. }
  84586. #endif
  84587. /* Opcode: Function0 P1 P2 P3 P4 P5
  84588. ** Synopsis: r[P3]=func(r[P2@P5])
  84589. **
  84590. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  84591. ** defines the function) with P5 arguments taken from register P2 and
  84592. ** successors. The result of the function is stored in register P3.
  84593. ** Register P3 must not be one of the function inputs.
  84594. **
  84595. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  84596. ** function was determined to be constant at compile time. If the first
  84597. ** argument was constant then bit 0 of P1 is set. This is used to determine
  84598. ** whether meta data associated with a user function argument using the
  84599. ** sqlite3_set_auxdata() API may be safely retained until the next
  84600. ** invocation of this opcode.
  84601. **
  84602. ** See also: Function, AggStep, AggFinal
  84603. */
  84604. /* Opcode: Function P1 P2 P3 P4 P5
  84605. ** Synopsis: r[P3]=func(r[P2@P5])
  84606. **
  84607. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  84608. ** contains a pointer to the function to be run) with P5 arguments taken
  84609. ** from register P2 and successors. The result of the function is stored
  84610. ** in register P3. Register P3 must not be one of the function inputs.
  84611. **
  84612. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  84613. ** function was determined to be constant at compile time. If the first
  84614. ** argument was constant then bit 0 of P1 is set. This is used to determine
  84615. ** whether meta data associated with a user function argument using the
  84616. ** sqlite3_set_auxdata() API may be safely retained until the next
  84617. ** invocation of this opcode.
  84618. **
  84619. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  84620. ** to a FuncDef object. But on first evaluation, the P4 operand is
  84621. ** automatically converted into an sqlite3_context object and the operation
  84622. ** changed to this OP_Function opcode. In this way, the initialization of
  84623. ** the sqlite3_context object occurs only once, rather than once for each
  84624. ** evaluation of the function.
  84625. **
  84626. ** See also: Function0, AggStep, AggFinal
  84627. */
  84628. case OP_PureFunc0: /* group */
  84629. case OP_Function0: { /* group */
  84630. int n;
  84631. sqlite3_context *pCtx;
  84632. assert( pOp->p4type==P4_FUNCDEF );
  84633. n = pOp->p5;
  84634. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  84635. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  84636. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  84637. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  84638. if( pCtx==0 ) goto no_mem;
  84639. pCtx->pOut = 0;
  84640. pCtx->pFunc = pOp->p4.pFunc;
  84641. pCtx->iOp = (int)(pOp - aOp);
  84642. pCtx->pVdbe = p;
  84643. pCtx->isError = 0;
  84644. pCtx->argc = n;
  84645. pOp->p4type = P4_FUNCCTX;
  84646. pOp->p4.pCtx = pCtx;
  84647. assert( OP_PureFunc == OP_PureFunc0+2 );
  84648. assert( OP_Function == OP_Function0+2 );
  84649. pOp->opcode += 2;
  84650. /* Fall through into OP_Function */
  84651. }
  84652. case OP_PureFunc: /* group */
  84653. case OP_Function: { /* group */
  84654. int i;
  84655. sqlite3_context *pCtx;
  84656. assert( pOp->p4type==P4_FUNCCTX );
  84657. pCtx = pOp->p4.pCtx;
  84658. /* If this function is inside of a trigger, the register array in aMem[]
  84659. ** might change from one evaluation to the next. The next block of code
  84660. ** checks to see if the register array has changed, and if so it
  84661. ** reinitializes the relavant parts of the sqlite3_context object */
  84662. pOut = &aMem[pOp->p3];
  84663. if( pCtx->pOut != pOut ){
  84664. pCtx->pOut = pOut;
  84665. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  84666. }
  84667. memAboutToChange(p, pOut);
  84668. #ifdef SQLITE_DEBUG
  84669. for(i=0; i<pCtx->argc; i++){
  84670. assert( memIsValid(pCtx->argv[i]) );
  84671. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  84672. }
  84673. #endif
  84674. MemSetTypeFlag(pOut, MEM_Null);
  84675. assert( pCtx->isError==0 );
  84676. (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
  84677. /* If the function returned an error, throw an exception */
  84678. if( pCtx->isError ){
  84679. if( pCtx->isError>0 ){
  84680. sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
  84681. rc = pCtx->isError;
  84682. }
  84683. sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
  84684. pCtx->isError = 0;
  84685. if( rc ) goto abort_due_to_error;
  84686. }
  84687. /* Copy the result of the function into register P3 */
  84688. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  84689. sqlite3VdbeChangeEncoding(pOut, encoding);
  84690. if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
  84691. }
  84692. REGISTER_TRACE(pOp->p3, pOut);
  84693. UPDATE_MAX_BLOBSIZE(pOut);
  84694. break;
  84695. }
  84696. /* Opcode: Trace P1 P2 * P4 *
  84697. **
  84698. ** Write P4 on the statement trace output if statement tracing is
  84699. ** enabled.
  84700. **
  84701. ** Operand P1 must be 0x7fffffff and P2 must positive.
  84702. */
  84703. /* Opcode: Init P1 P2 P3 P4 *
  84704. ** Synopsis: Start at P2
  84705. **
  84706. ** Programs contain a single instance of this opcode as the very first
  84707. ** opcode.
  84708. **
  84709. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  84710. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  84711. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  84712. **
  84713. ** If P2 is not zero, jump to instruction P2.
  84714. **
  84715. ** Increment the value of P1 so that OP_Once opcodes will jump the
  84716. ** first time they are evaluated for this run.
  84717. **
  84718. ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
  84719. ** error is encountered.
  84720. */
  84721. case OP_Trace:
  84722. case OP_Init: { /* jump */
  84723. int i;
  84724. #ifndef SQLITE_OMIT_TRACE
  84725. char *zTrace;
  84726. #endif
  84727. /* If the P4 argument is not NULL, then it must be an SQL comment string.
  84728. ** The "--" string is broken up to prevent false-positives with srcck1.c.
  84729. **
  84730. ** This assert() provides evidence for:
  84731. ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
  84732. ** would have been returned by the legacy sqlite3_trace() interface by
  84733. ** using the X argument when X begins with "--" and invoking
  84734. ** sqlite3_expanded_sql(P) otherwise.
  84735. */
  84736. assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
  84737. /* OP_Init is always instruction 0 */
  84738. assert( pOp==p->aOp || pOp->opcode==OP_Trace );
  84739. #ifndef SQLITE_OMIT_TRACE
  84740. if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
  84741. && !p->doingRerun
  84742. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  84743. ){
  84744. #ifndef SQLITE_OMIT_DEPRECATED
  84745. if( db->mTrace & SQLITE_TRACE_LEGACY ){
  84746. void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
  84747. char *z = sqlite3VdbeExpandSql(p, zTrace);
  84748. x(db->pTraceArg, z);
  84749. sqlite3_free(z);
  84750. }else
  84751. #endif
  84752. if( db->nVdbeExec>1 ){
  84753. char *z = sqlite3MPrintf(db, "-- %s", zTrace);
  84754. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
  84755. sqlite3DbFree(db, z);
  84756. }else{
  84757. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
  84758. }
  84759. }
  84760. #ifdef SQLITE_USE_FCNTL_TRACE
  84761. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  84762. if( zTrace ){
  84763. int j;
  84764. for(j=0; j<db->nDb; j++){
  84765. if( DbMaskTest(p->btreeMask, j)==0 ) continue;
  84766. sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
  84767. }
  84768. }
  84769. #endif /* SQLITE_USE_FCNTL_TRACE */
  84770. #ifdef SQLITE_DEBUG
  84771. if( (db->flags & SQLITE_SqlTrace)!=0
  84772. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  84773. ){
  84774. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  84775. }
  84776. #endif /* SQLITE_DEBUG */
  84777. #endif /* SQLITE_OMIT_TRACE */
  84778. assert( pOp->p2>0 );
  84779. if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
  84780. if( pOp->opcode==OP_Trace ) break;
  84781. for(i=1; i<p->nOp; i++){
  84782. if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
  84783. }
  84784. pOp->p1 = 0;
  84785. }
  84786. pOp->p1++;
  84787. p->aCounter[SQLITE_STMTSTATUS_RUN]++;
  84788. goto jump_to_p2;
  84789. }
  84790. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  84791. /* Opcode: CursorHint P1 * * P4 *
  84792. **
  84793. ** Provide a hint to cursor P1 that it only needs to return rows that
  84794. ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
  84795. ** to values currently held in registers. TK_COLUMN terms in the P4
  84796. ** expression refer to columns in the b-tree to which cursor P1 is pointing.
  84797. */
  84798. case OP_CursorHint: {
  84799. VdbeCursor *pC;
  84800. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84801. assert( pOp->p4type==P4_EXPR );
  84802. pC = p->apCsr[pOp->p1];
  84803. if( pC ){
  84804. assert( pC->eCurType==CURTYPE_BTREE );
  84805. sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
  84806. pOp->p4.pExpr, aMem);
  84807. }
  84808. break;
  84809. }
  84810. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  84811. #ifdef SQLITE_DEBUG
  84812. /* Opcode: Abortable * * * * *
  84813. **
  84814. ** Verify that an Abort can happen. Assert if an Abort at this point
  84815. ** might cause database corruption. This opcode only appears in debugging
  84816. ** builds.
  84817. **
  84818. ** An Abort is safe if either there have been no writes, or if there is
  84819. ** an active statement journal.
  84820. */
  84821. case OP_Abortable: {
  84822. sqlite3VdbeAssertAbortable(p);
  84823. break;
  84824. }
  84825. #endif
  84826. /* Opcode: Noop * * * * *
  84827. **
  84828. ** Do nothing. This instruction is often useful as a jump
  84829. ** destination.
  84830. */
  84831. /*
  84832. ** The magic Explain opcode are only inserted when explain==2 (which
  84833. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  84834. ** This opcode records information from the optimizer. It is the
  84835. ** the same as a no-op. This opcodesnever appears in a real VM program.
  84836. */
  84837. default: { /* This is really OP_Noop, OP_Explain */
  84838. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  84839. break;
  84840. }
  84841. /*****************************************************************************
  84842. ** The cases of the switch statement above this line should all be indented
  84843. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  84844. ** readability. From this point on down, the normal indentation rules are
  84845. ** restored.
  84846. *****************************************************************************/
  84847. }
  84848. #ifdef VDBE_PROFILE
  84849. {
  84850. u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  84851. if( endTime>start ) pOrigOp->cycles += endTime - start;
  84852. pOrigOp->cnt++;
  84853. }
  84854. #endif
  84855. /* The following code adds nothing to the actual functionality
  84856. ** of the program. It is only here for testing and debugging.
  84857. ** On the other hand, it does burn CPU cycles every time through
  84858. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  84859. */
  84860. #ifndef NDEBUG
  84861. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  84862. #ifdef SQLITE_DEBUG
  84863. if( db->flags & SQLITE_VdbeTrace ){
  84864. u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
  84865. if( rc!=0 ) printf("rc=%d\n",rc);
  84866. if( opProperty & (OPFLG_OUT2) ){
  84867. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  84868. }
  84869. if( opProperty & OPFLG_OUT3 ){
  84870. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  84871. }
  84872. }
  84873. #endif /* SQLITE_DEBUG */
  84874. #endif /* NDEBUG */
  84875. } /* The end of the for(;;) loop the loops through opcodes */
  84876. /* If we reach this point, it means that execution is finished with
  84877. ** an error of some kind.
  84878. */
  84879. abort_due_to_error:
  84880. if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
  84881. assert( rc );
  84882. if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
  84883. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  84884. }
  84885. p->rc = rc;
  84886. sqlite3SystemError(db, rc);
  84887. testcase( sqlite3GlobalConfig.xLog!=0 );
  84888. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  84889. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  84890. sqlite3VdbeHalt(p);
  84891. if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
  84892. rc = SQLITE_ERROR;
  84893. if( resetSchemaOnFault>0 ){
  84894. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  84895. }
  84896. /* This is the only way out of this procedure. We have to
  84897. ** release the mutexes on btrees that were acquired at the
  84898. ** top. */
  84899. vdbe_return:
  84900. testcase( nVmStep>0 );
  84901. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  84902. sqlite3VdbeLeave(p);
  84903. assert( rc!=SQLITE_OK || nExtraDelete==0
  84904. || sqlite3_strlike("DELETE%",p->zSql,0)!=0
  84905. );
  84906. return rc;
  84907. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  84908. ** is encountered.
  84909. */
  84910. too_big:
  84911. sqlite3VdbeError(p, "string or blob too big");
  84912. rc = SQLITE_TOOBIG;
  84913. goto abort_due_to_error;
  84914. /* Jump to here if a malloc() fails.
  84915. */
  84916. no_mem:
  84917. sqlite3OomFault(db);
  84918. sqlite3VdbeError(p, "out of memory");
  84919. rc = SQLITE_NOMEM_BKPT;
  84920. goto abort_due_to_error;
  84921. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  84922. ** flag.
  84923. */
  84924. abort_due_to_interrupt:
  84925. assert( db->u1.isInterrupted );
  84926. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  84927. p->rc = rc;
  84928. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  84929. goto abort_due_to_error;
  84930. }
  84931. /************** End of vdbe.c ************************************************/
  84932. /************** Begin file vdbeblob.c ****************************************/
  84933. /*
  84934. ** 2007 May 1
  84935. **
  84936. ** The author disclaims copyright to this source code. In place of
  84937. ** a legal notice, here is a blessing:
  84938. **
  84939. ** May you do good and not evil.
  84940. ** May you find forgiveness for yourself and forgive others.
  84941. ** May you share freely, never taking more than you give.
  84942. **
  84943. *************************************************************************
  84944. **
  84945. ** This file contains code used to implement incremental BLOB I/O.
  84946. */
  84947. /* #include "sqliteInt.h" */
  84948. /* #include "vdbeInt.h" */
  84949. #ifndef SQLITE_OMIT_INCRBLOB
  84950. /*
  84951. ** Valid sqlite3_blob* handles point to Incrblob structures.
  84952. */
  84953. typedef struct Incrblob Incrblob;
  84954. struct Incrblob {
  84955. int nByte; /* Size of open blob, in bytes */
  84956. int iOffset; /* Byte offset of blob in cursor data */
  84957. u16 iCol; /* Table column this handle is open on */
  84958. BtCursor *pCsr; /* Cursor pointing at blob row */
  84959. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  84960. sqlite3 *db; /* The associated database */
  84961. char *zDb; /* Database name */
  84962. Table *pTab; /* Table object */
  84963. };
  84964. /*
  84965. ** This function is used by both blob_open() and blob_reopen(). It seeks
  84966. ** the b-tree cursor associated with blob handle p to point to row iRow.
  84967. ** If successful, SQLITE_OK is returned and subsequent calls to
  84968. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  84969. **
  84970. ** If an error occurs, or if the specified row does not exist or does not
  84971. ** contain a value of type TEXT or BLOB in the column nominated when the
  84972. ** blob handle was opened, then an error code is returned and *pzErr may
  84973. ** be set to point to a buffer containing an error message. It is the
  84974. ** responsibility of the caller to free the error message buffer using
  84975. ** sqlite3DbFree().
  84976. **
  84977. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  84978. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  84979. ** immediately return SQLITE_ABORT.
  84980. */
  84981. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  84982. int rc; /* Error code */
  84983. char *zErr = 0; /* Error message */
  84984. Vdbe *v = (Vdbe *)p->pStmt;
  84985. /* Set the value of register r[1] in the SQL statement to integer iRow.
  84986. ** This is done directly as a performance optimization
  84987. */
  84988. v->aMem[1].flags = MEM_Int;
  84989. v->aMem[1].u.i = iRow;
  84990. /* If the statement has been run before (and is paused at the OP_ResultRow)
  84991. ** then back it up to the point where it does the OP_NotExists. This could
  84992. ** have been down with an extra OP_Goto, but simply setting the program
  84993. ** counter is faster. */
  84994. if( v->pc>4 ){
  84995. v->pc = 4;
  84996. assert( v->aOp[v->pc].opcode==OP_NotExists );
  84997. rc = sqlite3VdbeExec(v);
  84998. }else{
  84999. rc = sqlite3_step(p->pStmt);
  85000. }
  85001. if( rc==SQLITE_ROW ){
  85002. VdbeCursor *pC = v->apCsr[0];
  85003. u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
  85004. testcase( pC->nHdrParsed==p->iCol );
  85005. testcase( pC->nHdrParsed==p->iCol+1 );
  85006. if( type<12 ){
  85007. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  85008. type==0?"null": type==7?"real": "integer"
  85009. );
  85010. rc = SQLITE_ERROR;
  85011. sqlite3_finalize(p->pStmt);
  85012. p->pStmt = 0;
  85013. }else{
  85014. p->iOffset = pC->aType[p->iCol + pC->nField];
  85015. p->nByte = sqlite3VdbeSerialTypeLen(type);
  85016. p->pCsr = pC->uc.pCursor;
  85017. sqlite3BtreeIncrblobCursor(p->pCsr);
  85018. }
  85019. }
  85020. if( rc==SQLITE_ROW ){
  85021. rc = SQLITE_OK;
  85022. }else if( p->pStmt ){
  85023. rc = sqlite3_finalize(p->pStmt);
  85024. p->pStmt = 0;
  85025. if( rc==SQLITE_OK ){
  85026. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  85027. rc = SQLITE_ERROR;
  85028. }else{
  85029. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  85030. }
  85031. }
  85032. assert( rc!=SQLITE_OK || zErr==0 );
  85033. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  85034. *pzErr = zErr;
  85035. return rc;
  85036. }
  85037. /*
  85038. ** Open a blob handle.
  85039. */
  85040. SQLITE_API int sqlite3_blob_open(
  85041. sqlite3* db, /* The database connection */
  85042. const char *zDb, /* The attached database containing the blob */
  85043. const char *zTable, /* The table containing the blob */
  85044. const char *zColumn, /* The column containing the blob */
  85045. sqlite_int64 iRow, /* The row containing the glob */
  85046. int wrFlag, /* True -> read/write access, false -> read-only */
  85047. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  85048. ){
  85049. int nAttempt = 0;
  85050. int iCol; /* Index of zColumn in row-record */
  85051. int rc = SQLITE_OK;
  85052. char *zErr = 0;
  85053. Table *pTab;
  85054. Incrblob *pBlob = 0;
  85055. Parse sParse;
  85056. #ifdef SQLITE_ENABLE_API_ARMOR
  85057. if( ppBlob==0 ){
  85058. return SQLITE_MISUSE_BKPT;
  85059. }
  85060. #endif
  85061. *ppBlob = 0;
  85062. #ifdef SQLITE_ENABLE_API_ARMOR
  85063. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  85064. return SQLITE_MISUSE_BKPT;
  85065. }
  85066. #endif
  85067. wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
  85068. sqlite3_mutex_enter(db->mutex);
  85069. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  85070. do {
  85071. memset(&sParse, 0, sizeof(Parse));
  85072. if( !pBlob ) goto blob_open_out;
  85073. sParse.db = db;
  85074. sqlite3DbFree(db, zErr);
  85075. zErr = 0;
  85076. sqlite3BtreeEnterAll(db);
  85077. pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
  85078. if( pTab && IsVirtual(pTab) ){
  85079. pTab = 0;
  85080. sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
  85081. }
  85082. if( pTab && !HasRowid(pTab) ){
  85083. pTab = 0;
  85084. sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
  85085. }
  85086. #ifndef SQLITE_OMIT_VIEW
  85087. if( pTab && pTab->pSelect ){
  85088. pTab = 0;
  85089. sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
  85090. }
  85091. #endif
  85092. if( !pTab ){
  85093. if( sParse.zErrMsg ){
  85094. sqlite3DbFree(db, zErr);
  85095. zErr = sParse.zErrMsg;
  85096. sParse.zErrMsg = 0;
  85097. }
  85098. rc = SQLITE_ERROR;
  85099. sqlite3BtreeLeaveAll(db);
  85100. goto blob_open_out;
  85101. }
  85102. pBlob->pTab = pTab;
  85103. pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
  85104. /* Now search pTab for the exact column. */
  85105. for(iCol=0; iCol<pTab->nCol; iCol++) {
  85106. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  85107. break;
  85108. }
  85109. }
  85110. if( iCol==pTab->nCol ){
  85111. sqlite3DbFree(db, zErr);
  85112. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  85113. rc = SQLITE_ERROR;
  85114. sqlite3BtreeLeaveAll(db);
  85115. goto blob_open_out;
  85116. }
  85117. /* If the value is being opened for writing, check that the
  85118. ** column is not indexed, and that it is not part of a foreign key.
  85119. */
  85120. if( wrFlag ){
  85121. const char *zFault = 0;
  85122. Index *pIdx;
  85123. #ifndef SQLITE_OMIT_FOREIGN_KEY
  85124. if( db->flags&SQLITE_ForeignKeys ){
  85125. /* Check that the column is not part of an FK child key definition. It
  85126. ** is not necessary to check if it is part of a parent key, as parent
  85127. ** key columns must be indexed. The check below will pick up this
  85128. ** case. */
  85129. FKey *pFKey;
  85130. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  85131. int j;
  85132. for(j=0; j<pFKey->nCol; j++){
  85133. if( pFKey->aCol[j].iFrom==iCol ){
  85134. zFault = "foreign key";
  85135. }
  85136. }
  85137. }
  85138. }
  85139. #endif
  85140. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  85141. int j;
  85142. for(j=0; j<pIdx->nKeyCol; j++){
  85143. /* FIXME: Be smarter about indexes that use expressions */
  85144. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  85145. zFault = "indexed";
  85146. }
  85147. }
  85148. }
  85149. if( zFault ){
  85150. sqlite3DbFree(db, zErr);
  85151. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  85152. rc = SQLITE_ERROR;
  85153. sqlite3BtreeLeaveAll(db);
  85154. goto blob_open_out;
  85155. }
  85156. }
  85157. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
  85158. assert( pBlob->pStmt || db->mallocFailed );
  85159. if( pBlob->pStmt ){
  85160. /* This VDBE program seeks a btree cursor to the identified
  85161. ** db/table/row entry. The reason for using a vdbe program instead
  85162. ** of writing code to use the b-tree layer directly is that the
  85163. ** vdbe program will take advantage of the various transaction,
  85164. ** locking and error handling infrastructure built into the vdbe.
  85165. **
  85166. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  85167. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  85168. ** uses it to implement the blob_read(), blob_write() and
  85169. ** blob_bytes() functions.
  85170. **
  85171. ** The sqlite3_blob_close() function finalizes the vdbe program,
  85172. ** which closes the b-tree cursor and (possibly) commits the
  85173. ** transaction.
  85174. */
  85175. static const int iLn = VDBE_OFFSET_LINENO(2);
  85176. static const VdbeOpList openBlob[] = {
  85177. {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
  85178. {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
  85179. /* blobSeekToRow() will initialize r[1] to the desired rowid */
  85180. {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
  85181. {OP_Column, 0, 0, 1}, /* 3 */
  85182. {OP_ResultRow, 1, 0, 0}, /* 4 */
  85183. {OP_Halt, 0, 0, 0}, /* 5 */
  85184. };
  85185. Vdbe *v = (Vdbe *)pBlob->pStmt;
  85186. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85187. VdbeOp *aOp;
  85188. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
  85189. pTab->pSchema->schema_cookie,
  85190. pTab->pSchema->iGeneration);
  85191. sqlite3VdbeChangeP5(v, 1);
  85192. assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
  85193. aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  85194. /* Make sure a mutex is held on the table to be accessed */
  85195. sqlite3VdbeUsesBtree(v, iDb);
  85196. if( db->mallocFailed==0 ){
  85197. assert( aOp!=0 );
  85198. /* Configure the OP_TableLock instruction */
  85199. #ifdef SQLITE_OMIT_SHARED_CACHE
  85200. aOp[0].opcode = OP_Noop;
  85201. #else
  85202. aOp[0].p1 = iDb;
  85203. aOp[0].p2 = pTab->tnum;
  85204. aOp[0].p3 = wrFlag;
  85205. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  85206. }
  85207. if( db->mallocFailed==0 ){
  85208. #endif
  85209. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  85210. ** parameter of the other to pTab->tnum. */
  85211. if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
  85212. aOp[1].p2 = pTab->tnum;
  85213. aOp[1].p3 = iDb;
  85214. /* Configure the number of columns. Configure the cursor to
  85215. ** think that the table has one more column than it really
  85216. ** does. An OP_Column to retrieve this imaginary column will
  85217. ** always return an SQL NULL. This is useful because it means
  85218. ** we can invoke OP_Column to fill in the vdbe cursors type
  85219. ** and offset cache without causing any IO.
  85220. */
  85221. aOp[1].p4type = P4_INT32;
  85222. aOp[1].p4.i = pTab->nCol+1;
  85223. aOp[3].p2 = pTab->nCol;
  85224. sParse.nVar = 0;
  85225. sParse.nMem = 1;
  85226. sParse.nTab = 1;
  85227. sqlite3VdbeMakeReady(v, &sParse);
  85228. }
  85229. }
  85230. pBlob->iCol = iCol;
  85231. pBlob->db = db;
  85232. sqlite3BtreeLeaveAll(db);
  85233. if( db->mallocFailed ){
  85234. goto blob_open_out;
  85235. }
  85236. rc = blobSeekToRow(pBlob, iRow, &zErr);
  85237. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  85238. blob_open_out:
  85239. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  85240. *ppBlob = (sqlite3_blob *)pBlob;
  85241. }else{
  85242. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  85243. sqlite3DbFree(db, pBlob);
  85244. }
  85245. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  85246. sqlite3DbFree(db, zErr);
  85247. sqlite3ParserReset(&sParse);
  85248. rc = sqlite3ApiExit(db, rc);
  85249. sqlite3_mutex_leave(db->mutex);
  85250. return rc;
  85251. }
  85252. /*
  85253. ** Close a blob handle that was previously created using
  85254. ** sqlite3_blob_open().
  85255. */
  85256. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  85257. Incrblob *p = (Incrblob *)pBlob;
  85258. int rc;
  85259. sqlite3 *db;
  85260. if( p ){
  85261. db = p->db;
  85262. sqlite3_mutex_enter(db->mutex);
  85263. rc = sqlite3_finalize(p->pStmt);
  85264. sqlite3DbFree(db, p);
  85265. sqlite3_mutex_leave(db->mutex);
  85266. }else{
  85267. rc = SQLITE_OK;
  85268. }
  85269. return rc;
  85270. }
  85271. /*
  85272. ** Perform a read or write operation on a blob
  85273. */
  85274. static int blobReadWrite(
  85275. sqlite3_blob *pBlob,
  85276. void *z,
  85277. int n,
  85278. int iOffset,
  85279. int (*xCall)(BtCursor*, u32, u32, void*)
  85280. ){
  85281. int rc;
  85282. Incrblob *p = (Incrblob *)pBlob;
  85283. Vdbe *v;
  85284. sqlite3 *db;
  85285. if( p==0 ) return SQLITE_MISUSE_BKPT;
  85286. db = p->db;
  85287. sqlite3_mutex_enter(db->mutex);
  85288. v = (Vdbe*)p->pStmt;
  85289. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  85290. /* Request is out of range. Return a transient error. */
  85291. rc = SQLITE_ERROR;
  85292. }else if( v==0 ){
  85293. /* If there is no statement handle, then the blob-handle has
  85294. ** already been invalidated. Return SQLITE_ABORT in this case.
  85295. */
  85296. rc = SQLITE_ABORT;
  85297. }else{
  85298. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  85299. ** returned, clean-up the statement handle.
  85300. */
  85301. assert( db == v->db );
  85302. sqlite3BtreeEnterCursor(p->pCsr);
  85303. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  85304. if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
  85305. /* If a pre-update hook is registered and this is a write cursor,
  85306. ** invoke it here.
  85307. **
  85308. ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
  85309. ** operation should really be an SQLITE_UPDATE. This is probably
  85310. ** incorrect, but is convenient because at this point the new.* values
  85311. ** are not easily obtainable. And for the sessions module, an
  85312. ** SQLITE_UPDATE where the PK columns do not change is handled in the
  85313. ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
  85314. ** slightly more efficient). Since you cannot write to a PK column
  85315. ** using the incremental-blob API, this works. For the sessions module
  85316. ** anyhow.
  85317. */
  85318. sqlite3_int64 iKey;
  85319. iKey = sqlite3BtreeIntegerKey(p->pCsr);
  85320. sqlite3VdbePreUpdateHook(
  85321. v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
  85322. );
  85323. }
  85324. #endif
  85325. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  85326. sqlite3BtreeLeaveCursor(p->pCsr);
  85327. if( rc==SQLITE_ABORT ){
  85328. sqlite3VdbeFinalize(v);
  85329. p->pStmt = 0;
  85330. }else{
  85331. v->rc = rc;
  85332. }
  85333. }
  85334. sqlite3Error(db, rc);
  85335. rc = sqlite3ApiExit(db, rc);
  85336. sqlite3_mutex_leave(db->mutex);
  85337. return rc;
  85338. }
  85339. /*
  85340. ** Read data from a blob handle.
  85341. */
  85342. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  85343. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
  85344. }
  85345. /*
  85346. ** Write data to a blob handle.
  85347. */
  85348. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  85349. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  85350. }
  85351. /*
  85352. ** Query a blob handle for the size of the data.
  85353. **
  85354. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  85355. ** so no mutex is required for access.
  85356. */
  85357. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  85358. Incrblob *p = (Incrblob *)pBlob;
  85359. return (p && p->pStmt) ? p->nByte : 0;
  85360. }
  85361. /*
  85362. ** Move an existing blob handle to point to a different row of the same
  85363. ** database table.
  85364. **
  85365. ** If an error occurs, or if the specified row does not exist or does not
  85366. ** contain a blob or text value, then an error code is returned and the
  85367. ** database handle error code and message set. If this happens, then all
  85368. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  85369. ** immediately return SQLITE_ABORT.
  85370. */
  85371. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  85372. int rc;
  85373. Incrblob *p = (Incrblob *)pBlob;
  85374. sqlite3 *db;
  85375. if( p==0 ) return SQLITE_MISUSE_BKPT;
  85376. db = p->db;
  85377. sqlite3_mutex_enter(db->mutex);
  85378. if( p->pStmt==0 ){
  85379. /* If there is no statement handle, then the blob-handle has
  85380. ** already been invalidated. Return SQLITE_ABORT in this case.
  85381. */
  85382. rc = SQLITE_ABORT;
  85383. }else{
  85384. char *zErr;
  85385. rc = blobSeekToRow(p, iRow, &zErr);
  85386. if( rc!=SQLITE_OK ){
  85387. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  85388. sqlite3DbFree(db, zErr);
  85389. }
  85390. assert( rc!=SQLITE_SCHEMA );
  85391. }
  85392. rc = sqlite3ApiExit(db, rc);
  85393. assert( rc==SQLITE_OK || p->pStmt==0 );
  85394. sqlite3_mutex_leave(db->mutex);
  85395. return rc;
  85396. }
  85397. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  85398. /************** End of vdbeblob.c ********************************************/
  85399. /************** Begin file vdbesort.c ****************************************/
  85400. /*
  85401. ** 2011-07-09
  85402. **
  85403. ** The author disclaims copyright to this source code. In place of
  85404. ** a legal notice, here is a blessing:
  85405. **
  85406. ** May you do good and not evil.
  85407. ** May you find forgiveness for yourself and forgive others.
  85408. ** May you share freely, never taking more than you give.
  85409. **
  85410. *************************************************************************
  85411. ** This file contains code for the VdbeSorter object, used in concert with
  85412. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  85413. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  85414. ** using indexes and without LIMIT clauses.
  85415. **
  85416. ** The VdbeSorter object implements a multi-threaded external merge sort
  85417. ** algorithm that is efficient even if the number of elements being sorted
  85418. ** exceeds the available memory.
  85419. **
  85420. ** Here is the (internal, non-API) interface between this module and the
  85421. ** rest of the SQLite system:
  85422. **
  85423. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  85424. **
  85425. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  85426. ** object. The row is a binary blob in the
  85427. ** OP_MakeRecord format that contains both
  85428. ** the ORDER BY key columns and result columns
  85429. ** in the case of a SELECT w/ ORDER BY, or
  85430. ** the complete record for an index entry
  85431. ** in the case of a CREATE INDEX.
  85432. **
  85433. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  85434. ** Position the read cursor on the
  85435. ** first sorted element.
  85436. **
  85437. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  85438. ** element.
  85439. **
  85440. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  85441. ** row currently under the read cursor.
  85442. **
  85443. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  85444. ** currently under the read cursor against
  85445. ** another binary blob X and report if
  85446. ** X is strictly less than the read cursor.
  85447. ** Used to enforce uniqueness in a
  85448. ** CREATE UNIQUE INDEX statement.
  85449. **
  85450. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  85451. ** all resources.
  85452. **
  85453. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  85454. ** is like Close() followed by Init() only
  85455. ** much faster.
  85456. **
  85457. ** The interfaces above must be called in a particular order. Write() can
  85458. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  85459. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  85460. **
  85461. ** Init()
  85462. ** for each record: Write()
  85463. ** Rewind()
  85464. ** Rowkey()/Compare()
  85465. ** Next()
  85466. ** Close()
  85467. **
  85468. ** Algorithm:
  85469. **
  85470. ** Records passed to the sorter via calls to Write() are initially held
  85471. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  85472. ** a threshold, when Rewind() is called the set of records is sorted using
  85473. ** an in-memory merge sort. In this case, no temporary files are required
  85474. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  85475. ** directly from main memory.
  85476. **
  85477. ** If the amount of space used to store records in main memory exceeds the
  85478. ** threshold, then the set of records currently in memory are sorted and
  85479. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  85480. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  85481. ** of PMAs may be created by merging existing PMAs together - for example
  85482. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  85483. **
  85484. ** The threshold for the amount of main memory to use before flushing
  85485. ** records to a PMA is roughly the same as the limit configured for the
  85486. ** page-cache of the main database. Specifically, the threshold is set to
  85487. ** the value returned by "PRAGMA main.page_size" multipled by
  85488. ** that returned by "PRAGMA main.cache_size", in bytes.
  85489. **
  85490. ** If the sorter is running in single-threaded mode, then all PMAs generated
  85491. ** are appended to a single temporary file. Or, if the sorter is running in
  85492. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  85493. ** N is the configured number of worker threads. In this case, instead of
  85494. ** sorting the records and writing the PMA to a temporary file itself, the
  85495. ** calling thread usually launches a worker thread to do so. Except, if
  85496. ** there are already N worker threads running, the main thread does the work
  85497. ** itself.
  85498. **
  85499. ** The sorter is running in multi-threaded mode if (a) the library was built
  85500. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  85501. ** than zero, and (b) worker threads have been enabled at runtime by calling
  85502. ** "PRAGMA threads=N" with some value of N greater than 0.
  85503. **
  85504. ** When Rewind() is called, any data remaining in memory is flushed to a
  85505. ** final PMA. So at this point the data is stored in some number of sorted
  85506. ** PMAs within temporary files on disk.
  85507. **
  85508. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  85509. ** sorter is running in single-threaded mode, then these PMAs are merged
  85510. ** incrementally as keys are retreived from the sorter by the VDBE. The
  85511. ** MergeEngine object, described in further detail below, performs this
  85512. ** merge.
  85513. **
  85514. ** Or, if running in multi-threaded mode, then a background thread is
  85515. ** launched to merge the existing PMAs. Once the background thread has
  85516. ** merged T bytes of data into a single sorted PMA, the main thread
  85517. ** begins reading keys from that PMA while the background thread proceeds
  85518. ** with merging the next T bytes of data. And so on.
  85519. **
  85520. ** Parameter T is set to half the value of the memory threshold used
  85521. ** by Write() above to determine when to create a new PMA.
  85522. **
  85523. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  85524. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  85525. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  85526. ** disk are merged together. Then T bytes of data from the second set, and
  85527. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  85528. ** PMAs at a time. This done is to improve locality.
  85529. **
  85530. ** If running in multi-threaded mode and there are more than
  85531. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  85532. ** than one background thread may be created. Specifically, there may be
  85533. ** one background thread for each temporary file on disk, and one background
  85534. ** thread to merge the output of each of the others to a single PMA for
  85535. ** the main thread to read from.
  85536. */
  85537. /* #include "sqliteInt.h" */
  85538. /* #include "vdbeInt.h" */
  85539. /*
  85540. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  85541. ** messages to stderr that may be helpful in understanding the performance
  85542. ** characteristics of the sorter in multi-threaded mode.
  85543. */
  85544. #if 0
  85545. # define SQLITE_DEBUG_SORTER_THREADS 1
  85546. #endif
  85547. /*
  85548. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  85549. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  85550. ** overflows. 512MiB.
  85551. */
  85552. #define SQLITE_MAX_PMASZ (1<<29)
  85553. /*
  85554. ** Private objects used by the sorter
  85555. */
  85556. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  85557. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  85558. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  85559. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  85560. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  85561. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  85562. typedef struct SorterList SorterList; /* In-memory list of records */
  85563. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  85564. /*
  85565. ** A container for a temp file handle and the current amount of data
  85566. ** stored in the file.
  85567. */
  85568. struct SorterFile {
  85569. sqlite3_file *pFd; /* File handle */
  85570. i64 iEof; /* Bytes of data stored in pFd */
  85571. };
  85572. /*
  85573. ** An in-memory list of objects to be sorted.
  85574. **
  85575. ** If aMemory==0 then each object is allocated separately and the objects
  85576. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  85577. ** are stored in the aMemory[] bulk memory, one right after the other, and
  85578. ** are connected using SorterRecord.u.iNext.
  85579. */
  85580. struct SorterList {
  85581. SorterRecord *pList; /* Linked list of records */
  85582. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  85583. int szPMA; /* Size of pList as PMA in bytes */
  85584. };
  85585. /*
  85586. ** The MergeEngine object is used to combine two or more smaller PMAs into
  85587. ** one big PMA using a merge operation. Separate PMAs all need to be
  85588. ** combined into one big PMA in order to be able to step through the sorted
  85589. ** records in order.
  85590. **
  85591. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  85592. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  85593. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  85594. ** For the purposes of the paragraphs below, we assume that the array is
  85595. ** actually N elements in size, where N is the smallest power of 2 greater
  85596. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  85597. ** are treated as if they are empty (always at EOF).
  85598. **
  85599. ** The aTree[] array is also N elements in size. The value of N is stored in
  85600. ** the MergeEngine.nTree variable.
  85601. **
  85602. ** The final (N/2) elements of aTree[] contain the results of comparing
  85603. ** pairs of PMA keys together. Element i contains the result of
  85604. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  85605. ** aTree element is set to the index of it.
  85606. **
  85607. ** For the purposes of this comparison, EOF is considered greater than any
  85608. ** other key value. If the keys are equal (only possible with two EOF
  85609. ** values), it doesn't matter which index is stored.
  85610. **
  85611. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  85612. ** above contains the index of the smallest of each block of 4 PmaReaders
  85613. ** And so on. So that aTree[1] contains the index of the PmaReader that
  85614. ** currently points to the smallest key value. aTree[0] is unused.
  85615. **
  85616. ** Example:
  85617. **
  85618. ** aReadr[0] -> Banana
  85619. ** aReadr[1] -> Feijoa
  85620. ** aReadr[2] -> Elderberry
  85621. ** aReadr[3] -> Currant
  85622. ** aReadr[4] -> Grapefruit
  85623. ** aReadr[5] -> Apple
  85624. ** aReadr[6] -> Durian
  85625. ** aReadr[7] -> EOF
  85626. **
  85627. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  85628. **
  85629. ** The current element is "Apple" (the value of the key indicated by
  85630. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  85631. ** be advanced to the next key in its segment. Say the next key is
  85632. ** "Eggplant":
  85633. **
  85634. ** aReadr[5] -> Eggplant
  85635. **
  85636. ** The contents of aTree[] are updated first by comparing the new PmaReader
  85637. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  85638. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  85639. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  85640. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  85641. ** so the value written into element 1 of the array is 0. As follows:
  85642. **
  85643. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  85644. **
  85645. ** In other words, each time we advance to the next sorter element, log2(N)
  85646. ** key comparison operations are required, where N is the number of segments
  85647. ** being merged (rounded up to the next power of 2).
  85648. */
  85649. struct MergeEngine {
  85650. int nTree; /* Used size of aTree/aReadr (power of 2) */
  85651. SortSubtask *pTask; /* Used by this thread only */
  85652. int *aTree; /* Current state of incremental merge */
  85653. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  85654. };
  85655. /*
  85656. ** This object represents a single thread of control in a sort operation.
  85657. ** Exactly VdbeSorter.nTask instances of this object are allocated
  85658. ** as part of each VdbeSorter object. Instances are never allocated any
  85659. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  85660. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  85661. ** single-threaded operation, there is exactly one instance of this object
  85662. ** and for multi-threaded operation there are two or more instances.
  85663. **
  85664. ** Essentially, this structure contains all those fields of the VdbeSorter
  85665. ** structure for which each thread requires a separate instance. For example,
  85666. ** each thread requries its own UnpackedRecord object to unpack records in
  85667. ** as part of comparison operations.
  85668. **
  85669. ** Before a background thread is launched, variable bDone is set to 0. Then,
  85670. ** right before it exits, the thread itself sets bDone to 1. This is used for
  85671. ** two purposes:
  85672. **
  85673. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  85674. ** attempt to select a SortSubtask for which there is not already an
  85675. ** active background thread (since doing so causes the main thread
  85676. ** to block until it finishes).
  85677. **
  85678. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  85679. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  85680. ** block provoke debugging output.
  85681. **
  85682. ** In both cases, the effects of the main thread seeing (bDone==0) even
  85683. ** after the thread has finished are not dire. So we don't worry about
  85684. ** memory barriers and such here.
  85685. */
  85686. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  85687. struct SortSubtask {
  85688. SQLiteThread *pThread; /* Background thread, if any */
  85689. int bDone; /* Set if thread is finished but not joined */
  85690. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  85691. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  85692. SorterList list; /* List for thread to write to a PMA */
  85693. int nPMA; /* Number of PMAs currently in file */
  85694. SorterCompare xCompare; /* Compare function to use */
  85695. SorterFile file; /* Temp file for level-0 PMAs */
  85696. SorterFile file2; /* Space for other PMAs */
  85697. };
  85698. /*
  85699. ** Main sorter structure. A single instance of this is allocated for each
  85700. ** sorter cursor created by the VDBE.
  85701. **
  85702. ** mxKeysize:
  85703. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  85704. ** this variable is updated so as to be set to the size on disk of the
  85705. ** largest record in the sorter.
  85706. */
  85707. struct VdbeSorter {
  85708. int mnPmaSize; /* Minimum PMA size, in bytes */
  85709. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  85710. int mxKeysize; /* Largest serialized key seen so far */
  85711. int pgsz; /* Main database page size */
  85712. PmaReader *pReader; /* Readr data from here after Rewind() */
  85713. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  85714. sqlite3 *db; /* Database connection */
  85715. KeyInfo *pKeyInfo; /* How to compare records */
  85716. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  85717. SorterList list; /* List of in-memory records */
  85718. int iMemory; /* Offset of free space in list.aMemory */
  85719. int nMemory; /* Size of list.aMemory allocation in bytes */
  85720. u8 bUsePMA; /* True if one or more PMAs created */
  85721. u8 bUseThreads; /* True to use background threads */
  85722. u8 iPrev; /* Previous thread used to flush PMA */
  85723. u8 nTask; /* Size of aTask[] array */
  85724. u8 typeMask;
  85725. SortSubtask aTask[1]; /* One or more subtasks */
  85726. };
  85727. #define SORTER_TYPE_INTEGER 0x01
  85728. #define SORTER_TYPE_TEXT 0x02
  85729. /*
  85730. ** An instance of the following object is used to read records out of a
  85731. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  85732. ** aKey might point into aMap or into aBuffer. If neither of those locations
  85733. ** contain a contiguous representation of the key, then aAlloc is allocated
  85734. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  85735. **
  85736. ** pFd==0 at EOF.
  85737. */
  85738. struct PmaReader {
  85739. i64 iReadOff; /* Current read offset */
  85740. i64 iEof; /* 1 byte past EOF for this PmaReader */
  85741. int nAlloc; /* Bytes of space at aAlloc */
  85742. int nKey; /* Number of bytes in key */
  85743. sqlite3_file *pFd; /* File handle we are reading from */
  85744. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  85745. u8 *aKey; /* Pointer to current key */
  85746. u8 *aBuffer; /* Current read buffer */
  85747. int nBuffer; /* Size of read buffer in bytes */
  85748. u8 *aMap; /* Pointer to mapping of entire file */
  85749. IncrMerger *pIncr; /* Incremental merger */
  85750. };
  85751. /*
  85752. ** Normally, a PmaReader object iterates through an existing PMA stored
  85753. ** within a temp file. However, if the PmaReader.pIncr variable points to
  85754. ** an object of the following type, it may be used to iterate/merge through
  85755. ** multiple PMAs simultaneously.
  85756. **
  85757. ** There are two types of IncrMerger object - single (bUseThread==0) and
  85758. ** multi-threaded (bUseThread==1).
  85759. **
  85760. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  85761. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  85762. ** size. When the IncrMerger is initialized, it reads enough data from
  85763. ** pMerger to populate aFile[0]. It then sets variables within the
  85764. ** corresponding PmaReader object to read from that file and kicks off
  85765. ** a background thread to populate aFile[1] with the next mxSz bytes of
  85766. ** sorted record data from pMerger.
  85767. **
  85768. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  85769. ** background thread has finished populating aFile[1]. It then exchanges
  85770. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  85771. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  85772. ** another background thread to populate the new aFile[1]. And so on, until
  85773. ** the contents of pMerger are exhausted.
  85774. **
  85775. ** A single-threaded IncrMerger does not open any temporary files of its
  85776. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  85777. ** at offset iStartOff of file pTask->file2. And instead of using a
  85778. ** background thread to prepare data for the PmaReader, with a single
  85779. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  85780. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  85781. ** of data.
  85782. */
  85783. struct IncrMerger {
  85784. SortSubtask *pTask; /* Task that owns this merger */
  85785. MergeEngine *pMerger; /* Merge engine thread reads data from */
  85786. i64 iStartOff; /* Offset to start writing file at */
  85787. int mxSz; /* Maximum bytes of data to store */
  85788. int bEof; /* Set to true when merge is finished */
  85789. int bUseThread; /* True to use a bg thread for this object */
  85790. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  85791. };
  85792. /*
  85793. ** An instance of this object is used for writing a PMA.
  85794. **
  85795. ** The PMA is written one record at a time. Each record is of an arbitrary
  85796. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  85797. ** each block is aligned on a page boundary. This object caches writes to
  85798. ** the PMA so that aligned, page-size blocks are written.
  85799. */
  85800. struct PmaWriter {
  85801. int eFWErr; /* Non-zero if in an error state */
  85802. u8 *aBuffer; /* Pointer to write buffer */
  85803. int nBuffer; /* Size of write buffer in bytes */
  85804. int iBufStart; /* First byte of buffer to write */
  85805. int iBufEnd; /* Last byte of buffer to write */
  85806. i64 iWriteOff; /* Offset of start of buffer in file */
  85807. sqlite3_file *pFd; /* File handle to write to */
  85808. };
  85809. /*
  85810. ** This object is the header on a single record while that record is being
  85811. ** held in memory and prior to being written out as part of a PMA.
  85812. **
  85813. ** How the linked list is connected depends on how memory is being managed
  85814. ** by this module. If using a separate allocation for each in-memory record
  85815. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  85816. ** SorterRecord.u.pNext pointers.
  85817. **
  85818. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  85819. ** then while records are being accumulated the list is linked using the
  85820. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  85821. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  85822. ** has finished passing records to the sorter, or when the in-memory buffer
  85823. ** is full, the list is sorted. As part of the sorting process, it is
  85824. ** converted to use the SorterRecord.u.pNext pointers. See function
  85825. ** vdbeSorterSort() for details.
  85826. */
  85827. struct SorterRecord {
  85828. int nVal; /* Size of the record in bytes */
  85829. union {
  85830. SorterRecord *pNext; /* Pointer to next record in list */
  85831. int iNext; /* Offset within aMemory of next record */
  85832. } u;
  85833. /* The data for the record immediately follows this header */
  85834. };
  85835. /* Return a pointer to the buffer containing the record data for SorterRecord
  85836. ** object p. Should be used as if:
  85837. **
  85838. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  85839. */
  85840. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  85841. /* Maximum number of PMAs that a single MergeEngine can merge */
  85842. #define SORTER_MAX_MERGE_COUNT 16
  85843. static int vdbeIncrSwap(IncrMerger*);
  85844. static void vdbeIncrFree(IncrMerger *);
  85845. /*
  85846. ** Free all memory belonging to the PmaReader object passed as the
  85847. ** argument. All structure fields are set to zero before returning.
  85848. */
  85849. static void vdbePmaReaderClear(PmaReader *pReadr){
  85850. sqlite3_free(pReadr->aAlloc);
  85851. sqlite3_free(pReadr->aBuffer);
  85852. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  85853. vdbeIncrFree(pReadr->pIncr);
  85854. memset(pReadr, 0, sizeof(PmaReader));
  85855. }
  85856. /*
  85857. ** Read the next nByte bytes of data from the PMA p.
  85858. ** If successful, set *ppOut to point to a buffer containing the data
  85859. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  85860. ** error code.
  85861. **
  85862. ** The buffer returned in *ppOut is only valid until the
  85863. ** next call to this function.
  85864. */
  85865. static int vdbePmaReadBlob(
  85866. PmaReader *p, /* PmaReader from which to take the blob */
  85867. int nByte, /* Bytes of data to read */
  85868. u8 **ppOut /* OUT: Pointer to buffer containing data */
  85869. ){
  85870. int iBuf; /* Offset within buffer to read from */
  85871. int nAvail; /* Bytes of data available in buffer */
  85872. if( p->aMap ){
  85873. *ppOut = &p->aMap[p->iReadOff];
  85874. p->iReadOff += nByte;
  85875. return SQLITE_OK;
  85876. }
  85877. assert( p->aBuffer );
  85878. /* If there is no more data to be read from the buffer, read the next
  85879. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  85880. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  85881. iBuf = p->iReadOff % p->nBuffer;
  85882. if( iBuf==0 ){
  85883. int nRead; /* Bytes to read from disk */
  85884. int rc; /* sqlite3OsRead() return code */
  85885. /* Determine how many bytes of data to read. */
  85886. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  85887. nRead = p->nBuffer;
  85888. }else{
  85889. nRead = (int)(p->iEof - p->iReadOff);
  85890. }
  85891. assert( nRead>0 );
  85892. /* Readr data from the file. Return early if an error occurs. */
  85893. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  85894. assert( rc!=SQLITE_IOERR_SHORT_READ );
  85895. if( rc!=SQLITE_OK ) return rc;
  85896. }
  85897. nAvail = p->nBuffer - iBuf;
  85898. if( nByte<=nAvail ){
  85899. /* The requested data is available in the in-memory buffer. In this
  85900. ** case there is no need to make a copy of the data, just return a
  85901. ** pointer into the buffer to the caller. */
  85902. *ppOut = &p->aBuffer[iBuf];
  85903. p->iReadOff += nByte;
  85904. }else{
  85905. /* The requested data is not all available in the in-memory buffer.
  85906. ** In this case, allocate space at p->aAlloc[] to copy the requested
  85907. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  85908. int nRem; /* Bytes remaining to copy */
  85909. /* Extend the p->aAlloc[] allocation if required. */
  85910. if( p->nAlloc<nByte ){
  85911. u8 *aNew;
  85912. int nNew = MAX(128, p->nAlloc*2);
  85913. while( nByte>nNew ) nNew = nNew*2;
  85914. aNew = sqlite3Realloc(p->aAlloc, nNew);
  85915. if( !aNew ) return SQLITE_NOMEM_BKPT;
  85916. p->nAlloc = nNew;
  85917. p->aAlloc = aNew;
  85918. }
  85919. /* Copy as much data as is available in the buffer into the start of
  85920. ** p->aAlloc[]. */
  85921. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  85922. p->iReadOff += nAvail;
  85923. nRem = nByte - nAvail;
  85924. /* The following loop copies up to p->nBuffer bytes per iteration into
  85925. ** the p->aAlloc[] buffer. */
  85926. while( nRem>0 ){
  85927. int rc; /* vdbePmaReadBlob() return code */
  85928. int nCopy; /* Number of bytes to copy */
  85929. u8 *aNext; /* Pointer to buffer to copy data from */
  85930. nCopy = nRem;
  85931. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  85932. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  85933. if( rc!=SQLITE_OK ) return rc;
  85934. assert( aNext!=p->aAlloc );
  85935. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  85936. nRem -= nCopy;
  85937. }
  85938. *ppOut = p->aAlloc;
  85939. }
  85940. return SQLITE_OK;
  85941. }
  85942. /*
  85943. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  85944. ** the value read.
  85945. */
  85946. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  85947. int iBuf;
  85948. if( p->aMap ){
  85949. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  85950. }else{
  85951. iBuf = p->iReadOff % p->nBuffer;
  85952. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  85953. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  85954. }else{
  85955. u8 aVarint[16], *a;
  85956. int i = 0, rc;
  85957. do{
  85958. rc = vdbePmaReadBlob(p, 1, &a);
  85959. if( rc ) return rc;
  85960. aVarint[(i++)&0xf] = a[0];
  85961. }while( (a[0]&0x80)!=0 );
  85962. sqlite3GetVarint(aVarint, pnOut);
  85963. }
  85964. }
  85965. return SQLITE_OK;
  85966. }
  85967. /*
  85968. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  85969. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  85970. ** (because the file is too large or the VFS layer is configured not to use
  85971. ** mmap), return SQLITE_OK and set *pp to NULL.
  85972. **
  85973. ** Or, if an error occurs, return an SQLite error code. The final value of
  85974. ** *pp is undefined in this case.
  85975. */
  85976. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  85977. int rc = SQLITE_OK;
  85978. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  85979. sqlite3_file *pFd = pFile->pFd;
  85980. if( pFd->pMethods->iVersion>=3 ){
  85981. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  85982. testcase( rc!=SQLITE_OK );
  85983. }
  85984. }
  85985. return rc;
  85986. }
  85987. /*
  85988. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  85989. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  85990. ** if successful, or an SQLite error code if an error occurs.
  85991. */
  85992. static int vdbePmaReaderSeek(
  85993. SortSubtask *pTask, /* Task context */
  85994. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  85995. SorterFile *pFile, /* Sorter file to read from */
  85996. i64 iOff /* Offset in pFile */
  85997. ){
  85998. int rc = SQLITE_OK;
  85999. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  86000. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  86001. if( pReadr->aMap ){
  86002. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  86003. pReadr->aMap = 0;
  86004. }
  86005. pReadr->iReadOff = iOff;
  86006. pReadr->iEof = pFile->iEof;
  86007. pReadr->pFd = pFile->pFd;
  86008. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  86009. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  86010. int pgsz = pTask->pSorter->pgsz;
  86011. int iBuf = pReadr->iReadOff % pgsz;
  86012. if( pReadr->aBuffer==0 ){
  86013. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  86014. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
  86015. pReadr->nBuffer = pgsz;
  86016. }
  86017. if( rc==SQLITE_OK && iBuf ){
  86018. int nRead = pgsz - iBuf;
  86019. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  86020. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  86021. }
  86022. rc = sqlite3OsRead(
  86023. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  86024. );
  86025. testcase( rc!=SQLITE_OK );
  86026. }
  86027. }
  86028. return rc;
  86029. }
  86030. /*
  86031. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  86032. ** no error occurs, or an SQLite error code if one does.
  86033. */
  86034. static int vdbePmaReaderNext(PmaReader *pReadr){
  86035. int rc = SQLITE_OK; /* Return Code */
  86036. u64 nRec = 0; /* Size of record in bytes */
  86037. if( pReadr->iReadOff>=pReadr->iEof ){
  86038. IncrMerger *pIncr = pReadr->pIncr;
  86039. int bEof = 1;
  86040. if( pIncr ){
  86041. rc = vdbeIncrSwap(pIncr);
  86042. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  86043. rc = vdbePmaReaderSeek(
  86044. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  86045. );
  86046. bEof = 0;
  86047. }
  86048. }
  86049. if( bEof ){
  86050. /* This is an EOF condition */
  86051. vdbePmaReaderClear(pReadr);
  86052. testcase( rc!=SQLITE_OK );
  86053. return rc;
  86054. }
  86055. }
  86056. if( rc==SQLITE_OK ){
  86057. rc = vdbePmaReadVarint(pReadr, &nRec);
  86058. }
  86059. if( rc==SQLITE_OK ){
  86060. pReadr->nKey = (int)nRec;
  86061. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  86062. testcase( rc!=SQLITE_OK );
  86063. }
  86064. return rc;
  86065. }
  86066. /*
  86067. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  86068. ** starting at offset iStart and ending at offset iEof-1. This function
  86069. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  86070. ** PMA is empty).
  86071. **
  86072. ** If the pnByte parameter is NULL, then it is assumed that the file
  86073. ** contains a single PMA, and that that PMA omits the initial length varint.
  86074. */
  86075. static int vdbePmaReaderInit(
  86076. SortSubtask *pTask, /* Task context */
  86077. SorterFile *pFile, /* Sorter file to read from */
  86078. i64 iStart, /* Start offset in pFile */
  86079. PmaReader *pReadr, /* PmaReader to populate */
  86080. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  86081. ){
  86082. int rc;
  86083. assert( pFile->iEof>iStart );
  86084. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  86085. assert( pReadr->aBuffer==0 );
  86086. assert( pReadr->aMap==0 );
  86087. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  86088. if( rc==SQLITE_OK ){
  86089. u64 nByte = 0; /* Size of PMA in bytes */
  86090. rc = vdbePmaReadVarint(pReadr, &nByte);
  86091. pReadr->iEof = pReadr->iReadOff + nByte;
  86092. *pnByte += nByte;
  86093. }
  86094. if( rc==SQLITE_OK ){
  86095. rc = vdbePmaReaderNext(pReadr);
  86096. }
  86097. return rc;
  86098. }
  86099. /*
  86100. ** A version of vdbeSorterCompare() that assumes that it has already been
  86101. ** determined that the first field of key1 is equal to the first field of
  86102. ** key2.
  86103. */
  86104. static int vdbeSorterCompareTail(
  86105. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  86106. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  86107. const void *pKey1, int nKey1, /* Left side of comparison */
  86108. const void *pKey2, int nKey2 /* Right side of comparison */
  86109. ){
  86110. UnpackedRecord *r2 = pTask->pUnpacked;
  86111. if( *pbKey2Cached==0 ){
  86112. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  86113. *pbKey2Cached = 1;
  86114. }
  86115. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  86116. }
  86117. /*
  86118. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  86119. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  86120. ** used by the comparison. Return the result of the comparison.
  86121. **
  86122. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  86123. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  86124. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  86125. ** version of key2 and *pbKey2Cached set to true before returning.
  86126. **
  86127. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  86128. ** to SQLITE_NOMEM.
  86129. */
  86130. static int vdbeSorterCompare(
  86131. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  86132. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  86133. const void *pKey1, int nKey1, /* Left side of comparison */
  86134. const void *pKey2, int nKey2 /* Right side of comparison */
  86135. ){
  86136. UnpackedRecord *r2 = pTask->pUnpacked;
  86137. if( !*pbKey2Cached ){
  86138. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  86139. *pbKey2Cached = 1;
  86140. }
  86141. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  86142. }
  86143. /*
  86144. ** A specially optimized version of vdbeSorterCompare() that assumes that
  86145. ** the first field of each key is a TEXT value and that the collation
  86146. ** sequence to compare them with is BINARY.
  86147. */
  86148. static int vdbeSorterCompareText(
  86149. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  86150. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  86151. const void *pKey1, int nKey1, /* Left side of comparison */
  86152. const void *pKey2, int nKey2 /* Right side of comparison */
  86153. ){
  86154. const u8 * const p1 = (const u8 * const)pKey1;
  86155. const u8 * const p2 = (const u8 * const)pKey2;
  86156. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  86157. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  86158. int n1;
  86159. int n2;
  86160. int res;
  86161. getVarint32(&p1[1], n1);
  86162. getVarint32(&p2[1], n2);
  86163. res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
  86164. if( res==0 ){
  86165. res = n1 - n2;
  86166. }
  86167. if( res==0 ){
  86168. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  86169. res = vdbeSorterCompareTail(
  86170. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  86171. );
  86172. }
  86173. }else{
  86174. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  86175. res = res * -1;
  86176. }
  86177. }
  86178. return res;
  86179. }
  86180. /*
  86181. ** A specially optimized version of vdbeSorterCompare() that assumes that
  86182. ** the first field of each key is an INTEGER value.
  86183. */
  86184. static int vdbeSorterCompareInt(
  86185. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  86186. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  86187. const void *pKey1, int nKey1, /* Left side of comparison */
  86188. const void *pKey2, int nKey2 /* Right side of comparison */
  86189. ){
  86190. const u8 * const p1 = (const u8 * const)pKey1;
  86191. const u8 * const p2 = (const u8 * const)pKey2;
  86192. const int s1 = p1[1]; /* Left hand serial type */
  86193. const int s2 = p2[1]; /* Right hand serial type */
  86194. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  86195. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  86196. int res; /* Return value */
  86197. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  86198. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  86199. if( s1==s2 ){
  86200. /* The two values have the same sign. Compare using memcmp(). */
  86201. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
  86202. const u8 n = aLen[s1];
  86203. int i;
  86204. res = 0;
  86205. for(i=0; i<n; i++){
  86206. if( (res = v1[i] - v2[i])!=0 ){
  86207. if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
  86208. res = v1[0] & 0x80 ? -1 : +1;
  86209. }
  86210. break;
  86211. }
  86212. }
  86213. }else if( s1>7 && s2>7 ){
  86214. res = s1 - s2;
  86215. }else{
  86216. if( s2>7 ){
  86217. res = +1;
  86218. }else if( s1>7 ){
  86219. res = -1;
  86220. }else{
  86221. res = s1 - s2;
  86222. }
  86223. assert( res!=0 );
  86224. if( res>0 ){
  86225. if( *v1 & 0x80 ) res = -1;
  86226. }else{
  86227. if( *v2 & 0x80 ) res = +1;
  86228. }
  86229. }
  86230. if( res==0 ){
  86231. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  86232. res = vdbeSorterCompareTail(
  86233. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  86234. );
  86235. }
  86236. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  86237. res = res * -1;
  86238. }
  86239. return res;
  86240. }
  86241. /*
  86242. ** Initialize the temporary index cursor just opened as a sorter cursor.
  86243. **
  86244. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
  86245. ** to determine the number of fields that should be compared from the
  86246. ** records being sorted. However, if the value passed as argument nField
  86247. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  86248. ** is used instead. This is used when sorting records for a CREATE INDEX
  86249. ** statement. In this case, keys are always delivered to the sorter in
  86250. ** order of the primary key, which happens to be make up the final part
  86251. ** of the records being sorted. So if the sort is stable, there is never
  86252. ** any reason to compare PK fields and they can be ignored for a small
  86253. ** performance boost.
  86254. **
  86255. ** The sorter can guarantee a stable sort when running in single-threaded
  86256. ** mode, but not in multi-threaded mode.
  86257. **
  86258. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  86259. */
  86260. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  86261. sqlite3 *db, /* Database connection (for malloc()) */
  86262. int nField, /* Number of key fields in each record */
  86263. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  86264. ){
  86265. int pgsz; /* Page size of main database */
  86266. int i; /* Used to iterate through aTask[] */
  86267. VdbeSorter *pSorter; /* The new sorter */
  86268. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  86269. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  86270. int sz; /* Size of pSorter in bytes */
  86271. int rc = SQLITE_OK;
  86272. #if SQLITE_MAX_WORKER_THREADS==0
  86273. # define nWorker 0
  86274. #else
  86275. int nWorker;
  86276. #endif
  86277. /* Initialize the upper limit on the number of worker threads */
  86278. #if SQLITE_MAX_WORKER_THREADS>0
  86279. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  86280. nWorker = 0;
  86281. }else{
  86282. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  86283. }
  86284. #endif
  86285. /* Do not allow the total number of threads (main thread + all workers)
  86286. ** to exceed the maximum merge count */
  86287. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  86288. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  86289. nWorker = SORTER_MAX_MERGE_COUNT-1;
  86290. }
  86291. #endif
  86292. assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
  86293. assert( pCsr->eCurType==CURTYPE_SORTER );
  86294. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
  86295. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  86296. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  86297. pCsr->uc.pSorter = pSorter;
  86298. if( pSorter==0 ){
  86299. rc = SQLITE_NOMEM_BKPT;
  86300. }else{
  86301. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  86302. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  86303. pKeyInfo->db = 0;
  86304. if( nField && nWorker==0 ){
  86305. pKeyInfo->nKeyField = nField;
  86306. }
  86307. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  86308. pSorter->nTask = nWorker + 1;
  86309. pSorter->iPrev = (u8)(nWorker - 1);
  86310. pSorter->bUseThreads = (pSorter->nTask>1);
  86311. pSorter->db = db;
  86312. for(i=0; i<pSorter->nTask; i++){
  86313. SortSubtask *pTask = &pSorter->aTask[i];
  86314. pTask->pSorter = pSorter;
  86315. }
  86316. if( !sqlite3TempInMemory(db) ){
  86317. i64 mxCache; /* Cache size in bytes*/
  86318. u32 szPma = sqlite3GlobalConfig.szPma;
  86319. pSorter->mnPmaSize = szPma * pgsz;
  86320. mxCache = db->aDb[0].pSchema->cache_size;
  86321. if( mxCache<0 ){
  86322. /* A negative cache-size value C indicates that the cache is abs(C)
  86323. ** KiB in size. */
  86324. mxCache = mxCache * -1024;
  86325. }else{
  86326. mxCache = mxCache * pgsz;
  86327. }
  86328. mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
  86329. pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
  86330. /* Avoid large memory allocations if the application has requested
  86331. ** SQLITE_CONFIG_SMALL_MALLOC. */
  86332. if( sqlite3GlobalConfig.bSmallMalloc==0 ){
  86333. assert( pSorter->iMemory==0 );
  86334. pSorter->nMemory = pgsz;
  86335. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  86336. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
  86337. }
  86338. }
  86339. if( pKeyInfo->nAllField<13
  86340. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  86341. ){
  86342. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  86343. }
  86344. }
  86345. return rc;
  86346. }
  86347. #undef nWorker /* Defined at the top of this function */
  86348. /*
  86349. ** Free the list of sorted records starting at pRecord.
  86350. */
  86351. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  86352. SorterRecord *p;
  86353. SorterRecord *pNext;
  86354. for(p=pRecord; p; p=pNext){
  86355. pNext = p->u.pNext;
  86356. sqlite3DbFree(db, p);
  86357. }
  86358. }
  86359. /*
  86360. ** Free all resources owned by the object indicated by argument pTask. All
  86361. ** fields of *pTask are zeroed before returning.
  86362. */
  86363. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  86364. sqlite3DbFree(db, pTask->pUnpacked);
  86365. #if SQLITE_MAX_WORKER_THREADS>0
  86366. /* pTask->list.aMemory can only be non-zero if it was handed memory
  86367. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  86368. if( pTask->list.aMemory ){
  86369. sqlite3_free(pTask->list.aMemory);
  86370. }else
  86371. #endif
  86372. {
  86373. assert( pTask->list.aMemory==0 );
  86374. vdbeSorterRecordFree(0, pTask->list.pList);
  86375. }
  86376. if( pTask->file.pFd ){
  86377. sqlite3OsCloseFree(pTask->file.pFd);
  86378. }
  86379. if( pTask->file2.pFd ){
  86380. sqlite3OsCloseFree(pTask->file2.pFd);
  86381. }
  86382. memset(pTask, 0, sizeof(SortSubtask));
  86383. }
  86384. #ifdef SQLITE_DEBUG_SORTER_THREADS
  86385. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  86386. i64 t;
  86387. int iTask = (pTask - pTask->pSorter->aTask);
  86388. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  86389. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  86390. }
  86391. static void vdbeSorterRewindDebug(const char *zEvent){
  86392. i64 t;
  86393. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  86394. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  86395. }
  86396. static void vdbeSorterPopulateDebug(
  86397. SortSubtask *pTask,
  86398. const char *zEvent
  86399. ){
  86400. i64 t;
  86401. int iTask = (pTask - pTask->pSorter->aTask);
  86402. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  86403. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  86404. }
  86405. static void vdbeSorterBlockDebug(
  86406. SortSubtask *pTask,
  86407. int bBlocked,
  86408. const char *zEvent
  86409. ){
  86410. if( bBlocked ){
  86411. i64 t;
  86412. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  86413. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  86414. }
  86415. }
  86416. #else
  86417. # define vdbeSorterWorkDebug(x,y)
  86418. # define vdbeSorterRewindDebug(y)
  86419. # define vdbeSorterPopulateDebug(x,y)
  86420. # define vdbeSorterBlockDebug(x,y,z)
  86421. #endif
  86422. #if SQLITE_MAX_WORKER_THREADS>0
  86423. /*
  86424. ** Join thread pTask->thread.
  86425. */
  86426. static int vdbeSorterJoinThread(SortSubtask *pTask){
  86427. int rc = SQLITE_OK;
  86428. if( pTask->pThread ){
  86429. #ifdef SQLITE_DEBUG_SORTER_THREADS
  86430. int bDone = pTask->bDone;
  86431. #endif
  86432. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  86433. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  86434. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  86435. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  86436. rc = SQLITE_PTR_TO_INT(pRet);
  86437. assert( pTask->bDone==1 );
  86438. pTask->bDone = 0;
  86439. pTask->pThread = 0;
  86440. }
  86441. return rc;
  86442. }
  86443. /*
  86444. ** Launch a background thread to run xTask(pIn).
  86445. */
  86446. static int vdbeSorterCreateThread(
  86447. SortSubtask *pTask, /* Thread will use this task object */
  86448. void *(*xTask)(void*), /* Routine to run in a separate thread */
  86449. void *pIn /* Argument passed into xTask() */
  86450. ){
  86451. assert( pTask->pThread==0 && pTask->bDone==0 );
  86452. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  86453. }
  86454. /*
  86455. ** Join all outstanding threads launched by SorterWrite() to create
  86456. ** level-0 PMAs.
  86457. */
  86458. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  86459. int rc = rcin;
  86460. int i;
  86461. /* This function is always called by the main user thread.
  86462. **
  86463. ** If this function is being called after SorterRewind() has been called,
  86464. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  86465. ** is currently attempt to join one of the other threads. To avoid a race
  86466. ** condition where this thread also attempts to join the same object, join
  86467. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  86468. for(i=pSorter->nTask-1; i>=0; i--){
  86469. SortSubtask *pTask = &pSorter->aTask[i];
  86470. int rc2 = vdbeSorterJoinThread(pTask);
  86471. if( rc==SQLITE_OK ) rc = rc2;
  86472. }
  86473. return rc;
  86474. }
  86475. #else
  86476. # define vdbeSorterJoinAll(x,rcin) (rcin)
  86477. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  86478. #endif
  86479. /*
  86480. ** Allocate a new MergeEngine object capable of handling up to
  86481. ** nReader PmaReader inputs.
  86482. **
  86483. ** nReader is automatically rounded up to the next power of two.
  86484. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  86485. */
  86486. static MergeEngine *vdbeMergeEngineNew(int nReader){
  86487. int N = 2; /* Smallest power of two >= nReader */
  86488. int nByte; /* Total bytes of space to allocate */
  86489. MergeEngine *pNew; /* Pointer to allocated object to return */
  86490. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  86491. while( N<nReader ) N += N;
  86492. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  86493. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  86494. if( pNew ){
  86495. pNew->nTree = N;
  86496. pNew->pTask = 0;
  86497. pNew->aReadr = (PmaReader*)&pNew[1];
  86498. pNew->aTree = (int*)&pNew->aReadr[N];
  86499. }
  86500. return pNew;
  86501. }
  86502. /*
  86503. ** Free the MergeEngine object passed as the only argument.
  86504. */
  86505. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  86506. int i;
  86507. if( pMerger ){
  86508. for(i=0; i<pMerger->nTree; i++){
  86509. vdbePmaReaderClear(&pMerger->aReadr[i]);
  86510. }
  86511. }
  86512. sqlite3_free(pMerger);
  86513. }
  86514. /*
  86515. ** Free all resources associated with the IncrMerger object indicated by
  86516. ** the first argument.
  86517. */
  86518. static void vdbeIncrFree(IncrMerger *pIncr){
  86519. if( pIncr ){
  86520. #if SQLITE_MAX_WORKER_THREADS>0
  86521. if( pIncr->bUseThread ){
  86522. vdbeSorterJoinThread(pIncr->pTask);
  86523. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  86524. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  86525. }
  86526. #endif
  86527. vdbeMergeEngineFree(pIncr->pMerger);
  86528. sqlite3_free(pIncr);
  86529. }
  86530. }
  86531. /*
  86532. ** Reset a sorting cursor back to its original empty state.
  86533. */
  86534. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  86535. int i;
  86536. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  86537. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  86538. #if SQLITE_MAX_WORKER_THREADS>0
  86539. if( pSorter->pReader ){
  86540. vdbePmaReaderClear(pSorter->pReader);
  86541. sqlite3DbFree(db, pSorter->pReader);
  86542. pSorter->pReader = 0;
  86543. }
  86544. #endif
  86545. vdbeMergeEngineFree(pSorter->pMerger);
  86546. pSorter->pMerger = 0;
  86547. for(i=0; i<pSorter->nTask; i++){
  86548. SortSubtask *pTask = &pSorter->aTask[i];
  86549. vdbeSortSubtaskCleanup(db, pTask);
  86550. pTask->pSorter = pSorter;
  86551. }
  86552. if( pSorter->list.aMemory==0 ){
  86553. vdbeSorterRecordFree(0, pSorter->list.pList);
  86554. }
  86555. pSorter->list.pList = 0;
  86556. pSorter->list.szPMA = 0;
  86557. pSorter->bUsePMA = 0;
  86558. pSorter->iMemory = 0;
  86559. pSorter->mxKeysize = 0;
  86560. sqlite3DbFree(db, pSorter->pUnpacked);
  86561. pSorter->pUnpacked = 0;
  86562. }
  86563. /*
  86564. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  86565. */
  86566. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  86567. VdbeSorter *pSorter;
  86568. assert( pCsr->eCurType==CURTYPE_SORTER );
  86569. pSorter = pCsr->uc.pSorter;
  86570. if( pSorter ){
  86571. sqlite3VdbeSorterReset(db, pSorter);
  86572. sqlite3_free(pSorter->list.aMemory);
  86573. sqlite3DbFree(db, pSorter);
  86574. pCsr->uc.pSorter = 0;
  86575. }
  86576. }
  86577. #if SQLITE_MAX_MMAP_SIZE>0
  86578. /*
  86579. ** The first argument is a file-handle open on a temporary file. The file
  86580. ** is guaranteed to be nByte bytes or smaller in size. This function
  86581. ** attempts to extend the file to nByte bytes in size and to ensure that
  86582. ** the VFS has memory mapped it.
  86583. **
  86584. ** Whether or not the file does end up memory mapped of course depends on
  86585. ** the specific VFS implementation.
  86586. */
  86587. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  86588. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  86589. void *p = 0;
  86590. int chunksize = 4*1024;
  86591. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  86592. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  86593. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  86594. sqlite3OsUnfetch(pFd, 0, p);
  86595. }
  86596. }
  86597. #else
  86598. # define vdbeSorterExtendFile(x,y,z)
  86599. #endif
  86600. /*
  86601. ** Allocate space for a file-handle and open a temporary file. If successful,
  86602. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  86603. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  86604. */
  86605. static int vdbeSorterOpenTempFile(
  86606. sqlite3 *db, /* Database handle doing sort */
  86607. i64 nExtend, /* Attempt to extend file to this size */
  86608. sqlite3_file **ppFd
  86609. ){
  86610. int rc;
  86611. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  86612. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  86613. SQLITE_OPEN_TEMP_JOURNAL |
  86614. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  86615. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  86616. );
  86617. if( rc==SQLITE_OK ){
  86618. i64 max = SQLITE_MAX_MMAP_SIZE;
  86619. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  86620. if( nExtend>0 ){
  86621. vdbeSorterExtendFile(db, *ppFd, nExtend);
  86622. }
  86623. }
  86624. return rc;
  86625. }
  86626. /*
  86627. ** If it has not already been allocated, allocate the UnpackedRecord
  86628. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  86629. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  86630. */
  86631. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  86632. if( pTask->pUnpacked==0 ){
  86633. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
  86634. if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
  86635. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
  86636. pTask->pUnpacked->errCode = 0;
  86637. }
  86638. return SQLITE_OK;
  86639. }
  86640. /*
  86641. ** Merge the two sorted lists p1 and p2 into a single list.
  86642. */
  86643. static SorterRecord *vdbeSorterMerge(
  86644. SortSubtask *pTask, /* Calling thread context */
  86645. SorterRecord *p1, /* First list to merge */
  86646. SorterRecord *p2 /* Second list to merge */
  86647. ){
  86648. SorterRecord *pFinal = 0;
  86649. SorterRecord **pp = &pFinal;
  86650. int bCached = 0;
  86651. assert( p1!=0 && p2!=0 );
  86652. for(;;){
  86653. int res;
  86654. res = pTask->xCompare(
  86655. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  86656. );
  86657. if( res<=0 ){
  86658. *pp = p1;
  86659. pp = &p1->u.pNext;
  86660. p1 = p1->u.pNext;
  86661. if( p1==0 ){
  86662. *pp = p2;
  86663. break;
  86664. }
  86665. }else{
  86666. *pp = p2;
  86667. pp = &p2->u.pNext;
  86668. p2 = p2->u.pNext;
  86669. bCached = 0;
  86670. if( p2==0 ){
  86671. *pp = p1;
  86672. break;
  86673. }
  86674. }
  86675. }
  86676. return pFinal;
  86677. }
  86678. /*
  86679. ** Return the SorterCompare function to compare values collected by the
  86680. ** sorter object passed as the only argument.
  86681. */
  86682. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  86683. if( p->typeMask==SORTER_TYPE_INTEGER ){
  86684. return vdbeSorterCompareInt;
  86685. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  86686. return vdbeSorterCompareText;
  86687. }
  86688. return vdbeSorterCompare;
  86689. }
  86690. /*
  86691. ** Sort the linked list of records headed at pTask->pList. Return
  86692. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  86693. ** an error occurs.
  86694. */
  86695. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  86696. int i;
  86697. SorterRecord **aSlot;
  86698. SorterRecord *p;
  86699. int rc;
  86700. rc = vdbeSortAllocUnpacked(pTask);
  86701. if( rc!=SQLITE_OK ) return rc;
  86702. p = pList->pList;
  86703. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  86704. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  86705. if( !aSlot ){
  86706. return SQLITE_NOMEM_BKPT;
  86707. }
  86708. while( p ){
  86709. SorterRecord *pNext;
  86710. if( pList->aMemory ){
  86711. if( (u8*)p==pList->aMemory ){
  86712. pNext = 0;
  86713. }else{
  86714. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  86715. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  86716. }
  86717. }else{
  86718. pNext = p->u.pNext;
  86719. }
  86720. p->u.pNext = 0;
  86721. for(i=0; aSlot[i]; i++){
  86722. p = vdbeSorterMerge(pTask, p, aSlot[i]);
  86723. aSlot[i] = 0;
  86724. }
  86725. aSlot[i] = p;
  86726. p = pNext;
  86727. }
  86728. p = 0;
  86729. for(i=0; i<64; i++){
  86730. if( aSlot[i]==0 ) continue;
  86731. p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
  86732. }
  86733. pList->pList = p;
  86734. sqlite3_free(aSlot);
  86735. assert( pTask->pUnpacked->errCode==SQLITE_OK
  86736. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  86737. );
  86738. return pTask->pUnpacked->errCode;
  86739. }
  86740. /*
  86741. ** Initialize a PMA-writer object.
  86742. */
  86743. static void vdbePmaWriterInit(
  86744. sqlite3_file *pFd, /* File handle to write to */
  86745. PmaWriter *p, /* Object to populate */
  86746. int nBuf, /* Buffer size */
  86747. i64 iStart /* Offset of pFd to begin writing at */
  86748. ){
  86749. memset(p, 0, sizeof(PmaWriter));
  86750. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  86751. if( !p->aBuffer ){
  86752. p->eFWErr = SQLITE_NOMEM_BKPT;
  86753. }else{
  86754. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  86755. p->iWriteOff = iStart - p->iBufStart;
  86756. p->nBuffer = nBuf;
  86757. p->pFd = pFd;
  86758. }
  86759. }
  86760. /*
  86761. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  86762. ** if successful, or an SQLite error code if an error occurs.
  86763. */
  86764. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  86765. int nRem = nData;
  86766. while( nRem>0 && p->eFWErr==0 ){
  86767. int nCopy = nRem;
  86768. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  86769. nCopy = p->nBuffer - p->iBufEnd;
  86770. }
  86771. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  86772. p->iBufEnd += nCopy;
  86773. if( p->iBufEnd==p->nBuffer ){
  86774. p->eFWErr = sqlite3OsWrite(p->pFd,
  86775. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  86776. p->iWriteOff + p->iBufStart
  86777. );
  86778. p->iBufStart = p->iBufEnd = 0;
  86779. p->iWriteOff += p->nBuffer;
  86780. }
  86781. assert( p->iBufEnd<p->nBuffer );
  86782. nRem -= nCopy;
  86783. }
  86784. }
  86785. /*
  86786. ** Flush any buffered data to disk and clean up the PMA-writer object.
  86787. ** The results of using the PMA-writer after this call are undefined.
  86788. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  86789. ** required. Otherwise, return an SQLite error code.
  86790. **
  86791. ** Before returning, set *piEof to the offset immediately following the
  86792. ** last byte written to the file.
  86793. */
  86794. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  86795. int rc;
  86796. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  86797. p->eFWErr = sqlite3OsWrite(p->pFd,
  86798. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  86799. p->iWriteOff + p->iBufStart
  86800. );
  86801. }
  86802. *piEof = (p->iWriteOff + p->iBufEnd);
  86803. sqlite3_free(p->aBuffer);
  86804. rc = p->eFWErr;
  86805. memset(p, 0, sizeof(PmaWriter));
  86806. return rc;
  86807. }
  86808. /*
  86809. ** Write value iVal encoded as a varint to the PMA. Return
  86810. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  86811. */
  86812. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  86813. int nByte;
  86814. u8 aByte[10];
  86815. nByte = sqlite3PutVarint(aByte, iVal);
  86816. vdbePmaWriteBlob(p, aByte, nByte);
  86817. }
  86818. /*
  86819. ** Write the current contents of in-memory linked-list pList to a level-0
  86820. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  86821. ** successful, or an SQLite error code otherwise.
  86822. **
  86823. ** The format of a PMA is:
  86824. **
  86825. ** * A varint. This varint contains the total number of bytes of content
  86826. ** in the PMA (not including the varint itself).
  86827. **
  86828. ** * One or more records packed end-to-end in order of ascending keys.
  86829. ** Each record consists of a varint followed by a blob of data (the
  86830. ** key). The varint is the number of bytes in the blob of data.
  86831. */
  86832. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  86833. sqlite3 *db = pTask->pSorter->db;
  86834. int rc = SQLITE_OK; /* Return code */
  86835. PmaWriter writer; /* Object used to write to the file */
  86836. #ifdef SQLITE_DEBUG
  86837. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  86838. ** This is used by an assert() statement at the end of this function. */
  86839. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  86840. #endif
  86841. vdbeSorterWorkDebug(pTask, "enter");
  86842. memset(&writer, 0, sizeof(PmaWriter));
  86843. assert( pList->szPMA>0 );
  86844. /* If the first temporary PMA file has not been opened, open it now. */
  86845. if( pTask->file.pFd==0 ){
  86846. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  86847. assert( rc!=SQLITE_OK || pTask->file.pFd );
  86848. assert( pTask->file.iEof==0 );
  86849. assert( pTask->nPMA==0 );
  86850. }
  86851. /* Try to get the file to memory map */
  86852. if( rc==SQLITE_OK ){
  86853. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  86854. }
  86855. /* Sort the list */
  86856. if( rc==SQLITE_OK ){
  86857. rc = vdbeSorterSort(pTask, pList);
  86858. }
  86859. if( rc==SQLITE_OK ){
  86860. SorterRecord *p;
  86861. SorterRecord *pNext = 0;
  86862. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  86863. pTask->file.iEof);
  86864. pTask->nPMA++;
  86865. vdbePmaWriteVarint(&writer, pList->szPMA);
  86866. for(p=pList->pList; p; p=pNext){
  86867. pNext = p->u.pNext;
  86868. vdbePmaWriteVarint(&writer, p->nVal);
  86869. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  86870. if( pList->aMemory==0 ) sqlite3_free(p);
  86871. }
  86872. pList->pList = p;
  86873. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  86874. }
  86875. vdbeSorterWorkDebug(pTask, "exit");
  86876. assert( rc!=SQLITE_OK || pList->pList==0 );
  86877. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  86878. return rc;
  86879. }
  86880. /*
  86881. ** Advance the MergeEngine to its next entry.
  86882. ** Set *pbEof to true there is no next entry because
  86883. ** the MergeEngine has reached the end of all its inputs.
  86884. **
  86885. ** Return SQLITE_OK if successful or an error code if an error occurs.
  86886. */
  86887. static int vdbeMergeEngineStep(
  86888. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  86889. int *pbEof /* Set TRUE at EOF. Set false for more content */
  86890. ){
  86891. int rc;
  86892. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  86893. SortSubtask *pTask = pMerger->pTask;
  86894. /* Advance the current PmaReader */
  86895. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  86896. /* Update contents of aTree[] */
  86897. if( rc==SQLITE_OK ){
  86898. int i; /* Index of aTree[] to recalculate */
  86899. PmaReader *pReadr1; /* First PmaReader to compare */
  86900. PmaReader *pReadr2; /* Second PmaReader to compare */
  86901. int bCached = 0;
  86902. /* Find the first two PmaReaders to compare. The one that was just
  86903. ** advanced (iPrev) and the one next to it in the array. */
  86904. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  86905. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  86906. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  86907. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  86908. int iRes;
  86909. if( pReadr1->pFd==0 ){
  86910. iRes = +1;
  86911. }else if( pReadr2->pFd==0 ){
  86912. iRes = -1;
  86913. }else{
  86914. iRes = pTask->xCompare(pTask, &bCached,
  86915. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  86916. );
  86917. }
  86918. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  86919. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  86920. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  86921. ** pKey2 to point to the record belonging to pReadr2.
  86922. **
  86923. ** Alternatively, if pReadr2 contains the smaller of the two values,
  86924. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  86925. ** was actually called above, then pTask->pUnpacked now contains
  86926. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  86927. ** vdbeSorterCompare() from decoding pReadr2 again.
  86928. **
  86929. ** If the two values were equal, then the value from the oldest
  86930. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  86931. ** is sorted from oldest to newest, so pReadr1 contains older values
  86932. ** than pReadr2 iff (pReadr1<pReadr2). */
  86933. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  86934. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  86935. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  86936. bCached = 0;
  86937. }else{
  86938. if( pReadr1->pFd ) bCached = 0;
  86939. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  86940. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  86941. }
  86942. }
  86943. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  86944. }
  86945. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  86946. }
  86947. #if SQLITE_MAX_WORKER_THREADS>0
  86948. /*
  86949. ** The main routine for background threads that write level-0 PMAs.
  86950. */
  86951. static void *vdbeSorterFlushThread(void *pCtx){
  86952. SortSubtask *pTask = (SortSubtask*)pCtx;
  86953. int rc; /* Return code */
  86954. assert( pTask->bDone==0 );
  86955. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  86956. pTask->bDone = 1;
  86957. return SQLITE_INT_TO_PTR(rc);
  86958. }
  86959. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  86960. /*
  86961. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  86962. ** using a background thread.
  86963. */
  86964. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  86965. #if SQLITE_MAX_WORKER_THREADS==0
  86966. pSorter->bUsePMA = 1;
  86967. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  86968. #else
  86969. int rc = SQLITE_OK;
  86970. int i;
  86971. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  86972. int nWorker = (pSorter->nTask-1);
  86973. /* Set the flag to indicate that at least one PMA has been written.
  86974. ** Or will be, anyhow. */
  86975. pSorter->bUsePMA = 1;
  86976. /* Select a sub-task to sort and flush the current list of in-memory
  86977. ** records to disk. If the sorter is running in multi-threaded mode,
  86978. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  86979. ** the background thread from a sub-tasks previous turn is still running,
  86980. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  86981. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  86982. ** sub-tasks are prefered as they use background threads - the final
  86983. ** sub-task uses the main thread. */
  86984. for(i=0; i<nWorker; i++){
  86985. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  86986. pTask = &pSorter->aTask[iTest];
  86987. if( pTask->bDone ){
  86988. rc = vdbeSorterJoinThread(pTask);
  86989. }
  86990. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  86991. }
  86992. if( rc==SQLITE_OK ){
  86993. if( i==nWorker ){
  86994. /* Use the foreground thread for this operation */
  86995. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  86996. }else{
  86997. /* Launch a background thread for this operation */
  86998. u8 *aMem = pTask->list.aMemory;
  86999. void *pCtx = (void*)pTask;
  87000. assert( pTask->pThread==0 && pTask->bDone==0 );
  87001. assert( pTask->list.pList==0 );
  87002. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  87003. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  87004. pTask->list = pSorter->list;
  87005. pSorter->list.pList = 0;
  87006. pSorter->list.szPMA = 0;
  87007. if( aMem ){
  87008. pSorter->list.aMemory = aMem;
  87009. pSorter->nMemory = sqlite3MallocSize(aMem);
  87010. }else if( pSorter->list.aMemory ){
  87011. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  87012. if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
  87013. }
  87014. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  87015. }
  87016. }
  87017. return rc;
  87018. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  87019. }
  87020. /*
  87021. ** Add a record to the sorter.
  87022. */
  87023. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  87024. const VdbeCursor *pCsr, /* Sorter cursor */
  87025. Mem *pVal /* Memory cell containing record */
  87026. ){
  87027. VdbeSorter *pSorter;
  87028. int rc = SQLITE_OK; /* Return Code */
  87029. SorterRecord *pNew; /* New list element */
  87030. int bFlush; /* True to flush contents of memory to PMA */
  87031. int nReq; /* Bytes of memory required */
  87032. int nPMA; /* Bytes of PMA space required */
  87033. int t; /* serial type of first record field */
  87034. assert( pCsr->eCurType==CURTYPE_SORTER );
  87035. pSorter = pCsr->uc.pSorter;
  87036. getVarint32((const u8*)&pVal->z[1], t);
  87037. if( t>0 && t<10 && t!=7 ){
  87038. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  87039. }else if( t>10 && (t & 0x01) ){
  87040. pSorter->typeMask &= SORTER_TYPE_TEXT;
  87041. }else{
  87042. pSorter->typeMask = 0;
  87043. }
  87044. assert( pSorter );
  87045. /* Figure out whether or not the current contents of memory should be
  87046. ** flushed to a PMA before continuing. If so, do so.
  87047. **
  87048. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  87049. ** flush the contents of memory to a new PMA if (a) at least one value is
  87050. ** already in memory and (b) the new value will not fit in memory.
  87051. **
  87052. ** Or, if using separate allocations for each record, flush the contents
  87053. ** of memory to a PMA if either of the following are true:
  87054. **
  87055. ** * The total memory allocated for the in-memory list is greater
  87056. ** than (page-size * cache-size), or
  87057. **
  87058. ** * The total memory allocated for the in-memory list is greater
  87059. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  87060. */
  87061. nReq = pVal->n + sizeof(SorterRecord);
  87062. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  87063. if( pSorter->mxPmaSize ){
  87064. if( pSorter->list.aMemory ){
  87065. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  87066. }else{
  87067. bFlush = (
  87068. (pSorter->list.szPMA > pSorter->mxPmaSize)
  87069. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  87070. );
  87071. }
  87072. if( bFlush ){
  87073. rc = vdbeSorterFlushPMA(pSorter);
  87074. pSorter->list.szPMA = 0;
  87075. pSorter->iMemory = 0;
  87076. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  87077. }
  87078. }
  87079. pSorter->list.szPMA += nPMA;
  87080. if( nPMA>pSorter->mxKeysize ){
  87081. pSorter->mxKeysize = nPMA;
  87082. }
  87083. if( pSorter->list.aMemory ){
  87084. int nMin = pSorter->iMemory + nReq;
  87085. if( nMin>pSorter->nMemory ){
  87086. u8 *aNew;
  87087. int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
  87088. int nNew = pSorter->nMemory * 2;
  87089. while( nNew < nMin ) nNew = nNew*2;
  87090. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  87091. if( nNew < nMin ) nNew = nMin;
  87092. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  87093. if( !aNew ) return SQLITE_NOMEM_BKPT;
  87094. pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
  87095. pSorter->list.aMemory = aNew;
  87096. pSorter->nMemory = nNew;
  87097. }
  87098. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  87099. pSorter->iMemory += ROUND8(nReq);
  87100. if( pSorter->list.pList ){
  87101. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  87102. }
  87103. }else{
  87104. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  87105. if( pNew==0 ){
  87106. return SQLITE_NOMEM_BKPT;
  87107. }
  87108. pNew->u.pNext = pSorter->list.pList;
  87109. }
  87110. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  87111. pNew->nVal = pVal->n;
  87112. pSorter->list.pList = pNew;
  87113. return rc;
  87114. }
  87115. /*
  87116. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  87117. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  87118. ** except that the number-of-bytes varint is omitted from the start.
  87119. */
  87120. static int vdbeIncrPopulate(IncrMerger *pIncr){
  87121. int rc = SQLITE_OK;
  87122. int rc2;
  87123. i64 iStart = pIncr->iStartOff;
  87124. SorterFile *pOut = &pIncr->aFile[1];
  87125. SortSubtask *pTask = pIncr->pTask;
  87126. MergeEngine *pMerger = pIncr->pMerger;
  87127. PmaWriter writer;
  87128. assert( pIncr->bEof==0 );
  87129. vdbeSorterPopulateDebug(pTask, "enter");
  87130. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  87131. while( rc==SQLITE_OK ){
  87132. int dummy;
  87133. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  87134. int nKey = pReader->nKey;
  87135. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  87136. /* Check if the output file is full or if the input has been exhausted.
  87137. ** In either case exit the loop. */
  87138. if( pReader->pFd==0 ) break;
  87139. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  87140. /* Write the next key to the output. */
  87141. vdbePmaWriteVarint(&writer, nKey);
  87142. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  87143. assert( pIncr->pMerger->pTask==pTask );
  87144. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  87145. }
  87146. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  87147. if( rc==SQLITE_OK ) rc = rc2;
  87148. vdbeSorterPopulateDebug(pTask, "exit");
  87149. return rc;
  87150. }
  87151. #if SQLITE_MAX_WORKER_THREADS>0
  87152. /*
  87153. ** The main routine for background threads that populate aFile[1] of
  87154. ** multi-threaded IncrMerger objects.
  87155. */
  87156. static void *vdbeIncrPopulateThread(void *pCtx){
  87157. IncrMerger *pIncr = (IncrMerger*)pCtx;
  87158. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  87159. pIncr->pTask->bDone = 1;
  87160. return pRet;
  87161. }
  87162. /*
  87163. ** Launch a background thread to populate aFile[1] of pIncr.
  87164. */
  87165. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  87166. void *p = (void*)pIncr;
  87167. assert( pIncr->bUseThread );
  87168. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  87169. }
  87170. #endif
  87171. /*
  87172. ** This function is called when the PmaReader corresponding to pIncr has
  87173. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  87174. ** aFile[0] such that the PmaReader should start rereading it from the
  87175. ** beginning.
  87176. **
  87177. ** For single-threaded objects, this is accomplished by literally reading
  87178. ** keys from pIncr->pMerger and repopulating aFile[0].
  87179. **
  87180. ** For multi-threaded objects, all that is required is to wait until the
  87181. ** background thread is finished (if it is not already) and then swap
  87182. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  87183. ** been exhausted, this function also launches a new background thread
  87184. ** to populate the new aFile[1].
  87185. **
  87186. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  87187. */
  87188. static int vdbeIncrSwap(IncrMerger *pIncr){
  87189. int rc = SQLITE_OK;
  87190. #if SQLITE_MAX_WORKER_THREADS>0
  87191. if( pIncr->bUseThread ){
  87192. rc = vdbeSorterJoinThread(pIncr->pTask);
  87193. if( rc==SQLITE_OK ){
  87194. SorterFile f0 = pIncr->aFile[0];
  87195. pIncr->aFile[0] = pIncr->aFile[1];
  87196. pIncr->aFile[1] = f0;
  87197. }
  87198. if( rc==SQLITE_OK ){
  87199. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  87200. pIncr->bEof = 1;
  87201. }else{
  87202. rc = vdbeIncrBgPopulate(pIncr);
  87203. }
  87204. }
  87205. }else
  87206. #endif
  87207. {
  87208. rc = vdbeIncrPopulate(pIncr);
  87209. pIncr->aFile[0] = pIncr->aFile[1];
  87210. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  87211. pIncr->bEof = 1;
  87212. }
  87213. }
  87214. return rc;
  87215. }
  87216. /*
  87217. ** Allocate and return a new IncrMerger object to read data from pMerger.
  87218. **
  87219. ** If an OOM condition is encountered, return NULL. In this case free the
  87220. ** pMerger argument before returning.
  87221. */
  87222. static int vdbeIncrMergerNew(
  87223. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  87224. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  87225. IncrMerger **ppOut /* Write the new IncrMerger here */
  87226. ){
  87227. int rc = SQLITE_OK;
  87228. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  87229. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  87230. if( pIncr ){
  87231. pIncr->pMerger = pMerger;
  87232. pIncr->pTask = pTask;
  87233. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  87234. pTask->file2.iEof += pIncr->mxSz;
  87235. }else{
  87236. vdbeMergeEngineFree(pMerger);
  87237. rc = SQLITE_NOMEM_BKPT;
  87238. }
  87239. return rc;
  87240. }
  87241. #if SQLITE_MAX_WORKER_THREADS>0
  87242. /*
  87243. ** Set the "use-threads" flag on object pIncr.
  87244. */
  87245. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  87246. pIncr->bUseThread = 1;
  87247. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  87248. }
  87249. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  87250. /*
  87251. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  87252. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  87253. ** are advanced. This routine merely does the comparison.
  87254. */
  87255. static void vdbeMergeEngineCompare(
  87256. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  87257. int iOut /* Store the result in pMerger->aTree[iOut] */
  87258. ){
  87259. int i1;
  87260. int i2;
  87261. int iRes;
  87262. PmaReader *p1;
  87263. PmaReader *p2;
  87264. assert( iOut<pMerger->nTree && iOut>0 );
  87265. if( iOut>=(pMerger->nTree/2) ){
  87266. i1 = (iOut - pMerger->nTree/2) * 2;
  87267. i2 = i1 + 1;
  87268. }else{
  87269. i1 = pMerger->aTree[iOut*2];
  87270. i2 = pMerger->aTree[iOut*2+1];
  87271. }
  87272. p1 = &pMerger->aReadr[i1];
  87273. p2 = &pMerger->aReadr[i2];
  87274. if( p1->pFd==0 ){
  87275. iRes = i2;
  87276. }else if( p2->pFd==0 ){
  87277. iRes = i1;
  87278. }else{
  87279. SortSubtask *pTask = pMerger->pTask;
  87280. int bCached = 0;
  87281. int res;
  87282. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  87283. res = pTask->xCompare(
  87284. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  87285. );
  87286. if( res<=0 ){
  87287. iRes = i1;
  87288. }else{
  87289. iRes = i2;
  87290. }
  87291. }
  87292. pMerger->aTree[iOut] = iRes;
  87293. }
  87294. /*
  87295. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  87296. ** and vdbePmaReaderIncrMergeInit().
  87297. **
  87298. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  87299. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  87300. ** when there exists one or more separate worker threads.
  87301. */
  87302. #define INCRINIT_NORMAL 0
  87303. #define INCRINIT_TASK 1
  87304. #define INCRINIT_ROOT 2
  87305. /*
  87306. ** Forward reference required as the vdbeIncrMergeInit() and
  87307. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  87308. ** building a merge tree.
  87309. */
  87310. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  87311. /*
  87312. ** Initialize the MergeEngine object passed as the second argument. Once this
  87313. ** function returns, the first key of merged data may be read from the
  87314. ** MergeEngine object in the usual fashion.
  87315. **
  87316. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  87317. ** objects attached to the PmaReader objects that the merger reads from have
  87318. ** already been populated, but that they have not yet populated aFile[0] and
  87319. ** set the PmaReader objects up to read from it. In this case all that is
  87320. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  87321. ** its first key.
  87322. **
  87323. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  87324. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  87325. ** to pMerger.
  87326. **
  87327. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  87328. */
  87329. static int vdbeMergeEngineInit(
  87330. SortSubtask *pTask, /* Thread that will run pMerger */
  87331. MergeEngine *pMerger, /* MergeEngine to initialize */
  87332. int eMode /* One of the INCRINIT_XXX constants */
  87333. ){
  87334. int rc = SQLITE_OK; /* Return code */
  87335. int i; /* For looping over PmaReader objects */
  87336. int nTree; /* Number of subtrees to merge */
  87337. /* Failure to allocate the merge would have been detected prior to
  87338. ** invoking this routine */
  87339. assert( pMerger!=0 );
  87340. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  87341. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  87342. /* Verify that the MergeEngine is assigned to a single thread */
  87343. assert( pMerger->pTask==0 );
  87344. pMerger->pTask = pTask;
  87345. nTree = pMerger->nTree;
  87346. for(i=0; i<nTree; i++){
  87347. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  87348. /* PmaReaders should be normally initialized in order, as if they are
  87349. ** reading from the same temp file this makes for more linear file IO.
  87350. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  87351. ** in use it will block the vdbePmaReaderNext() call while it uses
  87352. ** the main thread to fill its buffer. So calling PmaReaderNext()
  87353. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  87354. ** better advantage of multi-processor hardware. */
  87355. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  87356. }else{
  87357. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  87358. }
  87359. if( rc!=SQLITE_OK ) return rc;
  87360. }
  87361. for(i=pMerger->nTree-1; i>0; i--){
  87362. vdbeMergeEngineCompare(pMerger, i);
  87363. }
  87364. return pTask->pUnpacked->errCode;
  87365. }
  87366. /*
  87367. ** The PmaReader passed as the first argument is guaranteed to be an
  87368. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  87369. ** and/or initialize the temp file related fields of the IncrMerge
  87370. ** object at (pReadr->pIncr).
  87371. **
  87372. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  87373. ** in the sub-tree headed by pReadr are also initialized. Data is then
  87374. ** loaded into the buffers belonging to pReadr and it is set to point to
  87375. ** the first key in its range.
  87376. **
  87377. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  87378. ** to be a multi-threaded PmaReader and this function is being called in a
  87379. ** background thread. In this case all PmaReaders in the sub-tree are
  87380. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  87381. ** pReadr is populated. However, pReadr itself is not set up to point
  87382. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  87383. ** that.
  87384. **
  87385. ** The reason this function does not call vdbePmaReaderNext() immediately
  87386. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  87387. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  87388. ** this entire function is being run by thread (pTask->thread), that will
  87389. ** lead to the current background thread attempting to join itself.
  87390. **
  87391. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  87392. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  87393. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  87394. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  87395. ** the current PmaReader set to point to the first key in its range.
  87396. **
  87397. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  87398. */
  87399. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  87400. int rc = SQLITE_OK;
  87401. IncrMerger *pIncr = pReadr->pIncr;
  87402. SortSubtask *pTask = pIncr->pTask;
  87403. sqlite3 *db = pTask->pSorter->db;
  87404. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  87405. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  87406. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  87407. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  87408. ** requires two temp files to itself, whereas a single-threaded object
  87409. ** only requires a region of pTask->file2. */
  87410. if( rc==SQLITE_OK ){
  87411. int mxSz = pIncr->mxSz;
  87412. #if SQLITE_MAX_WORKER_THREADS>0
  87413. if( pIncr->bUseThread ){
  87414. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  87415. if( rc==SQLITE_OK ){
  87416. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  87417. }
  87418. }else
  87419. #endif
  87420. /*if( !pIncr->bUseThread )*/{
  87421. if( pTask->file2.pFd==0 ){
  87422. assert( pTask->file2.iEof>0 );
  87423. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  87424. pTask->file2.iEof = 0;
  87425. }
  87426. if( rc==SQLITE_OK ){
  87427. pIncr->aFile[1].pFd = pTask->file2.pFd;
  87428. pIncr->iStartOff = pTask->file2.iEof;
  87429. pTask->file2.iEof += mxSz;
  87430. }
  87431. }
  87432. }
  87433. #if SQLITE_MAX_WORKER_THREADS>0
  87434. if( rc==SQLITE_OK && pIncr->bUseThread ){
  87435. /* Use the current thread to populate aFile[1], even though this
  87436. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  87437. ** then this function is already running in background thread
  87438. ** pIncr->pTask->thread.
  87439. **
  87440. ** If this is the INCRINIT_ROOT object, then it is running in the
  87441. ** main VDBE thread. But that is Ok, as that thread cannot return
  87442. ** control to the VDBE or proceed with anything useful until the
  87443. ** first results are ready from this merger object anyway.
  87444. */
  87445. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  87446. rc = vdbeIncrPopulate(pIncr);
  87447. }
  87448. #endif
  87449. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  87450. rc = vdbePmaReaderNext(pReadr);
  87451. }
  87452. return rc;
  87453. }
  87454. #if SQLITE_MAX_WORKER_THREADS>0
  87455. /*
  87456. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  87457. ** background threads.
  87458. */
  87459. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  87460. PmaReader *pReader = (PmaReader*)pCtx;
  87461. void *pRet = SQLITE_INT_TO_PTR(
  87462. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  87463. );
  87464. pReader->pIncr->pTask->bDone = 1;
  87465. return pRet;
  87466. }
  87467. #endif
  87468. /*
  87469. ** If the PmaReader passed as the first argument is not an incremental-reader
  87470. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  87471. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  87472. ** this routine to initialize the incremental merge.
  87473. **
  87474. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  87475. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  87476. ** Or, if the IncrMerger is single threaded, the same function is called
  87477. ** using the current thread.
  87478. */
  87479. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  87480. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  87481. int rc = SQLITE_OK; /* Return code */
  87482. if( pIncr ){
  87483. #if SQLITE_MAX_WORKER_THREADS>0
  87484. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  87485. if( pIncr->bUseThread ){
  87486. void *pCtx = (void*)pReadr;
  87487. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  87488. }else
  87489. #endif
  87490. {
  87491. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  87492. }
  87493. }
  87494. return rc;
  87495. }
  87496. /*
  87497. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  87498. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  87499. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  87500. ** to NULL and return an SQLite error code.
  87501. **
  87502. ** When this function is called, *piOffset is set to the offset of the
  87503. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  87504. ** set to the offset immediately following the last byte of the last
  87505. ** PMA before returning. If an error does occur, then the final value of
  87506. ** *piOffset is undefined.
  87507. */
  87508. static int vdbeMergeEngineLevel0(
  87509. SortSubtask *pTask, /* Sorter task to read from */
  87510. int nPMA, /* Number of PMAs to read */
  87511. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  87512. MergeEngine **ppOut /* OUT: New merge-engine */
  87513. ){
  87514. MergeEngine *pNew; /* Merge engine to return */
  87515. i64 iOff = *piOffset;
  87516. int i;
  87517. int rc = SQLITE_OK;
  87518. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  87519. if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
  87520. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  87521. i64 nDummy = 0;
  87522. PmaReader *pReadr = &pNew->aReadr[i];
  87523. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  87524. iOff = pReadr->iEof;
  87525. }
  87526. if( rc!=SQLITE_OK ){
  87527. vdbeMergeEngineFree(pNew);
  87528. *ppOut = 0;
  87529. }
  87530. *piOffset = iOff;
  87531. return rc;
  87532. }
  87533. /*
  87534. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  87535. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  87536. **
  87537. ** i.e.
  87538. **
  87539. ** nPMA<=16 -> TreeDepth() == 0
  87540. ** nPMA<=256 -> TreeDepth() == 1
  87541. ** nPMA<=65536 -> TreeDepth() == 2
  87542. */
  87543. static int vdbeSorterTreeDepth(int nPMA){
  87544. int nDepth = 0;
  87545. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  87546. while( nDiv < (i64)nPMA ){
  87547. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  87548. nDepth++;
  87549. }
  87550. return nDepth;
  87551. }
  87552. /*
  87553. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  87554. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  87555. ** tree, counting from zero. This function adds pLeaf to the tree.
  87556. **
  87557. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  87558. ** code is returned and pLeaf is freed.
  87559. */
  87560. static int vdbeSorterAddToTree(
  87561. SortSubtask *pTask, /* Task context */
  87562. int nDepth, /* Depth of tree according to TreeDepth() */
  87563. int iSeq, /* Sequence number of leaf within tree */
  87564. MergeEngine *pRoot, /* Root of tree */
  87565. MergeEngine *pLeaf /* Leaf to add to tree */
  87566. ){
  87567. int rc = SQLITE_OK;
  87568. int nDiv = 1;
  87569. int i;
  87570. MergeEngine *p = pRoot;
  87571. IncrMerger *pIncr;
  87572. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  87573. for(i=1; i<nDepth; i++){
  87574. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  87575. }
  87576. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  87577. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  87578. PmaReader *pReadr = &p->aReadr[iIter];
  87579. if( pReadr->pIncr==0 ){
  87580. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  87581. if( pNew==0 ){
  87582. rc = SQLITE_NOMEM_BKPT;
  87583. }else{
  87584. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  87585. }
  87586. }
  87587. if( rc==SQLITE_OK ){
  87588. p = pReadr->pIncr->pMerger;
  87589. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  87590. }
  87591. }
  87592. if( rc==SQLITE_OK ){
  87593. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  87594. }else{
  87595. vdbeIncrFree(pIncr);
  87596. }
  87597. return rc;
  87598. }
  87599. /*
  87600. ** This function is called as part of a SorterRewind() operation on a sorter
  87601. ** that has already written two or more level-0 PMAs to one or more temp
  87602. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  87603. ** can be used to incrementally merge all PMAs on disk.
  87604. **
  87605. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  87606. ** MergeEngine object at the root of the tree before returning. Or, if an
  87607. ** error occurs, an SQLite error code is returned and the final value
  87608. ** of *ppOut is undefined.
  87609. */
  87610. static int vdbeSorterMergeTreeBuild(
  87611. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  87612. MergeEngine **ppOut /* Write the MergeEngine here */
  87613. ){
  87614. MergeEngine *pMain = 0;
  87615. int rc = SQLITE_OK;
  87616. int iTask;
  87617. #if SQLITE_MAX_WORKER_THREADS>0
  87618. /* If the sorter uses more than one task, then create the top-level
  87619. ** MergeEngine here. This MergeEngine will read data from exactly
  87620. ** one PmaReader per sub-task. */
  87621. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  87622. if( pSorter->nTask>1 ){
  87623. pMain = vdbeMergeEngineNew(pSorter->nTask);
  87624. if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
  87625. }
  87626. #endif
  87627. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  87628. SortSubtask *pTask = &pSorter->aTask[iTask];
  87629. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  87630. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  87631. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  87632. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  87633. i64 iReadOff = 0;
  87634. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  87635. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  87636. }else{
  87637. int i;
  87638. int iSeq = 0;
  87639. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  87640. if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
  87641. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  87642. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  87643. int nReader; /* Number of level-0 PMAs to merge */
  87644. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  87645. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  87646. if( rc==SQLITE_OK ){
  87647. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  87648. }
  87649. }
  87650. }
  87651. if( rc==SQLITE_OK ){
  87652. #if SQLITE_MAX_WORKER_THREADS>0
  87653. if( pMain!=0 ){
  87654. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  87655. }else
  87656. #endif
  87657. {
  87658. assert( pMain==0 );
  87659. pMain = pRoot;
  87660. }
  87661. }else{
  87662. vdbeMergeEngineFree(pRoot);
  87663. }
  87664. }
  87665. }
  87666. if( rc!=SQLITE_OK ){
  87667. vdbeMergeEngineFree(pMain);
  87668. pMain = 0;
  87669. }
  87670. *ppOut = pMain;
  87671. return rc;
  87672. }
  87673. /*
  87674. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  87675. ** on a sorter that has written two or more PMAs to temporary files. It sets
  87676. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  87677. ** (for multi-threaded sorters) so that it can be used to iterate through
  87678. ** all records stored in the sorter.
  87679. **
  87680. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  87681. */
  87682. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  87683. int rc; /* Return code */
  87684. SortSubtask *pTask0 = &pSorter->aTask[0];
  87685. MergeEngine *pMain = 0;
  87686. #if SQLITE_MAX_WORKER_THREADS
  87687. sqlite3 *db = pTask0->pSorter->db;
  87688. int i;
  87689. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  87690. for(i=0; i<pSorter->nTask; i++){
  87691. pSorter->aTask[i].xCompare = xCompare;
  87692. }
  87693. #endif
  87694. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  87695. if( rc==SQLITE_OK ){
  87696. #if SQLITE_MAX_WORKER_THREADS
  87697. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  87698. if( pSorter->bUseThreads ){
  87699. int iTask;
  87700. PmaReader *pReadr = 0;
  87701. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  87702. rc = vdbeSortAllocUnpacked(pLast);
  87703. if( rc==SQLITE_OK ){
  87704. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  87705. pSorter->pReader = pReadr;
  87706. if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
  87707. }
  87708. if( rc==SQLITE_OK ){
  87709. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  87710. if( rc==SQLITE_OK ){
  87711. vdbeIncrMergerSetThreads(pReadr->pIncr);
  87712. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  87713. IncrMerger *pIncr;
  87714. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  87715. vdbeIncrMergerSetThreads(pIncr);
  87716. assert( pIncr->pTask!=pLast );
  87717. }
  87718. }
  87719. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  87720. /* Check that:
  87721. **
  87722. ** a) The incremental merge object is configured to use the
  87723. ** right task, and
  87724. ** b) If it is using task (nTask-1), it is configured to run
  87725. ** in single-threaded mode. This is important, as the
  87726. ** root merge (INCRINIT_ROOT) will be using the same task
  87727. ** object.
  87728. */
  87729. PmaReader *p = &pMain->aReadr[iTask];
  87730. assert( p->pIncr==0 || (
  87731. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  87732. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  87733. ));
  87734. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  87735. }
  87736. }
  87737. pMain = 0;
  87738. }
  87739. if( rc==SQLITE_OK ){
  87740. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  87741. }
  87742. }else
  87743. #endif
  87744. {
  87745. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  87746. pSorter->pMerger = pMain;
  87747. pMain = 0;
  87748. }
  87749. }
  87750. if( rc!=SQLITE_OK ){
  87751. vdbeMergeEngineFree(pMain);
  87752. }
  87753. return rc;
  87754. }
  87755. /*
  87756. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  87757. ** this function is called to prepare for iterating through the records
  87758. ** in sorted order.
  87759. */
  87760. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  87761. VdbeSorter *pSorter;
  87762. int rc = SQLITE_OK; /* Return code */
  87763. assert( pCsr->eCurType==CURTYPE_SORTER );
  87764. pSorter = pCsr->uc.pSorter;
  87765. assert( pSorter );
  87766. /* If no data has been written to disk, then do not do so now. Instead,
  87767. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  87768. ** from the in-memory list. */
  87769. if( pSorter->bUsePMA==0 ){
  87770. if( pSorter->list.pList ){
  87771. *pbEof = 0;
  87772. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  87773. }else{
  87774. *pbEof = 1;
  87775. }
  87776. return rc;
  87777. }
  87778. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  87779. ** function flushes the contents of memory to disk, it immediately always
  87780. ** creates a new list consisting of a single key immediately afterwards.
  87781. ** So the list is never empty at this point. */
  87782. assert( pSorter->list.pList );
  87783. rc = vdbeSorterFlushPMA(pSorter);
  87784. /* Join all threads */
  87785. rc = vdbeSorterJoinAll(pSorter, rc);
  87786. vdbeSorterRewindDebug("rewind");
  87787. /* Assuming no errors have occurred, set up a merger structure to
  87788. ** incrementally read and merge all remaining PMAs. */
  87789. assert( pSorter->pReader==0 );
  87790. if( rc==SQLITE_OK ){
  87791. rc = vdbeSorterSetupMerge(pSorter);
  87792. *pbEof = 0;
  87793. }
  87794. vdbeSorterRewindDebug("rewinddone");
  87795. return rc;
  87796. }
  87797. /*
  87798. ** Advance to the next element in the sorter. Return value:
  87799. **
  87800. ** SQLITE_OK success
  87801. ** SQLITE_DONE end of data
  87802. ** otherwise some kind of error.
  87803. */
  87804. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
  87805. VdbeSorter *pSorter;
  87806. int rc; /* Return code */
  87807. assert( pCsr->eCurType==CURTYPE_SORTER );
  87808. pSorter = pCsr->uc.pSorter;
  87809. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  87810. if( pSorter->bUsePMA ){
  87811. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  87812. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  87813. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  87814. #if SQLITE_MAX_WORKER_THREADS>0
  87815. if( pSorter->bUseThreads ){
  87816. rc = vdbePmaReaderNext(pSorter->pReader);
  87817. if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
  87818. }else
  87819. #endif
  87820. /*if( !pSorter->bUseThreads )*/ {
  87821. int res = 0;
  87822. assert( pSorter->pMerger!=0 );
  87823. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  87824. rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
  87825. if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
  87826. }
  87827. }else{
  87828. SorterRecord *pFree = pSorter->list.pList;
  87829. pSorter->list.pList = pFree->u.pNext;
  87830. pFree->u.pNext = 0;
  87831. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  87832. rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
  87833. }
  87834. return rc;
  87835. }
  87836. /*
  87837. ** Return a pointer to a buffer owned by the sorter that contains the
  87838. ** current key.
  87839. */
  87840. static void *vdbeSorterRowkey(
  87841. const VdbeSorter *pSorter, /* Sorter object */
  87842. int *pnKey /* OUT: Size of current key in bytes */
  87843. ){
  87844. void *pKey;
  87845. if( pSorter->bUsePMA ){
  87846. PmaReader *pReader;
  87847. #if SQLITE_MAX_WORKER_THREADS>0
  87848. if( pSorter->bUseThreads ){
  87849. pReader = pSorter->pReader;
  87850. }else
  87851. #endif
  87852. /*if( !pSorter->bUseThreads )*/{
  87853. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  87854. }
  87855. *pnKey = pReader->nKey;
  87856. pKey = pReader->aKey;
  87857. }else{
  87858. *pnKey = pSorter->list.pList->nVal;
  87859. pKey = SRVAL(pSorter->list.pList);
  87860. }
  87861. return pKey;
  87862. }
  87863. /*
  87864. ** Copy the current sorter key into the memory cell pOut.
  87865. */
  87866. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  87867. VdbeSorter *pSorter;
  87868. void *pKey; int nKey; /* Sorter key to copy into pOut */
  87869. assert( pCsr->eCurType==CURTYPE_SORTER );
  87870. pSorter = pCsr->uc.pSorter;
  87871. pKey = vdbeSorterRowkey(pSorter, &nKey);
  87872. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  87873. return SQLITE_NOMEM_BKPT;
  87874. }
  87875. pOut->n = nKey;
  87876. MemSetTypeFlag(pOut, MEM_Blob);
  87877. memcpy(pOut->z, pKey, nKey);
  87878. return SQLITE_OK;
  87879. }
  87880. /*
  87881. ** Compare the key in memory cell pVal with the key that the sorter cursor
  87882. ** passed as the first argument currently points to. For the purposes of
  87883. ** the comparison, ignore the rowid field at the end of each record.
  87884. **
  87885. ** If the sorter cursor key contains any NULL values, consider it to be
  87886. ** less than pVal. Even if pVal also contains NULL values.
  87887. **
  87888. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  87889. ** Otherwise, set *pRes to a negative, zero or positive value if the
  87890. ** key in pVal is smaller than, equal to or larger than the current sorter
  87891. ** key.
  87892. **
  87893. ** This routine forms the core of the OP_SorterCompare opcode, which in
  87894. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  87895. */
  87896. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  87897. const VdbeCursor *pCsr, /* Sorter cursor */
  87898. Mem *pVal, /* Value to compare to current sorter key */
  87899. int nKeyCol, /* Compare this many columns */
  87900. int *pRes /* OUT: Result of comparison */
  87901. ){
  87902. VdbeSorter *pSorter;
  87903. UnpackedRecord *r2;
  87904. KeyInfo *pKeyInfo;
  87905. int i;
  87906. void *pKey; int nKey; /* Sorter key to compare pVal with */
  87907. assert( pCsr->eCurType==CURTYPE_SORTER );
  87908. pSorter = pCsr->uc.pSorter;
  87909. r2 = pSorter->pUnpacked;
  87910. pKeyInfo = pCsr->pKeyInfo;
  87911. if( r2==0 ){
  87912. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  87913. if( r2==0 ) return SQLITE_NOMEM_BKPT;
  87914. r2->nField = nKeyCol;
  87915. }
  87916. assert( r2->nField==nKeyCol );
  87917. pKey = vdbeSorterRowkey(pSorter, &nKey);
  87918. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  87919. for(i=0; i<nKeyCol; i++){
  87920. if( r2->aMem[i].flags & MEM_Null ){
  87921. *pRes = -1;
  87922. return SQLITE_OK;
  87923. }
  87924. }
  87925. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  87926. return SQLITE_OK;
  87927. }
  87928. /************** End of vdbesort.c ********************************************/
  87929. /************** Begin file memjournal.c **************************************/
  87930. /*
  87931. ** 2008 October 7
  87932. **
  87933. ** The author disclaims copyright to this source code. In place of
  87934. ** a legal notice, here is a blessing:
  87935. **
  87936. ** May you do good and not evil.
  87937. ** May you find forgiveness for yourself and forgive others.
  87938. ** May you share freely, never taking more than you give.
  87939. **
  87940. *************************************************************************
  87941. **
  87942. ** This file contains code use to implement an in-memory rollback journal.
  87943. ** The in-memory rollback journal is used to journal transactions for
  87944. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  87945. **
  87946. ** Update: The in-memory journal is also used to temporarily cache
  87947. ** smaller journals that are not critical for power-loss recovery.
  87948. ** For example, statement journals that are not too big will be held
  87949. ** entirely in memory, thus reducing the number of file I/O calls, and
  87950. ** more importantly, reducing temporary file creation events. If these
  87951. ** journals become too large for memory, they are spilled to disk. But
  87952. ** in the common case, they are usually small and no file I/O needs to
  87953. ** occur.
  87954. */
  87955. /* #include "sqliteInt.h" */
  87956. /* Forward references to internal structures */
  87957. typedef struct MemJournal MemJournal;
  87958. typedef struct FilePoint FilePoint;
  87959. typedef struct FileChunk FileChunk;
  87960. /*
  87961. ** The rollback journal is composed of a linked list of these structures.
  87962. **
  87963. ** The zChunk array is always at least 8 bytes in size - usually much more.
  87964. ** Its actual size is stored in the MemJournal.nChunkSize variable.
  87965. */
  87966. struct FileChunk {
  87967. FileChunk *pNext; /* Next chunk in the journal */
  87968. u8 zChunk[8]; /* Content of this chunk */
  87969. };
  87970. /*
  87971. ** By default, allocate this many bytes of memory for each FileChunk object.
  87972. */
  87973. #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
  87974. /*
  87975. ** For chunk size nChunkSize, return the number of bytes that should
  87976. ** be allocated for each FileChunk structure.
  87977. */
  87978. #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
  87979. /*
  87980. ** An instance of this object serves as a cursor into the rollback journal.
  87981. ** The cursor can be either for reading or writing.
  87982. */
  87983. struct FilePoint {
  87984. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  87985. FileChunk *pChunk; /* Specific chunk into which cursor points */
  87986. };
  87987. /*
  87988. ** This structure is a subclass of sqlite3_file. Each open memory-journal
  87989. ** is an instance of this class.
  87990. */
  87991. struct MemJournal {
  87992. const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  87993. int nChunkSize; /* In-memory chunk-size */
  87994. int nSpill; /* Bytes of data before flushing */
  87995. int nSize; /* Bytes of data currently in memory */
  87996. FileChunk *pFirst; /* Head of in-memory chunk-list */
  87997. FilePoint endpoint; /* Pointer to the end of the file */
  87998. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  87999. int flags; /* xOpen flags */
  88000. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  88001. const char *zJournal; /* Name of the journal file */
  88002. };
  88003. /*
  88004. ** Read data from the in-memory journal file. This is the implementation
  88005. ** of the sqlite3_vfs.xRead method.
  88006. */
  88007. static int memjrnlRead(
  88008. sqlite3_file *pJfd, /* The journal file from which to read */
  88009. void *zBuf, /* Put the results here */
  88010. int iAmt, /* Number of bytes to read */
  88011. sqlite_int64 iOfst /* Begin reading at this offset */
  88012. ){
  88013. MemJournal *p = (MemJournal *)pJfd;
  88014. u8 *zOut = zBuf;
  88015. int nRead = iAmt;
  88016. int iChunkOffset;
  88017. FileChunk *pChunk;
  88018. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  88019. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  88020. if( (iAmt+iOfst)>p->endpoint.iOffset ){
  88021. return SQLITE_IOERR_SHORT_READ;
  88022. }
  88023. #endif
  88024. assert( (iAmt+iOfst)<=p->endpoint.iOffset );
  88025. assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
  88026. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  88027. sqlite3_int64 iOff = 0;
  88028. for(pChunk=p->pFirst;
  88029. ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
  88030. pChunk=pChunk->pNext
  88031. ){
  88032. iOff += p->nChunkSize;
  88033. }
  88034. }else{
  88035. pChunk = p->readpoint.pChunk;
  88036. assert( pChunk!=0 );
  88037. }
  88038. iChunkOffset = (int)(iOfst%p->nChunkSize);
  88039. do {
  88040. int iSpace = p->nChunkSize - iChunkOffset;
  88041. int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
  88042. memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
  88043. zOut += nCopy;
  88044. nRead -= iSpace;
  88045. iChunkOffset = 0;
  88046. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  88047. p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
  88048. p->readpoint.pChunk = pChunk;
  88049. return SQLITE_OK;
  88050. }
  88051. /*
  88052. ** Free the list of FileChunk structures headed at MemJournal.pFirst.
  88053. */
  88054. static void memjrnlFreeChunks(MemJournal *p){
  88055. FileChunk *pIter;
  88056. FileChunk *pNext;
  88057. for(pIter=p->pFirst; pIter; pIter=pNext){
  88058. pNext = pIter->pNext;
  88059. sqlite3_free(pIter);
  88060. }
  88061. p->pFirst = 0;
  88062. }
  88063. /*
  88064. ** Flush the contents of memory to a real file on disk.
  88065. */
  88066. static int memjrnlCreateFile(MemJournal *p){
  88067. int rc;
  88068. sqlite3_file *pReal = (sqlite3_file*)p;
  88069. MemJournal copy = *p;
  88070. memset(p, 0, sizeof(MemJournal));
  88071. rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
  88072. if( rc==SQLITE_OK ){
  88073. int nChunk = copy.nChunkSize;
  88074. i64 iOff = 0;
  88075. FileChunk *pIter;
  88076. for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
  88077. if( iOff + nChunk > copy.endpoint.iOffset ){
  88078. nChunk = copy.endpoint.iOffset - iOff;
  88079. }
  88080. rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
  88081. if( rc ) break;
  88082. iOff += nChunk;
  88083. }
  88084. if( rc==SQLITE_OK ){
  88085. /* No error has occurred. Free the in-memory buffers. */
  88086. memjrnlFreeChunks(&copy);
  88087. }
  88088. }
  88089. if( rc!=SQLITE_OK ){
  88090. /* If an error occurred while creating or writing to the file, restore
  88091. ** the original before returning. This way, SQLite uses the in-memory
  88092. ** journal data to roll back changes made to the internal page-cache
  88093. ** before this function was called. */
  88094. sqlite3OsClose(pReal);
  88095. *p = copy;
  88096. }
  88097. return rc;
  88098. }
  88099. /*
  88100. ** Write data to the file.
  88101. */
  88102. static int memjrnlWrite(
  88103. sqlite3_file *pJfd, /* The journal file into which to write */
  88104. const void *zBuf, /* Take data to be written from here */
  88105. int iAmt, /* Number of bytes to write */
  88106. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  88107. ){
  88108. MemJournal *p = (MemJournal *)pJfd;
  88109. int nWrite = iAmt;
  88110. u8 *zWrite = (u8 *)zBuf;
  88111. /* If the file should be created now, create it and write the new data
  88112. ** into the file on disk. */
  88113. if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
  88114. int rc = memjrnlCreateFile(p);
  88115. if( rc==SQLITE_OK ){
  88116. rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
  88117. }
  88118. return rc;
  88119. }
  88120. /* If the contents of this write should be stored in memory */
  88121. else{
  88122. /* An in-memory journal file should only ever be appended to. Random
  88123. ** access writes are not required. The only exception to this is when
  88124. ** the in-memory journal is being used by a connection using the
  88125. ** atomic-write optimization. In this case the first 28 bytes of the
  88126. ** journal file may be written as part of committing the transaction. */
  88127. assert( iOfst==p->endpoint.iOffset || iOfst==0 );
  88128. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  88129. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  88130. if( iOfst==0 && p->pFirst ){
  88131. assert( p->nChunkSize>iAmt );
  88132. memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
  88133. }else
  88134. #else
  88135. assert( iOfst>0 || p->pFirst==0 );
  88136. #endif
  88137. {
  88138. while( nWrite>0 ){
  88139. FileChunk *pChunk = p->endpoint.pChunk;
  88140. int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
  88141. int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
  88142. if( iChunkOffset==0 ){
  88143. /* New chunk is required to extend the file. */
  88144. FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
  88145. if( !pNew ){
  88146. return SQLITE_IOERR_NOMEM_BKPT;
  88147. }
  88148. pNew->pNext = 0;
  88149. if( pChunk ){
  88150. assert( p->pFirst );
  88151. pChunk->pNext = pNew;
  88152. }else{
  88153. assert( !p->pFirst );
  88154. p->pFirst = pNew;
  88155. }
  88156. p->endpoint.pChunk = pNew;
  88157. }
  88158. memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
  88159. zWrite += iSpace;
  88160. nWrite -= iSpace;
  88161. p->endpoint.iOffset += iSpace;
  88162. }
  88163. p->nSize = iAmt + iOfst;
  88164. }
  88165. }
  88166. return SQLITE_OK;
  88167. }
  88168. /*
  88169. ** Truncate the file.
  88170. **
  88171. ** If the journal file is already on disk, truncate it there. Or, if it
  88172. ** is still in main memory but is being truncated to zero bytes in size,
  88173. ** ignore
  88174. */
  88175. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  88176. MemJournal *p = (MemJournal *)pJfd;
  88177. if( ALWAYS(size==0) ){
  88178. memjrnlFreeChunks(p);
  88179. p->nSize = 0;
  88180. p->endpoint.pChunk = 0;
  88181. p->endpoint.iOffset = 0;
  88182. p->readpoint.pChunk = 0;
  88183. p->readpoint.iOffset = 0;
  88184. }
  88185. return SQLITE_OK;
  88186. }
  88187. /*
  88188. ** Close the file.
  88189. */
  88190. static int memjrnlClose(sqlite3_file *pJfd){
  88191. MemJournal *p = (MemJournal *)pJfd;
  88192. memjrnlFreeChunks(p);
  88193. return SQLITE_OK;
  88194. }
  88195. /*
  88196. ** Sync the file.
  88197. **
  88198. ** If the real file has been created, call its xSync method. Otherwise,
  88199. ** syncing an in-memory journal is a no-op.
  88200. */
  88201. static int memjrnlSync(sqlite3_file *pJfd, int flags){
  88202. UNUSED_PARAMETER2(pJfd, flags);
  88203. return SQLITE_OK;
  88204. }
  88205. /*
  88206. ** Query the size of the file in bytes.
  88207. */
  88208. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  88209. MemJournal *p = (MemJournal *)pJfd;
  88210. *pSize = (sqlite_int64) p->endpoint.iOffset;
  88211. return SQLITE_OK;
  88212. }
  88213. /*
  88214. ** Table of methods for MemJournal sqlite3_file object.
  88215. */
  88216. static const struct sqlite3_io_methods MemJournalMethods = {
  88217. 1, /* iVersion */
  88218. memjrnlClose, /* xClose */
  88219. memjrnlRead, /* xRead */
  88220. memjrnlWrite, /* xWrite */
  88221. memjrnlTruncate, /* xTruncate */
  88222. memjrnlSync, /* xSync */
  88223. memjrnlFileSize, /* xFileSize */
  88224. 0, /* xLock */
  88225. 0, /* xUnlock */
  88226. 0, /* xCheckReservedLock */
  88227. 0, /* xFileControl */
  88228. 0, /* xSectorSize */
  88229. 0, /* xDeviceCharacteristics */
  88230. 0, /* xShmMap */
  88231. 0, /* xShmLock */
  88232. 0, /* xShmBarrier */
  88233. 0, /* xShmUnmap */
  88234. 0, /* xFetch */
  88235. 0 /* xUnfetch */
  88236. };
  88237. /*
  88238. ** Open a journal file.
  88239. **
  88240. ** The behaviour of the journal file depends on the value of parameter
  88241. ** nSpill. If nSpill is 0, then the journal file is always create and
  88242. ** accessed using the underlying VFS. If nSpill is less than zero, then
  88243. ** all content is always stored in main-memory. Finally, if nSpill is a
  88244. ** positive value, then the journal file is initially created in-memory
  88245. ** but may be flushed to disk later on. In this case the journal file is
  88246. ** flushed to disk either when it grows larger than nSpill bytes in size,
  88247. ** or when sqlite3JournalCreate() is called.
  88248. */
  88249. SQLITE_PRIVATE int sqlite3JournalOpen(
  88250. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  88251. const char *zName, /* Name of the journal file */
  88252. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  88253. int flags, /* Opening flags */
  88254. int nSpill /* Bytes buffered before opening the file */
  88255. ){
  88256. MemJournal *p = (MemJournal*)pJfd;
  88257. /* Zero the file-handle object. If nSpill was passed zero, initialize
  88258. ** it using the sqlite3OsOpen() function of the underlying VFS. In this
  88259. ** case none of the code in this module is executed as a result of calls
  88260. ** made on the journal file-handle. */
  88261. memset(p, 0, sizeof(MemJournal));
  88262. if( nSpill==0 ){
  88263. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  88264. }
  88265. if( nSpill>0 ){
  88266. p->nChunkSize = nSpill;
  88267. }else{
  88268. p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
  88269. assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
  88270. }
  88271. p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
  88272. p->nSpill = nSpill;
  88273. p->flags = flags;
  88274. p->zJournal = zName;
  88275. p->pVfs = pVfs;
  88276. return SQLITE_OK;
  88277. }
  88278. /*
  88279. ** Open an in-memory journal file.
  88280. */
  88281. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  88282. sqlite3JournalOpen(0, 0, pJfd, 0, -1);
  88283. }
  88284. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  88285. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  88286. /*
  88287. ** If the argument p points to a MemJournal structure that is not an
  88288. ** in-memory-only journal file (i.e. is one that was opened with a +ve
  88289. ** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
  88290. ** file has not yet been created, create it now.
  88291. */
  88292. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
  88293. int rc = SQLITE_OK;
  88294. MemJournal *p = (MemJournal*)pJfd;
  88295. if( p->pMethod==&MemJournalMethods && (
  88296. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  88297. p->nSpill>0
  88298. #else
  88299. /* While this appears to not be possible without ATOMIC_WRITE, the
  88300. ** paths are complex, so it seems prudent to leave the test in as
  88301. ** a NEVER(), in case our analysis is subtly flawed. */
  88302. NEVER(p->nSpill>0)
  88303. #endif
  88304. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  88305. || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
  88306. #endif
  88307. )){
  88308. rc = memjrnlCreateFile(p);
  88309. }
  88310. return rc;
  88311. }
  88312. #endif
  88313. /*
  88314. ** The file-handle passed as the only argument is open on a journal file.
  88315. ** Return true if this "journal file" is currently stored in heap memory,
  88316. ** or false otherwise.
  88317. */
  88318. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
  88319. return p->pMethods==&MemJournalMethods;
  88320. }
  88321. /*
  88322. ** Return the number of bytes required to store a JournalFile that uses vfs
  88323. ** pVfs to create the underlying on-disk files.
  88324. */
  88325. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  88326. return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
  88327. }
  88328. /************** End of memjournal.c ******************************************/
  88329. /************** Begin file walker.c ******************************************/
  88330. /*
  88331. ** 2008 August 16
  88332. **
  88333. ** The author disclaims copyright to this source code. In place of
  88334. ** a legal notice, here is a blessing:
  88335. **
  88336. ** May you do good and not evil.
  88337. ** May you find forgiveness for yourself and forgive others.
  88338. ** May you share freely, never taking more than you give.
  88339. **
  88340. *************************************************************************
  88341. ** This file contains routines used for walking the parser tree for
  88342. ** an SQL statement.
  88343. */
  88344. /* #include "sqliteInt.h" */
  88345. /* #include <stdlib.h> */
  88346. /* #include <string.h> */
  88347. /*
  88348. ** Walk an expression tree. Invoke the callback once for each node
  88349. ** of the expression, while descending. (In other words, the callback
  88350. ** is invoked before visiting children.)
  88351. **
  88352. ** The return value from the callback should be one of the WRC_*
  88353. ** constants to specify how to proceed with the walk.
  88354. **
  88355. ** WRC_Continue Continue descending down the tree.
  88356. **
  88357. ** WRC_Prune Do not descend into child nodes, but allow
  88358. ** the walk to continue with sibling nodes.
  88359. **
  88360. ** WRC_Abort Do no more callbacks. Unwind the stack and
  88361. ** return from the top-level walk call.
  88362. **
  88363. ** The return value from this routine is WRC_Abort to abandon the tree walk
  88364. ** and WRC_Continue to continue.
  88365. */
  88366. static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
  88367. int rc;
  88368. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  88369. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  88370. while(1){
  88371. rc = pWalker->xExprCallback(pWalker, pExpr);
  88372. if( rc ) return rc & WRC_Abort;
  88373. if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
  88374. if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  88375. assert( pExpr->x.pList==0 || pExpr->pRight==0 );
  88376. if( pExpr->pRight ){
  88377. pExpr = pExpr->pRight;
  88378. continue;
  88379. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  88380. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  88381. }else if( pExpr->x.pList ){
  88382. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  88383. }
  88384. #ifndef SQLITE_OMIT_WINDOWFUNC
  88385. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  88386. Window *pWin = pExpr->y.pWin;
  88387. if( sqlite3WalkExprList(pWalker, pWin->pPartition) ) return WRC_Abort;
  88388. if( sqlite3WalkExprList(pWalker, pWin->pOrderBy) ) return WRC_Abort;
  88389. if( sqlite3WalkExpr(pWalker, pWin->pFilter) ) return WRC_Abort;
  88390. }
  88391. #endif
  88392. }
  88393. break;
  88394. }
  88395. return WRC_Continue;
  88396. }
  88397. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  88398. return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
  88399. }
  88400. /*
  88401. ** Call sqlite3WalkExpr() for every expression in list p or until
  88402. ** an abort request is seen.
  88403. */
  88404. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  88405. int i;
  88406. struct ExprList_item *pItem;
  88407. if( p ){
  88408. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  88409. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  88410. }
  88411. }
  88412. return WRC_Continue;
  88413. }
  88414. /*
  88415. ** Walk all expressions associated with SELECT statement p. Do
  88416. ** not invoke the SELECT callback on p, but do (of course) invoke
  88417. ** any expr callbacks and SELECT callbacks that come from subqueries.
  88418. ** Return WRC_Abort or WRC_Continue.
  88419. */
  88420. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  88421. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  88422. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  88423. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  88424. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  88425. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  88426. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  88427. return WRC_Continue;
  88428. }
  88429. /*
  88430. ** Walk the parse trees associated with all subqueries in the
  88431. ** FROM clause of SELECT statement p. Do not invoke the select
  88432. ** callback on p, but do invoke it on each FROM clause subquery
  88433. ** and on any subqueries further down in the tree. Return
  88434. ** WRC_Abort or WRC_Continue;
  88435. */
  88436. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  88437. SrcList *pSrc;
  88438. int i;
  88439. struct SrcList_item *pItem;
  88440. pSrc = p->pSrc;
  88441. assert( pSrc!=0 );
  88442. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  88443. if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  88444. return WRC_Abort;
  88445. }
  88446. if( pItem->fg.isTabFunc
  88447. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  88448. ){
  88449. return WRC_Abort;
  88450. }
  88451. }
  88452. return WRC_Continue;
  88453. }
  88454. /*
  88455. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  88456. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  88457. ** on the compound select chain, p->pPrior.
  88458. **
  88459. ** If it is not NULL, the xSelectCallback() callback is invoked before
  88460. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  88461. ** method is invoked following the walk of the expressions and FROM clause,
  88462. ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
  88463. ** and if the expressions and FROM clause both return WRC_Continue;
  88464. **
  88465. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  88466. ** there is an abort request.
  88467. **
  88468. ** If the Walker does not have an xSelectCallback() then this routine
  88469. ** is a no-op returning WRC_Continue.
  88470. */
  88471. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  88472. int rc;
  88473. if( p==0 ) return WRC_Continue;
  88474. if( pWalker->xSelectCallback==0 ) return WRC_Continue;
  88475. do{
  88476. rc = pWalker->xSelectCallback(pWalker, p);
  88477. if( rc ) return rc & WRC_Abort;
  88478. if( sqlite3WalkSelectExpr(pWalker, p)
  88479. || sqlite3WalkSelectFrom(pWalker, p)
  88480. ){
  88481. return WRC_Abort;
  88482. }
  88483. if( pWalker->xSelectCallback2 ){
  88484. pWalker->xSelectCallback2(pWalker, p);
  88485. }
  88486. p = p->pPrior;
  88487. }while( p!=0 );
  88488. return WRC_Continue;
  88489. }
  88490. /************** End of walker.c **********************************************/
  88491. /************** Begin file resolve.c *****************************************/
  88492. /*
  88493. ** 2008 August 18
  88494. **
  88495. ** The author disclaims copyright to this source code. In place of
  88496. ** a legal notice, here is a blessing:
  88497. **
  88498. ** May you do good and not evil.
  88499. ** May you find forgiveness for yourself and forgive others.
  88500. ** May you share freely, never taking more than you give.
  88501. **
  88502. *************************************************************************
  88503. **
  88504. ** This file contains routines used for walking the parser tree and
  88505. ** resolve all identifiers by associating them with a particular
  88506. ** table and column.
  88507. */
  88508. /* #include "sqliteInt.h" */
  88509. /*
  88510. ** Walk the expression tree pExpr and increase the aggregate function
  88511. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  88512. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  88513. ** outer query into an inner subquery.
  88514. **
  88515. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  88516. ** is a helper function - a callback for the tree walker.
  88517. */
  88518. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  88519. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  88520. return WRC_Continue;
  88521. }
  88522. static void incrAggFunctionDepth(Expr *pExpr, int N){
  88523. if( N>0 ){
  88524. Walker w;
  88525. memset(&w, 0, sizeof(w));
  88526. w.xExprCallback = incrAggDepth;
  88527. w.u.n = N;
  88528. sqlite3WalkExpr(&w, pExpr);
  88529. }
  88530. }
  88531. /*
  88532. ** Turn the pExpr expression into an alias for the iCol-th column of the
  88533. ** result set in pEList.
  88534. **
  88535. ** If the reference is followed by a COLLATE operator, then make sure
  88536. ** the COLLATE operator is preserved. For example:
  88537. **
  88538. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  88539. **
  88540. ** Should be transformed into:
  88541. **
  88542. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  88543. **
  88544. ** The nSubquery parameter specifies how many levels of subquery the
  88545. ** alias is removed from the original expression. The usual value is
  88546. ** zero but it might be more if the alias is contained within a subquery
  88547. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  88548. ** structures must be increased by the nSubquery amount.
  88549. */
  88550. static void resolveAlias(
  88551. Parse *pParse, /* Parsing context */
  88552. ExprList *pEList, /* A result set */
  88553. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  88554. Expr *pExpr, /* Transform this into an alias to the result set */
  88555. const char *zType, /* "GROUP" or "ORDER" or "" */
  88556. int nSubquery /* Number of subqueries that the label is moving */
  88557. ){
  88558. Expr *pOrig; /* The iCol-th column of the result set */
  88559. Expr *pDup; /* Copy of pOrig */
  88560. sqlite3 *db; /* The database connection */
  88561. assert( iCol>=0 && iCol<pEList->nExpr );
  88562. pOrig = pEList->a[iCol].pExpr;
  88563. assert( pOrig!=0 );
  88564. db = pParse->db;
  88565. pDup = sqlite3ExprDup(db, pOrig, 0);
  88566. if( pDup!=0 ){
  88567. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  88568. if( pExpr->op==TK_COLLATE ){
  88569. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  88570. }
  88571. ExprSetProperty(pDup, EP_Alias);
  88572. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  88573. ** prevents ExprDelete() from deleting the Expr structure itself,
  88574. ** allowing it to be repopulated by the memcpy() on the following line.
  88575. ** The pExpr->u.zToken might point into memory that will be freed by the
  88576. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  88577. ** make a copy of the token before doing the sqlite3DbFree().
  88578. */
  88579. ExprSetProperty(pExpr, EP_Static);
  88580. sqlite3ExprDelete(db, pExpr);
  88581. memcpy(pExpr, pDup, sizeof(*pExpr));
  88582. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  88583. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  88584. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  88585. pExpr->flags |= EP_MemToken;
  88586. }
  88587. sqlite3DbFree(db, pDup);
  88588. }
  88589. ExprSetProperty(pExpr, EP_Alias);
  88590. }
  88591. /*
  88592. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  88593. **
  88594. ** Return FALSE if the USING clause is NULL or if it does not contain
  88595. ** zCol.
  88596. */
  88597. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  88598. if( pUsing ){
  88599. int k;
  88600. for(k=0; k<pUsing->nId; k++){
  88601. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  88602. }
  88603. }
  88604. return 0;
  88605. }
  88606. /*
  88607. ** Subqueries stores the original database, table and column names for their
  88608. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  88609. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  88610. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  88611. ** match anything.
  88612. */
  88613. SQLITE_PRIVATE int sqlite3MatchSpanName(
  88614. const char *zSpan,
  88615. const char *zCol,
  88616. const char *zTab,
  88617. const char *zDb
  88618. ){
  88619. int n;
  88620. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  88621. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  88622. return 0;
  88623. }
  88624. zSpan += n+1;
  88625. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  88626. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  88627. return 0;
  88628. }
  88629. zSpan += n+1;
  88630. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  88631. return 0;
  88632. }
  88633. return 1;
  88634. }
  88635. /*
  88636. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  88637. ** that name in the set of source tables in pSrcList and make the pExpr
  88638. ** expression node refer back to that source column. The following changes
  88639. ** are made to pExpr:
  88640. **
  88641. ** pExpr->iDb Set the index in db->aDb[] of the database X
  88642. ** (even if X is implied).
  88643. ** pExpr->iTable Set to the cursor number for the table obtained
  88644. ** from pSrcList.
  88645. ** pExpr->y.pTab Points to the Table structure of X.Y (even if
  88646. ** X and/or Y are implied.)
  88647. ** pExpr->iColumn Set to the column number within the table.
  88648. ** pExpr->op Set to TK_COLUMN.
  88649. ** pExpr->pLeft Any expression this points to is deleted
  88650. ** pExpr->pRight Any expression this points to is deleted.
  88651. **
  88652. ** The zDb variable is the name of the database (the "X"). This value may be
  88653. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  88654. ** can be used. The zTable variable is the name of the table (the "Y"). This
  88655. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  88656. ** means that the form of the name is Z and that columns from any table
  88657. ** can be used.
  88658. **
  88659. ** If the name cannot be resolved unambiguously, leave an error message
  88660. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  88661. */
  88662. static int lookupName(
  88663. Parse *pParse, /* The parsing context */
  88664. const char *zDb, /* Name of the database containing table, or NULL */
  88665. const char *zTab, /* Name of table containing column, or NULL */
  88666. const char *zCol, /* Name of the column. */
  88667. NameContext *pNC, /* The name context used to resolve the name */
  88668. Expr *pExpr /* Make this EXPR node point to the selected column */
  88669. ){
  88670. int i, j; /* Loop counters */
  88671. int cnt = 0; /* Number of matching column names */
  88672. int cntTab = 0; /* Number of matching table names */
  88673. int nSubquery = 0; /* How many levels of subquery */
  88674. sqlite3 *db = pParse->db; /* The database connection */
  88675. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  88676. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  88677. NameContext *pTopNC = pNC; /* First namecontext in the list */
  88678. Schema *pSchema = 0; /* Schema of the expression */
  88679. int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
  88680. Table *pTab = 0; /* Table hold the row */
  88681. Column *pCol; /* A column of pTab */
  88682. assert( pNC ); /* the name context cannot be NULL. */
  88683. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  88684. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  88685. /* Initialize the node to no-match */
  88686. pExpr->iTable = -1;
  88687. ExprSetVVAProperty(pExpr, EP_NoReduce);
  88688. /* Translate the schema name in zDb into a pointer to the corresponding
  88689. ** schema. If not found, pSchema will remain NULL and nothing will match
  88690. ** resulting in an appropriate error message toward the end of this routine
  88691. */
  88692. if( zDb ){
  88693. testcase( pNC->ncFlags & NC_PartIdx );
  88694. testcase( pNC->ncFlags & NC_IsCheck );
  88695. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  88696. /* Silently ignore database qualifiers inside CHECK constraints and
  88697. ** partial indices. Do not raise errors because that might break
  88698. ** legacy and because it does not hurt anything to just ignore the
  88699. ** database name. */
  88700. zDb = 0;
  88701. }else{
  88702. for(i=0; i<db->nDb; i++){
  88703. assert( db->aDb[i].zDbSName );
  88704. if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
  88705. pSchema = db->aDb[i].pSchema;
  88706. break;
  88707. }
  88708. }
  88709. }
  88710. }
  88711. /* Start at the inner-most context and move outward until a match is found */
  88712. assert( pNC && cnt==0 );
  88713. do{
  88714. ExprList *pEList;
  88715. SrcList *pSrcList = pNC->pSrcList;
  88716. if( pSrcList ){
  88717. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  88718. pTab = pItem->pTab;
  88719. assert( pTab!=0 && pTab->zName!=0 );
  88720. assert( pTab->nCol>0 );
  88721. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  88722. int hit = 0;
  88723. pEList = pItem->pSelect->pEList;
  88724. for(j=0; j<pEList->nExpr; j++){
  88725. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  88726. cnt++;
  88727. cntTab = 2;
  88728. pMatch = pItem;
  88729. pExpr->iColumn = j;
  88730. hit = 1;
  88731. }
  88732. }
  88733. if( hit || zTab==0 ) continue;
  88734. }
  88735. if( zDb && pTab->pSchema!=pSchema ){
  88736. continue;
  88737. }
  88738. if( zTab ){
  88739. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  88740. assert( zTabName!=0 );
  88741. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  88742. continue;
  88743. }
  88744. if( IN_RENAME_OBJECT && pItem->zAlias ){
  88745. sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
  88746. }
  88747. }
  88748. if( 0==(cntTab++) ){
  88749. pMatch = pItem;
  88750. }
  88751. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  88752. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  88753. /* If there has been exactly one prior match and this match
  88754. ** is for the right-hand table of a NATURAL JOIN or is in a
  88755. ** USING clause, then skip this match.
  88756. */
  88757. if( cnt==1 ){
  88758. if( pItem->fg.jointype & JT_NATURAL ) continue;
  88759. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  88760. }
  88761. cnt++;
  88762. pMatch = pItem;
  88763. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  88764. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  88765. break;
  88766. }
  88767. }
  88768. }
  88769. if( pMatch ){
  88770. pExpr->iTable = pMatch->iCursor;
  88771. pExpr->y.pTab = pMatch->pTab;
  88772. /* RIGHT JOIN not (yet) supported */
  88773. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  88774. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  88775. ExprSetProperty(pExpr, EP_CanBeNull);
  88776. }
  88777. pSchema = pExpr->y.pTab->pSchema;
  88778. }
  88779. } /* if( pSrcList ) */
  88780. #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
  88781. /* If we have not already resolved the name, then maybe
  88782. ** it is a new.* or old.* trigger argument reference. Or
  88783. ** maybe it is an excluded.* from an upsert.
  88784. */
  88785. if( zDb==0 && zTab!=0 && cntTab==0 ){
  88786. pTab = 0;
  88787. #ifndef SQLITE_OMIT_TRIGGER
  88788. if( pParse->pTriggerTab!=0 ){
  88789. int op = pParse->eTriggerOp;
  88790. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  88791. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  88792. pExpr->iTable = 1;
  88793. pTab = pParse->pTriggerTab;
  88794. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  88795. pExpr->iTable = 0;
  88796. pTab = pParse->pTriggerTab;
  88797. }
  88798. }
  88799. #endif /* SQLITE_OMIT_TRIGGER */
  88800. #ifndef SQLITE_OMIT_UPSERT
  88801. if( (pNC->ncFlags & NC_UUpsert)!=0 ){
  88802. Upsert *pUpsert = pNC->uNC.pUpsert;
  88803. if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
  88804. pTab = pUpsert->pUpsertSrc->a[0].pTab;
  88805. pExpr->iTable = 2;
  88806. }
  88807. }
  88808. #endif /* SQLITE_OMIT_UPSERT */
  88809. if( pTab ){
  88810. int iCol;
  88811. pSchema = pTab->pSchema;
  88812. cntTab++;
  88813. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  88814. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  88815. if( iCol==pTab->iPKey ){
  88816. iCol = -1;
  88817. }
  88818. break;
  88819. }
  88820. }
  88821. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  88822. /* IMP: R-51414-32910 */
  88823. iCol = -1;
  88824. }
  88825. if( iCol<pTab->nCol ){
  88826. cnt++;
  88827. #ifndef SQLITE_OMIT_UPSERT
  88828. if( pExpr->iTable==2 ){
  88829. testcase( iCol==(-1) );
  88830. if( IN_RENAME_OBJECT ){
  88831. pExpr->iColumn = iCol;
  88832. pExpr->y.pTab = pTab;
  88833. eNewExprOp = TK_COLUMN;
  88834. }else{
  88835. pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;
  88836. eNewExprOp = TK_REGISTER;
  88837. ExprSetProperty(pExpr, EP_Alias);
  88838. }
  88839. }else
  88840. #endif /* SQLITE_OMIT_UPSERT */
  88841. {
  88842. #ifndef SQLITE_OMIT_TRIGGER
  88843. if( iCol<0 ){
  88844. pExpr->affinity = SQLITE_AFF_INTEGER;
  88845. }else if( pExpr->iTable==0 ){
  88846. testcase( iCol==31 );
  88847. testcase( iCol==32 );
  88848. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  88849. }else{
  88850. testcase( iCol==31 );
  88851. testcase( iCol==32 );
  88852. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  88853. }
  88854. pExpr->y.pTab = pTab;
  88855. pExpr->iColumn = (i16)iCol;
  88856. eNewExprOp = TK_TRIGGER;
  88857. #endif /* SQLITE_OMIT_TRIGGER */
  88858. }
  88859. }
  88860. }
  88861. }
  88862. #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
  88863. /*
  88864. ** Perhaps the name is a reference to the ROWID
  88865. */
  88866. if( cnt==0
  88867. && cntTab==1
  88868. && pMatch
  88869. && (pNC->ncFlags & NC_IdxExpr)==0
  88870. && sqlite3IsRowid(zCol)
  88871. && VisibleRowid(pMatch->pTab)
  88872. ){
  88873. cnt = 1;
  88874. pExpr->iColumn = -1;
  88875. pExpr->affinity = SQLITE_AFF_INTEGER;
  88876. }
  88877. /*
  88878. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  88879. ** might refer to an result-set alias. This happens, for example, when
  88880. ** we are resolving names in the WHERE clause of the following command:
  88881. **
  88882. ** SELECT a+b AS x FROM table WHERE x<10;
  88883. **
  88884. ** In cases like this, replace pExpr with a copy of the expression that
  88885. ** forms the result set entry ("a+b" in the example) and return immediately.
  88886. ** Note that the expression in the result set should have already been
  88887. ** resolved by the time the WHERE clause is resolved.
  88888. **
  88889. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  88890. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  88891. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  88892. ** is supported for backwards compatibility only. Hence, we issue a warning
  88893. ** on sqlite3_log() whenever the capability is used.
  88894. */
  88895. if( (pNC->ncFlags & NC_UEList)!=0
  88896. && cnt==0
  88897. && zTab==0
  88898. ){
  88899. pEList = pNC->uNC.pEList;
  88900. assert( pEList!=0 );
  88901. for(j=0; j<pEList->nExpr; j++){
  88902. char *zAs = pEList->a[j].zName;
  88903. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  88904. Expr *pOrig;
  88905. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  88906. assert( pExpr->x.pList==0 );
  88907. assert( pExpr->x.pSelect==0 );
  88908. pOrig = pEList->a[j].pExpr;
  88909. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  88910. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  88911. return WRC_Abort;
  88912. }
  88913. if( sqlite3ExprVectorSize(pOrig)!=1 ){
  88914. sqlite3ErrorMsg(pParse, "row value misused");
  88915. return WRC_Abort;
  88916. }
  88917. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  88918. cnt = 1;
  88919. pMatch = 0;
  88920. assert( zTab==0 && zDb==0 );
  88921. if( IN_RENAME_OBJECT ){
  88922. sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
  88923. }
  88924. goto lookupname_end;
  88925. }
  88926. }
  88927. }
  88928. /* Advance to the next name context. The loop will exit when either
  88929. ** we have a match (cnt>0) or when we run out of name contexts.
  88930. */
  88931. if( cnt ) break;
  88932. pNC = pNC->pNext;
  88933. nSubquery++;
  88934. }while( pNC );
  88935. /*
  88936. ** If X and Y are NULL (in other words if only the column name Z is
  88937. ** supplied) and the value of Z is enclosed in double-quotes, then
  88938. ** Z is a string literal if it doesn't match any column names. In that
  88939. ** case, we need to return right away and not make any changes to
  88940. ** pExpr.
  88941. **
  88942. ** Because no reference was made to outer contexts, the pNC->nRef
  88943. ** fields are not changed in any context.
  88944. */
  88945. if( cnt==0 && zTab==0 ){
  88946. assert( pExpr->op==TK_ID );
  88947. if( ExprHasProperty(pExpr,EP_DblQuoted) ){
  88948. pExpr->op = TK_STRING;
  88949. pExpr->y.pTab = 0;
  88950. return WRC_Prune;
  88951. }
  88952. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  88953. return WRC_Prune;
  88954. }
  88955. }
  88956. /*
  88957. ** cnt==0 means there was not match. cnt>1 means there were two or
  88958. ** more matches. Either way, we have an error.
  88959. */
  88960. if( cnt!=1 ){
  88961. const char *zErr;
  88962. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  88963. if( zDb ){
  88964. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  88965. }else if( zTab ){
  88966. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  88967. }else{
  88968. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  88969. }
  88970. pParse->checkSchema = 1;
  88971. pTopNC->nErr++;
  88972. }
  88973. /* If a column from a table in pSrcList is referenced, then record
  88974. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  88975. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  88976. ** column number is greater than the number of bits in the bitmask
  88977. ** then set the high-order bit of the bitmask.
  88978. */
  88979. if( pExpr->iColumn>=0 && pMatch!=0 ){
  88980. int n = pExpr->iColumn;
  88981. testcase( n==BMS-1 );
  88982. if( n>=BMS ){
  88983. n = BMS-1;
  88984. }
  88985. assert( pMatch->iCursor==pExpr->iTable );
  88986. pMatch->colUsed |= ((Bitmask)1)<<n;
  88987. }
  88988. /* Clean up and return
  88989. */
  88990. sqlite3ExprDelete(db, pExpr->pLeft);
  88991. pExpr->pLeft = 0;
  88992. sqlite3ExprDelete(db, pExpr->pRight);
  88993. pExpr->pRight = 0;
  88994. pExpr->op = eNewExprOp;
  88995. ExprSetProperty(pExpr, EP_Leaf);
  88996. lookupname_end:
  88997. if( cnt==1 ){
  88998. assert( pNC!=0 );
  88999. if( !ExprHasProperty(pExpr, EP_Alias) ){
  89000. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  89001. }
  89002. /* Increment the nRef value on all name contexts from TopNC up to
  89003. ** the point where the name matched. */
  89004. for(;;){
  89005. assert( pTopNC!=0 );
  89006. pTopNC->nRef++;
  89007. if( pTopNC==pNC ) break;
  89008. pTopNC = pTopNC->pNext;
  89009. }
  89010. return WRC_Prune;
  89011. } else {
  89012. return WRC_Abort;
  89013. }
  89014. }
  89015. /*
  89016. ** Allocate and return a pointer to an expression to load the column iCol
  89017. ** from datasource iSrc in SrcList pSrc.
  89018. */
  89019. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  89020. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  89021. if( p ){
  89022. struct SrcList_item *pItem = &pSrc->a[iSrc];
  89023. p->y.pTab = pItem->pTab;
  89024. p->iTable = pItem->iCursor;
  89025. if( p->y.pTab->iPKey==iCol ){
  89026. p->iColumn = -1;
  89027. }else{
  89028. p->iColumn = (ynVar)iCol;
  89029. testcase( iCol==BMS );
  89030. testcase( iCol==BMS-1 );
  89031. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  89032. }
  89033. }
  89034. return p;
  89035. }
  89036. /*
  89037. ** Report an error that an expression is not valid for some set of
  89038. ** pNC->ncFlags values determined by validMask.
  89039. */
  89040. static void notValid(
  89041. Parse *pParse, /* Leave error message here */
  89042. NameContext *pNC, /* The name context */
  89043. const char *zMsg, /* Type of error */
  89044. int validMask /* Set of contexts for which prohibited */
  89045. ){
  89046. assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
  89047. if( (pNC->ncFlags & validMask)!=0 ){
  89048. const char *zIn = "partial index WHERE clauses";
  89049. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  89050. #ifndef SQLITE_OMIT_CHECK
  89051. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  89052. #endif
  89053. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  89054. }
  89055. }
  89056. /*
  89057. ** Expression p should encode a floating point value between 1.0 and 0.0.
  89058. ** Return 1024 times this value. Or return -1 if p is not a floating point
  89059. ** value between 1.0 and 0.0.
  89060. */
  89061. static int exprProbability(Expr *p){
  89062. double r = -1.0;
  89063. if( p->op!=TK_FLOAT ) return -1;
  89064. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  89065. assert( r>=0.0 );
  89066. if( r>1.0 ) return -1;
  89067. return (int)(r*134217728.0);
  89068. }
  89069. /*
  89070. ** This routine is callback for sqlite3WalkExpr().
  89071. **
  89072. ** Resolve symbolic names into TK_COLUMN operators for the current
  89073. ** node in the expression tree. Return 0 to continue the search down
  89074. ** the tree or 2 to abort the tree walk.
  89075. **
  89076. ** This routine also does error checking and name resolution for
  89077. ** function names. The operator for aggregate functions is changed
  89078. ** to TK_AGG_FUNCTION.
  89079. */
  89080. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  89081. NameContext *pNC;
  89082. Parse *pParse;
  89083. pNC = pWalker->u.pNC;
  89084. assert( pNC!=0 );
  89085. pParse = pNC->pParse;
  89086. assert( pParse==pWalker->pParse );
  89087. #ifndef NDEBUG
  89088. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  89089. SrcList *pSrcList = pNC->pSrcList;
  89090. int i;
  89091. for(i=0; i<pNC->pSrcList->nSrc; i++){
  89092. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  89093. }
  89094. }
  89095. #endif
  89096. switch( pExpr->op ){
  89097. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  89098. /* The special operator TK_ROW means use the rowid for the first
  89099. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  89100. ** clause processing on UPDATE and DELETE statements.
  89101. */
  89102. case TK_ROW: {
  89103. SrcList *pSrcList = pNC->pSrcList;
  89104. struct SrcList_item *pItem;
  89105. assert( pSrcList && pSrcList->nSrc==1 );
  89106. pItem = pSrcList->a;
  89107. assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );
  89108. pExpr->op = TK_COLUMN;
  89109. pExpr->y.pTab = pItem->pTab;
  89110. pExpr->iTable = pItem->iCursor;
  89111. pExpr->iColumn = -1;
  89112. pExpr->affinity = SQLITE_AFF_INTEGER;
  89113. break;
  89114. }
  89115. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  89116. && !defined(SQLITE_OMIT_SUBQUERY) */
  89117. /* A column name: ID
  89118. ** Or table name and column name: ID.ID
  89119. ** Or a database, table and column: ID.ID.ID
  89120. **
  89121. ** The TK_ID and TK_OUT cases are combined so that there will only
  89122. ** be one call to lookupName(). Then the compiler will in-line
  89123. ** lookupName() for a size reduction and performance increase.
  89124. */
  89125. case TK_ID:
  89126. case TK_DOT: {
  89127. const char *zColumn;
  89128. const char *zTable;
  89129. const char *zDb;
  89130. Expr *pRight;
  89131. if( pExpr->op==TK_ID ){
  89132. zDb = 0;
  89133. zTable = 0;
  89134. zColumn = pExpr->u.zToken;
  89135. }else{
  89136. Expr *pLeft = pExpr->pLeft;
  89137. notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
  89138. pRight = pExpr->pRight;
  89139. if( pRight->op==TK_ID ){
  89140. zDb = 0;
  89141. }else{
  89142. assert( pRight->op==TK_DOT );
  89143. zDb = pLeft->u.zToken;
  89144. pLeft = pRight->pLeft;
  89145. pRight = pRight->pRight;
  89146. }
  89147. zTable = pLeft->u.zToken;
  89148. zColumn = pRight->u.zToken;
  89149. if( IN_RENAME_OBJECT ){
  89150. sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
  89151. sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
  89152. }
  89153. }
  89154. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  89155. }
  89156. /* Resolve function names
  89157. */
  89158. case TK_FUNCTION: {
  89159. ExprList *pList = pExpr->x.pList; /* The argument list */
  89160. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  89161. int no_such_func = 0; /* True if no such function exists */
  89162. int wrong_num_args = 0; /* True if wrong number of arguments */
  89163. int is_agg = 0; /* True if is an aggregate function */
  89164. int nId; /* Number of characters in function name */
  89165. const char *zId; /* The function name. */
  89166. FuncDef *pDef; /* Information about the function */
  89167. u8 enc = ENC(pParse->db); /* The database encoding */
  89168. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  89169. zId = pExpr->u.zToken;
  89170. nId = sqlite3Strlen30(zId);
  89171. pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
  89172. if( pDef==0 ){
  89173. pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
  89174. if( pDef==0 ){
  89175. no_such_func = 1;
  89176. }else{
  89177. wrong_num_args = 1;
  89178. }
  89179. }else{
  89180. is_agg = pDef->xFinalize!=0;
  89181. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  89182. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  89183. if( n==2 ){
  89184. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  89185. if( pExpr->iTable<0 ){
  89186. sqlite3ErrorMsg(pParse,
  89187. "second argument to likelihood() must be a "
  89188. "constant between 0.0 and 1.0");
  89189. pNC->nErr++;
  89190. }
  89191. }else{
  89192. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  89193. ** equivalent to likelihood(X, 0.0625).
  89194. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  89195. ** short-hand for likelihood(X,0.0625).
  89196. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  89197. ** for likelihood(X,0.9375).
  89198. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  89199. ** to likelihood(X,0.9375). */
  89200. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  89201. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  89202. }
  89203. }
  89204. #ifndef SQLITE_OMIT_AUTHORIZATION
  89205. {
  89206. int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
  89207. if( auth!=SQLITE_OK ){
  89208. if( auth==SQLITE_DENY ){
  89209. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  89210. pDef->zName);
  89211. pNC->nErr++;
  89212. }
  89213. pExpr->op = TK_NULL;
  89214. return WRC_Prune;
  89215. }
  89216. }
  89217. #endif
  89218. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  89219. /* For the purposes of the EP_ConstFunc flag, date and time
  89220. ** functions and other functions that change slowly are considered
  89221. ** constant because they are constant for the duration of one query */
  89222. ExprSetProperty(pExpr,EP_ConstFunc);
  89223. }
  89224. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  89225. /* Date/time functions that use 'now', and other functions like
  89226. ** sqlite_version() that might change over time cannot be used
  89227. ** in an index. */
  89228. notValid(pParse, pNC, "non-deterministic functions",
  89229. NC_IdxExpr|NC_PartIdx);
  89230. }
  89231. if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
  89232. && pParse->nested==0
  89233. && sqlite3Config.bInternalFunctions==0
  89234. ){
  89235. /* Internal-use-only functions are disallowed unless the
  89236. ** SQL is being compiled using sqlite3NestedParse() */
  89237. no_such_func = 1;
  89238. pDef = 0;
  89239. }
  89240. }
  89241. if( 0==IN_RENAME_OBJECT ){
  89242. #ifndef SQLITE_OMIT_WINDOWFUNC
  89243. assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
  89244. || (pDef->xValue==0 && pDef->xInverse==0)
  89245. || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
  89246. );
  89247. if( pDef && pDef->xValue==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
  89248. sqlite3ErrorMsg(pParse,
  89249. "%.*s() may not be used as a window function", nId, zId
  89250. );
  89251. pNC->nErr++;
  89252. }else if(
  89253. (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
  89254. || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pExpr->y.pWin)
  89255. || (is_agg && pExpr->y.pWin && (pNC->ncFlags & NC_AllowWin)==0)
  89256. ){
  89257. const char *zType;
  89258. if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pExpr->y.pWin ){
  89259. zType = "window";
  89260. }else{
  89261. zType = "aggregate";
  89262. }
  89263. sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId);
  89264. pNC->nErr++;
  89265. is_agg = 0;
  89266. }
  89267. #else
  89268. if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
  89269. sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId);
  89270. pNC->nErr++;
  89271. is_agg = 0;
  89272. }
  89273. #endif
  89274. else if( no_such_func && pParse->db->init.busy==0
  89275. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  89276. && pParse->explain==0
  89277. #endif
  89278. ){
  89279. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  89280. pNC->nErr++;
  89281. }else if( wrong_num_args ){
  89282. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  89283. nId, zId);
  89284. pNC->nErr++;
  89285. }
  89286. if( is_agg ){
  89287. #ifndef SQLITE_OMIT_WINDOWFUNC
  89288. pNC->ncFlags &= ~(pExpr->y.pWin ? NC_AllowWin : NC_AllowAgg);
  89289. #else
  89290. pNC->ncFlags &= ~NC_AllowAgg;
  89291. #endif
  89292. }
  89293. }
  89294. sqlite3WalkExprList(pWalker, pList);
  89295. if( is_agg ){
  89296. #ifndef SQLITE_OMIT_WINDOWFUNC
  89297. if( pExpr->y.pWin ){
  89298. Select *pSel = pNC->pWinSelect;
  89299. sqlite3WalkExprList(pWalker, pExpr->y.pWin->pPartition);
  89300. sqlite3WalkExprList(pWalker, pExpr->y.pWin->pOrderBy);
  89301. sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
  89302. sqlite3WindowUpdate(pParse, pSel->pWinDefn, pExpr->y.pWin, pDef);
  89303. if( 0==pSel->pWin
  89304. || 0==sqlite3WindowCompare(pParse, pSel->pWin, pExpr->y.pWin)
  89305. ){
  89306. pExpr->y.pWin->pNextWin = pSel->pWin;
  89307. pSel->pWin = pExpr->y.pWin;
  89308. }
  89309. pNC->ncFlags |= NC_AllowWin;
  89310. }else
  89311. #endif /* SQLITE_OMIT_WINDOWFUNC */
  89312. {
  89313. NameContext *pNC2 = pNC;
  89314. pExpr->op = TK_AGG_FUNCTION;
  89315. pExpr->op2 = 0;
  89316. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  89317. pExpr->op2++;
  89318. pNC2 = pNC2->pNext;
  89319. }
  89320. assert( pDef!=0 );
  89321. if( pNC2 ){
  89322. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  89323. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  89324. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  89325. }
  89326. pNC->ncFlags |= NC_AllowAgg;
  89327. }
  89328. }
  89329. /* FIX ME: Compute pExpr->affinity based on the expected return
  89330. ** type of the function
  89331. */
  89332. return WRC_Prune;
  89333. }
  89334. #ifndef SQLITE_OMIT_SUBQUERY
  89335. case TK_SELECT:
  89336. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  89337. #endif
  89338. case TK_IN: {
  89339. testcase( pExpr->op==TK_IN );
  89340. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  89341. int nRef = pNC->nRef;
  89342. notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  89343. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  89344. assert( pNC->nRef>=nRef );
  89345. if( nRef!=pNC->nRef ){
  89346. ExprSetProperty(pExpr, EP_VarSelect);
  89347. pNC->ncFlags |= NC_VarSelect;
  89348. }
  89349. }
  89350. break;
  89351. }
  89352. case TK_VARIABLE: {
  89353. notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  89354. break;
  89355. }
  89356. case TK_IS:
  89357. case TK_ISNOT: {
  89358. Expr *pRight;
  89359. assert( !ExprHasProperty(pExpr, EP_Reduced) );
  89360. /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
  89361. ** and "x IS NOT FALSE". */
  89362. if( (pRight = pExpr->pRight)->op==TK_ID ){
  89363. int rc = resolveExprStep(pWalker, pRight);
  89364. if( rc==WRC_Abort ) return WRC_Abort;
  89365. if( pRight->op==TK_TRUEFALSE ){
  89366. pExpr->op2 = pExpr->op;
  89367. pExpr->op = TK_TRUTH;
  89368. return WRC_Continue;
  89369. }
  89370. }
  89371. /* Fall thru */
  89372. }
  89373. case TK_BETWEEN:
  89374. case TK_EQ:
  89375. case TK_NE:
  89376. case TK_LT:
  89377. case TK_LE:
  89378. case TK_GT:
  89379. case TK_GE: {
  89380. int nLeft, nRight;
  89381. if( pParse->db->mallocFailed ) break;
  89382. assert( pExpr->pLeft!=0 );
  89383. nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
  89384. if( pExpr->op==TK_BETWEEN ){
  89385. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
  89386. if( nRight==nLeft ){
  89387. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
  89388. }
  89389. }else{
  89390. assert( pExpr->pRight!=0 );
  89391. nRight = sqlite3ExprVectorSize(pExpr->pRight);
  89392. }
  89393. if( nLeft!=nRight ){
  89394. testcase( pExpr->op==TK_EQ );
  89395. testcase( pExpr->op==TK_NE );
  89396. testcase( pExpr->op==TK_LT );
  89397. testcase( pExpr->op==TK_LE );
  89398. testcase( pExpr->op==TK_GT );
  89399. testcase( pExpr->op==TK_GE );
  89400. testcase( pExpr->op==TK_IS );
  89401. testcase( pExpr->op==TK_ISNOT );
  89402. testcase( pExpr->op==TK_BETWEEN );
  89403. sqlite3ErrorMsg(pParse, "row value misused");
  89404. }
  89405. break;
  89406. }
  89407. }
  89408. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  89409. }
  89410. /*
  89411. ** pEList is a list of expressions which are really the result set of the
  89412. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  89413. ** This routine checks to see if pE is a simple identifier which corresponds
  89414. ** to the AS-name of one of the terms of the expression list. If it is,
  89415. ** this routine return an integer between 1 and N where N is the number of
  89416. ** elements in pEList, corresponding to the matching entry. If there is
  89417. ** no match, or if pE is not a simple identifier, then this routine
  89418. ** return 0.
  89419. **
  89420. ** pEList has been resolved. pE has not.
  89421. */
  89422. static int resolveAsName(
  89423. Parse *pParse, /* Parsing context for error messages */
  89424. ExprList *pEList, /* List of expressions to scan */
  89425. Expr *pE /* Expression we are trying to match */
  89426. ){
  89427. int i; /* Loop counter */
  89428. UNUSED_PARAMETER(pParse);
  89429. if( pE->op==TK_ID ){
  89430. char *zCol = pE->u.zToken;
  89431. for(i=0; i<pEList->nExpr; i++){
  89432. char *zAs = pEList->a[i].zName;
  89433. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  89434. return i+1;
  89435. }
  89436. }
  89437. }
  89438. return 0;
  89439. }
  89440. /*
  89441. ** pE is a pointer to an expression which is a single term in the
  89442. ** ORDER BY of a compound SELECT. The expression has not been
  89443. ** name resolved.
  89444. **
  89445. ** At the point this routine is called, we already know that the
  89446. ** ORDER BY term is not an integer index into the result set. That
  89447. ** case is handled by the calling routine.
  89448. **
  89449. ** Attempt to match pE against result set columns in the left-most
  89450. ** SELECT statement. Return the index i of the matching column,
  89451. ** as an indication to the caller that it should sort by the i-th column.
  89452. ** The left-most column is 1. In other words, the value returned is the
  89453. ** same integer value that would be used in the SQL statement to indicate
  89454. ** the column.
  89455. **
  89456. ** If there is no match, return 0. Return -1 if an error occurs.
  89457. */
  89458. static int resolveOrderByTermToExprList(
  89459. Parse *pParse, /* Parsing context for error messages */
  89460. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  89461. Expr *pE /* The specific ORDER BY term */
  89462. ){
  89463. int i; /* Loop counter */
  89464. ExprList *pEList; /* The columns of the result set */
  89465. NameContext nc; /* Name context for resolving pE */
  89466. sqlite3 *db; /* Database connection */
  89467. int rc; /* Return code from subprocedures */
  89468. u8 savedSuppErr; /* Saved value of db->suppressErr */
  89469. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  89470. pEList = pSelect->pEList;
  89471. /* Resolve all names in the ORDER BY term expression
  89472. */
  89473. memset(&nc, 0, sizeof(nc));
  89474. nc.pParse = pParse;
  89475. nc.pSrcList = pSelect->pSrc;
  89476. nc.uNC.pEList = pEList;
  89477. nc.ncFlags = NC_AllowAgg|NC_UEList;
  89478. nc.nErr = 0;
  89479. db = pParse->db;
  89480. savedSuppErr = db->suppressErr;
  89481. db->suppressErr = 1;
  89482. rc = sqlite3ResolveExprNames(&nc, pE);
  89483. db->suppressErr = savedSuppErr;
  89484. if( rc ) return 0;
  89485. /* Try to match the ORDER BY expression against an expression
  89486. ** in the result set. Return an 1-based index of the matching
  89487. ** result-set entry.
  89488. */
  89489. for(i=0; i<pEList->nExpr; i++){
  89490. if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
  89491. return i+1;
  89492. }
  89493. }
  89494. /* If no match, return 0. */
  89495. return 0;
  89496. }
  89497. /*
  89498. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  89499. */
  89500. static void resolveOutOfRangeError(
  89501. Parse *pParse, /* The error context into which to write the error */
  89502. const char *zType, /* "ORDER" or "GROUP" */
  89503. int i, /* The index (1-based) of the term out of range */
  89504. int mx /* Largest permissible value of i */
  89505. ){
  89506. sqlite3ErrorMsg(pParse,
  89507. "%r %s BY term out of range - should be "
  89508. "between 1 and %d", i, zType, mx);
  89509. }
  89510. /*
  89511. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  89512. ** each term of the ORDER BY clause is a constant integer between 1
  89513. ** and N where N is the number of columns in the compound SELECT.
  89514. **
  89515. ** ORDER BY terms that are already an integer between 1 and N are
  89516. ** unmodified. ORDER BY terms that are integers outside the range of
  89517. ** 1 through N generate an error. ORDER BY terms that are expressions
  89518. ** are matched against result set expressions of compound SELECT
  89519. ** beginning with the left-most SELECT and working toward the right.
  89520. ** At the first match, the ORDER BY expression is transformed into
  89521. ** the integer column number.
  89522. **
  89523. ** Return the number of errors seen.
  89524. */
  89525. static int resolveCompoundOrderBy(
  89526. Parse *pParse, /* Parsing context. Leave error messages here */
  89527. Select *pSelect /* The SELECT statement containing the ORDER BY */
  89528. ){
  89529. int i;
  89530. ExprList *pOrderBy;
  89531. ExprList *pEList;
  89532. sqlite3 *db;
  89533. int moreToDo = 1;
  89534. pOrderBy = pSelect->pOrderBy;
  89535. if( pOrderBy==0 ) return 0;
  89536. db = pParse->db;
  89537. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  89538. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  89539. return 1;
  89540. }
  89541. for(i=0; i<pOrderBy->nExpr; i++){
  89542. pOrderBy->a[i].done = 0;
  89543. }
  89544. pSelect->pNext = 0;
  89545. while( pSelect->pPrior ){
  89546. pSelect->pPrior->pNext = pSelect;
  89547. pSelect = pSelect->pPrior;
  89548. }
  89549. while( pSelect && moreToDo ){
  89550. struct ExprList_item *pItem;
  89551. moreToDo = 0;
  89552. pEList = pSelect->pEList;
  89553. assert( pEList!=0 );
  89554. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  89555. int iCol = -1;
  89556. Expr *pE, *pDup;
  89557. if( pItem->done ) continue;
  89558. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  89559. if( sqlite3ExprIsInteger(pE, &iCol) ){
  89560. if( iCol<=0 || iCol>pEList->nExpr ){
  89561. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  89562. return 1;
  89563. }
  89564. }else{
  89565. iCol = resolveAsName(pParse, pEList, pE);
  89566. if( iCol==0 ){
  89567. pDup = sqlite3ExprDup(db, pE, 0);
  89568. if( !db->mallocFailed ){
  89569. assert(pDup);
  89570. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  89571. }
  89572. sqlite3ExprDelete(db, pDup);
  89573. }
  89574. }
  89575. if( iCol>0 ){
  89576. /* Convert the ORDER BY term into an integer column number iCol,
  89577. ** taking care to preserve the COLLATE clause if it exists */
  89578. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  89579. if( pNew==0 ) return 1;
  89580. pNew->flags |= EP_IntValue;
  89581. pNew->u.iValue = iCol;
  89582. if( pItem->pExpr==pE ){
  89583. pItem->pExpr = pNew;
  89584. }else{
  89585. Expr *pParent = pItem->pExpr;
  89586. assert( pParent->op==TK_COLLATE );
  89587. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  89588. assert( pParent->pLeft==pE );
  89589. pParent->pLeft = pNew;
  89590. }
  89591. sqlite3ExprDelete(db, pE);
  89592. pItem->u.x.iOrderByCol = (u16)iCol;
  89593. pItem->done = 1;
  89594. }else{
  89595. moreToDo = 1;
  89596. }
  89597. }
  89598. pSelect = pSelect->pNext;
  89599. }
  89600. for(i=0; i<pOrderBy->nExpr; i++){
  89601. if( pOrderBy->a[i].done==0 ){
  89602. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  89603. "column in the result set", i+1);
  89604. return 1;
  89605. }
  89606. }
  89607. return 0;
  89608. }
  89609. /*
  89610. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  89611. ** the SELECT statement pSelect. If any term is reference to a
  89612. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  89613. ** field) then convert that term into a copy of the corresponding result set
  89614. ** column.
  89615. **
  89616. ** If any errors are detected, add an error message to pParse and
  89617. ** return non-zero. Return zero if no errors are seen.
  89618. */
  89619. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  89620. Parse *pParse, /* Parsing context. Leave error messages here */
  89621. Select *pSelect, /* The SELECT statement containing the clause */
  89622. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  89623. const char *zType /* "ORDER" or "GROUP" */
  89624. ){
  89625. int i;
  89626. sqlite3 *db = pParse->db;
  89627. ExprList *pEList;
  89628. struct ExprList_item *pItem;
  89629. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  89630. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  89631. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  89632. return 1;
  89633. }
  89634. pEList = pSelect->pEList;
  89635. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  89636. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  89637. if( pItem->u.x.iOrderByCol ){
  89638. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  89639. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  89640. return 1;
  89641. }
  89642. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  89643. zType,0);
  89644. }
  89645. }
  89646. return 0;
  89647. }
  89648. /*
  89649. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  89650. ** The Name context of the SELECT statement is pNC. zType is either
  89651. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  89652. **
  89653. ** This routine resolves each term of the clause into an expression.
  89654. ** If the order-by term is an integer I between 1 and N (where N is the
  89655. ** number of columns in the result set of the SELECT) then the expression
  89656. ** in the resolution is a copy of the I-th result-set expression. If
  89657. ** the order-by term is an identifier that corresponds to the AS-name of
  89658. ** a result-set expression, then the term resolves to a copy of the
  89659. ** result-set expression. Otherwise, the expression is resolved in
  89660. ** the usual way - using sqlite3ResolveExprNames().
  89661. **
  89662. ** This routine returns the number of errors. If errors occur, then
  89663. ** an appropriate error message might be left in pParse. (OOM errors
  89664. ** excepted.)
  89665. */
  89666. static int resolveOrderGroupBy(
  89667. NameContext *pNC, /* The name context of the SELECT statement */
  89668. Select *pSelect, /* The SELECT statement holding pOrderBy */
  89669. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  89670. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  89671. ){
  89672. int i, j; /* Loop counters */
  89673. int iCol; /* Column number */
  89674. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  89675. Parse *pParse; /* Parsing context */
  89676. int nResult; /* Number of terms in the result set */
  89677. if( pOrderBy==0 ) return 0;
  89678. nResult = pSelect->pEList->nExpr;
  89679. pParse = pNC->pParse;
  89680. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  89681. Expr *pE = pItem->pExpr;
  89682. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  89683. if( zType[0]!='G' ){
  89684. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  89685. if( iCol>0 ){
  89686. /* If an AS-name match is found, mark this ORDER BY column as being
  89687. ** a copy of the iCol-th result-set column. The subsequent call to
  89688. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  89689. ** copy of the iCol-th result-set expression. */
  89690. pItem->u.x.iOrderByCol = (u16)iCol;
  89691. continue;
  89692. }
  89693. }
  89694. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  89695. /* The ORDER BY term is an integer constant. Again, set the column
  89696. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  89697. ** order-by term to a copy of the result-set expression */
  89698. if( iCol<1 || iCol>0xffff ){
  89699. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  89700. return 1;
  89701. }
  89702. pItem->u.x.iOrderByCol = (u16)iCol;
  89703. continue;
  89704. }
  89705. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  89706. pItem->u.x.iOrderByCol = 0;
  89707. if( sqlite3ResolveExprNames(pNC, pE) ){
  89708. return 1;
  89709. }
  89710. for(j=0; j<pSelect->pEList->nExpr; j++){
  89711. if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  89712. #ifndef SQLITE_OMIT_WINDOWFUNC
  89713. if( ExprHasProperty(pE, EP_WinFunc) ){
  89714. /* Since this window function is being changed into a reference
  89715. ** to the same window function the result set, remove the instance
  89716. ** of this window function from the Select.pWin list. */
  89717. Window **pp;
  89718. for(pp=&pSelect->pWin; *pp; pp=&(*pp)->pNextWin){
  89719. if( *pp==pE->y.pWin ){
  89720. *pp = (*pp)->pNextWin;
  89721. }
  89722. }
  89723. }
  89724. #endif
  89725. pItem->u.x.iOrderByCol = j+1;
  89726. }
  89727. }
  89728. }
  89729. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  89730. }
  89731. /*
  89732. ** Resolve names in the SELECT statement p and all of its descendants.
  89733. */
  89734. static int resolveSelectStep(Walker *pWalker, Select *p){
  89735. NameContext *pOuterNC; /* Context that contains this SELECT */
  89736. NameContext sNC; /* Name context of this SELECT */
  89737. int isCompound; /* True if p is a compound select */
  89738. int nCompound; /* Number of compound terms processed so far */
  89739. Parse *pParse; /* Parsing context */
  89740. int i; /* Loop counter */
  89741. ExprList *pGroupBy; /* The GROUP BY clause */
  89742. Select *pLeftmost; /* Left-most of SELECT of a compound */
  89743. sqlite3 *db; /* Database connection */
  89744. assert( p!=0 );
  89745. if( p->selFlags & SF_Resolved ){
  89746. return WRC_Prune;
  89747. }
  89748. pOuterNC = pWalker->u.pNC;
  89749. pParse = pWalker->pParse;
  89750. db = pParse->db;
  89751. /* Normally sqlite3SelectExpand() will be called first and will have
  89752. ** already expanded this SELECT. However, if this is a subquery within
  89753. ** an expression, sqlite3ResolveExprNames() will be called without a
  89754. ** prior call to sqlite3SelectExpand(). When that happens, let
  89755. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  89756. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  89757. ** this routine in the correct order.
  89758. */
  89759. if( (p->selFlags & SF_Expanded)==0 ){
  89760. sqlite3SelectPrep(pParse, p, pOuterNC);
  89761. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  89762. }
  89763. isCompound = p->pPrior!=0;
  89764. nCompound = 0;
  89765. pLeftmost = p;
  89766. while( p ){
  89767. assert( (p->selFlags & SF_Expanded)!=0 );
  89768. assert( (p->selFlags & SF_Resolved)==0 );
  89769. p->selFlags |= SF_Resolved;
  89770. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  89771. ** are not allowed to refer to any names, so pass an empty NameContext.
  89772. */
  89773. memset(&sNC, 0, sizeof(sNC));
  89774. sNC.pParse = pParse;
  89775. sNC.pWinSelect = p;
  89776. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
  89777. return WRC_Abort;
  89778. }
  89779. /* If the SF_Converted flags is set, then this Select object was
  89780. ** was created by the convertCompoundSelectToSubquery() function.
  89781. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  89782. ** as if it were part of the sub-query, not the parent. This block
  89783. ** moves the pOrderBy down to the sub-query. It will be moved back
  89784. ** after the names have been resolved. */
  89785. if( p->selFlags & SF_Converted ){
  89786. Select *pSub = p->pSrc->a[0].pSelect;
  89787. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  89788. assert( pSub->pPrior && pSub->pOrderBy==0 );
  89789. pSub->pOrderBy = p->pOrderBy;
  89790. p->pOrderBy = 0;
  89791. }
  89792. /* Recursively resolve names in all subqueries
  89793. */
  89794. for(i=0; i<p->pSrc->nSrc; i++){
  89795. struct SrcList_item *pItem = &p->pSrc->a[i];
  89796. if( pItem->pSelect ){
  89797. NameContext *pNC; /* Used to iterate name contexts */
  89798. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  89799. const char *zSavedContext = pParse->zAuthContext;
  89800. /* Count the total number of references to pOuterNC and all of its
  89801. ** parent contexts. After resolving references to expressions in
  89802. ** pItem->pSelect, check if this value has changed. If so, then
  89803. ** SELECT statement pItem->pSelect must be correlated. Set the
  89804. ** pItem->fg.isCorrelated flag if this is the case. */
  89805. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  89806. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  89807. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  89808. pParse->zAuthContext = zSavedContext;
  89809. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  89810. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  89811. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  89812. pItem->fg.isCorrelated = (nRef!=0);
  89813. }
  89814. }
  89815. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  89816. ** resolve the result-set expression list.
  89817. */
  89818. sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
  89819. sNC.pSrcList = p->pSrc;
  89820. sNC.pNext = pOuterNC;
  89821. /* Resolve names in the result set. */
  89822. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  89823. sNC.ncFlags &= ~NC_AllowWin;
  89824. /* If there are no aggregate functions in the result-set, and no GROUP BY
  89825. ** expression, do not allow aggregates in any of the other expressions.
  89826. */
  89827. assert( (p->selFlags & SF_Aggregate)==0 );
  89828. pGroupBy = p->pGroupBy;
  89829. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  89830. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  89831. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  89832. }else{
  89833. sNC.ncFlags &= ~NC_AllowAgg;
  89834. }
  89835. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  89836. */
  89837. if( p->pHaving && !pGroupBy ){
  89838. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  89839. return WRC_Abort;
  89840. }
  89841. /* Add the output column list to the name-context before parsing the
  89842. ** other expressions in the SELECT statement. This is so that
  89843. ** expressions in the WHERE clause (etc.) can refer to expressions by
  89844. ** aliases in the result set.
  89845. **
  89846. ** Minor point: If this is the case, then the expression will be
  89847. ** re-evaluated for each reference to it.
  89848. */
  89849. assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 );
  89850. sNC.uNC.pEList = p->pEList;
  89851. sNC.ncFlags |= NC_UEList;
  89852. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  89853. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  89854. /* Resolve names in table-valued-function arguments */
  89855. for(i=0; i<p->pSrc->nSrc; i++){
  89856. struct SrcList_item *pItem = &p->pSrc->a[i];
  89857. if( pItem->fg.isTabFunc
  89858. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  89859. ){
  89860. return WRC_Abort;
  89861. }
  89862. }
  89863. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  89864. ** outer queries
  89865. */
  89866. sNC.pNext = 0;
  89867. sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
  89868. /* If this is a converted compound query, move the ORDER BY clause from
  89869. ** the sub-query back to the parent query. At this point each term
  89870. ** within the ORDER BY clause has been transformed to an integer value.
  89871. ** These integers will be replaced by copies of the corresponding result
  89872. ** set expressions by the call to resolveOrderGroupBy() below. */
  89873. if( p->selFlags & SF_Converted ){
  89874. Select *pSub = p->pSrc->a[0].pSelect;
  89875. p->pOrderBy = pSub->pOrderBy;
  89876. pSub->pOrderBy = 0;
  89877. }
  89878. /* Process the ORDER BY clause for singleton SELECT statements.
  89879. ** The ORDER BY clause for compounds SELECT statements is handled
  89880. ** below, after all of the result-sets for all of the elements of
  89881. ** the compound have been resolved.
  89882. **
  89883. ** If there is an ORDER BY clause on a term of a compound-select other
  89884. ** than the right-most term, then that is a syntax error. But the error
  89885. ** is not detected until much later, and so we need to go ahead and
  89886. ** resolve those symbols on the incorrect ORDER BY for consistency.
  89887. */
  89888. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  89889. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  89890. ){
  89891. return WRC_Abort;
  89892. }
  89893. if( db->mallocFailed ){
  89894. return WRC_Abort;
  89895. }
  89896. sNC.ncFlags &= ~NC_AllowWin;
  89897. /* Resolve the GROUP BY clause. At the same time, make sure
  89898. ** the GROUP BY clause does not contain aggregate functions.
  89899. */
  89900. if( pGroupBy ){
  89901. struct ExprList_item *pItem;
  89902. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  89903. return WRC_Abort;
  89904. }
  89905. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  89906. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  89907. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  89908. "the GROUP BY clause");
  89909. return WRC_Abort;
  89910. }
  89911. }
  89912. }
  89913. /* If this is part of a compound SELECT, check that it has the right
  89914. ** number of expressions in the select list. */
  89915. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  89916. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  89917. return WRC_Abort;
  89918. }
  89919. /* Advance to the next term of the compound
  89920. */
  89921. p = p->pPrior;
  89922. nCompound++;
  89923. }
  89924. /* Resolve the ORDER BY on a compound SELECT after all terms of
  89925. ** the compound have been resolved.
  89926. */
  89927. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  89928. return WRC_Abort;
  89929. }
  89930. return WRC_Prune;
  89931. }
  89932. /*
  89933. ** This routine walks an expression tree and resolves references to
  89934. ** table columns and result-set columns. At the same time, do error
  89935. ** checking on function usage and set a flag if any aggregate functions
  89936. ** are seen.
  89937. **
  89938. ** To resolve table columns references we look for nodes (or subtrees) of the
  89939. ** form X.Y.Z or Y.Z or just Z where
  89940. **
  89941. ** X: The name of a database. Ex: "main" or "temp" or
  89942. ** the symbolic name assigned to an ATTACH-ed database.
  89943. **
  89944. ** Y: The name of a table in a FROM clause. Or in a trigger
  89945. ** one of the special names "old" or "new".
  89946. **
  89947. ** Z: The name of a column in table Y.
  89948. **
  89949. ** The node at the root of the subtree is modified as follows:
  89950. **
  89951. ** Expr.op Changed to TK_COLUMN
  89952. ** Expr.pTab Points to the Table object for X.Y
  89953. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  89954. ** Expr.iTable The VDBE cursor number for X.Y
  89955. **
  89956. **
  89957. ** To resolve result-set references, look for expression nodes of the
  89958. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  89959. ** size of an AS clause in the result-set of a SELECT. The Z expression
  89960. ** is replaced by a copy of the left-hand side of the result-set expression.
  89961. ** Table-name and function resolution occurs on the substituted expression
  89962. ** tree. For example, in:
  89963. **
  89964. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  89965. **
  89966. ** The "x" term of the order by is replaced by "a+b" to render:
  89967. **
  89968. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  89969. **
  89970. ** Function calls are checked to make sure that the function is
  89971. ** defined and that the correct number of arguments are specified.
  89972. ** If the function is an aggregate function, then the NC_HasAgg flag is
  89973. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  89974. ** If an expression contains aggregate functions then the EP_Agg
  89975. ** property on the expression is set.
  89976. **
  89977. ** An error message is left in pParse if anything is amiss. The number
  89978. ** if errors is returned.
  89979. */
  89980. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  89981. NameContext *pNC, /* Namespace to resolve expressions in. */
  89982. Expr *pExpr /* The expression to be analyzed. */
  89983. ){
  89984. u16 savedHasAgg;
  89985. Walker w;
  89986. if( pExpr==0 ) return SQLITE_OK;
  89987. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  89988. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  89989. w.pParse = pNC->pParse;
  89990. w.xExprCallback = resolveExprStep;
  89991. w.xSelectCallback = resolveSelectStep;
  89992. w.xSelectCallback2 = 0;
  89993. w.u.pNC = pNC;
  89994. #if SQLITE_MAX_EXPR_DEPTH>0
  89995. w.pParse->nHeight += pExpr->nHeight;
  89996. if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
  89997. return SQLITE_ERROR;
  89998. }
  89999. #endif
  90000. sqlite3WalkExpr(&w, pExpr);
  90001. #if SQLITE_MAX_EXPR_DEPTH>0
  90002. w.pParse->nHeight -= pExpr->nHeight;
  90003. #endif
  90004. if( pNC->ncFlags & NC_HasAgg ){
  90005. ExprSetProperty(pExpr, EP_Agg);
  90006. }
  90007. pNC->ncFlags |= savedHasAgg;
  90008. return pNC->nErr>0 || w.pParse->nErr>0;
  90009. }
  90010. /*
  90011. ** Resolve all names for all expression in an expression list. This is
  90012. ** just like sqlite3ResolveExprNames() except that it works for an expression
  90013. ** list rather than a single expression.
  90014. */
  90015. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  90016. NameContext *pNC, /* Namespace to resolve expressions in. */
  90017. ExprList *pList /* The expression list to be analyzed. */
  90018. ){
  90019. int i;
  90020. if( pList ){
  90021. for(i=0; i<pList->nExpr; i++){
  90022. if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
  90023. }
  90024. }
  90025. return WRC_Continue;
  90026. }
  90027. /*
  90028. ** Resolve all names in all expressions of a SELECT and in all
  90029. ** decendents of the SELECT, including compounds off of p->pPrior,
  90030. ** subqueries in expressions, and subqueries used as FROM clause
  90031. ** terms.
  90032. **
  90033. ** See sqlite3ResolveExprNames() for a description of the kinds of
  90034. ** transformations that occur.
  90035. **
  90036. ** All SELECT statements should have been expanded using
  90037. ** sqlite3SelectExpand() prior to invoking this routine.
  90038. */
  90039. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  90040. Parse *pParse, /* The parser context */
  90041. Select *p, /* The SELECT statement being coded. */
  90042. NameContext *pOuterNC /* Name context for parent SELECT statement */
  90043. ){
  90044. Walker w;
  90045. assert( p!=0 );
  90046. w.xExprCallback = resolveExprStep;
  90047. w.xSelectCallback = resolveSelectStep;
  90048. w.xSelectCallback2 = 0;
  90049. w.pParse = pParse;
  90050. w.u.pNC = pOuterNC;
  90051. sqlite3WalkSelect(&w, p);
  90052. }
  90053. /*
  90054. ** Resolve names in expressions that can only reference a single table:
  90055. **
  90056. ** * CHECK constraints
  90057. ** * WHERE clauses on partial indices
  90058. **
  90059. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  90060. ** is set to -1 and the Expr.iColumn value is set to the column number.
  90061. **
  90062. ** Any errors cause an error message to be set in pParse.
  90063. */
  90064. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  90065. Parse *pParse, /* Parsing context */
  90066. Table *pTab, /* The table being referenced */
  90067. int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
  90068. Expr *pExpr, /* Expression to resolve. May be NULL. */
  90069. ExprList *pList /* Expression list to resolve. May be NULL. */
  90070. ){
  90071. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  90072. NameContext sNC; /* Name context for pParse->pNewTable */
  90073. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
  90074. memset(&sNC, 0, sizeof(sNC));
  90075. memset(&sSrc, 0, sizeof(sSrc));
  90076. sSrc.nSrc = 1;
  90077. sSrc.a[0].zName = pTab->zName;
  90078. sSrc.a[0].pTab = pTab;
  90079. sSrc.a[0].iCursor = -1;
  90080. sNC.pParse = pParse;
  90081. sNC.pSrcList = &sSrc;
  90082. sNC.ncFlags = type;
  90083. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  90084. if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
  90085. }
  90086. /************** End of resolve.c *********************************************/
  90087. /************** Begin file expr.c ********************************************/
  90088. /*
  90089. ** 2001 September 15
  90090. **
  90091. ** The author disclaims copyright to this source code. In place of
  90092. ** a legal notice, here is a blessing:
  90093. **
  90094. ** May you do good and not evil.
  90095. ** May you find forgiveness for yourself and forgive others.
  90096. ** May you share freely, never taking more than you give.
  90097. **
  90098. *************************************************************************
  90099. ** This file contains routines used for analyzing expressions and
  90100. ** for generating VDBE code that evaluates expressions in SQLite.
  90101. */
  90102. /* #include "sqliteInt.h" */
  90103. /* Forward declarations */
  90104. static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
  90105. static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
  90106. /*
  90107. ** Return the affinity character for a single column of a table.
  90108. */
  90109. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
  90110. assert( iCol<pTab->nCol );
  90111. return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  90112. }
  90113. /*
  90114. ** Return the 'affinity' of the expression pExpr if any.
  90115. **
  90116. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  90117. ** or a sub-select with a column as the return value, then the
  90118. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  90119. ** indicating no affinity for the expression.
  90120. **
  90121. ** i.e. the WHERE clause expressions in the following statements all
  90122. ** have an affinity:
  90123. **
  90124. ** CREATE TABLE t1(a);
  90125. ** SELECT * FROM t1 WHERE a;
  90126. ** SELECT a AS b FROM t1 WHERE b;
  90127. ** SELECT * FROM t1 WHERE (select a from t1);
  90128. */
  90129. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  90130. int op;
  90131. pExpr = sqlite3ExprSkipCollate(pExpr);
  90132. if( pExpr->flags & EP_Generic ) return 0;
  90133. op = pExpr->op;
  90134. if( op==TK_SELECT ){
  90135. assert( pExpr->flags&EP_xIsSelect );
  90136. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  90137. }
  90138. if( op==TK_REGISTER ) op = pExpr->op2;
  90139. #ifndef SQLITE_OMIT_CAST
  90140. if( op==TK_CAST ){
  90141. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  90142. return sqlite3AffinityType(pExpr->u.zToken, 0);
  90143. }
  90144. #endif
  90145. if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
  90146. return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
  90147. }
  90148. if( op==TK_SELECT_COLUMN ){
  90149. assert( pExpr->pLeft->flags&EP_xIsSelect );
  90150. return sqlite3ExprAffinity(
  90151. pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
  90152. );
  90153. }
  90154. return pExpr->affinity;
  90155. }
  90156. /*
  90157. ** Set the collating sequence for expression pExpr to be the collating
  90158. ** sequence named by pToken. Return a pointer to a new Expr node that
  90159. ** implements the COLLATE operator.
  90160. **
  90161. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  90162. ** and the pExpr parameter is returned unchanged.
  90163. */
  90164. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  90165. Parse *pParse, /* Parsing context */
  90166. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  90167. const Token *pCollName, /* Name of collating sequence */
  90168. int dequote /* True to dequote pCollName */
  90169. ){
  90170. if( pCollName->n>0 ){
  90171. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  90172. if( pNew ){
  90173. pNew->pLeft = pExpr;
  90174. pNew->flags |= EP_Collate|EP_Skip;
  90175. pExpr = pNew;
  90176. }
  90177. }
  90178. return pExpr;
  90179. }
  90180. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  90181. Token s;
  90182. assert( zC!=0 );
  90183. sqlite3TokenInit(&s, (char*)zC);
  90184. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  90185. }
  90186. /*
  90187. ** Skip over any TK_COLLATE operators and any unlikely()
  90188. ** or likelihood() function at the root of an expression.
  90189. */
  90190. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  90191. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  90192. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  90193. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  90194. assert( pExpr->x.pList->nExpr>0 );
  90195. assert( pExpr->op==TK_FUNCTION );
  90196. pExpr = pExpr->x.pList->a[0].pExpr;
  90197. }else{
  90198. assert( pExpr->op==TK_COLLATE );
  90199. pExpr = pExpr->pLeft;
  90200. }
  90201. }
  90202. return pExpr;
  90203. }
  90204. /*
  90205. ** Return the collation sequence for the expression pExpr. If
  90206. ** there is no defined collating sequence, return NULL.
  90207. **
  90208. ** See also: sqlite3ExprNNCollSeq()
  90209. **
  90210. ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
  90211. ** default collation if pExpr has no defined collation.
  90212. **
  90213. ** The collating sequence might be determined by a COLLATE operator
  90214. ** or by the presence of a column with a defined collating sequence.
  90215. ** COLLATE operators take first precedence. Left operands take
  90216. ** precedence over right operands.
  90217. */
  90218. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  90219. sqlite3 *db = pParse->db;
  90220. CollSeq *pColl = 0;
  90221. Expr *p = pExpr;
  90222. while( p ){
  90223. int op = p->op;
  90224. if( p->flags & EP_Generic ) break;
  90225. if( (op==TK_AGG_COLUMN || op==TK_COLUMN
  90226. || op==TK_REGISTER || op==TK_TRIGGER)
  90227. && p->y.pTab!=0
  90228. ){
  90229. /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
  90230. ** a TK_COLUMN but was previously evaluated and cached in a register */
  90231. int j = p->iColumn;
  90232. if( j>=0 ){
  90233. const char *zColl = p->y.pTab->aCol[j].zColl;
  90234. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  90235. }
  90236. break;
  90237. }
  90238. if( op==TK_CAST || op==TK_UPLUS ){
  90239. p = p->pLeft;
  90240. continue;
  90241. }
  90242. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  90243. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  90244. break;
  90245. }
  90246. if( p->flags & EP_Collate ){
  90247. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  90248. p = p->pLeft;
  90249. }else{
  90250. Expr *pNext = p->pRight;
  90251. /* The Expr.x union is never used at the same time as Expr.pRight */
  90252. assert( p->x.pList==0 || p->pRight==0 );
  90253. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  90254. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  90255. ** least one EP_Collate. Thus the following two ALWAYS. */
  90256. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  90257. int i;
  90258. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  90259. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  90260. pNext = p->x.pList->a[i].pExpr;
  90261. break;
  90262. }
  90263. }
  90264. }
  90265. p = pNext;
  90266. }
  90267. }else{
  90268. break;
  90269. }
  90270. }
  90271. if( sqlite3CheckCollSeq(pParse, pColl) ){
  90272. pColl = 0;
  90273. }
  90274. return pColl;
  90275. }
  90276. /*
  90277. ** Return the collation sequence for the expression pExpr. If
  90278. ** there is no defined collating sequence, return a pointer to the
  90279. ** defautl collation sequence.
  90280. **
  90281. ** See also: sqlite3ExprCollSeq()
  90282. **
  90283. ** The sqlite3ExprCollSeq() routine works the same except that it
  90284. ** returns NULL if there is no defined collation.
  90285. */
  90286. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
  90287. CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
  90288. if( p==0 ) p = pParse->db->pDfltColl;
  90289. assert( p!=0 );
  90290. return p;
  90291. }
  90292. /*
  90293. ** Return TRUE if the two expressions have equivalent collating sequences.
  90294. */
  90295. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
  90296. CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
  90297. CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
  90298. return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
  90299. }
  90300. /*
  90301. ** pExpr is an operand of a comparison operator. aff2 is the
  90302. ** type affinity of the other operand. This routine returns the
  90303. ** type affinity that should be used for the comparison operator.
  90304. */
  90305. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  90306. char aff1 = sqlite3ExprAffinity(pExpr);
  90307. if( aff1 && aff2 ){
  90308. /* Both sides of the comparison are columns. If one has numeric
  90309. ** affinity, use that. Otherwise use no affinity.
  90310. */
  90311. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  90312. return SQLITE_AFF_NUMERIC;
  90313. }else{
  90314. return SQLITE_AFF_BLOB;
  90315. }
  90316. }else if( !aff1 && !aff2 ){
  90317. /* Neither side of the comparison is a column. Compare the
  90318. ** results directly.
  90319. */
  90320. return SQLITE_AFF_BLOB;
  90321. }else{
  90322. /* One side is a column, the other is not. Use the columns affinity. */
  90323. assert( aff1==0 || aff2==0 );
  90324. return (aff1 + aff2);
  90325. }
  90326. }
  90327. /*
  90328. ** pExpr is a comparison operator. Return the type affinity that should
  90329. ** be applied to both operands prior to doing the comparison.
  90330. */
  90331. static char comparisonAffinity(Expr *pExpr){
  90332. char aff;
  90333. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  90334. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  90335. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  90336. assert( pExpr->pLeft );
  90337. aff = sqlite3ExprAffinity(pExpr->pLeft);
  90338. if( pExpr->pRight ){
  90339. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  90340. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  90341. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  90342. }else if( aff==0 ){
  90343. aff = SQLITE_AFF_BLOB;
  90344. }
  90345. return aff;
  90346. }
  90347. /*
  90348. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  90349. ** idx_affinity is the affinity of an indexed column. Return true
  90350. ** if the index with affinity idx_affinity may be used to implement
  90351. ** the comparison in pExpr.
  90352. */
  90353. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  90354. char aff = comparisonAffinity(pExpr);
  90355. switch( aff ){
  90356. case SQLITE_AFF_BLOB:
  90357. return 1;
  90358. case SQLITE_AFF_TEXT:
  90359. return idx_affinity==SQLITE_AFF_TEXT;
  90360. default:
  90361. return sqlite3IsNumericAffinity(idx_affinity);
  90362. }
  90363. }
  90364. /*
  90365. ** Return the P5 value that should be used for a binary comparison
  90366. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  90367. */
  90368. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  90369. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  90370. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  90371. return aff;
  90372. }
  90373. /*
  90374. ** Return a pointer to the collation sequence that should be used by
  90375. ** a binary comparison operator comparing pLeft and pRight.
  90376. **
  90377. ** If the left hand expression has a collating sequence type, then it is
  90378. ** used. Otherwise the collation sequence for the right hand expression
  90379. ** is used, or the default (BINARY) if neither expression has a collating
  90380. ** type.
  90381. **
  90382. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  90383. ** it is not considered.
  90384. */
  90385. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  90386. Parse *pParse,
  90387. Expr *pLeft,
  90388. Expr *pRight
  90389. ){
  90390. CollSeq *pColl;
  90391. assert( pLeft );
  90392. if( pLeft->flags & EP_Collate ){
  90393. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  90394. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  90395. pColl = sqlite3ExprCollSeq(pParse, pRight);
  90396. }else{
  90397. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  90398. if( !pColl ){
  90399. pColl = sqlite3ExprCollSeq(pParse, pRight);
  90400. }
  90401. }
  90402. return pColl;
  90403. }
  90404. /*
  90405. ** Generate code for a comparison operator.
  90406. */
  90407. static int codeCompare(
  90408. Parse *pParse, /* The parsing (and code generating) context */
  90409. Expr *pLeft, /* The left operand */
  90410. Expr *pRight, /* The right operand */
  90411. int opcode, /* The comparison opcode */
  90412. int in1, int in2, /* Register holding operands */
  90413. int dest, /* Jump here if true. */
  90414. int jumpIfNull /* If true, jump if either operand is NULL */
  90415. ){
  90416. int p5;
  90417. int addr;
  90418. CollSeq *p4;
  90419. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  90420. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  90421. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  90422. (void*)p4, P4_COLLSEQ);
  90423. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  90424. return addr;
  90425. }
  90426. /*
  90427. ** Return true if expression pExpr is a vector, or false otherwise.
  90428. **
  90429. ** A vector is defined as any expression that results in two or more
  90430. ** columns of result. Every TK_VECTOR node is an vector because the
  90431. ** parser will not generate a TK_VECTOR with fewer than two entries.
  90432. ** But a TK_SELECT might be either a vector or a scalar. It is only
  90433. ** considered a vector if it has two or more result columns.
  90434. */
  90435. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
  90436. return sqlite3ExprVectorSize(pExpr)>1;
  90437. }
  90438. /*
  90439. ** If the expression passed as the only argument is of type TK_VECTOR
  90440. ** return the number of expressions in the vector. Or, if the expression
  90441. ** is a sub-select, return the number of columns in the sub-select. For
  90442. ** any other type of expression, return 1.
  90443. */
  90444. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
  90445. u8 op = pExpr->op;
  90446. if( op==TK_REGISTER ) op = pExpr->op2;
  90447. if( op==TK_VECTOR ){
  90448. return pExpr->x.pList->nExpr;
  90449. }else if( op==TK_SELECT ){
  90450. return pExpr->x.pSelect->pEList->nExpr;
  90451. }else{
  90452. return 1;
  90453. }
  90454. }
  90455. /*
  90456. ** Return a pointer to a subexpression of pVector that is the i-th
  90457. ** column of the vector (numbered starting with 0). The caller must
  90458. ** ensure that i is within range.
  90459. **
  90460. ** If pVector is really a scalar (and "scalar" here includes subqueries
  90461. ** that return a single column!) then return pVector unmodified.
  90462. **
  90463. ** pVector retains ownership of the returned subexpression.
  90464. **
  90465. ** If the vector is a (SELECT ...) then the expression returned is
  90466. ** just the expression for the i-th term of the result set, and may
  90467. ** not be ready for evaluation because the table cursor has not yet
  90468. ** been positioned.
  90469. */
  90470. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
  90471. assert( i<sqlite3ExprVectorSize(pVector) );
  90472. if( sqlite3ExprIsVector(pVector) ){
  90473. assert( pVector->op2==0 || pVector->op==TK_REGISTER );
  90474. if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
  90475. return pVector->x.pSelect->pEList->a[i].pExpr;
  90476. }else{
  90477. return pVector->x.pList->a[i].pExpr;
  90478. }
  90479. }
  90480. return pVector;
  90481. }
  90482. /*
  90483. ** Compute and return a new Expr object which when passed to
  90484. ** sqlite3ExprCode() will generate all necessary code to compute
  90485. ** the iField-th column of the vector expression pVector.
  90486. **
  90487. ** It is ok for pVector to be a scalar (as long as iField==0).
  90488. ** In that case, this routine works like sqlite3ExprDup().
  90489. **
  90490. ** The caller owns the returned Expr object and is responsible for
  90491. ** ensuring that the returned value eventually gets freed.
  90492. **
  90493. ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
  90494. ** then the returned object will reference pVector and so pVector must remain
  90495. ** valid for the life of the returned object. If pVector is a TK_VECTOR
  90496. ** or a scalar expression, then it can be deleted as soon as this routine
  90497. ** returns.
  90498. **
  90499. ** A trick to cause a TK_SELECT pVector to be deleted together with
  90500. ** the returned Expr object is to attach the pVector to the pRight field
  90501. ** of the returned TK_SELECT_COLUMN Expr object.
  90502. */
  90503. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
  90504. Parse *pParse, /* Parsing context */
  90505. Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
  90506. int iField /* Which column of the vector to return */
  90507. ){
  90508. Expr *pRet;
  90509. if( pVector->op==TK_SELECT ){
  90510. assert( pVector->flags & EP_xIsSelect );
  90511. /* The TK_SELECT_COLUMN Expr node:
  90512. **
  90513. ** pLeft: pVector containing TK_SELECT. Not deleted.
  90514. ** pRight: not used. But recursively deleted.
  90515. ** iColumn: Index of a column in pVector
  90516. ** iTable: 0 or the number of columns on the LHS of an assignment
  90517. ** pLeft->iTable: First in an array of register holding result, or 0
  90518. ** if the result is not yet computed.
  90519. **
  90520. ** sqlite3ExprDelete() specifically skips the recursive delete of
  90521. ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
  90522. ** can be attached to pRight to cause this node to take ownership of
  90523. ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
  90524. ** with the same pLeft pointer to the pVector, but only one of them
  90525. ** will own the pVector.
  90526. */
  90527. pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
  90528. if( pRet ){
  90529. pRet->iColumn = iField;
  90530. pRet->pLeft = pVector;
  90531. }
  90532. assert( pRet==0 || pRet->iTable==0 );
  90533. }else{
  90534. if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
  90535. pRet = sqlite3ExprDup(pParse->db, pVector, 0);
  90536. }
  90537. return pRet;
  90538. }
  90539. /*
  90540. ** If expression pExpr is of type TK_SELECT, generate code to evaluate
  90541. ** it. Return the register in which the result is stored (or, if the
  90542. ** sub-select returns more than one column, the first in an array
  90543. ** of registers in which the result is stored).
  90544. **
  90545. ** If pExpr is not a TK_SELECT expression, return 0.
  90546. */
  90547. static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
  90548. int reg = 0;
  90549. #ifndef SQLITE_OMIT_SUBQUERY
  90550. if( pExpr->op==TK_SELECT ){
  90551. reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  90552. }
  90553. #endif
  90554. return reg;
  90555. }
  90556. /*
  90557. ** Argument pVector points to a vector expression - either a TK_VECTOR
  90558. ** or TK_SELECT that returns more than one column. This function returns
  90559. ** the register number of a register that contains the value of
  90560. ** element iField of the vector.
  90561. **
  90562. ** If pVector is a TK_SELECT expression, then code for it must have
  90563. ** already been generated using the exprCodeSubselect() routine. In this
  90564. ** case parameter regSelect should be the first in an array of registers
  90565. ** containing the results of the sub-select.
  90566. **
  90567. ** If pVector is of type TK_VECTOR, then code for the requested field
  90568. ** is generated. In this case (*pRegFree) may be set to the number of
  90569. ** a temporary register to be freed by the caller before returning.
  90570. **
  90571. ** Before returning, output parameter (*ppExpr) is set to point to the
  90572. ** Expr object corresponding to element iElem of the vector.
  90573. */
  90574. static int exprVectorRegister(
  90575. Parse *pParse, /* Parse context */
  90576. Expr *pVector, /* Vector to extract element from */
  90577. int iField, /* Field to extract from pVector */
  90578. int regSelect, /* First in array of registers */
  90579. Expr **ppExpr, /* OUT: Expression element */
  90580. int *pRegFree /* OUT: Temp register to free */
  90581. ){
  90582. u8 op = pVector->op;
  90583. assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
  90584. if( op==TK_REGISTER ){
  90585. *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
  90586. return pVector->iTable+iField;
  90587. }
  90588. if( op==TK_SELECT ){
  90589. *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
  90590. return regSelect+iField;
  90591. }
  90592. *ppExpr = pVector->x.pList->a[iField].pExpr;
  90593. return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
  90594. }
  90595. /*
  90596. ** Expression pExpr is a comparison between two vector values. Compute
  90597. ** the result of the comparison (1, 0, or NULL) and write that
  90598. ** result into register dest.
  90599. **
  90600. ** The caller must satisfy the following preconditions:
  90601. **
  90602. ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
  90603. ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
  90604. ** otherwise: op==pExpr->op and p5==0
  90605. */
  90606. static void codeVectorCompare(
  90607. Parse *pParse, /* Code generator context */
  90608. Expr *pExpr, /* The comparison operation */
  90609. int dest, /* Write results into this register */
  90610. u8 op, /* Comparison operator */
  90611. u8 p5 /* SQLITE_NULLEQ or zero */
  90612. ){
  90613. Vdbe *v = pParse->pVdbe;
  90614. Expr *pLeft = pExpr->pLeft;
  90615. Expr *pRight = pExpr->pRight;
  90616. int nLeft = sqlite3ExprVectorSize(pLeft);
  90617. int i;
  90618. int regLeft = 0;
  90619. int regRight = 0;
  90620. u8 opx = op;
  90621. int addrDone = sqlite3VdbeMakeLabel(v);
  90622. if( nLeft!=sqlite3ExprVectorSize(pRight) ){
  90623. sqlite3ErrorMsg(pParse, "row value misused");
  90624. return;
  90625. }
  90626. assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
  90627. || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
  90628. || pExpr->op==TK_LT || pExpr->op==TK_GT
  90629. || pExpr->op==TK_LE || pExpr->op==TK_GE
  90630. );
  90631. assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
  90632. || (pExpr->op==TK_ISNOT && op==TK_NE) );
  90633. assert( p5==0 || pExpr->op!=op );
  90634. assert( p5==SQLITE_NULLEQ || pExpr->op==op );
  90635. p5 |= SQLITE_STOREP2;
  90636. if( opx==TK_LE ) opx = TK_LT;
  90637. if( opx==TK_GE ) opx = TK_GT;
  90638. regLeft = exprCodeSubselect(pParse, pLeft);
  90639. regRight = exprCodeSubselect(pParse, pRight);
  90640. for(i=0; 1 /*Loop exits by "break"*/; i++){
  90641. int regFree1 = 0, regFree2 = 0;
  90642. Expr *pL, *pR;
  90643. int r1, r2;
  90644. assert( i>=0 && i<nLeft );
  90645. r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
  90646. r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
  90647. codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
  90648. testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  90649. testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  90650. testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  90651. testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  90652. testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  90653. testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  90654. sqlite3ReleaseTempReg(pParse, regFree1);
  90655. sqlite3ReleaseTempReg(pParse, regFree2);
  90656. if( i==nLeft-1 ){
  90657. break;
  90658. }
  90659. if( opx==TK_EQ ){
  90660. sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
  90661. p5 |= SQLITE_KEEPNULL;
  90662. }else if( opx==TK_NE ){
  90663. sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
  90664. p5 |= SQLITE_KEEPNULL;
  90665. }else{
  90666. assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
  90667. sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
  90668. VdbeCoverageIf(v, op==TK_LT);
  90669. VdbeCoverageIf(v, op==TK_GT);
  90670. VdbeCoverageIf(v, op==TK_LE);
  90671. VdbeCoverageIf(v, op==TK_GE);
  90672. if( i==nLeft-2 ) opx = op;
  90673. }
  90674. }
  90675. sqlite3VdbeResolveLabel(v, addrDone);
  90676. }
  90677. #if SQLITE_MAX_EXPR_DEPTH>0
  90678. /*
  90679. ** Check that argument nHeight is less than or equal to the maximum
  90680. ** expression depth allowed. If it is not, leave an error message in
  90681. ** pParse.
  90682. */
  90683. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  90684. int rc = SQLITE_OK;
  90685. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  90686. if( nHeight>mxHeight ){
  90687. sqlite3ErrorMsg(pParse,
  90688. "Expression tree is too large (maximum depth %d)", mxHeight
  90689. );
  90690. rc = SQLITE_ERROR;
  90691. }
  90692. return rc;
  90693. }
  90694. /* The following three functions, heightOfExpr(), heightOfExprList()
  90695. ** and heightOfSelect(), are used to determine the maximum height
  90696. ** of any expression tree referenced by the structure passed as the
  90697. ** first argument.
  90698. **
  90699. ** If this maximum height is greater than the current value pointed
  90700. ** to by pnHeight, the second parameter, then set *pnHeight to that
  90701. ** value.
  90702. */
  90703. static void heightOfExpr(Expr *p, int *pnHeight){
  90704. if( p ){
  90705. if( p->nHeight>*pnHeight ){
  90706. *pnHeight = p->nHeight;
  90707. }
  90708. }
  90709. }
  90710. static void heightOfExprList(ExprList *p, int *pnHeight){
  90711. if( p ){
  90712. int i;
  90713. for(i=0; i<p->nExpr; i++){
  90714. heightOfExpr(p->a[i].pExpr, pnHeight);
  90715. }
  90716. }
  90717. }
  90718. static void heightOfSelect(Select *pSelect, int *pnHeight){
  90719. Select *p;
  90720. for(p=pSelect; p; p=p->pPrior){
  90721. heightOfExpr(p->pWhere, pnHeight);
  90722. heightOfExpr(p->pHaving, pnHeight);
  90723. heightOfExpr(p->pLimit, pnHeight);
  90724. heightOfExprList(p->pEList, pnHeight);
  90725. heightOfExprList(p->pGroupBy, pnHeight);
  90726. heightOfExprList(p->pOrderBy, pnHeight);
  90727. }
  90728. }
  90729. /*
  90730. ** Set the Expr.nHeight variable in the structure passed as an
  90731. ** argument. An expression with no children, Expr.pList or
  90732. ** Expr.pSelect member has a height of 1. Any other expression
  90733. ** has a height equal to the maximum height of any other
  90734. ** referenced Expr plus one.
  90735. **
  90736. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  90737. ** if appropriate.
  90738. */
  90739. static void exprSetHeight(Expr *p){
  90740. int nHeight = 0;
  90741. heightOfExpr(p->pLeft, &nHeight);
  90742. heightOfExpr(p->pRight, &nHeight);
  90743. if( ExprHasProperty(p, EP_xIsSelect) ){
  90744. heightOfSelect(p->x.pSelect, &nHeight);
  90745. }else if( p->x.pList ){
  90746. heightOfExprList(p->x.pList, &nHeight);
  90747. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  90748. }
  90749. p->nHeight = nHeight + 1;
  90750. }
  90751. /*
  90752. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  90753. ** the height is greater than the maximum allowed expression depth,
  90754. ** leave an error in pParse.
  90755. **
  90756. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  90757. ** Expr.flags.
  90758. */
  90759. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  90760. if( pParse->nErr ) return;
  90761. exprSetHeight(p);
  90762. sqlite3ExprCheckHeight(pParse, p->nHeight);
  90763. }
  90764. /*
  90765. ** Return the maximum height of any expression tree referenced
  90766. ** by the select statement passed as an argument.
  90767. */
  90768. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  90769. int nHeight = 0;
  90770. heightOfSelect(p, &nHeight);
  90771. return nHeight;
  90772. }
  90773. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  90774. /*
  90775. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  90776. ** Expr.flags.
  90777. */
  90778. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  90779. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  90780. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  90781. }
  90782. }
  90783. #define exprSetHeight(y)
  90784. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  90785. /*
  90786. ** This routine is the core allocator for Expr nodes.
  90787. **
  90788. ** Construct a new expression node and return a pointer to it. Memory
  90789. ** for this node and for the pToken argument is a single allocation
  90790. ** obtained from sqlite3DbMalloc(). The calling function
  90791. ** is responsible for making sure the node eventually gets freed.
  90792. **
  90793. ** If dequote is true, then the token (if it exists) is dequoted.
  90794. ** If dequote is false, no dequoting is performed. The deQuote
  90795. ** parameter is ignored if pToken is NULL or if the token does not
  90796. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  90797. ** then the EP_DblQuoted flag is set on the expression node.
  90798. **
  90799. ** Special case: If op==TK_INTEGER and pToken points to a string that
  90800. ** can be translated into a 32-bit integer, then the token is not
  90801. ** stored in u.zToken. Instead, the integer values is written
  90802. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  90803. ** is allocated to hold the integer text and the dequote flag is ignored.
  90804. */
  90805. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  90806. sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
  90807. int op, /* Expression opcode */
  90808. const Token *pToken, /* Token argument. Might be NULL */
  90809. int dequote /* True to dequote */
  90810. ){
  90811. Expr *pNew;
  90812. int nExtra = 0;
  90813. int iValue = 0;
  90814. assert( db!=0 );
  90815. if( pToken ){
  90816. if( op!=TK_INTEGER || pToken->z==0
  90817. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  90818. nExtra = pToken->n+1;
  90819. assert( iValue>=0 );
  90820. }
  90821. }
  90822. pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
  90823. if( pNew ){
  90824. memset(pNew, 0, sizeof(Expr));
  90825. pNew->op = (u8)op;
  90826. pNew->iAgg = -1;
  90827. if( pToken ){
  90828. if( nExtra==0 ){
  90829. pNew->flags |= EP_IntValue|EP_Leaf;
  90830. pNew->u.iValue = iValue;
  90831. }else{
  90832. pNew->u.zToken = (char*)&pNew[1];
  90833. assert( pToken->z!=0 || pToken->n==0 );
  90834. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  90835. pNew->u.zToken[pToken->n] = 0;
  90836. if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
  90837. if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
  90838. sqlite3Dequote(pNew->u.zToken);
  90839. }
  90840. }
  90841. }
  90842. #if SQLITE_MAX_EXPR_DEPTH>0
  90843. pNew->nHeight = 1;
  90844. #endif
  90845. }
  90846. return pNew;
  90847. }
  90848. /*
  90849. ** Allocate a new expression node from a zero-terminated token that has
  90850. ** already been dequoted.
  90851. */
  90852. SQLITE_PRIVATE Expr *sqlite3Expr(
  90853. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  90854. int op, /* Expression opcode */
  90855. const char *zToken /* Token argument. Might be NULL */
  90856. ){
  90857. Token x;
  90858. x.z = zToken;
  90859. x.n = sqlite3Strlen30(zToken);
  90860. return sqlite3ExprAlloc(db, op, &x, 0);
  90861. }
  90862. /*
  90863. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  90864. **
  90865. ** If pRoot==NULL that means that a memory allocation error has occurred.
  90866. ** In that case, delete the subtrees pLeft and pRight.
  90867. */
  90868. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  90869. sqlite3 *db,
  90870. Expr *pRoot,
  90871. Expr *pLeft,
  90872. Expr *pRight
  90873. ){
  90874. if( pRoot==0 ){
  90875. assert( db->mallocFailed );
  90876. sqlite3ExprDelete(db, pLeft);
  90877. sqlite3ExprDelete(db, pRight);
  90878. }else{
  90879. if( pRight ){
  90880. pRoot->pRight = pRight;
  90881. pRoot->flags |= EP_Propagate & pRight->flags;
  90882. }
  90883. if( pLeft ){
  90884. pRoot->pLeft = pLeft;
  90885. pRoot->flags |= EP_Propagate & pLeft->flags;
  90886. }
  90887. exprSetHeight(pRoot);
  90888. }
  90889. }
  90890. /*
  90891. ** Allocate an Expr node which joins as many as two subtrees.
  90892. **
  90893. ** One or both of the subtrees can be NULL. Return a pointer to the new
  90894. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  90895. ** free the subtrees and return NULL.
  90896. */
  90897. SQLITE_PRIVATE Expr *sqlite3PExpr(
  90898. Parse *pParse, /* Parsing context */
  90899. int op, /* Expression opcode */
  90900. Expr *pLeft, /* Left operand */
  90901. Expr *pRight /* Right operand */
  90902. ){
  90903. Expr *p;
  90904. if( op==TK_AND && pParse->nErr==0 ){
  90905. /* Take advantage of short-circuit false optimization for AND */
  90906. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  90907. }else{
  90908. p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
  90909. if( p ){
  90910. memset(p, 0, sizeof(Expr));
  90911. p->op = op & TKFLG_MASK;
  90912. p->iAgg = -1;
  90913. }
  90914. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  90915. }
  90916. if( p ) {
  90917. sqlite3ExprCheckHeight(pParse, p->nHeight);
  90918. }
  90919. return p;
  90920. }
  90921. /*
  90922. ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
  90923. ** do a memory allocation failure) then delete the pSelect object.
  90924. */
  90925. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
  90926. if( pExpr ){
  90927. pExpr->x.pSelect = pSelect;
  90928. ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
  90929. sqlite3ExprSetHeightAndFlags(pParse, pExpr);
  90930. }else{
  90931. assert( pParse->db->mallocFailed );
  90932. sqlite3SelectDelete(pParse->db, pSelect);
  90933. }
  90934. }
  90935. /*
  90936. ** If the expression is always either TRUE or FALSE (respectively),
  90937. ** then return 1. If one cannot determine the truth value of the
  90938. ** expression at compile-time return 0.
  90939. **
  90940. ** This is an optimization. If is OK to return 0 here even if
  90941. ** the expression really is always false or false (a false negative).
  90942. ** But it is a bug to return 1 if the expression might have different
  90943. ** boolean values in different circumstances (a false positive.)
  90944. **
  90945. ** Note that if the expression is part of conditional for a
  90946. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  90947. ** is it true or false, so always return 0.
  90948. */
  90949. static int exprAlwaysTrue(Expr *p){
  90950. int v = 0;
  90951. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  90952. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  90953. return v!=0;
  90954. }
  90955. static int exprAlwaysFalse(Expr *p){
  90956. int v = 0;
  90957. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  90958. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  90959. return v==0;
  90960. }
  90961. /*
  90962. ** Join two expressions using an AND operator. If either expression is
  90963. ** NULL, then just return the other expression.
  90964. **
  90965. ** If one side or the other of the AND is known to be false, then instead
  90966. ** of returning an AND expression, just return a constant expression with
  90967. ** a value of false.
  90968. */
  90969. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  90970. if( pLeft==0 ){
  90971. return pRight;
  90972. }else if( pRight==0 ){
  90973. return pLeft;
  90974. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  90975. sqlite3ExprDelete(db, pLeft);
  90976. sqlite3ExprDelete(db, pRight);
  90977. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  90978. }else{
  90979. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  90980. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  90981. return pNew;
  90982. }
  90983. }
  90984. /*
  90985. ** Construct a new expression node for a function with multiple
  90986. ** arguments.
  90987. */
  90988. SQLITE_PRIVATE Expr *sqlite3ExprFunction(
  90989. Parse *pParse, /* Parsing context */
  90990. ExprList *pList, /* Argument list */
  90991. Token *pToken, /* Name of the function */
  90992. int eDistinct /* SF_Distinct or SF_ALL or 0 */
  90993. ){
  90994. Expr *pNew;
  90995. sqlite3 *db = pParse->db;
  90996. assert( pToken );
  90997. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  90998. if( pNew==0 ){
  90999. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  91000. return 0;
  91001. }
  91002. if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  91003. sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
  91004. }
  91005. pNew->x.pList = pList;
  91006. ExprSetProperty(pNew, EP_HasFunc);
  91007. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  91008. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  91009. if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
  91010. return pNew;
  91011. }
  91012. /*
  91013. ** Assign a variable number to an expression that encodes a wildcard
  91014. ** in the original SQL statement.
  91015. **
  91016. ** Wildcards consisting of a single "?" are assigned the next sequential
  91017. ** variable number.
  91018. **
  91019. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  91020. ** sure "nnn" is not too big to avoid a denial of service attack when
  91021. ** the SQL statement comes from an external source.
  91022. **
  91023. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  91024. ** as the previous instance of the same wildcard. Or if this is the first
  91025. ** instance of the wildcard, the next sequential variable number is
  91026. ** assigned.
  91027. */
  91028. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
  91029. sqlite3 *db = pParse->db;
  91030. const char *z;
  91031. ynVar x;
  91032. if( pExpr==0 ) return;
  91033. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  91034. z = pExpr->u.zToken;
  91035. assert( z!=0 );
  91036. assert( z[0]!=0 );
  91037. assert( n==(u32)sqlite3Strlen30(z) );
  91038. if( z[1]==0 ){
  91039. /* Wildcard of the form "?". Assign the next variable number */
  91040. assert( z[0]=='?' );
  91041. x = (ynVar)(++pParse->nVar);
  91042. }else{
  91043. int doAdd = 0;
  91044. if( z[0]=='?' ){
  91045. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  91046. ** use it as the variable number */
  91047. i64 i;
  91048. int bOk;
  91049. if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
  91050. i = z[1]-'0'; /* The common case of ?N for a single digit N */
  91051. bOk = 1;
  91052. }else{
  91053. bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  91054. }
  91055. testcase( i==0 );
  91056. testcase( i==1 );
  91057. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  91058. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  91059. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  91060. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  91061. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  91062. return;
  91063. }
  91064. x = (ynVar)i;
  91065. if( x>pParse->nVar ){
  91066. pParse->nVar = (int)x;
  91067. doAdd = 1;
  91068. }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
  91069. doAdd = 1;
  91070. }
  91071. }else{
  91072. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  91073. ** number as the prior appearance of the same name, or if the name
  91074. ** has never appeared before, reuse the same variable number
  91075. */
  91076. x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
  91077. if( x==0 ){
  91078. x = (ynVar)(++pParse->nVar);
  91079. doAdd = 1;
  91080. }
  91081. }
  91082. if( doAdd ){
  91083. pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
  91084. }
  91085. }
  91086. pExpr->iColumn = x;
  91087. if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  91088. sqlite3ErrorMsg(pParse, "too many SQL variables");
  91089. }
  91090. }
  91091. /*
  91092. ** Recursively delete an expression tree.
  91093. */
  91094. static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
  91095. assert( p!=0 );
  91096. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  91097. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  91098. assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
  91099. assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
  91100. || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
  91101. #ifdef SQLITE_DEBUG
  91102. if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
  91103. assert( p->pLeft==0 );
  91104. assert( p->pRight==0 );
  91105. assert( p->x.pSelect==0 );
  91106. }
  91107. #endif
  91108. if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
  91109. /* The Expr.x union is never used at the same time as Expr.pRight */
  91110. assert( p->x.pList==0 || p->pRight==0 );
  91111. if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
  91112. if( p->pRight ){
  91113. sqlite3ExprDeleteNN(db, p->pRight);
  91114. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  91115. sqlite3SelectDelete(db, p->x.pSelect);
  91116. }else{
  91117. sqlite3ExprListDelete(db, p->x.pList);
  91118. }
  91119. if( ExprHasProperty(p, EP_WinFunc) ){
  91120. assert( p->op==TK_FUNCTION );
  91121. sqlite3WindowDelete(db, p->y.pWin);
  91122. }
  91123. }
  91124. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  91125. if( !ExprHasProperty(p, EP_Static) ){
  91126. sqlite3DbFreeNN(db, p);
  91127. }
  91128. }
  91129. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  91130. if( p ) sqlite3ExprDeleteNN(db, p);
  91131. }
  91132. /*
  91133. ** Return the number of bytes allocated for the expression structure
  91134. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  91135. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  91136. */
  91137. static int exprStructSize(Expr *p){
  91138. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  91139. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  91140. return EXPR_FULLSIZE;
  91141. }
  91142. /*
  91143. ** The dupedExpr*Size() routines each return the number of bytes required
  91144. ** to store a copy of an expression or expression tree. They differ in
  91145. ** how much of the tree is measured.
  91146. **
  91147. ** dupedExprStructSize() Size of only the Expr structure
  91148. ** dupedExprNodeSize() Size of Expr + space for token
  91149. ** dupedExprSize() Expr + token + subtree components
  91150. **
  91151. ***************************************************************************
  91152. **
  91153. ** The dupedExprStructSize() function returns two values OR-ed together:
  91154. ** (1) the space required for a copy of the Expr structure only and
  91155. ** (2) the EP_xxx flags that indicate what the structure size should be.
  91156. ** The return values is always one of:
  91157. **
  91158. ** EXPR_FULLSIZE
  91159. ** EXPR_REDUCEDSIZE | EP_Reduced
  91160. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  91161. **
  91162. ** The size of the structure can be found by masking the return value
  91163. ** of this routine with 0xfff. The flags can be found by masking the
  91164. ** return value with EP_Reduced|EP_TokenOnly.
  91165. **
  91166. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  91167. ** (unreduced) Expr objects as they or originally constructed by the parser.
  91168. ** During expression analysis, extra information is computed and moved into
  91169. ** later parts of the Expr object and that extra information might get chopped
  91170. ** off if the expression is reduced. Note also that it does not work to
  91171. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  91172. ** to reduce a pristine expression tree from the parser. The implementation
  91173. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  91174. ** to enforce this constraint.
  91175. */
  91176. static int dupedExprStructSize(Expr *p, int flags){
  91177. int nSize;
  91178. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  91179. assert( EXPR_FULLSIZE<=0xfff );
  91180. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  91181. if( 0==flags || p->op==TK_SELECT_COLUMN
  91182. #ifndef SQLITE_OMIT_WINDOWFUNC
  91183. || ExprHasProperty(p, EP_WinFunc)
  91184. #endif
  91185. ){
  91186. nSize = EXPR_FULLSIZE;
  91187. }else{
  91188. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  91189. assert( !ExprHasProperty(p, EP_FromJoin) );
  91190. assert( !ExprHasProperty(p, EP_MemToken) );
  91191. assert( !ExprHasProperty(p, EP_NoReduce) );
  91192. if( p->pLeft || p->x.pList ){
  91193. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  91194. }else{
  91195. assert( p->pRight==0 );
  91196. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  91197. }
  91198. }
  91199. return nSize;
  91200. }
  91201. /*
  91202. ** This function returns the space in bytes required to store the copy
  91203. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  91204. ** string is defined.)
  91205. */
  91206. static int dupedExprNodeSize(Expr *p, int flags){
  91207. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  91208. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  91209. nByte += sqlite3Strlen30NN(p->u.zToken)+1;
  91210. }
  91211. return ROUND8(nByte);
  91212. }
  91213. /*
  91214. ** Return the number of bytes required to create a duplicate of the
  91215. ** expression passed as the first argument. The second argument is a
  91216. ** mask containing EXPRDUP_XXX flags.
  91217. **
  91218. ** The value returned includes space to create a copy of the Expr struct
  91219. ** itself and the buffer referred to by Expr.u.zToken, if any.
  91220. **
  91221. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  91222. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  91223. ** and Expr.pRight variables (but not for any structures pointed to or
  91224. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  91225. */
  91226. static int dupedExprSize(Expr *p, int flags){
  91227. int nByte = 0;
  91228. if( p ){
  91229. nByte = dupedExprNodeSize(p, flags);
  91230. if( flags&EXPRDUP_REDUCE ){
  91231. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  91232. }
  91233. }
  91234. return nByte;
  91235. }
  91236. /*
  91237. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  91238. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  91239. ** to store the copy of expression p, the copies of p->u.zToken
  91240. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  91241. ** if any. Before returning, *pzBuffer is set to the first byte past the
  91242. ** portion of the buffer copied into by this function.
  91243. */
  91244. static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
  91245. Expr *pNew; /* Value to return */
  91246. u8 *zAlloc; /* Memory space from which to build Expr object */
  91247. u32 staticFlag; /* EP_Static if space not obtained from malloc */
  91248. assert( db!=0 );
  91249. assert( p );
  91250. assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
  91251. assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
  91252. /* Figure out where to write the new Expr structure. */
  91253. if( pzBuffer ){
  91254. zAlloc = *pzBuffer;
  91255. staticFlag = EP_Static;
  91256. }else{
  91257. zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
  91258. staticFlag = 0;
  91259. }
  91260. pNew = (Expr *)zAlloc;
  91261. if( pNew ){
  91262. /* Set nNewSize to the size allocated for the structure pointed to
  91263. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  91264. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  91265. ** by the copy of the p->u.zToken string (if any).
  91266. */
  91267. const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
  91268. const int nNewSize = nStructSize & 0xfff;
  91269. int nToken;
  91270. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  91271. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  91272. }else{
  91273. nToken = 0;
  91274. }
  91275. if( dupFlags ){
  91276. assert( ExprHasProperty(p, EP_Reduced)==0 );
  91277. memcpy(zAlloc, p, nNewSize);
  91278. }else{
  91279. u32 nSize = (u32)exprStructSize(p);
  91280. memcpy(zAlloc, p, nSize);
  91281. if( nSize<EXPR_FULLSIZE ){
  91282. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  91283. }
  91284. }
  91285. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  91286. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  91287. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  91288. pNew->flags |= staticFlag;
  91289. /* Copy the p->u.zToken string, if any. */
  91290. if( nToken ){
  91291. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  91292. memcpy(zToken, p->u.zToken, nToken);
  91293. }
  91294. if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
  91295. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  91296. if( ExprHasProperty(p, EP_xIsSelect) ){
  91297. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
  91298. }else{
  91299. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
  91300. }
  91301. }
  91302. /* Fill in pNew->pLeft and pNew->pRight. */
  91303. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
  91304. zAlloc += dupedExprNodeSize(p, dupFlags);
  91305. if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
  91306. pNew->pLeft = p->pLeft ?
  91307. exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
  91308. pNew->pRight = p->pRight ?
  91309. exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
  91310. }
  91311. #ifndef SQLITE_OMIT_WINDOWFUNC
  91312. if( ExprHasProperty(p, EP_WinFunc) ){
  91313. pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
  91314. assert( ExprHasProperty(pNew, EP_WinFunc) );
  91315. }
  91316. #endif /* SQLITE_OMIT_WINDOWFUNC */
  91317. if( pzBuffer ){
  91318. *pzBuffer = zAlloc;
  91319. }
  91320. }else{
  91321. if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  91322. if( pNew->op==TK_SELECT_COLUMN ){
  91323. pNew->pLeft = p->pLeft;
  91324. assert( p->iColumn==0 || p->pRight==0 );
  91325. assert( p->pRight==0 || p->pRight==p->pLeft );
  91326. }else{
  91327. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  91328. }
  91329. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  91330. }
  91331. }
  91332. }
  91333. return pNew;
  91334. }
  91335. /*
  91336. ** Create and return a deep copy of the object passed as the second
  91337. ** argument. If an OOM condition is encountered, NULL is returned
  91338. ** and the db->mallocFailed flag set.
  91339. */
  91340. #ifndef SQLITE_OMIT_CTE
  91341. static With *withDup(sqlite3 *db, With *p){
  91342. With *pRet = 0;
  91343. if( p ){
  91344. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  91345. pRet = sqlite3DbMallocZero(db, nByte);
  91346. if( pRet ){
  91347. int i;
  91348. pRet->nCte = p->nCte;
  91349. for(i=0; i<p->nCte; i++){
  91350. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  91351. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  91352. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  91353. }
  91354. }
  91355. }
  91356. return pRet;
  91357. }
  91358. #else
  91359. # define withDup(x,y) 0
  91360. #endif
  91361. /*
  91362. ** The following group of routines make deep copies of expressions,
  91363. ** expression lists, ID lists, and select statements. The copies can
  91364. ** be deleted (by being passed to their respective ...Delete() routines)
  91365. ** without effecting the originals.
  91366. **
  91367. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  91368. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  91369. ** by subsequent calls to sqlite*ListAppend() routines.
  91370. **
  91371. ** Any tables that the SrcList might point to are not duplicated.
  91372. **
  91373. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  91374. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  91375. ** truncated version of the usual Expr structure that will be stored as
  91376. ** part of the in-memory representation of the database schema.
  91377. */
  91378. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  91379. assert( flags==0 || flags==EXPRDUP_REDUCE );
  91380. return p ? exprDup(db, p, flags, 0) : 0;
  91381. }
  91382. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  91383. ExprList *pNew;
  91384. struct ExprList_item *pItem, *pOldItem;
  91385. int i;
  91386. Expr *pPriorSelectCol = 0;
  91387. assert( db!=0 );
  91388. if( p==0 ) return 0;
  91389. pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
  91390. if( pNew==0 ) return 0;
  91391. pNew->nExpr = p->nExpr;
  91392. pItem = pNew->a;
  91393. pOldItem = p->a;
  91394. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  91395. Expr *pOldExpr = pOldItem->pExpr;
  91396. Expr *pNewExpr;
  91397. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  91398. if( pOldExpr
  91399. && pOldExpr->op==TK_SELECT_COLUMN
  91400. && (pNewExpr = pItem->pExpr)!=0
  91401. ){
  91402. assert( pNewExpr->iColumn==0 || i>0 );
  91403. if( pNewExpr->iColumn==0 ){
  91404. assert( pOldExpr->pLeft==pOldExpr->pRight );
  91405. pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
  91406. }else{
  91407. assert( i>0 );
  91408. assert( pItem[-1].pExpr!=0 );
  91409. assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
  91410. assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
  91411. pNewExpr->pLeft = pPriorSelectCol;
  91412. }
  91413. }
  91414. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  91415. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  91416. pItem->sortOrder = pOldItem->sortOrder;
  91417. pItem->done = 0;
  91418. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  91419. pItem->bSorterRef = pOldItem->bSorterRef;
  91420. pItem->u = pOldItem->u;
  91421. }
  91422. return pNew;
  91423. }
  91424. /*
  91425. ** If cursors, triggers, views and subqueries are all omitted from
  91426. ** the build, then none of the following routines, except for
  91427. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  91428. ** called with a NULL argument.
  91429. */
  91430. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  91431. || !defined(SQLITE_OMIT_SUBQUERY)
  91432. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  91433. SrcList *pNew;
  91434. int i;
  91435. int nByte;
  91436. assert( db!=0 );
  91437. if( p==0 ) return 0;
  91438. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  91439. pNew = sqlite3DbMallocRawNN(db, nByte );
  91440. if( pNew==0 ) return 0;
  91441. pNew->nSrc = pNew->nAlloc = p->nSrc;
  91442. for(i=0; i<p->nSrc; i++){
  91443. struct SrcList_item *pNewItem = &pNew->a[i];
  91444. struct SrcList_item *pOldItem = &p->a[i];
  91445. Table *pTab;
  91446. pNewItem->pSchema = pOldItem->pSchema;
  91447. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  91448. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  91449. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  91450. pNewItem->fg = pOldItem->fg;
  91451. pNewItem->iCursor = pOldItem->iCursor;
  91452. pNewItem->addrFillSub = pOldItem->addrFillSub;
  91453. pNewItem->regReturn = pOldItem->regReturn;
  91454. if( pNewItem->fg.isIndexedBy ){
  91455. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  91456. }
  91457. pNewItem->pIBIndex = pOldItem->pIBIndex;
  91458. if( pNewItem->fg.isTabFunc ){
  91459. pNewItem->u1.pFuncArg =
  91460. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  91461. }
  91462. pTab = pNewItem->pTab = pOldItem->pTab;
  91463. if( pTab ){
  91464. pTab->nTabRef++;
  91465. }
  91466. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  91467. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  91468. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  91469. pNewItem->colUsed = pOldItem->colUsed;
  91470. }
  91471. return pNew;
  91472. }
  91473. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  91474. IdList *pNew;
  91475. int i;
  91476. assert( db!=0 );
  91477. if( p==0 ) return 0;
  91478. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  91479. if( pNew==0 ) return 0;
  91480. pNew->nId = p->nId;
  91481. pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
  91482. if( pNew->a==0 ){
  91483. sqlite3DbFreeNN(db, pNew);
  91484. return 0;
  91485. }
  91486. /* Note that because the size of the allocation for p->a[] is not
  91487. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  91488. ** on the duplicate created by this function. */
  91489. for(i=0; i<p->nId; i++){
  91490. struct IdList_item *pNewItem = &pNew->a[i];
  91491. struct IdList_item *pOldItem = &p->a[i];
  91492. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  91493. pNewItem->idx = pOldItem->idx;
  91494. }
  91495. return pNew;
  91496. }
  91497. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
  91498. Select *pRet = 0;
  91499. Select *pNext = 0;
  91500. Select **pp = &pRet;
  91501. Select *p;
  91502. assert( db!=0 );
  91503. for(p=pDup; p; p=p->pPrior){
  91504. Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
  91505. if( pNew==0 ) break;
  91506. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  91507. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  91508. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  91509. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  91510. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  91511. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  91512. pNew->op = p->op;
  91513. pNew->pNext = pNext;
  91514. pNew->pPrior = 0;
  91515. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  91516. pNew->iLimit = 0;
  91517. pNew->iOffset = 0;
  91518. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  91519. pNew->addrOpenEphm[0] = -1;
  91520. pNew->addrOpenEphm[1] = -1;
  91521. pNew->nSelectRow = p->nSelectRow;
  91522. pNew->pWith = withDup(db, p->pWith);
  91523. #ifndef SQLITE_OMIT_WINDOWFUNC
  91524. pNew->pWin = 0;
  91525. pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
  91526. #endif
  91527. pNew->selId = p->selId;
  91528. *pp = pNew;
  91529. pp = &pNew->pPrior;
  91530. pNext = pNew;
  91531. }
  91532. return pRet;
  91533. }
  91534. #else
  91535. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  91536. assert( p==0 );
  91537. return 0;
  91538. }
  91539. #endif
  91540. /*
  91541. ** Add a new element to the end of an expression list. If pList is
  91542. ** initially NULL, then create a new expression list.
  91543. **
  91544. ** The pList argument must be either NULL or a pointer to an ExprList
  91545. ** obtained from a prior call to sqlite3ExprListAppend(). This routine
  91546. ** may not be used with an ExprList obtained from sqlite3ExprListDup().
  91547. ** Reason: This routine assumes that the number of slots in pList->a[]
  91548. ** is a power of two. That is true for sqlite3ExprListAppend() returns
  91549. ** but is not necessarily true from the return value of sqlite3ExprListDup().
  91550. **
  91551. ** If a memory allocation error occurs, the entire list is freed and
  91552. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  91553. ** that the new entry was successfully appended.
  91554. */
  91555. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  91556. Parse *pParse, /* Parsing context */
  91557. ExprList *pList, /* List to which to append. Might be NULL */
  91558. Expr *pExpr /* Expression to be appended. Might be NULL */
  91559. ){
  91560. struct ExprList_item *pItem;
  91561. sqlite3 *db = pParse->db;
  91562. assert( db!=0 );
  91563. if( pList==0 ){
  91564. pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
  91565. if( pList==0 ){
  91566. goto no_mem;
  91567. }
  91568. pList->nExpr = 0;
  91569. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  91570. ExprList *pNew;
  91571. pNew = sqlite3DbRealloc(db, pList,
  91572. sizeof(*pList)+(2*pList->nExpr - 1)*sizeof(pList->a[0]));
  91573. if( pNew==0 ){
  91574. goto no_mem;
  91575. }
  91576. pList = pNew;
  91577. }
  91578. pItem = &pList->a[pList->nExpr++];
  91579. assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
  91580. assert( offsetof(struct ExprList_item,pExpr)==0 );
  91581. memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
  91582. pItem->pExpr = pExpr;
  91583. return pList;
  91584. no_mem:
  91585. /* Avoid leaking memory if malloc has failed. */
  91586. sqlite3ExprDelete(db, pExpr);
  91587. sqlite3ExprListDelete(db, pList);
  91588. return 0;
  91589. }
  91590. /*
  91591. ** pColumns and pExpr form a vector assignment which is part of the SET
  91592. ** clause of an UPDATE statement. Like this:
  91593. **
  91594. ** (a,b,c) = (expr1,expr2,expr3)
  91595. ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
  91596. **
  91597. ** For each term of the vector assignment, append new entries to the
  91598. ** expression list pList. In the case of a subquery on the RHS, append
  91599. ** TK_SELECT_COLUMN expressions.
  91600. */
  91601. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
  91602. Parse *pParse, /* Parsing context */
  91603. ExprList *pList, /* List to which to append. Might be NULL */
  91604. IdList *pColumns, /* List of names of LHS of the assignment */
  91605. Expr *pExpr /* Vector expression to be appended. Might be NULL */
  91606. ){
  91607. sqlite3 *db = pParse->db;
  91608. int n;
  91609. int i;
  91610. int iFirst = pList ? pList->nExpr : 0;
  91611. /* pColumns can only be NULL due to an OOM but an OOM will cause an
  91612. ** exit prior to this routine being invoked */
  91613. if( NEVER(pColumns==0) ) goto vector_append_error;
  91614. if( pExpr==0 ) goto vector_append_error;
  91615. /* If the RHS is a vector, then we can immediately check to see that
  91616. ** the size of the RHS and LHS match. But if the RHS is a SELECT,
  91617. ** wildcards ("*") in the result set of the SELECT must be expanded before
  91618. ** we can do the size check, so defer the size check until code generation.
  91619. */
  91620. if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
  91621. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  91622. pColumns->nId, n);
  91623. goto vector_append_error;
  91624. }
  91625. for(i=0; i<pColumns->nId; i++){
  91626. Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
  91627. pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
  91628. if( pList ){
  91629. assert( pList->nExpr==iFirst+i+1 );
  91630. pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
  91631. pColumns->a[i].zName = 0;
  91632. }
  91633. }
  91634. if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
  91635. Expr *pFirst = pList->a[iFirst].pExpr;
  91636. assert( pFirst!=0 );
  91637. assert( pFirst->op==TK_SELECT_COLUMN );
  91638. /* Store the SELECT statement in pRight so it will be deleted when
  91639. ** sqlite3ExprListDelete() is called */
  91640. pFirst->pRight = pExpr;
  91641. pExpr = 0;
  91642. /* Remember the size of the LHS in iTable so that we can check that
  91643. ** the RHS and LHS sizes match during code generation. */
  91644. pFirst->iTable = pColumns->nId;
  91645. }
  91646. vector_append_error:
  91647. sqlite3ExprDelete(db, pExpr);
  91648. sqlite3IdListDelete(db, pColumns);
  91649. return pList;
  91650. }
  91651. /*
  91652. ** Set the sort order for the last element on the given ExprList.
  91653. */
  91654. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
  91655. if( p==0 ) return;
  91656. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
  91657. assert( p->nExpr>0 );
  91658. if( iSortOrder<0 ){
  91659. assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
  91660. return;
  91661. }
  91662. p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
  91663. }
  91664. /*
  91665. ** Set the ExprList.a[].zName element of the most recently added item
  91666. ** on the expression list.
  91667. **
  91668. ** pList might be NULL following an OOM error. But pName should never be
  91669. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  91670. ** is set.
  91671. */
  91672. SQLITE_PRIVATE void sqlite3ExprListSetName(
  91673. Parse *pParse, /* Parsing context */
  91674. ExprList *pList, /* List to which to add the span. */
  91675. Token *pName, /* Name to be added */
  91676. int dequote /* True to cause the name to be dequoted */
  91677. ){
  91678. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  91679. if( pList ){
  91680. struct ExprList_item *pItem;
  91681. assert( pList->nExpr>0 );
  91682. pItem = &pList->a[pList->nExpr-1];
  91683. assert( pItem->zName==0 );
  91684. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  91685. if( dequote ) sqlite3Dequote(pItem->zName);
  91686. if( IN_RENAME_OBJECT ){
  91687. sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
  91688. }
  91689. }
  91690. }
  91691. /*
  91692. ** Set the ExprList.a[].zSpan element of the most recently added item
  91693. ** on the expression list.
  91694. **
  91695. ** pList might be NULL following an OOM error. But pSpan should never be
  91696. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  91697. ** is set.
  91698. */
  91699. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  91700. Parse *pParse, /* Parsing context */
  91701. ExprList *pList, /* List to which to add the span. */
  91702. const char *zStart, /* Start of the span */
  91703. const char *zEnd /* End of the span */
  91704. ){
  91705. sqlite3 *db = pParse->db;
  91706. assert( pList!=0 || db->mallocFailed!=0 );
  91707. if( pList ){
  91708. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  91709. assert( pList->nExpr>0 );
  91710. sqlite3DbFree(db, pItem->zSpan);
  91711. pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
  91712. }
  91713. }
  91714. /*
  91715. ** If the expression list pEList contains more than iLimit elements,
  91716. ** leave an error message in pParse.
  91717. */
  91718. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  91719. Parse *pParse,
  91720. ExprList *pEList,
  91721. const char *zObject
  91722. ){
  91723. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  91724. testcase( pEList && pEList->nExpr==mx );
  91725. testcase( pEList && pEList->nExpr==mx+1 );
  91726. if( pEList && pEList->nExpr>mx ){
  91727. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  91728. }
  91729. }
  91730. /*
  91731. ** Delete an entire expression list.
  91732. */
  91733. static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
  91734. int i = pList->nExpr;
  91735. struct ExprList_item *pItem = pList->a;
  91736. assert( pList->nExpr>0 );
  91737. do{
  91738. sqlite3ExprDelete(db, pItem->pExpr);
  91739. sqlite3DbFree(db, pItem->zName);
  91740. sqlite3DbFree(db, pItem->zSpan);
  91741. pItem++;
  91742. }while( --i>0 );
  91743. sqlite3DbFreeNN(db, pList);
  91744. }
  91745. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  91746. if( pList ) exprListDeleteNN(db, pList);
  91747. }
  91748. /*
  91749. ** Return the bitwise-OR of all Expr.flags fields in the given
  91750. ** ExprList.
  91751. */
  91752. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  91753. int i;
  91754. u32 m = 0;
  91755. assert( pList!=0 );
  91756. for(i=0; i<pList->nExpr; i++){
  91757. Expr *pExpr = pList->a[i].pExpr;
  91758. assert( pExpr!=0 );
  91759. m |= pExpr->flags;
  91760. }
  91761. return m;
  91762. }
  91763. /*
  91764. ** This is a SELECT-node callback for the expression walker that
  91765. ** always "fails". By "fail" in this case, we mean set
  91766. ** pWalker->eCode to zero and abort.
  91767. **
  91768. ** This callback is used by multiple expression walkers.
  91769. */
  91770. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
  91771. UNUSED_PARAMETER(NotUsed);
  91772. pWalker->eCode = 0;
  91773. return WRC_Abort;
  91774. }
  91775. /*
  91776. ** If the input expression is an ID with the name "true" or "false"
  91777. ** then convert it into an TK_TRUEFALSE term. Return non-zero if
  91778. ** the conversion happened, and zero if the expression is unaltered.
  91779. */
  91780. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
  91781. assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
  91782. if( sqlite3StrICmp(pExpr->u.zToken, "true")==0
  91783. || sqlite3StrICmp(pExpr->u.zToken, "false")==0
  91784. ){
  91785. pExpr->op = TK_TRUEFALSE;
  91786. return 1;
  91787. }
  91788. return 0;
  91789. }
  91790. /*
  91791. ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
  91792. ** and 0 if it is FALSE.
  91793. */
  91794. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){
  91795. assert( pExpr->op==TK_TRUEFALSE );
  91796. assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
  91797. || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
  91798. return pExpr->u.zToken[4]==0;
  91799. }
  91800. /*
  91801. ** These routines are Walker callbacks used to check expressions to
  91802. ** see if they are "constant" for some definition of constant. The
  91803. ** Walker.eCode value determines the type of "constant" we are looking
  91804. ** for.
  91805. **
  91806. ** These callback routines are used to implement the following:
  91807. **
  91808. ** sqlite3ExprIsConstant() pWalker->eCode==1
  91809. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  91810. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  91811. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  91812. **
  91813. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  91814. ** is found to not be a constant.
  91815. **
  91816. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  91817. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  91818. ** an existing schema and 4 when processing a new statement. A bound
  91819. ** parameter raises an error for new statements, but is silently converted
  91820. ** to NULL for existing schemas. This allows sqlite_master tables that
  91821. ** contain a bound parameter because they were generated by older versions
  91822. ** of SQLite to be parsed by newer versions of SQLite without raising a
  91823. ** malformed schema error.
  91824. */
  91825. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  91826. /* If pWalker->eCode is 2 then any term of the expression that comes from
  91827. ** the ON or USING clauses of a left join disqualifies the expression
  91828. ** from being considered constant. */
  91829. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  91830. pWalker->eCode = 0;
  91831. return WRC_Abort;
  91832. }
  91833. switch( pExpr->op ){
  91834. /* Consider functions to be constant if all their arguments are constant
  91835. ** and either pWalker->eCode==4 or 5 or the function has the
  91836. ** SQLITE_FUNC_CONST flag. */
  91837. case TK_FUNCTION:
  91838. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  91839. return WRC_Continue;
  91840. }else{
  91841. pWalker->eCode = 0;
  91842. return WRC_Abort;
  91843. }
  91844. case TK_ID:
  91845. /* Convert "true" or "false" in a DEFAULT clause into the
  91846. ** appropriate TK_TRUEFALSE operator */
  91847. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  91848. return WRC_Prune;
  91849. }
  91850. /* Fall thru */
  91851. case TK_COLUMN:
  91852. case TK_AGG_FUNCTION:
  91853. case TK_AGG_COLUMN:
  91854. testcase( pExpr->op==TK_ID );
  91855. testcase( pExpr->op==TK_COLUMN );
  91856. testcase( pExpr->op==TK_AGG_FUNCTION );
  91857. testcase( pExpr->op==TK_AGG_COLUMN );
  91858. if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
  91859. return WRC_Continue;
  91860. }
  91861. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  91862. return WRC_Continue;
  91863. }
  91864. /* Fall through */
  91865. case TK_IF_NULL_ROW:
  91866. case TK_REGISTER:
  91867. testcase( pExpr->op==TK_REGISTER );
  91868. testcase( pExpr->op==TK_IF_NULL_ROW );
  91869. pWalker->eCode = 0;
  91870. return WRC_Abort;
  91871. case TK_VARIABLE:
  91872. if( pWalker->eCode==5 ){
  91873. /* Silently convert bound parameters that appear inside of CREATE
  91874. ** statements into a NULL when parsing the CREATE statement text out
  91875. ** of the sqlite_master table */
  91876. pExpr->op = TK_NULL;
  91877. }else if( pWalker->eCode==4 ){
  91878. /* A bound parameter in a CREATE statement that originates from
  91879. ** sqlite3_prepare() causes an error */
  91880. pWalker->eCode = 0;
  91881. return WRC_Abort;
  91882. }
  91883. /* Fall through */
  91884. default:
  91885. testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
  91886. testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
  91887. return WRC_Continue;
  91888. }
  91889. }
  91890. static int exprIsConst(Expr *p, int initFlag, int iCur){
  91891. Walker w;
  91892. w.eCode = initFlag;
  91893. w.xExprCallback = exprNodeIsConstant;
  91894. w.xSelectCallback = sqlite3SelectWalkFail;
  91895. #ifdef SQLITE_DEBUG
  91896. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  91897. #endif
  91898. w.u.iCur = iCur;
  91899. sqlite3WalkExpr(&w, p);
  91900. return w.eCode;
  91901. }
  91902. /*
  91903. ** Walk an expression tree. Return non-zero if the expression is constant
  91904. ** and 0 if it involves variables or function calls.
  91905. **
  91906. ** For the purposes of this function, a double-quoted string (ex: "abc")
  91907. ** is considered a variable but a single-quoted string (ex: 'abc') is
  91908. ** a constant.
  91909. */
  91910. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  91911. return exprIsConst(p, 1, 0);
  91912. }
  91913. /*
  91914. ** Walk an expression tree. Return non-zero if
  91915. **
  91916. ** (1) the expression is constant, and
  91917. ** (2) the expression does originate in the ON or USING clause
  91918. ** of a LEFT JOIN, and
  91919. ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
  91920. ** operands created by the constant propagation optimization.
  91921. **
  91922. ** When this routine returns true, it indicates that the expression
  91923. ** can be added to the pParse->pConstExpr list and evaluated once when
  91924. ** the prepared statement starts up. See sqlite3ExprCodeAtInit().
  91925. */
  91926. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  91927. return exprIsConst(p, 2, 0);
  91928. }
  91929. /*
  91930. ** Walk an expression tree. Return non-zero if the expression is constant
  91931. ** for any single row of the table with cursor iCur. In other words, the
  91932. ** expression must not refer to any non-deterministic function nor any
  91933. ** table other than iCur.
  91934. */
  91935. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  91936. return exprIsConst(p, 3, iCur);
  91937. }
  91938. /*
  91939. ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
  91940. */
  91941. static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
  91942. ExprList *pGroupBy = pWalker->u.pGroupBy;
  91943. int i;
  91944. /* Check if pExpr is identical to any GROUP BY term. If so, consider
  91945. ** it constant. */
  91946. for(i=0; i<pGroupBy->nExpr; i++){
  91947. Expr *p = pGroupBy->a[i].pExpr;
  91948. if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
  91949. CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
  91950. if( sqlite3IsBinary(pColl) ){
  91951. return WRC_Prune;
  91952. }
  91953. }
  91954. }
  91955. /* Check if pExpr is a sub-select. If so, consider it variable. */
  91956. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  91957. pWalker->eCode = 0;
  91958. return WRC_Abort;
  91959. }
  91960. return exprNodeIsConstant(pWalker, pExpr);
  91961. }
  91962. /*
  91963. ** Walk the expression tree passed as the first argument. Return non-zero
  91964. ** if the expression consists entirely of constants or copies of terms
  91965. ** in pGroupBy that sort with the BINARY collation sequence.
  91966. **
  91967. ** This routine is used to determine if a term of the HAVING clause can
  91968. ** be promoted into the WHERE clause. In order for such a promotion to work,
  91969. ** the value of the HAVING clause term must be the same for all members of
  91970. ** a "group". The requirement that the GROUP BY term must be BINARY
  91971. ** assumes that no other collating sequence will have a finer-grained
  91972. ** grouping than binary. In other words (A=B COLLATE binary) implies
  91973. ** A=B in every other collating sequence. The requirement that the
  91974. ** GROUP BY be BINARY is stricter than necessary. It would also work
  91975. ** to promote HAVING clauses that use the same alternative collating
  91976. ** sequence as the GROUP BY term, but that is much harder to check,
  91977. ** alternative collating sequences are uncommon, and this is only an
  91978. ** optimization, so we take the easy way out and simply require the
  91979. ** GROUP BY to use the BINARY collating sequence.
  91980. */
  91981. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
  91982. Walker w;
  91983. w.eCode = 1;
  91984. w.xExprCallback = exprNodeIsConstantOrGroupBy;
  91985. w.xSelectCallback = 0;
  91986. w.u.pGroupBy = pGroupBy;
  91987. w.pParse = pParse;
  91988. sqlite3WalkExpr(&w, p);
  91989. return w.eCode;
  91990. }
  91991. /*
  91992. ** Walk an expression tree. Return non-zero if the expression is constant
  91993. ** or a function call with constant arguments. Return and 0 if there
  91994. ** are any variables.
  91995. **
  91996. ** For the purposes of this function, a double-quoted string (ex: "abc")
  91997. ** is considered a variable but a single-quoted string (ex: 'abc') is
  91998. ** a constant.
  91999. */
  92000. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  92001. assert( isInit==0 || isInit==1 );
  92002. return exprIsConst(p, 4+isInit, 0);
  92003. }
  92004. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  92005. /*
  92006. ** Walk an expression tree. Return 1 if the expression contains a
  92007. ** subquery of some kind. Return 0 if there are no subqueries.
  92008. */
  92009. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
  92010. Walker w;
  92011. w.eCode = 1;
  92012. w.xExprCallback = sqlite3ExprWalkNoop;
  92013. w.xSelectCallback = sqlite3SelectWalkFail;
  92014. #ifdef SQLITE_DEBUG
  92015. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  92016. #endif
  92017. sqlite3WalkExpr(&w, p);
  92018. return w.eCode==0;
  92019. }
  92020. #endif
  92021. /*
  92022. ** If the expression p codes a constant integer that is small enough
  92023. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  92024. ** in *pValue. If the expression is not an integer or if it is too big
  92025. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  92026. */
  92027. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  92028. int rc = 0;
  92029. if( p==0 ) return 0; /* Can only happen following on OOM */
  92030. /* If an expression is an integer literal that fits in a signed 32-bit
  92031. ** integer, then the EP_IntValue flag will have already been set */
  92032. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  92033. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  92034. if( p->flags & EP_IntValue ){
  92035. *pValue = p->u.iValue;
  92036. return 1;
  92037. }
  92038. switch( p->op ){
  92039. case TK_UPLUS: {
  92040. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  92041. break;
  92042. }
  92043. case TK_UMINUS: {
  92044. int v;
  92045. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  92046. assert( v!=(-2147483647-1) );
  92047. *pValue = -v;
  92048. rc = 1;
  92049. }
  92050. break;
  92051. }
  92052. default: break;
  92053. }
  92054. return rc;
  92055. }
  92056. /*
  92057. ** Return FALSE if there is no chance that the expression can be NULL.
  92058. **
  92059. ** If the expression might be NULL or if the expression is too complex
  92060. ** to tell return TRUE.
  92061. **
  92062. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  92063. ** when we know that a value cannot be NULL. Hence, a false positive
  92064. ** (returning TRUE when in fact the expression can never be NULL) might
  92065. ** be a small performance hit but is otherwise harmless. On the other
  92066. ** hand, a false negative (returning FALSE when the result could be NULL)
  92067. ** will likely result in an incorrect answer. So when in doubt, return
  92068. ** TRUE.
  92069. */
  92070. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  92071. u8 op;
  92072. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  92073. op = p->op;
  92074. if( op==TK_REGISTER ) op = p->op2;
  92075. switch( op ){
  92076. case TK_INTEGER:
  92077. case TK_STRING:
  92078. case TK_FLOAT:
  92079. case TK_BLOB:
  92080. return 0;
  92081. case TK_COLUMN:
  92082. return ExprHasProperty(p, EP_CanBeNull) ||
  92083. p->y.pTab==0 || /* Reference to column of index on expression */
  92084. (p->iColumn>=0 && p->y.pTab->aCol[p->iColumn].notNull==0);
  92085. default:
  92086. return 1;
  92087. }
  92088. }
  92089. /*
  92090. ** Return TRUE if the given expression is a constant which would be
  92091. ** unchanged by OP_Affinity with the affinity given in the second
  92092. ** argument.
  92093. **
  92094. ** This routine is used to determine if the OP_Affinity operation
  92095. ** can be omitted. When in doubt return FALSE. A false negative
  92096. ** is harmless. A false positive, however, can result in the wrong
  92097. ** answer.
  92098. */
  92099. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  92100. u8 op;
  92101. if( aff==SQLITE_AFF_BLOB ) return 1;
  92102. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  92103. op = p->op;
  92104. if( op==TK_REGISTER ) op = p->op2;
  92105. switch( op ){
  92106. case TK_INTEGER: {
  92107. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  92108. }
  92109. case TK_FLOAT: {
  92110. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  92111. }
  92112. case TK_STRING: {
  92113. return aff==SQLITE_AFF_TEXT;
  92114. }
  92115. case TK_BLOB: {
  92116. return 1;
  92117. }
  92118. case TK_COLUMN: {
  92119. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  92120. return p->iColumn<0
  92121. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  92122. }
  92123. default: {
  92124. return 0;
  92125. }
  92126. }
  92127. }
  92128. /*
  92129. ** Return TRUE if the given string is a row-id column name.
  92130. */
  92131. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  92132. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  92133. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  92134. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  92135. return 0;
  92136. }
  92137. #ifdef SQLITE_ENABLE_NORMALIZE
  92138. SQLITE_PRIVATE int sqlite3IsRowidN(const char *z, int n){
  92139. if( sqlite3StrNICmp(z, "_ROWID_", n)==0 ) return 1;
  92140. if( sqlite3StrNICmp(z, "ROWID", n)==0 ) return 1;
  92141. if( sqlite3StrNICmp(z, "OID", n)==0 ) return 1;
  92142. return 0;
  92143. }
  92144. #endif
  92145. /*
  92146. ** pX is the RHS of an IN operator. If pX is a SELECT statement
  92147. ** that can be simplified to a direct table access, then return
  92148. ** a pointer to the SELECT statement. If pX is not a SELECT statement,
  92149. ** or if the SELECT statement needs to be manifested into a transient
  92150. ** table, then return NULL.
  92151. */
  92152. #ifndef SQLITE_OMIT_SUBQUERY
  92153. static Select *isCandidateForInOpt(Expr *pX){
  92154. Select *p;
  92155. SrcList *pSrc;
  92156. ExprList *pEList;
  92157. Table *pTab;
  92158. int i;
  92159. if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
  92160. if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
  92161. p = pX->x.pSelect;
  92162. if( p->pPrior ) return 0; /* Not a compound SELECT */
  92163. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  92164. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  92165. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  92166. return 0; /* No DISTINCT keyword and no aggregate functions */
  92167. }
  92168. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  92169. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  92170. if( p->pWhere ) return 0; /* Has no WHERE clause */
  92171. pSrc = p->pSrc;
  92172. assert( pSrc!=0 );
  92173. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  92174. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  92175. pTab = pSrc->a[0].pTab;
  92176. assert( pTab!=0 );
  92177. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  92178. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  92179. pEList = p->pEList;
  92180. assert( pEList!=0 );
  92181. /* All SELECT results must be columns. */
  92182. for(i=0; i<pEList->nExpr; i++){
  92183. Expr *pRes = pEList->a[i].pExpr;
  92184. if( pRes->op!=TK_COLUMN ) return 0;
  92185. assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
  92186. }
  92187. return p;
  92188. }
  92189. #endif /* SQLITE_OMIT_SUBQUERY */
  92190. #ifndef SQLITE_OMIT_SUBQUERY
  92191. /*
  92192. ** Generate code that checks the left-most column of index table iCur to see if
  92193. ** it contains any NULL entries. Cause the register at regHasNull to be set
  92194. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  92195. ** to be set to NULL if iCur contains one or more NULL values.
  92196. */
  92197. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  92198. int addr1;
  92199. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  92200. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  92201. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  92202. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  92203. VdbeComment((v, "first_entry_in(%d)", iCur));
  92204. sqlite3VdbeJumpHere(v, addr1);
  92205. }
  92206. #endif
  92207. #ifndef SQLITE_OMIT_SUBQUERY
  92208. /*
  92209. ** The argument is an IN operator with a list (not a subquery) on the
  92210. ** right-hand side. Return TRUE if that list is constant.
  92211. */
  92212. static int sqlite3InRhsIsConstant(Expr *pIn){
  92213. Expr *pLHS;
  92214. int res;
  92215. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  92216. pLHS = pIn->pLeft;
  92217. pIn->pLeft = 0;
  92218. res = sqlite3ExprIsConstant(pIn);
  92219. pIn->pLeft = pLHS;
  92220. return res;
  92221. }
  92222. #endif
  92223. /*
  92224. ** This function is used by the implementation of the IN (...) operator.
  92225. ** The pX parameter is the expression on the RHS of the IN operator, which
  92226. ** might be either a list of expressions or a subquery.
  92227. **
  92228. ** The job of this routine is to find or create a b-tree object that can
  92229. ** be used either to test for membership in the RHS set or to iterate through
  92230. ** all members of the RHS set, skipping duplicates.
  92231. **
  92232. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  92233. ** and pX->iTable is set to the index of that cursor.
  92234. **
  92235. ** The returned value of this function indicates the b-tree type, as follows:
  92236. **
  92237. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  92238. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  92239. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  92240. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  92241. ** populated epheremal table.
  92242. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  92243. ** implemented as a sequence of comparisons.
  92244. **
  92245. ** An existing b-tree might be used if the RHS expression pX is a simple
  92246. ** subquery such as:
  92247. **
  92248. ** SELECT <column1>, <column2>... FROM <table>
  92249. **
  92250. ** If the RHS of the IN operator is a list or a more complex subquery, then
  92251. ** an ephemeral table might need to be generated from the RHS and then
  92252. ** pX->iTable made to point to the ephemeral table instead of an
  92253. ** existing table.
  92254. **
  92255. ** The inFlags parameter must contain, at a minimum, one of the bits
  92256. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
  92257. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
  92258. ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
  92259. ** be used to loop over all values of the RHS of the IN operator.
  92260. **
  92261. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  92262. ** through the set members) then the b-tree must not contain duplicates.
  92263. ** An epheremal table will be created unless the selected columns are guaranteed
  92264. ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
  92265. ** a UNIQUE constraint or index.
  92266. **
  92267. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  92268. ** for fast set membership tests) then an epheremal table must
  92269. ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
  92270. ** index can be found with the specified <columns> as its left-most.
  92271. **
  92272. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  92273. ** if the RHS of the IN operator is a list (not a subquery) then this
  92274. ** routine might decide that creating an ephemeral b-tree for membership
  92275. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  92276. ** calling routine should implement the IN operator using a sequence
  92277. ** of Eq or Ne comparison operations.
  92278. **
  92279. ** When the b-tree is being used for membership tests, the calling function
  92280. ** might need to know whether or not the RHS side of the IN operator
  92281. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  92282. ** if there is any chance that the (...) might contain a NULL value at
  92283. ** runtime, then a register is allocated and the register number written
  92284. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  92285. ** NULL value, then *prRhsHasNull is left unchanged.
  92286. **
  92287. ** If a register is allocated and its location stored in *prRhsHasNull, then
  92288. ** the value in that register will be NULL if the b-tree contains one or more
  92289. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  92290. ** NULL values.
  92291. **
  92292. ** If the aiMap parameter is not NULL, it must point to an array containing
  92293. ** one element for each column returned by the SELECT statement on the RHS
  92294. ** of the IN(...) operator. The i'th entry of the array is populated with the
  92295. ** offset of the index column that matches the i'th column returned by the
  92296. ** SELECT. For example, if the expression and selected index are:
  92297. **
  92298. ** (?,?,?) IN (SELECT a, b, c FROM t1)
  92299. ** CREATE INDEX i1 ON t1(b, c, a);
  92300. **
  92301. ** then aiMap[] is populated with {2, 0, 1}.
  92302. */
  92303. #ifndef SQLITE_OMIT_SUBQUERY
  92304. SQLITE_PRIVATE int sqlite3FindInIndex(
  92305. Parse *pParse, /* Parsing context */
  92306. Expr *pX, /* The right-hand side (RHS) of the IN operator */
  92307. u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
  92308. int *prRhsHasNull, /* Register holding NULL status. See notes */
  92309. int *aiMap /* Mapping from Index fields to RHS fields */
  92310. ){
  92311. Select *p; /* SELECT to the right of IN operator */
  92312. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  92313. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  92314. int mustBeUnique; /* True if RHS must be unique */
  92315. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  92316. assert( pX->op==TK_IN );
  92317. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  92318. /* If the RHS of this IN(...) operator is a SELECT, and if it matters
  92319. ** whether or not the SELECT result contains NULL values, check whether
  92320. ** or not NULL is actually possible (it may not be, for example, due
  92321. ** to NOT NULL constraints in the schema). If no NULL values are possible,
  92322. ** set prRhsHasNull to 0 before continuing. */
  92323. if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
  92324. int i;
  92325. ExprList *pEList = pX->x.pSelect->pEList;
  92326. for(i=0; i<pEList->nExpr; i++){
  92327. if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
  92328. }
  92329. if( i==pEList->nExpr ){
  92330. prRhsHasNull = 0;
  92331. }
  92332. }
  92333. /* Check to see if an existing table or index can be used to
  92334. ** satisfy the query. This is preferable to generating a new
  92335. ** ephemeral table. */
  92336. if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
  92337. sqlite3 *db = pParse->db; /* Database connection */
  92338. Table *pTab; /* Table <table>. */
  92339. i16 iDb; /* Database idx for pTab */
  92340. ExprList *pEList = p->pEList;
  92341. int nExpr = pEList->nExpr;
  92342. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  92343. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  92344. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  92345. pTab = p->pSrc->a[0].pTab;
  92346. /* Code an OP_Transaction and OP_TableLock for <table>. */
  92347. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  92348. sqlite3CodeVerifySchema(pParse, iDb);
  92349. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  92350. assert(v); /* sqlite3GetVdbe() has always been previously called */
  92351. if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
  92352. /* The "x IN (SELECT rowid FROM table)" case */
  92353. int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
  92354. VdbeCoverage(v);
  92355. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  92356. eType = IN_INDEX_ROWID;
  92357. ExplainQueryPlan((pParse, 0,
  92358. "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
  92359. sqlite3VdbeJumpHere(v, iAddr);
  92360. }else{
  92361. Index *pIdx; /* Iterator variable */
  92362. int affinity_ok = 1;
  92363. int i;
  92364. /* Check that the affinity that will be used to perform each
  92365. ** comparison is the same as the affinity of each column in table
  92366. ** on the RHS of the IN operator. If it not, it is not possible to
  92367. ** use any index of the RHS table. */
  92368. for(i=0; i<nExpr && affinity_ok; i++){
  92369. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  92370. int iCol = pEList->a[i].pExpr->iColumn;
  92371. char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
  92372. char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
  92373. testcase( cmpaff==SQLITE_AFF_BLOB );
  92374. testcase( cmpaff==SQLITE_AFF_TEXT );
  92375. switch( cmpaff ){
  92376. case SQLITE_AFF_BLOB:
  92377. break;
  92378. case SQLITE_AFF_TEXT:
  92379. /* sqlite3CompareAffinity() only returns TEXT if one side or the
  92380. ** other has no affinity and the other side is TEXT. Hence,
  92381. ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
  92382. ** and for the term on the LHS of the IN to have no affinity. */
  92383. assert( idxaff==SQLITE_AFF_TEXT );
  92384. break;
  92385. default:
  92386. affinity_ok = sqlite3IsNumericAffinity(idxaff);
  92387. }
  92388. }
  92389. if( affinity_ok ){
  92390. /* Search for an existing index that will work for this IN operator */
  92391. for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
  92392. Bitmask colUsed; /* Columns of the index used */
  92393. Bitmask mCol; /* Mask for the current column */
  92394. if( pIdx->nColumn<nExpr ) continue;
  92395. /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
  92396. ** BITMASK(nExpr) without overflowing */
  92397. testcase( pIdx->nColumn==BMS-2 );
  92398. testcase( pIdx->nColumn==BMS-1 );
  92399. if( pIdx->nColumn>=BMS-1 ) continue;
  92400. if( mustBeUnique ){
  92401. if( pIdx->nKeyCol>nExpr
  92402. ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
  92403. ){
  92404. continue; /* This index is not unique over the IN RHS columns */
  92405. }
  92406. }
  92407. colUsed = 0; /* Columns of index used so far */
  92408. for(i=0; i<nExpr; i++){
  92409. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  92410. Expr *pRhs = pEList->a[i].pExpr;
  92411. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  92412. int j;
  92413. assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
  92414. for(j=0; j<nExpr; j++){
  92415. if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
  92416. assert( pIdx->azColl[j] );
  92417. if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
  92418. continue;
  92419. }
  92420. break;
  92421. }
  92422. if( j==nExpr ) break;
  92423. mCol = MASKBIT(j);
  92424. if( mCol & colUsed ) break; /* Each column used only once */
  92425. colUsed |= mCol;
  92426. if( aiMap ) aiMap[i] = j;
  92427. }
  92428. assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
  92429. if( colUsed==(MASKBIT(nExpr)-1) ){
  92430. /* If we reach this point, that means the index pIdx is usable */
  92431. int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  92432. ExplainQueryPlan((pParse, 0,
  92433. "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
  92434. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  92435. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  92436. VdbeComment((v, "%s", pIdx->zName));
  92437. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  92438. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  92439. if( prRhsHasNull ){
  92440. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  92441. i64 mask = (1<<nExpr)-1;
  92442. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
  92443. iTab, 0, 0, (u8*)&mask, P4_INT64);
  92444. #endif
  92445. *prRhsHasNull = ++pParse->nMem;
  92446. if( nExpr==1 ){
  92447. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  92448. }
  92449. }
  92450. sqlite3VdbeJumpHere(v, iAddr);
  92451. }
  92452. } /* End loop over indexes */
  92453. } /* End if( affinity_ok ) */
  92454. } /* End if not an rowid index */
  92455. } /* End attempt to optimize using an index */
  92456. /* If no preexisting index is available for the IN clause
  92457. ** and IN_INDEX_NOOP is an allowed reply
  92458. ** and the RHS of the IN operator is a list, not a subquery
  92459. ** and the RHS is not constant or has two or fewer terms,
  92460. ** then it is not worth creating an ephemeral table to evaluate
  92461. ** the IN operator so return IN_INDEX_NOOP.
  92462. */
  92463. if( eType==0
  92464. && (inFlags & IN_INDEX_NOOP_OK)
  92465. && !ExprHasProperty(pX, EP_xIsSelect)
  92466. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  92467. ){
  92468. eType = IN_INDEX_NOOP;
  92469. }
  92470. if( eType==0 ){
  92471. /* Could not find an existing table or index to use as the RHS b-tree.
  92472. ** We will have to generate an ephemeral table to do the job.
  92473. */
  92474. u32 savedNQueryLoop = pParse->nQueryLoop;
  92475. int rMayHaveNull = 0;
  92476. eType = IN_INDEX_EPH;
  92477. if( inFlags & IN_INDEX_LOOP ){
  92478. pParse->nQueryLoop = 0;
  92479. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  92480. eType = IN_INDEX_ROWID;
  92481. }
  92482. }else if( prRhsHasNull ){
  92483. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  92484. }
  92485. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  92486. pParse->nQueryLoop = savedNQueryLoop;
  92487. }else{
  92488. pX->iTable = iTab;
  92489. }
  92490. if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
  92491. int i, n;
  92492. n = sqlite3ExprVectorSize(pX->pLeft);
  92493. for(i=0; i<n; i++) aiMap[i] = i;
  92494. }
  92495. return eType;
  92496. }
  92497. #endif
  92498. #ifndef SQLITE_OMIT_SUBQUERY
  92499. /*
  92500. ** Argument pExpr is an (?, ?...) IN(...) expression. This
  92501. ** function allocates and returns a nul-terminated string containing
  92502. ** the affinities to be used for each column of the comparison.
  92503. **
  92504. ** It is the responsibility of the caller to ensure that the returned
  92505. ** string is eventually freed using sqlite3DbFree().
  92506. */
  92507. static char *exprINAffinity(Parse *pParse, Expr *pExpr){
  92508. Expr *pLeft = pExpr->pLeft;
  92509. int nVal = sqlite3ExprVectorSize(pLeft);
  92510. Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
  92511. char *zRet;
  92512. assert( pExpr->op==TK_IN );
  92513. zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
  92514. if( zRet ){
  92515. int i;
  92516. for(i=0; i<nVal; i++){
  92517. Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
  92518. char a = sqlite3ExprAffinity(pA);
  92519. if( pSelect ){
  92520. zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
  92521. }else{
  92522. zRet[i] = a;
  92523. }
  92524. }
  92525. zRet[nVal] = '\0';
  92526. }
  92527. return zRet;
  92528. }
  92529. #endif
  92530. #ifndef SQLITE_OMIT_SUBQUERY
  92531. /*
  92532. ** Load the Parse object passed as the first argument with an error
  92533. ** message of the form:
  92534. **
  92535. ** "sub-select returns N columns - expected M"
  92536. */
  92537. SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
  92538. const char *zFmt = "sub-select returns %d columns - expected %d";
  92539. sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
  92540. }
  92541. #endif
  92542. /*
  92543. ** Expression pExpr is a vector that has been used in a context where
  92544. ** it is not permitted. If pExpr is a sub-select vector, this routine
  92545. ** loads the Parse object with a message of the form:
  92546. **
  92547. ** "sub-select returns N columns - expected 1"
  92548. **
  92549. ** Or, if it is a regular scalar vector:
  92550. **
  92551. ** "row value misused"
  92552. */
  92553. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
  92554. #ifndef SQLITE_OMIT_SUBQUERY
  92555. if( pExpr->flags & EP_xIsSelect ){
  92556. sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
  92557. }else
  92558. #endif
  92559. {
  92560. sqlite3ErrorMsg(pParse, "row value misused");
  92561. }
  92562. }
  92563. /*
  92564. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  92565. ** or IN operators. Examples:
  92566. **
  92567. ** (SELECT a FROM b) -- subquery
  92568. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  92569. ** x IN (4,5,11) -- IN operator with list on right-hand side
  92570. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  92571. **
  92572. ** The pExpr parameter describes the expression that contains the IN
  92573. ** operator or subquery.
  92574. **
  92575. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  92576. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  92577. ** to some integer key column of a table B-Tree. In this case, use an
  92578. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  92579. ** (slower) variable length keys B-Tree.
  92580. **
  92581. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  92582. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  92583. ** All this routine does is initialize the register given by rMayHaveNull
  92584. ** to NULL. Calling routines will take care of changing this register
  92585. ** value to non-NULL if the RHS is NULL-free.
  92586. **
  92587. ** For a SELECT or EXISTS operator, return the register that holds the
  92588. ** result. For a multi-column SELECT, the result is stored in a contiguous
  92589. ** array of registers and the return value is the register of the left-most
  92590. ** result column. Return 0 for IN operators or if an error occurs.
  92591. */
  92592. #ifndef SQLITE_OMIT_SUBQUERY
  92593. SQLITE_PRIVATE int sqlite3CodeSubselect(
  92594. Parse *pParse, /* Parsing context */
  92595. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  92596. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  92597. int isRowid /* If true, LHS of IN operator is a rowid */
  92598. ){
  92599. int jmpIfDynamic = -1; /* One-time test address */
  92600. int rReg = 0; /* Register storing resulting */
  92601. Vdbe *v = sqlite3GetVdbe(pParse);
  92602. if( NEVER(v==0) ) return 0;
  92603. /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
  92604. ** is encountered if any of the following is true:
  92605. **
  92606. ** * The right-hand side is a correlated subquery
  92607. ** * The right-hand side is an expression list containing variables
  92608. ** * We are inside a trigger
  92609. **
  92610. ** If all of the above are false, then we can run this code just once
  92611. ** save the results, and reuse the same result on subsequent invocations.
  92612. */
  92613. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  92614. jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  92615. }
  92616. switch( pExpr->op ){
  92617. case TK_IN: {
  92618. int addr; /* Address of OP_OpenEphemeral instruction */
  92619. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  92620. KeyInfo *pKeyInfo = 0; /* Key information */
  92621. int nVal; /* Size of vector pLeft */
  92622. nVal = sqlite3ExprVectorSize(pLeft);
  92623. assert( !isRowid || nVal==1 );
  92624. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  92625. ** expression it is handled the same way. An ephemeral table is
  92626. ** filled with index keys representing the results from the
  92627. ** SELECT or the <exprlist>.
  92628. **
  92629. ** If the 'x' expression is a column value, or the SELECT...
  92630. ** statement returns a column value, then the affinity of that
  92631. ** column is used to build the index keys. If both 'x' and the
  92632. ** SELECT... statement are columns, then numeric affinity is used
  92633. ** if either column has NUMERIC or INTEGER affinity. If neither
  92634. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  92635. ** is used.
  92636. */
  92637. pExpr->iTable = pParse->nTab++;
  92638. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
  92639. pExpr->iTable, (isRowid?0:nVal));
  92640. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
  92641. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  92642. /* Case 1: expr IN (SELECT ...)
  92643. **
  92644. ** Generate code to write the results of the select into the temporary
  92645. ** table allocated and opened above.
  92646. */
  92647. Select *pSelect = pExpr->x.pSelect;
  92648. ExprList *pEList = pSelect->pEList;
  92649. ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY",
  92650. jmpIfDynamic>=0?"":"CORRELATED "
  92651. ));
  92652. assert( !isRowid );
  92653. /* If the LHS and RHS of the IN operator do not match, that
  92654. ** error will have been caught long before we reach this point. */
  92655. if( ALWAYS(pEList->nExpr==nVal) ){
  92656. SelectDest dest;
  92657. int i;
  92658. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  92659. dest.zAffSdst = exprINAffinity(pParse, pExpr);
  92660. pSelect->iLimit = 0;
  92661. testcase( pSelect->selFlags & SF_Distinct );
  92662. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  92663. if( sqlite3Select(pParse, pSelect, &dest) ){
  92664. sqlite3DbFree(pParse->db, dest.zAffSdst);
  92665. sqlite3KeyInfoUnref(pKeyInfo);
  92666. return 0;
  92667. }
  92668. sqlite3DbFree(pParse->db, dest.zAffSdst);
  92669. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  92670. assert( pEList!=0 );
  92671. assert( pEList->nExpr>0 );
  92672. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  92673. for(i=0; i<nVal; i++){
  92674. Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
  92675. pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
  92676. pParse, p, pEList->a[i].pExpr
  92677. );
  92678. }
  92679. }
  92680. }else if( ALWAYS(pExpr->x.pList!=0) ){
  92681. /* Case 2: expr IN (exprlist)
  92682. **
  92683. ** For each expression, build an index key from the evaluation and
  92684. ** store it in the temporary table. If <expr> is a column, then use
  92685. ** that columns affinity when building index keys. If <expr> is not
  92686. ** a column, use numeric affinity.
  92687. */
  92688. char affinity; /* Affinity of the LHS of the IN */
  92689. int i;
  92690. ExprList *pList = pExpr->x.pList;
  92691. struct ExprList_item *pItem;
  92692. int r1, r2, r3;
  92693. affinity = sqlite3ExprAffinity(pLeft);
  92694. if( !affinity ){
  92695. affinity = SQLITE_AFF_BLOB;
  92696. }
  92697. if( pKeyInfo ){
  92698. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  92699. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  92700. }
  92701. /* Loop through each expression in <exprlist>. */
  92702. r1 = sqlite3GetTempReg(pParse);
  92703. r2 = sqlite3GetTempReg(pParse);
  92704. if( isRowid ) sqlite3VdbeAddOp4(v, OP_Blob, 0, r2, 0, "", P4_STATIC);
  92705. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  92706. Expr *pE2 = pItem->pExpr;
  92707. int iValToIns;
  92708. /* If the expression is not constant then we will need to
  92709. ** disable the test that was generated above that makes sure
  92710. ** this code only executes once. Because for a non-constant
  92711. ** expression we need to rerun this code each time.
  92712. */
  92713. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  92714. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  92715. jmpIfDynamic = -1;
  92716. }
  92717. /* Evaluate the expression and insert it into the temp table */
  92718. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  92719. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  92720. }else{
  92721. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  92722. if( isRowid ){
  92723. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  92724. sqlite3VdbeCurrentAddr(v)+2);
  92725. VdbeCoverage(v);
  92726. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  92727. }else{
  92728. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  92729. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
  92730. }
  92731. }
  92732. }
  92733. sqlite3ReleaseTempReg(pParse, r1);
  92734. sqlite3ReleaseTempReg(pParse, r2);
  92735. }
  92736. if( pKeyInfo ){
  92737. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  92738. }
  92739. break;
  92740. }
  92741. case TK_EXISTS:
  92742. case TK_SELECT:
  92743. default: {
  92744. /* Case 3: (SELECT ... FROM ...)
  92745. ** or: EXISTS(SELECT ... FROM ...)
  92746. **
  92747. ** For a SELECT, generate code to put the values for all columns of
  92748. ** the first row into an array of registers and return the index of
  92749. ** the first register.
  92750. **
  92751. ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
  92752. ** into a register and return that register number.
  92753. **
  92754. ** In both cases, the query is augmented with "LIMIT 1". Any
  92755. ** preexisting limit is discarded in place of the new LIMIT 1.
  92756. */
  92757. Select *pSel; /* SELECT statement to encode */
  92758. SelectDest dest; /* How to deal with SELECT result */
  92759. int nReg; /* Registers to allocate */
  92760. Expr *pLimit; /* New limit expression */
  92761. testcase( pExpr->op==TK_EXISTS );
  92762. testcase( pExpr->op==TK_SELECT );
  92763. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  92764. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  92765. pSel = pExpr->x.pSelect;
  92766. ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY",
  92767. jmpIfDynamic>=0?"":"CORRELATED "));
  92768. nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
  92769. sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
  92770. pParse->nMem += nReg;
  92771. if( pExpr->op==TK_SELECT ){
  92772. dest.eDest = SRT_Mem;
  92773. dest.iSdst = dest.iSDParm;
  92774. dest.nSdst = nReg;
  92775. sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
  92776. VdbeComment((v, "Init subquery result"));
  92777. }else{
  92778. dest.eDest = SRT_Exists;
  92779. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  92780. VdbeComment((v, "Init EXISTS result"));
  92781. }
  92782. pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[1], 0);
  92783. if( pSel->pLimit ){
  92784. sqlite3ExprDelete(pParse->db, pSel->pLimit->pLeft);
  92785. pSel->pLimit->pLeft = pLimit;
  92786. }else{
  92787. pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
  92788. }
  92789. pSel->iLimit = 0;
  92790. if( sqlite3Select(pParse, pSel, &dest) ){
  92791. return 0;
  92792. }
  92793. rReg = dest.iSDParm;
  92794. ExprSetVVAProperty(pExpr, EP_NoReduce);
  92795. break;
  92796. }
  92797. }
  92798. if( rHasNullFlag ){
  92799. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  92800. }
  92801. if( jmpIfDynamic>=0 ){
  92802. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  92803. }
  92804. return rReg;
  92805. }
  92806. #endif /* SQLITE_OMIT_SUBQUERY */
  92807. #ifndef SQLITE_OMIT_SUBQUERY
  92808. /*
  92809. ** Expr pIn is an IN(...) expression. This function checks that the
  92810. ** sub-select on the RHS of the IN() operator has the same number of
  92811. ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
  92812. ** a sub-query, that the LHS is a vector of size 1.
  92813. */
  92814. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
  92815. int nVector = sqlite3ExprVectorSize(pIn->pLeft);
  92816. if( (pIn->flags & EP_xIsSelect) ){
  92817. if( nVector!=pIn->x.pSelect->pEList->nExpr ){
  92818. sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
  92819. return 1;
  92820. }
  92821. }else if( nVector!=1 ){
  92822. sqlite3VectorErrorMsg(pParse, pIn->pLeft);
  92823. return 1;
  92824. }
  92825. return 0;
  92826. }
  92827. #endif
  92828. #ifndef SQLITE_OMIT_SUBQUERY
  92829. /*
  92830. ** Generate code for an IN expression.
  92831. **
  92832. ** x IN (SELECT ...)
  92833. ** x IN (value, value, ...)
  92834. **
  92835. ** The left-hand side (LHS) is a scalar or vector expression. The
  92836. ** right-hand side (RHS) is an array of zero or more scalar values, or a
  92837. ** subquery. If the RHS is a subquery, the number of result columns must
  92838. ** match the number of columns in the vector on the LHS. If the RHS is
  92839. ** a list of values, the LHS must be a scalar.
  92840. **
  92841. ** The IN operator is true if the LHS value is contained within the RHS.
  92842. ** The result is false if the LHS is definitely not in the RHS. The
  92843. ** result is NULL if the presence of the LHS in the RHS cannot be
  92844. ** determined due to NULLs.
  92845. **
  92846. ** This routine generates code that jumps to destIfFalse if the LHS is not
  92847. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  92848. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  92849. ** within the RHS then fall through.
  92850. **
  92851. ** See the separate in-operator.md documentation file in the canonical
  92852. ** SQLite source tree for additional information.
  92853. */
  92854. static void sqlite3ExprCodeIN(
  92855. Parse *pParse, /* Parsing and code generating context */
  92856. Expr *pExpr, /* The IN expression */
  92857. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  92858. int destIfNull /* Jump here if the results are unknown due to NULLs */
  92859. ){
  92860. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  92861. int eType; /* Type of the RHS */
  92862. int rLhs; /* Register(s) holding the LHS values */
  92863. int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
  92864. Vdbe *v; /* Statement under construction */
  92865. int *aiMap = 0; /* Map from vector field to index column */
  92866. char *zAff = 0; /* Affinity string for comparisons */
  92867. int nVector; /* Size of vectors for this IN operator */
  92868. int iDummy; /* Dummy parameter to exprCodeVector() */
  92869. Expr *pLeft; /* The LHS of the IN operator */
  92870. int i; /* loop counter */
  92871. int destStep2; /* Where to jump when NULLs seen in step 2 */
  92872. int destStep6 = 0; /* Start of code for Step 6 */
  92873. int addrTruthOp; /* Address of opcode that determines the IN is true */
  92874. int destNotNull; /* Jump here if a comparison is not true in step 6 */
  92875. int addrTop; /* Top of the step-6 loop */
  92876. pLeft = pExpr->pLeft;
  92877. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  92878. zAff = exprINAffinity(pParse, pExpr);
  92879. nVector = sqlite3ExprVectorSize(pExpr->pLeft);
  92880. aiMap = (int*)sqlite3DbMallocZero(
  92881. pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
  92882. );
  92883. if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
  92884. /* Attempt to compute the RHS. After this step, if anything other than
  92885. ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
  92886. ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
  92887. ** the RHS has not yet been coded. */
  92888. v = pParse->pVdbe;
  92889. assert( v!=0 ); /* OOM detected prior to this routine */
  92890. VdbeNoopComment((v, "begin IN expr"));
  92891. eType = sqlite3FindInIndex(pParse, pExpr,
  92892. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  92893. destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
  92894. assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
  92895. || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
  92896. );
  92897. #ifdef SQLITE_DEBUG
  92898. /* Confirm that aiMap[] contains nVector integer values between 0 and
  92899. ** nVector-1. */
  92900. for(i=0; i<nVector; i++){
  92901. int j, cnt;
  92902. for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
  92903. assert( cnt==1 );
  92904. }
  92905. #endif
  92906. /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
  92907. ** vector, then it is stored in an array of nVector registers starting
  92908. ** at r1.
  92909. **
  92910. ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
  92911. ** so that the fields are in the same order as an existing index. The
  92912. ** aiMap[] array contains a mapping from the original LHS field order to
  92913. ** the field order that matches the RHS index.
  92914. */
  92915. rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
  92916. for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
  92917. if( i==nVector ){
  92918. /* LHS fields are not reordered */
  92919. rLhs = rLhsOrig;
  92920. }else{
  92921. /* Need to reorder the LHS fields according to aiMap */
  92922. rLhs = sqlite3GetTempRange(pParse, nVector);
  92923. for(i=0; i<nVector; i++){
  92924. sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
  92925. }
  92926. }
  92927. /* If sqlite3FindInIndex() did not find or create an index that is
  92928. ** suitable for evaluating the IN operator, then evaluate using a
  92929. ** sequence of comparisons.
  92930. **
  92931. ** This is step (1) in the in-operator.md optimized algorithm.
  92932. */
  92933. if( eType==IN_INDEX_NOOP ){
  92934. ExprList *pList = pExpr->x.pList;
  92935. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  92936. int labelOk = sqlite3VdbeMakeLabel(v);
  92937. int r2, regToFree;
  92938. int regCkNull = 0;
  92939. int ii;
  92940. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  92941. if( destIfNull!=destIfFalse ){
  92942. regCkNull = sqlite3GetTempReg(pParse);
  92943. sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
  92944. }
  92945. for(ii=0; ii<pList->nExpr; ii++){
  92946. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  92947. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  92948. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  92949. }
  92950. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  92951. sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
  92952. (void*)pColl, P4_COLLSEQ);
  92953. VdbeCoverageIf(v, ii<pList->nExpr-1);
  92954. VdbeCoverageIf(v, ii==pList->nExpr-1);
  92955. sqlite3VdbeChangeP5(v, zAff[0]);
  92956. }else{
  92957. assert( destIfNull==destIfFalse );
  92958. sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
  92959. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  92960. sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
  92961. }
  92962. sqlite3ReleaseTempReg(pParse, regToFree);
  92963. }
  92964. if( regCkNull ){
  92965. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  92966. sqlite3VdbeGoto(v, destIfFalse);
  92967. }
  92968. sqlite3VdbeResolveLabel(v, labelOk);
  92969. sqlite3ReleaseTempReg(pParse, regCkNull);
  92970. goto sqlite3ExprCodeIN_finished;
  92971. }
  92972. /* Step 2: Check to see if the LHS contains any NULL columns. If the
  92973. ** LHS does contain NULLs then the result must be either FALSE or NULL.
  92974. ** We will then skip the binary search of the RHS.
  92975. */
  92976. if( destIfNull==destIfFalse ){
  92977. destStep2 = destIfFalse;
  92978. }else{
  92979. destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
  92980. }
  92981. for(i=0; i<nVector; i++){
  92982. Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
  92983. if( sqlite3ExprCanBeNull(p) ){
  92984. sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
  92985. VdbeCoverage(v);
  92986. }
  92987. }
  92988. /* Step 3. The LHS is now known to be non-NULL. Do the binary search
  92989. ** of the RHS using the LHS as a probe. If found, the result is
  92990. ** true.
  92991. */
  92992. if( eType==IN_INDEX_ROWID ){
  92993. /* In this case, the RHS is the ROWID of table b-tree and so we also
  92994. ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
  92995. ** into a single opcode. */
  92996. sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
  92997. VdbeCoverage(v);
  92998. addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
  92999. }else{
  93000. sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
  93001. if( destIfFalse==destIfNull ){
  93002. /* Combine Step 3 and Step 5 into a single opcode */
  93003. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
  93004. rLhs, nVector); VdbeCoverage(v);
  93005. goto sqlite3ExprCodeIN_finished;
  93006. }
  93007. /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
  93008. addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
  93009. rLhs, nVector); VdbeCoverage(v);
  93010. }
  93011. /* Step 4. If the RHS is known to be non-NULL and we did not find
  93012. ** an match on the search above, then the result must be FALSE.
  93013. */
  93014. if( rRhsHasNull && nVector==1 ){
  93015. sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
  93016. VdbeCoverage(v);
  93017. }
  93018. /* Step 5. If we do not care about the difference between NULL and
  93019. ** FALSE, then just return false.
  93020. */
  93021. if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
  93022. /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
  93023. ** If any comparison is NULL, then the result is NULL. If all
  93024. ** comparisons are FALSE then the final result is FALSE.
  93025. **
  93026. ** For a scalar LHS, it is sufficient to check just the first row
  93027. ** of the RHS.
  93028. */
  93029. if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
  93030. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  93031. VdbeCoverage(v);
  93032. if( nVector>1 ){
  93033. destNotNull = sqlite3VdbeMakeLabel(v);
  93034. }else{
  93035. /* For nVector==1, combine steps 6 and 7 by immediately returning
  93036. ** FALSE if the first comparison is not NULL */
  93037. destNotNull = destIfFalse;
  93038. }
  93039. for(i=0; i<nVector; i++){
  93040. Expr *p;
  93041. CollSeq *pColl;
  93042. int r3 = sqlite3GetTempReg(pParse);
  93043. p = sqlite3VectorFieldSubexpr(pLeft, i);
  93044. pColl = sqlite3ExprCollSeq(pParse, p);
  93045. sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
  93046. sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
  93047. (void*)pColl, P4_COLLSEQ);
  93048. VdbeCoverage(v);
  93049. sqlite3ReleaseTempReg(pParse, r3);
  93050. }
  93051. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  93052. if( nVector>1 ){
  93053. sqlite3VdbeResolveLabel(v, destNotNull);
  93054. sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
  93055. VdbeCoverage(v);
  93056. /* Step 7: If we reach this point, we know that the result must
  93057. ** be false. */
  93058. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  93059. }
  93060. /* Jumps here in order to return true. */
  93061. sqlite3VdbeJumpHere(v, addrTruthOp);
  93062. sqlite3ExprCodeIN_finished:
  93063. if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
  93064. VdbeComment((v, "end IN expr"));
  93065. sqlite3ExprCodeIN_oom_error:
  93066. sqlite3DbFree(pParse->db, aiMap);
  93067. sqlite3DbFree(pParse->db, zAff);
  93068. }
  93069. #endif /* SQLITE_OMIT_SUBQUERY */
  93070. #ifndef SQLITE_OMIT_FLOATING_POINT
  93071. /*
  93072. ** Generate an instruction that will put the floating point
  93073. ** value described by z[0..n-1] into register iMem.
  93074. **
  93075. ** The z[] string will probably not be zero-terminated. But the
  93076. ** z[n] character is guaranteed to be something that does not look
  93077. ** like the continuation of the number.
  93078. */
  93079. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  93080. if( ALWAYS(z!=0) ){
  93081. double value;
  93082. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  93083. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  93084. if( negateFlag ) value = -value;
  93085. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  93086. }
  93087. }
  93088. #endif
  93089. /*
  93090. ** Generate an instruction that will put the integer describe by
  93091. ** text z[0..n-1] into register iMem.
  93092. **
  93093. ** Expr.u.zToken is always UTF8 and zero-terminated.
  93094. */
  93095. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  93096. Vdbe *v = pParse->pVdbe;
  93097. if( pExpr->flags & EP_IntValue ){
  93098. int i = pExpr->u.iValue;
  93099. assert( i>=0 );
  93100. if( negFlag ) i = -i;
  93101. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  93102. }else{
  93103. int c;
  93104. i64 value;
  93105. const char *z = pExpr->u.zToken;
  93106. assert( z!=0 );
  93107. c = sqlite3DecOrHexToI64(z, &value);
  93108. if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
  93109. #ifdef SQLITE_OMIT_FLOATING_POINT
  93110. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  93111. #else
  93112. #ifndef SQLITE_OMIT_HEX_INTEGER
  93113. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  93114. sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
  93115. }else
  93116. #endif
  93117. {
  93118. codeReal(v, z, negFlag, iMem);
  93119. }
  93120. #endif
  93121. }else{
  93122. if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
  93123. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  93124. }
  93125. }
  93126. }
  93127. /* Generate code that will load into register regOut a value that is
  93128. ** appropriate for the iIdxCol-th column of index pIdx.
  93129. */
  93130. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  93131. Parse *pParse, /* The parsing context */
  93132. Index *pIdx, /* The index whose column is to be loaded */
  93133. int iTabCur, /* Cursor pointing to a table row */
  93134. int iIdxCol, /* The column of the index to be loaded */
  93135. int regOut /* Store the index column value in this register */
  93136. ){
  93137. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  93138. if( iTabCol==XN_EXPR ){
  93139. assert( pIdx->aColExpr );
  93140. assert( pIdx->aColExpr->nExpr>iIdxCol );
  93141. pParse->iSelfTab = iTabCur + 1;
  93142. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  93143. pParse->iSelfTab = 0;
  93144. }else{
  93145. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  93146. iTabCol, regOut);
  93147. }
  93148. }
  93149. /*
  93150. ** Generate code to extract the value of the iCol-th column of a table.
  93151. */
  93152. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  93153. Vdbe *v, /* The VDBE under construction */
  93154. Table *pTab, /* The table containing the value */
  93155. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  93156. int iCol, /* Index of the column to extract */
  93157. int regOut /* Extract the value into this register */
  93158. ){
  93159. if( pTab==0 ){
  93160. sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
  93161. return;
  93162. }
  93163. if( iCol<0 || iCol==pTab->iPKey ){
  93164. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  93165. }else{
  93166. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  93167. int x = iCol;
  93168. if( !HasRowid(pTab) && !IsVirtual(pTab) ){
  93169. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  93170. }
  93171. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  93172. }
  93173. if( iCol>=0 ){
  93174. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  93175. }
  93176. }
  93177. /*
  93178. ** Generate code that will extract the iColumn-th column from
  93179. ** table pTab and store the column value in register iReg.
  93180. **
  93181. ** There must be an open cursor to pTab in iTable when this routine
  93182. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  93183. */
  93184. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  93185. Parse *pParse, /* Parsing and code generating context */
  93186. Table *pTab, /* Description of the table we are reading from */
  93187. int iColumn, /* Index of the table column */
  93188. int iTable, /* The cursor pointing to the table */
  93189. int iReg, /* Store results here */
  93190. u8 p5 /* P5 value for OP_Column + FLAGS */
  93191. ){
  93192. Vdbe *v = pParse->pVdbe;
  93193. assert( v!=0 );
  93194. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  93195. if( p5 ){
  93196. sqlite3VdbeChangeP5(v, p5);
  93197. }
  93198. return iReg;
  93199. }
  93200. /*
  93201. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  93202. ** over to iTo..iTo+nReg-1.
  93203. */
  93204. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  93205. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  93206. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  93207. }
  93208. /*
  93209. ** Convert a scalar expression node to a TK_REGISTER referencing
  93210. ** register iReg. The caller must ensure that iReg already contains
  93211. ** the correct value for the expression.
  93212. */
  93213. static void exprToRegister(Expr *p, int iReg){
  93214. p->op2 = p->op;
  93215. p->op = TK_REGISTER;
  93216. p->iTable = iReg;
  93217. ExprClearProperty(p, EP_Skip);
  93218. }
  93219. /*
  93220. ** Evaluate an expression (either a vector or a scalar expression) and store
  93221. ** the result in continguous temporary registers. Return the index of
  93222. ** the first register used to store the result.
  93223. **
  93224. ** If the returned result register is a temporary scalar, then also write
  93225. ** that register number into *piFreeable. If the returned result register
  93226. ** is not a temporary or if the expression is a vector set *piFreeable
  93227. ** to 0.
  93228. */
  93229. static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
  93230. int iResult;
  93231. int nResult = sqlite3ExprVectorSize(p);
  93232. if( nResult==1 ){
  93233. iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
  93234. }else{
  93235. *piFreeable = 0;
  93236. if( p->op==TK_SELECT ){
  93237. #if SQLITE_OMIT_SUBQUERY
  93238. iResult = 0;
  93239. #else
  93240. iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
  93241. #endif
  93242. }else{
  93243. int i;
  93244. iResult = pParse->nMem+1;
  93245. pParse->nMem += nResult;
  93246. for(i=0; i<nResult; i++){
  93247. sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
  93248. }
  93249. }
  93250. }
  93251. return iResult;
  93252. }
  93253. /*
  93254. ** Generate code into the current Vdbe to evaluate the given
  93255. ** expression. Attempt to store the results in register "target".
  93256. ** Return the register where results are stored.
  93257. **
  93258. ** With this routine, there is no guarantee that results will
  93259. ** be stored in target. The result might be stored in some other
  93260. ** register if it is convenient to do so. The calling function
  93261. ** must check the return code and move the results to the desired
  93262. ** register.
  93263. */
  93264. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  93265. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  93266. int op; /* The opcode being coded */
  93267. int inReg = target; /* Results stored in register inReg */
  93268. int regFree1 = 0; /* If non-zero free this temporary register */
  93269. int regFree2 = 0; /* If non-zero free this temporary register */
  93270. int r1, r2; /* Various register numbers */
  93271. Expr tempX; /* Temporary expression node */
  93272. int p5 = 0;
  93273. assert( target>0 && target<=pParse->nMem );
  93274. if( v==0 ){
  93275. assert( pParse->db->mallocFailed );
  93276. return 0;
  93277. }
  93278. expr_code_doover:
  93279. if( pExpr==0 ){
  93280. op = TK_NULL;
  93281. }else{
  93282. op = pExpr->op;
  93283. }
  93284. switch( op ){
  93285. case TK_AGG_COLUMN: {
  93286. AggInfo *pAggInfo = pExpr->pAggInfo;
  93287. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  93288. if( !pAggInfo->directMode ){
  93289. assert( pCol->iMem>0 );
  93290. return pCol->iMem;
  93291. }else if( pAggInfo->useSortingIdx ){
  93292. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  93293. pCol->iSorterColumn, target);
  93294. return target;
  93295. }
  93296. /* Otherwise, fall thru into the TK_COLUMN case */
  93297. }
  93298. case TK_COLUMN: {
  93299. int iTab = pExpr->iTable;
  93300. if( ExprHasProperty(pExpr, EP_FixedCol) ){
  93301. /* This COLUMN expression is really a constant due to WHERE clause
  93302. ** constraints, and that constant is coded by the pExpr->pLeft
  93303. ** expresssion. However, make sure the constant has the correct
  93304. ** datatype by applying the Affinity of the table column to the
  93305. ** constant.
  93306. */
  93307. int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
  93308. int aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
  93309. if( aff!=SQLITE_AFF_BLOB ){
  93310. static const char zAff[] = "B\000C\000D\000E";
  93311. assert( SQLITE_AFF_BLOB=='A' );
  93312. assert( SQLITE_AFF_TEXT=='B' );
  93313. if( iReg!=target ){
  93314. sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
  93315. iReg = target;
  93316. }
  93317. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
  93318. &zAff[(aff-'B')*2], P4_STATIC);
  93319. }
  93320. return iReg;
  93321. }
  93322. if( iTab<0 ){
  93323. if( pParse->iSelfTab<0 ){
  93324. /* Generating CHECK constraints or inserting into partial index */
  93325. return pExpr->iColumn - pParse->iSelfTab;
  93326. }else{
  93327. /* Coding an expression that is part of an index where column names
  93328. ** in the index refer to the table to which the index belongs */
  93329. iTab = pParse->iSelfTab - 1;
  93330. }
  93331. }
  93332. return sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
  93333. pExpr->iColumn, iTab, target,
  93334. pExpr->op2);
  93335. }
  93336. case TK_INTEGER: {
  93337. codeInteger(pParse, pExpr, 0, target);
  93338. return target;
  93339. }
  93340. case TK_TRUEFALSE: {
  93341. sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
  93342. return target;
  93343. }
  93344. #ifndef SQLITE_OMIT_FLOATING_POINT
  93345. case TK_FLOAT: {
  93346. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  93347. codeReal(v, pExpr->u.zToken, 0, target);
  93348. return target;
  93349. }
  93350. #endif
  93351. case TK_STRING: {
  93352. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  93353. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  93354. return target;
  93355. }
  93356. case TK_NULL: {
  93357. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  93358. return target;
  93359. }
  93360. #ifndef SQLITE_OMIT_BLOB_LITERAL
  93361. case TK_BLOB: {
  93362. int n;
  93363. const char *z;
  93364. char *zBlob;
  93365. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  93366. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  93367. assert( pExpr->u.zToken[1]=='\'' );
  93368. z = &pExpr->u.zToken[2];
  93369. n = sqlite3Strlen30(z) - 1;
  93370. assert( z[n]=='\'' );
  93371. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  93372. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  93373. return target;
  93374. }
  93375. #endif
  93376. case TK_VARIABLE: {
  93377. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  93378. assert( pExpr->u.zToken!=0 );
  93379. assert( pExpr->u.zToken[0]!=0 );
  93380. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  93381. if( pExpr->u.zToken[1]!=0 ){
  93382. const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
  93383. assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
  93384. pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
  93385. sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
  93386. }
  93387. return target;
  93388. }
  93389. case TK_REGISTER: {
  93390. return pExpr->iTable;
  93391. }
  93392. #ifndef SQLITE_OMIT_CAST
  93393. case TK_CAST: {
  93394. /* Expressions of the form: CAST(pLeft AS token) */
  93395. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  93396. if( inReg!=target ){
  93397. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  93398. inReg = target;
  93399. }
  93400. sqlite3VdbeAddOp2(v, OP_Cast, target,
  93401. sqlite3AffinityType(pExpr->u.zToken, 0));
  93402. return inReg;
  93403. }
  93404. #endif /* SQLITE_OMIT_CAST */
  93405. case TK_IS:
  93406. case TK_ISNOT:
  93407. op = (op==TK_IS) ? TK_EQ : TK_NE;
  93408. p5 = SQLITE_NULLEQ;
  93409. /* fall-through */
  93410. case TK_LT:
  93411. case TK_LE:
  93412. case TK_GT:
  93413. case TK_GE:
  93414. case TK_NE:
  93415. case TK_EQ: {
  93416. Expr *pLeft = pExpr->pLeft;
  93417. if( sqlite3ExprIsVector(pLeft) ){
  93418. codeVectorCompare(pParse, pExpr, target, op, p5);
  93419. }else{
  93420. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  93421. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  93422. codeCompare(pParse, pLeft, pExpr->pRight, op,
  93423. r1, r2, inReg, SQLITE_STOREP2 | p5);
  93424. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  93425. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  93426. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  93427. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  93428. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  93429. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  93430. testcase( regFree1==0 );
  93431. testcase( regFree2==0 );
  93432. }
  93433. break;
  93434. }
  93435. case TK_AND:
  93436. case TK_OR:
  93437. case TK_PLUS:
  93438. case TK_STAR:
  93439. case TK_MINUS:
  93440. case TK_REM:
  93441. case TK_BITAND:
  93442. case TK_BITOR:
  93443. case TK_SLASH:
  93444. case TK_LSHIFT:
  93445. case TK_RSHIFT:
  93446. case TK_CONCAT: {
  93447. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  93448. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  93449. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  93450. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  93451. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  93452. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  93453. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  93454. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  93455. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  93456. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  93457. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  93458. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  93459. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  93460. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  93461. testcase( regFree1==0 );
  93462. testcase( regFree2==0 );
  93463. break;
  93464. }
  93465. case TK_UMINUS: {
  93466. Expr *pLeft = pExpr->pLeft;
  93467. assert( pLeft );
  93468. if( pLeft->op==TK_INTEGER ){
  93469. codeInteger(pParse, pLeft, 1, target);
  93470. return target;
  93471. #ifndef SQLITE_OMIT_FLOATING_POINT
  93472. }else if( pLeft->op==TK_FLOAT ){
  93473. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  93474. codeReal(v, pLeft->u.zToken, 1, target);
  93475. return target;
  93476. #endif
  93477. }else{
  93478. tempX.op = TK_INTEGER;
  93479. tempX.flags = EP_IntValue|EP_TokenOnly;
  93480. tempX.u.iValue = 0;
  93481. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  93482. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  93483. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  93484. testcase( regFree2==0 );
  93485. }
  93486. break;
  93487. }
  93488. case TK_BITNOT:
  93489. case TK_NOT: {
  93490. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  93491. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  93492. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  93493. testcase( regFree1==0 );
  93494. sqlite3VdbeAddOp2(v, op, r1, inReg);
  93495. break;
  93496. }
  93497. case TK_TRUTH: {
  93498. int isTrue; /* IS TRUE or IS NOT TRUE */
  93499. int bNormal; /* IS TRUE or IS FALSE */
  93500. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  93501. testcase( regFree1==0 );
  93502. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  93503. bNormal = pExpr->op2==TK_IS;
  93504. testcase( isTrue && bNormal);
  93505. testcase( !isTrue && bNormal);
  93506. sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
  93507. break;
  93508. }
  93509. case TK_ISNULL:
  93510. case TK_NOTNULL: {
  93511. int addr;
  93512. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  93513. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  93514. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  93515. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  93516. testcase( regFree1==0 );
  93517. addr = sqlite3VdbeAddOp1(v, op, r1);
  93518. VdbeCoverageIf(v, op==TK_ISNULL);
  93519. VdbeCoverageIf(v, op==TK_NOTNULL);
  93520. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  93521. sqlite3VdbeJumpHere(v, addr);
  93522. break;
  93523. }
  93524. case TK_AGG_FUNCTION: {
  93525. AggInfo *pInfo = pExpr->pAggInfo;
  93526. if( pInfo==0 ){
  93527. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  93528. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  93529. }else{
  93530. return pInfo->aFunc[pExpr->iAgg].iMem;
  93531. }
  93532. break;
  93533. }
  93534. case TK_FUNCTION: {
  93535. ExprList *pFarg; /* List of function arguments */
  93536. int nFarg; /* Number of function arguments */
  93537. FuncDef *pDef; /* The function definition object */
  93538. const char *zId; /* The function name */
  93539. u32 constMask = 0; /* Mask of function arguments that are constant */
  93540. int i; /* Loop counter */
  93541. sqlite3 *db = pParse->db; /* The database connection */
  93542. u8 enc = ENC(db); /* The text encoding used by this database */
  93543. CollSeq *pColl = 0; /* A collating sequence */
  93544. #ifndef SQLITE_OMIT_WINDOWFUNC
  93545. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  93546. return pExpr->y.pWin->regResult;
  93547. }
  93548. #endif
  93549. if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
  93550. /* SQL functions can be expensive. So try to move constant functions
  93551. ** out of the inner loop, even if that means an extra OP_Copy. */
  93552. return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  93553. }
  93554. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  93555. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  93556. pFarg = 0;
  93557. }else{
  93558. pFarg = pExpr->x.pList;
  93559. }
  93560. nFarg = pFarg ? pFarg->nExpr : 0;
  93561. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  93562. zId = pExpr->u.zToken;
  93563. pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
  93564. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  93565. if( pDef==0 && pParse->explain ){
  93566. pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
  93567. }
  93568. #endif
  93569. if( pDef==0 || pDef->xFinalize!=0 ){
  93570. sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
  93571. break;
  93572. }
  93573. /* Attempt a direct implementation of the built-in COALESCE() and
  93574. ** IFNULL() functions. This avoids unnecessary evaluation of
  93575. ** arguments past the first non-NULL argument.
  93576. */
  93577. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  93578. int endCoalesce = sqlite3VdbeMakeLabel(v);
  93579. assert( nFarg>=2 );
  93580. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  93581. for(i=1; i<nFarg; i++){
  93582. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  93583. VdbeCoverage(v);
  93584. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  93585. }
  93586. sqlite3VdbeResolveLabel(v, endCoalesce);
  93587. break;
  93588. }
  93589. /* The UNLIKELY() function is a no-op. The result is the value
  93590. ** of the first argument.
  93591. */
  93592. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  93593. assert( nFarg>=1 );
  93594. return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  93595. }
  93596. #ifdef SQLITE_DEBUG
  93597. /* The AFFINITY() function evaluates to a string that describes
  93598. ** the type affinity of the argument. This is used for testing of
  93599. ** the SQLite type logic.
  93600. */
  93601. if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
  93602. const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
  93603. char aff;
  93604. assert( nFarg==1 );
  93605. aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
  93606. sqlite3VdbeLoadString(v, target,
  93607. aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
  93608. return target;
  93609. }
  93610. #endif
  93611. for(i=0; i<nFarg; i++){
  93612. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  93613. testcase( i==31 );
  93614. constMask |= MASKBIT32(i);
  93615. }
  93616. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  93617. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  93618. }
  93619. }
  93620. if( pFarg ){
  93621. if( constMask ){
  93622. r1 = pParse->nMem+1;
  93623. pParse->nMem += nFarg;
  93624. }else{
  93625. r1 = sqlite3GetTempRange(pParse, nFarg);
  93626. }
  93627. /* For length() and typeof() functions with a column argument,
  93628. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  93629. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  93630. ** loading.
  93631. */
  93632. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  93633. u8 exprOp;
  93634. assert( nFarg==1 );
  93635. assert( pFarg->a[0].pExpr!=0 );
  93636. exprOp = pFarg->a[0].pExpr->op;
  93637. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  93638. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  93639. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  93640. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  93641. pFarg->a[0].pExpr->op2 =
  93642. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  93643. }
  93644. }
  93645. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  93646. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  93647. }else{
  93648. r1 = 0;
  93649. }
  93650. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93651. /* Possibly overload the function if the first argument is
  93652. ** a virtual table column.
  93653. **
  93654. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  93655. ** second argument, not the first, as the argument to test to
  93656. ** see if it is a column in a virtual table. This is done because
  93657. ** the left operand of infix functions (the operand we want to
  93658. ** control overloading) ends up as the second argument to the
  93659. ** function. The expression "A glob B" is equivalent to
  93660. ** "glob(B,A). We want to use the A in "A glob B" to test
  93661. ** for function overloading. But we use the B term in "glob(B,A)".
  93662. */
  93663. if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
  93664. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  93665. }else if( nFarg>0 ){
  93666. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  93667. }
  93668. #endif
  93669. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  93670. if( !pColl ) pColl = db->pDfltColl;
  93671. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  93672. }
  93673. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  93674. if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
  93675. Expr *pArg = pFarg->a[0].pExpr;
  93676. if( pArg->op==TK_COLUMN ){
  93677. sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
  93678. }else{
  93679. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  93680. }
  93681. }else
  93682. #endif
  93683. {
  93684. sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
  93685. constMask, r1, target, (char*)pDef, P4_FUNCDEF);
  93686. sqlite3VdbeChangeP5(v, (u8)nFarg);
  93687. }
  93688. if( nFarg && constMask==0 ){
  93689. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  93690. }
  93691. return target;
  93692. }
  93693. #ifndef SQLITE_OMIT_SUBQUERY
  93694. case TK_EXISTS:
  93695. case TK_SELECT: {
  93696. int nCol;
  93697. testcase( op==TK_EXISTS );
  93698. testcase( op==TK_SELECT );
  93699. if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
  93700. sqlite3SubselectError(pParse, nCol, 1);
  93701. }else{
  93702. return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  93703. }
  93704. break;
  93705. }
  93706. case TK_SELECT_COLUMN: {
  93707. int n;
  93708. if( pExpr->pLeft->iTable==0 ){
  93709. pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
  93710. }
  93711. assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
  93712. if( pExpr->iTable
  93713. && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
  93714. ){
  93715. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  93716. pExpr->iTable, n);
  93717. }
  93718. return pExpr->pLeft->iTable + pExpr->iColumn;
  93719. }
  93720. case TK_IN: {
  93721. int destIfFalse = sqlite3VdbeMakeLabel(v);
  93722. int destIfNull = sqlite3VdbeMakeLabel(v);
  93723. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  93724. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  93725. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  93726. sqlite3VdbeResolveLabel(v, destIfFalse);
  93727. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  93728. sqlite3VdbeResolveLabel(v, destIfNull);
  93729. return target;
  93730. }
  93731. #endif /* SQLITE_OMIT_SUBQUERY */
  93732. /*
  93733. ** x BETWEEN y AND z
  93734. **
  93735. ** This is equivalent to
  93736. **
  93737. ** x>=y AND x<=z
  93738. **
  93739. ** X is stored in pExpr->pLeft.
  93740. ** Y is stored in pExpr->pList->a[0].pExpr.
  93741. ** Z is stored in pExpr->pList->a[1].pExpr.
  93742. */
  93743. case TK_BETWEEN: {
  93744. exprCodeBetween(pParse, pExpr, target, 0, 0);
  93745. return target;
  93746. }
  93747. case TK_SPAN:
  93748. case TK_COLLATE:
  93749. case TK_UPLUS: {
  93750. pExpr = pExpr->pLeft;
  93751. goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
  93752. }
  93753. case TK_TRIGGER: {
  93754. /* If the opcode is TK_TRIGGER, then the expression is a reference
  93755. ** to a column in the new.* or old.* pseudo-tables available to
  93756. ** trigger programs. In this case Expr.iTable is set to 1 for the
  93757. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  93758. ** is set to the column of the pseudo-table to read, or to -1 to
  93759. ** read the rowid field.
  93760. **
  93761. ** The expression is implemented using an OP_Param opcode. The p1
  93762. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  93763. ** to reference another column of the old.* pseudo-table, where
  93764. ** i is the index of the column. For a new.rowid reference, p1 is
  93765. ** set to (n+1), where n is the number of columns in each pseudo-table.
  93766. ** For a reference to any other column in the new.* pseudo-table, p1
  93767. ** is set to (n+2+i), where n and i are as defined previously. For
  93768. ** example, if the table on which triggers are being fired is
  93769. ** declared as:
  93770. **
  93771. ** CREATE TABLE t1(a, b);
  93772. **
  93773. ** Then p1 is interpreted as follows:
  93774. **
  93775. ** p1==0 -> old.rowid p1==3 -> new.rowid
  93776. ** p1==1 -> old.a p1==4 -> new.a
  93777. ** p1==2 -> old.b p1==5 -> new.b
  93778. */
  93779. Table *pTab = pExpr->y.pTab;
  93780. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  93781. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  93782. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  93783. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  93784. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  93785. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  93786. VdbeComment((v, "r[%d]=%s.%s", target,
  93787. (pExpr->iTable ? "new" : "old"),
  93788. (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[pExpr->iColumn].zName)
  93789. ));
  93790. #ifndef SQLITE_OMIT_FLOATING_POINT
  93791. /* If the column has REAL affinity, it may currently be stored as an
  93792. ** integer. Use OP_RealAffinity to make sure it is really real.
  93793. **
  93794. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  93795. ** floating point when extracting it from the record. */
  93796. if( pExpr->iColumn>=0
  93797. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  93798. ){
  93799. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  93800. }
  93801. #endif
  93802. break;
  93803. }
  93804. case TK_VECTOR: {
  93805. sqlite3ErrorMsg(pParse, "row value misused");
  93806. break;
  93807. }
  93808. case TK_IF_NULL_ROW: {
  93809. int addrINR;
  93810. addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
  93811. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  93812. sqlite3VdbeJumpHere(v, addrINR);
  93813. sqlite3VdbeChangeP3(v, addrINR, inReg);
  93814. break;
  93815. }
  93816. /*
  93817. ** Form A:
  93818. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  93819. **
  93820. ** Form B:
  93821. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  93822. **
  93823. ** Form A is can be transformed into the equivalent form B as follows:
  93824. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  93825. ** WHEN x=eN THEN rN ELSE y END
  93826. **
  93827. ** X (if it exists) is in pExpr->pLeft.
  93828. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  93829. ** odd. The Y is also optional. If the number of elements in x.pList
  93830. ** is even, then Y is omitted and the "otherwise" result is NULL.
  93831. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  93832. **
  93833. ** The result of the expression is the Ri for the first matching Ei,
  93834. ** or if there is no matching Ei, the ELSE term Y, or if there is
  93835. ** no ELSE term, NULL.
  93836. */
  93837. default: assert( op==TK_CASE ); {
  93838. int endLabel; /* GOTO label for end of CASE stmt */
  93839. int nextCase; /* GOTO label for next WHEN clause */
  93840. int nExpr; /* 2x number of WHEN terms */
  93841. int i; /* Loop counter */
  93842. ExprList *pEList; /* List of WHEN terms */
  93843. struct ExprList_item *aListelem; /* Array of WHEN terms */
  93844. Expr opCompare; /* The X==Ei expression */
  93845. Expr *pX; /* The X expression */
  93846. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  93847. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  93848. assert(pExpr->x.pList->nExpr > 0);
  93849. pEList = pExpr->x.pList;
  93850. aListelem = pEList->a;
  93851. nExpr = pEList->nExpr;
  93852. endLabel = sqlite3VdbeMakeLabel(v);
  93853. if( (pX = pExpr->pLeft)!=0 ){
  93854. tempX = *pX;
  93855. testcase( pX->op==TK_COLUMN );
  93856. exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
  93857. testcase( regFree1==0 );
  93858. memset(&opCompare, 0, sizeof(opCompare));
  93859. opCompare.op = TK_EQ;
  93860. opCompare.pLeft = &tempX;
  93861. pTest = &opCompare;
  93862. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  93863. ** The value in regFree1 might get SCopy-ed into the file result.
  93864. ** So make sure that the regFree1 register is not reused for other
  93865. ** purposes and possibly overwritten. */
  93866. regFree1 = 0;
  93867. }
  93868. for(i=0; i<nExpr-1; i=i+2){
  93869. if( pX ){
  93870. assert( pTest!=0 );
  93871. opCompare.pRight = aListelem[i].pExpr;
  93872. }else{
  93873. pTest = aListelem[i].pExpr;
  93874. }
  93875. nextCase = sqlite3VdbeMakeLabel(v);
  93876. testcase( pTest->op==TK_COLUMN );
  93877. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  93878. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  93879. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  93880. sqlite3VdbeGoto(v, endLabel);
  93881. sqlite3VdbeResolveLabel(v, nextCase);
  93882. }
  93883. if( (nExpr&1)!=0 ){
  93884. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  93885. }else{
  93886. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  93887. }
  93888. sqlite3VdbeResolveLabel(v, endLabel);
  93889. break;
  93890. }
  93891. #ifndef SQLITE_OMIT_TRIGGER
  93892. case TK_RAISE: {
  93893. assert( pExpr->affinity==OE_Rollback
  93894. || pExpr->affinity==OE_Abort
  93895. || pExpr->affinity==OE_Fail
  93896. || pExpr->affinity==OE_Ignore
  93897. );
  93898. if( !pParse->pTriggerTab ){
  93899. sqlite3ErrorMsg(pParse,
  93900. "RAISE() may only be used within a trigger-program");
  93901. return 0;
  93902. }
  93903. if( pExpr->affinity==OE_Abort ){
  93904. sqlite3MayAbort(pParse);
  93905. }
  93906. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  93907. if( pExpr->affinity==OE_Ignore ){
  93908. sqlite3VdbeAddOp4(
  93909. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  93910. VdbeCoverage(v);
  93911. }else{
  93912. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  93913. pExpr->affinity, pExpr->u.zToken, 0, 0);
  93914. }
  93915. break;
  93916. }
  93917. #endif
  93918. }
  93919. sqlite3ReleaseTempReg(pParse, regFree1);
  93920. sqlite3ReleaseTempReg(pParse, regFree2);
  93921. return inReg;
  93922. }
  93923. /*
  93924. ** Factor out the code of the given expression to initialization time.
  93925. **
  93926. ** If regDest>=0 then the result is always stored in that register and the
  93927. ** result is not reusable. If regDest<0 then this routine is free to
  93928. ** store the value whereever it wants. The register where the expression
  93929. ** is stored is returned. When regDest<0, two identical expressions will
  93930. ** code to the same register.
  93931. */
  93932. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
  93933. Parse *pParse, /* Parsing context */
  93934. Expr *pExpr, /* The expression to code when the VDBE initializes */
  93935. int regDest /* Store the value in this register */
  93936. ){
  93937. ExprList *p;
  93938. assert( ConstFactorOk(pParse) );
  93939. p = pParse->pConstExpr;
  93940. if( regDest<0 && p ){
  93941. struct ExprList_item *pItem;
  93942. int i;
  93943. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  93944. if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
  93945. return pItem->u.iConstExprReg;
  93946. }
  93947. }
  93948. }
  93949. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  93950. p = sqlite3ExprListAppend(pParse, p, pExpr);
  93951. if( p ){
  93952. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  93953. pItem->reusable = regDest<0;
  93954. if( regDest<0 ) regDest = ++pParse->nMem;
  93955. pItem->u.iConstExprReg = regDest;
  93956. }
  93957. pParse->pConstExpr = p;
  93958. return regDest;
  93959. }
  93960. /*
  93961. ** Generate code to evaluate an expression and store the results
  93962. ** into a register. Return the register number where the results
  93963. ** are stored.
  93964. **
  93965. ** If the register is a temporary register that can be deallocated,
  93966. ** then write its number into *pReg. If the result register is not
  93967. ** a temporary, then set *pReg to zero.
  93968. **
  93969. ** If pExpr is a constant, then this routine might generate this
  93970. ** code to fill the register in the initialization section of the
  93971. ** VDBE program, in order to factor it out of the evaluation loop.
  93972. */
  93973. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  93974. int r2;
  93975. pExpr = sqlite3ExprSkipCollate(pExpr);
  93976. if( ConstFactorOk(pParse)
  93977. && pExpr->op!=TK_REGISTER
  93978. && sqlite3ExprIsConstantNotJoin(pExpr)
  93979. ){
  93980. *pReg = 0;
  93981. r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  93982. }else{
  93983. int r1 = sqlite3GetTempReg(pParse);
  93984. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  93985. if( r2==r1 ){
  93986. *pReg = r1;
  93987. }else{
  93988. sqlite3ReleaseTempReg(pParse, r1);
  93989. *pReg = 0;
  93990. }
  93991. }
  93992. return r2;
  93993. }
  93994. /*
  93995. ** Generate code that will evaluate expression pExpr and store the
  93996. ** results in register target. The results are guaranteed to appear
  93997. ** in register target.
  93998. */
  93999. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  94000. int inReg;
  94001. assert( target>0 && target<=pParse->nMem );
  94002. if( pExpr && pExpr->op==TK_REGISTER ){
  94003. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  94004. }else{
  94005. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  94006. assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  94007. if( inReg!=target && pParse->pVdbe ){
  94008. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  94009. }
  94010. }
  94011. }
  94012. /*
  94013. ** Make a transient copy of expression pExpr and then code it using
  94014. ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
  94015. ** except that the input expression is guaranteed to be unchanged.
  94016. */
  94017. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
  94018. sqlite3 *db = pParse->db;
  94019. pExpr = sqlite3ExprDup(db, pExpr, 0);
  94020. if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
  94021. sqlite3ExprDelete(db, pExpr);
  94022. }
  94023. /*
  94024. ** Generate code that will evaluate expression pExpr and store the
  94025. ** results in register target. The results are guaranteed to appear
  94026. ** in register target. If the expression is constant, then this routine
  94027. ** might choose to code the expression at initialization time.
  94028. */
  94029. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  94030. if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
  94031. sqlite3ExprCodeAtInit(pParse, pExpr, target);
  94032. }else{
  94033. sqlite3ExprCode(pParse, pExpr, target);
  94034. }
  94035. }
  94036. /*
  94037. ** Generate code that evaluates the given expression and puts the result
  94038. ** in register target.
  94039. **
  94040. ** Also make a copy of the expression results into another "cache" register
  94041. ** and modify the expression so that the next time it is evaluated,
  94042. ** the result is a copy of the cache register.
  94043. **
  94044. ** This routine is used for expressions that are used multiple
  94045. ** times. They are evaluated once and the results of the expression
  94046. ** are reused.
  94047. */
  94048. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  94049. Vdbe *v = pParse->pVdbe;
  94050. int iMem;
  94051. assert( target>0 );
  94052. assert( pExpr->op!=TK_REGISTER );
  94053. sqlite3ExprCode(pParse, pExpr, target);
  94054. iMem = ++pParse->nMem;
  94055. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  94056. exprToRegister(pExpr, iMem);
  94057. }
  94058. /*
  94059. ** Generate code that pushes the value of every element of the given
  94060. ** expression list into a sequence of registers beginning at target.
  94061. **
  94062. ** Return the number of elements evaluated. The number returned will
  94063. ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
  94064. ** is defined.
  94065. **
  94066. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  94067. ** filled using OP_SCopy. OP_Copy must be used instead.
  94068. **
  94069. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  94070. ** factored out into initialization code.
  94071. **
  94072. ** The SQLITE_ECEL_REF flag means that expressions in the list with
  94073. ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
  94074. ** in registers at srcReg, and so the value can be copied from there.
  94075. ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
  94076. ** are simply omitted rather than being copied from srcReg.
  94077. */
  94078. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  94079. Parse *pParse, /* Parsing context */
  94080. ExprList *pList, /* The expression list to be coded */
  94081. int target, /* Where to write results */
  94082. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  94083. u8 flags /* SQLITE_ECEL_* flags */
  94084. ){
  94085. struct ExprList_item *pItem;
  94086. int i, j, n;
  94087. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  94088. Vdbe *v = pParse->pVdbe;
  94089. assert( pList!=0 );
  94090. assert( target>0 );
  94091. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  94092. n = pList->nExpr;
  94093. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  94094. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  94095. Expr *pExpr = pItem->pExpr;
  94096. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  94097. if( pItem->bSorterRef ){
  94098. i--;
  94099. n--;
  94100. }else
  94101. #endif
  94102. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
  94103. if( flags & SQLITE_ECEL_OMITREF ){
  94104. i--;
  94105. n--;
  94106. }else{
  94107. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  94108. }
  94109. }else if( (flags & SQLITE_ECEL_FACTOR)!=0
  94110. && sqlite3ExprIsConstantNotJoin(pExpr)
  94111. ){
  94112. sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
  94113. }else{
  94114. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  94115. if( inReg!=target+i ){
  94116. VdbeOp *pOp;
  94117. if( copyOp==OP_Copy
  94118. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  94119. && pOp->p1+pOp->p3+1==inReg
  94120. && pOp->p2+pOp->p3+1==target+i
  94121. ){
  94122. pOp->p3++;
  94123. }else{
  94124. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  94125. }
  94126. }
  94127. }
  94128. }
  94129. return n;
  94130. }
  94131. /*
  94132. ** Generate code for a BETWEEN operator.
  94133. **
  94134. ** x BETWEEN y AND z
  94135. **
  94136. ** The above is equivalent to
  94137. **
  94138. ** x>=y AND x<=z
  94139. **
  94140. ** Code it as such, taking care to do the common subexpression
  94141. ** elimination of x.
  94142. **
  94143. ** The xJumpIf parameter determines details:
  94144. **
  94145. ** NULL: Store the boolean result in reg[dest]
  94146. ** sqlite3ExprIfTrue: Jump to dest if true
  94147. ** sqlite3ExprIfFalse: Jump to dest if false
  94148. **
  94149. ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
  94150. */
  94151. static void exprCodeBetween(
  94152. Parse *pParse, /* Parsing and code generating context */
  94153. Expr *pExpr, /* The BETWEEN expression */
  94154. int dest, /* Jump destination or storage location */
  94155. void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
  94156. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  94157. ){
  94158. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  94159. Expr compLeft; /* The x>=y term */
  94160. Expr compRight; /* The x<=z term */
  94161. Expr exprX; /* The x subexpression */
  94162. int regFree1 = 0; /* Temporary use register */
  94163. memset(&compLeft, 0, sizeof(Expr));
  94164. memset(&compRight, 0, sizeof(Expr));
  94165. memset(&exprAnd, 0, sizeof(Expr));
  94166. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  94167. exprX = *pExpr->pLeft;
  94168. exprAnd.op = TK_AND;
  94169. exprAnd.pLeft = &compLeft;
  94170. exprAnd.pRight = &compRight;
  94171. compLeft.op = TK_GE;
  94172. compLeft.pLeft = &exprX;
  94173. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  94174. compRight.op = TK_LE;
  94175. compRight.pLeft = &exprX;
  94176. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  94177. exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
  94178. if( xJump ){
  94179. xJump(pParse, &exprAnd, dest, jumpIfNull);
  94180. }else{
  94181. /* Mark the expression is being from the ON or USING clause of a join
  94182. ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
  94183. ** it into the Parse.pConstExpr list. We should use a new bit for this,
  94184. ** for clarity, but we are out of bits in the Expr.flags field so we
  94185. ** have to reuse the EP_FromJoin bit. Bummer. */
  94186. exprX.flags |= EP_FromJoin;
  94187. sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
  94188. }
  94189. sqlite3ReleaseTempReg(pParse, regFree1);
  94190. /* Ensure adequate test coverage */
  94191. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
  94192. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
  94193. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
  94194. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
  94195. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
  94196. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
  94197. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
  94198. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
  94199. testcase( xJump==0 );
  94200. }
  94201. /*
  94202. ** Generate code for a boolean expression such that a jump is made
  94203. ** to the label "dest" if the expression is true but execution
  94204. ** continues straight thru if the expression is false.
  94205. **
  94206. ** If the expression evaluates to NULL (neither true nor false), then
  94207. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  94208. **
  94209. ** This code depends on the fact that certain token values (ex: TK_EQ)
  94210. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  94211. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  94212. ** the make process cause these values to align. Assert()s in the code
  94213. ** below verify that the numbers are aligned correctly.
  94214. */
  94215. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  94216. Vdbe *v = pParse->pVdbe;
  94217. int op = 0;
  94218. int regFree1 = 0;
  94219. int regFree2 = 0;
  94220. int r1, r2;
  94221. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  94222. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  94223. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  94224. op = pExpr->op;
  94225. switch( op ){
  94226. case TK_AND: {
  94227. int d2 = sqlite3VdbeMakeLabel(v);
  94228. testcase( jumpIfNull==0 );
  94229. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  94230. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  94231. sqlite3VdbeResolveLabel(v, d2);
  94232. break;
  94233. }
  94234. case TK_OR: {
  94235. testcase( jumpIfNull==0 );
  94236. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  94237. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  94238. break;
  94239. }
  94240. case TK_NOT: {
  94241. testcase( jumpIfNull==0 );
  94242. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  94243. break;
  94244. }
  94245. case TK_TRUTH: {
  94246. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  94247. int isTrue; /* IS TRUE or IS NOT TRUE */
  94248. testcase( jumpIfNull==0 );
  94249. isNot = pExpr->op2==TK_ISNOT;
  94250. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  94251. testcase( isTrue && isNot );
  94252. testcase( !isTrue && isNot );
  94253. if( isTrue ^ isNot ){
  94254. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  94255. isNot ? SQLITE_JUMPIFNULL : 0);
  94256. }else{
  94257. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  94258. isNot ? SQLITE_JUMPIFNULL : 0);
  94259. }
  94260. break;
  94261. }
  94262. case TK_IS:
  94263. case TK_ISNOT:
  94264. testcase( op==TK_IS );
  94265. testcase( op==TK_ISNOT );
  94266. op = (op==TK_IS) ? TK_EQ : TK_NE;
  94267. jumpIfNull = SQLITE_NULLEQ;
  94268. /* Fall thru */
  94269. case TK_LT:
  94270. case TK_LE:
  94271. case TK_GT:
  94272. case TK_GE:
  94273. case TK_NE:
  94274. case TK_EQ: {
  94275. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  94276. testcase( jumpIfNull==0 );
  94277. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94278. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  94279. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  94280. r1, r2, dest, jumpIfNull);
  94281. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  94282. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  94283. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  94284. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  94285. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  94286. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  94287. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  94288. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  94289. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  94290. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  94291. testcase( regFree1==0 );
  94292. testcase( regFree2==0 );
  94293. break;
  94294. }
  94295. case TK_ISNULL:
  94296. case TK_NOTNULL: {
  94297. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  94298. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  94299. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94300. sqlite3VdbeAddOp2(v, op, r1, dest);
  94301. VdbeCoverageIf(v, op==TK_ISNULL);
  94302. VdbeCoverageIf(v, op==TK_NOTNULL);
  94303. testcase( regFree1==0 );
  94304. break;
  94305. }
  94306. case TK_BETWEEN: {
  94307. testcase( jumpIfNull==0 );
  94308. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
  94309. break;
  94310. }
  94311. #ifndef SQLITE_OMIT_SUBQUERY
  94312. case TK_IN: {
  94313. int destIfFalse = sqlite3VdbeMakeLabel(v);
  94314. int destIfNull = jumpIfNull ? dest : destIfFalse;
  94315. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  94316. sqlite3VdbeGoto(v, dest);
  94317. sqlite3VdbeResolveLabel(v, destIfFalse);
  94318. break;
  94319. }
  94320. #endif
  94321. default: {
  94322. default_expr:
  94323. if( exprAlwaysTrue(pExpr) ){
  94324. sqlite3VdbeGoto(v, dest);
  94325. }else if( exprAlwaysFalse(pExpr) ){
  94326. /* No-op */
  94327. }else{
  94328. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  94329. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  94330. VdbeCoverage(v);
  94331. testcase( regFree1==0 );
  94332. testcase( jumpIfNull==0 );
  94333. }
  94334. break;
  94335. }
  94336. }
  94337. sqlite3ReleaseTempReg(pParse, regFree1);
  94338. sqlite3ReleaseTempReg(pParse, regFree2);
  94339. }
  94340. /*
  94341. ** Generate code for a boolean expression such that a jump is made
  94342. ** to the label "dest" if the expression is false but execution
  94343. ** continues straight thru if the expression is true.
  94344. **
  94345. ** If the expression evaluates to NULL (neither true nor false) then
  94346. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  94347. ** is 0.
  94348. */
  94349. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  94350. Vdbe *v = pParse->pVdbe;
  94351. int op = 0;
  94352. int regFree1 = 0;
  94353. int regFree2 = 0;
  94354. int r1, r2;
  94355. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  94356. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  94357. if( pExpr==0 ) return;
  94358. /* The value of pExpr->op and op are related as follows:
  94359. **
  94360. ** pExpr->op op
  94361. ** --------- ----------
  94362. ** TK_ISNULL OP_NotNull
  94363. ** TK_NOTNULL OP_IsNull
  94364. ** TK_NE OP_Eq
  94365. ** TK_EQ OP_Ne
  94366. ** TK_GT OP_Le
  94367. ** TK_LE OP_Gt
  94368. ** TK_GE OP_Lt
  94369. ** TK_LT OP_Ge
  94370. **
  94371. ** For other values of pExpr->op, op is undefined and unused.
  94372. ** The value of TK_ and OP_ constants are arranged such that we
  94373. ** can compute the mapping above using the following expression.
  94374. ** Assert()s verify that the computation is correct.
  94375. */
  94376. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  94377. /* Verify correct alignment of TK_ and OP_ constants
  94378. */
  94379. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  94380. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  94381. assert( pExpr->op!=TK_NE || op==OP_Eq );
  94382. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  94383. assert( pExpr->op!=TK_LT || op==OP_Ge );
  94384. assert( pExpr->op!=TK_LE || op==OP_Gt );
  94385. assert( pExpr->op!=TK_GT || op==OP_Le );
  94386. assert( pExpr->op!=TK_GE || op==OP_Lt );
  94387. switch( pExpr->op ){
  94388. case TK_AND: {
  94389. testcase( jumpIfNull==0 );
  94390. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  94391. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  94392. break;
  94393. }
  94394. case TK_OR: {
  94395. int d2 = sqlite3VdbeMakeLabel(v);
  94396. testcase( jumpIfNull==0 );
  94397. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  94398. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  94399. sqlite3VdbeResolveLabel(v, d2);
  94400. break;
  94401. }
  94402. case TK_NOT: {
  94403. testcase( jumpIfNull==0 );
  94404. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  94405. break;
  94406. }
  94407. case TK_TRUTH: {
  94408. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  94409. int isTrue; /* IS TRUE or IS NOT TRUE */
  94410. testcase( jumpIfNull==0 );
  94411. isNot = pExpr->op2==TK_ISNOT;
  94412. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  94413. testcase( isTrue && isNot );
  94414. testcase( !isTrue && isNot );
  94415. if( isTrue ^ isNot ){
  94416. /* IS TRUE and IS NOT FALSE */
  94417. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  94418. isNot ? 0 : SQLITE_JUMPIFNULL);
  94419. }else{
  94420. /* IS FALSE and IS NOT TRUE */
  94421. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  94422. isNot ? 0 : SQLITE_JUMPIFNULL);
  94423. }
  94424. break;
  94425. }
  94426. case TK_IS:
  94427. case TK_ISNOT:
  94428. testcase( pExpr->op==TK_IS );
  94429. testcase( pExpr->op==TK_ISNOT );
  94430. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  94431. jumpIfNull = SQLITE_NULLEQ;
  94432. /* Fall thru */
  94433. case TK_LT:
  94434. case TK_LE:
  94435. case TK_GT:
  94436. case TK_GE:
  94437. case TK_NE:
  94438. case TK_EQ: {
  94439. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  94440. testcase( jumpIfNull==0 );
  94441. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94442. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  94443. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  94444. r1, r2, dest, jumpIfNull);
  94445. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  94446. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  94447. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  94448. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  94449. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  94450. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  94451. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  94452. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  94453. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  94454. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  94455. testcase( regFree1==0 );
  94456. testcase( regFree2==0 );
  94457. break;
  94458. }
  94459. case TK_ISNULL:
  94460. case TK_NOTNULL: {
  94461. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94462. sqlite3VdbeAddOp2(v, op, r1, dest);
  94463. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  94464. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  94465. testcase( regFree1==0 );
  94466. break;
  94467. }
  94468. case TK_BETWEEN: {
  94469. testcase( jumpIfNull==0 );
  94470. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
  94471. break;
  94472. }
  94473. #ifndef SQLITE_OMIT_SUBQUERY
  94474. case TK_IN: {
  94475. if( jumpIfNull ){
  94476. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  94477. }else{
  94478. int destIfNull = sqlite3VdbeMakeLabel(v);
  94479. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  94480. sqlite3VdbeResolveLabel(v, destIfNull);
  94481. }
  94482. break;
  94483. }
  94484. #endif
  94485. default: {
  94486. default_expr:
  94487. if( exprAlwaysFalse(pExpr) ){
  94488. sqlite3VdbeGoto(v, dest);
  94489. }else if( exprAlwaysTrue(pExpr) ){
  94490. /* no-op */
  94491. }else{
  94492. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  94493. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  94494. VdbeCoverage(v);
  94495. testcase( regFree1==0 );
  94496. testcase( jumpIfNull==0 );
  94497. }
  94498. break;
  94499. }
  94500. }
  94501. sqlite3ReleaseTempReg(pParse, regFree1);
  94502. sqlite3ReleaseTempReg(pParse, regFree2);
  94503. }
  94504. /*
  94505. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  94506. ** code generation, and that copy is deleted after code generation. This
  94507. ** ensures that the original pExpr is unchanged.
  94508. */
  94509. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  94510. sqlite3 *db = pParse->db;
  94511. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  94512. if( db->mallocFailed==0 ){
  94513. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  94514. }
  94515. sqlite3ExprDelete(db, pCopy);
  94516. }
  94517. /*
  94518. ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
  94519. ** type of expression.
  94520. **
  94521. ** If pExpr is a simple SQL value - an integer, real, string, blob
  94522. ** or NULL value - then the VDBE currently being prepared is configured
  94523. ** to re-prepare each time a new value is bound to variable pVar.
  94524. **
  94525. ** Additionally, if pExpr is a simple SQL value and the value is the
  94526. ** same as that currently bound to variable pVar, non-zero is returned.
  94527. ** Otherwise, if the values are not the same or if pExpr is not a simple
  94528. ** SQL value, zero is returned.
  94529. */
  94530. static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
  94531. int res = 0;
  94532. int iVar;
  94533. sqlite3_value *pL, *pR = 0;
  94534. sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
  94535. if( pR ){
  94536. iVar = pVar->iColumn;
  94537. sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
  94538. pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
  94539. if( pL ){
  94540. if( sqlite3_value_type(pL)==SQLITE_TEXT ){
  94541. sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
  94542. }
  94543. res = 0==sqlite3MemCompare(pL, pR, 0);
  94544. }
  94545. sqlite3ValueFree(pR);
  94546. sqlite3ValueFree(pL);
  94547. }
  94548. return res;
  94549. }
  94550. /*
  94551. ** Do a deep comparison of two expression trees. Return 0 if the two
  94552. ** expressions are completely identical. Return 1 if they differ only
  94553. ** by a COLLATE operator at the top level. Return 2 if there are differences
  94554. ** other than the top-level COLLATE operator.
  94555. **
  94556. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  94557. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  94558. **
  94559. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  94560. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  94561. **
  94562. ** Sometimes this routine will return 2 even if the two expressions
  94563. ** really are equivalent. If we cannot prove that the expressions are
  94564. ** identical, we return 2 just to be safe. So if this routine
  94565. ** returns 2, then you do not really know for certain if the two
  94566. ** expressions are the same. But if you get a 0 or 1 return, then you
  94567. ** can be sure the expressions are the same. In the places where
  94568. ** this routine is used, it does not hurt to get an extra 2 - that
  94569. ** just might result in some slightly slower code. But returning
  94570. ** an incorrect 0 or 1 could lead to a malfunction.
  94571. **
  94572. ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
  94573. ** pParse->pReprepare can be matched against literals in pB. The
  94574. ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
  94575. ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
  94576. ** Argument pParse should normally be NULL. If it is not NULL and pA or
  94577. ** pB causes a return value of 2.
  94578. */
  94579. SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
  94580. u32 combinedFlags;
  94581. if( pA==0 || pB==0 ){
  94582. return pB==pA ? 0 : 2;
  94583. }
  94584. if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
  94585. return 0;
  94586. }
  94587. combinedFlags = pA->flags | pB->flags;
  94588. if( combinedFlags & EP_IntValue ){
  94589. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  94590. return 0;
  94591. }
  94592. return 2;
  94593. }
  94594. if( pA->op!=pB->op ){
  94595. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
  94596. return 1;
  94597. }
  94598. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
  94599. return 1;
  94600. }
  94601. return 2;
  94602. }
  94603. if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
  94604. if( pA->op==TK_FUNCTION ){
  94605. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  94606. #ifndef SQLITE_OMIT_WINDOWFUNC
  94607. /* Justification for the assert():
  94608. ** window functions have p->op==TK_FUNCTION but aggregate functions
  94609. ** have p->op==TK_AGG_FUNCTION. So any comparison between an aggregate
  94610. ** function and a window function should have failed before reaching
  94611. ** this point. And, it is not possible to have a window function and
  94612. ** a scalar function with the same name and number of arguments. So
  94613. ** if we reach this point, either A and B both window functions or
  94614. ** neither are a window functions. */
  94615. assert( ExprHasProperty(pA,EP_WinFunc)==ExprHasProperty(pB,EP_WinFunc) );
  94616. if( ExprHasProperty(pA,EP_WinFunc) ){
  94617. if( sqlite3WindowCompare(pParse,pA->y.pWin,pB->y.pWin)!=0 ) return 2;
  94618. }
  94619. #endif
  94620. }else if( pA->op==TK_COLLATE ){
  94621. if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  94622. }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  94623. return 2;
  94624. }
  94625. }
  94626. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  94627. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  94628. if( combinedFlags & EP_xIsSelect ) return 2;
  94629. if( (combinedFlags & EP_FixedCol)==0
  94630. && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
  94631. if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
  94632. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  94633. assert( (combinedFlags & EP_Reduced)==0 );
  94634. if( pA->op!=TK_STRING && pA->op!=TK_TRUEFALSE ){
  94635. if( pA->iColumn!=pB->iColumn ) return 2;
  94636. if( pA->iTable!=pB->iTable
  94637. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  94638. }
  94639. }
  94640. return 0;
  94641. }
  94642. /*
  94643. ** Compare two ExprList objects. Return 0 if they are identical and
  94644. ** non-zero if they differ in any way.
  94645. **
  94646. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  94647. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  94648. **
  94649. ** This routine might return non-zero for equivalent ExprLists. The
  94650. ** only consequence will be disabled optimizations. But this routine
  94651. ** must never return 0 if the two ExprList objects are different, or
  94652. ** a malfunction will result.
  94653. **
  94654. ** Two NULL pointers are considered to be the same. But a NULL pointer
  94655. ** always differs from a non-NULL pointer.
  94656. */
  94657. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  94658. int i;
  94659. if( pA==0 && pB==0 ) return 0;
  94660. if( pA==0 || pB==0 ) return 1;
  94661. if( pA->nExpr!=pB->nExpr ) return 1;
  94662. for(i=0; i<pA->nExpr; i++){
  94663. Expr *pExprA = pA->a[i].pExpr;
  94664. Expr *pExprB = pB->a[i].pExpr;
  94665. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  94666. if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
  94667. }
  94668. return 0;
  94669. }
  94670. /*
  94671. ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
  94672. ** are ignored.
  94673. */
  94674. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
  94675. return sqlite3ExprCompare(0,
  94676. sqlite3ExprSkipCollate(pA),
  94677. sqlite3ExprSkipCollate(pB),
  94678. iTab);
  94679. }
  94680. /*
  94681. ** Return true if we can prove the pE2 will always be true if pE1 is
  94682. ** true. Return false if we cannot complete the proof or if pE2 might
  94683. ** be false. Examples:
  94684. **
  94685. ** pE1: x==5 pE2: x==5 Result: true
  94686. ** pE1: x>0 pE2: x==5 Result: false
  94687. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  94688. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  94689. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  94690. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  94691. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  94692. **
  94693. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  94694. ** Expr.iTable<0 then assume a table number given by iTab.
  94695. **
  94696. ** If pParse is not NULL, then the values of bound variables in pE1 are
  94697. ** compared against literal values in pE2 and pParse->pVdbe->expmask is
  94698. ** modified to record which bound variables are referenced. If pParse
  94699. ** is NULL, then false will be returned if pE1 contains any bound variables.
  94700. **
  94701. ** When in doubt, return false. Returning true might give a performance
  94702. ** improvement. Returning false might cause a performance reduction, but
  94703. ** it will always give the correct answer and is hence always safe.
  94704. */
  94705. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
  94706. if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
  94707. return 1;
  94708. }
  94709. if( pE2->op==TK_OR
  94710. && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
  94711. || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
  94712. ){
  94713. return 1;
  94714. }
  94715. if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
  94716. Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
  94717. testcase( pX!=pE1->pLeft );
  94718. if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
  94719. }
  94720. return 0;
  94721. }
  94722. /*
  94723. ** This is the Expr node callback for sqlite3ExprImpliesNotNullRow().
  94724. ** If the expression node requires that the table at pWalker->iCur
  94725. ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
  94726. **
  94727. ** This routine controls an optimization. False positives (setting
  94728. ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
  94729. ** (never setting pWalker->eCode) is a harmless missed optimization.
  94730. */
  94731. static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
  94732. testcase( pExpr->op==TK_AGG_COLUMN );
  94733. testcase( pExpr->op==TK_AGG_FUNCTION );
  94734. if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
  94735. switch( pExpr->op ){
  94736. case TK_ISNOT:
  94737. case TK_NOT:
  94738. case TK_ISNULL:
  94739. case TK_IS:
  94740. case TK_OR:
  94741. case TK_CASE:
  94742. case TK_IN:
  94743. case TK_FUNCTION:
  94744. testcase( pExpr->op==TK_ISNOT );
  94745. testcase( pExpr->op==TK_NOT );
  94746. testcase( pExpr->op==TK_ISNULL );
  94747. testcase( pExpr->op==TK_IS );
  94748. testcase( pExpr->op==TK_OR );
  94749. testcase( pExpr->op==TK_CASE );
  94750. testcase( pExpr->op==TK_IN );
  94751. testcase( pExpr->op==TK_FUNCTION );
  94752. return WRC_Prune;
  94753. case TK_COLUMN:
  94754. if( pWalker->u.iCur==pExpr->iTable ){
  94755. pWalker->eCode = 1;
  94756. return WRC_Abort;
  94757. }
  94758. return WRC_Prune;
  94759. /* Virtual tables are allowed to use constraints like x=NULL. So
  94760. ** a term of the form x=y does not prove that y is not null if x
  94761. ** is the column of a virtual table */
  94762. case TK_EQ:
  94763. case TK_NE:
  94764. case TK_LT:
  94765. case TK_LE:
  94766. case TK_GT:
  94767. case TK_GE:
  94768. testcase( pExpr->op==TK_EQ );
  94769. testcase( pExpr->op==TK_NE );
  94770. testcase( pExpr->op==TK_LT );
  94771. testcase( pExpr->op==TK_LE );
  94772. testcase( pExpr->op==TK_GT );
  94773. testcase( pExpr->op==TK_GE );
  94774. if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab))
  94775. || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab))
  94776. ){
  94777. return WRC_Prune;
  94778. }
  94779. default:
  94780. return WRC_Continue;
  94781. }
  94782. }
  94783. /*
  94784. ** Return true (non-zero) if expression p can only be true if at least
  94785. ** one column of table iTab is non-null. In other words, return true
  94786. ** if expression p will always be NULL or false if every column of iTab
  94787. ** is NULL.
  94788. **
  94789. ** False negatives are acceptable. In other words, it is ok to return
  94790. ** zero even if expression p will never be true of every column of iTab
  94791. ** is NULL. A false negative is merely a missed optimization opportunity.
  94792. **
  94793. ** False positives are not allowed, however. A false positive may result
  94794. ** in an incorrect answer.
  94795. **
  94796. ** Terms of p that are marked with EP_FromJoin (and hence that come from
  94797. ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
  94798. **
  94799. ** This routine is used to check if a LEFT JOIN can be converted into
  94800. ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
  94801. ** clause requires that some column of the right table of the LEFT JOIN
  94802. ** be non-NULL, then the LEFT JOIN can be safely converted into an
  94803. ** ordinary join.
  94804. */
  94805. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
  94806. Walker w;
  94807. w.xExprCallback = impliesNotNullRow;
  94808. w.xSelectCallback = 0;
  94809. w.xSelectCallback2 = 0;
  94810. w.eCode = 0;
  94811. w.u.iCur = iTab;
  94812. sqlite3WalkExpr(&w, p);
  94813. return w.eCode;
  94814. }
  94815. /*
  94816. ** An instance of the following structure is used by the tree walker
  94817. ** to determine if an expression can be evaluated by reference to the
  94818. ** index only, without having to do a search for the corresponding
  94819. ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
  94820. ** is the cursor for the table.
  94821. */
  94822. struct IdxCover {
  94823. Index *pIdx; /* The index to be tested for coverage */
  94824. int iCur; /* Cursor number for the table corresponding to the index */
  94825. };
  94826. /*
  94827. ** Check to see if there are references to columns in table
  94828. ** pWalker->u.pIdxCover->iCur can be satisfied using the index
  94829. ** pWalker->u.pIdxCover->pIdx.
  94830. */
  94831. static int exprIdxCover(Walker *pWalker, Expr *pExpr){
  94832. if( pExpr->op==TK_COLUMN
  94833. && pExpr->iTable==pWalker->u.pIdxCover->iCur
  94834. && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
  94835. ){
  94836. pWalker->eCode = 1;
  94837. return WRC_Abort;
  94838. }
  94839. return WRC_Continue;
  94840. }
  94841. /*
  94842. ** Determine if an index pIdx on table with cursor iCur contains will
  94843. ** the expression pExpr. Return true if the index does cover the
  94844. ** expression and false if the pExpr expression references table columns
  94845. ** that are not found in the index pIdx.
  94846. **
  94847. ** An index covering an expression means that the expression can be
  94848. ** evaluated using only the index and without having to lookup the
  94849. ** corresponding table entry.
  94850. */
  94851. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
  94852. Expr *pExpr, /* The index to be tested */
  94853. int iCur, /* The cursor number for the corresponding table */
  94854. Index *pIdx /* The index that might be used for coverage */
  94855. ){
  94856. Walker w;
  94857. struct IdxCover xcov;
  94858. memset(&w, 0, sizeof(w));
  94859. xcov.iCur = iCur;
  94860. xcov.pIdx = pIdx;
  94861. w.xExprCallback = exprIdxCover;
  94862. w.u.pIdxCover = &xcov;
  94863. sqlite3WalkExpr(&w, pExpr);
  94864. return !w.eCode;
  94865. }
  94866. /*
  94867. ** An instance of the following structure is used by the tree walker
  94868. ** to count references to table columns in the arguments of an
  94869. ** aggregate function, in order to implement the
  94870. ** sqlite3FunctionThisSrc() routine.
  94871. */
  94872. struct SrcCount {
  94873. SrcList *pSrc; /* One particular FROM clause in a nested query */
  94874. int nThis; /* Number of references to columns in pSrcList */
  94875. int nOther; /* Number of references to columns in other FROM clauses */
  94876. };
  94877. /*
  94878. ** Count the number of references to columns.
  94879. */
  94880. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  94881. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  94882. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  94883. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  94884. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  94885. ** NEVER() will need to be removed. */
  94886. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  94887. int i;
  94888. struct SrcCount *p = pWalker->u.pSrcCount;
  94889. SrcList *pSrc = p->pSrc;
  94890. int nSrc = pSrc ? pSrc->nSrc : 0;
  94891. for(i=0; i<nSrc; i++){
  94892. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  94893. }
  94894. if( i<nSrc ){
  94895. p->nThis++;
  94896. }else{
  94897. p->nOther++;
  94898. }
  94899. }
  94900. return WRC_Continue;
  94901. }
  94902. /*
  94903. ** Determine if any of the arguments to the pExpr Function reference
  94904. ** pSrcList. Return true if they do. Also return true if the function
  94905. ** has no arguments or has only constant arguments. Return false if pExpr
  94906. ** references columns but not columns of tables found in pSrcList.
  94907. */
  94908. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  94909. Walker w;
  94910. struct SrcCount cnt;
  94911. assert( pExpr->op==TK_AGG_FUNCTION );
  94912. w.xExprCallback = exprSrcCount;
  94913. w.xSelectCallback = 0;
  94914. w.u.pSrcCount = &cnt;
  94915. cnt.pSrc = pSrcList;
  94916. cnt.nThis = 0;
  94917. cnt.nOther = 0;
  94918. sqlite3WalkExprList(&w, pExpr->x.pList);
  94919. return cnt.nThis>0 || cnt.nOther==0;
  94920. }
  94921. /*
  94922. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  94923. ** the new element. Return a negative number if malloc fails.
  94924. */
  94925. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  94926. int i;
  94927. pInfo->aCol = sqlite3ArrayAllocate(
  94928. db,
  94929. pInfo->aCol,
  94930. sizeof(pInfo->aCol[0]),
  94931. &pInfo->nColumn,
  94932. &i
  94933. );
  94934. return i;
  94935. }
  94936. /*
  94937. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  94938. ** the new element. Return a negative number if malloc fails.
  94939. */
  94940. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  94941. int i;
  94942. pInfo->aFunc = sqlite3ArrayAllocate(
  94943. db,
  94944. pInfo->aFunc,
  94945. sizeof(pInfo->aFunc[0]),
  94946. &pInfo->nFunc,
  94947. &i
  94948. );
  94949. return i;
  94950. }
  94951. /*
  94952. ** This is the xExprCallback for a tree walker. It is used to
  94953. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  94954. ** for additional information.
  94955. */
  94956. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  94957. int i;
  94958. NameContext *pNC = pWalker->u.pNC;
  94959. Parse *pParse = pNC->pParse;
  94960. SrcList *pSrcList = pNC->pSrcList;
  94961. AggInfo *pAggInfo = pNC->uNC.pAggInfo;
  94962. assert( pNC->ncFlags & NC_UAggInfo );
  94963. switch( pExpr->op ){
  94964. case TK_AGG_COLUMN:
  94965. case TK_COLUMN: {
  94966. testcase( pExpr->op==TK_AGG_COLUMN );
  94967. testcase( pExpr->op==TK_COLUMN );
  94968. /* Check to see if the column is in one of the tables in the FROM
  94969. ** clause of the aggregate query */
  94970. if( ALWAYS(pSrcList!=0) ){
  94971. struct SrcList_item *pItem = pSrcList->a;
  94972. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  94973. struct AggInfo_col *pCol;
  94974. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  94975. if( pExpr->iTable==pItem->iCursor ){
  94976. /* If we reach this point, it means that pExpr refers to a table
  94977. ** that is in the FROM clause of the aggregate query.
  94978. **
  94979. ** Make an entry for the column in pAggInfo->aCol[] if there
  94980. ** is not an entry there already.
  94981. */
  94982. int k;
  94983. pCol = pAggInfo->aCol;
  94984. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  94985. if( pCol->iTable==pExpr->iTable &&
  94986. pCol->iColumn==pExpr->iColumn ){
  94987. break;
  94988. }
  94989. }
  94990. if( (k>=pAggInfo->nColumn)
  94991. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  94992. ){
  94993. pCol = &pAggInfo->aCol[k];
  94994. pCol->pTab = pExpr->y.pTab;
  94995. pCol->iTable = pExpr->iTable;
  94996. pCol->iColumn = pExpr->iColumn;
  94997. pCol->iMem = ++pParse->nMem;
  94998. pCol->iSorterColumn = -1;
  94999. pCol->pExpr = pExpr;
  95000. if( pAggInfo->pGroupBy ){
  95001. int j, n;
  95002. ExprList *pGB = pAggInfo->pGroupBy;
  95003. struct ExprList_item *pTerm = pGB->a;
  95004. n = pGB->nExpr;
  95005. for(j=0; j<n; j++, pTerm++){
  95006. Expr *pE = pTerm->pExpr;
  95007. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  95008. pE->iColumn==pExpr->iColumn ){
  95009. pCol->iSorterColumn = j;
  95010. break;
  95011. }
  95012. }
  95013. }
  95014. if( pCol->iSorterColumn<0 ){
  95015. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  95016. }
  95017. }
  95018. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  95019. ** because it was there before or because we just created it).
  95020. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  95021. ** pAggInfo->aCol[] entry.
  95022. */
  95023. ExprSetVVAProperty(pExpr, EP_NoReduce);
  95024. pExpr->pAggInfo = pAggInfo;
  95025. pExpr->op = TK_AGG_COLUMN;
  95026. pExpr->iAgg = (i16)k;
  95027. break;
  95028. } /* endif pExpr->iTable==pItem->iCursor */
  95029. } /* end loop over pSrcList */
  95030. }
  95031. return WRC_Prune;
  95032. }
  95033. case TK_AGG_FUNCTION: {
  95034. if( (pNC->ncFlags & NC_InAggFunc)==0
  95035. && pWalker->walkerDepth==pExpr->op2
  95036. ){
  95037. /* Check to see if pExpr is a duplicate of another aggregate
  95038. ** function that is already in the pAggInfo structure
  95039. */
  95040. struct AggInfo_func *pItem = pAggInfo->aFunc;
  95041. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  95042. if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
  95043. break;
  95044. }
  95045. }
  95046. if( i>=pAggInfo->nFunc ){
  95047. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  95048. */
  95049. u8 enc = ENC(pParse->db);
  95050. i = addAggInfoFunc(pParse->db, pAggInfo);
  95051. if( i>=0 ){
  95052. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  95053. pItem = &pAggInfo->aFunc[i];
  95054. pItem->pExpr = pExpr;
  95055. pItem->iMem = ++pParse->nMem;
  95056. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  95057. pItem->pFunc = sqlite3FindFunction(pParse->db,
  95058. pExpr->u.zToken,
  95059. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  95060. if( pExpr->flags & EP_Distinct ){
  95061. pItem->iDistinct = pParse->nTab++;
  95062. }else{
  95063. pItem->iDistinct = -1;
  95064. }
  95065. }
  95066. }
  95067. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  95068. */
  95069. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  95070. ExprSetVVAProperty(pExpr, EP_NoReduce);
  95071. pExpr->iAgg = (i16)i;
  95072. pExpr->pAggInfo = pAggInfo;
  95073. return WRC_Prune;
  95074. }else{
  95075. return WRC_Continue;
  95076. }
  95077. }
  95078. }
  95079. return WRC_Continue;
  95080. }
  95081. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  95082. UNUSED_PARAMETER(pSelect);
  95083. pWalker->walkerDepth++;
  95084. return WRC_Continue;
  95085. }
  95086. static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
  95087. UNUSED_PARAMETER(pSelect);
  95088. pWalker->walkerDepth--;
  95089. }
  95090. /*
  95091. ** Analyze the pExpr expression looking for aggregate functions and
  95092. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  95093. ** points to. Additional entries are made on the AggInfo object as
  95094. ** necessary.
  95095. **
  95096. ** This routine should only be called after the expression has been
  95097. ** analyzed by sqlite3ResolveExprNames().
  95098. */
  95099. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  95100. Walker w;
  95101. w.xExprCallback = analyzeAggregate;
  95102. w.xSelectCallback = analyzeAggregatesInSelect;
  95103. w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
  95104. w.walkerDepth = 0;
  95105. w.u.pNC = pNC;
  95106. assert( pNC->pSrcList!=0 );
  95107. sqlite3WalkExpr(&w, pExpr);
  95108. }
  95109. /*
  95110. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  95111. ** expression list. Return the number of errors.
  95112. **
  95113. ** If an error is found, the analysis is cut short.
  95114. */
  95115. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  95116. struct ExprList_item *pItem;
  95117. int i;
  95118. if( pList ){
  95119. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  95120. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  95121. }
  95122. }
  95123. }
  95124. /*
  95125. ** Allocate a single new register for use to hold some intermediate result.
  95126. */
  95127. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  95128. if( pParse->nTempReg==0 ){
  95129. return ++pParse->nMem;
  95130. }
  95131. return pParse->aTempReg[--pParse->nTempReg];
  95132. }
  95133. /*
  95134. ** Deallocate a register, making available for reuse for some other
  95135. ** purpose.
  95136. */
  95137. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  95138. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  95139. pParse->aTempReg[pParse->nTempReg++] = iReg;
  95140. }
  95141. }
  95142. /*
  95143. ** Allocate or deallocate a block of nReg consecutive registers.
  95144. */
  95145. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  95146. int i, n;
  95147. if( nReg==1 ) return sqlite3GetTempReg(pParse);
  95148. i = pParse->iRangeReg;
  95149. n = pParse->nRangeReg;
  95150. if( nReg<=n ){
  95151. pParse->iRangeReg += nReg;
  95152. pParse->nRangeReg -= nReg;
  95153. }else{
  95154. i = pParse->nMem+1;
  95155. pParse->nMem += nReg;
  95156. }
  95157. return i;
  95158. }
  95159. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  95160. if( nReg==1 ){
  95161. sqlite3ReleaseTempReg(pParse, iReg);
  95162. return;
  95163. }
  95164. if( nReg>pParse->nRangeReg ){
  95165. pParse->nRangeReg = nReg;
  95166. pParse->iRangeReg = iReg;
  95167. }
  95168. }
  95169. /*
  95170. ** Mark all temporary registers as being unavailable for reuse.
  95171. */
  95172. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  95173. pParse->nTempReg = 0;
  95174. pParse->nRangeReg = 0;
  95175. }
  95176. /*
  95177. ** Validate that no temporary register falls within the range of
  95178. ** iFirst..iLast, inclusive. This routine is only call from within assert()
  95179. ** statements.
  95180. */
  95181. #ifdef SQLITE_DEBUG
  95182. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  95183. int i;
  95184. if( pParse->nRangeReg>0
  95185. && pParse->iRangeReg+pParse->nRangeReg > iFirst
  95186. && pParse->iRangeReg <= iLast
  95187. ){
  95188. return 0;
  95189. }
  95190. for(i=0; i<pParse->nTempReg; i++){
  95191. if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
  95192. return 0;
  95193. }
  95194. }
  95195. return 1;
  95196. }
  95197. #endif /* SQLITE_DEBUG */
  95198. /************** End of expr.c ************************************************/
  95199. /************** Begin file alter.c *******************************************/
  95200. /*
  95201. ** 2005 February 15
  95202. **
  95203. ** The author disclaims copyright to this source code. In place of
  95204. ** a legal notice, here is a blessing:
  95205. **
  95206. ** May you do good and not evil.
  95207. ** May you find forgiveness for yourself and forgive others.
  95208. ** May you share freely, never taking more than you give.
  95209. **
  95210. *************************************************************************
  95211. ** This file contains C code routines that used to generate VDBE code
  95212. ** that implements the ALTER TABLE command.
  95213. */
  95214. /* #include "sqliteInt.h" */
  95215. /*
  95216. ** The code in this file only exists if we are not omitting the
  95217. ** ALTER TABLE logic from the build.
  95218. */
  95219. #ifndef SQLITE_OMIT_ALTERTABLE
  95220. /*
  95221. ** Parameter zName is the name of a table that is about to be altered
  95222. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  95223. ** If the table is a system table, this function leaves an error message
  95224. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  95225. **
  95226. ** Or, if zName is not a system table, zero is returned.
  95227. */
  95228. static int isSystemTable(Parse *pParse, const char *zName){
  95229. if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  95230. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  95231. return 1;
  95232. }
  95233. return 0;
  95234. }
  95235. /*
  95236. ** Generate code to verify that the schemas of database zDb and, if
  95237. ** bTemp is not true, database "temp", can still be parsed. This is
  95238. ** called at the end of the generation of an ALTER TABLE ... RENAME ...
  95239. ** statement to ensure that the operation has not rendered any schema
  95240. ** objects unusable.
  95241. */
  95242. static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
  95243. sqlite3NestedParse(pParse,
  95244. "SELECT 1 "
  95245. "FROM \"%w\".%s "
  95246. "WHERE name NOT LIKE 'sqlite_%%'"
  95247. " AND sql NOT LIKE 'create virtual%%'"
  95248. " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
  95249. zDb, MASTER_NAME,
  95250. zDb, bTemp
  95251. );
  95252. if( bTemp==0 ){
  95253. sqlite3NestedParse(pParse,
  95254. "SELECT 1 "
  95255. "FROM temp.%s "
  95256. "WHERE name NOT LIKE 'sqlite_%%'"
  95257. " AND sql NOT LIKE 'create virtual%%'"
  95258. " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
  95259. MASTER_NAME, zDb
  95260. );
  95261. }
  95262. }
  95263. /*
  95264. ** Generate code to reload the schema for database iDb. And, if iDb!=1, for
  95265. ** the temp database as well.
  95266. */
  95267. static void renameReloadSchema(Parse *pParse, int iDb){
  95268. Vdbe *v = pParse->pVdbe;
  95269. if( v ){
  95270. sqlite3ChangeCookie(pParse, iDb);
  95271. sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
  95272. if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
  95273. }
  95274. }
  95275. /*
  95276. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  95277. ** command.
  95278. */
  95279. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  95280. Parse *pParse, /* Parser context. */
  95281. SrcList *pSrc, /* The table to rename. */
  95282. Token *pName /* The new table name. */
  95283. ){
  95284. int iDb; /* Database that contains the table */
  95285. char *zDb; /* Name of database iDb */
  95286. Table *pTab; /* Table being renamed */
  95287. char *zName = 0; /* NULL-terminated version of pName */
  95288. sqlite3 *db = pParse->db; /* Database connection */
  95289. int nTabName; /* Number of UTF-8 characters in zTabName */
  95290. const char *zTabName; /* Original name of the table */
  95291. Vdbe *v;
  95292. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  95293. u32 savedDbFlags; /* Saved value of db->mDbFlags */
  95294. savedDbFlags = db->mDbFlags;
  95295. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  95296. assert( pSrc->nSrc==1 );
  95297. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  95298. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  95299. if( !pTab ) goto exit_rename_table;
  95300. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  95301. zDb = db->aDb[iDb].zDbSName;
  95302. db->mDbFlags |= DBFLAG_PreferBuiltin;
  95303. /* Get a NULL terminated version of the new table name. */
  95304. zName = sqlite3NameFromToken(db, pName);
  95305. if( !zName ) goto exit_rename_table;
  95306. /* Check that a table or index named 'zName' does not already exist
  95307. ** in database iDb. If so, this is an error.
  95308. */
  95309. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  95310. sqlite3ErrorMsg(pParse,
  95311. "there is already another table or index with this name: %s", zName);
  95312. goto exit_rename_table;
  95313. }
  95314. /* Make sure it is not a system table being altered, or a reserved name
  95315. ** that the table is being renamed to.
  95316. */
  95317. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  95318. goto exit_rename_table;
  95319. }
  95320. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  95321. exit_rename_table;
  95322. }
  95323. #ifndef SQLITE_OMIT_VIEW
  95324. if( pTab->pSelect ){
  95325. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  95326. goto exit_rename_table;
  95327. }
  95328. #endif
  95329. #ifndef SQLITE_OMIT_AUTHORIZATION
  95330. /* Invoke the authorization callback. */
  95331. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  95332. goto exit_rename_table;
  95333. }
  95334. #endif
  95335. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95336. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  95337. goto exit_rename_table;
  95338. }
  95339. if( IsVirtual(pTab) ){
  95340. pVTab = sqlite3GetVTable(db, pTab);
  95341. if( pVTab->pVtab->pModule->xRename==0 ){
  95342. pVTab = 0;
  95343. }
  95344. }
  95345. #endif
  95346. /* Begin a transaction for database iDb.
  95347. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  95348. ** schema). Open a statement transaction if the table is a virtual
  95349. ** table.
  95350. */
  95351. v = sqlite3GetVdbe(pParse);
  95352. if( v==0 ){
  95353. goto exit_rename_table;
  95354. }
  95355. /* figure out how many UTF-8 characters are in zName */
  95356. zTabName = pTab->zName;
  95357. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  95358. /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
  95359. ** the schema to use the new table name. */
  95360. sqlite3NestedParse(pParse,
  95361. "UPDATE \"%w\".%s SET "
  95362. "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
  95363. "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
  95364. "AND name NOT LIKE 'sqlite_%%'"
  95365. , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
  95366. );
  95367. /* Update the tbl_name and name columns of the sqlite_master table
  95368. ** as required. */
  95369. sqlite3NestedParse(pParse,
  95370. "UPDATE %Q.%s SET "
  95371. "tbl_name = %Q, "
  95372. "name = CASE "
  95373. "WHEN type='table' THEN %Q "
  95374. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  95375. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  95376. "ELSE name END "
  95377. "WHERE tbl_name=%Q COLLATE nocase AND "
  95378. "(type='table' OR type='index' OR type='trigger');",
  95379. zDb, MASTER_NAME,
  95380. zName, zName, zName,
  95381. nTabName, zTabName
  95382. );
  95383. #ifndef SQLITE_OMIT_AUTOINCREMENT
  95384. /* If the sqlite_sequence table exists in this database, then update
  95385. ** it with the new table name.
  95386. */
  95387. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  95388. sqlite3NestedParse(pParse,
  95389. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  95390. zDb, zName, pTab->zName);
  95391. }
  95392. #endif
  95393. /* If the table being renamed is not itself part of the temp database,
  95394. ** edit view and trigger definitions within the temp database
  95395. ** as required. */
  95396. if( iDb!=1 ){
  95397. sqlite3NestedParse(pParse,
  95398. "UPDATE sqlite_temp_master SET "
  95399. "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
  95400. "tbl_name = "
  95401. "CASE WHEN tbl_name=%Q COLLATE nocase AND "
  95402. " sqlite_rename_test(%Q, sql, type, name, 1) "
  95403. "THEN %Q ELSE tbl_name END "
  95404. "WHERE type IN ('view', 'trigger')"
  95405. , zDb, zTabName, zName, zTabName, zDb, zName);
  95406. }
  95407. /* If this is a virtual table, invoke the xRename() function if
  95408. ** one is defined. The xRename() callback will modify the names
  95409. ** of any resources used by the v-table implementation (including other
  95410. ** SQLite tables) that are identified by the name of the virtual table.
  95411. */
  95412. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95413. if( pVTab ){
  95414. int i = ++pParse->nMem;
  95415. sqlite3VdbeLoadString(v, i, zName);
  95416. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  95417. sqlite3MayAbort(pParse);
  95418. }
  95419. #endif
  95420. renameReloadSchema(pParse, iDb);
  95421. renameTestSchema(pParse, zDb, iDb==1);
  95422. exit_rename_table:
  95423. sqlite3SrcListDelete(db, pSrc);
  95424. sqlite3DbFree(db, zName);
  95425. db->mDbFlags = savedDbFlags;
  95426. }
  95427. /*
  95428. ** This function is called after an "ALTER TABLE ... ADD" statement
  95429. ** has been parsed. Argument pColDef contains the text of the new
  95430. ** column definition.
  95431. **
  95432. ** The Table structure pParse->pNewTable was extended to include
  95433. ** the new column during parsing.
  95434. */
  95435. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  95436. Table *pNew; /* Copy of pParse->pNewTable */
  95437. Table *pTab; /* Table being altered */
  95438. int iDb; /* Database number */
  95439. const char *zDb; /* Database name */
  95440. const char *zTab; /* Table name */
  95441. char *zCol; /* Null-terminated column definition */
  95442. Column *pCol; /* The new column */
  95443. Expr *pDflt; /* Default value for the new column */
  95444. sqlite3 *db; /* The database connection; */
  95445. Vdbe *v; /* The prepared statement under construction */
  95446. int r1; /* Temporary registers */
  95447. db = pParse->db;
  95448. if( pParse->nErr || db->mallocFailed ) return;
  95449. pNew = pParse->pNewTable;
  95450. assert( pNew );
  95451. assert( sqlite3BtreeHoldsAllMutexes(db) );
  95452. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  95453. zDb = db->aDb[iDb].zDbSName;
  95454. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  95455. pCol = &pNew->aCol[pNew->nCol-1];
  95456. pDflt = pCol->pDflt;
  95457. pTab = sqlite3FindTable(db, zTab, zDb);
  95458. assert( pTab );
  95459. #ifndef SQLITE_OMIT_AUTHORIZATION
  95460. /* Invoke the authorization callback. */
  95461. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  95462. return;
  95463. }
  95464. #endif
  95465. /* If the default value for the new column was specified with a
  95466. ** literal NULL, then set pDflt to 0. This simplifies checking
  95467. ** for an SQL NULL default below.
  95468. */
  95469. assert( pDflt==0 || pDflt->op==TK_SPAN );
  95470. if( pDflt && pDflt->pLeft->op==TK_NULL ){
  95471. pDflt = 0;
  95472. }
  95473. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  95474. ** If there is a NOT NULL constraint, then the default value for the
  95475. ** column must not be NULL.
  95476. */
  95477. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  95478. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  95479. return;
  95480. }
  95481. if( pNew->pIndex ){
  95482. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  95483. return;
  95484. }
  95485. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  95486. sqlite3ErrorMsg(pParse,
  95487. "Cannot add a REFERENCES column with non-NULL default value");
  95488. return;
  95489. }
  95490. if( pCol->notNull && !pDflt ){
  95491. sqlite3ErrorMsg(pParse,
  95492. "Cannot add a NOT NULL column with default value NULL");
  95493. return;
  95494. }
  95495. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  95496. ** can handle (i.e. not CURRENT_TIME etc.)
  95497. */
  95498. if( pDflt ){
  95499. sqlite3_value *pVal = 0;
  95500. int rc;
  95501. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  95502. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  95503. if( rc!=SQLITE_OK ){
  95504. assert( db->mallocFailed == 1 );
  95505. return;
  95506. }
  95507. if( !pVal ){
  95508. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  95509. return;
  95510. }
  95511. sqlite3ValueFree(pVal);
  95512. }
  95513. /* Modify the CREATE TABLE statement. */
  95514. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  95515. if( zCol ){
  95516. char *zEnd = &zCol[pColDef->n-1];
  95517. u32 savedDbFlags = db->mDbFlags;
  95518. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  95519. *zEnd-- = '\0';
  95520. }
  95521. db->mDbFlags |= DBFLAG_PreferBuiltin;
  95522. sqlite3NestedParse(pParse,
  95523. "UPDATE \"%w\".%s SET "
  95524. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  95525. "WHERE type = 'table' AND name = %Q",
  95526. zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
  95527. zTab
  95528. );
  95529. sqlite3DbFree(db, zCol);
  95530. db->mDbFlags = savedDbFlags;
  95531. }
  95532. /* Make sure the schema version is at least 3. But do not upgrade
  95533. ** from less than 3 to 4, as that will corrupt any preexisting DESC
  95534. ** index.
  95535. */
  95536. v = sqlite3GetVdbe(pParse);
  95537. if( v ){
  95538. r1 = sqlite3GetTempReg(pParse);
  95539. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  95540. sqlite3VdbeUsesBtree(v, iDb);
  95541. sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
  95542. sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
  95543. VdbeCoverage(v);
  95544. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
  95545. sqlite3ReleaseTempReg(pParse, r1);
  95546. }
  95547. /* Reload the table definition */
  95548. renameReloadSchema(pParse, iDb);
  95549. }
  95550. /*
  95551. ** This function is called by the parser after the table-name in
  95552. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  95553. ** pSrc is the full-name of the table being altered.
  95554. **
  95555. ** This routine makes a (partial) copy of the Table structure
  95556. ** for the table being altered and sets Parse.pNewTable to point
  95557. ** to it. Routines called by the parser as the column definition
  95558. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  95559. ** the copy. The copy of the Table structure is deleted by tokenize.c
  95560. ** after parsing is finished.
  95561. **
  95562. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  95563. ** coding the "ALTER TABLE ... ADD" statement.
  95564. */
  95565. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  95566. Table *pNew;
  95567. Table *pTab;
  95568. int iDb;
  95569. int i;
  95570. int nAlloc;
  95571. sqlite3 *db = pParse->db;
  95572. /* Look up the table being altered. */
  95573. assert( pParse->pNewTable==0 );
  95574. assert( sqlite3BtreeHoldsAllMutexes(db) );
  95575. if( db->mallocFailed ) goto exit_begin_add_column;
  95576. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  95577. if( !pTab ) goto exit_begin_add_column;
  95578. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95579. if( IsVirtual(pTab) ){
  95580. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  95581. goto exit_begin_add_column;
  95582. }
  95583. #endif
  95584. /* Make sure this is not an attempt to ALTER a view. */
  95585. if( pTab->pSelect ){
  95586. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  95587. goto exit_begin_add_column;
  95588. }
  95589. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  95590. goto exit_begin_add_column;
  95591. }
  95592. assert( pTab->addColOffset>0 );
  95593. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95594. /* Put a copy of the Table struct in Parse.pNewTable for the
  95595. ** sqlite3AddColumn() function and friends to modify. But modify
  95596. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  95597. ** prefix, we insure that the name will not collide with an existing
  95598. ** table because user table are not allowed to have the "sqlite_"
  95599. ** prefix on their name.
  95600. */
  95601. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  95602. if( !pNew ) goto exit_begin_add_column;
  95603. pParse->pNewTable = pNew;
  95604. pNew->nTabRef = 1;
  95605. pNew->nCol = pTab->nCol;
  95606. assert( pNew->nCol>0 );
  95607. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  95608. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  95609. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  95610. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  95611. if( !pNew->aCol || !pNew->zName ){
  95612. assert( db->mallocFailed );
  95613. goto exit_begin_add_column;
  95614. }
  95615. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  95616. for(i=0; i<pNew->nCol; i++){
  95617. Column *pCol = &pNew->aCol[i];
  95618. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  95619. pCol->zColl = 0;
  95620. pCol->pDflt = 0;
  95621. }
  95622. pNew->pSchema = db->aDb[iDb].pSchema;
  95623. pNew->addColOffset = pTab->addColOffset;
  95624. pNew->nTabRef = 1;
  95625. exit_begin_add_column:
  95626. sqlite3SrcListDelete(db, pSrc);
  95627. return;
  95628. }
  95629. /*
  95630. ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
  95631. ** command. This function checks if the table is a view or virtual
  95632. ** table (columns of views or virtual tables may not be renamed). If so,
  95633. ** it loads an error message into pParse and returns non-zero.
  95634. **
  95635. ** Or, if pTab is not a view or virtual table, zero is returned.
  95636. */
  95637. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  95638. static int isRealTable(Parse *pParse, Table *pTab){
  95639. const char *zType = 0;
  95640. #ifndef SQLITE_OMIT_VIEW
  95641. if( pTab->pSelect ){
  95642. zType = "view";
  95643. }
  95644. #endif
  95645. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95646. if( IsVirtual(pTab) ){
  95647. zType = "virtual table";
  95648. }
  95649. #endif
  95650. if( zType ){
  95651. sqlite3ErrorMsg(
  95652. pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
  95653. );
  95654. return 1;
  95655. }
  95656. return 0;
  95657. }
  95658. #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  95659. # define isRealTable(x,y) (0)
  95660. #endif
  95661. /*
  95662. ** Handles the following parser reduction:
  95663. **
  95664. ** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
  95665. */
  95666. SQLITE_PRIVATE void sqlite3AlterRenameColumn(
  95667. Parse *pParse, /* Parsing context */
  95668. SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
  95669. Token *pOld, /* Name of column being changed */
  95670. Token *pNew /* New column name */
  95671. ){
  95672. sqlite3 *db = pParse->db; /* Database connection */
  95673. Table *pTab; /* Table being updated */
  95674. int iCol; /* Index of column being renamed */
  95675. char *zOld = 0; /* Old column name */
  95676. char *zNew = 0; /* New column name */
  95677. const char *zDb; /* Name of schema containing the table */
  95678. int iSchema; /* Index of the schema */
  95679. int bQuote; /* True to quote the new name */
  95680. /* Locate the table to be altered */
  95681. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  95682. if( !pTab ) goto exit_rename_column;
  95683. /* Cannot alter a system table */
  95684. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ) goto exit_rename_column;
  95685. if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
  95686. /* Which schema holds the table to be altered */
  95687. iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
  95688. assert( iSchema>=0 );
  95689. zDb = db->aDb[iSchema].zDbSName;
  95690. #ifndef SQLITE_OMIT_AUTHORIZATION
  95691. /* Invoke the authorization callback. */
  95692. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  95693. goto exit_rename_column;
  95694. }
  95695. #endif
  95696. /* Make sure the old name really is a column name in the table to be
  95697. ** altered. Set iCol to be the index of the column being renamed */
  95698. zOld = sqlite3NameFromToken(db, pOld);
  95699. if( !zOld ) goto exit_rename_column;
  95700. for(iCol=0; iCol<pTab->nCol; iCol++){
  95701. if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
  95702. }
  95703. if( iCol==pTab->nCol ){
  95704. sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
  95705. goto exit_rename_column;
  95706. }
  95707. /* Do the rename operation using a recursive UPDATE statement that
  95708. ** uses the sqlite_rename_column() SQL function to compute the new
  95709. ** CREATE statement text for the sqlite_master table.
  95710. */
  95711. zNew = sqlite3NameFromToken(db, pNew);
  95712. if( !zNew ) goto exit_rename_column;
  95713. assert( pNew->n>0 );
  95714. bQuote = sqlite3Isquote(pNew->z[0]);
  95715. sqlite3NestedParse(pParse,
  95716. "UPDATE \"%w\".%s SET "
  95717. "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
  95718. "WHERE name NOT LIKE 'sqlite_%%' AND (type != 'index' OR tbl_name = %Q)"
  95719. " AND sql NOT LIKE 'create virtual%%'",
  95720. zDb, MASTER_NAME,
  95721. zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
  95722. pTab->zName
  95723. );
  95724. sqlite3NestedParse(pParse,
  95725. "UPDATE temp.%s SET "
  95726. "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
  95727. "WHERE type IN ('trigger', 'view')",
  95728. MASTER_NAME,
  95729. zDb, pTab->zName, iCol, zNew, bQuote
  95730. );
  95731. /* Drop and reload the database schema. */
  95732. renameReloadSchema(pParse, iSchema);
  95733. renameTestSchema(pParse, zDb, iSchema==1);
  95734. exit_rename_column:
  95735. sqlite3SrcListDelete(db, pSrc);
  95736. sqlite3DbFree(db, zOld);
  95737. sqlite3DbFree(db, zNew);
  95738. return;
  95739. }
  95740. /*
  95741. ** Each RenameToken object maps an element of the parse tree into
  95742. ** the token that generated that element. The parse tree element
  95743. ** might be one of:
  95744. **
  95745. ** * A pointer to an Expr that represents an ID
  95746. ** * The name of a table column in Column.zName
  95747. **
  95748. ** A list of RenameToken objects can be constructed during parsing.
  95749. ** Each new object is created by sqlite3RenameTokenMap().
  95750. ** As the parse tree is transformed, the sqlite3RenameTokenRemap()
  95751. ** routine is used to keep the mapping current.
  95752. **
  95753. ** After the parse finishes, renameTokenFind() routine can be used
  95754. ** to look up the actual token value that created some element in
  95755. ** the parse tree.
  95756. */
  95757. struct RenameToken {
  95758. void *p; /* Parse tree element created by token t */
  95759. Token t; /* The token that created parse tree element p */
  95760. RenameToken *pNext; /* Next is a list of all RenameToken objects */
  95761. };
  95762. /*
  95763. ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
  95764. ** down into the Walker.
  95765. */
  95766. typedef struct RenameCtx RenameCtx;
  95767. struct RenameCtx {
  95768. RenameToken *pList; /* List of tokens to overwrite */
  95769. int nList; /* Number of tokens in pList */
  95770. int iCol; /* Index of column being renamed */
  95771. Table *pTab; /* Table being ALTERed */
  95772. const char *zOld; /* Old column name */
  95773. };
  95774. #ifdef SQLITE_DEBUG
  95775. /*
  95776. ** This function is only for debugging. It performs two tasks:
  95777. **
  95778. ** 1. Checks that pointer pPtr does not already appear in the
  95779. ** rename-token list.
  95780. **
  95781. ** 2. Dereferences each pointer in the rename-token list.
  95782. **
  95783. ** The second is most effective when debugging under valgrind or
  95784. ** address-sanitizer or similar. If any of these pointers no longer
  95785. ** point to valid objects, an exception is raised by the memory-checking
  95786. ** tool.
  95787. **
  95788. ** The point of this is to prevent comparisons of invalid pointer values.
  95789. ** Even though this always seems to work, it is undefined according to the
  95790. ** C standard. Example of undefined comparison:
  95791. **
  95792. ** sqlite3_free(x);
  95793. ** if( x==y ) ...
  95794. **
  95795. ** Technically, as x no longer points into a valid object or to the byte
  95796. ** following a valid object, it may not be used in comparison operations.
  95797. */
  95798. static void renameTokenCheckAll(Parse *pParse, void *pPtr){
  95799. if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
  95800. RenameToken *p;
  95801. u8 i = 0;
  95802. for(p=pParse->pRename; p; p=p->pNext){
  95803. if( p->p ){
  95804. assert( p->p!=pPtr );
  95805. i += *(u8*)(p->p);
  95806. }
  95807. }
  95808. }
  95809. }
  95810. #else
  95811. # define renameTokenCheckAll(x,y)
  95812. #endif
  95813. /*
  95814. ** Remember that the parser tree element pPtr was created using
  95815. ** the token pToken.
  95816. **
  95817. ** In other words, construct a new RenameToken object and add it
  95818. ** to the list of RenameToken objects currently being built up
  95819. ** in pParse->pRename.
  95820. **
  95821. ** The pPtr argument is returned so that this routine can be used
  95822. ** with tail recursion in tokenExpr() routine, for a small performance
  95823. ** improvement.
  95824. */
  95825. SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
  95826. RenameToken *pNew;
  95827. assert( pPtr || pParse->db->mallocFailed );
  95828. renameTokenCheckAll(pParse, pPtr);
  95829. pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
  95830. if( pNew ){
  95831. pNew->p = pPtr;
  95832. pNew->t = *pToken;
  95833. pNew->pNext = pParse->pRename;
  95834. pParse->pRename = pNew;
  95835. }
  95836. return pPtr;
  95837. }
  95838. /*
  95839. ** It is assumed that there is already a RenameToken object associated
  95840. ** with parse tree element pFrom. This function remaps the associated token
  95841. ** to parse tree element pTo.
  95842. */
  95843. SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
  95844. RenameToken *p;
  95845. renameTokenCheckAll(pParse, pTo);
  95846. for(p=pParse->pRename; p; p=p->pNext){
  95847. if( p->p==pFrom ){
  95848. p->p = pTo;
  95849. break;
  95850. }
  95851. }
  95852. }
  95853. /*
  95854. ** Walker callback used by sqlite3RenameExprUnmap().
  95855. */
  95856. static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
  95857. Parse *pParse = pWalker->pParse;
  95858. sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
  95859. return WRC_Continue;
  95860. }
  95861. /*
  95862. ** Remove all nodes that are part of expression pExpr from the rename list.
  95863. */
  95864. SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
  95865. Walker sWalker;
  95866. memset(&sWalker, 0, sizeof(Walker));
  95867. sWalker.pParse = pParse;
  95868. sWalker.xExprCallback = renameUnmapExprCb;
  95869. sqlite3WalkExpr(&sWalker, pExpr);
  95870. }
  95871. /*
  95872. ** Remove all nodes that are part of expression-list pEList from the
  95873. ** rename list.
  95874. */
  95875. SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
  95876. if( pEList ){
  95877. int i;
  95878. Walker sWalker;
  95879. memset(&sWalker, 0, sizeof(Walker));
  95880. sWalker.pParse = pParse;
  95881. sWalker.xExprCallback = renameUnmapExprCb;
  95882. sqlite3WalkExprList(&sWalker, pEList);
  95883. for(i=0; i<pEList->nExpr; i++){
  95884. sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
  95885. }
  95886. }
  95887. }
  95888. /*
  95889. ** Free the list of RenameToken objects given in the second argument
  95890. */
  95891. static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
  95892. RenameToken *pNext;
  95893. RenameToken *p;
  95894. for(p=pToken; p; p=pNext){
  95895. pNext = p->pNext;
  95896. sqlite3DbFree(db, p);
  95897. }
  95898. }
  95899. /*
  95900. ** Search the Parse object passed as the first argument for a RenameToken
  95901. ** object associated with parse tree element pPtr. If found, remove it
  95902. ** from the Parse object and add it to the list maintained by the
  95903. ** RenameCtx object passed as the second argument.
  95904. */
  95905. static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
  95906. RenameToken **pp;
  95907. assert( pPtr!=0 );
  95908. for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
  95909. if( (*pp)->p==pPtr ){
  95910. RenameToken *pToken = *pp;
  95911. *pp = pToken->pNext;
  95912. pToken->pNext = pCtx->pList;
  95913. pCtx->pList = pToken;
  95914. pCtx->nList++;
  95915. break;
  95916. }
  95917. }
  95918. }
  95919. /*
  95920. ** This is a Walker select callback. It does nothing. It is only required
  95921. ** because without a dummy callback, sqlite3WalkExpr() and similar do not
  95922. ** descend into sub-select statements.
  95923. */
  95924. static int renameColumnSelectCb(Walker *pWalker, Select *p){
  95925. UNUSED_PARAMETER(pWalker);
  95926. UNUSED_PARAMETER(p);
  95927. return WRC_Continue;
  95928. }
  95929. /*
  95930. ** This is a Walker expression callback.
  95931. **
  95932. ** For every TK_COLUMN node in the expression tree, search to see
  95933. ** if the column being references is the column being renamed by an
  95934. ** ALTER TABLE statement. If it is, then attach its associated
  95935. ** RenameToken object to the list of RenameToken objects being
  95936. ** constructed in RenameCtx object at pWalker->u.pRename.
  95937. */
  95938. static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
  95939. RenameCtx *p = pWalker->u.pRename;
  95940. if( pExpr->op==TK_TRIGGER
  95941. && pExpr->iColumn==p->iCol
  95942. && pWalker->pParse->pTriggerTab==p->pTab
  95943. ){
  95944. renameTokenFind(pWalker->pParse, p, (void*)pExpr);
  95945. }else if( pExpr->op==TK_COLUMN
  95946. && pExpr->iColumn==p->iCol
  95947. && p->pTab==pExpr->y.pTab
  95948. ){
  95949. renameTokenFind(pWalker->pParse, p, (void*)pExpr);
  95950. }
  95951. return WRC_Continue;
  95952. }
  95953. /*
  95954. ** The RenameCtx contains a list of tokens that reference a column that
  95955. ** is being renamed by an ALTER TABLE statement. Return the "last"
  95956. ** RenameToken in the RenameCtx and remove that RenameToken from the
  95957. ** RenameContext. "Last" means the last RenameToken encountered when
  95958. ** the input SQL is parsed from left to right. Repeated calls to this routine
  95959. ** return all column name tokens in the order that they are encountered
  95960. ** in the SQL statement.
  95961. */
  95962. static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
  95963. RenameToken *pBest = pCtx->pList;
  95964. RenameToken *pToken;
  95965. RenameToken **pp;
  95966. for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
  95967. if( pToken->t.z>pBest->t.z ) pBest = pToken;
  95968. }
  95969. for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
  95970. *pp = pBest->pNext;
  95971. return pBest;
  95972. }
  95973. /*
  95974. ** An error occured while parsing or otherwise processing a database
  95975. ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
  95976. ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
  95977. ** sub-routine is currently stored in pParse->zErrMsg. This function
  95978. ** adds context to the error message and then stores it in pCtx.
  95979. */
  95980. static void renameColumnParseError(
  95981. sqlite3_context *pCtx,
  95982. int bPost,
  95983. sqlite3_value *pType,
  95984. sqlite3_value *pObject,
  95985. Parse *pParse
  95986. ){
  95987. const char *zT = (const char*)sqlite3_value_text(pType);
  95988. const char *zN = (const char*)sqlite3_value_text(pObject);
  95989. char *zErr;
  95990. zErr = sqlite3_mprintf("error in %s %s%s: %s",
  95991. zT, zN, (bPost ? " after rename" : ""),
  95992. pParse->zErrMsg
  95993. );
  95994. sqlite3_result_error(pCtx, zErr, -1);
  95995. sqlite3_free(zErr);
  95996. }
  95997. /*
  95998. ** For each name in the the expression-list pEList (i.e. each
  95999. ** pEList->a[i].zName) that matches the string in zOld, extract the
  96000. ** corresponding rename-token from Parse object pParse and add it
  96001. ** to the RenameCtx pCtx.
  96002. */
  96003. static void renameColumnElistNames(
  96004. Parse *pParse,
  96005. RenameCtx *pCtx,
  96006. ExprList *pEList,
  96007. const char *zOld
  96008. ){
  96009. if( pEList ){
  96010. int i;
  96011. for(i=0; i<pEList->nExpr; i++){
  96012. char *zName = pEList->a[i].zName;
  96013. if( 0==sqlite3_stricmp(zName, zOld) ){
  96014. renameTokenFind(pParse, pCtx, (void*)zName);
  96015. }
  96016. }
  96017. }
  96018. }
  96019. /*
  96020. ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
  96021. ** that matches the string in zOld, extract the corresponding rename-token
  96022. ** from Parse object pParse and add it to the RenameCtx pCtx.
  96023. */
  96024. static void renameColumnIdlistNames(
  96025. Parse *pParse,
  96026. RenameCtx *pCtx,
  96027. IdList *pIdList,
  96028. const char *zOld
  96029. ){
  96030. if( pIdList ){
  96031. int i;
  96032. for(i=0; i<pIdList->nId; i++){
  96033. char *zName = pIdList->a[i].zName;
  96034. if( 0==sqlite3_stricmp(zName, zOld) ){
  96035. renameTokenFind(pParse, pCtx, (void*)zName);
  96036. }
  96037. }
  96038. }
  96039. }
  96040. /*
  96041. ** Parse the SQL statement zSql using Parse object (*p). The Parse object
  96042. ** is initialized by this function before it is used.
  96043. */
  96044. static int renameParseSql(
  96045. Parse *p, /* Memory to use for Parse object */
  96046. const char *zDb, /* Name of schema SQL belongs to */
  96047. int bTable, /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
  96048. sqlite3 *db, /* Database handle */
  96049. const char *zSql, /* SQL to parse */
  96050. int bTemp /* True if SQL is from temp schema */
  96051. ){
  96052. int rc;
  96053. char *zErr = 0;
  96054. db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
  96055. /* Parse the SQL statement passed as the first argument. If no error
  96056. ** occurs and the parse does not result in a new table, index or
  96057. ** trigger object, the database must be corrupt. */
  96058. memset(p, 0, sizeof(Parse));
  96059. p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
  96060. p->db = db;
  96061. p->nQueryLoop = 1;
  96062. rc = sqlite3RunParser(p, zSql, &zErr);
  96063. assert( p->zErrMsg==0 );
  96064. assert( rc!=SQLITE_OK || zErr==0 );
  96065. assert( (0!=p->pNewTable) + (0!=p->pNewIndex) + (0!=p->pNewTrigger)<2 );
  96066. p->zErrMsg = zErr;
  96067. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  96068. if( rc==SQLITE_OK
  96069. && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
  96070. ){
  96071. rc = SQLITE_CORRUPT_BKPT;
  96072. }
  96073. #ifdef SQLITE_DEBUG
  96074. /* Ensure that all mappings in the Parse.pRename list really do map to
  96075. ** a part of the input string. */
  96076. if( rc==SQLITE_OK ){
  96077. int nSql = sqlite3Strlen30(zSql);
  96078. RenameToken *pToken;
  96079. for(pToken=p->pRename; pToken; pToken=pToken->pNext){
  96080. assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
  96081. }
  96082. }
  96083. #endif
  96084. db->init.iDb = 0;
  96085. return rc;
  96086. }
  96087. /*
  96088. ** This function edits SQL statement zSql, replacing each token identified
  96089. ** by the linked list pRename with the text of zNew. If argument bQuote is
  96090. ** true, then zNew is always quoted first. If no error occurs, the result
  96091. ** is loaded into context object pCtx as the result.
  96092. **
  96093. ** Or, if an error occurs (i.e. an OOM condition), an error is left in
  96094. ** pCtx and an SQLite error code returned.
  96095. */
  96096. static int renameEditSql(
  96097. sqlite3_context *pCtx, /* Return result here */
  96098. RenameCtx *pRename, /* Rename context */
  96099. const char *zSql, /* SQL statement to edit */
  96100. const char *zNew, /* New token text */
  96101. int bQuote /* True to always quote token */
  96102. ){
  96103. int nNew = sqlite3Strlen30(zNew);
  96104. int nSql = sqlite3Strlen30(zSql);
  96105. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  96106. int rc = SQLITE_OK;
  96107. char *zQuot;
  96108. char *zOut;
  96109. int nQuot;
  96110. /* Set zQuot to point to a buffer containing a quoted copy of the
  96111. ** identifier zNew. If the corresponding identifier in the original
  96112. ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
  96113. ** point to zQuot so that all substitutions are made using the
  96114. ** quoted version of the new column name. */
  96115. zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
  96116. if( zQuot==0 ){
  96117. return SQLITE_NOMEM;
  96118. }else{
  96119. nQuot = sqlite3Strlen30(zQuot);
  96120. }
  96121. if( bQuote ){
  96122. zNew = zQuot;
  96123. nNew = nQuot;
  96124. }
  96125. /* At this point pRename->pList contains a list of RenameToken objects
  96126. ** corresponding to all tokens in the input SQL that must be replaced
  96127. ** with the new column name. All that remains is to construct and
  96128. ** return the edited SQL string. */
  96129. assert( nQuot>=nNew );
  96130. zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
  96131. if( zOut ){
  96132. int nOut = nSql;
  96133. memcpy(zOut, zSql, nSql);
  96134. while( pRename->pList ){
  96135. int iOff; /* Offset of token to replace in zOut */
  96136. RenameToken *pBest = renameColumnTokenNext(pRename);
  96137. u32 nReplace;
  96138. const char *zReplace;
  96139. if( sqlite3IsIdChar(*pBest->t.z) ){
  96140. nReplace = nNew;
  96141. zReplace = zNew;
  96142. }else{
  96143. nReplace = nQuot;
  96144. zReplace = zQuot;
  96145. }
  96146. iOff = pBest->t.z - zSql;
  96147. if( pBest->t.n!=nReplace ){
  96148. memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
  96149. nOut - (iOff + pBest->t.n)
  96150. );
  96151. nOut += nReplace - pBest->t.n;
  96152. zOut[nOut] = '\0';
  96153. }
  96154. memcpy(&zOut[iOff], zReplace, nReplace);
  96155. sqlite3DbFree(db, pBest);
  96156. }
  96157. sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
  96158. sqlite3DbFree(db, zOut);
  96159. }else{
  96160. rc = SQLITE_NOMEM;
  96161. }
  96162. sqlite3_free(zQuot);
  96163. return rc;
  96164. }
  96165. /*
  96166. ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
  96167. ** it was read from the schema of database zDb. Return SQLITE_OK if
  96168. ** successful. Otherwise, return an SQLite error code and leave an error
  96169. ** message in the Parse object.
  96170. */
  96171. static int renameResolveTrigger(Parse *pParse, const char *zDb){
  96172. sqlite3 *db = pParse->db;
  96173. Trigger *pNew = pParse->pNewTrigger;
  96174. TriggerStep *pStep;
  96175. NameContext sNC;
  96176. int rc = SQLITE_OK;
  96177. memset(&sNC, 0, sizeof(sNC));
  96178. sNC.pParse = pParse;
  96179. assert( pNew->pTabSchema );
  96180. pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
  96181. db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
  96182. );
  96183. pParse->eTriggerOp = pNew->op;
  96184. /* ALWAYS() because if the table of the trigger does not exist, the
  96185. ** error would have been hit before this point */
  96186. if( ALWAYS(pParse->pTriggerTab) ){
  96187. rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
  96188. }
  96189. /* Resolve symbols in WHEN clause */
  96190. if( rc==SQLITE_OK && pNew->pWhen ){
  96191. rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
  96192. }
  96193. for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
  96194. if( pStep->pSelect ){
  96195. sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
  96196. if( pParse->nErr ) rc = pParse->rc;
  96197. }
  96198. if( rc==SQLITE_OK && pStep->zTarget ){
  96199. Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
  96200. if( pTarget==0 ){
  96201. rc = SQLITE_ERROR;
  96202. }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
  96203. SrcList sSrc;
  96204. memset(&sSrc, 0, sizeof(sSrc));
  96205. sSrc.nSrc = 1;
  96206. sSrc.a[0].zName = pStep->zTarget;
  96207. sSrc.a[0].pTab = pTarget;
  96208. sNC.pSrcList = &sSrc;
  96209. if( pStep->pWhere ){
  96210. rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
  96211. }
  96212. if( rc==SQLITE_OK ){
  96213. rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
  96214. }
  96215. assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
  96216. if( pStep->pUpsert ){
  96217. Upsert *pUpsert = pStep->pUpsert;
  96218. assert( rc==SQLITE_OK );
  96219. pUpsert->pUpsertSrc = &sSrc;
  96220. sNC.uNC.pUpsert = pUpsert;
  96221. sNC.ncFlags = NC_UUpsert;
  96222. rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
  96223. if( rc==SQLITE_OK ){
  96224. ExprList *pUpsertSet = pUpsert->pUpsertSet;
  96225. rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
  96226. }
  96227. if( rc==SQLITE_OK ){
  96228. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
  96229. }
  96230. if( rc==SQLITE_OK ){
  96231. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
  96232. }
  96233. sNC.ncFlags = 0;
  96234. }
  96235. }
  96236. }
  96237. }
  96238. return rc;
  96239. }
  96240. /*
  96241. ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
  96242. ** objects that are part of the trigger passed as the second argument.
  96243. */
  96244. static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
  96245. TriggerStep *pStep;
  96246. /* Find tokens to edit in WHEN clause */
  96247. sqlite3WalkExpr(pWalker, pTrigger->pWhen);
  96248. /* Find tokens to edit in trigger steps */
  96249. for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
  96250. sqlite3WalkSelect(pWalker, pStep->pSelect);
  96251. sqlite3WalkExpr(pWalker, pStep->pWhere);
  96252. sqlite3WalkExprList(pWalker, pStep->pExprList);
  96253. if( pStep->pUpsert ){
  96254. Upsert *pUpsert = pStep->pUpsert;
  96255. sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
  96256. sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
  96257. sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
  96258. sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
  96259. }
  96260. }
  96261. }
  96262. /*
  96263. ** Free the contents of Parse object (*pParse). Do not free the memory
  96264. ** occupied by the Parse object itself.
  96265. */
  96266. static void renameParseCleanup(Parse *pParse){
  96267. sqlite3 *db = pParse->db;
  96268. if( pParse->pVdbe ){
  96269. sqlite3VdbeFinalize(pParse->pVdbe);
  96270. }
  96271. sqlite3DeleteTable(db, pParse->pNewTable);
  96272. if( pParse->pNewIndex ) sqlite3FreeIndex(db, pParse->pNewIndex);
  96273. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  96274. sqlite3DbFree(db, pParse->zErrMsg);
  96275. renameTokenFree(db, pParse->pRename);
  96276. sqlite3ParserReset(pParse);
  96277. }
  96278. /*
  96279. ** SQL function:
  96280. **
  96281. ** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
  96282. **
  96283. ** 0. zSql: SQL statement to rewrite
  96284. ** 1. type: Type of object ("table", "view" etc.)
  96285. ** 2. object: Name of object
  96286. ** 3. Database: Database name (e.g. "main")
  96287. ** 4. Table: Table name
  96288. ** 5. iCol: Index of column to rename
  96289. ** 6. zNew: New column name
  96290. ** 7. bQuote: Non-zero if the new column name should be quoted.
  96291. ** 8. bTemp: True if zSql comes from temp schema
  96292. **
  96293. ** Do a column rename operation on the CREATE statement given in zSql.
  96294. ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
  96295. ** into zNew. The name should be quoted if bQuote is true.
  96296. **
  96297. ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
  96298. ** It is only accessible to SQL created using sqlite3NestedParse(). It is
  96299. ** not reachable from ordinary SQL passed into sqlite3_prepare().
  96300. */
  96301. static void renameColumnFunc(
  96302. sqlite3_context *context,
  96303. int NotUsed,
  96304. sqlite3_value **argv
  96305. ){
  96306. sqlite3 *db = sqlite3_context_db_handle(context);
  96307. RenameCtx sCtx;
  96308. const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  96309. const char *zDb = (const char*)sqlite3_value_text(argv[3]);
  96310. const char *zTable = (const char*)sqlite3_value_text(argv[4]);
  96311. int iCol = sqlite3_value_int(argv[5]);
  96312. const char *zNew = (const char*)sqlite3_value_text(argv[6]);
  96313. int bQuote = sqlite3_value_int(argv[7]);
  96314. int bTemp = sqlite3_value_int(argv[8]);
  96315. const char *zOld;
  96316. int rc;
  96317. Parse sParse;
  96318. Walker sWalker;
  96319. Index *pIdx;
  96320. int i;
  96321. Table *pTab;
  96322. #ifndef SQLITE_OMIT_AUTHORIZATION
  96323. sqlite3_xauth xAuth = db->xAuth;
  96324. #endif
  96325. UNUSED_PARAMETER(NotUsed);
  96326. if( zSql==0 ) return;
  96327. if( zTable==0 ) return;
  96328. if( zNew==0 ) return;
  96329. if( iCol<0 ) return;
  96330. sqlite3BtreeEnterAll(db);
  96331. pTab = sqlite3FindTable(db, zTable, zDb);
  96332. if( pTab==0 || iCol>=pTab->nCol ){
  96333. sqlite3BtreeLeaveAll(db);
  96334. return;
  96335. }
  96336. zOld = pTab->aCol[iCol].zName;
  96337. memset(&sCtx, 0, sizeof(sCtx));
  96338. sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
  96339. #ifndef SQLITE_OMIT_AUTHORIZATION
  96340. db->xAuth = 0;
  96341. #endif
  96342. rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
  96343. /* Find tokens that need to be replaced. */
  96344. memset(&sWalker, 0, sizeof(Walker));
  96345. sWalker.pParse = &sParse;
  96346. sWalker.xExprCallback = renameColumnExprCb;
  96347. sWalker.xSelectCallback = renameColumnSelectCb;
  96348. sWalker.u.pRename = &sCtx;
  96349. sCtx.pTab = pTab;
  96350. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  96351. if( sParse.pNewTable ){
  96352. Select *pSelect = sParse.pNewTable->pSelect;
  96353. if( pSelect ){
  96354. sParse.rc = SQLITE_OK;
  96355. sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
  96356. rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
  96357. if( rc==SQLITE_OK ){
  96358. sqlite3WalkSelect(&sWalker, pSelect);
  96359. }
  96360. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  96361. }else{
  96362. /* A regular table */
  96363. int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
  96364. FKey *pFKey;
  96365. assert( sParse.pNewTable->pSelect==0 );
  96366. sCtx.pTab = sParse.pNewTable;
  96367. if( bFKOnly==0 ){
  96368. renameTokenFind(
  96369. &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
  96370. );
  96371. if( sCtx.iCol<0 ){
  96372. renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
  96373. }
  96374. sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
  96375. for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
  96376. sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
  96377. }
  96378. }
  96379. for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  96380. for(i=0; i<pFKey->nCol; i++){
  96381. if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
  96382. renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
  96383. }
  96384. if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
  96385. && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
  96386. ){
  96387. renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
  96388. }
  96389. }
  96390. }
  96391. }
  96392. }else if( sParse.pNewIndex ){
  96393. sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
  96394. sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
  96395. }else{
  96396. /* A trigger */
  96397. TriggerStep *pStep;
  96398. rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
  96399. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  96400. for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
  96401. if( pStep->zTarget ){
  96402. Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
  96403. if( pTarget==pTab ){
  96404. if( pStep->pUpsert ){
  96405. ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
  96406. renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
  96407. }
  96408. renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
  96409. renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
  96410. }
  96411. }
  96412. }
  96413. /* Find tokens to edit in UPDATE OF clause */
  96414. if( sParse.pTriggerTab==pTab ){
  96415. renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
  96416. }
  96417. /* Find tokens to edit in various expressions and selects */
  96418. renameWalkTrigger(&sWalker, sParse.pNewTrigger);
  96419. }
  96420. assert( rc==SQLITE_OK );
  96421. rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
  96422. renameColumnFunc_done:
  96423. if( rc!=SQLITE_OK ){
  96424. if( sParse.zErrMsg ){
  96425. renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
  96426. }else{
  96427. sqlite3_result_error_code(context, rc);
  96428. }
  96429. }
  96430. renameParseCleanup(&sParse);
  96431. renameTokenFree(db, sCtx.pList);
  96432. #ifndef SQLITE_OMIT_AUTHORIZATION
  96433. db->xAuth = xAuth;
  96434. #endif
  96435. sqlite3BtreeLeaveAll(db);
  96436. }
  96437. /*
  96438. ** Walker expression callback used by "RENAME TABLE".
  96439. */
  96440. static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
  96441. RenameCtx *p = pWalker->u.pRename;
  96442. if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
  96443. renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
  96444. }
  96445. return WRC_Continue;
  96446. }
  96447. /*
  96448. ** Walker select callback used by "RENAME TABLE".
  96449. */
  96450. static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
  96451. int i;
  96452. RenameCtx *p = pWalker->u.pRename;
  96453. SrcList *pSrc = pSelect->pSrc;
  96454. for(i=0; i<pSrc->nSrc; i++){
  96455. struct SrcList_item *pItem = &pSrc->a[i];
  96456. if( pItem->pTab==p->pTab ){
  96457. renameTokenFind(pWalker->pParse, p, pItem->zName);
  96458. }
  96459. }
  96460. return WRC_Continue;
  96461. }
  96462. /*
  96463. ** This C function implements an SQL user function that is used by SQL code
  96464. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  96465. ** of any foreign key constraints that use the table being renamed as the
  96466. ** parent table. It is passed three arguments:
  96467. **
  96468. ** 0: The database containing the table being renamed.
  96469. ** 1. type: Type of object ("table", "view" etc.)
  96470. ** 2. object: Name of object
  96471. ** 3: The complete text of the schema statement being modified,
  96472. ** 4: The old name of the table being renamed, and
  96473. ** 5: The new name of the table being renamed.
  96474. ** 6: True if the schema statement comes from the temp db.
  96475. **
  96476. ** It returns the new schema statement. For example:
  96477. **
  96478. ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
  96479. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  96480. */
  96481. static void renameTableFunc(
  96482. sqlite3_context *context,
  96483. int NotUsed,
  96484. sqlite3_value **argv
  96485. ){
  96486. sqlite3 *db = sqlite3_context_db_handle(context);
  96487. const char *zDb = (const char*)sqlite3_value_text(argv[0]);
  96488. const char *zInput = (const char*)sqlite3_value_text(argv[3]);
  96489. const char *zOld = (const char*)sqlite3_value_text(argv[4]);
  96490. const char *zNew = (const char*)sqlite3_value_text(argv[5]);
  96491. int bTemp = sqlite3_value_int(argv[6]);
  96492. UNUSED_PARAMETER(NotUsed);
  96493. if( zInput && zOld && zNew ){
  96494. Parse sParse;
  96495. int rc;
  96496. int bQuote = 1;
  96497. RenameCtx sCtx;
  96498. Walker sWalker;
  96499. #ifndef SQLITE_OMIT_AUTHORIZATION
  96500. sqlite3_xauth xAuth = db->xAuth;
  96501. db->xAuth = 0;
  96502. #endif
  96503. sqlite3BtreeEnterAll(db);
  96504. memset(&sCtx, 0, sizeof(RenameCtx));
  96505. sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
  96506. memset(&sWalker, 0, sizeof(Walker));
  96507. sWalker.pParse = &sParse;
  96508. sWalker.xExprCallback = renameTableExprCb;
  96509. sWalker.xSelectCallback = renameTableSelectCb;
  96510. sWalker.u.pRename = &sCtx;
  96511. rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
  96512. if( rc==SQLITE_OK ){
  96513. int isLegacy = (db->flags & SQLITE_LegacyAlter);
  96514. if( sParse.pNewTable ){
  96515. Table *pTab = sParse.pNewTable;
  96516. if( pTab->pSelect ){
  96517. if( isLegacy==0 ){
  96518. NameContext sNC;
  96519. memset(&sNC, 0, sizeof(sNC));
  96520. sNC.pParse = &sParse;
  96521. sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
  96522. if( sParse.nErr ) rc = sParse.rc;
  96523. sqlite3WalkSelect(&sWalker, pTab->pSelect);
  96524. }
  96525. }else{
  96526. /* Modify any FK definitions to point to the new table. */
  96527. #ifndef SQLITE_OMIT_FOREIGN_KEY
  96528. if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
  96529. FKey *pFKey;
  96530. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  96531. if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
  96532. renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
  96533. }
  96534. }
  96535. }
  96536. #endif
  96537. /* If this is the table being altered, fix any table refs in CHECK
  96538. ** expressions. Also update the name that appears right after the
  96539. ** "CREATE [VIRTUAL] TABLE" bit. */
  96540. if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
  96541. sCtx.pTab = pTab;
  96542. if( isLegacy==0 ){
  96543. sqlite3WalkExprList(&sWalker, pTab->pCheck);
  96544. }
  96545. renameTokenFind(&sParse, &sCtx, pTab->zName);
  96546. }
  96547. }
  96548. }
  96549. else if( sParse.pNewIndex ){
  96550. renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
  96551. if( isLegacy==0 ){
  96552. sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
  96553. }
  96554. }
  96555. #ifndef SQLITE_OMIT_TRIGGER
  96556. else{
  96557. Trigger *pTrigger = sParse.pNewTrigger;
  96558. TriggerStep *pStep;
  96559. if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
  96560. && sCtx.pTab->pSchema==pTrigger->pTabSchema
  96561. ){
  96562. renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
  96563. }
  96564. if( isLegacy==0 ){
  96565. rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
  96566. if( rc==SQLITE_OK ){
  96567. renameWalkTrigger(&sWalker, pTrigger);
  96568. for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
  96569. if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
  96570. renameTokenFind(&sParse, &sCtx, pStep->zTarget);
  96571. }
  96572. }
  96573. }
  96574. }
  96575. }
  96576. #endif
  96577. }
  96578. if( rc==SQLITE_OK ){
  96579. rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
  96580. }
  96581. if( rc!=SQLITE_OK ){
  96582. if( sParse.zErrMsg ){
  96583. renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
  96584. }else{
  96585. sqlite3_result_error_code(context, rc);
  96586. }
  96587. }
  96588. renameParseCleanup(&sParse);
  96589. renameTokenFree(db, sCtx.pList);
  96590. sqlite3BtreeLeaveAll(db);
  96591. #ifndef SQLITE_OMIT_AUTHORIZATION
  96592. db->xAuth = xAuth;
  96593. #endif
  96594. }
  96595. return;
  96596. }
  96597. /*
  96598. ** An SQL user function that checks that there are no parse or symbol
  96599. ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
  96600. ** After an ALTER TABLE .. RENAME operation is performed and the schema
  96601. ** reloaded, this function is called on each SQL statement in the schema
  96602. ** to ensure that it is still usable.
  96603. **
  96604. ** 0: Database name ("main", "temp" etc.).
  96605. ** 1: SQL statement.
  96606. ** 2: Object type ("view", "table", "trigger" or "index").
  96607. ** 3: Object name.
  96608. ** 4: True if object is from temp schema.
  96609. **
  96610. ** Unless it finds an error, this function normally returns NULL. However, it
  96611. ** returns integer value 1 if:
  96612. **
  96613. ** * the SQL argument creates a trigger, and
  96614. ** * the table that the trigger is attached to is in database zDb.
  96615. */
  96616. static void renameTableTest(
  96617. sqlite3_context *context,
  96618. int NotUsed,
  96619. sqlite3_value **argv
  96620. ){
  96621. sqlite3 *db = sqlite3_context_db_handle(context);
  96622. char const *zDb = (const char*)sqlite3_value_text(argv[0]);
  96623. char const *zInput = (const char*)sqlite3_value_text(argv[1]);
  96624. int bTemp = sqlite3_value_int(argv[4]);
  96625. int isLegacy = (db->flags & SQLITE_LegacyAlter);
  96626. #ifndef SQLITE_OMIT_AUTHORIZATION
  96627. sqlite3_xauth xAuth = db->xAuth;
  96628. db->xAuth = 0;
  96629. #endif
  96630. UNUSED_PARAMETER(NotUsed);
  96631. if( zDb && zInput ){
  96632. int rc;
  96633. Parse sParse;
  96634. rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
  96635. if( rc==SQLITE_OK ){
  96636. if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
  96637. NameContext sNC;
  96638. memset(&sNC, 0, sizeof(sNC));
  96639. sNC.pParse = &sParse;
  96640. sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
  96641. if( sParse.nErr ) rc = sParse.rc;
  96642. }
  96643. else if( sParse.pNewTrigger ){
  96644. if( isLegacy==0 ){
  96645. rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
  96646. }
  96647. if( rc==SQLITE_OK ){
  96648. int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
  96649. int i2 = sqlite3FindDbName(db, zDb);
  96650. if( i1==i2 ) sqlite3_result_int(context, 1);
  96651. }
  96652. }
  96653. }
  96654. if( rc!=SQLITE_OK ){
  96655. renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
  96656. }
  96657. renameParseCleanup(&sParse);
  96658. }
  96659. #ifndef SQLITE_OMIT_AUTHORIZATION
  96660. db->xAuth = xAuth;
  96661. #endif
  96662. }
  96663. /*
  96664. ** Register built-in functions used to help implement ALTER TABLE
  96665. */
  96666. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  96667. static FuncDef aAlterTableFuncs[] = {
  96668. INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
  96669. INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
  96670. INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
  96671. };
  96672. sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
  96673. }
  96674. #endif /* SQLITE_ALTER_TABLE */
  96675. /************** End of alter.c ***********************************************/
  96676. /************** Begin file analyze.c *****************************************/
  96677. /*
  96678. ** 2005-07-08
  96679. **
  96680. ** The author disclaims copyright to this source code. In place of
  96681. ** a legal notice, here is a blessing:
  96682. **
  96683. ** May you do good and not evil.
  96684. ** May you find forgiveness for yourself and forgive others.
  96685. ** May you share freely, never taking more than you give.
  96686. **
  96687. *************************************************************************
  96688. ** This file contains code associated with the ANALYZE command.
  96689. **
  96690. ** The ANALYZE command gather statistics about the content of tables
  96691. ** and indices. These statistics are made available to the query planner
  96692. ** to help it make better decisions about how to perform queries.
  96693. **
  96694. ** The following system tables are or have been supported:
  96695. **
  96696. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  96697. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  96698. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  96699. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  96700. **
  96701. ** Additional tables might be added in future releases of SQLite.
  96702. ** The sqlite_stat2 table is not created or used unless the SQLite version
  96703. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  96704. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  96705. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  96706. ** created and used by SQLite versions 3.7.9 and later and with
  96707. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  96708. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  96709. ** version of sqlite_stat3 and is only available when compiled with
  96710. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  96711. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  96712. ** are both enabled, then STAT4 takes precedence.
  96713. **
  96714. ** For most applications, sqlite_stat1 provides all the statistics required
  96715. ** for the query planner to make good choices.
  96716. **
  96717. ** Format of sqlite_stat1:
  96718. **
  96719. ** There is normally one row per index, with the index identified by the
  96720. ** name in the idx column. The tbl column is the name of the table to
  96721. ** which the index belongs. In each such row, the stat column will be
  96722. ** a string consisting of a list of integers. The first integer in this
  96723. ** list is the number of rows in the index. (This is the same as the
  96724. ** number of rows in the table, except for partial indices.) The second
  96725. ** integer is the average number of rows in the index that have the same
  96726. ** value in the first column of the index. The third integer is the average
  96727. ** number of rows in the index that have the same value for the first two
  96728. ** columns. The N-th integer (for N>1) is the average number of rows in
  96729. ** the index which have the same value for the first N-1 columns. For
  96730. ** a K-column index, there will be K+1 integers in the stat column. If
  96731. ** the index is unique, then the last integer will be 1.
  96732. **
  96733. ** The list of integers in the stat column can optionally be followed
  96734. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  96735. ** must be separated from the last integer by a single space. If the
  96736. ** "unordered" keyword is present, then the query planner assumes that
  96737. ** the index is unordered and will not use the index for a range query.
  96738. **
  96739. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  96740. ** column contains a single integer which is the (estimated) number of
  96741. ** rows in the table identified by sqlite_stat1.tbl.
  96742. **
  96743. ** Format of sqlite_stat2:
  96744. **
  96745. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  96746. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  96747. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  96748. ** about the distribution of keys within an index. The index is identified by
  96749. ** the "idx" column and the "tbl" column is the name of the table to which
  96750. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  96751. ** table for each index.
  96752. **
  96753. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  96754. ** inclusive are samples of the left-most key value in the index taken at
  96755. ** evenly spaced points along the index. Let the number of samples be S
  96756. ** (10 in the standard build) and let C be the number of rows in the index.
  96757. ** Then the sampled rows are given by:
  96758. **
  96759. ** rownumber = (i*C*2 + C)/(S*2)
  96760. **
  96761. ** For i between 0 and S-1. Conceptually, the index space is divided into
  96762. ** S uniform buckets and the samples are the middle row from each bucket.
  96763. **
  96764. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  96765. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  96766. ** writes the sqlite_stat2 table. This version of SQLite only supports
  96767. ** sqlite_stat3.
  96768. **
  96769. ** Format for sqlite_stat3:
  96770. **
  96771. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  96772. ** sqlite_stat4 format will be described first. Further information
  96773. ** about sqlite_stat3 follows the sqlite_stat4 description.
  96774. **
  96775. ** Format for sqlite_stat4:
  96776. **
  96777. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  96778. ** to aid the query planner in choosing good indices based on the values
  96779. ** that indexed columns are compared against in the WHERE clauses of
  96780. ** queries.
  96781. **
  96782. ** The sqlite_stat4 table contains multiple entries for each index.
  96783. ** The idx column names the index and the tbl column is the table of the
  96784. ** index. If the idx and tbl columns are the same, then the sample is
  96785. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  96786. ** binary encoding of a key from the index. The nEq column is a
  96787. ** list of integers. The first integer is the approximate number
  96788. ** of entries in the index whose left-most column exactly matches
  96789. ** the left-most column of the sample. The second integer in nEq
  96790. ** is the approximate number of entries in the index where the
  96791. ** first two columns match the first two columns of the sample.
  96792. ** And so forth. nLt is another list of integers that show the approximate
  96793. ** number of entries that are strictly less than the sample. The first
  96794. ** integer in nLt contains the number of entries in the index where the
  96795. ** left-most column is less than the left-most column of the sample.
  96796. ** The K-th integer in the nLt entry is the number of index entries
  96797. ** where the first K columns are less than the first K columns of the
  96798. ** sample. The nDLt column is like nLt except that it contains the
  96799. ** number of distinct entries in the index that are less than the
  96800. ** sample.
  96801. **
  96802. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  96803. ** The ANALYZE command will typically generate sqlite_stat4 tables
  96804. ** that contain between 10 and 40 samples which are distributed across
  96805. ** the key space, though not uniformly, and which include samples with
  96806. ** large nEq values.
  96807. **
  96808. ** Format for sqlite_stat3 redux:
  96809. **
  96810. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  96811. ** looks at the left-most column of the index. The sqlite_stat3.sample
  96812. ** column contains the actual value of the left-most column instead
  96813. ** of a blob encoding of the complete index key as is found in
  96814. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  96815. ** all contain just a single integer which is the same as the first
  96816. ** integer in the equivalent columns in sqlite_stat4.
  96817. */
  96818. #ifndef SQLITE_OMIT_ANALYZE
  96819. /* #include "sqliteInt.h" */
  96820. #if defined(SQLITE_ENABLE_STAT4)
  96821. # define IsStat4 1
  96822. # define IsStat3 0
  96823. #elif defined(SQLITE_ENABLE_STAT3)
  96824. # define IsStat4 0
  96825. # define IsStat3 1
  96826. #else
  96827. # define IsStat4 0
  96828. # define IsStat3 0
  96829. # undef SQLITE_STAT4_SAMPLES
  96830. # define SQLITE_STAT4_SAMPLES 1
  96831. #endif
  96832. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  96833. /*
  96834. ** This routine generates code that opens the sqlite_statN tables.
  96835. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  96836. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  96837. ** appropriate compile-time options are provided.
  96838. **
  96839. ** If the sqlite_statN tables do not previously exist, it is created.
  96840. **
  96841. ** Argument zWhere may be a pointer to a buffer containing a table name,
  96842. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  96843. ** the sqlite_statN tables associated with the named table are deleted.
  96844. ** If zWhere==0, then code is generated to delete all stat table entries.
  96845. */
  96846. static void openStatTable(
  96847. Parse *pParse, /* Parsing context */
  96848. int iDb, /* The database we are looking in */
  96849. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  96850. const char *zWhere, /* Delete entries for this table or index */
  96851. const char *zWhereType /* Either "tbl" or "idx" */
  96852. ){
  96853. static const struct {
  96854. const char *zName;
  96855. const char *zCols;
  96856. } aTable[] = {
  96857. { "sqlite_stat1", "tbl,idx,stat" },
  96858. #if defined(SQLITE_ENABLE_STAT4)
  96859. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  96860. { "sqlite_stat3", 0 },
  96861. #elif defined(SQLITE_ENABLE_STAT3)
  96862. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  96863. { "sqlite_stat4", 0 },
  96864. #else
  96865. { "sqlite_stat3", 0 },
  96866. { "sqlite_stat4", 0 },
  96867. #endif
  96868. };
  96869. int i;
  96870. sqlite3 *db = pParse->db;
  96871. Db *pDb;
  96872. Vdbe *v = sqlite3GetVdbe(pParse);
  96873. int aRoot[ArraySize(aTable)];
  96874. u8 aCreateTbl[ArraySize(aTable)];
  96875. if( v==0 ) return;
  96876. assert( sqlite3BtreeHoldsAllMutexes(db) );
  96877. assert( sqlite3VdbeDb(v)==db );
  96878. pDb = &db->aDb[iDb];
  96879. /* Create new statistic tables if they do not exist, or clear them
  96880. ** if they do already exist.
  96881. */
  96882. for(i=0; i<ArraySize(aTable); i++){
  96883. const char *zTab = aTable[i].zName;
  96884. Table *pStat;
  96885. if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
  96886. if( aTable[i].zCols ){
  96887. /* The sqlite_statN table does not exist. Create it. Note that a
  96888. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  96889. ** of the new table in register pParse->regRoot. This is important
  96890. ** because the OpenWrite opcode below will be needing it. */
  96891. sqlite3NestedParse(pParse,
  96892. "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
  96893. );
  96894. aRoot[i] = pParse->regRoot;
  96895. aCreateTbl[i] = OPFLAG_P2ISREG;
  96896. }
  96897. }else{
  96898. /* The table already exists. If zWhere is not NULL, delete all entries
  96899. ** associated with the table zWhere. If zWhere is NULL, delete the
  96900. ** entire contents of the table. */
  96901. aRoot[i] = pStat->tnum;
  96902. aCreateTbl[i] = 0;
  96903. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  96904. if( zWhere ){
  96905. sqlite3NestedParse(pParse,
  96906. "DELETE FROM %Q.%s WHERE %s=%Q",
  96907. pDb->zDbSName, zTab, zWhereType, zWhere
  96908. );
  96909. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  96910. }else if( db->xPreUpdateCallback ){
  96911. sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
  96912. #endif
  96913. }else{
  96914. /* The sqlite_stat[134] table already exists. Delete all rows. */
  96915. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  96916. }
  96917. }
  96918. }
  96919. /* Open the sqlite_stat[134] tables for writing. */
  96920. for(i=0; aTable[i].zCols; i++){
  96921. assert( i<ArraySize(aTable) );
  96922. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  96923. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  96924. VdbeComment((v, aTable[i].zName));
  96925. }
  96926. }
  96927. /*
  96928. ** Recommended number of samples for sqlite_stat4
  96929. */
  96930. #ifndef SQLITE_STAT4_SAMPLES
  96931. # define SQLITE_STAT4_SAMPLES 24
  96932. #endif
  96933. /*
  96934. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  96935. ** share an instance of the following structure to hold their state
  96936. ** information.
  96937. */
  96938. typedef struct Stat4Accum Stat4Accum;
  96939. typedef struct Stat4Sample Stat4Sample;
  96940. struct Stat4Sample {
  96941. tRowcnt *anEq; /* sqlite_stat4.nEq */
  96942. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  96943. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  96944. tRowcnt *anLt; /* sqlite_stat4.nLt */
  96945. union {
  96946. i64 iRowid; /* Rowid in main table of the key */
  96947. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  96948. } u;
  96949. u32 nRowid; /* Sizeof aRowid[] */
  96950. u8 isPSample; /* True if a periodic sample */
  96951. int iCol; /* If !isPSample, the reason for inclusion */
  96952. u32 iHash; /* Tiebreaker hash */
  96953. #endif
  96954. };
  96955. struct Stat4Accum {
  96956. tRowcnt nRow; /* Number of rows in the entire table */
  96957. tRowcnt nPSample; /* How often to do a periodic sample */
  96958. int nCol; /* Number of columns in index + pk/rowid */
  96959. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  96960. int mxSample; /* Maximum number of samples to accumulate */
  96961. Stat4Sample current; /* Current row as a Stat4Sample */
  96962. u32 iPrn; /* Pseudo-random number used for sampling */
  96963. Stat4Sample *aBest; /* Array of nCol best samples */
  96964. int iMin; /* Index in a[] of entry with minimum score */
  96965. int nSample; /* Current number of samples */
  96966. int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
  96967. int iGet; /* Index of current sample accessed by stat_get() */
  96968. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  96969. sqlite3 *db; /* Database connection, for malloc() */
  96970. };
  96971. /* Reclaim memory used by a Stat4Sample
  96972. */
  96973. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  96974. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  96975. assert( db!=0 );
  96976. if( p->nRowid ){
  96977. sqlite3DbFree(db, p->u.aRowid);
  96978. p->nRowid = 0;
  96979. }
  96980. }
  96981. #endif
  96982. /* Initialize the BLOB value of a ROWID
  96983. */
  96984. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  96985. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  96986. assert( db!=0 );
  96987. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  96988. p->u.aRowid = sqlite3DbMallocRawNN(db, n);
  96989. if( p->u.aRowid ){
  96990. p->nRowid = n;
  96991. memcpy(p->u.aRowid, pData, n);
  96992. }else{
  96993. p->nRowid = 0;
  96994. }
  96995. }
  96996. #endif
  96997. /* Initialize the INTEGER value of a ROWID.
  96998. */
  96999. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97000. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  97001. assert( db!=0 );
  97002. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  97003. p->nRowid = 0;
  97004. p->u.iRowid = iRowid;
  97005. }
  97006. #endif
  97007. /*
  97008. ** Copy the contents of object (*pFrom) into (*pTo).
  97009. */
  97010. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97011. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  97012. pTo->isPSample = pFrom->isPSample;
  97013. pTo->iCol = pFrom->iCol;
  97014. pTo->iHash = pFrom->iHash;
  97015. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  97016. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  97017. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  97018. if( pFrom->nRowid ){
  97019. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  97020. }else{
  97021. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  97022. }
  97023. }
  97024. #endif
  97025. /*
  97026. ** Reclaim all memory of a Stat4Accum structure.
  97027. */
  97028. static void stat4Destructor(void *pOld){
  97029. Stat4Accum *p = (Stat4Accum*)pOld;
  97030. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97031. int i;
  97032. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  97033. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  97034. sampleClear(p->db, &p->current);
  97035. #endif
  97036. sqlite3DbFree(p->db, p);
  97037. }
  97038. /*
  97039. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  97040. ** are:
  97041. ** N: The number of columns in the index including the rowid/pk (note 1)
  97042. ** K: The number of columns in the index excluding the rowid/pk.
  97043. ** C: The number of rows in the index (note 2)
  97044. **
  97045. ** Note 1: In the special case of the covering index that implements a
  97046. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  97047. ** total number of columns in the table.
  97048. **
  97049. ** Note 2: C is only used for STAT3 and STAT4.
  97050. **
  97051. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  97052. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  97053. ** PRIMARY KEY of the table. The covering index that implements the
  97054. ** original WITHOUT ROWID table as N==K as a special case.
  97055. **
  97056. ** This routine allocates the Stat4Accum object in heap memory. The return
  97057. ** value is a pointer to the Stat4Accum object. The datatype of the
  97058. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  97059. ** object.
  97060. */
  97061. static void statInit(
  97062. sqlite3_context *context,
  97063. int argc,
  97064. sqlite3_value **argv
  97065. ){
  97066. Stat4Accum *p;
  97067. int nCol; /* Number of columns in index being sampled */
  97068. int nKeyCol; /* Number of key columns */
  97069. int nColUp; /* nCol rounded up for alignment */
  97070. int n; /* Bytes of space to allocate */
  97071. sqlite3 *db; /* Database connection */
  97072. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97073. int mxSample = SQLITE_STAT4_SAMPLES;
  97074. #endif
  97075. /* Decode the three function arguments */
  97076. UNUSED_PARAMETER(argc);
  97077. nCol = sqlite3_value_int(argv[0]);
  97078. assert( nCol>0 );
  97079. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  97080. nKeyCol = sqlite3_value_int(argv[1]);
  97081. assert( nKeyCol<=nCol );
  97082. assert( nKeyCol>0 );
  97083. /* Allocate the space required for the Stat4Accum object */
  97084. n = sizeof(*p)
  97085. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  97086. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  97087. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97088. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  97089. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  97090. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  97091. #endif
  97092. ;
  97093. db = sqlite3_context_db_handle(context);
  97094. p = sqlite3DbMallocZero(db, n);
  97095. if( p==0 ){
  97096. sqlite3_result_error_nomem(context);
  97097. return;
  97098. }
  97099. p->db = db;
  97100. p->nRow = 0;
  97101. p->nCol = nCol;
  97102. p->nKeyCol = nKeyCol;
  97103. p->current.anDLt = (tRowcnt*)&p[1];
  97104. p->current.anEq = &p->current.anDLt[nColUp];
  97105. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97106. {
  97107. u8 *pSpace; /* Allocated space not yet assigned */
  97108. int i; /* Used to iterate through p->aSample[] */
  97109. p->iGet = -1;
  97110. p->mxSample = mxSample;
  97111. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  97112. p->current.anLt = &p->current.anEq[nColUp];
  97113. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  97114. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  97115. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  97116. p->aBest = &p->a[mxSample];
  97117. pSpace = (u8*)(&p->a[mxSample+nCol]);
  97118. for(i=0; i<(mxSample+nCol); i++){
  97119. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  97120. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  97121. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  97122. }
  97123. assert( (pSpace - (u8*)p)==n );
  97124. for(i=0; i<nCol; i++){
  97125. p->aBest[i].iCol = i;
  97126. }
  97127. }
  97128. #endif
  97129. /* Return a pointer to the allocated object to the caller. Note that
  97130. ** only the pointer (the 2nd parameter) matters. The size of the object
  97131. ** (given by the 3rd parameter) is never used and can be any positive
  97132. ** value. */
  97133. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  97134. }
  97135. static const FuncDef statInitFuncdef = {
  97136. 2+IsStat34, /* nArg */
  97137. SQLITE_UTF8, /* funcFlags */
  97138. 0, /* pUserData */
  97139. 0, /* pNext */
  97140. statInit, /* xSFunc */
  97141. 0, /* xFinalize */
  97142. 0, 0, /* xValue, xInverse */
  97143. "stat_init", /* zName */
  97144. {0}
  97145. };
  97146. #ifdef SQLITE_ENABLE_STAT4
  97147. /*
  97148. ** pNew and pOld are both candidate non-periodic samples selected for
  97149. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  97150. ** considering only any trailing columns and the sample hash value, this
  97151. ** function returns true if sample pNew is to be preferred over pOld.
  97152. ** In other words, if we assume that the cardinalities of the selected
  97153. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  97154. **
  97155. ** This function assumes that for each argument sample, the contents of
  97156. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  97157. */
  97158. static int sampleIsBetterPost(
  97159. Stat4Accum *pAccum,
  97160. Stat4Sample *pNew,
  97161. Stat4Sample *pOld
  97162. ){
  97163. int nCol = pAccum->nCol;
  97164. int i;
  97165. assert( pNew->iCol==pOld->iCol );
  97166. for(i=pNew->iCol+1; i<nCol; i++){
  97167. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  97168. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  97169. }
  97170. if( pNew->iHash>pOld->iHash ) return 1;
  97171. return 0;
  97172. }
  97173. #endif
  97174. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97175. /*
  97176. ** Return true if pNew is to be preferred over pOld.
  97177. **
  97178. ** This function assumes that for each argument sample, the contents of
  97179. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  97180. */
  97181. static int sampleIsBetter(
  97182. Stat4Accum *pAccum,
  97183. Stat4Sample *pNew,
  97184. Stat4Sample *pOld
  97185. ){
  97186. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  97187. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  97188. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  97189. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  97190. if( (nEqNew>nEqOld) ) return 1;
  97191. #ifdef SQLITE_ENABLE_STAT4
  97192. if( nEqNew==nEqOld ){
  97193. if( pNew->iCol<pOld->iCol ) return 1;
  97194. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  97195. }
  97196. return 0;
  97197. #else
  97198. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  97199. #endif
  97200. }
  97201. /*
  97202. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  97203. ** remove the least desirable sample from p->a[] to make room.
  97204. */
  97205. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  97206. Stat4Sample *pSample = 0;
  97207. int i;
  97208. assert( IsStat4 || nEqZero==0 );
  97209. #ifdef SQLITE_ENABLE_STAT4
  97210. /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
  97211. ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
  97212. ** other words, if nMaxEqZero is n, then it is guaranteed that there
  97213. ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
  97214. if( nEqZero>p->nMaxEqZero ){
  97215. p->nMaxEqZero = nEqZero;
  97216. }
  97217. if( pNew->isPSample==0 ){
  97218. Stat4Sample *pUpgrade = 0;
  97219. assert( pNew->anEq[pNew->iCol]>0 );
  97220. /* This sample is being added because the prefix that ends in column
  97221. ** iCol occurs many times in the table. However, if we have already
  97222. ** added a sample that shares this prefix, there is no need to add
  97223. ** this one. Instead, upgrade the priority of the highest priority
  97224. ** existing sample that shares this prefix. */
  97225. for(i=p->nSample-1; i>=0; i--){
  97226. Stat4Sample *pOld = &p->a[i];
  97227. if( pOld->anEq[pNew->iCol]==0 ){
  97228. if( pOld->isPSample ) return;
  97229. assert( pOld->iCol>pNew->iCol );
  97230. assert( sampleIsBetter(p, pNew, pOld) );
  97231. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  97232. pUpgrade = pOld;
  97233. }
  97234. }
  97235. }
  97236. if( pUpgrade ){
  97237. pUpgrade->iCol = pNew->iCol;
  97238. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  97239. goto find_new_min;
  97240. }
  97241. }
  97242. #endif
  97243. /* If necessary, remove sample iMin to make room for the new sample. */
  97244. if( p->nSample>=p->mxSample ){
  97245. Stat4Sample *pMin = &p->a[p->iMin];
  97246. tRowcnt *anEq = pMin->anEq;
  97247. tRowcnt *anLt = pMin->anLt;
  97248. tRowcnt *anDLt = pMin->anDLt;
  97249. sampleClear(p->db, pMin);
  97250. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  97251. pSample = &p->a[p->nSample-1];
  97252. pSample->nRowid = 0;
  97253. pSample->anEq = anEq;
  97254. pSample->anDLt = anDLt;
  97255. pSample->anLt = anLt;
  97256. p->nSample = p->mxSample-1;
  97257. }
  97258. /* The "rows less-than" for the rowid column must be greater than that
  97259. ** for the last sample in the p->a[] array. Otherwise, the samples would
  97260. ** be out of order. */
  97261. #ifdef SQLITE_ENABLE_STAT4
  97262. assert( p->nSample==0
  97263. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  97264. #endif
  97265. /* Insert the new sample */
  97266. pSample = &p->a[p->nSample];
  97267. sampleCopy(p, pSample, pNew);
  97268. p->nSample++;
  97269. /* Zero the first nEqZero entries in the anEq[] array. */
  97270. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  97271. #ifdef SQLITE_ENABLE_STAT4
  97272. find_new_min:
  97273. #endif
  97274. if( p->nSample>=p->mxSample ){
  97275. int iMin = -1;
  97276. for(i=0; i<p->mxSample; i++){
  97277. if( p->a[i].isPSample ) continue;
  97278. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  97279. iMin = i;
  97280. }
  97281. }
  97282. assert( iMin>=0 );
  97283. p->iMin = iMin;
  97284. }
  97285. }
  97286. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  97287. /*
  97288. ** Field iChng of the index being scanned has changed. So at this point
  97289. ** p->current contains a sample that reflects the previous row of the
  97290. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  97291. ** correct at this point.
  97292. */
  97293. static void samplePushPrevious(Stat4Accum *p, int iChng){
  97294. #ifdef SQLITE_ENABLE_STAT4
  97295. int i;
  97296. /* Check if any samples from the aBest[] array should be pushed
  97297. ** into IndexSample.a[] at this point. */
  97298. for(i=(p->nCol-2); i>=iChng; i--){
  97299. Stat4Sample *pBest = &p->aBest[i];
  97300. pBest->anEq[i] = p->current.anEq[i];
  97301. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  97302. sampleInsert(p, pBest, i);
  97303. }
  97304. }
  97305. /* Check that no sample contains an anEq[] entry with an index of
  97306. ** p->nMaxEqZero or greater set to zero. */
  97307. for(i=p->nSample-1; i>=0; i--){
  97308. int j;
  97309. for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
  97310. }
  97311. /* Update the anEq[] fields of any samples already collected. */
  97312. if( iChng<p->nMaxEqZero ){
  97313. for(i=p->nSample-1; i>=0; i--){
  97314. int j;
  97315. for(j=iChng; j<p->nCol; j++){
  97316. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  97317. }
  97318. }
  97319. p->nMaxEqZero = iChng;
  97320. }
  97321. #endif
  97322. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  97323. if( iChng==0 ){
  97324. tRowcnt nLt = p->current.anLt[0];
  97325. tRowcnt nEq = p->current.anEq[0];
  97326. /* Check if this is to be a periodic sample. If so, add it. */
  97327. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  97328. p->current.isPSample = 1;
  97329. sampleInsert(p, &p->current, 0);
  97330. p->current.isPSample = 0;
  97331. }else
  97332. /* Or if it is a non-periodic sample. Add it in this case too. */
  97333. if( p->nSample<p->mxSample
  97334. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  97335. ){
  97336. sampleInsert(p, &p->current, 0);
  97337. }
  97338. }
  97339. #endif
  97340. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  97341. UNUSED_PARAMETER( p );
  97342. UNUSED_PARAMETER( iChng );
  97343. #endif
  97344. }
  97345. /*
  97346. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  97347. ** Arguments:
  97348. **
  97349. ** P Pointer to the Stat4Accum object created by stat_init()
  97350. ** C Index of left-most column to differ from previous row
  97351. ** R Rowid for the current row. Might be a key record for
  97352. ** WITHOUT ROWID tables.
  97353. **
  97354. ** This SQL function always returns NULL. It's purpose it to accumulate
  97355. ** statistical data and/or samples in the Stat4Accum object about the
  97356. ** index being analyzed. The stat_get() SQL function will later be used to
  97357. ** extract relevant information for constructing the sqlite_statN tables.
  97358. **
  97359. ** The R parameter is only used for STAT3 and STAT4
  97360. */
  97361. static void statPush(
  97362. sqlite3_context *context,
  97363. int argc,
  97364. sqlite3_value **argv
  97365. ){
  97366. int i;
  97367. /* The three function arguments */
  97368. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  97369. int iChng = sqlite3_value_int(argv[1]);
  97370. UNUSED_PARAMETER( argc );
  97371. UNUSED_PARAMETER( context );
  97372. assert( p->nCol>0 );
  97373. assert( iChng<p->nCol );
  97374. if( p->nRow==0 ){
  97375. /* This is the first call to this function. Do initialization. */
  97376. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  97377. }else{
  97378. /* Second and subsequent calls get processed here */
  97379. samplePushPrevious(p, iChng);
  97380. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  97381. ** to the current row of the index. */
  97382. for(i=0; i<iChng; i++){
  97383. p->current.anEq[i]++;
  97384. }
  97385. for(i=iChng; i<p->nCol; i++){
  97386. p->current.anDLt[i]++;
  97387. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97388. p->current.anLt[i] += p->current.anEq[i];
  97389. #endif
  97390. p->current.anEq[i] = 1;
  97391. }
  97392. }
  97393. p->nRow++;
  97394. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97395. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  97396. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  97397. }else{
  97398. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  97399. sqlite3_value_blob(argv[2]));
  97400. }
  97401. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  97402. #endif
  97403. #ifdef SQLITE_ENABLE_STAT4
  97404. {
  97405. tRowcnt nLt = p->current.anLt[p->nCol-1];
  97406. /* Check if this is to be a periodic sample. If so, add it. */
  97407. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  97408. p->current.isPSample = 1;
  97409. p->current.iCol = 0;
  97410. sampleInsert(p, &p->current, p->nCol-1);
  97411. p->current.isPSample = 0;
  97412. }
  97413. /* Update the aBest[] array. */
  97414. for(i=0; i<(p->nCol-1); i++){
  97415. p->current.iCol = i;
  97416. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  97417. sampleCopy(p, &p->aBest[i], &p->current);
  97418. }
  97419. }
  97420. }
  97421. #endif
  97422. }
  97423. static const FuncDef statPushFuncdef = {
  97424. 2+IsStat34, /* nArg */
  97425. SQLITE_UTF8, /* funcFlags */
  97426. 0, /* pUserData */
  97427. 0, /* pNext */
  97428. statPush, /* xSFunc */
  97429. 0, /* xFinalize */
  97430. 0, 0, /* xValue, xInverse */
  97431. "stat_push", /* zName */
  97432. {0}
  97433. };
  97434. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  97435. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  97436. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  97437. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  97438. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  97439. /*
  97440. ** Implementation of the stat_get(P,J) SQL function. This routine is
  97441. ** used to query statistical information that has been gathered into
  97442. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  97443. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  97444. ** The content to returned is determined by the parameter J
  97445. ** which is one of the STAT_GET_xxxx values defined above.
  97446. **
  97447. ** The stat_get(P,J) function is not available to generic SQL. It is
  97448. ** inserted as part of a manually constructed bytecode program. (See
  97449. ** the callStatGet() routine below.) It is guaranteed that the P
  97450. ** parameter will always be a poiner to a Stat4Accum object, never a
  97451. ** NULL.
  97452. **
  97453. ** If neither STAT3 nor STAT4 are enabled, then J is always
  97454. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  97455. ** a one-parameter function, stat_get(P), that always returns the
  97456. ** stat1 table entry information.
  97457. */
  97458. static void statGet(
  97459. sqlite3_context *context,
  97460. int argc,
  97461. sqlite3_value **argv
  97462. ){
  97463. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  97464. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97465. /* STAT3 and STAT4 have a parameter on this routine. */
  97466. int eCall = sqlite3_value_int(argv[1]);
  97467. assert( argc==2 );
  97468. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  97469. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  97470. || eCall==STAT_GET_NDLT
  97471. );
  97472. if( eCall==STAT_GET_STAT1 )
  97473. #else
  97474. assert( argc==1 );
  97475. #endif
  97476. {
  97477. /* Return the value to store in the "stat" column of the sqlite_stat1
  97478. ** table for this index.
  97479. **
  97480. ** The value is a string composed of a list of integers describing
  97481. ** the index. The first integer in the list is the total number of
  97482. ** entries in the index. There is one additional integer in the list
  97483. ** for each indexed column. This additional integer is an estimate of
  97484. ** the number of rows matched by a stabbing query on the index using
  97485. ** a key with the corresponding number of fields. In other words,
  97486. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  97487. ** "100 10 2", then SQLite estimates that:
  97488. **
  97489. ** * the index contains 100 rows,
  97490. ** * "WHERE a=?" matches 10 rows, and
  97491. ** * "WHERE a=? AND b=?" matches 2 rows.
  97492. **
  97493. ** If D is the count of distinct values and K is the total number of
  97494. ** rows, then each estimate is computed as:
  97495. **
  97496. ** I = (K+D-1)/D
  97497. */
  97498. char *z;
  97499. int i;
  97500. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  97501. if( zRet==0 ){
  97502. sqlite3_result_error_nomem(context);
  97503. return;
  97504. }
  97505. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  97506. z = zRet + sqlite3Strlen30(zRet);
  97507. for(i=0; i<p->nKeyCol; i++){
  97508. u64 nDistinct = p->current.anDLt[i] + 1;
  97509. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  97510. sqlite3_snprintf(24, z, " %llu", iVal);
  97511. z += sqlite3Strlen30(z);
  97512. assert( p->current.anEq[i] );
  97513. }
  97514. assert( z[0]=='\0' && z>zRet );
  97515. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  97516. }
  97517. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97518. else if( eCall==STAT_GET_ROWID ){
  97519. if( p->iGet<0 ){
  97520. samplePushPrevious(p, 0);
  97521. p->iGet = 0;
  97522. }
  97523. if( p->iGet<p->nSample ){
  97524. Stat4Sample *pS = p->a + p->iGet;
  97525. if( pS->nRowid==0 ){
  97526. sqlite3_result_int64(context, pS->u.iRowid);
  97527. }else{
  97528. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  97529. SQLITE_TRANSIENT);
  97530. }
  97531. }
  97532. }else{
  97533. tRowcnt *aCnt = 0;
  97534. assert( p->iGet<p->nSample );
  97535. switch( eCall ){
  97536. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  97537. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  97538. default: {
  97539. aCnt = p->a[p->iGet].anDLt;
  97540. p->iGet++;
  97541. break;
  97542. }
  97543. }
  97544. if( IsStat3 ){
  97545. sqlite3_result_int64(context, (i64)aCnt[0]);
  97546. }else{
  97547. char *zRet = sqlite3MallocZero(p->nCol * 25);
  97548. if( zRet==0 ){
  97549. sqlite3_result_error_nomem(context);
  97550. }else{
  97551. int i;
  97552. char *z = zRet;
  97553. for(i=0; i<p->nCol; i++){
  97554. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  97555. z += sqlite3Strlen30(z);
  97556. }
  97557. assert( z[0]=='\0' && z>zRet );
  97558. z[-1] = '\0';
  97559. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  97560. }
  97561. }
  97562. }
  97563. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  97564. #ifndef SQLITE_DEBUG
  97565. UNUSED_PARAMETER( argc );
  97566. #endif
  97567. }
  97568. static const FuncDef statGetFuncdef = {
  97569. 1+IsStat34, /* nArg */
  97570. SQLITE_UTF8, /* funcFlags */
  97571. 0, /* pUserData */
  97572. 0, /* pNext */
  97573. statGet, /* xSFunc */
  97574. 0, /* xFinalize */
  97575. 0, 0, /* xValue, xInverse */
  97576. "stat_get", /* zName */
  97577. {0}
  97578. };
  97579. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  97580. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  97581. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97582. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  97583. #elif SQLITE_DEBUG
  97584. assert( iParam==STAT_GET_STAT1 );
  97585. #else
  97586. UNUSED_PARAMETER( iParam );
  97587. #endif
  97588. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
  97589. (char*)&statGetFuncdef, P4_FUNCDEF);
  97590. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  97591. }
  97592. /*
  97593. ** Generate code to do an analysis of all indices associated with
  97594. ** a single table.
  97595. */
  97596. static void analyzeOneTable(
  97597. Parse *pParse, /* Parser context */
  97598. Table *pTab, /* Table whose indices are to be analyzed */
  97599. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  97600. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  97601. int iMem, /* Available memory locations begin here */
  97602. int iTab /* Next available cursor */
  97603. ){
  97604. sqlite3 *db = pParse->db; /* Database handle */
  97605. Index *pIdx; /* An index to being analyzed */
  97606. int iIdxCur; /* Cursor open on index being analyzed */
  97607. int iTabCur; /* Table cursor */
  97608. Vdbe *v; /* The virtual machine being built up */
  97609. int i; /* Loop counter */
  97610. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  97611. int iDb; /* Index of database containing pTab */
  97612. u8 needTableCnt = 1; /* True to count the table */
  97613. int regNewRowid = iMem++; /* Rowid for the inserted record */
  97614. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  97615. int regChng = iMem++; /* Index of changed index field */
  97616. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97617. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  97618. #endif
  97619. int regTemp = iMem++; /* Temporary use register */
  97620. int regTabname = iMem++; /* Register containing table name */
  97621. int regIdxname = iMem++; /* Register containing index name */
  97622. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  97623. int regPrev = iMem; /* MUST BE LAST (see below) */
  97624. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  97625. Table *pStat1 = 0;
  97626. #endif
  97627. pParse->nMem = MAX(pParse->nMem, iMem);
  97628. v = sqlite3GetVdbe(pParse);
  97629. if( v==0 || NEVER(pTab==0) ){
  97630. return;
  97631. }
  97632. if( pTab->tnum==0 ){
  97633. /* Do not gather statistics on views or virtual tables */
  97634. return;
  97635. }
  97636. if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
  97637. /* Do not gather statistics on system tables */
  97638. return;
  97639. }
  97640. assert( sqlite3BtreeHoldsAllMutexes(db) );
  97641. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  97642. assert( iDb>=0 );
  97643. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97644. #ifndef SQLITE_OMIT_AUTHORIZATION
  97645. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  97646. db->aDb[iDb].zDbSName ) ){
  97647. return;
  97648. }
  97649. #endif
  97650. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  97651. if( db->xPreUpdateCallback ){
  97652. pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
  97653. if( pStat1==0 ) return;
  97654. pStat1->zName = (char*)&pStat1[1];
  97655. memcpy(pStat1->zName, "sqlite_stat1", 13);
  97656. pStat1->nCol = 3;
  97657. pStat1->iPKey = -1;
  97658. sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);
  97659. }
  97660. #endif
  97661. /* Establish a read-lock on the table at the shared-cache level.
  97662. ** Open a read-only cursor on the table. Also allocate a cursor number
  97663. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  97664. ** this time though. */
  97665. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  97666. iTabCur = iTab++;
  97667. iIdxCur = iTab++;
  97668. pParse->nTab = MAX(pParse->nTab, iTab);
  97669. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  97670. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  97671. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  97672. int nCol; /* Number of columns in pIdx. "N" */
  97673. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  97674. int addrNextRow; /* Address of "next_row:" */
  97675. const char *zIdxName; /* Name of the index */
  97676. int nColTest; /* Number of columns to test for changes */
  97677. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  97678. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  97679. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  97680. nCol = pIdx->nKeyCol;
  97681. zIdxName = pTab->zName;
  97682. nColTest = nCol - 1;
  97683. }else{
  97684. nCol = pIdx->nColumn;
  97685. zIdxName = pIdx->zName;
  97686. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  97687. }
  97688. /* Populate the register containing the index name. */
  97689. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  97690. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  97691. /*
  97692. ** Pseudo-code for loop that calls stat_push():
  97693. **
  97694. ** Rewind csr
  97695. ** if eof(csr) goto end_of_scan;
  97696. ** regChng = 0
  97697. ** goto chng_addr_0;
  97698. **
  97699. ** next_row:
  97700. ** regChng = 0
  97701. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  97702. ** regChng = 1
  97703. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  97704. ** ...
  97705. ** regChng = N
  97706. ** goto chng_addr_N
  97707. **
  97708. ** chng_addr_0:
  97709. ** regPrev(0) = idx(0)
  97710. ** chng_addr_1:
  97711. ** regPrev(1) = idx(1)
  97712. ** ...
  97713. **
  97714. ** endDistinctTest:
  97715. ** regRowid = idx(rowid)
  97716. ** stat_push(P, regChng, regRowid)
  97717. ** Next csr
  97718. ** if !eof(csr) goto next_row;
  97719. **
  97720. ** end_of_scan:
  97721. */
  97722. /* Make sure there are enough memory cells allocated to accommodate
  97723. ** the regPrev array and a trailing rowid (the rowid slot is required
  97724. ** when building a record to insert into the sample column of
  97725. ** the sqlite_stat4 table. */
  97726. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  97727. /* Open a read-only cursor on the index being analyzed. */
  97728. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  97729. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  97730. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  97731. VdbeComment((v, "%s", pIdx->zName));
  97732. /* Invoke the stat_init() function. The arguments are:
  97733. **
  97734. ** (1) the number of columns in the index including the rowid
  97735. ** (or for a WITHOUT ROWID table, the number of PK columns),
  97736. ** (2) the number of columns in the key without the rowid/pk
  97737. ** (3) the number of rows in the index,
  97738. **
  97739. **
  97740. ** The third argument is only used for STAT3 and STAT4
  97741. */
  97742. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97743. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  97744. #endif
  97745. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  97746. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  97747. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
  97748. (char*)&statInitFuncdef, P4_FUNCDEF);
  97749. sqlite3VdbeChangeP5(v, 2+IsStat34);
  97750. /* Implementation of the following:
  97751. **
  97752. ** Rewind csr
  97753. ** if eof(csr) goto end_of_scan;
  97754. ** regChng = 0
  97755. ** goto next_push_0;
  97756. **
  97757. */
  97758. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  97759. VdbeCoverage(v);
  97760. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  97761. addrNextRow = sqlite3VdbeCurrentAddr(v);
  97762. if( nColTest>0 ){
  97763. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  97764. int *aGotoChng; /* Array of jump instruction addresses */
  97765. aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
  97766. if( aGotoChng==0 ) continue;
  97767. /*
  97768. ** next_row:
  97769. ** regChng = 0
  97770. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  97771. ** regChng = 1
  97772. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  97773. ** ...
  97774. ** regChng = N
  97775. ** goto endDistinctTest
  97776. */
  97777. sqlite3VdbeAddOp0(v, OP_Goto);
  97778. addrNextRow = sqlite3VdbeCurrentAddr(v);
  97779. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  97780. /* For a single-column UNIQUE index, once we have found a non-NULL
  97781. ** row, we know that all the rest will be distinct, so skip
  97782. ** subsequent distinctness tests. */
  97783. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  97784. VdbeCoverage(v);
  97785. }
  97786. for(i=0; i<nColTest; i++){
  97787. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  97788. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  97789. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  97790. aGotoChng[i] =
  97791. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  97792. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  97793. VdbeCoverage(v);
  97794. }
  97795. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  97796. sqlite3VdbeGoto(v, endDistinctTest);
  97797. /*
  97798. ** chng_addr_0:
  97799. ** regPrev(0) = idx(0)
  97800. ** chng_addr_1:
  97801. ** regPrev(1) = idx(1)
  97802. ** ...
  97803. */
  97804. sqlite3VdbeJumpHere(v, addrNextRow-1);
  97805. for(i=0; i<nColTest; i++){
  97806. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  97807. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  97808. }
  97809. sqlite3VdbeResolveLabel(v, endDistinctTest);
  97810. sqlite3DbFree(db, aGotoChng);
  97811. }
  97812. /*
  97813. ** chng_addr_N:
  97814. ** regRowid = idx(rowid) // STAT34 only
  97815. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  97816. ** Next csr
  97817. ** if !eof(csr) goto next_row;
  97818. */
  97819. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97820. assert( regRowid==(regStat4+2) );
  97821. if( HasRowid(pTab) ){
  97822. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  97823. }else{
  97824. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  97825. int j, k, regKey;
  97826. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  97827. for(j=0; j<pPk->nKeyCol; j++){
  97828. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  97829. assert( k>=0 && k<pIdx->nColumn );
  97830. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  97831. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  97832. }
  97833. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  97834. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  97835. }
  97836. #endif
  97837. assert( regChng==(regStat4+1) );
  97838. sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
  97839. (char*)&statPushFuncdef, P4_FUNCDEF);
  97840. sqlite3VdbeChangeP5(v, 2+IsStat34);
  97841. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  97842. /* Add the entry to the stat1 table. */
  97843. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  97844. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  97845. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  97846. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  97847. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  97848. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  97849. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  97850. #endif
  97851. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  97852. /* Add the entries to the stat3 or stat4 table. */
  97853. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97854. {
  97855. int regEq = regStat1;
  97856. int regLt = regStat1+1;
  97857. int regDLt = regStat1+2;
  97858. int regSample = regStat1+3;
  97859. int regCol = regStat1+4;
  97860. int regSampleRowid = regCol + nCol;
  97861. int addrNext;
  97862. int addrIsNull;
  97863. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  97864. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  97865. addrNext = sqlite3VdbeCurrentAddr(v);
  97866. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  97867. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  97868. VdbeCoverage(v);
  97869. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  97870. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  97871. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  97872. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  97873. VdbeCoverage(v);
  97874. #ifdef SQLITE_ENABLE_STAT3
  97875. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
  97876. #else
  97877. for(i=0; i<nCol; i++){
  97878. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  97879. }
  97880. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  97881. #endif
  97882. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  97883. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  97884. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  97885. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  97886. sqlite3VdbeJumpHere(v, addrIsNull);
  97887. }
  97888. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  97889. /* End of analysis */
  97890. sqlite3VdbeJumpHere(v, addrRewind);
  97891. }
  97892. /* Create a single sqlite_stat1 entry containing NULL as the index
  97893. ** name and the row count as the content.
  97894. */
  97895. if( pOnlyIdx==0 && needTableCnt ){
  97896. VdbeComment((v, "%s", pTab->zName));
  97897. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  97898. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  97899. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  97900. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  97901. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  97902. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  97903. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  97904. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  97905. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  97906. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  97907. #endif
  97908. sqlite3VdbeJumpHere(v, jZeroRows);
  97909. }
  97910. }
  97911. /*
  97912. ** Generate code that will cause the most recent index analysis to
  97913. ** be loaded into internal hash tables where is can be used.
  97914. */
  97915. static void loadAnalysis(Parse *pParse, int iDb){
  97916. Vdbe *v = sqlite3GetVdbe(pParse);
  97917. if( v ){
  97918. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  97919. }
  97920. }
  97921. /*
  97922. ** Generate code that will do an analysis of an entire database
  97923. */
  97924. static void analyzeDatabase(Parse *pParse, int iDb){
  97925. sqlite3 *db = pParse->db;
  97926. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  97927. HashElem *k;
  97928. int iStatCur;
  97929. int iMem;
  97930. int iTab;
  97931. sqlite3BeginWriteOperation(pParse, 0, iDb);
  97932. iStatCur = pParse->nTab;
  97933. pParse->nTab += 3;
  97934. openStatTable(pParse, iDb, iStatCur, 0, 0);
  97935. iMem = pParse->nMem+1;
  97936. iTab = pParse->nTab;
  97937. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97938. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  97939. Table *pTab = (Table*)sqliteHashData(k);
  97940. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  97941. }
  97942. loadAnalysis(pParse, iDb);
  97943. }
  97944. /*
  97945. ** Generate code that will do an analysis of a single table in
  97946. ** a database. If pOnlyIdx is not NULL then it is a single index
  97947. ** in pTab that should be analyzed.
  97948. */
  97949. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  97950. int iDb;
  97951. int iStatCur;
  97952. assert( pTab!=0 );
  97953. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  97954. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  97955. sqlite3BeginWriteOperation(pParse, 0, iDb);
  97956. iStatCur = pParse->nTab;
  97957. pParse->nTab += 3;
  97958. if( pOnlyIdx ){
  97959. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  97960. }else{
  97961. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  97962. }
  97963. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  97964. loadAnalysis(pParse, iDb);
  97965. }
  97966. /*
  97967. ** Generate code for the ANALYZE command. The parser calls this routine
  97968. ** when it recognizes an ANALYZE command.
  97969. **
  97970. ** ANALYZE -- 1
  97971. ** ANALYZE <database> -- 2
  97972. ** ANALYZE ?<database>.?<tablename> -- 3
  97973. **
  97974. ** Form 1 causes all indices in all attached databases to be analyzed.
  97975. ** Form 2 analyzes all indices the single database named.
  97976. ** Form 3 analyzes all indices associated with the named table.
  97977. */
  97978. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  97979. sqlite3 *db = pParse->db;
  97980. int iDb;
  97981. int i;
  97982. char *z, *zDb;
  97983. Table *pTab;
  97984. Index *pIdx;
  97985. Token *pTableName;
  97986. Vdbe *v;
  97987. /* Read the database schema. If an error occurs, leave an error message
  97988. ** and code in pParse and return NULL. */
  97989. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  97990. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  97991. return;
  97992. }
  97993. assert( pName2!=0 || pName1==0 );
  97994. if( pName1==0 ){
  97995. /* Form 1: Analyze everything */
  97996. for(i=0; i<db->nDb; i++){
  97997. if( i==1 ) continue; /* Do not analyze the TEMP database */
  97998. analyzeDatabase(pParse, i);
  97999. }
  98000. }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
  98001. /* Analyze the schema named as the argument */
  98002. analyzeDatabase(pParse, iDb);
  98003. }else{
  98004. /* Form 3: Analyze the table or index named as an argument */
  98005. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  98006. if( iDb>=0 ){
  98007. zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
  98008. z = sqlite3NameFromToken(db, pTableName);
  98009. if( z ){
  98010. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  98011. analyzeTable(pParse, pIdx->pTable, pIdx);
  98012. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  98013. analyzeTable(pParse, pTab, 0);
  98014. }
  98015. sqlite3DbFree(db, z);
  98016. }
  98017. }
  98018. }
  98019. if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
  98020. sqlite3VdbeAddOp0(v, OP_Expire);
  98021. }
  98022. }
  98023. /*
  98024. ** Used to pass information from the analyzer reader through to the
  98025. ** callback routine.
  98026. */
  98027. typedef struct analysisInfo analysisInfo;
  98028. struct analysisInfo {
  98029. sqlite3 *db;
  98030. const char *zDatabase;
  98031. };
  98032. /*
  98033. ** The first argument points to a nul-terminated string containing a
  98034. ** list of space separated integers. Read the first nOut of these into
  98035. ** the array aOut[].
  98036. */
  98037. static void decodeIntArray(
  98038. char *zIntArray, /* String containing int array to decode */
  98039. int nOut, /* Number of slots in aOut[] */
  98040. tRowcnt *aOut, /* Store integers here */
  98041. LogEst *aLog, /* Or, if aOut==0, here */
  98042. Index *pIndex /* Handle extra flags for this index, if not NULL */
  98043. ){
  98044. char *z = zIntArray;
  98045. int c;
  98046. int i;
  98047. tRowcnt v;
  98048. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98049. if( z==0 ) z = "";
  98050. #else
  98051. assert( z!=0 );
  98052. #endif
  98053. for(i=0; *z && i<nOut; i++){
  98054. v = 0;
  98055. while( (c=z[0])>='0' && c<='9' ){
  98056. v = v*10 + c - '0';
  98057. z++;
  98058. }
  98059. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98060. if( aOut ) aOut[i] = v;
  98061. if( aLog ) aLog[i] = sqlite3LogEst(v);
  98062. #else
  98063. assert( aOut==0 );
  98064. UNUSED_PARAMETER(aOut);
  98065. assert( aLog!=0 );
  98066. aLog[i] = sqlite3LogEst(v);
  98067. #endif
  98068. if( *z==' ' ) z++;
  98069. }
  98070. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  98071. assert( pIndex!=0 ); {
  98072. #else
  98073. if( pIndex ){
  98074. #endif
  98075. pIndex->bUnordered = 0;
  98076. pIndex->noSkipScan = 0;
  98077. while( z[0] ){
  98078. if( sqlite3_strglob("unordered*", z)==0 ){
  98079. pIndex->bUnordered = 1;
  98080. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  98081. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  98082. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  98083. pIndex->noSkipScan = 1;
  98084. }
  98085. #ifdef SQLITE_ENABLE_COSTMULT
  98086. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  98087. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  98088. }
  98089. #endif
  98090. while( z[0]!=0 && z[0]!=' ' ) z++;
  98091. while( z[0]==' ' ) z++;
  98092. }
  98093. }
  98094. }
  98095. /*
  98096. ** This callback is invoked once for each index when reading the
  98097. ** sqlite_stat1 table.
  98098. **
  98099. ** argv[0] = name of the table
  98100. ** argv[1] = name of the index (might be NULL)
  98101. ** argv[2] = results of analysis - on integer for each column
  98102. **
  98103. ** Entries for which argv[1]==NULL simply record the number of rows in
  98104. ** the table.
  98105. */
  98106. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  98107. analysisInfo *pInfo = (analysisInfo*)pData;
  98108. Index *pIndex;
  98109. Table *pTable;
  98110. const char *z;
  98111. assert( argc==3 );
  98112. UNUSED_PARAMETER2(NotUsed, argc);
  98113. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  98114. return 0;
  98115. }
  98116. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  98117. if( pTable==0 ){
  98118. return 0;
  98119. }
  98120. if( argv[1]==0 ){
  98121. pIndex = 0;
  98122. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  98123. pIndex = sqlite3PrimaryKeyIndex(pTable);
  98124. }else{
  98125. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  98126. }
  98127. z = argv[2];
  98128. if( pIndex ){
  98129. tRowcnt *aiRowEst = 0;
  98130. int nCol = pIndex->nKeyCol+1;
  98131. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98132. /* Index.aiRowEst may already be set here if there are duplicate
  98133. ** sqlite_stat1 entries for this index. In that case just clobber
  98134. ** the old data with the new instead of allocating a new array. */
  98135. if( pIndex->aiRowEst==0 ){
  98136. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  98137. if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
  98138. }
  98139. aiRowEst = pIndex->aiRowEst;
  98140. #endif
  98141. pIndex->bUnordered = 0;
  98142. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  98143. pIndex->hasStat1 = 1;
  98144. if( pIndex->pPartIdxWhere==0 ){
  98145. pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  98146. pTable->tabFlags |= TF_HasStat1;
  98147. }
  98148. }else{
  98149. Index fakeIdx;
  98150. fakeIdx.szIdxRow = pTable->szTabRow;
  98151. #ifdef SQLITE_ENABLE_COSTMULT
  98152. fakeIdx.pTable = pTable;
  98153. #endif
  98154. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  98155. pTable->szTabRow = fakeIdx.szIdxRow;
  98156. pTable->tabFlags |= TF_HasStat1;
  98157. }
  98158. return 0;
  98159. }
  98160. /*
  98161. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  98162. ** and its contents.
  98163. */
  98164. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  98165. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98166. if( pIdx->aSample ){
  98167. int j;
  98168. for(j=0; j<pIdx->nSample; j++){
  98169. IndexSample *p = &pIdx->aSample[j];
  98170. sqlite3DbFree(db, p->p);
  98171. }
  98172. sqlite3DbFree(db, pIdx->aSample);
  98173. }
  98174. if( db && db->pnBytesFreed==0 ){
  98175. pIdx->nSample = 0;
  98176. pIdx->aSample = 0;
  98177. }
  98178. #else
  98179. UNUSED_PARAMETER(db);
  98180. UNUSED_PARAMETER(pIdx);
  98181. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  98182. }
  98183. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98184. /*
  98185. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  98186. ** stored in pIdx->aSample[].
  98187. */
  98188. static void initAvgEq(Index *pIdx){
  98189. if( pIdx ){
  98190. IndexSample *aSample = pIdx->aSample;
  98191. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  98192. int iCol;
  98193. int nCol = 1;
  98194. if( pIdx->nSampleCol>1 ){
  98195. /* If this is stat4 data, then calculate aAvgEq[] values for all
  98196. ** sample columns except the last. The last is always set to 1, as
  98197. ** once the trailing PK fields are considered all index keys are
  98198. ** unique. */
  98199. nCol = pIdx->nSampleCol-1;
  98200. pIdx->aAvgEq[nCol] = 1;
  98201. }
  98202. for(iCol=0; iCol<nCol; iCol++){
  98203. int nSample = pIdx->nSample;
  98204. int i; /* Used to iterate through samples */
  98205. tRowcnt sumEq = 0; /* Sum of the nEq values */
  98206. tRowcnt avgEq = 0;
  98207. tRowcnt nRow; /* Number of rows in index */
  98208. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  98209. i64 nDist100; /* Number of distinct values in index */
  98210. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  98211. nRow = pFinal->anLt[iCol];
  98212. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  98213. nSample--;
  98214. }else{
  98215. nRow = pIdx->aiRowEst[0];
  98216. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  98217. }
  98218. pIdx->nRowEst0 = nRow;
  98219. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  98220. ** occur in the stat4 table for this index. Set sumEq to the sum of
  98221. ** the nEq values for column iCol for the same set (adding the value
  98222. ** only once where there exist duplicate prefixes). */
  98223. for(i=0; i<nSample; i++){
  98224. if( i==(pIdx->nSample-1)
  98225. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  98226. ){
  98227. sumEq += aSample[i].anEq[iCol];
  98228. nSum100 += 100;
  98229. }
  98230. }
  98231. if( nDist100>nSum100 && sumEq<nRow ){
  98232. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  98233. }
  98234. if( avgEq==0 ) avgEq = 1;
  98235. pIdx->aAvgEq[iCol] = avgEq;
  98236. }
  98237. }
  98238. }
  98239. /*
  98240. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  98241. ** is supplied instead, find the PRIMARY KEY index for that table.
  98242. */
  98243. static Index *findIndexOrPrimaryKey(
  98244. sqlite3 *db,
  98245. const char *zName,
  98246. const char *zDb
  98247. ){
  98248. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  98249. if( pIdx==0 ){
  98250. Table *pTab = sqlite3FindTable(db, zName, zDb);
  98251. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  98252. }
  98253. return pIdx;
  98254. }
  98255. /*
  98256. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  98257. ** into the relevant Index.aSample[] arrays.
  98258. **
  98259. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  98260. ** data equivalent to the following (statements are different for stat3,
  98261. ** see the caller of this function for details):
  98262. **
  98263. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  98264. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  98265. **
  98266. ** where %Q is replaced with the database name before the SQL is executed.
  98267. */
  98268. static int loadStatTbl(
  98269. sqlite3 *db, /* Database handle */
  98270. int bStat3, /* Assume single column records only */
  98271. const char *zSql1, /* SQL statement 1 (see above) */
  98272. const char *zSql2, /* SQL statement 2 (see above) */
  98273. const char *zDb /* Database name (e.g. "main") */
  98274. ){
  98275. int rc; /* Result codes from subroutines */
  98276. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  98277. char *zSql; /* Text of the SQL statement */
  98278. Index *pPrevIdx = 0; /* Previous index in the loop */
  98279. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  98280. assert( db->lookaside.bDisable );
  98281. zSql = sqlite3MPrintf(db, zSql1, zDb);
  98282. if( !zSql ){
  98283. return SQLITE_NOMEM_BKPT;
  98284. }
  98285. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  98286. sqlite3DbFree(db, zSql);
  98287. if( rc ) return rc;
  98288. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  98289. int nIdxCol = 1; /* Number of columns in stat4 records */
  98290. char *zIndex; /* Index name */
  98291. Index *pIdx; /* Pointer to the index object */
  98292. int nSample; /* Number of samples */
  98293. int nByte; /* Bytes of space required */
  98294. int i; /* Bytes of space required */
  98295. tRowcnt *pSpace;
  98296. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  98297. if( zIndex==0 ) continue;
  98298. nSample = sqlite3_column_int(pStmt, 1);
  98299. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  98300. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  98301. /* Index.nSample is non-zero at this point if data has already been
  98302. ** loaded from the stat4 table. In this case ignore stat3 data. */
  98303. if( pIdx==0 || pIdx->nSample ) continue;
  98304. if( bStat3==0 ){
  98305. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  98306. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  98307. nIdxCol = pIdx->nKeyCol;
  98308. }else{
  98309. nIdxCol = pIdx->nColumn;
  98310. }
  98311. }
  98312. pIdx->nSampleCol = nIdxCol;
  98313. nByte = sizeof(IndexSample) * nSample;
  98314. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  98315. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  98316. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  98317. if( pIdx->aSample==0 ){
  98318. sqlite3_finalize(pStmt);
  98319. return SQLITE_NOMEM_BKPT;
  98320. }
  98321. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  98322. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  98323. for(i=0; i<nSample; i++){
  98324. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  98325. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  98326. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  98327. }
  98328. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  98329. }
  98330. rc = sqlite3_finalize(pStmt);
  98331. if( rc ) return rc;
  98332. zSql = sqlite3MPrintf(db, zSql2, zDb);
  98333. if( !zSql ){
  98334. return SQLITE_NOMEM_BKPT;
  98335. }
  98336. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  98337. sqlite3DbFree(db, zSql);
  98338. if( rc ) return rc;
  98339. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  98340. char *zIndex; /* Index name */
  98341. Index *pIdx; /* Pointer to the index object */
  98342. int nCol = 1; /* Number of columns in index */
  98343. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  98344. if( zIndex==0 ) continue;
  98345. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  98346. if( pIdx==0 ) continue;
  98347. /* This next condition is true if data has already been loaded from
  98348. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  98349. nCol = pIdx->nSampleCol;
  98350. if( bStat3 && nCol>1 ) continue;
  98351. if( pIdx!=pPrevIdx ){
  98352. initAvgEq(pPrevIdx);
  98353. pPrevIdx = pIdx;
  98354. }
  98355. pSample = &pIdx->aSample[pIdx->nSample];
  98356. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  98357. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  98358. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  98359. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  98360. ** This is in case the sample record is corrupted. In that case, the
  98361. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  98362. ** end of the allocated buffer before it realizes it is dealing with
  98363. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  98364. ** a buffer overread. */
  98365. pSample->n = sqlite3_column_bytes(pStmt, 4);
  98366. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  98367. if( pSample->p==0 ){
  98368. sqlite3_finalize(pStmt);
  98369. return SQLITE_NOMEM_BKPT;
  98370. }
  98371. if( pSample->n ){
  98372. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  98373. }
  98374. pIdx->nSample++;
  98375. }
  98376. rc = sqlite3_finalize(pStmt);
  98377. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  98378. return rc;
  98379. }
  98380. /*
  98381. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  98382. ** the Index.aSample[] arrays of all indices.
  98383. */
  98384. static int loadStat4(sqlite3 *db, const char *zDb){
  98385. int rc = SQLITE_OK; /* Result codes from subroutines */
  98386. assert( db->lookaside.bDisable );
  98387. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  98388. rc = loadStatTbl(db, 0,
  98389. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  98390. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  98391. zDb
  98392. );
  98393. }
  98394. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  98395. rc = loadStatTbl(db, 1,
  98396. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  98397. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  98398. zDb
  98399. );
  98400. }
  98401. return rc;
  98402. }
  98403. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  98404. /*
  98405. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  98406. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  98407. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  98408. ** Index.aSample[] arrays.
  98409. **
  98410. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  98411. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  98412. ** during compilation and the sqlite_stat3/4 table is present, no data is
  98413. ** read from it.
  98414. **
  98415. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  98416. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  98417. ** returned. However, in this case, data is read from the sqlite_stat1
  98418. ** table (if it is present) before returning.
  98419. **
  98420. ** If an OOM error occurs, this function always sets db->mallocFailed.
  98421. ** This means if the caller does not care about other errors, the return
  98422. ** code may be ignored.
  98423. */
  98424. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  98425. analysisInfo sInfo;
  98426. HashElem *i;
  98427. char *zSql;
  98428. int rc = SQLITE_OK;
  98429. Schema *pSchema = db->aDb[iDb].pSchema;
  98430. assert( iDb>=0 && iDb<db->nDb );
  98431. assert( db->aDb[iDb].pBt!=0 );
  98432. /* Clear any prior statistics */
  98433. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98434. for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
  98435. Table *pTab = sqliteHashData(i);
  98436. pTab->tabFlags &= ~TF_HasStat1;
  98437. }
  98438. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  98439. Index *pIdx = sqliteHashData(i);
  98440. pIdx->hasStat1 = 0;
  98441. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98442. sqlite3DeleteIndexSamples(db, pIdx);
  98443. pIdx->aSample = 0;
  98444. #endif
  98445. }
  98446. /* Load new statistics out of the sqlite_stat1 table */
  98447. sInfo.db = db;
  98448. sInfo.zDatabase = db->aDb[iDb].zDbSName;
  98449. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
  98450. zSql = sqlite3MPrintf(db,
  98451. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  98452. if( zSql==0 ){
  98453. rc = SQLITE_NOMEM_BKPT;
  98454. }else{
  98455. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  98456. sqlite3DbFree(db, zSql);
  98457. }
  98458. }
  98459. /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
  98460. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98461. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  98462. Index *pIdx = sqliteHashData(i);
  98463. if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
  98464. }
  98465. /* Load the statistics from the sqlite_stat4 table. */
  98466. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98467. if( rc==SQLITE_OK ){
  98468. db->lookaside.bDisable++;
  98469. rc = loadStat4(db, sInfo.zDatabase);
  98470. db->lookaside.bDisable--;
  98471. }
  98472. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  98473. Index *pIdx = sqliteHashData(i);
  98474. sqlite3_free(pIdx->aiRowEst);
  98475. pIdx->aiRowEst = 0;
  98476. }
  98477. #endif
  98478. if( rc==SQLITE_NOMEM ){
  98479. sqlite3OomFault(db);
  98480. }
  98481. return rc;
  98482. }
  98483. #endif /* SQLITE_OMIT_ANALYZE */
  98484. /************** End of analyze.c *********************************************/
  98485. /************** Begin file attach.c ******************************************/
  98486. /*
  98487. ** 2003 April 6
  98488. **
  98489. ** The author disclaims copyright to this source code. In place of
  98490. ** a legal notice, here is a blessing:
  98491. **
  98492. ** May you do good and not evil.
  98493. ** May you find forgiveness for yourself and forgive others.
  98494. ** May you share freely, never taking more than you give.
  98495. **
  98496. *************************************************************************
  98497. ** This file contains code used to implement the ATTACH and DETACH commands.
  98498. */
  98499. /* #include "sqliteInt.h" */
  98500. #ifndef SQLITE_OMIT_ATTACH
  98501. /*
  98502. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  98503. ** is slightly different from resolving a normal SQL expression, because simple
  98504. ** identifiers are treated as strings, not possible column names or aliases.
  98505. **
  98506. ** i.e. if the parser sees:
  98507. **
  98508. ** ATTACH DATABASE abc AS def
  98509. **
  98510. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  98511. ** looking for columns of the same name.
  98512. **
  98513. ** This only applies to the root node of pExpr, so the statement:
  98514. **
  98515. ** ATTACH DATABASE abc||def AS 'db2'
  98516. **
  98517. ** will fail because neither abc or def can be resolved.
  98518. */
  98519. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  98520. {
  98521. int rc = SQLITE_OK;
  98522. if( pExpr ){
  98523. if( pExpr->op!=TK_ID ){
  98524. rc = sqlite3ResolveExprNames(pName, pExpr);
  98525. }else{
  98526. pExpr->op = TK_STRING;
  98527. }
  98528. }
  98529. return rc;
  98530. }
  98531. /*
  98532. ** An SQL user-function registered to do the work of an ATTACH statement. The
  98533. ** three arguments to the function come directly from an attach statement:
  98534. **
  98535. ** ATTACH DATABASE x AS y KEY z
  98536. **
  98537. ** SELECT sqlite_attach(x, y, z)
  98538. **
  98539. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  98540. ** third argument.
  98541. **
  98542. ** If the db->init.reopenMemdb flags is set, then instead of attaching a
  98543. ** new database, close the database on db->init.iDb and reopen it as an
  98544. ** empty MemDB.
  98545. */
  98546. static void attachFunc(
  98547. sqlite3_context *context,
  98548. int NotUsed,
  98549. sqlite3_value **argv
  98550. ){
  98551. int i;
  98552. int rc = 0;
  98553. sqlite3 *db = sqlite3_context_db_handle(context);
  98554. const char *zName;
  98555. const char *zFile;
  98556. char *zPath = 0;
  98557. char *zErr = 0;
  98558. unsigned int flags;
  98559. Db *aNew; /* New array of Db pointers */
  98560. Db *pNew; /* Db object for the newly attached database */
  98561. char *zErrDyn = 0;
  98562. sqlite3_vfs *pVfs;
  98563. UNUSED_PARAMETER(NotUsed);
  98564. zFile = (const char *)sqlite3_value_text(argv[0]);
  98565. zName = (const char *)sqlite3_value_text(argv[1]);
  98566. if( zFile==0 ) zFile = "";
  98567. if( zName==0 ) zName = "";
  98568. #ifdef SQLITE_ENABLE_DESERIALIZE
  98569. # define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb)
  98570. #else
  98571. # define REOPEN_AS_MEMDB(db) (0)
  98572. #endif
  98573. if( REOPEN_AS_MEMDB(db) ){
  98574. /* This is not a real ATTACH. Instead, this routine is being called
  98575. ** from sqlite3_deserialize() to close database db->init.iDb and
  98576. ** reopen it as a MemDB */
  98577. pVfs = sqlite3_vfs_find("memdb");
  98578. if( pVfs==0 ) return;
  98579. pNew = &db->aDb[db->init.iDb];
  98580. if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
  98581. pNew->pBt = 0;
  98582. pNew->pSchema = 0;
  98583. rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
  98584. }else{
  98585. /* This is a real ATTACH
  98586. **
  98587. ** Check for the following errors:
  98588. **
  98589. ** * Too many attached databases,
  98590. ** * Transaction currently open
  98591. ** * Specified database name already being used.
  98592. */
  98593. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  98594. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  98595. db->aLimit[SQLITE_LIMIT_ATTACHED]
  98596. );
  98597. goto attach_error;
  98598. }
  98599. for(i=0; i<db->nDb; i++){
  98600. char *z = db->aDb[i].zDbSName;
  98601. assert( z && zName );
  98602. if( sqlite3StrICmp(z, zName)==0 ){
  98603. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  98604. goto attach_error;
  98605. }
  98606. }
  98607. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  98608. ** hash tables.
  98609. */
  98610. if( db->aDb==db->aDbStatic ){
  98611. aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
  98612. if( aNew==0 ) return;
  98613. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  98614. }else{
  98615. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  98616. if( aNew==0 ) return;
  98617. }
  98618. db->aDb = aNew;
  98619. pNew = &db->aDb[db->nDb];
  98620. memset(pNew, 0, sizeof(*pNew));
  98621. /* Open the database file. If the btree is successfully opened, use
  98622. ** it to obtain the database schema. At this point the schema may
  98623. ** or may not be initialized.
  98624. */
  98625. flags = db->openFlags;
  98626. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  98627. if( rc!=SQLITE_OK ){
  98628. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  98629. sqlite3_result_error(context, zErr, -1);
  98630. sqlite3_free(zErr);
  98631. return;
  98632. }
  98633. assert( pVfs );
  98634. flags |= SQLITE_OPEN_MAIN_DB;
  98635. rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
  98636. sqlite3_free( zPath );
  98637. db->nDb++;
  98638. }
  98639. db->noSharedCache = 0;
  98640. if( rc==SQLITE_CONSTRAINT ){
  98641. rc = SQLITE_ERROR;
  98642. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  98643. }else if( rc==SQLITE_OK ){
  98644. Pager *pPager;
  98645. pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
  98646. if( !pNew->pSchema ){
  98647. rc = SQLITE_NOMEM_BKPT;
  98648. }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
  98649. zErrDyn = sqlite3MPrintf(db,
  98650. "attached databases must use the same text encoding as main database");
  98651. rc = SQLITE_ERROR;
  98652. }
  98653. sqlite3BtreeEnter(pNew->pBt);
  98654. pPager = sqlite3BtreePager(pNew->pBt);
  98655. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  98656. sqlite3BtreeSecureDelete(pNew->pBt,
  98657. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  98658. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  98659. sqlite3BtreeSetPagerFlags(pNew->pBt,
  98660. PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
  98661. #endif
  98662. sqlite3BtreeLeave(pNew->pBt);
  98663. }
  98664. pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  98665. if( !REOPEN_AS_MEMDB(db) ) pNew->zDbSName = sqlite3DbStrDup(db, zName);
  98666. if( rc==SQLITE_OK && pNew->zDbSName==0 ){
  98667. rc = SQLITE_NOMEM_BKPT;
  98668. }
  98669. #ifdef SQLITE_HAS_CODEC
  98670. if( rc==SQLITE_OK ){
  98671. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  98672. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  98673. int nKey;
  98674. char *zKey;
  98675. int t = sqlite3_value_type(argv[2]);
  98676. switch( t ){
  98677. case SQLITE_INTEGER:
  98678. case SQLITE_FLOAT:
  98679. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  98680. rc = SQLITE_ERROR;
  98681. break;
  98682. case SQLITE_TEXT:
  98683. case SQLITE_BLOB:
  98684. nKey = sqlite3_value_bytes(argv[2]);
  98685. zKey = (char *)sqlite3_value_blob(argv[2]);
  98686. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  98687. break;
  98688. case SQLITE_NULL:
  98689. /* No key specified. Use the key from the main database */
  98690. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  98691. if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  98692. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  98693. }
  98694. break;
  98695. }
  98696. }
  98697. #endif
  98698. /* If the file was opened successfully, read the schema for the new database.
  98699. ** If this fails, or if opening the file failed, then close the file and
  98700. ** remove the entry from the db->aDb[] array. i.e. put everything back the
  98701. ** way we found it.
  98702. */
  98703. if( rc==SQLITE_OK ){
  98704. sqlite3BtreeEnterAll(db);
  98705. db->init.iDb = 0;
  98706. db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
  98707. rc = sqlite3Init(db, &zErrDyn);
  98708. sqlite3BtreeLeaveAll(db);
  98709. assert( zErrDyn==0 || rc!=SQLITE_OK );
  98710. }
  98711. #ifdef SQLITE_USER_AUTHENTICATION
  98712. if( rc==SQLITE_OK ){
  98713. u8 newAuth = 0;
  98714. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  98715. if( newAuth<db->auth.authLevel ){
  98716. rc = SQLITE_AUTH_USER;
  98717. }
  98718. }
  98719. #endif
  98720. if( rc ){
  98721. if( !REOPEN_AS_MEMDB(db) ){
  98722. int iDb = db->nDb - 1;
  98723. assert( iDb>=2 );
  98724. if( db->aDb[iDb].pBt ){
  98725. sqlite3BtreeClose(db->aDb[iDb].pBt);
  98726. db->aDb[iDb].pBt = 0;
  98727. db->aDb[iDb].pSchema = 0;
  98728. }
  98729. sqlite3ResetAllSchemasOfConnection(db);
  98730. db->nDb = iDb;
  98731. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  98732. sqlite3OomFault(db);
  98733. sqlite3DbFree(db, zErrDyn);
  98734. zErrDyn = sqlite3MPrintf(db, "out of memory");
  98735. }else if( zErrDyn==0 ){
  98736. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  98737. }
  98738. }
  98739. goto attach_error;
  98740. }
  98741. return;
  98742. attach_error:
  98743. /* Return an error if we get here */
  98744. if( zErrDyn ){
  98745. sqlite3_result_error(context, zErrDyn, -1);
  98746. sqlite3DbFree(db, zErrDyn);
  98747. }
  98748. if( rc ) sqlite3_result_error_code(context, rc);
  98749. }
  98750. /*
  98751. ** An SQL user-function registered to do the work of an DETACH statement. The
  98752. ** three arguments to the function come directly from a detach statement:
  98753. **
  98754. ** DETACH DATABASE x
  98755. **
  98756. ** SELECT sqlite_detach(x)
  98757. */
  98758. static void detachFunc(
  98759. sqlite3_context *context,
  98760. int NotUsed,
  98761. sqlite3_value **argv
  98762. ){
  98763. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  98764. sqlite3 *db = sqlite3_context_db_handle(context);
  98765. int i;
  98766. Db *pDb = 0;
  98767. char zErr[128];
  98768. UNUSED_PARAMETER(NotUsed);
  98769. if( zName==0 ) zName = "";
  98770. for(i=0; i<db->nDb; i++){
  98771. pDb = &db->aDb[i];
  98772. if( pDb->pBt==0 ) continue;
  98773. if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
  98774. }
  98775. if( i>=db->nDb ){
  98776. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  98777. goto detach_error;
  98778. }
  98779. if( i<2 ){
  98780. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  98781. goto detach_error;
  98782. }
  98783. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  98784. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  98785. goto detach_error;
  98786. }
  98787. sqlite3BtreeClose(pDb->pBt);
  98788. pDb->pBt = 0;
  98789. pDb->pSchema = 0;
  98790. sqlite3CollapseDatabaseArray(db);
  98791. return;
  98792. detach_error:
  98793. sqlite3_result_error(context, zErr, -1);
  98794. }
  98795. /*
  98796. ** This procedure generates VDBE code for a single invocation of either the
  98797. ** sqlite_detach() or sqlite_attach() SQL user functions.
  98798. */
  98799. static void codeAttach(
  98800. Parse *pParse, /* The parser context */
  98801. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  98802. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  98803. Expr *pAuthArg, /* Expression to pass to authorization callback */
  98804. Expr *pFilename, /* Name of database file */
  98805. Expr *pDbname, /* Name of the database to use internally */
  98806. Expr *pKey /* Database key for encryption extension */
  98807. ){
  98808. int rc;
  98809. NameContext sName;
  98810. Vdbe *v;
  98811. sqlite3* db = pParse->db;
  98812. int regArgs;
  98813. if( pParse->nErr ) goto attach_end;
  98814. memset(&sName, 0, sizeof(NameContext));
  98815. sName.pParse = pParse;
  98816. if(
  98817. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  98818. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  98819. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  98820. ){
  98821. goto attach_end;
  98822. }
  98823. #ifndef SQLITE_OMIT_AUTHORIZATION
  98824. if( pAuthArg ){
  98825. char *zAuthArg;
  98826. if( pAuthArg->op==TK_STRING ){
  98827. zAuthArg = pAuthArg->u.zToken;
  98828. }else{
  98829. zAuthArg = 0;
  98830. }
  98831. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  98832. if(rc!=SQLITE_OK ){
  98833. goto attach_end;
  98834. }
  98835. }
  98836. #endif /* SQLITE_OMIT_AUTHORIZATION */
  98837. v = sqlite3GetVdbe(pParse);
  98838. regArgs = sqlite3GetTempRange(pParse, 4);
  98839. sqlite3ExprCode(pParse, pFilename, regArgs);
  98840. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  98841. sqlite3ExprCode(pParse, pKey, regArgs+2);
  98842. assert( v || db->mallocFailed );
  98843. if( v ){
  98844. sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
  98845. (char *)pFunc, P4_FUNCDEF);
  98846. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  98847. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  98848. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  98849. ** statement only). For DETACH, set it to false (expire all existing
  98850. ** statements).
  98851. */
  98852. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  98853. }
  98854. attach_end:
  98855. sqlite3ExprDelete(db, pFilename);
  98856. sqlite3ExprDelete(db, pDbname);
  98857. sqlite3ExprDelete(db, pKey);
  98858. }
  98859. /*
  98860. ** Called by the parser to compile a DETACH statement.
  98861. **
  98862. ** DETACH pDbname
  98863. */
  98864. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  98865. static const FuncDef detach_func = {
  98866. 1, /* nArg */
  98867. SQLITE_UTF8, /* funcFlags */
  98868. 0, /* pUserData */
  98869. 0, /* pNext */
  98870. detachFunc, /* xSFunc */
  98871. 0, /* xFinalize */
  98872. 0, 0, /* xValue, xInverse */
  98873. "sqlite_detach", /* zName */
  98874. {0}
  98875. };
  98876. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  98877. }
  98878. /*
  98879. ** Called by the parser to compile an ATTACH statement.
  98880. **
  98881. ** ATTACH p AS pDbname KEY pKey
  98882. */
  98883. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  98884. static const FuncDef attach_func = {
  98885. 3, /* nArg */
  98886. SQLITE_UTF8, /* funcFlags */
  98887. 0, /* pUserData */
  98888. 0, /* pNext */
  98889. attachFunc, /* xSFunc */
  98890. 0, /* xFinalize */
  98891. 0, 0, /* xValue, xInverse */
  98892. "sqlite_attach", /* zName */
  98893. {0}
  98894. };
  98895. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  98896. }
  98897. #endif /* SQLITE_OMIT_ATTACH */
  98898. /*
  98899. ** Initialize a DbFixer structure. This routine must be called prior
  98900. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  98901. */
  98902. SQLITE_PRIVATE void sqlite3FixInit(
  98903. DbFixer *pFix, /* The fixer to be initialized */
  98904. Parse *pParse, /* Error messages will be written here */
  98905. int iDb, /* This is the database that must be used */
  98906. const char *zType, /* "view", "trigger", or "index" */
  98907. const Token *pName /* Name of the view, trigger, or index */
  98908. ){
  98909. sqlite3 *db;
  98910. db = pParse->db;
  98911. assert( db->nDb>iDb );
  98912. pFix->pParse = pParse;
  98913. pFix->zDb = db->aDb[iDb].zDbSName;
  98914. pFix->pSchema = db->aDb[iDb].pSchema;
  98915. pFix->zType = zType;
  98916. pFix->pName = pName;
  98917. pFix->bVarOnly = (iDb==1);
  98918. }
  98919. /*
  98920. ** The following set of routines walk through the parse tree and assign
  98921. ** a specific database to all table references where the database name
  98922. ** was left unspecified in the original SQL statement. The pFix structure
  98923. ** must have been initialized by a prior call to sqlite3FixInit().
  98924. **
  98925. ** These routines are used to make sure that an index, trigger, or
  98926. ** view in one database does not refer to objects in a different database.
  98927. ** (Exception: indices, triggers, and views in the TEMP database are
  98928. ** allowed to refer to anything.) If a reference is explicitly made
  98929. ** to an object in a different database, an error message is added to
  98930. ** pParse->zErrMsg and these routines return non-zero. If everything
  98931. ** checks out, these routines return 0.
  98932. */
  98933. SQLITE_PRIVATE int sqlite3FixSrcList(
  98934. DbFixer *pFix, /* Context of the fixation */
  98935. SrcList *pList /* The Source list to check and modify */
  98936. ){
  98937. int i;
  98938. const char *zDb;
  98939. struct SrcList_item *pItem;
  98940. if( NEVER(pList==0) ) return 0;
  98941. zDb = pFix->zDb;
  98942. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  98943. if( pFix->bVarOnly==0 ){
  98944. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  98945. sqlite3ErrorMsg(pFix->pParse,
  98946. "%s %T cannot reference objects in database %s",
  98947. pFix->zType, pFix->pName, pItem->zDatabase);
  98948. return 1;
  98949. }
  98950. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  98951. pItem->zDatabase = 0;
  98952. pItem->pSchema = pFix->pSchema;
  98953. }
  98954. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  98955. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  98956. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  98957. #endif
  98958. if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){
  98959. return 1;
  98960. }
  98961. }
  98962. return 0;
  98963. }
  98964. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  98965. SQLITE_PRIVATE int sqlite3FixSelect(
  98966. DbFixer *pFix, /* Context of the fixation */
  98967. Select *pSelect /* The SELECT statement to be fixed to one database */
  98968. ){
  98969. while( pSelect ){
  98970. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  98971. return 1;
  98972. }
  98973. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  98974. return 1;
  98975. }
  98976. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  98977. return 1;
  98978. }
  98979. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  98980. return 1;
  98981. }
  98982. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  98983. return 1;
  98984. }
  98985. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  98986. return 1;
  98987. }
  98988. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  98989. return 1;
  98990. }
  98991. if( pSelect->pWith ){
  98992. int i;
  98993. for(i=0; i<pSelect->pWith->nCte; i++){
  98994. if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
  98995. return 1;
  98996. }
  98997. }
  98998. }
  98999. pSelect = pSelect->pPrior;
  99000. }
  99001. return 0;
  99002. }
  99003. SQLITE_PRIVATE int sqlite3FixExpr(
  99004. DbFixer *pFix, /* Context of the fixation */
  99005. Expr *pExpr /* The expression to be fixed to one database */
  99006. ){
  99007. while( pExpr ){
  99008. if( pExpr->op==TK_VARIABLE ){
  99009. if( pFix->pParse->db->init.busy ){
  99010. pExpr->op = TK_NULL;
  99011. }else{
  99012. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  99013. return 1;
  99014. }
  99015. }
  99016. if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
  99017. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  99018. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  99019. }else{
  99020. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  99021. }
  99022. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  99023. return 1;
  99024. }
  99025. pExpr = pExpr->pLeft;
  99026. }
  99027. return 0;
  99028. }
  99029. SQLITE_PRIVATE int sqlite3FixExprList(
  99030. DbFixer *pFix, /* Context of the fixation */
  99031. ExprList *pList /* The expression to be fixed to one database */
  99032. ){
  99033. int i;
  99034. struct ExprList_item *pItem;
  99035. if( pList==0 ) return 0;
  99036. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  99037. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  99038. return 1;
  99039. }
  99040. }
  99041. return 0;
  99042. }
  99043. #endif
  99044. #ifndef SQLITE_OMIT_TRIGGER
  99045. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  99046. DbFixer *pFix, /* Context of the fixation */
  99047. TriggerStep *pStep /* The trigger step be fixed to one database */
  99048. ){
  99049. while( pStep ){
  99050. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  99051. return 1;
  99052. }
  99053. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  99054. return 1;
  99055. }
  99056. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  99057. return 1;
  99058. }
  99059. #ifndef SQLITE_OMIT_UPSERT
  99060. if( pStep->pUpsert ){
  99061. Upsert *pUp = pStep->pUpsert;
  99062. if( sqlite3FixExprList(pFix, pUp->pUpsertTarget)
  99063. || sqlite3FixExpr(pFix, pUp->pUpsertTargetWhere)
  99064. || sqlite3FixExprList(pFix, pUp->pUpsertSet)
  99065. || sqlite3FixExpr(pFix, pUp->pUpsertWhere)
  99066. ){
  99067. return 1;
  99068. }
  99069. }
  99070. #endif
  99071. pStep = pStep->pNext;
  99072. }
  99073. return 0;
  99074. }
  99075. #endif
  99076. /************** End of attach.c **********************************************/
  99077. /************** Begin file auth.c ********************************************/
  99078. /*
  99079. ** 2003 January 11
  99080. **
  99081. ** The author disclaims copyright to this source code. In place of
  99082. ** a legal notice, here is a blessing:
  99083. **
  99084. ** May you do good and not evil.
  99085. ** May you find forgiveness for yourself and forgive others.
  99086. ** May you share freely, never taking more than you give.
  99087. **
  99088. *************************************************************************
  99089. ** This file contains code used to implement the sqlite3_set_authorizer()
  99090. ** API. This facility is an optional feature of the library. Embedded
  99091. ** systems that do not need this facility may omit it by recompiling
  99092. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  99093. */
  99094. /* #include "sqliteInt.h" */
  99095. /*
  99096. ** All of the code in this file may be omitted by defining a single
  99097. ** macro.
  99098. */
  99099. #ifndef SQLITE_OMIT_AUTHORIZATION
  99100. /*
  99101. ** Set or clear the access authorization function.
  99102. **
  99103. ** The access authorization function is be called during the compilation
  99104. ** phase to verify that the user has read and/or write access permission on
  99105. ** various fields of the database. The first argument to the auth function
  99106. ** is a copy of the 3rd argument to this routine. The second argument
  99107. ** to the auth function is one of these constants:
  99108. **
  99109. ** SQLITE_CREATE_INDEX
  99110. ** SQLITE_CREATE_TABLE
  99111. ** SQLITE_CREATE_TEMP_INDEX
  99112. ** SQLITE_CREATE_TEMP_TABLE
  99113. ** SQLITE_CREATE_TEMP_TRIGGER
  99114. ** SQLITE_CREATE_TEMP_VIEW
  99115. ** SQLITE_CREATE_TRIGGER
  99116. ** SQLITE_CREATE_VIEW
  99117. ** SQLITE_DELETE
  99118. ** SQLITE_DROP_INDEX
  99119. ** SQLITE_DROP_TABLE
  99120. ** SQLITE_DROP_TEMP_INDEX
  99121. ** SQLITE_DROP_TEMP_TABLE
  99122. ** SQLITE_DROP_TEMP_TRIGGER
  99123. ** SQLITE_DROP_TEMP_VIEW
  99124. ** SQLITE_DROP_TRIGGER
  99125. ** SQLITE_DROP_VIEW
  99126. ** SQLITE_INSERT
  99127. ** SQLITE_PRAGMA
  99128. ** SQLITE_READ
  99129. ** SQLITE_SELECT
  99130. ** SQLITE_TRANSACTION
  99131. ** SQLITE_UPDATE
  99132. **
  99133. ** The third and fourth arguments to the auth function are the name of
  99134. ** the table and the column that are being accessed. The auth function
  99135. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  99136. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  99137. ** means that the SQL statement will never-run - the sqlite3_exec() call
  99138. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  99139. ** should run but attempts to read the specified column will return NULL
  99140. ** and attempts to write the column will be ignored.
  99141. **
  99142. ** Setting the auth function to NULL disables this hook. The default
  99143. ** setting of the auth function is NULL.
  99144. */
  99145. SQLITE_API int sqlite3_set_authorizer(
  99146. sqlite3 *db,
  99147. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  99148. void *pArg
  99149. ){
  99150. #ifdef SQLITE_ENABLE_API_ARMOR
  99151. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  99152. #endif
  99153. sqlite3_mutex_enter(db->mutex);
  99154. db->xAuth = (sqlite3_xauth)xAuth;
  99155. db->pAuthArg = pArg;
  99156. sqlite3ExpirePreparedStatements(db, 0);
  99157. sqlite3_mutex_leave(db->mutex);
  99158. return SQLITE_OK;
  99159. }
  99160. /*
  99161. ** Write an error message into pParse->zErrMsg that explains that the
  99162. ** user-supplied authorization function returned an illegal value.
  99163. */
  99164. static void sqliteAuthBadReturnCode(Parse *pParse){
  99165. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  99166. pParse->rc = SQLITE_ERROR;
  99167. }
  99168. /*
  99169. ** Invoke the authorization callback for permission to read column zCol from
  99170. ** table zTab in database zDb. This function assumes that an authorization
  99171. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  99172. **
  99173. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  99174. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  99175. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  99176. */
  99177. SQLITE_PRIVATE int sqlite3AuthReadCol(
  99178. Parse *pParse, /* The parser context */
  99179. const char *zTab, /* Table name */
  99180. const char *zCol, /* Column name */
  99181. int iDb /* Index of containing database. */
  99182. ){
  99183. sqlite3 *db = pParse->db; /* Database handle */
  99184. char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
  99185. int rc; /* Auth callback return code */
  99186. if( db->init.busy ) return SQLITE_OK;
  99187. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  99188. #ifdef SQLITE_USER_AUTHENTICATION
  99189. ,db->auth.zAuthUser
  99190. #endif
  99191. );
  99192. if( rc==SQLITE_DENY ){
  99193. char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
  99194. if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
  99195. sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
  99196. pParse->rc = SQLITE_AUTH;
  99197. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  99198. sqliteAuthBadReturnCode(pParse);
  99199. }
  99200. return rc;
  99201. }
  99202. /*
  99203. ** The pExpr should be a TK_COLUMN expression. The table referred to
  99204. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  99205. ** Check to see if it is OK to read this particular column.
  99206. **
  99207. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  99208. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  99209. ** then generate an error.
  99210. */
  99211. SQLITE_PRIVATE void sqlite3AuthRead(
  99212. Parse *pParse, /* The parser context */
  99213. Expr *pExpr, /* The expression to check authorization on */
  99214. Schema *pSchema, /* The schema of the expression */
  99215. SrcList *pTabList /* All table that pExpr might refer to */
  99216. ){
  99217. sqlite3 *db = pParse->db;
  99218. Table *pTab = 0; /* The table being read */
  99219. const char *zCol; /* Name of the column of the table */
  99220. int iSrc; /* Index in pTabList->a[] of table being read */
  99221. int iDb; /* The index of the database the expression refers to */
  99222. int iCol; /* Index of column in table */
  99223. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  99224. assert( !IN_RENAME_OBJECT || db->xAuth==0 );
  99225. if( db->xAuth==0 ) return;
  99226. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  99227. if( iDb<0 ){
  99228. /* An attempt to read a column out of a subquery or other
  99229. ** temporary table. */
  99230. return;
  99231. }
  99232. if( pExpr->op==TK_TRIGGER ){
  99233. pTab = pParse->pTriggerTab;
  99234. }else{
  99235. assert( pTabList );
  99236. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  99237. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  99238. pTab = pTabList->a[iSrc].pTab;
  99239. break;
  99240. }
  99241. }
  99242. }
  99243. iCol = pExpr->iColumn;
  99244. if( NEVER(pTab==0) ) return;
  99245. if( iCol>=0 ){
  99246. assert( iCol<pTab->nCol );
  99247. zCol = pTab->aCol[iCol].zName;
  99248. }else if( pTab->iPKey>=0 ){
  99249. assert( pTab->iPKey<pTab->nCol );
  99250. zCol = pTab->aCol[pTab->iPKey].zName;
  99251. }else{
  99252. zCol = "ROWID";
  99253. }
  99254. assert( iDb>=0 && iDb<db->nDb );
  99255. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  99256. pExpr->op = TK_NULL;
  99257. }
  99258. }
  99259. /*
  99260. ** Do an authorization check using the code and arguments given. Return
  99261. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  99262. ** is returned, then the error count and error message in pParse are
  99263. ** modified appropriately.
  99264. */
  99265. SQLITE_PRIVATE int sqlite3AuthCheck(
  99266. Parse *pParse,
  99267. int code,
  99268. const char *zArg1,
  99269. const char *zArg2,
  99270. const char *zArg3
  99271. ){
  99272. sqlite3 *db = pParse->db;
  99273. int rc;
  99274. /* Don't do any authorization checks if the database is initialising
  99275. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  99276. */
  99277. assert( !IN_RENAME_OBJECT || db->xAuth==0 );
  99278. if( db->init.busy || IN_SPECIAL_PARSE ){
  99279. return SQLITE_OK;
  99280. }
  99281. if( db->xAuth==0 ){
  99282. return SQLITE_OK;
  99283. }
  99284. /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
  99285. ** callback are either NULL pointers or zero-terminated strings that
  99286. ** contain additional details about the action to be authorized.
  99287. **
  99288. ** The following testcase() macros show that any of the 3rd through 6th
  99289. ** parameters can be either NULL or a string. */
  99290. testcase( zArg1==0 );
  99291. testcase( zArg2==0 );
  99292. testcase( zArg3==0 );
  99293. testcase( pParse->zAuthContext==0 );
  99294. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  99295. #ifdef SQLITE_USER_AUTHENTICATION
  99296. ,db->auth.zAuthUser
  99297. #endif
  99298. );
  99299. if( rc==SQLITE_DENY ){
  99300. sqlite3ErrorMsg(pParse, "not authorized");
  99301. pParse->rc = SQLITE_AUTH;
  99302. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  99303. rc = SQLITE_DENY;
  99304. sqliteAuthBadReturnCode(pParse);
  99305. }
  99306. return rc;
  99307. }
  99308. /*
  99309. ** Push an authorization context. After this routine is called, the
  99310. ** zArg3 argument to authorization callbacks will be zContext until
  99311. ** popped. Or if pParse==0, this routine is a no-op.
  99312. */
  99313. SQLITE_PRIVATE void sqlite3AuthContextPush(
  99314. Parse *pParse,
  99315. AuthContext *pContext,
  99316. const char *zContext
  99317. ){
  99318. assert( pParse );
  99319. pContext->pParse = pParse;
  99320. pContext->zAuthContext = pParse->zAuthContext;
  99321. pParse->zAuthContext = zContext;
  99322. }
  99323. /*
  99324. ** Pop an authorization context that was previously pushed
  99325. ** by sqlite3AuthContextPush
  99326. */
  99327. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  99328. if( pContext->pParse ){
  99329. pContext->pParse->zAuthContext = pContext->zAuthContext;
  99330. pContext->pParse = 0;
  99331. }
  99332. }
  99333. #endif /* SQLITE_OMIT_AUTHORIZATION */
  99334. /************** End of auth.c ************************************************/
  99335. /************** Begin file build.c *******************************************/
  99336. /*
  99337. ** 2001 September 15
  99338. **
  99339. ** The author disclaims copyright to this source code. In place of
  99340. ** a legal notice, here is a blessing:
  99341. **
  99342. ** May you do good and not evil.
  99343. ** May you find forgiveness for yourself and forgive others.
  99344. ** May you share freely, never taking more than you give.
  99345. **
  99346. *************************************************************************
  99347. ** This file contains C code routines that are called by the SQLite parser
  99348. ** when syntax rules are reduced. The routines in this file handle the
  99349. ** following kinds of SQL syntax:
  99350. **
  99351. ** CREATE TABLE
  99352. ** DROP TABLE
  99353. ** CREATE INDEX
  99354. ** DROP INDEX
  99355. ** creating ID lists
  99356. ** BEGIN TRANSACTION
  99357. ** COMMIT
  99358. ** ROLLBACK
  99359. */
  99360. /* #include "sqliteInt.h" */
  99361. #ifndef SQLITE_OMIT_SHARED_CACHE
  99362. /*
  99363. ** The TableLock structure is only used by the sqlite3TableLock() and
  99364. ** codeTableLocks() functions.
  99365. */
  99366. struct TableLock {
  99367. int iDb; /* The database containing the table to be locked */
  99368. int iTab; /* The root page of the table to be locked */
  99369. u8 isWriteLock; /* True for write lock. False for a read lock */
  99370. const char *zLockName; /* Name of the table */
  99371. };
  99372. /*
  99373. ** Record the fact that we want to lock a table at run-time.
  99374. **
  99375. ** The table to be locked has root page iTab and is found in database iDb.
  99376. ** A read or a write lock can be taken depending on isWritelock.
  99377. **
  99378. ** This routine just records the fact that the lock is desired. The
  99379. ** code to make the lock occur is generated by a later call to
  99380. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  99381. */
  99382. SQLITE_PRIVATE void sqlite3TableLock(
  99383. Parse *pParse, /* Parsing context */
  99384. int iDb, /* Index of the database containing the table to lock */
  99385. int iTab, /* Root page number of the table to be locked */
  99386. u8 isWriteLock, /* True for a write lock */
  99387. const char *zName /* Name of the table to be locked */
  99388. ){
  99389. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  99390. int i;
  99391. int nBytes;
  99392. TableLock *p;
  99393. assert( iDb>=0 );
  99394. if( iDb==1 ) return;
  99395. if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
  99396. for(i=0; i<pToplevel->nTableLock; i++){
  99397. p = &pToplevel->aTableLock[i];
  99398. if( p->iDb==iDb && p->iTab==iTab ){
  99399. p->isWriteLock = (p->isWriteLock || isWriteLock);
  99400. return;
  99401. }
  99402. }
  99403. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  99404. pToplevel->aTableLock =
  99405. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  99406. if( pToplevel->aTableLock ){
  99407. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  99408. p->iDb = iDb;
  99409. p->iTab = iTab;
  99410. p->isWriteLock = isWriteLock;
  99411. p->zLockName = zName;
  99412. }else{
  99413. pToplevel->nTableLock = 0;
  99414. sqlite3OomFault(pToplevel->db);
  99415. }
  99416. }
  99417. /*
  99418. ** Code an OP_TableLock instruction for each table locked by the
  99419. ** statement (configured by calls to sqlite3TableLock()).
  99420. */
  99421. static void codeTableLocks(Parse *pParse){
  99422. int i;
  99423. Vdbe *pVdbe;
  99424. pVdbe = sqlite3GetVdbe(pParse);
  99425. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  99426. for(i=0; i<pParse->nTableLock; i++){
  99427. TableLock *p = &pParse->aTableLock[i];
  99428. int p1 = p->iDb;
  99429. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  99430. p->zLockName, P4_STATIC);
  99431. }
  99432. }
  99433. #else
  99434. #define codeTableLocks(x)
  99435. #endif
  99436. /*
  99437. ** Return TRUE if the given yDbMask object is empty - if it contains no
  99438. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  99439. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  99440. */
  99441. #if SQLITE_MAX_ATTACHED>30
  99442. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  99443. int i;
  99444. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  99445. return 1;
  99446. }
  99447. #endif
  99448. /*
  99449. ** This routine is called after a single SQL statement has been
  99450. ** parsed and a VDBE program to execute that statement has been
  99451. ** prepared. This routine puts the finishing touches on the
  99452. ** VDBE program and resets the pParse structure for the next
  99453. ** parse.
  99454. **
  99455. ** Note that if an error occurred, it might be the case that
  99456. ** no VDBE code was generated.
  99457. */
  99458. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  99459. sqlite3 *db;
  99460. Vdbe *v;
  99461. assert( pParse->pToplevel==0 );
  99462. db = pParse->db;
  99463. if( pParse->nested ) return;
  99464. if( db->mallocFailed || pParse->nErr ){
  99465. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  99466. return;
  99467. }
  99468. /* Begin by generating some termination code at the end of the
  99469. ** vdbe program
  99470. */
  99471. v = sqlite3GetVdbe(pParse);
  99472. assert( !pParse->isMultiWrite
  99473. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  99474. if( v ){
  99475. sqlite3VdbeAddOp0(v, OP_Halt);
  99476. #if SQLITE_USER_AUTHENTICATION
  99477. if( pParse->nTableLock>0 && db->init.busy==0 ){
  99478. sqlite3UserAuthInit(db);
  99479. if( db->auth.authLevel<UAUTH_User ){
  99480. sqlite3ErrorMsg(pParse, "user not authenticated");
  99481. pParse->rc = SQLITE_AUTH_USER;
  99482. return;
  99483. }
  99484. }
  99485. #endif
  99486. /* The cookie mask contains one bit for each database file open.
  99487. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  99488. ** set for each database that is used. Generate code to start a
  99489. ** transaction on each used database and to verify the schema cookie
  99490. ** on each used database.
  99491. */
  99492. if( db->mallocFailed==0
  99493. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  99494. ){
  99495. int iDb, i;
  99496. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  99497. sqlite3VdbeJumpHere(v, 0);
  99498. for(iDb=0; iDb<db->nDb; iDb++){
  99499. Schema *pSchema;
  99500. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  99501. sqlite3VdbeUsesBtree(v, iDb);
  99502. pSchema = db->aDb[iDb].pSchema;
  99503. sqlite3VdbeAddOp4Int(v,
  99504. OP_Transaction, /* Opcode */
  99505. iDb, /* P1 */
  99506. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  99507. pSchema->schema_cookie, /* P3 */
  99508. pSchema->iGeneration /* P4 */
  99509. );
  99510. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  99511. VdbeComment((v,
  99512. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  99513. }
  99514. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99515. for(i=0; i<pParse->nVtabLock; i++){
  99516. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  99517. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  99518. }
  99519. pParse->nVtabLock = 0;
  99520. #endif
  99521. /* Once all the cookies have been verified and transactions opened,
  99522. ** obtain the required table-locks. This is a no-op unless the
  99523. ** shared-cache feature is enabled.
  99524. */
  99525. codeTableLocks(pParse);
  99526. /* Initialize any AUTOINCREMENT data structures required.
  99527. */
  99528. sqlite3AutoincrementBegin(pParse);
  99529. /* Code constant expressions that where factored out of inner loops */
  99530. if( pParse->pConstExpr ){
  99531. ExprList *pEL = pParse->pConstExpr;
  99532. pParse->okConstFactor = 0;
  99533. for(i=0; i<pEL->nExpr; i++){
  99534. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  99535. }
  99536. }
  99537. /* Finally, jump back to the beginning of the executable code. */
  99538. sqlite3VdbeGoto(v, 1);
  99539. }
  99540. }
  99541. /* Get the VDBE program ready for execution
  99542. */
  99543. if( v && pParse->nErr==0 && !db->mallocFailed ){
  99544. /* A minimum of one cursor is required if autoincrement is used
  99545. * See ticket [a696379c1f08866] */
  99546. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  99547. sqlite3VdbeMakeReady(v, pParse);
  99548. pParse->rc = SQLITE_DONE;
  99549. }else{
  99550. pParse->rc = SQLITE_ERROR;
  99551. }
  99552. }
  99553. /*
  99554. ** Run the parser and code generator recursively in order to generate
  99555. ** code for the SQL statement given onto the end of the pParse context
  99556. ** currently under construction. When the parser is run recursively
  99557. ** this way, the final OP_Halt is not appended and other initialization
  99558. ** and finalization steps are omitted because those are handling by the
  99559. ** outermost parser.
  99560. **
  99561. ** Not everything is nestable. This facility is designed to permit
  99562. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  99563. ** care if you decide to try to use this routine for some other purposes.
  99564. */
  99565. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  99566. va_list ap;
  99567. char *zSql;
  99568. char *zErrMsg = 0;
  99569. sqlite3 *db = pParse->db;
  99570. char saveBuf[PARSE_TAIL_SZ];
  99571. if( pParse->nErr ) return;
  99572. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  99573. va_start(ap, zFormat);
  99574. zSql = sqlite3VMPrintf(db, zFormat, ap);
  99575. va_end(ap);
  99576. if( zSql==0 ){
  99577. return; /* A malloc must have failed */
  99578. }
  99579. pParse->nested++;
  99580. memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
  99581. memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
  99582. sqlite3RunParser(pParse, zSql, &zErrMsg);
  99583. sqlite3DbFree(db, zErrMsg);
  99584. sqlite3DbFree(db, zSql);
  99585. memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
  99586. pParse->nested--;
  99587. }
  99588. #if SQLITE_USER_AUTHENTICATION
  99589. /*
  99590. ** Return TRUE if zTable is the name of the system table that stores the
  99591. ** list of users and their access credentials.
  99592. */
  99593. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  99594. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  99595. }
  99596. #endif
  99597. /*
  99598. ** Locate the in-memory structure that describes a particular database
  99599. ** table given the name of that table and (optionally) the name of the
  99600. ** database containing the table. Return NULL if not found.
  99601. **
  99602. ** If zDatabase is 0, all databases are searched for the table and the
  99603. ** first matching table is returned. (No checking for duplicate table
  99604. ** names is done.) The search order is TEMP first, then MAIN, then any
  99605. ** auxiliary databases added using the ATTACH command.
  99606. **
  99607. ** See also sqlite3LocateTable().
  99608. */
  99609. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  99610. Table *p = 0;
  99611. int i;
  99612. /* All mutexes are required for schema access. Make sure we hold them. */
  99613. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  99614. #if SQLITE_USER_AUTHENTICATION
  99615. /* Only the admin user is allowed to know that the sqlite_user table
  99616. ** exists */
  99617. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  99618. return 0;
  99619. }
  99620. #endif
  99621. while(1){
  99622. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  99623. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  99624. if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
  99625. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  99626. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  99627. if( p ) return p;
  99628. }
  99629. }
  99630. /* Not found. If the name we were looking for was temp.sqlite_master
  99631. ** then change the name to sqlite_temp_master and try again. */
  99632. if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
  99633. if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
  99634. zName = TEMP_MASTER_NAME;
  99635. }
  99636. return 0;
  99637. }
  99638. /*
  99639. ** Locate the in-memory structure that describes a particular database
  99640. ** table given the name of that table and (optionally) the name of the
  99641. ** database containing the table. Return NULL if not found. Also leave an
  99642. ** error message in pParse->zErrMsg.
  99643. **
  99644. ** The difference between this routine and sqlite3FindTable() is that this
  99645. ** routine leaves an error message in pParse->zErrMsg where
  99646. ** sqlite3FindTable() does not.
  99647. */
  99648. SQLITE_PRIVATE Table *sqlite3LocateTable(
  99649. Parse *pParse, /* context in which to report errors */
  99650. u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
  99651. const char *zName, /* Name of the table we are looking for */
  99652. const char *zDbase /* Name of the database. Might be NULL */
  99653. ){
  99654. Table *p;
  99655. sqlite3 *db = pParse->db;
  99656. /* Read the database schema. If an error occurs, leave an error message
  99657. ** and code in pParse and return NULL. */
  99658. if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
  99659. && SQLITE_OK!=sqlite3ReadSchema(pParse)
  99660. ){
  99661. return 0;
  99662. }
  99663. p = sqlite3FindTable(db, zName, zDbase);
  99664. if( p==0 ){
  99665. const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
  99666. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99667. /* If zName is the not the name of a table in the schema created using
  99668. ** CREATE, then check to see if it is the name of an virtual table that
  99669. ** can be an eponymous virtual table. */
  99670. Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
  99671. if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
  99672. pMod = sqlite3PragmaVtabRegister(db, zName);
  99673. }
  99674. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  99675. return pMod->pEpoTab;
  99676. }
  99677. #endif
  99678. if( (flags & LOCATE_NOERR)==0 ){
  99679. if( zDbase ){
  99680. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  99681. }else{
  99682. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  99683. }
  99684. pParse->checkSchema = 1;
  99685. }
  99686. }
  99687. return p;
  99688. }
  99689. /*
  99690. ** Locate the table identified by *p.
  99691. **
  99692. ** This is a wrapper around sqlite3LocateTable(). The difference between
  99693. ** sqlite3LocateTable() and this function is that this function restricts
  99694. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  99695. ** non-NULL if it is part of a view or trigger program definition. See
  99696. ** sqlite3FixSrcList() for details.
  99697. */
  99698. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  99699. Parse *pParse,
  99700. u32 flags,
  99701. struct SrcList_item *p
  99702. ){
  99703. const char *zDb;
  99704. assert( p->pSchema==0 || p->zDatabase==0 );
  99705. if( p->pSchema ){
  99706. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  99707. zDb = pParse->db->aDb[iDb].zDbSName;
  99708. }else{
  99709. zDb = p->zDatabase;
  99710. }
  99711. return sqlite3LocateTable(pParse, flags, p->zName, zDb);
  99712. }
  99713. /*
  99714. ** Locate the in-memory structure that describes
  99715. ** a particular index given the name of that index
  99716. ** and the name of the database that contains the index.
  99717. ** Return NULL if not found.
  99718. **
  99719. ** If zDatabase is 0, all databases are searched for the
  99720. ** table and the first matching index is returned. (No checking
  99721. ** for duplicate index names is done.) The search order is
  99722. ** TEMP first, then MAIN, then any auxiliary databases added
  99723. ** using the ATTACH command.
  99724. */
  99725. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  99726. Index *p = 0;
  99727. int i;
  99728. /* All mutexes are required for schema access. Make sure we hold them. */
  99729. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  99730. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  99731. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  99732. Schema *pSchema = db->aDb[j].pSchema;
  99733. assert( pSchema );
  99734. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
  99735. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  99736. p = sqlite3HashFind(&pSchema->idxHash, zName);
  99737. if( p ) break;
  99738. }
  99739. return p;
  99740. }
  99741. /*
  99742. ** Reclaim the memory used by an index
  99743. */
  99744. SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3 *db, Index *p){
  99745. #ifndef SQLITE_OMIT_ANALYZE
  99746. sqlite3DeleteIndexSamples(db, p);
  99747. #endif
  99748. sqlite3ExprDelete(db, p->pPartIdxWhere);
  99749. sqlite3ExprListDelete(db, p->aColExpr);
  99750. sqlite3DbFree(db, p->zColAff);
  99751. if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
  99752. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99753. sqlite3_free(p->aiRowEst);
  99754. #endif
  99755. sqlite3DbFree(db, p);
  99756. }
  99757. /*
  99758. ** For the index called zIdxName which is found in the database iDb,
  99759. ** unlike that index from its Table then remove the index from
  99760. ** the index hash table and free all memory structures associated
  99761. ** with the index.
  99762. */
  99763. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  99764. Index *pIndex;
  99765. Hash *pHash;
  99766. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99767. pHash = &db->aDb[iDb].pSchema->idxHash;
  99768. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  99769. if( ALWAYS(pIndex) ){
  99770. if( pIndex->pTable->pIndex==pIndex ){
  99771. pIndex->pTable->pIndex = pIndex->pNext;
  99772. }else{
  99773. Index *p;
  99774. /* Justification of ALWAYS(); The index must be on the list of
  99775. ** indices. */
  99776. p = pIndex->pTable->pIndex;
  99777. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  99778. if( ALWAYS(p && p->pNext==pIndex) ){
  99779. p->pNext = pIndex->pNext;
  99780. }
  99781. }
  99782. sqlite3FreeIndex(db, pIndex);
  99783. }
  99784. db->mDbFlags |= DBFLAG_SchemaChange;
  99785. }
  99786. /*
  99787. ** Look through the list of open database files in db->aDb[] and if
  99788. ** any have been closed, remove them from the list. Reallocate the
  99789. ** db->aDb[] structure to a smaller size, if possible.
  99790. **
  99791. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  99792. ** are never candidates for being collapsed.
  99793. */
  99794. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  99795. int i, j;
  99796. for(i=j=2; i<db->nDb; i++){
  99797. struct Db *pDb = &db->aDb[i];
  99798. if( pDb->pBt==0 ){
  99799. sqlite3DbFree(db, pDb->zDbSName);
  99800. pDb->zDbSName = 0;
  99801. continue;
  99802. }
  99803. if( j<i ){
  99804. db->aDb[j] = db->aDb[i];
  99805. }
  99806. j++;
  99807. }
  99808. db->nDb = j;
  99809. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  99810. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  99811. sqlite3DbFree(db, db->aDb);
  99812. db->aDb = db->aDbStatic;
  99813. }
  99814. }
  99815. /*
  99816. ** Reset the schema for the database at index iDb. Also reset the
  99817. ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
  99818. ** Deferred resets may be run by calling with iDb<0.
  99819. */
  99820. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  99821. int i;
  99822. assert( iDb<db->nDb );
  99823. if( iDb>=0 ){
  99824. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99825. DbSetProperty(db, iDb, DB_ResetWanted);
  99826. DbSetProperty(db, 1, DB_ResetWanted);
  99827. db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
  99828. }
  99829. if( db->nSchemaLock==0 ){
  99830. for(i=0; i<db->nDb; i++){
  99831. if( DbHasProperty(db, i, DB_ResetWanted) ){
  99832. sqlite3SchemaClear(db->aDb[i].pSchema);
  99833. }
  99834. }
  99835. }
  99836. }
  99837. /*
  99838. ** Erase all schema information from all attached databases (including
  99839. ** "main" and "temp") for a single database connection.
  99840. */
  99841. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  99842. int i;
  99843. sqlite3BtreeEnterAll(db);
  99844. for(i=0; i<db->nDb; i++){
  99845. Db *pDb = &db->aDb[i];
  99846. if( pDb->pSchema ){
  99847. if( db->nSchemaLock==0 ){
  99848. sqlite3SchemaClear(pDb->pSchema);
  99849. }else{
  99850. DbSetProperty(db, i, DB_ResetWanted);
  99851. }
  99852. }
  99853. }
  99854. db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
  99855. sqlite3VtabUnlockList(db);
  99856. sqlite3BtreeLeaveAll(db);
  99857. if( db->nSchemaLock==0 ){
  99858. sqlite3CollapseDatabaseArray(db);
  99859. }
  99860. }
  99861. /*
  99862. ** This routine is called when a commit occurs.
  99863. */
  99864. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  99865. db->mDbFlags &= ~DBFLAG_SchemaChange;
  99866. }
  99867. /*
  99868. ** Delete memory allocated for the column names of a table or view (the
  99869. ** Table.aCol[] array).
  99870. */
  99871. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  99872. int i;
  99873. Column *pCol;
  99874. assert( pTable!=0 );
  99875. if( (pCol = pTable->aCol)!=0 ){
  99876. for(i=0; i<pTable->nCol; i++, pCol++){
  99877. sqlite3DbFree(db, pCol->zName);
  99878. sqlite3ExprDelete(db, pCol->pDflt);
  99879. sqlite3DbFree(db, pCol->zColl);
  99880. }
  99881. sqlite3DbFree(db, pTable->aCol);
  99882. }
  99883. }
  99884. /*
  99885. ** Remove the memory data structures associated with the given
  99886. ** Table. No changes are made to disk by this routine.
  99887. **
  99888. ** This routine just deletes the data structure. It does not unlink
  99889. ** the table data structure from the hash table. But it does destroy
  99890. ** memory structures of the indices and foreign keys associated with
  99891. ** the table.
  99892. **
  99893. ** The db parameter is optional. It is needed if the Table object
  99894. ** contains lookaside memory. (Table objects in the schema do not use
  99895. ** lookaside memory, but some ephemeral Table objects do.) Or the
  99896. ** db parameter can be used with db->pnBytesFreed to measure the memory
  99897. ** used by the Table object.
  99898. */
  99899. static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
  99900. Index *pIndex, *pNext;
  99901. #ifdef SQLITE_DEBUG
  99902. /* Record the number of outstanding lookaside allocations in schema Tables
  99903. ** prior to doing any free() operations. Since schema Tables do not use
  99904. ** lookaside, this number should not change. */
  99905. int nLookaside = 0;
  99906. if( db && (pTable->tabFlags & TF_Ephemeral)==0 ){
  99907. nLookaside = sqlite3LookasideUsed(db, 0);
  99908. }
  99909. #endif
  99910. /* Delete all indices associated with this table. */
  99911. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  99912. pNext = pIndex->pNext;
  99913. assert( pIndex->pSchema==pTable->pSchema
  99914. || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
  99915. if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
  99916. char *zName = pIndex->zName;
  99917. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  99918. &pIndex->pSchema->idxHash, zName, 0
  99919. );
  99920. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  99921. assert( pOld==pIndex || pOld==0 );
  99922. }
  99923. sqlite3FreeIndex(db, pIndex);
  99924. }
  99925. /* Delete any foreign keys attached to this table. */
  99926. sqlite3FkDelete(db, pTable);
  99927. /* Delete the Table structure itself.
  99928. */
  99929. #ifdef SQLITE_ENABLE_NORMALIZE
  99930. if( pTable->pColHash ){
  99931. sqlite3HashClear(pTable->pColHash);
  99932. sqlite3_free(pTable->pColHash);
  99933. }
  99934. #endif
  99935. sqlite3DeleteColumnNames(db, pTable);
  99936. sqlite3DbFree(db, pTable->zName);
  99937. sqlite3DbFree(db, pTable->zColAff);
  99938. sqlite3SelectDelete(db, pTable->pSelect);
  99939. sqlite3ExprListDelete(db, pTable->pCheck);
  99940. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99941. sqlite3VtabClear(db, pTable);
  99942. #endif
  99943. sqlite3DbFree(db, pTable);
  99944. /* Verify that no lookaside memory was used by schema tables */
  99945. assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
  99946. }
  99947. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  99948. /* Do not delete the table until the reference count reaches zero. */
  99949. if( !pTable ) return;
  99950. if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
  99951. deleteTable(db, pTable);
  99952. }
  99953. /*
  99954. ** Unlink the given table from the hash tables and the delete the
  99955. ** table structure with all its indices and foreign keys.
  99956. */
  99957. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  99958. Table *p;
  99959. Db *pDb;
  99960. assert( db!=0 );
  99961. assert( iDb>=0 && iDb<db->nDb );
  99962. assert( zTabName );
  99963. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99964. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  99965. pDb = &db->aDb[iDb];
  99966. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  99967. sqlite3DeleteTable(db, p);
  99968. db->mDbFlags |= DBFLAG_SchemaChange;
  99969. }
  99970. /*
  99971. ** Given a token, return a string that consists of the text of that
  99972. ** token. Space to hold the returned string
  99973. ** is obtained from sqliteMalloc() and must be freed by the calling
  99974. ** function.
  99975. **
  99976. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  99977. ** surround the body of the token are removed.
  99978. **
  99979. ** Tokens are often just pointers into the original SQL text and so
  99980. ** are not \000 terminated and are not persistent. The returned string
  99981. ** is \000 terminated and is persistent.
  99982. */
  99983. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  99984. char *zName;
  99985. if( pName ){
  99986. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  99987. sqlite3Dequote(zName);
  99988. }else{
  99989. zName = 0;
  99990. }
  99991. return zName;
  99992. }
  99993. /*
  99994. ** Open the sqlite_master table stored in database number iDb for
  99995. ** writing. The table is opened using cursor 0.
  99996. */
  99997. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  99998. Vdbe *v = sqlite3GetVdbe(p);
  99999. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
  100000. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  100001. if( p->nTab==0 ){
  100002. p->nTab = 1;
  100003. }
  100004. }
  100005. /*
  100006. ** Parameter zName points to a nul-terminated buffer containing the name
  100007. ** of a database ("main", "temp" or the name of an attached db). This
  100008. ** function returns the index of the named database in db->aDb[], or
  100009. ** -1 if the named db cannot be found.
  100010. */
  100011. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  100012. int i = -1; /* Database number */
  100013. if( zName ){
  100014. Db *pDb;
  100015. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  100016. if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
  100017. /* "main" is always an acceptable alias for the primary database
  100018. ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
  100019. if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
  100020. }
  100021. }
  100022. return i;
  100023. }
  100024. /*
  100025. ** The token *pName contains the name of a database (either "main" or
  100026. ** "temp" or the name of an attached db). This routine returns the
  100027. ** index of the named database in db->aDb[], or -1 if the named db
  100028. ** does not exist.
  100029. */
  100030. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  100031. int i; /* Database number */
  100032. char *zName; /* Name we are searching for */
  100033. zName = sqlite3NameFromToken(db, pName);
  100034. i = sqlite3FindDbName(db, zName);
  100035. sqlite3DbFree(db, zName);
  100036. return i;
  100037. }
  100038. /* The table or view or trigger name is passed to this routine via tokens
  100039. ** pName1 and pName2. If the table name was fully qualified, for example:
  100040. **
  100041. ** CREATE TABLE xxx.yyy (...);
  100042. **
  100043. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  100044. ** the table name is not fully qualified, i.e.:
  100045. **
  100046. ** CREATE TABLE yyy(...);
  100047. **
  100048. ** Then pName1 is set to "yyy" and pName2 is "".
  100049. **
  100050. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  100051. ** pName2) that stores the unqualified table name. The index of the
  100052. ** database "xxx" is returned.
  100053. */
  100054. SQLITE_PRIVATE int sqlite3TwoPartName(
  100055. Parse *pParse, /* Parsing and code generating context */
  100056. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  100057. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  100058. Token **pUnqual /* Write the unqualified object name here */
  100059. ){
  100060. int iDb; /* Database holding the object */
  100061. sqlite3 *db = pParse->db;
  100062. assert( pName2!=0 );
  100063. if( pName2->n>0 ){
  100064. if( db->init.busy ) {
  100065. sqlite3ErrorMsg(pParse, "corrupt database");
  100066. return -1;
  100067. }
  100068. *pUnqual = pName2;
  100069. iDb = sqlite3FindDb(db, pName1);
  100070. if( iDb<0 ){
  100071. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  100072. return -1;
  100073. }
  100074. }else{
  100075. assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT
  100076. || (db->mDbFlags & DBFLAG_Vacuum)!=0);
  100077. iDb = db->init.iDb;
  100078. *pUnqual = pName1;
  100079. }
  100080. return iDb;
  100081. }
  100082. /*
  100083. ** True if PRAGMA writable_schema is ON
  100084. */
  100085. SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3 *db){
  100086. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
  100087. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  100088. SQLITE_WriteSchema );
  100089. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  100090. SQLITE_Defensive );
  100091. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  100092. (SQLITE_WriteSchema|SQLITE_Defensive) );
  100093. return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
  100094. }
  100095. /*
  100096. ** This routine is used to check if the UTF-8 string zName is a legal
  100097. ** unqualified name for a new schema object (table, index, view or
  100098. ** trigger). All names are legal except those that begin with the string
  100099. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  100100. ** is reserved for internal use.
  100101. */
  100102. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  100103. if( !pParse->db->init.busy && pParse->nested==0
  100104. && sqlite3WritableSchema(pParse->db)==0
  100105. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  100106. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  100107. return SQLITE_ERROR;
  100108. }
  100109. return SQLITE_OK;
  100110. }
  100111. /*
  100112. ** Return the PRIMARY KEY index of a table
  100113. */
  100114. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  100115. Index *p;
  100116. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  100117. return p;
  100118. }
  100119. /*
  100120. ** Return the column of index pIdx that corresponds to table
  100121. ** column iCol. Return -1 if not found.
  100122. */
  100123. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  100124. int i;
  100125. for(i=0; i<pIdx->nColumn; i++){
  100126. if( iCol==pIdx->aiColumn[i] ) return i;
  100127. }
  100128. return -1;
  100129. }
  100130. /*
  100131. ** Begin constructing a new table representation in memory. This is
  100132. ** the first of several action routines that get called in response
  100133. ** to a CREATE TABLE statement. In particular, this routine is called
  100134. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  100135. ** flag is true if the table should be stored in the auxiliary database
  100136. ** file instead of in the main database file. This is normally the case
  100137. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  100138. ** CREATE and TABLE.
  100139. **
  100140. ** The new table record is initialized and put in pParse->pNewTable.
  100141. ** As more of the CREATE TABLE statement is parsed, additional action
  100142. ** routines will be called to add more information to this record.
  100143. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  100144. ** is called to complete the construction of the new table record.
  100145. */
  100146. SQLITE_PRIVATE void sqlite3StartTable(
  100147. Parse *pParse, /* Parser context */
  100148. Token *pName1, /* First part of the name of the table or view */
  100149. Token *pName2, /* Second part of the name of the table or view */
  100150. int isTemp, /* True if this is a TEMP table */
  100151. int isView, /* True if this is a VIEW */
  100152. int isVirtual, /* True if this is a VIRTUAL table */
  100153. int noErr /* Do nothing if table already exists */
  100154. ){
  100155. Table *pTable;
  100156. char *zName = 0; /* The name of the new table */
  100157. sqlite3 *db = pParse->db;
  100158. Vdbe *v;
  100159. int iDb; /* Database number to create the table in */
  100160. Token *pName; /* Unqualified name of the table to create */
  100161. if( db->init.busy && db->init.newTnum==1 ){
  100162. /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
  100163. iDb = db->init.iDb;
  100164. zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
  100165. pName = pName1;
  100166. }else{
  100167. /* The common case */
  100168. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  100169. if( iDb<0 ) return;
  100170. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  100171. /* If creating a temp table, the name may not be qualified. Unless
  100172. ** the database name is "temp" anyway. */
  100173. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  100174. return;
  100175. }
  100176. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  100177. zName = sqlite3NameFromToken(db, pName);
  100178. if( IN_RENAME_OBJECT ){
  100179. sqlite3RenameTokenMap(pParse, (void*)zName, pName);
  100180. }
  100181. }
  100182. pParse->sNameToken = *pName;
  100183. if( zName==0 ) return;
  100184. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  100185. goto begin_table_error;
  100186. }
  100187. if( db->init.iDb==1 ) isTemp = 1;
  100188. #ifndef SQLITE_OMIT_AUTHORIZATION
  100189. assert( isTemp==0 || isTemp==1 );
  100190. assert( isView==0 || isView==1 );
  100191. {
  100192. static const u8 aCode[] = {
  100193. SQLITE_CREATE_TABLE,
  100194. SQLITE_CREATE_TEMP_TABLE,
  100195. SQLITE_CREATE_VIEW,
  100196. SQLITE_CREATE_TEMP_VIEW
  100197. };
  100198. char *zDb = db->aDb[iDb].zDbSName;
  100199. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  100200. goto begin_table_error;
  100201. }
  100202. if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
  100203. zName, 0, zDb) ){
  100204. goto begin_table_error;
  100205. }
  100206. }
  100207. #endif
  100208. /* Make sure the new table name does not collide with an existing
  100209. ** index or table name in the same database. Issue an error message if
  100210. ** it does. The exception is if the statement being parsed was passed
  100211. ** to an sqlite3_declare_vtab() call. In that case only the column names
  100212. ** and types will be used, so there is no need to test for namespace
  100213. ** collisions.
  100214. */
  100215. if( !IN_SPECIAL_PARSE ){
  100216. char *zDb = db->aDb[iDb].zDbSName;
  100217. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  100218. goto begin_table_error;
  100219. }
  100220. pTable = sqlite3FindTable(db, zName, zDb);
  100221. if( pTable ){
  100222. if( !noErr ){
  100223. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  100224. }else{
  100225. assert( !db->init.busy || CORRUPT_DB );
  100226. sqlite3CodeVerifySchema(pParse, iDb);
  100227. }
  100228. goto begin_table_error;
  100229. }
  100230. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  100231. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  100232. goto begin_table_error;
  100233. }
  100234. }
  100235. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  100236. if( pTable==0 ){
  100237. assert( db->mallocFailed );
  100238. pParse->rc = SQLITE_NOMEM_BKPT;
  100239. pParse->nErr++;
  100240. goto begin_table_error;
  100241. }
  100242. pTable->zName = zName;
  100243. pTable->iPKey = -1;
  100244. pTable->pSchema = db->aDb[iDb].pSchema;
  100245. pTable->nTabRef = 1;
  100246. #ifdef SQLITE_DEFAULT_ROWEST
  100247. pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
  100248. #else
  100249. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  100250. #endif
  100251. assert( pParse->pNewTable==0 );
  100252. pParse->pNewTable = pTable;
  100253. /* If this is the magic sqlite_sequence table used by autoincrement,
  100254. ** then record a pointer to this table in the main database structure
  100255. ** so that INSERT can find the table easily.
  100256. */
  100257. #ifndef SQLITE_OMIT_AUTOINCREMENT
  100258. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  100259. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100260. pTable->pSchema->pSeqTab = pTable;
  100261. }
  100262. #endif
  100263. /* Begin generating the code that will insert the table record into
  100264. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  100265. ** and allocate the record number for the table entry now. Before any
  100266. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  100267. ** indices to be created and the table record must come before the
  100268. ** indices. Hence, the record number for the table must be allocated
  100269. ** now.
  100270. */
  100271. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  100272. int addr1;
  100273. int fileFormat;
  100274. int reg1, reg2, reg3;
  100275. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  100276. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  100277. sqlite3BeginWriteOperation(pParse, 1, iDb);
  100278. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100279. if( isVirtual ){
  100280. sqlite3VdbeAddOp0(v, OP_VBegin);
  100281. }
  100282. #endif
  100283. /* If the file format and encoding in the database have not been set,
  100284. ** set them now.
  100285. */
  100286. reg1 = pParse->regRowid = ++pParse->nMem;
  100287. reg2 = pParse->regRoot = ++pParse->nMem;
  100288. reg3 = ++pParse->nMem;
  100289. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  100290. sqlite3VdbeUsesBtree(v, iDb);
  100291. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  100292. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  100293. 1 : SQLITE_MAX_FILE_FORMAT;
  100294. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
  100295. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
  100296. sqlite3VdbeJumpHere(v, addr1);
  100297. /* This just creates a place-holder record in the sqlite_master table.
  100298. ** The record created does not contain anything yet. It will be replaced
  100299. ** by the real entry in code generated at sqlite3EndTable().
  100300. **
  100301. ** The rowid for the new entry is left in register pParse->regRowid.
  100302. ** The root page number of the new table is left in reg pParse->regRoot.
  100303. ** The rowid and root page number values are needed by the code that
  100304. ** sqlite3EndTable will generate.
  100305. */
  100306. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  100307. if( isView || isVirtual ){
  100308. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  100309. }else
  100310. #endif
  100311. {
  100312. pParse->addrCrTab =
  100313. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
  100314. }
  100315. sqlite3OpenMasterTable(pParse, iDb);
  100316. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  100317. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  100318. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  100319. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  100320. sqlite3VdbeAddOp0(v, OP_Close);
  100321. }
  100322. /* Normal (non-error) return. */
  100323. return;
  100324. /* If an error occurs, we jump here */
  100325. begin_table_error:
  100326. sqlite3DbFree(db, zName);
  100327. return;
  100328. }
  100329. /* Set properties of a table column based on the (magical)
  100330. ** name of the column.
  100331. */
  100332. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  100333. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
  100334. if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
  100335. pCol->colFlags |= COLFLAG_HIDDEN;
  100336. }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
  100337. pTab->tabFlags |= TF_OOOHidden;
  100338. }
  100339. }
  100340. #endif
  100341. /*
  100342. ** Add a new column to the table currently being constructed.
  100343. **
  100344. ** The parser calls this routine once for each column declaration
  100345. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  100346. ** first to get things going. Then this routine is called for each
  100347. ** column.
  100348. */
  100349. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
  100350. Table *p;
  100351. int i;
  100352. char *z;
  100353. char *zType;
  100354. Column *pCol;
  100355. sqlite3 *db = pParse->db;
  100356. if( (p = pParse->pNewTable)==0 ) return;
  100357. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  100358. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  100359. return;
  100360. }
  100361. z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
  100362. if( z==0 ) return;
  100363. if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
  100364. memcpy(z, pName->z, pName->n);
  100365. z[pName->n] = 0;
  100366. sqlite3Dequote(z);
  100367. for(i=0; i<p->nCol; i++){
  100368. if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
  100369. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  100370. sqlite3DbFree(db, z);
  100371. return;
  100372. }
  100373. }
  100374. if( (p->nCol & 0x7)==0 ){
  100375. Column *aNew;
  100376. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  100377. if( aNew==0 ){
  100378. sqlite3DbFree(db, z);
  100379. return;
  100380. }
  100381. p->aCol = aNew;
  100382. }
  100383. pCol = &p->aCol[p->nCol];
  100384. memset(pCol, 0, sizeof(p->aCol[0]));
  100385. pCol->zName = z;
  100386. sqlite3ColumnPropertiesFromName(p, pCol);
  100387. if( pType->n==0 ){
  100388. /* If there is no type specified, columns have the default affinity
  100389. ** 'BLOB' with a default size of 4 bytes. */
  100390. pCol->affinity = SQLITE_AFF_BLOB;
  100391. pCol->szEst = 1;
  100392. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  100393. if( 4>=sqlite3GlobalConfig.szSorterRef ){
  100394. pCol->colFlags |= COLFLAG_SORTERREF;
  100395. }
  100396. #endif
  100397. }else{
  100398. zType = z + sqlite3Strlen30(z) + 1;
  100399. memcpy(zType, pType->z, pType->n);
  100400. zType[pType->n] = 0;
  100401. sqlite3Dequote(zType);
  100402. pCol->affinity = sqlite3AffinityType(zType, pCol);
  100403. pCol->colFlags |= COLFLAG_HASTYPE;
  100404. }
  100405. p->nCol++;
  100406. pParse->constraintName.n = 0;
  100407. }
  100408. /*
  100409. ** This routine is called by the parser while in the middle of
  100410. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  100411. ** been seen on a column. This routine sets the notNull flag on
  100412. ** the column currently under construction.
  100413. */
  100414. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  100415. Table *p;
  100416. Column *pCol;
  100417. p = pParse->pNewTable;
  100418. if( p==0 || NEVER(p->nCol<1) ) return;
  100419. pCol = &p->aCol[p->nCol-1];
  100420. pCol->notNull = (u8)onError;
  100421. p->tabFlags |= TF_HasNotNull;
  100422. /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
  100423. ** on this column. */
  100424. if( pCol->colFlags & COLFLAG_UNIQUE ){
  100425. Index *pIdx;
  100426. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  100427. assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
  100428. if( pIdx->aiColumn[0]==p->nCol-1 ){
  100429. pIdx->uniqNotNull = 1;
  100430. }
  100431. }
  100432. }
  100433. }
  100434. /*
  100435. ** Scan the column type name zType (length nType) and return the
  100436. ** associated affinity type.
  100437. **
  100438. ** This routine does a case-independent search of zType for the
  100439. ** substrings in the following table. If one of the substrings is
  100440. ** found, the corresponding affinity is returned. If zType contains
  100441. ** more than one of the substrings, entries toward the top of
  100442. ** the table take priority. For example, if zType is 'BLOBINT',
  100443. ** SQLITE_AFF_INTEGER is returned.
  100444. **
  100445. ** Substring | Affinity
  100446. ** --------------------------------
  100447. ** 'INT' | SQLITE_AFF_INTEGER
  100448. ** 'CHAR' | SQLITE_AFF_TEXT
  100449. ** 'CLOB' | SQLITE_AFF_TEXT
  100450. ** 'TEXT' | SQLITE_AFF_TEXT
  100451. ** 'BLOB' | SQLITE_AFF_BLOB
  100452. ** 'REAL' | SQLITE_AFF_REAL
  100453. ** 'FLOA' | SQLITE_AFF_REAL
  100454. ** 'DOUB' | SQLITE_AFF_REAL
  100455. **
  100456. ** If none of the substrings in the above table are found,
  100457. ** SQLITE_AFF_NUMERIC is returned.
  100458. */
  100459. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, Column *pCol){
  100460. u32 h = 0;
  100461. char aff = SQLITE_AFF_NUMERIC;
  100462. const char *zChar = 0;
  100463. assert( zIn!=0 );
  100464. while( zIn[0] ){
  100465. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  100466. zIn++;
  100467. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  100468. aff = SQLITE_AFF_TEXT;
  100469. zChar = zIn;
  100470. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  100471. aff = SQLITE_AFF_TEXT;
  100472. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  100473. aff = SQLITE_AFF_TEXT;
  100474. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  100475. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  100476. aff = SQLITE_AFF_BLOB;
  100477. if( zIn[0]=='(' ) zChar = zIn;
  100478. #ifndef SQLITE_OMIT_FLOATING_POINT
  100479. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  100480. && aff==SQLITE_AFF_NUMERIC ){
  100481. aff = SQLITE_AFF_REAL;
  100482. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  100483. && aff==SQLITE_AFF_NUMERIC ){
  100484. aff = SQLITE_AFF_REAL;
  100485. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  100486. && aff==SQLITE_AFF_NUMERIC ){
  100487. aff = SQLITE_AFF_REAL;
  100488. #endif
  100489. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  100490. aff = SQLITE_AFF_INTEGER;
  100491. break;
  100492. }
  100493. }
  100494. /* If pCol is not NULL, store an estimate of the field size. The
  100495. ** estimate is scaled so that the size of an integer is 1. */
  100496. if( pCol ){
  100497. int v = 0; /* default size is approx 4 bytes */
  100498. if( aff<SQLITE_AFF_NUMERIC ){
  100499. if( zChar ){
  100500. while( zChar[0] ){
  100501. if( sqlite3Isdigit(zChar[0]) ){
  100502. /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  100503. sqlite3GetInt32(zChar, &v);
  100504. break;
  100505. }
  100506. zChar++;
  100507. }
  100508. }else{
  100509. v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  100510. }
  100511. }
  100512. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  100513. if( v>=sqlite3GlobalConfig.szSorterRef ){
  100514. pCol->colFlags |= COLFLAG_SORTERREF;
  100515. }
  100516. #endif
  100517. v = v/4 + 1;
  100518. if( v>255 ) v = 255;
  100519. pCol->szEst = v;
  100520. }
  100521. return aff;
  100522. }
  100523. /*
  100524. ** The expression is the default value for the most recently added column
  100525. ** of the table currently under construction.
  100526. **
  100527. ** Default value expressions must be constant. Raise an exception if this
  100528. ** is not the case.
  100529. **
  100530. ** This routine is called by the parser while in the middle of
  100531. ** parsing a CREATE TABLE statement.
  100532. */
  100533. SQLITE_PRIVATE void sqlite3AddDefaultValue(
  100534. Parse *pParse, /* Parsing context */
  100535. Expr *pExpr, /* The parsed expression of the default value */
  100536. const char *zStart, /* Start of the default value text */
  100537. const char *zEnd /* First character past end of defaut value text */
  100538. ){
  100539. Table *p;
  100540. Column *pCol;
  100541. sqlite3 *db = pParse->db;
  100542. p = pParse->pNewTable;
  100543. if( p!=0 ){
  100544. pCol = &(p->aCol[p->nCol-1]);
  100545. if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
  100546. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  100547. pCol->zName);
  100548. }else{
  100549. /* A copy of pExpr is used instead of the original, as pExpr contains
  100550. ** tokens that point to volatile memory.
  100551. */
  100552. Expr x;
  100553. sqlite3ExprDelete(db, pCol->pDflt);
  100554. memset(&x, 0, sizeof(x));
  100555. x.op = TK_SPAN;
  100556. x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
  100557. x.pLeft = pExpr;
  100558. x.flags = EP_Skip;
  100559. pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
  100560. sqlite3DbFree(db, x.u.zToken);
  100561. }
  100562. }
  100563. if( IN_RENAME_OBJECT ){
  100564. sqlite3RenameExprUnmap(pParse, pExpr);
  100565. }
  100566. sqlite3ExprDelete(db, pExpr);
  100567. }
  100568. /*
  100569. ** Backwards Compatibility Hack:
  100570. **
  100571. ** Historical versions of SQLite accepted strings as column names in
  100572. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  100573. **
  100574. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  100575. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  100576. **
  100577. ** This is goofy. But to preserve backwards compatibility we continue to
  100578. ** accept it. This routine does the necessary conversion. It converts
  100579. ** the expression given in its argument from a TK_STRING into a TK_ID
  100580. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  100581. ** If the epxression is anything other than TK_STRING, the expression is
  100582. ** unchanged.
  100583. */
  100584. static void sqlite3StringToId(Expr *p){
  100585. if( p->op==TK_STRING ){
  100586. p->op = TK_ID;
  100587. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  100588. p->pLeft->op = TK_ID;
  100589. }
  100590. }
  100591. /*
  100592. ** Designate the PRIMARY KEY for the table. pList is a list of names
  100593. ** of columns that form the primary key. If pList is NULL, then the
  100594. ** most recently added column of the table is the primary key.
  100595. **
  100596. ** A table can have at most one primary key. If the table already has
  100597. ** a primary key (and this is the second primary key) then create an
  100598. ** error.
  100599. **
  100600. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  100601. ** then we will try to use that column as the rowid. Set the Table.iPKey
  100602. ** field of the table under construction to be the index of the
  100603. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  100604. ** no INTEGER PRIMARY KEY.
  100605. **
  100606. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  100607. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  100608. */
  100609. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  100610. Parse *pParse, /* Parsing context */
  100611. ExprList *pList, /* List of field names to be indexed */
  100612. int onError, /* What to do with a uniqueness conflict */
  100613. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  100614. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  100615. ){
  100616. Table *pTab = pParse->pNewTable;
  100617. Column *pCol = 0;
  100618. int iCol = -1, i;
  100619. int nTerm;
  100620. if( pTab==0 ) goto primary_key_exit;
  100621. if( pTab->tabFlags & TF_HasPrimaryKey ){
  100622. sqlite3ErrorMsg(pParse,
  100623. "table \"%s\" has more than one primary key", pTab->zName);
  100624. goto primary_key_exit;
  100625. }
  100626. pTab->tabFlags |= TF_HasPrimaryKey;
  100627. if( pList==0 ){
  100628. iCol = pTab->nCol - 1;
  100629. pCol = &pTab->aCol[iCol];
  100630. pCol->colFlags |= COLFLAG_PRIMKEY;
  100631. nTerm = 1;
  100632. }else{
  100633. nTerm = pList->nExpr;
  100634. for(i=0; i<nTerm; i++){
  100635. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  100636. assert( pCExpr!=0 );
  100637. sqlite3StringToId(pCExpr);
  100638. if( pCExpr->op==TK_ID ){
  100639. const char *zCName = pCExpr->u.zToken;
  100640. for(iCol=0; iCol<pTab->nCol; iCol++){
  100641. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  100642. pCol = &pTab->aCol[iCol];
  100643. pCol->colFlags |= COLFLAG_PRIMKEY;
  100644. break;
  100645. }
  100646. }
  100647. }
  100648. }
  100649. }
  100650. if( nTerm==1
  100651. && pCol
  100652. && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
  100653. && sortOrder!=SQLITE_SO_DESC
  100654. ){
  100655. if( IN_RENAME_OBJECT && pList ){
  100656. sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pList->a[0].pExpr);
  100657. }
  100658. pTab->iPKey = iCol;
  100659. pTab->keyConf = (u8)onError;
  100660. assert( autoInc==0 || autoInc==1 );
  100661. pTab->tabFlags |= autoInc*TF_Autoincrement;
  100662. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  100663. }else if( autoInc ){
  100664. #ifndef SQLITE_OMIT_AUTOINCREMENT
  100665. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  100666. "INTEGER PRIMARY KEY");
  100667. #endif
  100668. }else{
  100669. sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  100670. 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
  100671. pList = 0;
  100672. }
  100673. primary_key_exit:
  100674. sqlite3ExprListDelete(pParse->db, pList);
  100675. return;
  100676. }
  100677. /*
  100678. ** Add a new CHECK constraint to the table currently under construction.
  100679. */
  100680. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  100681. Parse *pParse, /* Parsing context */
  100682. Expr *pCheckExpr /* The check expression */
  100683. ){
  100684. #ifndef SQLITE_OMIT_CHECK
  100685. Table *pTab = pParse->pNewTable;
  100686. sqlite3 *db = pParse->db;
  100687. if( pTab && !IN_DECLARE_VTAB
  100688. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  100689. ){
  100690. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  100691. if( pParse->constraintName.n ){
  100692. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  100693. }
  100694. }else
  100695. #endif
  100696. {
  100697. sqlite3ExprDelete(pParse->db, pCheckExpr);
  100698. }
  100699. }
  100700. /*
  100701. ** Set the collation function of the most recently parsed table column
  100702. ** to the CollSeq given.
  100703. */
  100704. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  100705. Table *p;
  100706. int i;
  100707. char *zColl; /* Dequoted name of collation sequence */
  100708. sqlite3 *db;
  100709. if( (p = pParse->pNewTable)==0 ) return;
  100710. i = p->nCol-1;
  100711. db = pParse->db;
  100712. zColl = sqlite3NameFromToken(db, pToken);
  100713. if( !zColl ) return;
  100714. if( sqlite3LocateCollSeq(pParse, zColl) ){
  100715. Index *pIdx;
  100716. sqlite3DbFree(db, p->aCol[i].zColl);
  100717. p->aCol[i].zColl = zColl;
  100718. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  100719. ** then an index may have been created on this column before the
  100720. ** collation type was added. Correct this if it is the case.
  100721. */
  100722. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  100723. assert( pIdx->nKeyCol==1 );
  100724. if( pIdx->aiColumn[0]==i ){
  100725. pIdx->azColl[0] = p->aCol[i].zColl;
  100726. }
  100727. }
  100728. }else{
  100729. sqlite3DbFree(db, zColl);
  100730. }
  100731. }
  100732. /*
  100733. ** This function returns the collation sequence for database native text
  100734. ** encoding identified by the string zName, length nName.
  100735. **
  100736. ** If the requested collation sequence is not available, or not available
  100737. ** in the database native encoding, the collation factory is invoked to
  100738. ** request it. If the collation factory does not supply such a sequence,
  100739. ** and the sequence is available in another text encoding, then that is
  100740. ** returned instead.
  100741. **
  100742. ** If no versions of the requested collations sequence are available, or
  100743. ** another error occurs, NULL is returned and an error message written into
  100744. ** pParse.
  100745. **
  100746. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  100747. ** invokes the collation factory if the named collation cannot be found
  100748. ** and generates an error message.
  100749. **
  100750. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  100751. */
  100752. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  100753. sqlite3 *db = pParse->db;
  100754. u8 enc = ENC(db);
  100755. u8 initbusy = db->init.busy;
  100756. CollSeq *pColl;
  100757. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  100758. if( !initbusy && (!pColl || !pColl->xCmp) ){
  100759. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  100760. }
  100761. return pColl;
  100762. }
  100763. /*
  100764. ** Generate code that will increment the schema cookie.
  100765. **
  100766. ** The schema cookie is used to determine when the schema for the
  100767. ** database changes. After each schema change, the cookie value
  100768. ** changes. When a process first reads the schema it records the
  100769. ** cookie. Thereafter, whenever it goes to access the database,
  100770. ** it checks the cookie to make sure the schema has not changed
  100771. ** since it was last read.
  100772. **
  100773. ** This plan is not completely bullet-proof. It is possible for
  100774. ** the schema to change multiple times and for the cookie to be
  100775. ** set back to prior value. But schema changes are infrequent
  100776. ** and the probability of hitting the same cookie value is only
  100777. ** 1 chance in 2^32. So we're safe enough.
  100778. **
  100779. ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
  100780. ** the schema-version whenever the schema changes.
  100781. */
  100782. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  100783. sqlite3 *db = pParse->db;
  100784. Vdbe *v = pParse->pVdbe;
  100785. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100786. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
  100787. (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
  100788. }
  100789. /*
  100790. ** Measure the number of characters needed to output the given
  100791. ** identifier. The number returned includes any quotes used
  100792. ** but does not include the null terminator.
  100793. **
  100794. ** The estimate is conservative. It might be larger that what is
  100795. ** really needed.
  100796. */
  100797. static int identLength(const char *z){
  100798. int n;
  100799. for(n=0; *z; n++, z++){
  100800. if( *z=='"' ){ n++; }
  100801. }
  100802. return n + 2;
  100803. }
  100804. /*
  100805. ** The first parameter is a pointer to an output buffer. The second
  100806. ** parameter is a pointer to an integer that contains the offset at
  100807. ** which to write into the output buffer. This function copies the
  100808. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  100809. ** to the specified offset in the buffer and updates *pIdx to refer
  100810. ** to the first byte after the last byte written before returning.
  100811. **
  100812. ** If the string zSignedIdent consists entirely of alpha-numeric
  100813. ** characters, does not begin with a digit and is not an SQL keyword,
  100814. ** then it is copied to the output buffer exactly as it is. Otherwise,
  100815. ** it is quoted using double-quotes.
  100816. */
  100817. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  100818. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  100819. int i, j, needQuote;
  100820. i = *pIdx;
  100821. for(j=0; zIdent[j]; j++){
  100822. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  100823. }
  100824. needQuote = sqlite3Isdigit(zIdent[0])
  100825. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  100826. || zIdent[j]!=0
  100827. || j==0;
  100828. if( needQuote ) z[i++] = '"';
  100829. for(j=0; zIdent[j]; j++){
  100830. z[i++] = zIdent[j];
  100831. if( zIdent[j]=='"' ) z[i++] = '"';
  100832. }
  100833. if( needQuote ) z[i++] = '"';
  100834. z[i] = 0;
  100835. *pIdx = i;
  100836. }
  100837. /*
  100838. ** Generate a CREATE TABLE statement appropriate for the given
  100839. ** table. Memory to hold the text of the statement is obtained
  100840. ** from sqliteMalloc() and must be freed by the calling function.
  100841. */
  100842. static char *createTableStmt(sqlite3 *db, Table *p){
  100843. int i, k, n;
  100844. char *zStmt;
  100845. char *zSep, *zSep2, *zEnd;
  100846. Column *pCol;
  100847. n = 0;
  100848. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  100849. n += identLength(pCol->zName) + 5;
  100850. }
  100851. n += identLength(p->zName);
  100852. if( n<50 ){
  100853. zSep = "";
  100854. zSep2 = ",";
  100855. zEnd = ")";
  100856. }else{
  100857. zSep = "\n ";
  100858. zSep2 = ",\n ";
  100859. zEnd = "\n)";
  100860. }
  100861. n += 35 + 6*p->nCol;
  100862. zStmt = sqlite3DbMallocRaw(0, n);
  100863. if( zStmt==0 ){
  100864. sqlite3OomFault(db);
  100865. return 0;
  100866. }
  100867. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  100868. k = sqlite3Strlen30(zStmt);
  100869. identPut(zStmt, &k, p->zName);
  100870. zStmt[k++] = '(';
  100871. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  100872. static const char * const azType[] = {
  100873. /* SQLITE_AFF_BLOB */ "",
  100874. /* SQLITE_AFF_TEXT */ " TEXT",
  100875. /* SQLITE_AFF_NUMERIC */ " NUM",
  100876. /* SQLITE_AFF_INTEGER */ " INT",
  100877. /* SQLITE_AFF_REAL */ " REAL"
  100878. };
  100879. int len;
  100880. const char *zType;
  100881. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  100882. k += sqlite3Strlen30(&zStmt[k]);
  100883. zSep = zSep2;
  100884. identPut(zStmt, &k, pCol->zName);
  100885. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  100886. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  100887. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  100888. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  100889. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  100890. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  100891. testcase( pCol->affinity==SQLITE_AFF_REAL );
  100892. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  100893. len = sqlite3Strlen30(zType);
  100894. assert( pCol->affinity==SQLITE_AFF_BLOB
  100895. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  100896. memcpy(&zStmt[k], zType, len);
  100897. k += len;
  100898. assert( k<=n );
  100899. }
  100900. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  100901. return zStmt;
  100902. }
  100903. /*
  100904. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  100905. ** on success and SQLITE_NOMEM on an OOM error.
  100906. */
  100907. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  100908. char *zExtra;
  100909. int nByte;
  100910. if( pIdx->nColumn>=N ) return SQLITE_OK;
  100911. assert( pIdx->isResized==0 );
  100912. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  100913. zExtra = sqlite3DbMallocZero(db, nByte);
  100914. if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
  100915. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  100916. pIdx->azColl = (const char**)zExtra;
  100917. zExtra += sizeof(char*)*N;
  100918. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  100919. pIdx->aiColumn = (i16*)zExtra;
  100920. zExtra += sizeof(i16)*N;
  100921. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  100922. pIdx->aSortOrder = (u8*)zExtra;
  100923. pIdx->nColumn = N;
  100924. pIdx->isResized = 1;
  100925. return SQLITE_OK;
  100926. }
  100927. /*
  100928. ** Estimate the total row width for a table.
  100929. */
  100930. static void estimateTableWidth(Table *pTab){
  100931. unsigned wTable = 0;
  100932. const Column *pTabCol;
  100933. int i;
  100934. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  100935. wTable += pTabCol->szEst;
  100936. }
  100937. if( pTab->iPKey<0 ) wTable++;
  100938. pTab->szTabRow = sqlite3LogEst(wTable*4);
  100939. }
  100940. /*
  100941. ** Estimate the average size of a row for an index.
  100942. */
  100943. static void estimateIndexWidth(Index *pIdx){
  100944. unsigned wIndex = 0;
  100945. int i;
  100946. const Column *aCol = pIdx->pTable->aCol;
  100947. for(i=0; i<pIdx->nColumn; i++){
  100948. i16 x = pIdx->aiColumn[i];
  100949. assert( x<pIdx->pTable->nCol );
  100950. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  100951. }
  100952. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  100953. }
  100954. /* Return true if value x is found any of the first nCol entries of aiCol[]
  100955. */
  100956. static int hasColumn(const i16 *aiCol, int nCol, int x){
  100957. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  100958. return 0;
  100959. }
  100960. /* Recompute the colNotIdxed field of the Index.
  100961. **
  100962. ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
  100963. ** columns that are within the first 63 columns of the table. The
  100964. ** high-order bit of colNotIdxed is always 1. All unindexed columns
  100965. ** of the table have a 1.
  100966. **
  100967. ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
  100968. ** to determine if the index is covering index.
  100969. */
  100970. static void recomputeColumnsNotIndexed(Index *pIdx){
  100971. Bitmask m = 0;
  100972. int j;
  100973. for(j=pIdx->nColumn-1; j>=0; j--){
  100974. int x = pIdx->aiColumn[j];
  100975. if( x>=0 ){
  100976. testcase( x==BMS-1 );
  100977. testcase( x==BMS-2 );
  100978. if( x<BMS-1 ) m |= MASKBIT(x);
  100979. }
  100980. }
  100981. pIdx->colNotIdxed = ~m;
  100982. assert( (pIdx->colNotIdxed>>63)==1 );
  100983. }
  100984. /*
  100985. ** This routine runs at the end of parsing a CREATE TABLE statement that
  100986. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  100987. ** internal schema data structures and the generated VDBE code so that they
  100988. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  100989. ** Changes include:
  100990. **
  100991. ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  100992. ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
  100993. ** into BTREE_BLOBKEY.
  100994. ** (3) Bypass the creation of the sqlite_master table entry
  100995. ** for the PRIMARY KEY as the primary key index is now
  100996. ** identified by the sqlite_master table entry of the table itself.
  100997. ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
  100998. ** schema to the rootpage from the main table.
  100999. ** (5) Add all table columns to the PRIMARY KEY Index object
  101000. ** so that the PRIMARY KEY is a covering index. The surplus
  101001. ** columns are part of KeyInfo.nAllField and are not used for
  101002. ** sorting or lookup or uniqueness checks.
  101003. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  101004. ** indices with the PRIMARY KEY columns.
  101005. **
  101006. ** For virtual tables, only (1) is performed.
  101007. */
  101008. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  101009. Index *pIdx;
  101010. Index *pPk;
  101011. int nPk;
  101012. int i, j;
  101013. sqlite3 *db = pParse->db;
  101014. Vdbe *v = pParse->pVdbe;
  101015. /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
  101016. */
  101017. if( !db->init.imposterTable ){
  101018. for(i=0; i<pTab->nCol; i++){
  101019. if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
  101020. pTab->aCol[i].notNull = OE_Abort;
  101021. }
  101022. }
  101023. }
  101024. /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
  101025. ** into BTREE_BLOBKEY.
  101026. */
  101027. if( pParse->addrCrTab ){
  101028. assert( v );
  101029. sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
  101030. }
  101031. /* Locate the PRIMARY KEY index. Or, if this table was originally
  101032. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  101033. */
  101034. if( pTab->iPKey>=0 ){
  101035. ExprList *pList;
  101036. Token ipkToken;
  101037. sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
  101038. pList = sqlite3ExprListAppend(pParse, 0,
  101039. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  101040. if( pList==0 ) return;
  101041. pList->a[0].sortOrder = pParse->iPkSortOrder;
  101042. assert( pParse->pNewTable==pTab );
  101043. sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
  101044. SQLITE_IDXTYPE_PRIMARYKEY);
  101045. if( db->mallocFailed || pParse->nErr ) return;
  101046. pPk = sqlite3PrimaryKeyIndex(pTab);
  101047. pTab->iPKey = -1;
  101048. }else{
  101049. pPk = sqlite3PrimaryKeyIndex(pTab);
  101050. /*
  101051. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  101052. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  101053. ** code assumes the PRIMARY KEY contains no repeated columns.
  101054. */
  101055. for(i=j=1; i<pPk->nKeyCol; i++){
  101056. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  101057. pPk->nColumn--;
  101058. }else{
  101059. pPk->aiColumn[j++] = pPk->aiColumn[i];
  101060. }
  101061. }
  101062. pPk->nKeyCol = j;
  101063. }
  101064. assert( pPk!=0 );
  101065. pPk->isCovering = 1;
  101066. if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
  101067. nPk = pPk->nKeyCol;
  101068. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  101069. ** table entry. This is only required if currently generating VDBE
  101070. ** code for a CREATE TABLE (not when parsing one as part of reading
  101071. ** a database schema). */
  101072. if( v && pPk->tnum>0 ){
  101073. assert( db->init.busy==0 );
  101074. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  101075. }
  101076. /* The root page of the PRIMARY KEY is the table root page */
  101077. pPk->tnum = pTab->tnum;
  101078. /* Update the in-memory representation of all UNIQUE indices by converting
  101079. ** the final rowid column into one or more columns of the PRIMARY KEY.
  101080. */
  101081. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  101082. int n;
  101083. if( IsPrimaryKeyIndex(pIdx) ) continue;
  101084. for(i=n=0; i<nPk; i++){
  101085. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  101086. }
  101087. if( n==0 ){
  101088. /* This index is a superset of the primary key */
  101089. pIdx->nColumn = pIdx->nKeyCol;
  101090. continue;
  101091. }
  101092. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  101093. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  101094. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  101095. pIdx->aiColumn[j] = pPk->aiColumn[i];
  101096. pIdx->azColl[j] = pPk->azColl[i];
  101097. j++;
  101098. }
  101099. }
  101100. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  101101. assert( pIdx->nColumn>=j );
  101102. }
  101103. /* Add all table columns to the PRIMARY KEY index
  101104. */
  101105. if( nPk<pTab->nCol ){
  101106. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  101107. for(i=0, j=nPk; i<pTab->nCol; i++){
  101108. if( !hasColumn(pPk->aiColumn, j, i) ){
  101109. assert( j<pPk->nColumn );
  101110. pPk->aiColumn[j] = i;
  101111. pPk->azColl[j] = sqlite3StrBINARY;
  101112. j++;
  101113. }
  101114. }
  101115. assert( pPk->nColumn==j );
  101116. assert( pTab->nCol==j );
  101117. }else{
  101118. pPk->nColumn = pTab->nCol;
  101119. }
  101120. recomputeColumnsNotIndexed(pPk);
  101121. }
  101122. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101123. /*
  101124. ** Return true if zName is a shadow table name in the current database
  101125. ** connection.
  101126. **
  101127. ** zName is temporarily modified while this routine is running, but is
  101128. ** restored to its original value prior to this routine returning.
  101129. */
  101130. static int isShadowTableName(sqlite3 *db, char *zName){
  101131. char *zTail; /* Pointer to the last "_" in zName */
  101132. Table *pTab; /* Table that zName is a shadow of */
  101133. Module *pMod; /* Module for the virtual table */
  101134. zTail = strrchr(zName, '_');
  101135. if( zTail==0 ) return 0;
  101136. *zTail = 0;
  101137. pTab = sqlite3FindTable(db, zName, 0);
  101138. *zTail = '_';
  101139. if( pTab==0 ) return 0;
  101140. if( !IsVirtual(pTab) ) return 0;
  101141. pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
  101142. if( pMod==0 ) return 0;
  101143. if( pMod->pModule->iVersion<3 ) return 0;
  101144. if( pMod->pModule->xShadowName==0 ) return 0;
  101145. return pMod->pModule->xShadowName(zTail+1);
  101146. }
  101147. #else
  101148. # define isShadowTableName(x,y) 0
  101149. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  101150. /*
  101151. ** This routine is called to report the final ")" that terminates
  101152. ** a CREATE TABLE statement.
  101153. **
  101154. ** The table structure that other action routines have been building
  101155. ** is added to the internal hash tables, assuming no errors have
  101156. ** occurred.
  101157. **
  101158. ** An entry for the table is made in the master table on disk, unless
  101159. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  101160. ** it means we are reading the sqlite_master table because we just
  101161. ** connected to the database or because the sqlite_master table has
  101162. ** recently changed, so the entry for this table already exists in
  101163. ** the sqlite_master table. We do not want to create it again.
  101164. **
  101165. ** If the pSelect argument is not NULL, it means that this routine
  101166. ** was called to create a table generated from a
  101167. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  101168. ** the new table will match the result set of the SELECT.
  101169. */
  101170. SQLITE_PRIVATE void sqlite3EndTable(
  101171. Parse *pParse, /* Parse context */
  101172. Token *pCons, /* The ',' token after the last column defn. */
  101173. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  101174. u8 tabOpts, /* Extra table options. Usually 0. */
  101175. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  101176. ){
  101177. Table *p; /* The new table */
  101178. sqlite3 *db = pParse->db; /* The database connection */
  101179. int iDb; /* Database in which the table lives */
  101180. Index *pIdx; /* An implied index of the table */
  101181. if( pEnd==0 && pSelect==0 ){
  101182. return;
  101183. }
  101184. assert( !db->mallocFailed );
  101185. p = pParse->pNewTable;
  101186. if( p==0 ) return;
  101187. if( pSelect==0 && isShadowTableName(db, p->zName) ){
  101188. p->tabFlags |= TF_Shadow;
  101189. }
  101190. /* If the db->init.busy is 1 it means we are reading the SQL off the
  101191. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  101192. ** So do not write to the disk again. Extract the root page number
  101193. ** for the table from the db->init.newTnum field. (The page number
  101194. ** should have been put there by the sqliteOpenCb routine.)
  101195. **
  101196. ** If the root page number is 1, that means this is the sqlite_master
  101197. ** table itself. So mark it read-only.
  101198. */
  101199. if( db->init.busy ){
  101200. if( pSelect ){
  101201. sqlite3ErrorMsg(pParse, "");
  101202. return;
  101203. }
  101204. p->tnum = db->init.newTnum;
  101205. if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
  101206. }
  101207. /* Special processing for WITHOUT ROWID Tables */
  101208. if( tabOpts & TF_WithoutRowid ){
  101209. if( (p->tabFlags & TF_Autoincrement) ){
  101210. sqlite3ErrorMsg(pParse,
  101211. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  101212. return;
  101213. }
  101214. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  101215. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  101216. }else{
  101217. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  101218. convertToWithoutRowidTable(pParse, p);
  101219. }
  101220. }
  101221. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  101222. #ifndef SQLITE_OMIT_CHECK
  101223. /* Resolve names in all CHECK constraint expressions.
  101224. */
  101225. if( p->pCheck ){
  101226. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  101227. }
  101228. #endif /* !defined(SQLITE_OMIT_CHECK) */
  101229. /* Estimate the average row size for the table and for all implied indices */
  101230. estimateTableWidth(p);
  101231. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  101232. estimateIndexWidth(pIdx);
  101233. }
  101234. /* If not initializing, then create a record for the new table
  101235. ** in the SQLITE_MASTER table of the database.
  101236. **
  101237. ** If this is a TEMPORARY table, write the entry into the auxiliary
  101238. ** file instead of into the main database file.
  101239. */
  101240. if( !db->init.busy ){
  101241. int n;
  101242. Vdbe *v;
  101243. char *zType; /* "view" or "table" */
  101244. char *zType2; /* "VIEW" or "TABLE" */
  101245. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  101246. v = sqlite3GetVdbe(pParse);
  101247. if( NEVER(v==0) ) return;
  101248. sqlite3VdbeAddOp1(v, OP_Close, 0);
  101249. /*
  101250. ** Initialize zType for the new view or table.
  101251. */
  101252. if( p->pSelect==0 ){
  101253. /* A regular table */
  101254. zType = "table";
  101255. zType2 = "TABLE";
  101256. #ifndef SQLITE_OMIT_VIEW
  101257. }else{
  101258. /* A view */
  101259. zType = "view";
  101260. zType2 = "VIEW";
  101261. #endif
  101262. }
  101263. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  101264. ** statement to populate the new table. The root-page number for the
  101265. ** new table is in register pParse->regRoot.
  101266. **
  101267. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  101268. ** suitable state to query for the column names and types to be used
  101269. ** by the new table.
  101270. **
  101271. ** A shared-cache write-lock is not required to write to the new table,
  101272. ** as a schema-lock must have already been obtained to create it. Since
  101273. ** a schema-lock excludes all other database users, the write-lock would
  101274. ** be redundant.
  101275. */
  101276. if( pSelect ){
  101277. SelectDest dest; /* Where the SELECT should store results */
  101278. int regYield; /* Register holding co-routine entry-point */
  101279. int addrTop; /* Top of the co-routine */
  101280. int regRec; /* A record to be insert into the new table */
  101281. int regRowid; /* Rowid of the next row to insert */
  101282. int addrInsLoop; /* Top of the loop for inserting rows */
  101283. Table *pSelTab; /* A table that describes the SELECT results */
  101284. regYield = ++pParse->nMem;
  101285. regRec = ++pParse->nMem;
  101286. regRowid = ++pParse->nMem;
  101287. assert(pParse->nTab==1);
  101288. sqlite3MayAbort(pParse);
  101289. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  101290. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  101291. pParse->nTab = 2;
  101292. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  101293. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  101294. if( pParse->nErr ) return;
  101295. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  101296. if( pSelTab==0 ) return;
  101297. assert( p->aCol==0 );
  101298. p->nCol = pSelTab->nCol;
  101299. p->aCol = pSelTab->aCol;
  101300. pSelTab->nCol = 0;
  101301. pSelTab->aCol = 0;
  101302. sqlite3DeleteTable(db, pSelTab);
  101303. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  101304. sqlite3Select(pParse, pSelect, &dest);
  101305. if( pParse->nErr ) return;
  101306. sqlite3VdbeEndCoroutine(v, regYield);
  101307. sqlite3VdbeJumpHere(v, addrTop - 1);
  101308. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  101309. VdbeCoverage(v);
  101310. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  101311. sqlite3TableAffinity(v, p, 0);
  101312. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  101313. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  101314. sqlite3VdbeGoto(v, addrInsLoop);
  101315. sqlite3VdbeJumpHere(v, addrInsLoop);
  101316. sqlite3VdbeAddOp1(v, OP_Close, 1);
  101317. }
  101318. /* Compute the complete text of the CREATE statement */
  101319. if( pSelect ){
  101320. zStmt = createTableStmt(db, p);
  101321. }else{
  101322. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  101323. n = (int)(pEnd2->z - pParse->sNameToken.z);
  101324. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  101325. zStmt = sqlite3MPrintf(db,
  101326. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  101327. );
  101328. }
  101329. /* A slot for the record has already been allocated in the
  101330. ** SQLITE_MASTER table. We just need to update that slot with all
  101331. ** the information we've collected.
  101332. */
  101333. sqlite3NestedParse(pParse,
  101334. "UPDATE %Q.%s "
  101335. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  101336. "WHERE rowid=#%d",
  101337. db->aDb[iDb].zDbSName, MASTER_NAME,
  101338. zType,
  101339. p->zName,
  101340. p->zName,
  101341. pParse->regRoot,
  101342. zStmt,
  101343. pParse->regRowid
  101344. );
  101345. sqlite3DbFree(db, zStmt);
  101346. sqlite3ChangeCookie(pParse, iDb);
  101347. #ifndef SQLITE_OMIT_AUTOINCREMENT
  101348. /* Check to see if we need to create an sqlite_sequence table for
  101349. ** keeping track of autoincrement keys.
  101350. */
  101351. if( (p->tabFlags & TF_Autoincrement)!=0 ){
  101352. Db *pDb = &db->aDb[iDb];
  101353. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101354. if( pDb->pSchema->pSeqTab==0 ){
  101355. sqlite3NestedParse(pParse,
  101356. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  101357. pDb->zDbSName
  101358. );
  101359. }
  101360. }
  101361. #endif
  101362. /* Reparse everything to update our internal data structures */
  101363. sqlite3VdbeAddParseSchemaOp(v, iDb,
  101364. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  101365. }
  101366. /* Add the table to the in-memory representation of the database.
  101367. */
  101368. if( db->init.busy ){
  101369. Table *pOld;
  101370. Schema *pSchema = p->pSchema;
  101371. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101372. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  101373. if( pOld ){
  101374. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  101375. sqlite3OomFault(db);
  101376. return;
  101377. }
  101378. pParse->pNewTable = 0;
  101379. db->mDbFlags |= DBFLAG_SchemaChange;
  101380. #ifndef SQLITE_OMIT_ALTERTABLE
  101381. if( !p->pSelect ){
  101382. const char *zName = (const char *)pParse->sNameToken.z;
  101383. int nName;
  101384. assert( !pSelect && pCons && pEnd );
  101385. if( pCons->z==0 ){
  101386. pCons = pEnd;
  101387. }
  101388. nName = (int)((const char *)pCons->z - zName);
  101389. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  101390. }
  101391. #endif
  101392. }
  101393. }
  101394. #ifndef SQLITE_OMIT_VIEW
  101395. /*
  101396. ** The parser calls this routine in order to create a new VIEW
  101397. */
  101398. SQLITE_PRIVATE void sqlite3CreateView(
  101399. Parse *pParse, /* The parsing context */
  101400. Token *pBegin, /* The CREATE token that begins the statement */
  101401. Token *pName1, /* The token that holds the name of the view */
  101402. Token *pName2, /* The token that holds the name of the view */
  101403. ExprList *pCNames, /* Optional list of view column names */
  101404. Select *pSelect, /* A SELECT statement that will become the new view */
  101405. int isTemp, /* TRUE for a TEMPORARY view */
  101406. int noErr /* Suppress error messages if VIEW already exists */
  101407. ){
  101408. Table *p;
  101409. int n;
  101410. const char *z;
  101411. Token sEnd;
  101412. DbFixer sFix;
  101413. Token *pName = 0;
  101414. int iDb;
  101415. sqlite3 *db = pParse->db;
  101416. if( pParse->nVar>0 ){
  101417. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  101418. goto create_view_fail;
  101419. }
  101420. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  101421. p = pParse->pNewTable;
  101422. if( p==0 || pParse->nErr ) goto create_view_fail;
  101423. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  101424. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  101425. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  101426. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  101427. /* Make a copy of the entire SELECT statement that defines the view.
  101428. ** This will force all the Expr.token.z values to be dynamically
  101429. ** allocated rather than point to the input string - which means that
  101430. ** they will persist after the current sqlite3_exec() call returns.
  101431. */
  101432. if( IN_RENAME_OBJECT ){
  101433. p->pSelect = pSelect;
  101434. pSelect = 0;
  101435. }else{
  101436. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  101437. }
  101438. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  101439. if( db->mallocFailed ) goto create_view_fail;
  101440. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  101441. ** the end.
  101442. */
  101443. sEnd = pParse->sLastToken;
  101444. assert( sEnd.z[0]!=0 || sEnd.n==0 );
  101445. if( sEnd.z[0]!=';' ){
  101446. sEnd.z += sEnd.n;
  101447. }
  101448. sEnd.n = 0;
  101449. n = (int)(sEnd.z - pBegin->z);
  101450. assert( n>0 );
  101451. z = pBegin->z;
  101452. while( sqlite3Isspace(z[n-1]) ){ n--; }
  101453. sEnd.z = &z[n-1];
  101454. sEnd.n = 1;
  101455. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  101456. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  101457. create_view_fail:
  101458. sqlite3SelectDelete(db, pSelect);
  101459. if( IN_RENAME_OBJECT ){
  101460. sqlite3RenameExprlistUnmap(pParse, pCNames);
  101461. }
  101462. sqlite3ExprListDelete(db, pCNames);
  101463. return;
  101464. }
  101465. #endif /* SQLITE_OMIT_VIEW */
  101466. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  101467. /*
  101468. ** The Table structure pTable is really a VIEW. Fill in the names of
  101469. ** the columns of the view in the pTable structure. Return the number
  101470. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  101471. */
  101472. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  101473. Table *pSelTab; /* A fake table from which we get the result set */
  101474. Select *pSel; /* Copy of the SELECT that implements the view */
  101475. int nErr = 0; /* Number of errors encountered */
  101476. int n; /* Temporarily holds the number of cursors assigned */
  101477. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  101478. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101479. int rc;
  101480. #endif
  101481. #ifndef SQLITE_OMIT_AUTHORIZATION
  101482. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  101483. #endif
  101484. assert( pTable );
  101485. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101486. db->nSchemaLock++;
  101487. rc = sqlite3VtabCallConnect(pParse, pTable);
  101488. db->nSchemaLock--;
  101489. if( rc ){
  101490. return 1;
  101491. }
  101492. if( IsVirtual(pTable) ) return 0;
  101493. #endif
  101494. #ifndef SQLITE_OMIT_VIEW
  101495. /* A positive nCol means the columns names for this view are
  101496. ** already known.
  101497. */
  101498. if( pTable->nCol>0 ) return 0;
  101499. /* A negative nCol is a special marker meaning that we are currently
  101500. ** trying to compute the column names. If we enter this routine with
  101501. ** a negative nCol, it means two or more views form a loop, like this:
  101502. **
  101503. ** CREATE VIEW one AS SELECT * FROM two;
  101504. ** CREATE VIEW two AS SELECT * FROM one;
  101505. **
  101506. ** Actually, the error above is now caught prior to reaching this point.
  101507. ** But the following test is still important as it does come up
  101508. ** in the following:
  101509. **
  101510. ** CREATE TABLE main.ex1(a);
  101511. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  101512. ** SELECT * FROM temp.ex1;
  101513. */
  101514. if( pTable->nCol<0 ){
  101515. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  101516. return 1;
  101517. }
  101518. assert( pTable->nCol>=0 );
  101519. /* If we get this far, it means we need to compute the table names.
  101520. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  101521. ** "*" elements in the results set of the view and will assign cursors
  101522. ** to the elements of the FROM clause. But we do not want these changes
  101523. ** to be permanent. So the computation is done on a copy of the SELECT
  101524. ** statement that defines the view.
  101525. */
  101526. assert( pTable->pSelect );
  101527. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  101528. if( pSel ){
  101529. #ifndef SQLITE_OMIT_ALTERTABLE
  101530. u8 eParseMode = pParse->eParseMode;
  101531. pParse->eParseMode = PARSE_MODE_NORMAL;
  101532. #endif
  101533. n = pParse->nTab;
  101534. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  101535. pTable->nCol = -1;
  101536. db->lookaside.bDisable++;
  101537. #ifndef SQLITE_OMIT_AUTHORIZATION
  101538. xAuth = db->xAuth;
  101539. db->xAuth = 0;
  101540. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  101541. db->xAuth = xAuth;
  101542. #else
  101543. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  101544. #endif
  101545. pParse->nTab = n;
  101546. if( pTable->pCheck ){
  101547. /* CREATE VIEW name(arglist) AS ...
  101548. ** The names of the columns in the table are taken from
  101549. ** arglist which is stored in pTable->pCheck. The pCheck field
  101550. ** normally holds CHECK constraints on an ordinary table, but for
  101551. ** a VIEW it holds the list of column names.
  101552. */
  101553. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  101554. &pTable->nCol, &pTable->aCol);
  101555. if( db->mallocFailed==0
  101556. && pParse->nErr==0
  101557. && pTable->nCol==pSel->pEList->nExpr
  101558. ){
  101559. sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
  101560. }
  101561. }else if( pSelTab ){
  101562. /* CREATE VIEW name AS... without an argument list. Construct
  101563. ** the column names from the SELECT statement that defines the view.
  101564. */
  101565. assert( pTable->aCol==0 );
  101566. pTable->nCol = pSelTab->nCol;
  101567. pTable->aCol = pSelTab->aCol;
  101568. pSelTab->nCol = 0;
  101569. pSelTab->aCol = 0;
  101570. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  101571. }else{
  101572. pTable->nCol = 0;
  101573. nErr++;
  101574. }
  101575. sqlite3DeleteTable(db, pSelTab);
  101576. sqlite3SelectDelete(db, pSel);
  101577. db->lookaside.bDisable--;
  101578. #ifndef SQLITE_OMIT_ALTERTABLE
  101579. pParse->eParseMode = eParseMode;
  101580. #endif
  101581. } else {
  101582. nErr++;
  101583. }
  101584. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  101585. if( db->mallocFailed ){
  101586. sqlite3DeleteColumnNames(db, pTable);
  101587. pTable->aCol = 0;
  101588. pTable->nCol = 0;
  101589. }
  101590. #endif /* SQLITE_OMIT_VIEW */
  101591. return nErr;
  101592. }
  101593. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  101594. #ifndef SQLITE_OMIT_VIEW
  101595. /*
  101596. ** Clear the column names from every VIEW in database idx.
  101597. */
  101598. static void sqliteViewResetAll(sqlite3 *db, int idx){
  101599. HashElem *i;
  101600. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  101601. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  101602. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  101603. Table *pTab = sqliteHashData(i);
  101604. if( pTab->pSelect ){
  101605. sqlite3DeleteColumnNames(db, pTab);
  101606. pTab->aCol = 0;
  101607. pTab->nCol = 0;
  101608. }
  101609. }
  101610. DbClearProperty(db, idx, DB_UnresetViews);
  101611. }
  101612. #else
  101613. # define sqliteViewResetAll(A,B)
  101614. #endif /* SQLITE_OMIT_VIEW */
  101615. /*
  101616. ** This function is called by the VDBE to adjust the internal schema
  101617. ** used by SQLite when the btree layer moves a table root page. The
  101618. ** root-page of a table or index in database iDb has changed from iFrom
  101619. ** to iTo.
  101620. **
  101621. ** Ticket #1728: The symbol table might still contain information
  101622. ** on tables and/or indices that are the process of being deleted.
  101623. ** If you are unlucky, one of those deleted indices or tables might
  101624. ** have the same rootpage number as the real table or index that is
  101625. ** being moved. So we cannot stop searching after the first match
  101626. ** because the first match might be for one of the deleted indices
  101627. ** or tables and not the table/index that is actually being moved.
  101628. ** We must continue looping until all tables and indices with
  101629. ** rootpage==iFrom have been converted to have a rootpage of iTo
  101630. ** in order to be certain that we got the right one.
  101631. */
  101632. #ifndef SQLITE_OMIT_AUTOVACUUM
  101633. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  101634. HashElem *pElem;
  101635. Hash *pHash;
  101636. Db *pDb;
  101637. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101638. pDb = &db->aDb[iDb];
  101639. pHash = &pDb->pSchema->tblHash;
  101640. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  101641. Table *pTab = sqliteHashData(pElem);
  101642. if( pTab->tnum==iFrom ){
  101643. pTab->tnum = iTo;
  101644. }
  101645. }
  101646. pHash = &pDb->pSchema->idxHash;
  101647. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  101648. Index *pIdx = sqliteHashData(pElem);
  101649. if( pIdx->tnum==iFrom ){
  101650. pIdx->tnum = iTo;
  101651. }
  101652. }
  101653. }
  101654. #endif
  101655. /*
  101656. ** Write code to erase the table with root-page iTable from database iDb.
  101657. ** Also write code to modify the sqlite_master table and internal schema
  101658. ** if a root-page of another table is moved by the btree-layer whilst
  101659. ** erasing iTable (this can happen with an auto-vacuum database).
  101660. */
  101661. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  101662. Vdbe *v = sqlite3GetVdbe(pParse);
  101663. int r1 = sqlite3GetTempReg(pParse);
  101664. if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
  101665. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  101666. sqlite3MayAbort(pParse);
  101667. #ifndef SQLITE_OMIT_AUTOVACUUM
  101668. /* OP_Destroy stores an in integer r1. If this integer
  101669. ** is non-zero, then it is the root page number of a table moved to
  101670. ** location iTable. The following code modifies the sqlite_master table to
  101671. ** reflect this.
  101672. **
  101673. ** The "#NNN" in the SQL is a special constant that means whatever value
  101674. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  101675. ** token for additional information.
  101676. */
  101677. sqlite3NestedParse(pParse,
  101678. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  101679. pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
  101680. #endif
  101681. sqlite3ReleaseTempReg(pParse, r1);
  101682. }
  101683. /*
  101684. ** Write VDBE code to erase table pTab and all associated indices on disk.
  101685. ** Code to update the sqlite_master tables and internal schema definitions
  101686. ** in case a root-page belonging to another table is moved by the btree layer
  101687. ** is also added (this can happen with an auto-vacuum database).
  101688. */
  101689. static void destroyTable(Parse *pParse, Table *pTab){
  101690. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  101691. ** is not defined), then it is important to call OP_Destroy on the
  101692. ** table and index root-pages in order, starting with the numerically
  101693. ** largest root-page number. This guarantees that none of the root-pages
  101694. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  101695. ** following were coded:
  101696. **
  101697. ** OP_Destroy 4 0
  101698. ** ...
  101699. ** OP_Destroy 5 0
  101700. **
  101701. ** and root page 5 happened to be the largest root-page number in the
  101702. ** database, then root page 5 would be moved to page 4 by the
  101703. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  101704. ** a free-list page.
  101705. */
  101706. int iTab = pTab->tnum;
  101707. int iDestroyed = 0;
  101708. while( 1 ){
  101709. Index *pIdx;
  101710. int iLargest = 0;
  101711. if( iDestroyed==0 || iTab<iDestroyed ){
  101712. iLargest = iTab;
  101713. }
  101714. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  101715. int iIdx = pIdx->tnum;
  101716. assert( pIdx->pSchema==pTab->pSchema );
  101717. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  101718. iLargest = iIdx;
  101719. }
  101720. }
  101721. if( iLargest==0 ){
  101722. return;
  101723. }else{
  101724. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  101725. assert( iDb>=0 && iDb<pParse->db->nDb );
  101726. destroyRootPage(pParse, iLargest, iDb);
  101727. iDestroyed = iLargest;
  101728. }
  101729. }
  101730. }
  101731. /*
  101732. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  101733. ** after a DROP INDEX or DROP TABLE command.
  101734. */
  101735. static void sqlite3ClearStatTables(
  101736. Parse *pParse, /* The parsing context */
  101737. int iDb, /* The database number */
  101738. const char *zType, /* "idx" or "tbl" */
  101739. const char *zName /* Name of index or table */
  101740. ){
  101741. int i;
  101742. const char *zDbName = pParse->db->aDb[iDb].zDbSName;
  101743. for(i=1; i<=4; i++){
  101744. char zTab[24];
  101745. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  101746. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  101747. sqlite3NestedParse(pParse,
  101748. "DELETE FROM %Q.%s WHERE %s=%Q",
  101749. zDbName, zTab, zType, zName
  101750. );
  101751. }
  101752. }
  101753. }
  101754. /*
  101755. ** Generate code to drop a table.
  101756. */
  101757. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  101758. Vdbe *v;
  101759. sqlite3 *db = pParse->db;
  101760. Trigger *pTrigger;
  101761. Db *pDb = &db->aDb[iDb];
  101762. v = sqlite3GetVdbe(pParse);
  101763. assert( v!=0 );
  101764. sqlite3BeginWriteOperation(pParse, 1, iDb);
  101765. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101766. if( IsVirtual(pTab) ){
  101767. sqlite3VdbeAddOp0(v, OP_VBegin);
  101768. }
  101769. #endif
  101770. /* Drop all triggers associated with the table being dropped. Code
  101771. ** is generated to remove entries from sqlite_master and/or
  101772. ** sqlite_temp_master if required.
  101773. */
  101774. pTrigger = sqlite3TriggerList(pParse, pTab);
  101775. while( pTrigger ){
  101776. assert( pTrigger->pSchema==pTab->pSchema ||
  101777. pTrigger->pSchema==db->aDb[1].pSchema );
  101778. sqlite3DropTriggerPtr(pParse, pTrigger);
  101779. pTrigger = pTrigger->pNext;
  101780. }
  101781. #ifndef SQLITE_OMIT_AUTOINCREMENT
  101782. /* Remove any entries of the sqlite_sequence table associated with
  101783. ** the table being dropped. This is done before the table is dropped
  101784. ** at the btree level, in case the sqlite_sequence table needs to
  101785. ** move as a result of the drop (can happen in auto-vacuum mode).
  101786. */
  101787. if( pTab->tabFlags & TF_Autoincrement ){
  101788. sqlite3NestedParse(pParse,
  101789. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  101790. pDb->zDbSName, pTab->zName
  101791. );
  101792. }
  101793. #endif
  101794. /* Drop all SQLITE_MASTER table and index entries that refer to the
  101795. ** table. The program name loops through the master table and deletes
  101796. ** every row that refers to a table of the same name as the one being
  101797. ** dropped. Triggers are handled separately because a trigger can be
  101798. ** created in the temp database that refers to a table in another
  101799. ** database.
  101800. */
  101801. sqlite3NestedParse(pParse,
  101802. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  101803. pDb->zDbSName, MASTER_NAME, pTab->zName);
  101804. if( !isView && !IsVirtual(pTab) ){
  101805. destroyTable(pParse, pTab);
  101806. }
  101807. /* Remove the table entry from SQLite's internal schema and modify
  101808. ** the schema cookie.
  101809. */
  101810. if( IsVirtual(pTab) ){
  101811. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  101812. }
  101813. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  101814. sqlite3ChangeCookie(pParse, iDb);
  101815. sqliteViewResetAll(db, iDb);
  101816. }
  101817. /*
  101818. ** This routine is called to do the work of a DROP TABLE statement.
  101819. ** pName is the name of the table to be dropped.
  101820. */
  101821. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  101822. Table *pTab;
  101823. Vdbe *v;
  101824. sqlite3 *db = pParse->db;
  101825. int iDb;
  101826. if( db->mallocFailed ){
  101827. goto exit_drop_table;
  101828. }
  101829. assert( pParse->nErr==0 );
  101830. assert( pName->nSrc==1 );
  101831. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  101832. if( noErr ) db->suppressErr++;
  101833. assert( isView==0 || isView==LOCATE_VIEW );
  101834. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  101835. if( noErr ) db->suppressErr--;
  101836. if( pTab==0 ){
  101837. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  101838. goto exit_drop_table;
  101839. }
  101840. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  101841. assert( iDb>=0 && iDb<db->nDb );
  101842. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  101843. ** it is initialized.
  101844. */
  101845. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  101846. goto exit_drop_table;
  101847. }
  101848. #ifndef SQLITE_OMIT_AUTHORIZATION
  101849. {
  101850. int code;
  101851. const char *zTab = SCHEMA_TABLE(iDb);
  101852. const char *zDb = db->aDb[iDb].zDbSName;
  101853. const char *zArg2 = 0;
  101854. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  101855. goto exit_drop_table;
  101856. }
  101857. if( isView ){
  101858. if( !OMIT_TEMPDB && iDb==1 ){
  101859. code = SQLITE_DROP_TEMP_VIEW;
  101860. }else{
  101861. code = SQLITE_DROP_VIEW;
  101862. }
  101863. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101864. }else if( IsVirtual(pTab) ){
  101865. code = SQLITE_DROP_VTABLE;
  101866. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  101867. #endif
  101868. }else{
  101869. if( !OMIT_TEMPDB && iDb==1 ){
  101870. code = SQLITE_DROP_TEMP_TABLE;
  101871. }else{
  101872. code = SQLITE_DROP_TABLE;
  101873. }
  101874. }
  101875. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  101876. goto exit_drop_table;
  101877. }
  101878. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  101879. goto exit_drop_table;
  101880. }
  101881. }
  101882. #endif
  101883. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  101884. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  101885. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  101886. goto exit_drop_table;
  101887. }
  101888. #ifndef SQLITE_OMIT_VIEW
  101889. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  101890. ** on a table.
  101891. */
  101892. if( isView && pTab->pSelect==0 ){
  101893. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  101894. goto exit_drop_table;
  101895. }
  101896. if( !isView && pTab->pSelect ){
  101897. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  101898. goto exit_drop_table;
  101899. }
  101900. #endif
  101901. /* Generate code to remove the table from the master table
  101902. ** on disk.
  101903. */
  101904. v = sqlite3GetVdbe(pParse);
  101905. if( v ){
  101906. sqlite3BeginWriteOperation(pParse, 1, iDb);
  101907. if( !isView ){
  101908. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  101909. sqlite3FkDropTable(pParse, pName, pTab);
  101910. }
  101911. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  101912. }
  101913. exit_drop_table:
  101914. sqlite3SrcListDelete(db, pName);
  101915. }
  101916. /*
  101917. ** This routine is called to create a new foreign key on the table
  101918. ** currently under construction. pFromCol determines which columns
  101919. ** in the current table point to the foreign key. If pFromCol==0 then
  101920. ** connect the key to the last column inserted. pTo is the name of
  101921. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  101922. ** of tables in the parent pTo table. flags contains all
  101923. ** information about the conflict resolution algorithms specified
  101924. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  101925. **
  101926. ** An FKey structure is created and added to the table currently
  101927. ** under construction in the pParse->pNewTable field.
  101928. **
  101929. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  101930. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  101931. */
  101932. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  101933. Parse *pParse, /* Parsing context */
  101934. ExprList *pFromCol, /* Columns in this table that point to other table */
  101935. Token *pTo, /* Name of the other table */
  101936. ExprList *pToCol, /* Columns in the other table */
  101937. int flags /* Conflict resolution algorithms. */
  101938. ){
  101939. sqlite3 *db = pParse->db;
  101940. #ifndef SQLITE_OMIT_FOREIGN_KEY
  101941. FKey *pFKey = 0;
  101942. FKey *pNextTo;
  101943. Table *p = pParse->pNewTable;
  101944. int nByte;
  101945. int i;
  101946. int nCol;
  101947. char *z;
  101948. assert( pTo!=0 );
  101949. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  101950. if( pFromCol==0 ){
  101951. int iCol = p->nCol-1;
  101952. if( NEVER(iCol<0) ) goto fk_end;
  101953. if( pToCol && pToCol->nExpr!=1 ){
  101954. sqlite3ErrorMsg(pParse, "foreign key on %s"
  101955. " should reference only one column of table %T",
  101956. p->aCol[iCol].zName, pTo);
  101957. goto fk_end;
  101958. }
  101959. nCol = 1;
  101960. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  101961. sqlite3ErrorMsg(pParse,
  101962. "number of columns in foreign key does not match the number of "
  101963. "columns in the referenced table");
  101964. goto fk_end;
  101965. }else{
  101966. nCol = pFromCol->nExpr;
  101967. }
  101968. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  101969. if( pToCol ){
  101970. for(i=0; i<pToCol->nExpr; i++){
  101971. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  101972. }
  101973. }
  101974. pFKey = sqlite3DbMallocZero(db, nByte );
  101975. if( pFKey==0 ){
  101976. goto fk_end;
  101977. }
  101978. pFKey->pFrom = p;
  101979. pFKey->pNextFrom = p->pFKey;
  101980. z = (char*)&pFKey->aCol[nCol];
  101981. pFKey->zTo = z;
  101982. if( IN_RENAME_OBJECT ){
  101983. sqlite3RenameTokenMap(pParse, (void*)z, pTo);
  101984. }
  101985. memcpy(z, pTo->z, pTo->n);
  101986. z[pTo->n] = 0;
  101987. sqlite3Dequote(z);
  101988. z += pTo->n+1;
  101989. pFKey->nCol = nCol;
  101990. if( pFromCol==0 ){
  101991. pFKey->aCol[0].iFrom = p->nCol-1;
  101992. }else{
  101993. for(i=0; i<nCol; i++){
  101994. int j;
  101995. for(j=0; j<p->nCol; j++){
  101996. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  101997. pFKey->aCol[i].iFrom = j;
  101998. break;
  101999. }
  102000. }
  102001. if( j>=p->nCol ){
  102002. sqlite3ErrorMsg(pParse,
  102003. "unknown column \"%s\" in foreign key definition",
  102004. pFromCol->a[i].zName);
  102005. goto fk_end;
  102006. }
  102007. if( IN_RENAME_OBJECT ){
  102008. sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zName);
  102009. }
  102010. }
  102011. }
  102012. if( pToCol ){
  102013. for(i=0; i<nCol; i++){
  102014. int n = sqlite3Strlen30(pToCol->a[i].zName);
  102015. pFKey->aCol[i].zCol = z;
  102016. if( IN_RENAME_OBJECT ){
  102017. sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zName);
  102018. }
  102019. memcpy(z, pToCol->a[i].zName, n);
  102020. z[n] = 0;
  102021. z += n+1;
  102022. }
  102023. }
  102024. pFKey->isDeferred = 0;
  102025. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  102026. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  102027. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  102028. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  102029. pFKey->zTo, (void *)pFKey
  102030. );
  102031. if( pNextTo==pFKey ){
  102032. sqlite3OomFault(db);
  102033. goto fk_end;
  102034. }
  102035. if( pNextTo ){
  102036. assert( pNextTo->pPrevTo==0 );
  102037. pFKey->pNextTo = pNextTo;
  102038. pNextTo->pPrevTo = pFKey;
  102039. }
  102040. /* Link the foreign key to the table as the last step.
  102041. */
  102042. p->pFKey = pFKey;
  102043. pFKey = 0;
  102044. fk_end:
  102045. sqlite3DbFree(db, pFKey);
  102046. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  102047. sqlite3ExprListDelete(db, pFromCol);
  102048. sqlite3ExprListDelete(db, pToCol);
  102049. }
  102050. /*
  102051. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  102052. ** clause is seen as part of a foreign key definition. The isDeferred
  102053. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  102054. ** The behavior of the most recently created foreign key is adjusted
  102055. ** accordingly.
  102056. */
  102057. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  102058. #ifndef SQLITE_OMIT_FOREIGN_KEY
  102059. Table *pTab;
  102060. FKey *pFKey;
  102061. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  102062. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  102063. pFKey->isDeferred = (u8)isDeferred;
  102064. #endif
  102065. }
  102066. /*
  102067. ** Generate code that will erase and refill index *pIdx. This is
  102068. ** used to initialize a newly created index or to recompute the
  102069. ** content of an index in response to a REINDEX command.
  102070. **
  102071. ** if memRootPage is not negative, it means that the index is newly
  102072. ** created. The register specified by memRootPage contains the
  102073. ** root page number of the index. If memRootPage is negative, then
  102074. ** the index already exists and must be cleared before being refilled and
  102075. ** the root page number of the index is taken from pIndex->tnum.
  102076. */
  102077. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  102078. Table *pTab = pIndex->pTable; /* The table that is indexed */
  102079. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  102080. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  102081. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  102082. int addr1; /* Address of top of loop */
  102083. int addr2; /* Address to jump to for next iteration */
  102084. int tnum; /* Root page of index */
  102085. int iPartIdxLabel; /* Jump to this label to skip a row */
  102086. Vdbe *v; /* Generate code into this virtual machine */
  102087. KeyInfo *pKey; /* KeyInfo for index */
  102088. int regRecord; /* Register holding assembled index record */
  102089. sqlite3 *db = pParse->db; /* The database connection */
  102090. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  102091. #ifndef SQLITE_OMIT_AUTHORIZATION
  102092. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  102093. db->aDb[iDb].zDbSName ) ){
  102094. return;
  102095. }
  102096. #endif
  102097. /* Require a write-lock on the table to perform this operation */
  102098. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  102099. v = sqlite3GetVdbe(pParse);
  102100. if( v==0 ) return;
  102101. if( memRootPage>=0 ){
  102102. tnum = memRootPage;
  102103. }else{
  102104. tnum = pIndex->tnum;
  102105. }
  102106. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  102107. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  102108. /* Open the sorter cursor if we are to use one. */
  102109. iSorter = pParse->nTab++;
  102110. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  102111. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  102112. /* Open the table. Loop through all rows of the table, inserting index
  102113. ** records into the sorter. */
  102114. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  102115. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  102116. regRecord = sqlite3GetTempReg(pParse);
  102117. sqlite3MultiWrite(pParse);
  102118. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  102119. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  102120. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  102121. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  102122. sqlite3VdbeJumpHere(v, addr1);
  102123. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  102124. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  102125. (char *)pKey, P4_KEYINFO);
  102126. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  102127. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  102128. if( IsUniqueIndex(pIndex) ){
  102129. int j2 = sqlite3VdbeGoto(v, 1);
  102130. addr2 = sqlite3VdbeCurrentAddr(v);
  102131. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  102132. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  102133. pIndex->nKeyCol); VdbeCoverage(v);
  102134. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  102135. sqlite3VdbeJumpHere(v, j2);
  102136. }else{
  102137. addr2 = sqlite3VdbeCurrentAddr(v);
  102138. }
  102139. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  102140. sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
  102141. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  102142. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  102143. sqlite3ReleaseTempReg(pParse, regRecord);
  102144. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  102145. sqlite3VdbeJumpHere(v, addr1);
  102146. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  102147. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  102148. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  102149. }
  102150. /*
  102151. ** Allocate heap space to hold an Index object with nCol columns.
  102152. **
  102153. ** Increase the allocation size to provide an extra nExtra bytes
  102154. ** of 8-byte aligned space after the Index object and return a
  102155. ** pointer to this extra space in *ppExtra.
  102156. */
  102157. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  102158. sqlite3 *db, /* Database connection */
  102159. i16 nCol, /* Total number of columns in the index */
  102160. int nExtra, /* Number of bytes of extra space to alloc */
  102161. char **ppExtra /* Pointer to the "extra" space */
  102162. ){
  102163. Index *p; /* Allocated index object */
  102164. int nByte; /* Bytes of space for Index object + arrays */
  102165. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  102166. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  102167. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  102168. sizeof(i16)*nCol + /* Index.aiColumn */
  102169. sizeof(u8)*nCol); /* Index.aSortOrder */
  102170. p = sqlite3DbMallocZero(db, nByte + nExtra);
  102171. if( p ){
  102172. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  102173. p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  102174. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  102175. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  102176. p->aSortOrder = (u8*)pExtra;
  102177. p->nColumn = nCol;
  102178. p->nKeyCol = nCol - 1;
  102179. *ppExtra = ((char*)p) + nByte;
  102180. }
  102181. return p;
  102182. }
  102183. /*
  102184. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  102185. ** and pTblList is the name of the table that is to be indexed. Both will
  102186. ** be NULL for a primary key or an index that is created to satisfy a
  102187. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  102188. ** as the table to be indexed. pParse->pNewTable is a table that is
  102189. ** currently being constructed by a CREATE TABLE statement.
  102190. **
  102191. ** pList is a list of columns to be indexed. pList will be NULL if this
  102192. ** is a primary key or unique-constraint on the most recent column added
  102193. ** to the table currently under construction.
  102194. */
  102195. SQLITE_PRIVATE void sqlite3CreateIndex(
  102196. Parse *pParse, /* All information about this parse */
  102197. Token *pName1, /* First part of index name. May be NULL */
  102198. Token *pName2, /* Second part of index name. May be NULL */
  102199. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  102200. ExprList *pList, /* A list of columns to be indexed */
  102201. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  102202. Token *pStart, /* The CREATE token that begins this statement */
  102203. Expr *pPIWhere, /* WHERE clause for partial indices */
  102204. int sortOrder, /* Sort order of primary key when pList==NULL */
  102205. int ifNotExist, /* Omit error if index already exists */
  102206. u8 idxType /* The index type */
  102207. ){
  102208. Table *pTab = 0; /* Table to be indexed */
  102209. Index *pIndex = 0; /* The index to be created */
  102210. char *zName = 0; /* Name of the index */
  102211. int nName; /* Number of characters in zName */
  102212. int i, j;
  102213. DbFixer sFix; /* For assigning database names to pTable */
  102214. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  102215. sqlite3 *db = pParse->db;
  102216. Db *pDb; /* The specific table containing the indexed database */
  102217. int iDb; /* Index of the database that is being written */
  102218. Token *pName = 0; /* Unqualified name of the index to create */
  102219. struct ExprList_item *pListItem; /* For looping over pList */
  102220. int nExtra = 0; /* Space allocated for zExtra[] */
  102221. int nExtraCol; /* Number of extra columns needed */
  102222. char *zExtra = 0; /* Extra space after the Index object */
  102223. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  102224. if( db->mallocFailed || pParse->nErr>0 ){
  102225. goto exit_create_index;
  102226. }
  102227. if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
  102228. goto exit_create_index;
  102229. }
  102230. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  102231. goto exit_create_index;
  102232. }
  102233. /*
  102234. ** Find the table that is to be indexed. Return early if not found.
  102235. */
  102236. if( pTblName!=0 ){
  102237. /* Use the two-part index name to determine the database
  102238. ** to search for the table. 'Fix' the table name to this db
  102239. ** before looking up the table.
  102240. */
  102241. assert( pName1 && pName2 );
  102242. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  102243. if( iDb<0 ) goto exit_create_index;
  102244. assert( pName && pName->z );
  102245. #ifndef SQLITE_OMIT_TEMPDB
  102246. /* If the index name was unqualified, check if the table
  102247. ** is a temp table. If so, set the database to 1. Do not do this
  102248. ** if initialising a database schema.
  102249. */
  102250. if( !db->init.busy ){
  102251. pTab = sqlite3SrcListLookup(pParse, pTblName);
  102252. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  102253. iDb = 1;
  102254. }
  102255. }
  102256. #endif
  102257. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  102258. if( sqlite3FixSrcList(&sFix, pTblName) ){
  102259. /* Because the parser constructs pTblName from a single identifier,
  102260. ** sqlite3FixSrcList can never fail. */
  102261. assert(0);
  102262. }
  102263. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  102264. assert( db->mallocFailed==0 || pTab==0 );
  102265. if( pTab==0 ) goto exit_create_index;
  102266. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  102267. sqlite3ErrorMsg(pParse,
  102268. "cannot create a TEMP index on non-TEMP table \"%s\"",
  102269. pTab->zName);
  102270. goto exit_create_index;
  102271. }
  102272. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  102273. }else{
  102274. assert( pName==0 );
  102275. assert( pStart==0 );
  102276. pTab = pParse->pNewTable;
  102277. if( !pTab ) goto exit_create_index;
  102278. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102279. }
  102280. pDb = &db->aDb[iDb];
  102281. assert( pTab!=0 );
  102282. assert( pParse->nErr==0 );
  102283. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  102284. && db->init.busy==0
  102285. #if SQLITE_USER_AUTHENTICATION
  102286. && sqlite3UserAuthTable(pTab->zName)==0
  102287. #endif
  102288. #ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
  102289. && sqlite3StrICmp(&pTab->zName[7],"master")!=0
  102290. #endif
  102291. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0
  102292. ){
  102293. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  102294. goto exit_create_index;
  102295. }
  102296. #ifndef SQLITE_OMIT_VIEW
  102297. if( pTab->pSelect ){
  102298. sqlite3ErrorMsg(pParse, "views may not be indexed");
  102299. goto exit_create_index;
  102300. }
  102301. #endif
  102302. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102303. if( IsVirtual(pTab) ){
  102304. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  102305. goto exit_create_index;
  102306. }
  102307. #endif
  102308. /*
  102309. ** Find the name of the index. Make sure there is not already another
  102310. ** index or table with the same name.
  102311. **
  102312. ** Exception: If we are reading the names of permanent indices from the
  102313. ** sqlite_master table (because some other process changed the schema) and
  102314. ** one of the index names collides with the name of a temporary table or
  102315. ** index, then we will continue to process this index.
  102316. **
  102317. ** If pName==0 it means that we are
  102318. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  102319. ** own name.
  102320. */
  102321. if( pName ){
  102322. zName = sqlite3NameFromToken(db, pName);
  102323. if( zName==0 ) goto exit_create_index;
  102324. assert( pName->z!=0 );
  102325. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  102326. goto exit_create_index;
  102327. }
  102328. if( !IN_RENAME_OBJECT ){
  102329. if( !db->init.busy ){
  102330. if( sqlite3FindTable(db, zName, 0)!=0 ){
  102331. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  102332. goto exit_create_index;
  102333. }
  102334. }
  102335. if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
  102336. if( !ifNotExist ){
  102337. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  102338. }else{
  102339. assert( !db->init.busy );
  102340. sqlite3CodeVerifySchema(pParse, iDb);
  102341. }
  102342. goto exit_create_index;
  102343. }
  102344. }
  102345. }else{
  102346. int n;
  102347. Index *pLoop;
  102348. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  102349. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  102350. if( zName==0 ){
  102351. goto exit_create_index;
  102352. }
  102353. /* Automatic index names generated from within sqlite3_declare_vtab()
  102354. ** must have names that are distinct from normal automatic index names.
  102355. ** The following statement converts "sqlite3_autoindex..." into
  102356. ** "sqlite3_butoindex..." in order to make the names distinct.
  102357. ** The "vtab_err.test" test demonstrates the need of this statement. */
  102358. if( IN_SPECIAL_PARSE ) zName[7]++;
  102359. }
  102360. /* Check for authorization to create an index.
  102361. */
  102362. #ifndef SQLITE_OMIT_AUTHORIZATION
  102363. if( !IN_RENAME_OBJECT ){
  102364. const char *zDb = pDb->zDbSName;
  102365. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  102366. goto exit_create_index;
  102367. }
  102368. i = SQLITE_CREATE_INDEX;
  102369. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  102370. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  102371. goto exit_create_index;
  102372. }
  102373. }
  102374. #endif
  102375. /* If pList==0, it means this routine was called to make a primary
  102376. ** key out of the last column added to the table under construction.
  102377. ** So create a fake list to simulate this.
  102378. */
  102379. if( pList==0 ){
  102380. Token prevCol;
  102381. Column *pCol = &pTab->aCol[pTab->nCol-1];
  102382. pCol->colFlags |= COLFLAG_UNIQUE;
  102383. sqlite3TokenInit(&prevCol, pCol->zName);
  102384. pList = sqlite3ExprListAppend(pParse, 0,
  102385. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  102386. if( pList==0 ) goto exit_create_index;
  102387. assert( pList->nExpr==1 );
  102388. sqlite3ExprListSetSortOrder(pList, sortOrder);
  102389. }else{
  102390. sqlite3ExprListCheckLength(pParse, pList, "index");
  102391. }
  102392. /* Figure out how many bytes of space are required to store explicitly
  102393. ** specified collation sequence names.
  102394. */
  102395. for(i=0; i<pList->nExpr; i++){
  102396. Expr *pExpr = pList->a[i].pExpr;
  102397. assert( pExpr!=0 );
  102398. if( pExpr->op==TK_COLLATE ){
  102399. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  102400. }
  102401. }
  102402. /*
  102403. ** Allocate the index structure.
  102404. */
  102405. nName = sqlite3Strlen30(zName);
  102406. nExtraCol = pPk ? pPk->nKeyCol : 1;
  102407. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  102408. nName + nExtra + 1, &zExtra);
  102409. if( db->mallocFailed ){
  102410. goto exit_create_index;
  102411. }
  102412. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  102413. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  102414. pIndex->zName = zExtra;
  102415. zExtra += nName + 1;
  102416. memcpy(pIndex->zName, zName, nName+1);
  102417. pIndex->pTable = pTab;
  102418. pIndex->onError = (u8)onError;
  102419. pIndex->uniqNotNull = onError!=OE_None;
  102420. pIndex->idxType = idxType;
  102421. pIndex->pSchema = db->aDb[iDb].pSchema;
  102422. pIndex->nKeyCol = pList->nExpr;
  102423. if( pPIWhere ){
  102424. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  102425. pIndex->pPartIdxWhere = pPIWhere;
  102426. pPIWhere = 0;
  102427. }
  102428. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  102429. /* Check to see if we should honor DESC requests on index columns
  102430. */
  102431. if( pDb->pSchema->file_format>=4 ){
  102432. sortOrderMask = -1; /* Honor DESC */
  102433. }else{
  102434. sortOrderMask = 0; /* Ignore DESC */
  102435. }
  102436. /* Analyze the list of expressions that form the terms of the index and
  102437. ** report any errors. In the common case where the expression is exactly
  102438. ** a table column, store that column in aiColumn[]. For general expressions,
  102439. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  102440. **
  102441. ** TODO: Issue a warning if two or more columns of the index are identical.
  102442. ** TODO: Issue a warning if the table primary key is used as part of the
  102443. ** index key.
  102444. */
  102445. pListItem = pList->a;
  102446. if( IN_RENAME_OBJECT ){
  102447. pIndex->aColExpr = pList;
  102448. pList = 0;
  102449. }
  102450. for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
  102451. Expr *pCExpr; /* The i-th index expression */
  102452. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  102453. const char *zColl; /* Collation sequence name */
  102454. sqlite3StringToId(pListItem->pExpr);
  102455. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  102456. if( pParse->nErr ) goto exit_create_index;
  102457. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  102458. if( pCExpr->op!=TK_COLUMN ){
  102459. if( pTab==pParse->pNewTable ){
  102460. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  102461. "UNIQUE constraints");
  102462. goto exit_create_index;
  102463. }
  102464. if( pIndex->aColExpr==0 ){
  102465. pIndex->aColExpr = pList;
  102466. pList = 0;
  102467. }
  102468. j = XN_EXPR;
  102469. pIndex->aiColumn[i] = XN_EXPR;
  102470. pIndex->uniqNotNull = 0;
  102471. }else{
  102472. j = pCExpr->iColumn;
  102473. assert( j<=0x7fff );
  102474. if( j<0 ){
  102475. j = pTab->iPKey;
  102476. }else if( pTab->aCol[j].notNull==0 ){
  102477. pIndex->uniqNotNull = 0;
  102478. }
  102479. pIndex->aiColumn[i] = (i16)j;
  102480. }
  102481. zColl = 0;
  102482. if( pListItem->pExpr->op==TK_COLLATE ){
  102483. int nColl;
  102484. zColl = pListItem->pExpr->u.zToken;
  102485. nColl = sqlite3Strlen30(zColl) + 1;
  102486. assert( nExtra>=nColl );
  102487. memcpy(zExtra, zColl, nColl);
  102488. zColl = zExtra;
  102489. zExtra += nColl;
  102490. nExtra -= nColl;
  102491. }else if( j>=0 ){
  102492. zColl = pTab->aCol[j].zColl;
  102493. }
  102494. if( !zColl ) zColl = sqlite3StrBINARY;
  102495. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  102496. goto exit_create_index;
  102497. }
  102498. pIndex->azColl[i] = zColl;
  102499. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  102500. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  102501. }
  102502. /* Append the table key to the end of the index. For WITHOUT ROWID
  102503. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  102504. ** normal tables (when pPk==0) this will be the rowid.
  102505. */
  102506. if( pPk ){
  102507. for(j=0; j<pPk->nKeyCol; j++){
  102508. int x = pPk->aiColumn[j];
  102509. assert( x>=0 );
  102510. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  102511. pIndex->nColumn--;
  102512. }else{
  102513. pIndex->aiColumn[i] = x;
  102514. pIndex->azColl[i] = pPk->azColl[j];
  102515. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  102516. i++;
  102517. }
  102518. }
  102519. assert( i==pIndex->nColumn );
  102520. }else{
  102521. pIndex->aiColumn[i] = XN_ROWID;
  102522. pIndex->azColl[i] = sqlite3StrBINARY;
  102523. }
  102524. sqlite3DefaultRowEst(pIndex);
  102525. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  102526. /* If this index contains every column of its table, then mark
  102527. ** it as a covering index */
  102528. assert( HasRowid(pTab)
  102529. || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
  102530. recomputeColumnsNotIndexed(pIndex);
  102531. if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
  102532. pIndex->isCovering = 1;
  102533. for(j=0; j<pTab->nCol; j++){
  102534. if( j==pTab->iPKey ) continue;
  102535. if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
  102536. pIndex->isCovering = 0;
  102537. break;
  102538. }
  102539. }
  102540. if( pTab==pParse->pNewTable ){
  102541. /* This routine has been called to create an automatic index as a
  102542. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  102543. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  102544. ** i.e. one of:
  102545. **
  102546. ** CREATE TABLE t(x PRIMARY KEY, y);
  102547. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  102548. **
  102549. ** Either way, check to see if the table already has such an index. If
  102550. ** so, don't bother creating this one. This only applies to
  102551. ** automatically created indices. Users can do as they wish with
  102552. ** explicit indices.
  102553. **
  102554. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  102555. ** (and thus suppressing the second one) even if they have different
  102556. ** sort orders.
  102557. **
  102558. ** If there are different collating sequences or if the columns of
  102559. ** the constraint occur in different orders, then the constraints are
  102560. ** considered distinct and both result in separate indices.
  102561. */
  102562. Index *pIdx;
  102563. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  102564. int k;
  102565. assert( IsUniqueIndex(pIdx) );
  102566. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  102567. assert( IsUniqueIndex(pIndex) );
  102568. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  102569. for(k=0; k<pIdx->nKeyCol; k++){
  102570. const char *z1;
  102571. const char *z2;
  102572. assert( pIdx->aiColumn[k]>=0 );
  102573. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  102574. z1 = pIdx->azColl[k];
  102575. z2 = pIndex->azColl[k];
  102576. if( sqlite3StrICmp(z1, z2) ) break;
  102577. }
  102578. if( k==pIdx->nKeyCol ){
  102579. if( pIdx->onError!=pIndex->onError ){
  102580. /* This constraint creates the same index as a previous
  102581. ** constraint specified somewhere in the CREATE TABLE statement.
  102582. ** However the ON CONFLICT clauses are different. If both this
  102583. ** constraint and the previous equivalent constraint have explicit
  102584. ** ON CONFLICT clauses this is an error. Otherwise, use the
  102585. ** explicitly specified behavior for the index.
  102586. */
  102587. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  102588. sqlite3ErrorMsg(pParse,
  102589. "conflicting ON CONFLICT clauses specified", 0);
  102590. }
  102591. if( pIdx->onError==OE_Default ){
  102592. pIdx->onError = pIndex->onError;
  102593. }
  102594. }
  102595. if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
  102596. goto exit_create_index;
  102597. }
  102598. }
  102599. }
  102600. if( !IN_RENAME_OBJECT ){
  102601. /* Link the new Index structure to its table and to the other
  102602. ** in-memory database structures.
  102603. */
  102604. assert( pParse->nErr==0 );
  102605. if( db->init.busy ){
  102606. Index *p;
  102607. assert( !IN_SPECIAL_PARSE );
  102608. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  102609. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  102610. pIndex->zName, pIndex);
  102611. if( p ){
  102612. assert( p==pIndex ); /* Malloc must have failed */
  102613. sqlite3OomFault(db);
  102614. goto exit_create_index;
  102615. }
  102616. db->mDbFlags |= DBFLAG_SchemaChange;
  102617. if( pTblName!=0 ){
  102618. pIndex->tnum = db->init.newTnum;
  102619. }
  102620. }
  102621. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  102622. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  102623. ** emit code to allocate the index rootpage on disk and make an entry for
  102624. ** the index in the sqlite_master table and populate the index with
  102625. ** content. But, do not do this if we are simply reading the sqlite_master
  102626. ** table to parse the schema, or if this index is the PRIMARY KEY index
  102627. ** of a WITHOUT ROWID table.
  102628. **
  102629. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  102630. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  102631. ** has just been created, it contains no data and the index initialization
  102632. ** step can be skipped.
  102633. */
  102634. else if( HasRowid(pTab) || pTblName!=0 ){
  102635. Vdbe *v;
  102636. char *zStmt;
  102637. int iMem = ++pParse->nMem;
  102638. v = sqlite3GetVdbe(pParse);
  102639. if( v==0 ) goto exit_create_index;
  102640. sqlite3BeginWriteOperation(pParse, 1, iDb);
  102641. /* Create the rootpage for the index using CreateIndex. But before
  102642. ** doing so, code a Noop instruction and store its address in
  102643. ** Index.tnum. This is required in case this index is actually a
  102644. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  102645. ** that case the convertToWithoutRowidTable() routine will replace
  102646. ** the Noop with a Goto to jump over the VDBE code generated below. */
  102647. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  102648. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
  102649. /* Gather the complete text of the CREATE INDEX statement into
  102650. ** the zStmt variable
  102651. */
  102652. if( pStart ){
  102653. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  102654. if( pName->z[n-1]==';' ) n--;
  102655. /* A named index with an explicit CREATE INDEX statement */
  102656. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  102657. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  102658. }else{
  102659. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  102660. /* zStmt = sqlite3MPrintf(""); */
  102661. zStmt = 0;
  102662. }
  102663. /* Add an entry in sqlite_master for this index
  102664. */
  102665. sqlite3NestedParse(pParse,
  102666. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  102667. db->aDb[iDb].zDbSName, MASTER_NAME,
  102668. pIndex->zName,
  102669. pTab->zName,
  102670. iMem,
  102671. zStmt
  102672. );
  102673. sqlite3DbFree(db, zStmt);
  102674. /* Fill the index with data and reparse the schema. Code an OP_Expire
  102675. ** to invalidate all pre-compiled statements.
  102676. */
  102677. if( pTblName ){
  102678. sqlite3RefillIndex(pParse, pIndex, iMem);
  102679. sqlite3ChangeCookie(pParse, iDb);
  102680. sqlite3VdbeAddParseSchemaOp(v, iDb,
  102681. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  102682. sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
  102683. }
  102684. sqlite3VdbeJumpHere(v, pIndex->tnum);
  102685. }
  102686. }
  102687. /* When adding an index to the list of indices for a table, make
  102688. ** sure all indices labeled OE_Replace come after all those labeled
  102689. ** OE_Ignore. This is necessary for the correct constraint check
  102690. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  102691. ** UPDATE and INSERT statements.
  102692. */
  102693. if( db->init.busy || pTblName==0 ){
  102694. if( onError!=OE_Replace || pTab->pIndex==0
  102695. || pTab->pIndex->onError==OE_Replace){
  102696. pIndex->pNext = pTab->pIndex;
  102697. pTab->pIndex = pIndex;
  102698. }else{
  102699. Index *pOther = pTab->pIndex;
  102700. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  102701. pOther = pOther->pNext;
  102702. }
  102703. pIndex->pNext = pOther->pNext;
  102704. pOther->pNext = pIndex;
  102705. }
  102706. pIndex = 0;
  102707. }
  102708. else if( IN_RENAME_OBJECT ){
  102709. assert( pParse->pNewIndex==0 );
  102710. pParse->pNewIndex = pIndex;
  102711. pIndex = 0;
  102712. }
  102713. /* Clean up before exiting */
  102714. exit_create_index:
  102715. if( pIndex ) sqlite3FreeIndex(db, pIndex);
  102716. sqlite3ExprDelete(db, pPIWhere);
  102717. sqlite3ExprListDelete(db, pList);
  102718. sqlite3SrcListDelete(db, pTblName);
  102719. sqlite3DbFree(db, zName);
  102720. }
  102721. /*
  102722. ** Fill the Index.aiRowEst[] array with default information - information
  102723. ** to be used when we have not run the ANALYZE command.
  102724. **
  102725. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  102726. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  102727. ** number of rows in the table that match any particular value of the
  102728. ** first column of the index. aiRowEst[2] is an estimate of the number
  102729. ** of rows that match any particular combination of the first 2 columns
  102730. ** of the index. And so forth. It must always be the case that
  102731. *
  102732. ** aiRowEst[N]<=aiRowEst[N-1]
  102733. ** aiRowEst[N]>=1
  102734. **
  102735. ** Apart from that, we have little to go on besides intuition as to
  102736. ** how aiRowEst[] should be initialized. The numbers generated here
  102737. ** are based on typical values found in actual indices.
  102738. */
  102739. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  102740. /* 10, 9, 8, 7, 6 */
  102741. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  102742. LogEst *a = pIdx->aiRowLogEst;
  102743. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  102744. int i;
  102745. /* Indexes with default row estimates should not have stat1 data */
  102746. assert( !pIdx->hasStat1 );
  102747. /* Set the first entry (number of rows in the index) to the estimated
  102748. ** number of rows in the table, or half the number of rows in the table
  102749. ** for a partial index. But do not let the estimate drop below 10. */
  102750. a[0] = pIdx->pTable->nRowLogEst;
  102751. if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
  102752. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  102753. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  102754. ** 6 and each subsequent value (if any) is 5. */
  102755. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  102756. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  102757. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  102758. }
  102759. assert( 0==sqlite3LogEst(1) );
  102760. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  102761. }
  102762. /*
  102763. ** This routine will drop an existing named index. This routine
  102764. ** implements the DROP INDEX statement.
  102765. */
  102766. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  102767. Index *pIndex;
  102768. Vdbe *v;
  102769. sqlite3 *db = pParse->db;
  102770. int iDb;
  102771. assert( pParse->nErr==0 ); /* Never called with prior errors */
  102772. if( db->mallocFailed ){
  102773. goto exit_drop_index;
  102774. }
  102775. assert( pName->nSrc==1 );
  102776. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  102777. goto exit_drop_index;
  102778. }
  102779. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  102780. if( pIndex==0 ){
  102781. if( !ifExists ){
  102782. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  102783. }else{
  102784. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  102785. }
  102786. pParse->checkSchema = 1;
  102787. goto exit_drop_index;
  102788. }
  102789. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  102790. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  102791. "or PRIMARY KEY constraint cannot be dropped", 0);
  102792. goto exit_drop_index;
  102793. }
  102794. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  102795. #ifndef SQLITE_OMIT_AUTHORIZATION
  102796. {
  102797. int code = SQLITE_DROP_INDEX;
  102798. Table *pTab = pIndex->pTable;
  102799. const char *zDb = db->aDb[iDb].zDbSName;
  102800. const char *zTab = SCHEMA_TABLE(iDb);
  102801. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  102802. goto exit_drop_index;
  102803. }
  102804. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  102805. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  102806. goto exit_drop_index;
  102807. }
  102808. }
  102809. #endif
  102810. /* Generate code to remove the index and from the master table */
  102811. v = sqlite3GetVdbe(pParse);
  102812. if( v ){
  102813. sqlite3BeginWriteOperation(pParse, 1, iDb);
  102814. sqlite3NestedParse(pParse,
  102815. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  102816. db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
  102817. );
  102818. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  102819. sqlite3ChangeCookie(pParse, iDb);
  102820. destroyRootPage(pParse, pIndex->tnum, iDb);
  102821. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  102822. }
  102823. exit_drop_index:
  102824. sqlite3SrcListDelete(db, pName);
  102825. }
  102826. /*
  102827. ** pArray is a pointer to an array of objects. Each object in the
  102828. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  102829. ** to extend the array so that there is space for a new object at the end.
  102830. **
  102831. ** When this function is called, *pnEntry contains the current size of
  102832. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  102833. ** in total).
  102834. **
  102835. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  102836. ** space allocated for the new object is zeroed, *pnEntry updated to
  102837. ** reflect the new size of the array and a pointer to the new allocation
  102838. ** returned. *pIdx is set to the index of the new array entry in this case.
  102839. **
  102840. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  102841. ** unchanged and a copy of pArray returned.
  102842. */
  102843. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  102844. sqlite3 *db, /* Connection to notify of malloc failures */
  102845. void *pArray, /* Array of objects. Might be reallocated */
  102846. int szEntry, /* Size of each object in the array */
  102847. int *pnEntry, /* Number of objects currently in use */
  102848. int *pIdx /* Write the index of a new slot here */
  102849. ){
  102850. char *z;
  102851. int n = *pnEntry;
  102852. if( (n & (n-1))==0 ){
  102853. int sz = (n==0) ? 1 : 2*n;
  102854. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  102855. if( pNew==0 ){
  102856. *pIdx = -1;
  102857. return pArray;
  102858. }
  102859. pArray = pNew;
  102860. }
  102861. z = (char*)pArray;
  102862. memset(&z[n * szEntry], 0, szEntry);
  102863. *pIdx = n;
  102864. ++*pnEntry;
  102865. return pArray;
  102866. }
  102867. /*
  102868. ** Append a new element to the given IdList. Create a new IdList if
  102869. ** need be.
  102870. **
  102871. ** A new IdList is returned, or NULL if malloc() fails.
  102872. */
  102873. SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
  102874. sqlite3 *db = pParse->db;
  102875. int i;
  102876. if( pList==0 ){
  102877. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  102878. if( pList==0 ) return 0;
  102879. }
  102880. pList->a = sqlite3ArrayAllocate(
  102881. db,
  102882. pList->a,
  102883. sizeof(pList->a[0]),
  102884. &pList->nId,
  102885. &i
  102886. );
  102887. if( i<0 ){
  102888. sqlite3IdListDelete(db, pList);
  102889. return 0;
  102890. }
  102891. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  102892. if( IN_RENAME_OBJECT && pList->a[i].zName ){
  102893. sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
  102894. }
  102895. return pList;
  102896. }
  102897. /*
  102898. ** Delete an IdList.
  102899. */
  102900. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  102901. int i;
  102902. if( pList==0 ) return;
  102903. for(i=0; i<pList->nId; i++){
  102904. sqlite3DbFree(db, pList->a[i].zName);
  102905. }
  102906. sqlite3DbFree(db, pList->a);
  102907. sqlite3DbFreeNN(db, pList);
  102908. }
  102909. /*
  102910. ** Return the index in pList of the identifier named zId. Return -1
  102911. ** if not found.
  102912. */
  102913. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  102914. int i;
  102915. if( pList==0 ) return -1;
  102916. for(i=0; i<pList->nId; i++){
  102917. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  102918. }
  102919. return -1;
  102920. }
  102921. /*
  102922. ** Expand the space allocated for the given SrcList object by
  102923. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  102924. ** New slots are zeroed.
  102925. **
  102926. ** For example, suppose a SrcList initially contains two entries: A,B.
  102927. ** To append 3 new entries onto the end, do this:
  102928. **
  102929. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  102930. **
  102931. ** After the call above it would contain: A, B, nil, nil, nil.
  102932. ** If the iStart argument had been 1 instead of 2, then the result
  102933. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  102934. ** the iStart value would be 0. The result then would
  102935. ** be: nil, nil, nil, A, B.
  102936. **
  102937. ** If a memory allocation fails the SrcList is unchanged. The
  102938. ** db->mallocFailed flag will be set to true.
  102939. */
  102940. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  102941. sqlite3 *db, /* Database connection to notify of OOM errors */
  102942. SrcList *pSrc, /* The SrcList to be enlarged */
  102943. int nExtra, /* Number of new slots to add to pSrc->a[] */
  102944. int iStart /* Index in pSrc->a[] of first new slot */
  102945. ){
  102946. int i;
  102947. /* Sanity checking on calling parameters */
  102948. assert( iStart>=0 );
  102949. assert( nExtra>=1 );
  102950. assert( pSrc!=0 );
  102951. assert( iStart<=pSrc->nSrc );
  102952. /* Allocate additional space if needed */
  102953. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  102954. SrcList *pNew;
  102955. int nAlloc = pSrc->nSrc*2+nExtra;
  102956. int nGot;
  102957. pNew = sqlite3DbRealloc(db, pSrc,
  102958. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  102959. if( pNew==0 ){
  102960. assert( db->mallocFailed );
  102961. return pSrc;
  102962. }
  102963. pSrc = pNew;
  102964. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  102965. pSrc->nAlloc = nGot;
  102966. }
  102967. /* Move existing slots that come after the newly inserted slots
  102968. ** out of the way */
  102969. for(i=pSrc->nSrc-1; i>=iStart; i--){
  102970. pSrc->a[i+nExtra] = pSrc->a[i];
  102971. }
  102972. pSrc->nSrc += nExtra;
  102973. /* Zero the newly allocated slots */
  102974. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  102975. for(i=iStart; i<iStart+nExtra; i++){
  102976. pSrc->a[i].iCursor = -1;
  102977. }
  102978. /* Return a pointer to the enlarged SrcList */
  102979. return pSrc;
  102980. }
  102981. /*
  102982. ** Append a new table name to the given SrcList. Create a new SrcList if
  102983. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  102984. **
  102985. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  102986. ** SrcList might be the same as the SrcList that was input or it might be
  102987. ** a new one. If an OOM error does occurs, then the prior value of pList
  102988. ** that is input to this routine is automatically freed.
  102989. **
  102990. ** If pDatabase is not null, it means that the table has an optional
  102991. ** database name prefix. Like this: "database.table". The pDatabase
  102992. ** points to the table name and the pTable points to the database name.
  102993. ** The SrcList.a[].zName field is filled with the table name which might
  102994. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  102995. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  102996. ** or with NULL if no database is specified.
  102997. **
  102998. ** In other words, if call like this:
  102999. **
  103000. ** sqlite3SrcListAppend(D,A,B,0);
  103001. **
  103002. ** Then B is a table name and the database name is unspecified. If called
  103003. ** like this:
  103004. **
  103005. ** sqlite3SrcListAppend(D,A,B,C);
  103006. **
  103007. ** Then C is the table name and B is the database name. If C is defined
  103008. ** then so is B. In other words, we never have a case where:
  103009. **
  103010. ** sqlite3SrcListAppend(D,A,0,C);
  103011. **
  103012. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  103013. ** before being added to the SrcList.
  103014. */
  103015. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  103016. sqlite3 *db, /* Connection to notify of malloc failures */
  103017. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  103018. Token *pTable, /* Table to append */
  103019. Token *pDatabase /* Database of the table */
  103020. ){
  103021. struct SrcList_item *pItem;
  103022. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  103023. assert( db!=0 );
  103024. if( pList==0 ){
  103025. pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
  103026. if( pList==0 ) return 0;
  103027. pList->nAlloc = 1;
  103028. pList->nSrc = 1;
  103029. memset(&pList->a[0], 0, sizeof(pList->a[0]));
  103030. pList->a[0].iCursor = -1;
  103031. }else{
  103032. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  103033. }
  103034. if( db->mallocFailed ){
  103035. sqlite3SrcListDelete(db, pList);
  103036. return 0;
  103037. }
  103038. pItem = &pList->a[pList->nSrc-1];
  103039. if( pDatabase && pDatabase->z==0 ){
  103040. pDatabase = 0;
  103041. }
  103042. if( pDatabase ){
  103043. pItem->zName = sqlite3NameFromToken(db, pDatabase);
  103044. pItem->zDatabase = sqlite3NameFromToken(db, pTable);
  103045. }else{
  103046. pItem->zName = sqlite3NameFromToken(db, pTable);
  103047. pItem->zDatabase = 0;
  103048. }
  103049. return pList;
  103050. }
  103051. /*
  103052. ** Assign VdbeCursor index numbers to all tables in a SrcList
  103053. */
  103054. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  103055. int i;
  103056. struct SrcList_item *pItem;
  103057. assert(pList || pParse->db->mallocFailed );
  103058. if( pList ){
  103059. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  103060. if( pItem->iCursor>=0 ) break;
  103061. pItem->iCursor = pParse->nTab++;
  103062. if( pItem->pSelect ){
  103063. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  103064. }
  103065. }
  103066. }
  103067. }
  103068. /*
  103069. ** Delete an entire SrcList including all its substructure.
  103070. */
  103071. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  103072. int i;
  103073. struct SrcList_item *pItem;
  103074. if( pList==0 ) return;
  103075. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  103076. sqlite3DbFree(db, pItem->zDatabase);
  103077. sqlite3DbFree(db, pItem->zName);
  103078. sqlite3DbFree(db, pItem->zAlias);
  103079. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  103080. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  103081. sqlite3DeleteTable(db, pItem->pTab);
  103082. sqlite3SelectDelete(db, pItem->pSelect);
  103083. sqlite3ExprDelete(db, pItem->pOn);
  103084. sqlite3IdListDelete(db, pItem->pUsing);
  103085. }
  103086. sqlite3DbFreeNN(db, pList);
  103087. }
  103088. /*
  103089. ** This routine is called by the parser to add a new term to the
  103090. ** end of a growing FROM clause. The "p" parameter is the part of
  103091. ** the FROM clause that has already been constructed. "p" is NULL
  103092. ** if this is the first term of the FROM clause. pTable and pDatabase
  103093. ** are the name of the table and database named in the FROM clause term.
  103094. ** pDatabase is NULL if the database name qualifier is missing - the
  103095. ** usual case. If the term has an alias, then pAlias points to the
  103096. ** alias token. If the term is a subquery, then pSubquery is the
  103097. ** SELECT statement that the subquery encodes. The pTable and
  103098. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  103099. ** parameters are the content of the ON and USING clauses.
  103100. **
  103101. ** Return a new SrcList which encodes is the FROM with the new
  103102. ** term added.
  103103. */
  103104. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  103105. Parse *pParse, /* Parsing context */
  103106. SrcList *p, /* The left part of the FROM clause already seen */
  103107. Token *pTable, /* Name of the table to add to the FROM clause */
  103108. Token *pDatabase, /* Name of the database containing pTable */
  103109. Token *pAlias, /* The right-hand side of the AS subexpression */
  103110. Select *pSubquery, /* A subquery used in place of a table name */
  103111. Expr *pOn, /* The ON clause of a join */
  103112. IdList *pUsing /* The USING clause of a join */
  103113. ){
  103114. struct SrcList_item *pItem;
  103115. sqlite3 *db = pParse->db;
  103116. if( !p && (pOn || pUsing) ){
  103117. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  103118. (pOn ? "ON" : "USING")
  103119. );
  103120. goto append_from_error;
  103121. }
  103122. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  103123. if( p==0 ){
  103124. goto append_from_error;
  103125. }
  103126. assert( p->nSrc>0 );
  103127. pItem = &p->a[p->nSrc-1];
  103128. assert( (pTable==0)==(pDatabase==0) );
  103129. assert( pItem->zName==0 || pDatabase!=0 );
  103130. if( IN_RENAME_OBJECT && pItem->zName ){
  103131. Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
  103132. sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
  103133. }
  103134. assert( pAlias!=0 );
  103135. if( pAlias->n ){
  103136. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  103137. }
  103138. pItem->pSelect = pSubquery;
  103139. pItem->pOn = pOn;
  103140. pItem->pUsing = pUsing;
  103141. return p;
  103142. append_from_error:
  103143. assert( p==0 );
  103144. sqlite3ExprDelete(db, pOn);
  103145. sqlite3IdListDelete(db, pUsing);
  103146. sqlite3SelectDelete(db, pSubquery);
  103147. return 0;
  103148. }
  103149. /*
  103150. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  103151. ** element of the source-list passed as the second argument.
  103152. */
  103153. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  103154. assert( pIndexedBy!=0 );
  103155. if( p && pIndexedBy->n>0 ){
  103156. struct SrcList_item *pItem;
  103157. assert( p->nSrc>0 );
  103158. pItem = &p->a[p->nSrc-1];
  103159. assert( pItem->fg.notIndexed==0 );
  103160. assert( pItem->fg.isIndexedBy==0 );
  103161. assert( pItem->fg.isTabFunc==0 );
  103162. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  103163. /* A "NOT INDEXED" clause was supplied. See parse.y
  103164. ** construct "indexed_opt" for details. */
  103165. pItem->fg.notIndexed = 1;
  103166. }else{
  103167. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  103168. pItem->fg.isIndexedBy = 1;
  103169. }
  103170. }
  103171. }
  103172. /*
  103173. ** Add the list of function arguments to the SrcList entry for a
  103174. ** table-valued-function.
  103175. */
  103176. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  103177. if( p ){
  103178. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  103179. assert( pItem->fg.notIndexed==0 );
  103180. assert( pItem->fg.isIndexedBy==0 );
  103181. assert( pItem->fg.isTabFunc==0 );
  103182. pItem->u1.pFuncArg = pList;
  103183. pItem->fg.isTabFunc = 1;
  103184. }else{
  103185. sqlite3ExprListDelete(pParse->db, pList);
  103186. }
  103187. }
  103188. /*
  103189. ** When building up a FROM clause in the parser, the join operator
  103190. ** is initially attached to the left operand. But the code generator
  103191. ** expects the join operator to be on the right operand. This routine
  103192. ** Shifts all join operators from left to right for an entire FROM
  103193. ** clause.
  103194. **
  103195. ** Example: Suppose the join is like this:
  103196. **
  103197. ** A natural cross join B
  103198. **
  103199. ** The operator is "natural cross join". The A and B operands are stored
  103200. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  103201. ** operator with A. This routine shifts that operator over to B.
  103202. */
  103203. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  103204. if( p ){
  103205. int i;
  103206. for(i=p->nSrc-1; i>0; i--){
  103207. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  103208. }
  103209. p->a[0].fg.jointype = 0;
  103210. }
  103211. }
  103212. /*
  103213. ** Generate VDBE code for a BEGIN statement.
  103214. */
  103215. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  103216. sqlite3 *db;
  103217. Vdbe *v;
  103218. int i;
  103219. assert( pParse!=0 );
  103220. db = pParse->db;
  103221. assert( db!=0 );
  103222. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  103223. return;
  103224. }
  103225. v = sqlite3GetVdbe(pParse);
  103226. if( !v ) return;
  103227. if( type!=TK_DEFERRED ){
  103228. for(i=0; i<db->nDb; i++){
  103229. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  103230. sqlite3VdbeUsesBtree(v, i);
  103231. }
  103232. }
  103233. sqlite3VdbeAddOp0(v, OP_AutoCommit);
  103234. }
  103235. /*
  103236. ** Generate VDBE code for a COMMIT or ROLLBACK statement.
  103237. ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
  103238. ** code is generated for a COMMIT.
  103239. */
  103240. SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
  103241. Vdbe *v;
  103242. int isRollback;
  103243. assert( pParse!=0 );
  103244. assert( pParse->db!=0 );
  103245. assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
  103246. isRollback = eType==TK_ROLLBACK;
  103247. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
  103248. isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
  103249. return;
  103250. }
  103251. v = sqlite3GetVdbe(pParse);
  103252. if( v ){
  103253. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
  103254. }
  103255. }
  103256. /*
  103257. ** This function is called by the parser when it parses a command to create,
  103258. ** release or rollback an SQL savepoint.
  103259. */
  103260. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  103261. char *zName = sqlite3NameFromToken(pParse->db, pName);
  103262. if( zName ){
  103263. Vdbe *v = sqlite3GetVdbe(pParse);
  103264. #ifndef SQLITE_OMIT_AUTHORIZATION
  103265. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  103266. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  103267. #endif
  103268. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  103269. sqlite3DbFree(pParse->db, zName);
  103270. return;
  103271. }
  103272. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  103273. }
  103274. }
  103275. /*
  103276. ** Make sure the TEMP database is open and available for use. Return
  103277. ** the number of errors. Leave any error messages in the pParse structure.
  103278. */
  103279. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  103280. sqlite3 *db = pParse->db;
  103281. if( db->aDb[1].pBt==0 && !pParse->explain ){
  103282. int rc;
  103283. Btree *pBt;
  103284. static const int flags =
  103285. SQLITE_OPEN_READWRITE |
  103286. SQLITE_OPEN_CREATE |
  103287. SQLITE_OPEN_EXCLUSIVE |
  103288. SQLITE_OPEN_DELETEONCLOSE |
  103289. SQLITE_OPEN_TEMP_DB;
  103290. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  103291. if( rc!=SQLITE_OK ){
  103292. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  103293. "file for storing temporary tables");
  103294. pParse->rc = rc;
  103295. return 1;
  103296. }
  103297. db->aDb[1].pBt = pBt;
  103298. assert( db->aDb[1].pSchema );
  103299. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  103300. sqlite3OomFault(db);
  103301. return 1;
  103302. }
  103303. }
  103304. return 0;
  103305. }
  103306. /*
  103307. ** Record the fact that the schema cookie will need to be verified
  103308. ** for database iDb. The code to actually verify the schema cookie
  103309. ** will occur at the end of the top-level VDBE and will be generated
  103310. ** later, by sqlite3FinishCoding().
  103311. */
  103312. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  103313. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  103314. assert( iDb>=0 && iDb<pParse->db->nDb );
  103315. assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
  103316. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  103317. assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
  103318. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  103319. DbMaskSet(pToplevel->cookieMask, iDb);
  103320. if( !OMIT_TEMPDB && iDb==1 ){
  103321. sqlite3OpenTempDatabase(pToplevel);
  103322. }
  103323. }
  103324. }
  103325. /*
  103326. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  103327. ** attached database. Otherwise, invoke it for the database named zDb only.
  103328. */
  103329. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  103330. sqlite3 *db = pParse->db;
  103331. int i;
  103332. for(i=0; i<db->nDb; i++){
  103333. Db *pDb = &db->aDb[i];
  103334. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
  103335. sqlite3CodeVerifySchema(pParse, i);
  103336. }
  103337. }
  103338. }
  103339. /*
  103340. ** Generate VDBE code that prepares for doing an operation that
  103341. ** might change the database.
  103342. **
  103343. ** This routine starts a new transaction if we are not already within
  103344. ** a transaction. If we are already within a transaction, then a checkpoint
  103345. ** is set if the setStatement parameter is true. A checkpoint should
  103346. ** be set for operations that might fail (due to a constraint) part of
  103347. ** the way through and which will need to undo some writes without having to
  103348. ** rollback the whole transaction. For operations where all constraints
  103349. ** can be checked before any changes are made to the database, it is never
  103350. ** necessary to undo a write and the checkpoint should not be set.
  103351. */
  103352. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  103353. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  103354. sqlite3CodeVerifySchema(pParse, iDb);
  103355. DbMaskSet(pToplevel->writeMask, iDb);
  103356. pToplevel->isMultiWrite |= setStatement;
  103357. }
  103358. /*
  103359. ** Indicate that the statement currently under construction might write
  103360. ** more than one entry (example: deleting one row then inserting another,
  103361. ** inserting multiple rows in a table, or inserting a row and index entries.)
  103362. ** If an abort occurs after some of these writes have completed, then it will
  103363. ** be necessary to undo the completed writes.
  103364. */
  103365. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  103366. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  103367. pToplevel->isMultiWrite = 1;
  103368. }
  103369. /*
  103370. ** The code generator calls this routine if is discovers that it is
  103371. ** possible to abort a statement prior to completion. In order to
  103372. ** perform this abort without corrupting the database, we need to make
  103373. ** sure that the statement is protected by a statement transaction.
  103374. **
  103375. ** Technically, we only need to set the mayAbort flag if the
  103376. ** isMultiWrite flag was previously set. There is a time dependency
  103377. ** such that the abort must occur after the multiwrite. This makes
  103378. ** some statements involving the REPLACE conflict resolution algorithm
  103379. ** go a little faster. But taking advantage of this time dependency
  103380. ** makes it more difficult to prove that the code is correct (in
  103381. ** particular, it prevents us from writing an effective
  103382. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  103383. ** to take the safe route and skip the optimization.
  103384. */
  103385. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  103386. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  103387. pToplevel->mayAbort = 1;
  103388. }
  103389. /*
  103390. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  103391. ** error. The onError parameter determines which (if any) of the statement
  103392. ** and/or current transaction is rolled back.
  103393. */
  103394. SQLITE_PRIVATE void sqlite3HaltConstraint(
  103395. Parse *pParse, /* Parsing context */
  103396. int errCode, /* extended error code */
  103397. int onError, /* Constraint type */
  103398. char *p4, /* Error message */
  103399. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  103400. u8 p5Errmsg /* P5_ErrMsg type */
  103401. ){
  103402. Vdbe *v = sqlite3GetVdbe(pParse);
  103403. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  103404. if( onError==OE_Abort ){
  103405. sqlite3MayAbort(pParse);
  103406. }
  103407. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  103408. sqlite3VdbeChangeP5(v, p5Errmsg);
  103409. }
  103410. /*
  103411. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  103412. */
  103413. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  103414. Parse *pParse, /* Parsing context */
  103415. int onError, /* Constraint type */
  103416. Index *pIdx /* The index that triggers the constraint */
  103417. ){
  103418. char *zErr;
  103419. int j;
  103420. StrAccum errMsg;
  103421. Table *pTab = pIdx->pTable;
  103422. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
  103423. if( pIdx->aColExpr ){
  103424. sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
  103425. }else{
  103426. for(j=0; j<pIdx->nKeyCol; j++){
  103427. char *zCol;
  103428. assert( pIdx->aiColumn[j]>=0 );
  103429. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  103430. if( j ) sqlite3_str_append(&errMsg, ", ", 2);
  103431. sqlite3_str_appendall(&errMsg, pTab->zName);
  103432. sqlite3_str_append(&errMsg, ".", 1);
  103433. sqlite3_str_appendall(&errMsg, zCol);
  103434. }
  103435. }
  103436. zErr = sqlite3StrAccumFinish(&errMsg);
  103437. sqlite3HaltConstraint(pParse,
  103438. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  103439. : SQLITE_CONSTRAINT_UNIQUE,
  103440. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  103441. }
  103442. /*
  103443. ** Code an OP_Halt due to non-unique rowid.
  103444. */
  103445. SQLITE_PRIVATE void sqlite3RowidConstraint(
  103446. Parse *pParse, /* Parsing context */
  103447. int onError, /* Conflict resolution algorithm */
  103448. Table *pTab /* The table with the non-unique rowid */
  103449. ){
  103450. char *zMsg;
  103451. int rc;
  103452. if( pTab->iPKey>=0 ){
  103453. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  103454. pTab->aCol[pTab->iPKey].zName);
  103455. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  103456. }else{
  103457. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  103458. rc = SQLITE_CONSTRAINT_ROWID;
  103459. }
  103460. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  103461. P5_ConstraintUnique);
  103462. }
  103463. /*
  103464. ** Check to see if pIndex uses the collating sequence pColl. Return
  103465. ** true if it does and false if it does not.
  103466. */
  103467. #ifndef SQLITE_OMIT_REINDEX
  103468. static int collationMatch(const char *zColl, Index *pIndex){
  103469. int i;
  103470. assert( zColl!=0 );
  103471. for(i=0; i<pIndex->nColumn; i++){
  103472. const char *z = pIndex->azColl[i];
  103473. assert( z!=0 || pIndex->aiColumn[i]<0 );
  103474. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  103475. return 1;
  103476. }
  103477. }
  103478. return 0;
  103479. }
  103480. #endif
  103481. /*
  103482. ** Recompute all indices of pTab that use the collating sequence pColl.
  103483. ** If pColl==0 then recompute all indices of pTab.
  103484. */
  103485. #ifndef SQLITE_OMIT_REINDEX
  103486. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  103487. Index *pIndex; /* An index associated with pTab */
  103488. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  103489. if( zColl==0 || collationMatch(zColl, pIndex) ){
  103490. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  103491. sqlite3BeginWriteOperation(pParse, 0, iDb);
  103492. sqlite3RefillIndex(pParse, pIndex, -1);
  103493. }
  103494. }
  103495. }
  103496. #endif
  103497. /*
  103498. ** Recompute all indices of all tables in all databases where the
  103499. ** indices use the collating sequence pColl. If pColl==0 then recompute
  103500. ** all indices everywhere.
  103501. */
  103502. #ifndef SQLITE_OMIT_REINDEX
  103503. static void reindexDatabases(Parse *pParse, char const *zColl){
  103504. Db *pDb; /* A single database */
  103505. int iDb; /* The database index number */
  103506. sqlite3 *db = pParse->db; /* The database connection */
  103507. HashElem *k; /* For looping over tables in pDb */
  103508. Table *pTab; /* A table in the database */
  103509. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  103510. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  103511. assert( pDb!=0 );
  103512. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  103513. pTab = (Table*)sqliteHashData(k);
  103514. reindexTable(pParse, pTab, zColl);
  103515. }
  103516. }
  103517. }
  103518. #endif
  103519. /*
  103520. ** Generate code for the REINDEX command.
  103521. **
  103522. ** REINDEX -- 1
  103523. ** REINDEX <collation> -- 2
  103524. ** REINDEX ?<database>.?<tablename> -- 3
  103525. ** REINDEX ?<database>.?<indexname> -- 4
  103526. **
  103527. ** Form 1 causes all indices in all attached databases to be rebuilt.
  103528. ** Form 2 rebuilds all indices in all databases that use the named
  103529. ** collating function. Forms 3 and 4 rebuild the named index or all
  103530. ** indices associated with the named table.
  103531. */
  103532. #ifndef SQLITE_OMIT_REINDEX
  103533. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  103534. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  103535. char *z; /* Name of a table or index */
  103536. const char *zDb; /* Name of the database */
  103537. Table *pTab; /* A table in the database */
  103538. Index *pIndex; /* An index associated with pTab */
  103539. int iDb; /* The database index number */
  103540. sqlite3 *db = pParse->db; /* The database connection */
  103541. Token *pObjName; /* Name of the table or index to be reindexed */
  103542. /* Read the database schema. If an error occurs, leave an error message
  103543. ** and code in pParse and return NULL. */
  103544. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  103545. return;
  103546. }
  103547. if( pName1==0 ){
  103548. reindexDatabases(pParse, 0);
  103549. return;
  103550. }else if( NEVER(pName2==0) || pName2->z==0 ){
  103551. char *zColl;
  103552. assert( pName1->z );
  103553. zColl = sqlite3NameFromToken(pParse->db, pName1);
  103554. if( !zColl ) return;
  103555. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  103556. if( pColl ){
  103557. reindexDatabases(pParse, zColl);
  103558. sqlite3DbFree(db, zColl);
  103559. return;
  103560. }
  103561. sqlite3DbFree(db, zColl);
  103562. }
  103563. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  103564. if( iDb<0 ) return;
  103565. z = sqlite3NameFromToken(db, pObjName);
  103566. if( z==0 ) return;
  103567. zDb = db->aDb[iDb].zDbSName;
  103568. pTab = sqlite3FindTable(db, z, zDb);
  103569. if( pTab ){
  103570. reindexTable(pParse, pTab, 0);
  103571. sqlite3DbFree(db, z);
  103572. return;
  103573. }
  103574. pIndex = sqlite3FindIndex(db, z, zDb);
  103575. sqlite3DbFree(db, z);
  103576. if( pIndex ){
  103577. sqlite3BeginWriteOperation(pParse, 0, iDb);
  103578. sqlite3RefillIndex(pParse, pIndex, -1);
  103579. return;
  103580. }
  103581. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  103582. }
  103583. #endif
  103584. /*
  103585. ** Return a KeyInfo structure that is appropriate for the given Index.
  103586. **
  103587. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  103588. ** when it has finished using it.
  103589. */
  103590. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  103591. int i;
  103592. int nCol = pIdx->nColumn;
  103593. int nKey = pIdx->nKeyCol;
  103594. KeyInfo *pKey;
  103595. if( pParse->nErr ) return 0;
  103596. if( pIdx->uniqNotNull ){
  103597. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  103598. }else{
  103599. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  103600. }
  103601. if( pKey ){
  103602. assert( sqlite3KeyInfoIsWriteable(pKey) );
  103603. for(i=0; i<nCol; i++){
  103604. const char *zColl = pIdx->azColl[i];
  103605. pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
  103606. sqlite3LocateCollSeq(pParse, zColl);
  103607. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  103608. }
  103609. if( pParse->nErr ){
  103610. assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
  103611. if( pIdx->bNoQuery==0 ){
  103612. /* Deactivate the index because it contains an unknown collating
  103613. ** sequence. The only way to reactive the index is to reload the
  103614. ** schema. Adding the missing collating sequence later does not
  103615. ** reactive the index. The application had the chance to register
  103616. ** the missing index using the collation-needed callback. For
  103617. ** simplicity, SQLite will not give the application a second chance.
  103618. */
  103619. pIdx->bNoQuery = 1;
  103620. pParse->rc = SQLITE_ERROR_RETRY;
  103621. }
  103622. sqlite3KeyInfoUnref(pKey);
  103623. pKey = 0;
  103624. }
  103625. }
  103626. return pKey;
  103627. }
  103628. #ifndef SQLITE_OMIT_CTE
  103629. /*
  103630. ** This routine is invoked once per CTE by the parser while parsing a
  103631. ** WITH clause.
  103632. */
  103633. SQLITE_PRIVATE With *sqlite3WithAdd(
  103634. Parse *pParse, /* Parsing context */
  103635. With *pWith, /* Existing WITH clause, or NULL */
  103636. Token *pName, /* Name of the common-table */
  103637. ExprList *pArglist, /* Optional column name list for the table */
  103638. Select *pQuery /* Query used to initialize the table */
  103639. ){
  103640. sqlite3 *db = pParse->db;
  103641. With *pNew;
  103642. char *zName;
  103643. /* Check that the CTE name is unique within this WITH clause. If
  103644. ** not, store an error in the Parse structure. */
  103645. zName = sqlite3NameFromToken(pParse->db, pName);
  103646. if( zName && pWith ){
  103647. int i;
  103648. for(i=0; i<pWith->nCte; i++){
  103649. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  103650. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  103651. }
  103652. }
  103653. }
  103654. if( pWith ){
  103655. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  103656. pNew = sqlite3DbRealloc(db, pWith, nByte);
  103657. }else{
  103658. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  103659. }
  103660. assert( (pNew!=0 && zName!=0) || db->mallocFailed );
  103661. if( db->mallocFailed ){
  103662. sqlite3ExprListDelete(db, pArglist);
  103663. sqlite3SelectDelete(db, pQuery);
  103664. sqlite3DbFree(db, zName);
  103665. pNew = pWith;
  103666. }else{
  103667. pNew->a[pNew->nCte].pSelect = pQuery;
  103668. pNew->a[pNew->nCte].pCols = pArglist;
  103669. pNew->a[pNew->nCte].zName = zName;
  103670. pNew->a[pNew->nCte].zCteErr = 0;
  103671. pNew->nCte++;
  103672. }
  103673. return pNew;
  103674. }
  103675. /*
  103676. ** Free the contents of the With object passed as the second argument.
  103677. */
  103678. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  103679. if( pWith ){
  103680. int i;
  103681. for(i=0; i<pWith->nCte; i++){
  103682. struct Cte *pCte = &pWith->a[i];
  103683. sqlite3ExprListDelete(db, pCte->pCols);
  103684. sqlite3SelectDelete(db, pCte->pSelect);
  103685. sqlite3DbFree(db, pCte->zName);
  103686. }
  103687. sqlite3DbFree(db, pWith);
  103688. }
  103689. }
  103690. #endif /* !defined(SQLITE_OMIT_CTE) */
  103691. /************** End of build.c ***********************************************/
  103692. /************** Begin file callback.c ****************************************/
  103693. /*
  103694. ** 2005 May 23
  103695. **
  103696. ** The author disclaims copyright to this source code. In place of
  103697. ** a legal notice, here is a blessing:
  103698. **
  103699. ** May you do good and not evil.
  103700. ** May you find forgiveness for yourself and forgive others.
  103701. ** May you share freely, never taking more than you give.
  103702. **
  103703. *************************************************************************
  103704. **
  103705. ** This file contains functions used to access the internal hash tables
  103706. ** of user defined functions and collation sequences.
  103707. */
  103708. /* #include "sqliteInt.h" */
  103709. /*
  103710. ** Invoke the 'collation needed' callback to request a collation sequence
  103711. ** in the encoding enc of name zName, length nName.
  103712. */
  103713. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  103714. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  103715. if( db->xCollNeeded ){
  103716. char *zExternal = sqlite3DbStrDup(db, zName);
  103717. if( !zExternal ) return;
  103718. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  103719. sqlite3DbFree(db, zExternal);
  103720. }
  103721. #ifndef SQLITE_OMIT_UTF16
  103722. if( db->xCollNeeded16 ){
  103723. char const *zExternal;
  103724. sqlite3_value *pTmp = sqlite3ValueNew(db);
  103725. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  103726. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  103727. if( zExternal ){
  103728. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  103729. }
  103730. sqlite3ValueFree(pTmp);
  103731. }
  103732. #endif
  103733. }
  103734. /*
  103735. ** This routine is called if the collation factory fails to deliver a
  103736. ** collation function in the best encoding but there may be other versions
  103737. ** of this collation function (for other text encodings) available. Use one
  103738. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  103739. ** possible.
  103740. */
  103741. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  103742. CollSeq *pColl2;
  103743. char *z = pColl->zName;
  103744. int i;
  103745. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  103746. for(i=0; i<3; i++){
  103747. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  103748. if( pColl2->xCmp!=0 ){
  103749. memcpy(pColl, pColl2, sizeof(CollSeq));
  103750. pColl->xDel = 0; /* Do not copy the destructor */
  103751. return SQLITE_OK;
  103752. }
  103753. }
  103754. return SQLITE_ERROR;
  103755. }
  103756. /*
  103757. ** This function is responsible for invoking the collation factory callback
  103758. ** or substituting a collation sequence of a different encoding when the
  103759. ** requested collation sequence is not available in the desired encoding.
  103760. **
  103761. ** If it is not NULL, then pColl must point to the database native encoding
  103762. ** collation sequence with name zName, length nName.
  103763. **
  103764. ** The return value is either the collation sequence to be used in database
  103765. ** db for collation type name zName, length nName, or NULL, if no collation
  103766. ** sequence can be found. If no collation is found, leave an error message.
  103767. **
  103768. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  103769. */
  103770. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  103771. Parse *pParse, /* Parsing context */
  103772. u8 enc, /* The desired encoding for the collating sequence */
  103773. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  103774. const char *zName /* Collating sequence name */
  103775. ){
  103776. CollSeq *p;
  103777. sqlite3 *db = pParse->db;
  103778. p = pColl;
  103779. if( !p ){
  103780. p = sqlite3FindCollSeq(db, enc, zName, 0);
  103781. }
  103782. if( !p || !p->xCmp ){
  103783. /* No collation sequence of this type for this encoding is registered.
  103784. ** Call the collation factory to see if it can supply us with one.
  103785. */
  103786. callCollNeeded(db, enc, zName);
  103787. p = sqlite3FindCollSeq(db, enc, zName, 0);
  103788. }
  103789. if( p && !p->xCmp && synthCollSeq(db, p) ){
  103790. p = 0;
  103791. }
  103792. assert( !p || p->xCmp );
  103793. if( p==0 ){
  103794. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  103795. pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
  103796. }
  103797. return p;
  103798. }
  103799. /*
  103800. ** This routine is called on a collation sequence before it is used to
  103801. ** check that it is defined. An undefined collation sequence exists when
  103802. ** a database is loaded that contains references to collation sequences
  103803. ** that have not been defined by sqlite3_create_collation() etc.
  103804. **
  103805. ** If required, this routine calls the 'collation needed' callback to
  103806. ** request a definition of the collating sequence. If this doesn't work,
  103807. ** an equivalent collating sequence that uses a text encoding different
  103808. ** from the main database is substituted, if one is available.
  103809. */
  103810. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  103811. if( pColl && pColl->xCmp==0 ){
  103812. const char *zName = pColl->zName;
  103813. sqlite3 *db = pParse->db;
  103814. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  103815. if( !p ){
  103816. return SQLITE_ERROR;
  103817. }
  103818. assert( p==pColl );
  103819. }
  103820. return SQLITE_OK;
  103821. }
  103822. /*
  103823. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  103824. ** specified by zName and nName is not found and parameter 'create' is
  103825. ** true, then create a new entry. Otherwise return NULL.
  103826. **
  103827. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  103828. ** array of three CollSeq structures. The first is the collation sequence
  103829. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  103830. **
  103831. ** Stored immediately after the three collation sequences is a copy of
  103832. ** the collation sequence name. A pointer to this string is stored in
  103833. ** each collation sequence structure.
  103834. */
  103835. static CollSeq *findCollSeqEntry(
  103836. sqlite3 *db, /* Database connection */
  103837. const char *zName, /* Name of the collating sequence */
  103838. int create /* Create a new entry if true */
  103839. ){
  103840. CollSeq *pColl;
  103841. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  103842. if( 0==pColl && create ){
  103843. int nName = sqlite3Strlen30(zName) + 1;
  103844. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
  103845. if( pColl ){
  103846. CollSeq *pDel = 0;
  103847. pColl[0].zName = (char*)&pColl[3];
  103848. pColl[0].enc = SQLITE_UTF8;
  103849. pColl[1].zName = (char*)&pColl[3];
  103850. pColl[1].enc = SQLITE_UTF16LE;
  103851. pColl[2].zName = (char*)&pColl[3];
  103852. pColl[2].enc = SQLITE_UTF16BE;
  103853. memcpy(pColl[0].zName, zName, nName);
  103854. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  103855. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  103856. ** return the pColl pointer to be deleted (because it wasn't added
  103857. ** to the hash table).
  103858. */
  103859. assert( pDel==0 || pDel==pColl );
  103860. if( pDel!=0 ){
  103861. sqlite3OomFault(db);
  103862. sqlite3DbFree(db, pDel);
  103863. pColl = 0;
  103864. }
  103865. }
  103866. }
  103867. return pColl;
  103868. }
  103869. /*
  103870. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  103871. ** Return the CollSeq* pointer for the collation sequence named zName
  103872. ** for the encoding 'enc' from the database 'db'.
  103873. **
  103874. ** If the entry specified is not found and 'create' is true, then create a
  103875. ** new entry. Otherwise return NULL.
  103876. **
  103877. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  103878. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  103879. ** if necessary and generates an error message if the collating sequence
  103880. ** cannot be found.
  103881. **
  103882. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  103883. */
  103884. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  103885. sqlite3 *db,
  103886. u8 enc,
  103887. const char *zName,
  103888. int create
  103889. ){
  103890. CollSeq *pColl;
  103891. if( zName ){
  103892. pColl = findCollSeqEntry(db, zName, create);
  103893. }else{
  103894. pColl = db->pDfltColl;
  103895. }
  103896. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  103897. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  103898. if( pColl ) pColl += enc-1;
  103899. return pColl;
  103900. }
  103901. /* During the search for the best function definition, this procedure
  103902. ** is called to test how well the function passed as the first argument
  103903. ** matches the request for a function with nArg arguments in a system
  103904. ** that uses encoding enc. The value returned indicates how well the
  103905. ** request is matched. A higher value indicates a better match.
  103906. **
  103907. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  103908. ** is also -1. In other words, we are searching for a function that
  103909. ** takes a variable number of arguments.
  103910. **
  103911. ** If nArg is -2 that means that we are searching for any function
  103912. ** regardless of the number of arguments it uses, so return a positive
  103913. ** match score for any
  103914. **
  103915. ** The returned value is always between 0 and 6, as follows:
  103916. **
  103917. ** 0: Not a match.
  103918. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  103919. ** 2: UTF16 byte order change required and function takes any number of args.
  103920. ** 3: encoding matches and function takes any number of arguments
  103921. ** 4: UTF8/16 conversion required - argument count matches exactly
  103922. ** 5: UTF16 byte order conversion required - argument count matches exactly
  103923. ** 6: Perfect match: encoding and argument count match exactly.
  103924. **
  103925. ** If nArg==(-2) then any function with a non-null xSFunc is
  103926. ** a perfect match and any function with xSFunc NULL is
  103927. ** a non-match.
  103928. */
  103929. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  103930. static int matchQuality(
  103931. FuncDef *p, /* The function we are evaluating for match quality */
  103932. int nArg, /* Desired number of arguments. (-1)==any */
  103933. u8 enc /* Desired text encoding */
  103934. ){
  103935. int match;
  103936. /* nArg of -2 is a special case */
  103937. if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
  103938. /* Wrong number of arguments means "no match" */
  103939. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  103940. /* Give a better score to a function with a specific number of arguments
  103941. ** than to function that accepts any number of arguments. */
  103942. if( p->nArg==nArg ){
  103943. match = 4;
  103944. }else{
  103945. match = 1;
  103946. }
  103947. /* Bonus points if the text encoding matches */
  103948. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  103949. match += 2; /* Exact encoding match */
  103950. }else if( (enc & p->funcFlags & 2)!=0 ){
  103951. match += 1; /* Both are UTF16, but with different byte orders */
  103952. }
  103953. return match;
  103954. }
  103955. /*
  103956. ** Search a FuncDefHash for a function with the given name. Return
  103957. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  103958. */
  103959. static FuncDef *functionSearch(
  103960. int h, /* Hash of the name */
  103961. const char *zFunc /* Name of function */
  103962. ){
  103963. FuncDef *p;
  103964. for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
  103965. if( sqlite3StrICmp(p->zName, zFunc)==0 ){
  103966. return p;
  103967. }
  103968. }
  103969. return 0;
  103970. }
  103971. #ifdef SQLITE_ENABLE_NORMALIZE
  103972. SQLITE_PRIVATE FuncDef *sqlite3FunctionSearchN(
  103973. int h, /* Hash of the name */
  103974. const char *zFunc, /* Name of function */
  103975. int nFunc /* Length of the name */
  103976. ){
  103977. FuncDef *p;
  103978. for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
  103979. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 ){
  103980. return p;
  103981. }
  103982. }
  103983. return 0;
  103984. }
  103985. #endif /* SQLITE_ENABLE_NORMALIZE */
  103986. /*
  103987. ** Insert a new FuncDef into a FuncDefHash hash table.
  103988. */
  103989. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
  103990. FuncDef *aDef, /* List of global functions to be inserted */
  103991. int nDef /* Length of the apDef[] list */
  103992. ){
  103993. int i;
  103994. for(i=0; i<nDef; i++){
  103995. FuncDef *pOther;
  103996. const char *zName = aDef[i].zName;
  103997. int nName = sqlite3Strlen30(zName);
  103998. int h = SQLITE_FUNC_HASH(zName[0], nName);
  103999. assert( zName[0]>='a' && zName[0]<='z' );
  104000. pOther = functionSearch(h, zName);
  104001. if( pOther ){
  104002. assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
  104003. aDef[i].pNext = pOther->pNext;
  104004. pOther->pNext = &aDef[i];
  104005. }else{
  104006. aDef[i].pNext = 0;
  104007. aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
  104008. sqlite3BuiltinFunctions.a[h] = &aDef[i];
  104009. }
  104010. }
  104011. }
  104012. /*
  104013. ** Locate a user function given a name, a number of arguments and a flag
  104014. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  104015. ** pointer to the FuncDef structure that defines that function, or return
  104016. ** NULL if the function does not exist.
  104017. **
  104018. ** If the createFlag argument is true, then a new (blank) FuncDef
  104019. ** structure is created and liked into the "db" structure if a
  104020. ** no matching function previously existed.
  104021. **
  104022. ** If nArg is -2, then the first valid function found is returned. A
  104023. ** function is valid if xSFunc is non-zero. The nArg==(-2)
  104024. ** case is used to see if zName is a valid function name for some number
  104025. ** of arguments. If nArg is -2, then createFlag must be 0.
  104026. **
  104027. ** If createFlag is false, then a function with the required name and
  104028. ** number of arguments may be returned even if the eTextRep flag does not
  104029. ** match that requested.
  104030. */
  104031. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  104032. sqlite3 *db, /* An open database */
  104033. const char *zName, /* Name of the function. zero-terminated */
  104034. int nArg, /* Number of arguments. -1 means any number */
  104035. u8 enc, /* Preferred text encoding */
  104036. u8 createFlag /* Create new entry if true and does not otherwise exist */
  104037. ){
  104038. FuncDef *p; /* Iterator variable */
  104039. FuncDef *pBest = 0; /* Best match found so far */
  104040. int bestScore = 0; /* Score of best match */
  104041. int h; /* Hash value */
  104042. int nName; /* Length of the name */
  104043. assert( nArg>=(-2) );
  104044. assert( nArg>=(-1) || createFlag==0 );
  104045. nName = sqlite3Strlen30(zName);
  104046. /* First search for a match amongst the application-defined functions.
  104047. */
  104048. p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
  104049. while( p ){
  104050. int score = matchQuality(p, nArg, enc);
  104051. if( score>bestScore ){
  104052. pBest = p;
  104053. bestScore = score;
  104054. }
  104055. p = p->pNext;
  104056. }
  104057. /* If no match is found, search the built-in functions.
  104058. **
  104059. ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
  104060. ** functions even if a prior app-defined function was found. And give
  104061. ** priority to built-in functions.
  104062. **
  104063. ** Except, if createFlag is true, that means that we are trying to
  104064. ** install a new function. Whatever FuncDef structure is returned it will
  104065. ** have fields overwritten with new information appropriate for the
  104066. ** new function. But the FuncDefs for built-in functions are read-only.
  104067. ** So we must not search for built-ins when creating a new function.
  104068. */
  104069. if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
  104070. bestScore = 0;
  104071. h = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zName[0]], nName);
  104072. p = functionSearch(h, zName);
  104073. while( p ){
  104074. int score = matchQuality(p, nArg, enc);
  104075. if( score>bestScore ){
  104076. pBest = p;
  104077. bestScore = score;
  104078. }
  104079. p = p->pNext;
  104080. }
  104081. }
  104082. /* If the createFlag parameter is true and the search did not reveal an
  104083. ** exact match for the name, number of arguments and encoding, then add a
  104084. ** new entry to the hash table and return it.
  104085. */
  104086. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  104087. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  104088. FuncDef *pOther;
  104089. u8 *z;
  104090. pBest->zName = (const char*)&pBest[1];
  104091. pBest->nArg = (u16)nArg;
  104092. pBest->funcFlags = enc;
  104093. memcpy((char*)&pBest[1], zName, nName+1);
  104094. for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];
  104095. pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
  104096. if( pOther==pBest ){
  104097. sqlite3DbFree(db, pBest);
  104098. sqlite3OomFault(db);
  104099. return 0;
  104100. }else{
  104101. pBest->pNext = pOther;
  104102. }
  104103. }
  104104. if( pBest && (pBest->xSFunc || createFlag) ){
  104105. return pBest;
  104106. }
  104107. return 0;
  104108. }
  104109. /*
  104110. ** Free all resources held by the schema structure. The void* argument points
  104111. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  104112. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  104113. ** of the schema hash tables).
  104114. **
  104115. ** The Schema.cache_size variable is not cleared.
  104116. */
  104117. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  104118. Hash temp1;
  104119. Hash temp2;
  104120. HashElem *pElem;
  104121. Schema *pSchema = (Schema *)p;
  104122. temp1 = pSchema->tblHash;
  104123. temp2 = pSchema->trigHash;
  104124. sqlite3HashInit(&pSchema->trigHash);
  104125. sqlite3HashClear(&pSchema->idxHash);
  104126. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  104127. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  104128. }
  104129. sqlite3HashClear(&temp2);
  104130. sqlite3HashInit(&pSchema->tblHash);
  104131. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  104132. Table *pTab = sqliteHashData(pElem);
  104133. sqlite3DeleteTable(0, pTab);
  104134. }
  104135. sqlite3HashClear(&temp1);
  104136. sqlite3HashClear(&pSchema->fkeyHash);
  104137. pSchema->pSeqTab = 0;
  104138. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  104139. pSchema->iGeneration++;
  104140. }
  104141. pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
  104142. }
  104143. /*
  104144. ** Find and return the schema associated with a BTree. Create
  104145. ** a new one if necessary.
  104146. */
  104147. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  104148. Schema * p;
  104149. if( pBt ){
  104150. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  104151. }else{
  104152. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  104153. }
  104154. if( !p ){
  104155. sqlite3OomFault(db);
  104156. }else if ( 0==p->file_format ){
  104157. sqlite3HashInit(&p->tblHash);
  104158. sqlite3HashInit(&p->idxHash);
  104159. sqlite3HashInit(&p->trigHash);
  104160. sqlite3HashInit(&p->fkeyHash);
  104161. p->enc = SQLITE_UTF8;
  104162. }
  104163. return p;
  104164. }
  104165. /************** End of callback.c ********************************************/
  104166. /************** Begin file delete.c ******************************************/
  104167. /*
  104168. ** 2001 September 15
  104169. **
  104170. ** The author disclaims copyright to this source code. In place of
  104171. ** a legal notice, here is a blessing:
  104172. **
  104173. ** May you do good and not evil.
  104174. ** May you find forgiveness for yourself and forgive others.
  104175. ** May you share freely, never taking more than you give.
  104176. **
  104177. *************************************************************************
  104178. ** This file contains C code routines that are called by the parser
  104179. ** in order to generate code for DELETE FROM statements.
  104180. */
  104181. /* #include "sqliteInt.h" */
  104182. /*
  104183. ** While a SrcList can in general represent multiple tables and subqueries
  104184. ** (as in the FROM clause of a SELECT statement) in this case it contains
  104185. ** the name of a single table, as one might find in an INSERT, DELETE,
  104186. ** or UPDATE statement. Look up that table in the symbol table and
  104187. ** return a pointer. Set an error message and return NULL if the table
  104188. ** name is not found or if any other error occurs.
  104189. **
  104190. ** The following fields are initialized appropriate in pSrc:
  104191. **
  104192. ** pSrc->a[0].pTab Pointer to the Table object
  104193. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  104194. **
  104195. */
  104196. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  104197. struct SrcList_item *pItem = pSrc->a;
  104198. Table *pTab;
  104199. assert( pItem && pSrc->nSrc==1 );
  104200. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  104201. sqlite3DeleteTable(pParse->db, pItem->pTab);
  104202. pItem->pTab = pTab;
  104203. if( pTab ){
  104204. pTab->nTabRef++;
  104205. }
  104206. if( sqlite3IndexedByLookup(pParse, pItem) ){
  104207. pTab = 0;
  104208. }
  104209. return pTab;
  104210. }
  104211. /* Return true if table pTab is read-only.
  104212. **
  104213. ** A table is read-only if any of the following are true:
  104214. **
  104215. ** 1) It is a virtual table and no implementation of the xUpdate method
  104216. ** has been provided
  104217. **
  104218. ** 2) It is a system table (i.e. sqlite_master), this call is not
  104219. ** part of a nested parse and writable_schema pragma has not
  104220. ** been specified
  104221. **
  104222. ** 3) The table is a shadow table, the database connection is in
  104223. ** defensive mode, and the current sqlite3_prepare()
  104224. ** is for a top-level SQL statement.
  104225. */
  104226. static int tabIsReadOnly(Parse *pParse, Table *pTab){
  104227. sqlite3 *db;
  104228. if( IsVirtual(pTab) ){
  104229. return sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0;
  104230. }
  104231. if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;
  104232. db = pParse->db;
  104233. if( (pTab->tabFlags & TF_Readonly)!=0 ){
  104234. return sqlite3WritableSchema(db)==0 && pParse->nested==0;
  104235. }
  104236. assert( pTab->tabFlags & TF_Shadow );
  104237. return (db->flags & SQLITE_Defensive)!=0
  104238. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104239. && db->pVtabCtx==0
  104240. #endif
  104241. && db->nVdbeExec==0;
  104242. }
  104243. /*
  104244. ** Check to make sure the given table is writable. If it is not
  104245. ** writable, generate an error message and return 1. If it is
  104246. ** writable return 0;
  104247. */
  104248. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  104249. if( tabIsReadOnly(pParse, pTab) ){
  104250. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  104251. return 1;
  104252. }
  104253. #ifndef SQLITE_OMIT_VIEW
  104254. if( !viewOk && pTab->pSelect ){
  104255. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  104256. return 1;
  104257. }
  104258. #endif
  104259. return 0;
  104260. }
  104261. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  104262. /*
  104263. ** Evaluate a view and store its result in an ephemeral table. The
  104264. ** pWhere argument is an optional WHERE clause that restricts the
  104265. ** set of rows in the view that are to be added to the ephemeral table.
  104266. */
  104267. SQLITE_PRIVATE void sqlite3MaterializeView(
  104268. Parse *pParse, /* Parsing context */
  104269. Table *pView, /* View definition */
  104270. Expr *pWhere, /* Optional WHERE clause to be added */
  104271. ExprList *pOrderBy, /* Optional ORDER BY clause */
  104272. Expr *pLimit, /* Optional LIMIT clause */
  104273. int iCur /* Cursor number for ephemeral table */
  104274. ){
  104275. SelectDest dest;
  104276. Select *pSel;
  104277. SrcList *pFrom;
  104278. sqlite3 *db = pParse->db;
  104279. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  104280. pWhere = sqlite3ExprDup(db, pWhere, 0);
  104281. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  104282. if( pFrom ){
  104283. assert( pFrom->nSrc==1 );
  104284. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  104285. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
  104286. assert( pFrom->a[0].pOn==0 );
  104287. assert( pFrom->a[0].pUsing==0 );
  104288. }
  104289. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
  104290. SF_IncludeHidden, pLimit);
  104291. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  104292. sqlite3Select(pParse, pSel, &dest);
  104293. sqlite3SelectDelete(db, pSel);
  104294. }
  104295. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  104296. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  104297. /*
  104298. ** Generate an expression tree to implement the WHERE, ORDER BY,
  104299. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  104300. **
  104301. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  104302. ** \__________________________/
  104303. ** pLimitWhere (pInClause)
  104304. */
  104305. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  104306. Parse *pParse, /* The parser context */
  104307. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  104308. Expr *pWhere, /* The WHERE clause. May be null */
  104309. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  104310. Expr *pLimit, /* The LIMIT clause. May be null */
  104311. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  104312. ){
  104313. sqlite3 *db = pParse->db;
  104314. Expr *pLhs = NULL; /* LHS of IN(SELECT...) operator */
  104315. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  104316. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  104317. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  104318. Select *pSelect = NULL; /* Complete SELECT tree */
  104319. Table *pTab;
  104320. /* Check that there isn't an ORDER BY without a LIMIT clause.
  104321. */
  104322. if( pOrderBy && pLimit==0 ) {
  104323. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  104324. sqlite3ExprDelete(pParse->db, pWhere);
  104325. sqlite3ExprListDelete(pParse->db, pOrderBy);
  104326. return 0;
  104327. }
  104328. /* We only need to generate a select expression if there
  104329. ** is a limit/offset term to enforce.
  104330. */
  104331. if( pLimit == 0 ) {
  104332. return pWhere;
  104333. }
  104334. /* Generate a select expression tree to enforce the limit/offset
  104335. ** term for the DELETE or UPDATE statement. For example:
  104336. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  104337. ** becomes:
  104338. ** DELETE FROM table_a WHERE rowid IN (
  104339. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  104340. ** );
  104341. */
  104342. pTab = pSrc->a[0].pTab;
  104343. if( HasRowid(pTab) ){
  104344. pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  104345. pEList = sqlite3ExprListAppend(
  104346. pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
  104347. );
  104348. }else{
  104349. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  104350. if( pPk->nKeyCol==1 ){
  104351. const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;
  104352. pLhs = sqlite3Expr(db, TK_ID, zName);
  104353. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
  104354. }else{
  104355. int i;
  104356. for(i=0; i<pPk->nKeyCol; i++){
  104357. Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);
  104358. pEList = sqlite3ExprListAppend(pParse, pEList, p);
  104359. }
  104360. pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  104361. if( pLhs ){
  104362. pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
  104363. }
  104364. }
  104365. }
  104366. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  104367. ** and the SELECT subtree. */
  104368. pSrc->a[0].pTab = 0;
  104369. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  104370. pSrc->a[0].pTab = pTab;
  104371. pSrc->a[0].pIBIndex = 0;
  104372. /* generate the SELECT expression tree. */
  104373. pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
  104374. pOrderBy,0,pLimit
  104375. );
  104376. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  104377. pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
  104378. sqlite3PExprAddSelect(pParse, pInClause, pSelect);
  104379. return pInClause;
  104380. }
  104381. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  104382. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  104383. /*
  104384. ** Generate code for a DELETE FROM statement.
  104385. **
  104386. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  104387. ** \________/ \________________/
  104388. ** pTabList pWhere
  104389. */
  104390. SQLITE_PRIVATE void sqlite3DeleteFrom(
  104391. Parse *pParse, /* The parser context */
  104392. SrcList *pTabList, /* The table from which we should delete things */
  104393. Expr *pWhere, /* The WHERE clause. May be null */
  104394. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  104395. Expr *pLimit /* LIMIT clause. May be null */
  104396. ){
  104397. Vdbe *v; /* The virtual database engine */
  104398. Table *pTab; /* The table from which records will be deleted */
  104399. int i; /* Loop counter */
  104400. WhereInfo *pWInfo; /* Information about the WHERE clause */
  104401. Index *pIdx; /* For looping over indices of the table */
  104402. int iTabCur; /* Cursor number for the table */
  104403. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  104404. int iIdxCur = 0; /* Cursor number of the first index */
  104405. int nIdx; /* Number of indices */
  104406. sqlite3 *db; /* Main database structure */
  104407. AuthContext sContext; /* Authorization context */
  104408. NameContext sNC; /* Name context to resolve expressions in */
  104409. int iDb; /* Database number */
  104410. int memCnt = 0; /* Memory cell used for change counting */
  104411. int rcauth; /* Value returned by authorization callback */
  104412. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  104413. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  104414. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  104415. Index *pPk; /* The PRIMARY KEY index on the table */
  104416. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  104417. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  104418. int iKey; /* Memory cell holding key of row to be deleted */
  104419. i16 nKey; /* Number of memory cells in the row key */
  104420. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  104421. int iRowSet = 0; /* Register for rowset of rows to delete */
  104422. int addrBypass = 0; /* Address of jump over the delete logic */
  104423. int addrLoop = 0; /* Top of the delete loop */
  104424. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  104425. int bComplex; /* True if there are triggers or FKs or
  104426. ** subqueries in the WHERE clause */
  104427. #ifndef SQLITE_OMIT_TRIGGER
  104428. int isView; /* True if attempting to delete from a view */
  104429. Trigger *pTrigger; /* List of table triggers, if required */
  104430. #endif
  104431. memset(&sContext, 0, sizeof(sContext));
  104432. db = pParse->db;
  104433. if( pParse->nErr || db->mallocFailed ){
  104434. goto delete_from_cleanup;
  104435. }
  104436. assert( pTabList->nSrc==1 );
  104437. /* Locate the table which we want to delete. This table has to be
  104438. ** put in an SrcList structure because some of the subroutines we
  104439. ** will be calling are designed to work with multiple tables and expect
  104440. ** an SrcList* parameter instead of just a Table* parameter.
  104441. */
  104442. pTab = sqlite3SrcListLookup(pParse, pTabList);
  104443. if( pTab==0 ) goto delete_from_cleanup;
  104444. /* Figure out if we have any triggers and if the table being
  104445. ** deleted from is a view
  104446. */
  104447. #ifndef SQLITE_OMIT_TRIGGER
  104448. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  104449. isView = pTab->pSelect!=0;
  104450. #else
  104451. # define pTrigger 0
  104452. # define isView 0
  104453. #endif
  104454. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  104455. #ifdef SQLITE_OMIT_VIEW
  104456. # undef isView
  104457. # define isView 0
  104458. #endif
  104459. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  104460. if( !isView ){
  104461. pWhere = sqlite3LimitWhere(
  104462. pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
  104463. );
  104464. pOrderBy = 0;
  104465. pLimit = 0;
  104466. }
  104467. #endif
  104468. /* If pTab is really a view, make sure it has been initialized.
  104469. */
  104470. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  104471. goto delete_from_cleanup;
  104472. }
  104473. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  104474. goto delete_from_cleanup;
  104475. }
  104476. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  104477. assert( iDb<db->nDb );
  104478. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
  104479. db->aDb[iDb].zDbSName);
  104480. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  104481. if( rcauth==SQLITE_DENY ){
  104482. goto delete_from_cleanup;
  104483. }
  104484. assert(!isView || pTrigger);
  104485. /* Assign cursor numbers to the table and all its indices.
  104486. */
  104487. assert( pTabList->nSrc==1 );
  104488. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  104489. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  104490. pParse->nTab++;
  104491. }
  104492. /* Start the view context
  104493. */
  104494. if( isView ){
  104495. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  104496. }
  104497. /* Begin generating code.
  104498. */
  104499. v = sqlite3GetVdbe(pParse);
  104500. if( v==0 ){
  104501. goto delete_from_cleanup;
  104502. }
  104503. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  104504. sqlite3BeginWriteOperation(pParse, bComplex, iDb);
  104505. /* If we are trying to delete from a view, realize that view into
  104506. ** an ephemeral table.
  104507. */
  104508. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  104509. if( isView ){
  104510. sqlite3MaterializeView(pParse, pTab,
  104511. pWhere, pOrderBy, pLimit, iTabCur
  104512. );
  104513. iDataCur = iIdxCur = iTabCur;
  104514. pOrderBy = 0;
  104515. pLimit = 0;
  104516. }
  104517. #endif
  104518. /* Resolve the column names in the WHERE clause.
  104519. */
  104520. memset(&sNC, 0, sizeof(sNC));
  104521. sNC.pParse = pParse;
  104522. sNC.pSrcList = pTabList;
  104523. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  104524. goto delete_from_cleanup;
  104525. }
  104526. /* Initialize the counter of the number of rows deleted, if
  104527. ** we are counting rows.
  104528. */
  104529. if( (db->flags & SQLITE_CountRows)!=0
  104530. && !pParse->nested
  104531. && !pParse->pTriggerTab
  104532. ){
  104533. memCnt = ++pParse->nMem;
  104534. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  104535. }
  104536. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  104537. /* Special case: A DELETE without a WHERE clause deletes everything.
  104538. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  104539. ** this optimization caused the row change count (the value returned by
  104540. ** API function sqlite3_count_changes) to be set incorrectly.
  104541. **
  104542. ** The "rcauth==SQLITE_OK" terms is the
  104543. ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
  104544. ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
  104545. ** the truncate optimization is disabled and all rows are deleted
  104546. ** individually.
  104547. */
  104548. if( rcauth==SQLITE_OK
  104549. && pWhere==0
  104550. && !bComplex
  104551. && !IsVirtual(pTab)
  104552. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  104553. && db->xPreUpdateCallback==0
  104554. #endif
  104555. ){
  104556. assert( !isView );
  104557. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  104558. if( HasRowid(pTab) ){
  104559. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
  104560. pTab->zName, P4_STATIC);
  104561. }
  104562. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  104563. assert( pIdx->pSchema==pTab->pSchema );
  104564. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  104565. }
  104566. }else
  104567. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  104568. {
  104569. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
  104570. if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
  104571. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  104572. if( HasRowid(pTab) ){
  104573. /* For a rowid table, initialize the RowSet to an empty set */
  104574. pPk = 0;
  104575. nPk = 1;
  104576. iRowSet = ++pParse->nMem;
  104577. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  104578. }else{
  104579. /* For a WITHOUT ROWID table, create an ephemeral table used to
  104580. ** hold all primary keys for rows to be deleted. */
  104581. pPk = sqlite3PrimaryKeyIndex(pTab);
  104582. assert( pPk!=0 );
  104583. nPk = pPk->nKeyCol;
  104584. iPk = pParse->nMem+1;
  104585. pParse->nMem += nPk;
  104586. iEphCur = pParse->nTab++;
  104587. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  104588. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  104589. }
  104590. /* Construct a query to find the rowid or primary key for every row
  104591. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  104592. ** to indicate the strategy used to implement this delete:
  104593. **
  104594. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  104595. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  104596. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  104597. */
  104598. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  104599. if( pWInfo==0 ) goto delete_from_cleanup;
  104600. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  104601. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  104602. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  104603. if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
  104604. /* Keep track of the number of rows to be deleted */
  104605. if( memCnt ){
  104606. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  104607. }
  104608. /* Extract the rowid or primary key for the current row */
  104609. if( pPk ){
  104610. for(i=0; i<nPk; i++){
  104611. assert( pPk->aiColumn[i]>=0 );
  104612. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  104613. pPk->aiColumn[i], iPk+i);
  104614. }
  104615. iKey = iPk;
  104616. }else{
  104617. iKey = ++pParse->nMem;
  104618. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
  104619. }
  104620. if( eOnePass!=ONEPASS_OFF ){
  104621. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  104622. ** one, so just keep it in its register(s) and fall through to the
  104623. ** delete code. */
  104624. nKey = nPk; /* OP_Found will use an unpacked key */
  104625. aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
  104626. if( aToOpen==0 ){
  104627. sqlite3WhereEnd(pWInfo);
  104628. goto delete_from_cleanup;
  104629. }
  104630. memset(aToOpen, 1, nIdx+1);
  104631. aToOpen[nIdx+1] = 0;
  104632. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  104633. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  104634. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  104635. }else{
  104636. if( pPk ){
  104637. /* Add the PK key for this row to the temporary table */
  104638. iKey = ++pParse->nMem;
  104639. nKey = 0; /* Zero tells OP_Found to use a composite key */
  104640. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  104641. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  104642. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
  104643. }else{
  104644. /* Add the rowid of the row to be deleted to the RowSet */
  104645. nKey = 1; /* OP_DeferredSeek always uses a single rowid */
  104646. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  104647. }
  104648. }
  104649. /* If this DELETE cannot use the ONEPASS strategy, this is the
  104650. ** end of the WHERE loop */
  104651. if( eOnePass!=ONEPASS_OFF ){
  104652. addrBypass = sqlite3VdbeMakeLabel(v);
  104653. }else{
  104654. sqlite3WhereEnd(pWInfo);
  104655. }
  104656. /* Unless this is a view, open cursors for the table we are
  104657. ** deleting from and all its indices. If this is a view, then the
  104658. ** only effect this statement has is to fire the INSTEAD OF
  104659. ** triggers.
  104660. */
  104661. if( !isView ){
  104662. int iAddrOnce = 0;
  104663. if( eOnePass==ONEPASS_MULTI ){
  104664. iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  104665. }
  104666. testcase( IsVirtual(pTab) );
  104667. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
  104668. iTabCur, aToOpen, &iDataCur, &iIdxCur);
  104669. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  104670. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  104671. if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
  104672. }
  104673. /* Set up a loop over the rowids/primary-keys that were found in the
  104674. ** where-clause loop above.
  104675. */
  104676. if( eOnePass!=ONEPASS_OFF ){
  104677. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  104678. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  104679. assert( pPk!=0 || pTab->pSelect!=0 );
  104680. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  104681. VdbeCoverage(v);
  104682. }
  104683. }else if( pPk ){
  104684. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  104685. if( IsVirtual(pTab) ){
  104686. sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
  104687. }else{
  104688. sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
  104689. }
  104690. assert( nKey==0 ); /* OP_Found will use a composite key */
  104691. }else{
  104692. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  104693. VdbeCoverage(v);
  104694. assert( nKey==1 );
  104695. }
  104696. /* Delete the row */
  104697. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104698. if( IsVirtual(pTab) ){
  104699. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  104700. sqlite3VtabMakeWritable(pParse, pTab);
  104701. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  104702. sqlite3MayAbort(pParse);
  104703. if( eOnePass==ONEPASS_SINGLE ){
  104704. sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
  104705. if( sqlite3IsToplevel(pParse) ){
  104706. pParse->isMultiWrite = 0;
  104707. }
  104708. }
  104709. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  104710. sqlite3VdbeChangeP5(v, OE_Abort);
  104711. }else
  104712. #endif
  104713. {
  104714. int count = (pParse->nested==0); /* True to count changes */
  104715. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  104716. iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
  104717. }
  104718. /* End of the loop over all rowids/primary-keys. */
  104719. if( eOnePass!=ONEPASS_OFF ){
  104720. sqlite3VdbeResolveLabel(v, addrBypass);
  104721. sqlite3WhereEnd(pWInfo);
  104722. }else if( pPk ){
  104723. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  104724. sqlite3VdbeJumpHere(v, addrLoop);
  104725. }else{
  104726. sqlite3VdbeGoto(v, addrLoop);
  104727. sqlite3VdbeJumpHere(v, addrLoop);
  104728. }
  104729. } /* End non-truncate path */
  104730. /* Update the sqlite_sequence table by storing the content of the
  104731. ** maximum rowid counter values recorded while inserting into
  104732. ** autoincrement tables.
  104733. */
  104734. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  104735. sqlite3AutoincrementEnd(pParse);
  104736. }
  104737. /* Return the number of rows that were deleted. If this routine is
  104738. ** generating code because of a call to sqlite3NestedParse(), do not
  104739. ** invoke the callback function.
  104740. */
  104741. if( memCnt ){
  104742. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  104743. sqlite3VdbeSetNumCols(v, 1);
  104744. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  104745. }
  104746. delete_from_cleanup:
  104747. sqlite3AuthContextPop(&sContext);
  104748. sqlite3SrcListDelete(db, pTabList);
  104749. sqlite3ExprDelete(db, pWhere);
  104750. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  104751. sqlite3ExprListDelete(db, pOrderBy);
  104752. sqlite3ExprDelete(db, pLimit);
  104753. #endif
  104754. sqlite3DbFree(db, aToOpen);
  104755. return;
  104756. }
  104757. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  104758. ** they may interfere with compilation of other functions in this file
  104759. ** (or in another file, if this file becomes part of the amalgamation). */
  104760. #ifdef isView
  104761. #undef isView
  104762. #endif
  104763. #ifdef pTrigger
  104764. #undef pTrigger
  104765. #endif
  104766. /*
  104767. ** This routine generates VDBE code that causes a single row of a
  104768. ** single table to be deleted. Both the original table entry and
  104769. ** all indices are removed.
  104770. **
  104771. ** Preconditions:
  104772. **
  104773. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  104774. ** store for the table. (This will be either the table itself,
  104775. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  104776. ** of a WITHOUT ROWID table.)
  104777. **
  104778. ** 2. Read/write cursors for all indices of pTab must be open as
  104779. ** cursor number iIdxCur+i for the i-th index.
  104780. **
  104781. ** 3. The primary key for the row to be deleted must be stored in a
  104782. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  104783. ** that a search record formed from OP_MakeRecord is contained in the
  104784. ** single memory location iPk.
  104785. **
  104786. ** eMode:
  104787. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  104788. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  104789. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  104790. ** then this function must seek iDataCur to the entry identified by iPk
  104791. ** and nPk before reading from it.
  104792. **
  104793. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  104794. ** of a ONEPASS delete that affects multiple rows. In this case, if
  104795. ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
  104796. ** iDataCur, then its position should be preserved following the delete
  104797. ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
  104798. ** position of iDataCur should be preserved instead.
  104799. **
  104800. ** iIdxNoSeek:
  104801. ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
  104802. ** then it identifies an index cursor (from within array of cursors
  104803. ** starting at iIdxCur) that already points to the index entry to be deleted.
  104804. ** Except, this optimization is disabled if there are BEFORE triggers since
  104805. ** the trigger body might have moved the cursor.
  104806. */
  104807. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  104808. Parse *pParse, /* Parsing context */
  104809. Table *pTab, /* Table containing the row to be deleted */
  104810. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  104811. int iDataCur, /* Cursor from which column data is extracted */
  104812. int iIdxCur, /* First index cursor */
  104813. int iPk, /* First memory cell containing the PRIMARY KEY */
  104814. i16 nPk, /* Number of PRIMARY KEY memory cells */
  104815. u8 count, /* If non-zero, increment the row change counter */
  104816. u8 onconf, /* Default ON CONFLICT policy for triggers */
  104817. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  104818. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  104819. ){
  104820. Vdbe *v = pParse->pVdbe; /* Vdbe */
  104821. int iOld = 0; /* First register in OLD.* array */
  104822. int iLabel; /* Label resolved to end of generated code */
  104823. u8 opSeek; /* Seek opcode */
  104824. /* Vdbe is guaranteed to have been allocated by this stage. */
  104825. assert( v );
  104826. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  104827. iDataCur, iIdxCur, iPk, (int)nPk));
  104828. /* Seek cursor iCur to the row to delete. If this row no longer exists
  104829. ** (this can happen if a trigger program has already deleted it), do
  104830. ** not attempt to delete it or fire any DELETE triggers. */
  104831. iLabel = sqlite3VdbeMakeLabel(v);
  104832. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  104833. if( eMode==ONEPASS_OFF ){
  104834. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  104835. VdbeCoverageIf(v, opSeek==OP_NotExists);
  104836. VdbeCoverageIf(v, opSeek==OP_NotFound);
  104837. }
  104838. /* If there are any triggers to fire, allocate a range of registers to
  104839. ** use for the old.* references in the triggers. */
  104840. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  104841. u32 mask; /* Mask of OLD.* columns in use */
  104842. int iCol; /* Iterator used while populating OLD.* */
  104843. int addrStart; /* Start of BEFORE trigger programs */
  104844. /* TODO: Could use temporary registers here. Also could attempt to
  104845. ** avoid copying the contents of the rowid register. */
  104846. mask = sqlite3TriggerColmask(
  104847. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  104848. );
  104849. mask |= sqlite3FkOldmask(pParse, pTab);
  104850. iOld = pParse->nMem+1;
  104851. pParse->nMem += (1 + pTab->nCol);
  104852. /* Populate the OLD.* pseudo-table register array. These values will be
  104853. ** used by any BEFORE and AFTER triggers that exist. */
  104854. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  104855. for(iCol=0; iCol<pTab->nCol; iCol++){
  104856. testcase( mask!=0xffffffff && iCol==31 );
  104857. testcase( mask!=0xffffffff && iCol==32 );
  104858. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  104859. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  104860. }
  104861. }
  104862. /* Invoke BEFORE DELETE trigger programs. */
  104863. addrStart = sqlite3VdbeCurrentAddr(v);
  104864. sqlite3CodeRowTrigger(pParse, pTrigger,
  104865. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  104866. );
  104867. /* If any BEFORE triggers were coded, then seek the cursor to the
  104868. ** row to be deleted again. It may be that the BEFORE triggers moved
  104869. ** the cursor or already deleted the row that the cursor was
  104870. ** pointing to.
  104871. **
  104872. ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
  104873. ** may have moved that cursor.
  104874. */
  104875. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  104876. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  104877. VdbeCoverageIf(v, opSeek==OP_NotExists);
  104878. VdbeCoverageIf(v, opSeek==OP_NotFound);
  104879. testcase( iIdxNoSeek>=0 );
  104880. iIdxNoSeek = -1;
  104881. }
  104882. /* Do FK processing. This call checks that any FK constraints that
  104883. ** refer to this table (i.e. constraints attached to other tables)
  104884. ** are not violated by deleting this row. */
  104885. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  104886. }
  104887. /* Delete the index and table entries. Skip this step if pTab is really
  104888. ** a view (in which case the only effect of the DELETE statement is to
  104889. ** fire the INSTEAD OF triggers).
  104890. **
  104891. ** If variable 'count' is non-zero, then this OP_Delete instruction should
  104892. ** invoke the update-hook. The pre-update-hook, on the other hand should
  104893. ** be invoked unless table pTab is a system table. The difference is that
  104894. ** the update-hook is not invoked for rows removed by REPLACE, but the
  104895. ** pre-update-hook is.
  104896. */
  104897. if( pTab->pSelect==0 ){
  104898. u8 p5 = 0;
  104899. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  104900. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  104901. if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
  104902. sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
  104903. }
  104904. if( eMode!=ONEPASS_OFF ){
  104905. sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
  104906. }
  104907. if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
  104908. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  104909. }
  104910. if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
  104911. sqlite3VdbeChangeP5(v, p5);
  104912. }
  104913. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  104914. ** handle rows (possibly in other tables) that refer via a foreign key
  104915. ** to the row just deleted. */
  104916. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  104917. /* Invoke AFTER DELETE trigger programs. */
  104918. sqlite3CodeRowTrigger(pParse, pTrigger,
  104919. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  104920. );
  104921. /* Jump here if the row had already been deleted before any BEFORE
  104922. ** trigger programs were invoked. Or if a trigger program throws a
  104923. ** RAISE(IGNORE) exception. */
  104924. sqlite3VdbeResolveLabel(v, iLabel);
  104925. VdbeModuleComment((v, "END: GenRowDel()"));
  104926. }
  104927. /*
  104928. ** This routine generates VDBE code that causes the deletion of all
  104929. ** index entries associated with a single row of a single table, pTab
  104930. **
  104931. ** Preconditions:
  104932. **
  104933. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  104934. ** btree for the table pTab. (This will be either the table itself
  104935. ** for rowid tables or to the primary key index for WITHOUT ROWID
  104936. ** tables.)
  104937. **
  104938. ** 2. Read/write cursors for all indices of pTab must be open as
  104939. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  104940. ** index is the 0-th index.)
  104941. **
  104942. ** 3. The "iDataCur" cursor must be already be positioned on the row
  104943. ** that is to be deleted.
  104944. */
  104945. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  104946. Parse *pParse, /* Parsing and code generating context */
  104947. Table *pTab, /* Table containing the row to be deleted */
  104948. int iDataCur, /* Cursor of table holding data. */
  104949. int iIdxCur, /* First index cursor */
  104950. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  104951. int iIdxNoSeek /* Do not delete from this cursor */
  104952. ){
  104953. int i; /* Index loop counter */
  104954. int r1 = -1; /* Register holding an index key */
  104955. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  104956. Index *pIdx; /* Current index */
  104957. Index *pPrior = 0; /* Prior index */
  104958. Vdbe *v; /* The prepared statement under construction */
  104959. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  104960. v = pParse->pVdbe;
  104961. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  104962. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  104963. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  104964. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  104965. if( pIdx==pPk ) continue;
  104966. if( iIdxCur+i==iIdxNoSeek ) continue;
  104967. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  104968. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  104969. &iPartIdxLabel, pPrior, r1);
  104970. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  104971. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  104972. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  104973. pPrior = pIdx;
  104974. }
  104975. }
  104976. /*
  104977. ** Generate code that will assemble an index key and stores it in register
  104978. ** regOut. The key with be for index pIdx which is an index on pTab.
  104979. ** iCur is the index of a cursor open on the pTab table and pointing to
  104980. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  104981. ** iCur must be the cursor of the PRIMARY KEY index.
  104982. **
  104983. ** Return a register number which is the first in a block of
  104984. ** registers that holds the elements of the index key. The
  104985. ** block of registers has already been deallocated by the time
  104986. ** this routine returns.
  104987. **
  104988. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  104989. ** to that label if pIdx is a partial index that should be skipped.
  104990. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  104991. ** A partial index should be skipped if its WHERE clause evaluates
  104992. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  104993. ** will be set to zero which is an empty label that is ignored by
  104994. ** sqlite3ResolvePartIdxLabel().
  104995. **
  104996. ** The pPrior and regPrior parameters are used to implement a cache to
  104997. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  104998. ** a pointer to a different index for which an index key has just been
  104999. ** computed into register regPrior. If the current pIdx index is generating
  105000. ** its key into the same sequence of registers and if pPrior and pIdx share
  105001. ** a column in common, then the register corresponding to that column already
  105002. ** holds the correct value and the loading of that register is skipped.
  105003. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  105004. ** on a table with multiple indices, and especially with the ROWID or
  105005. ** PRIMARY KEY columns of the index.
  105006. */
  105007. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  105008. Parse *pParse, /* Parsing context */
  105009. Index *pIdx, /* The index for which to generate a key */
  105010. int iDataCur, /* Cursor number from which to take column data */
  105011. int regOut, /* Put the new key into this register if not 0 */
  105012. int prefixOnly, /* Compute only a unique prefix of the key */
  105013. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  105014. Index *pPrior, /* Previously generated index key */
  105015. int regPrior /* Register holding previous generated key */
  105016. ){
  105017. Vdbe *v = pParse->pVdbe;
  105018. int j;
  105019. int regBase;
  105020. int nCol;
  105021. if( piPartIdxLabel ){
  105022. if( pIdx->pPartIdxWhere ){
  105023. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  105024. pParse->iSelfTab = iDataCur + 1;
  105025. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  105026. SQLITE_JUMPIFNULL);
  105027. pParse->iSelfTab = 0;
  105028. }else{
  105029. *piPartIdxLabel = 0;
  105030. }
  105031. }
  105032. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  105033. regBase = sqlite3GetTempRange(pParse, nCol);
  105034. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  105035. for(j=0; j<nCol; j++){
  105036. if( pPrior
  105037. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  105038. && pPrior->aiColumn[j]!=XN_EXPR
  105039. ){
  105040. /* This column was already computed by the previous index */
  105041. continue;
  105042. }
  105043. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  105044. /* If the column affinity is REAL but the number is an integer, then it
  105045. ** might be stored in the table as an integer (using a compact
  105046. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  105047. ** But we are getting ready to store this value back into an index, where
  105048. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  105049. ** opcode if it is present */
  105050. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  105051. }
  105052. if( regOut ){
  105053. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  105054. if( pIdx->pTable->pSelect ){
  105055. const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
  105056. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  105057. }
  105058. }
  105059. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  105060. return regBase;
  105061. }
  105062. /*
  105063. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  105064. ** because it was a partial index, then this routine should be called to
  105065. ** resolve that label.
  105066. */
  105067. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  105068. if( iLabel ){
  105069. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  105070. }
  105071. }
  105072. /************** End of delete.c **********************************************/
  105073. /************** Begin file func.c ********************************************/
  105074. /*
  105075. ** 2002 February 23
  105076. **
  105077. ** The author disclaims copyright to this source code. In place of
  105078. ** a legal notice, here is a blessing:
  105079. **
  105080. ** May you do good and not evil.
  105081. ** May you find forgiveness for yourself and forgive others.
  105082. ** May you share freely, never taking more than you give.
  105083. **
  105084. *************************************************************************
  105085. ** This file contains the C-language implementations for many of the SQL
  105086. ** functions of SQLite. (Some function, and in particular the date and
  105087. ** time functions, are implemented separately.)
  105088. */
  105089. /* #include "sqliteInt.h" */
  105090. /* #include <stdlib.h> */
  105091. /* #include <assert.h> */
  105092. /* #include "vdbeInt.h" */
  105093. /*
  105094. ** Return the collating function associated with a function.
  105095. */
  105096. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  105097. VdbeOp *pOp;
  105098. assert( context->pVdbe!=0 );
  105099. pOp = &context->pVdbe->aOp[context->iOp-1];
  105100. assert( pOp->opcode==OP_CollSeq );
  105101. assert( pOp->p4type==P4_COLLSEQ );
  105102. return pOp->p4.pColl;
  105103. }
  105104. /*
  105105. ** Indicate that the accumulator load should be skipped on this
  105106. ** iteration of the aggregate loop.
  105107. */
  105108. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  105109. assert( context->isError<=0 );
  105110. context->isError = -1;
  105111. context->skipFlag = 1;
  105112. }
  105113. /*
  105114. ** Implementation of the non-aggregate min() and max() functions
  105115. */
  105116. static void minmaxFunc(
  105117. sqlite3_context *context,
  105118. int argc,
  105119. sqlite3_value **argv
  105120. ){
  105121. int i;
  105122. int mask; /* 0 for min() or 0xffffffff for max() */
  105123. int iBest;
  105124. CollSeq *pColl;
  105125. assert( argc>1 );
  105126. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  105127. pColl = sqlite3GetFuncCollSeq(context);
  105128. assert( pColl );
  105129. assert( mask==-1 || mask==0 );
  105130. iBest = 0;
  105131. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  105132. for(i=1; i<argc; i++){
  105133. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  105134. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  105135. testcase( mask==0 );
  105136. iBest = i;
  105137. }
  105138. }
  105139. sqlite3_result_value(context, argv[iBest]);
  105140. }
  105141. /*
  105142. ** Return the type of the argument.
  105143. */
  105144. static void typeofFunc(
  105145. sqlite3_context *context,
  105146. int NotUsed,
  105147. sqlite3_value **argv
  105148. ){
  105149. static const char *azType[] = { "integer", "real", "text", "blob", "null" };
  105150. int i = sqlite3_value_type(argv[0]) - 1;
  105151. UNUSED_PARAMETER(NotUsed);
  105152. assert( i>=0 && i<ArraySize(azType) );
  105153. assert( SQLITE_INTEGER==1 );
  105154. assert( SQLITE_FLOAT==2 );
  105155. assert( SQLITE_TEXT==3 );
  105156. assert( SQLITE_BLOB==4 );
  105157. assert( SQLITE_NULL==5 );
  105158. /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
  105159. ** the datatype code for the initial datatype of the sqlite3_value object
  105160. ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
  105161. ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
  105162. sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
  105163. }
  105164. /*
  105165. ** Implementation of the length() function
  105166. */
  105167. static void lengthFunc(
  105168. sqlite3_context *context,
  105169. int argc,
  105170. sqlite3_value **argv
  105171. ){
  105172. assert( argc==1 );
  105173. UNUSED_PARAMETER(argc);
  105174. switch( sqlite3_value_type(argv[0]) ){
  105175. case SQLITE_BLOB:
  105176. case SQLITE_INTEGER:
  105177. case SQLITE_FLOAT: {
  105178. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  105179. break;
  105180. }
  105181. case SQLITE_TEXT: {
  105182. const unsigned char *z = sqlite3_value_text(argv[0]);
  105183. const unsigned char *z0;
  105184. unsigned char c;
  105185. if( z==0 ) return;
  105186. z0 = z;
  105187. while( (c = *z)!=0 ){
  105188. z++;
  105189. if( c>=0xc0 ){
  105190. while( (*z & 0xc0)==0x80 ){ z++; z0++; }
  105191. }
  105192. }
  105193. sqlite3_result_int(context, (int)(z-z0));
  105194. break;
  105195. }
  105196. default: {
  105197. sqlite3_result_null(context);
  105198. break;
  105199. }
  105200. }
  105201. }
  105202. /*
  105203. ** Implementation of the abs() function.
  105204. **
  105205. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  105206. ** the numeric argument X.
  105207. */
  105208. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  105209. assert( argc==1 );
  105210. UNUSED_PARAMETER(argc);
  105211. switch( sqlite3_value_type(argv[0]) ){
  105212. case SQLITE_INTEGER: {
  105213. i64 iVal = sqlite3_value_int64(argv[0]);
  105214. if( iVal<0 ){
  105215. if( iVal==SMALLEST_INT64 ){
  105216. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  105217. ** then abs(X) throws an integer overflow error since there is no
  105218. ** equivalent positive 64-bit two complement value. */
  105219. sqlite3_result_error(context, "integer overflow", -1);
  105220. return;
  105221. }
  105222. iVal = -iVal;
  105223. }
  105224. sqlite3_result_int64(context, iVal);
  105225. break;
  105226. }
  105227. case SQLITE_NULL: {
  105228. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  105229. sqlite3_result_null(context);
  105230. break;
  105231. }
  105232. default: {
  105233. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  105234. ** something that can be converted into a number, we have:
  105235. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  105236. ** that cannot be converted to a numeric value.
  105237. */
  105238. double rVal = sqlite3_value_double(argv[0]);
  105239. if( rVal<0 ) rVal = -rVal;
  105240. sqlite3_result_double(context, rVal);
  105241. break;
  105242. }
  105243. }
  105244. }
  105245. /*
  105246. ** Implementation of the instr() function.
  105247. **
  105248. ** instr(haystack,needle) finds the first occurrence of needle
  105249. ** in haystack and returns the number of previous characters plus 1,
  105250. ** or 0 if needle does not occur within haystack.
  105251. **
  105252. ** If both haystack and needle are BLOBs, then the result is one more than
  105253. ** the number of bytes in haystack prior to the first occurrence of needle,
  105254. ** or 0 if needle never occurs in haystack.
  105255. */
  105256. static void instrFunc(
  105257. sqlite3_context *context,
  105258. int argc,
  105259. sqlite3_value **argv
  105260. ){
  105261. const unsigned char *zHaystack;
  105262. const unsigned char *zNeedle;
  105263. int nHaystack;
  105264. int nNeedle;
  105265. int typeHaystack, typeNeedle;
  105266. int N = 1;
  105267. int isText;
  105268. UNUSED_PARAMETER(argc);
  105269. typeHaystack = sqlite3_value_type(argv[0]);
  105270. typeNeedle = sqlite3_value_type(argv[1]);
  105271. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  105272. nHaystack = sqlite3_value_bytes(argv[0]);
  105273. nNeedle = sqlite3_value_bytes(argv[1]);
  105274. if( nNeedle>0 ){
  105275. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  105276. zHaystack = sqlite3_value_blob(argv[0]);
  105277. zNeedle = sqlite3_value_blob(argv[1]);
  105278. isText = 0;
  105279. }else{
  105280. zHaystack = sqlite3_value_text(argv[0]);
  105281. zNeedle = sqlite3_value_text(argv[1]);
  105282. isText = 1;
  105283. }
  105284. if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
  105285. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  105286. N++;
  105287. do{
  105288. nHaystack--;
  105289. zHaystack++;
  105290. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  105291. }
  105292. if( nNeedle>nHaystack ) N = 0;
  105293. }
  105294. sqlite3_result_int(context, N);
  105295. }
  105296. /*
  105297. ** Implementation of the printf() function.
  105298. */
  105299. static void printfFunc(
  105300. sqlite3_context *context,
  105301. int argc,
  105302. sqlite3_value **argv
  105303. ){
  105304. PrintfArguments x;
  105305. StrAccum str;
  105306. const char *zFormat;
  105307. int n;
  105308. sqlite3 *db = sqlite3_context_db_handle(context);
  105309. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  105310. x.nArg = argc-1;
  105311. x.nUsed = 0;
  105312. x.apArg = argv+1;
  105313. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  105314. str.printfFlags = SQLITE_PRINTF_SQLFUNC;
  105315. sqlite3_str_appendf(&str, zFormat, &x);
  105316. n = str.nChar;
  105317. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  105318. SQLITE_DYNAMIC);
  105319. }
  105320. }
  105321. /*
  105322. ** Implementation of the substr() function.
  105323. **
  105324. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  105325. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  105326. ** of x. If x is text, then we actually count UTF-8 characters.
  105327. ** If x is a blob, then we count bytes.
  105328. **
  105329. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  105330. **
  105331. ** If p2 is negative, return the p2 characters preceding p1.
  105332. */
  105333. static void substrFunc(
  105334. sqlite3_context *context,
  105335. int argc,
  105336. sqlite3_value **argv
  105337. ){
  105338. const unsigned char *z;
  105339. const unsigned char *z2;
  105340. int len;
  105341. int p0type;
  105342. i64 p1, p2;
  105343. int negP2 = 0;
  105344. assert( argc==3 || argc==2 );
  105345. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  105346. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  105347. ){
  105348. return;
  105349. }
  105350. p0type = sqlite3_value_type(argv[0]);
  105351. p1 = sqlite3_value_int(argv[1]);
  105352. if( p0type==SQLITE_BLOB ){
  105353. len = sqlite3_value_bytes(argv[0]);
  105354. z = sqlite3_value_blob(argv[0]);
  105355. if( z==0 ) return;
  105356. assert( len==sqlite3_value_bytes(argv[0]) );
  105357. }else{
  105358. z = sqlite3_value_text(argv[0]);
  105359. if( z==0 ) return;
  105360. len = 0;
  105361. if( p1<0 ){
  105362. for(z2=z; *z2; len++){
  105363. SQLITE_SKIP_UTF8(z2);
  105364. }
  105365. }
  105366. }
  105367. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  105368. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  105369. ** as substr(X,1,N) - it returns the first N characters of X. This
  105370. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  105371. ** from 2009-02-02 for compatibility of applications that exploited the
  105372. ** old buggy behavior. */
  105373. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  105374. #endif
  105375. if( argc==3 ){
  105376. p2 = sqlite3_value_int(argv[2]);
  105377. if( p2<0 ){
  105378. p2 = -p2;
  105379. negP2 = 1;
  105380. }
  105381. }else{
  105382. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  105383. }
  105384. if( p1<0 ){
  105385. p1 += len;
  105386. if( p1<0 ){
  105387. p2 += p1;
  105388. if( p2<0 ) p2 = 0;
  105389. p1 = 0;
  105390. }
  105391. }else if( p1>0 ){
  105392. p1--;
  105393. }else if( p2>0 ){
  105394. p2--;
  105395. }
  105396. if( negP2 ){
  105397. p1 -= p2;
  105398. if( p1<0 ){
  105399. p2 += p1;
  105400. p1 = 0;
  105401. }
  105402. }
  105403. assert( p1>=0 && p2>=0 );
  105404. if( p0type!=SQLITE_BLOB ){
  105405. while( *z && p1 ){
  105406. SQLITE_SKIP_UTF8(z);
  105407. p1--;
  105408. }
  105409. for(z2=z; *z2 && p2; p2--){
  105410. SQLITE_SKIP_UTF8(z2);
  105411. }
  105412. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  105413. SQLITE_UTF8);
  105414. }else{
  105415. if( p1+p2>len ){
  105416. p2 = len-p1;
  105417. if( p2<0 ) p2 = 0;
  105418. }
  105419. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  105420. }
  105421. }
  105422. /*
  105423. ** Implementation of the round() function
  105424. */
  105425. #ifndef SQLITE_OMIT_FLOATING_POINT
  105426. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  105427. int n = 0;
  105428. double r;
  105429. char *zBuf;
  105430. assert( argc==1 || argc==2 );
  105431. if( argc==2 ){
  105432. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  105433. n = sqlite3_value_int(argv[1]);
  105434. if( n>30 ) n = 30;
  105435. if( n<0 ) n = 0;
  105436. }
  105437. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  105438. r = sqlite3_value_double(argv[0]);
  105439. /* If Y==0 and X will fit in a 64-bit int,
  105440. ** handle the rounding directly,
  105441. ** otherwise use printf.
  105442. */
  105443. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  105444. r = (double)((sqlite_int64)(r+0.5));
  105445. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  105446. r = -(double)((sqlite_int64)((-r)+0.5));
  105447. }else{
  105448. zBuf = sqlite3_mprintf("%.*f",n,r);
  105449. if( zBuf==0 ){
  105450. sqlite3_result_error_nomem(context);
  105451. return;
  105452. }
  105453. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  105454. sqlite3_free(zBuf);
  105455. }
  105456. sqlite3_result_double(context, r);
  105457. }
  105458. #endif
  105459. /*
  105460. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  105461. ** allocation fails, call sqlite3_result_error_nomem() to notify
  105462. ** the database handle that malloc() has failed and return NULL.
  105463. ** If nByte is larger than the maximum string or blob length, then
  105464. ** raise an SQLITE_TOOBIG exception and return NULL.
  105465. */
  105466. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  105467. char *z;
  105468. sqlite3 *db = sqlite3_context_db_handle(context);
  105469. assert( nByte>0 );
  105470. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  105471. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  105472. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  105473. sqlite3_result_error_toobig(context);
  105474. z = 0;
  105475. }else{
  105476. z = sqlite3Malloc(nByte);
  105477. if( !z ){
  105478. sqlite3_result_error_nomem(context);
  105479. }
  105480. }
  105481. return z;
  105482. }
  105483. /*
  105484. ** Implementation of the upper() and lower() SQL functions.
  105485. */
  105486. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  105487. char *z1;
  105488. const char *z2;
  105489. int i, n;
  105490. UNUSED_PARAMETER(argc);
  105491. z2 = (char*)sqlite3_value_text(argv[0]);
  105492. n = sqlite3_value_bytes(argv[0]);
  105493. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  105494. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  105495. if( z2 ){
  105496. z1 = contextMalloc(context, ((i64)n)+1);
  105497. if( z1 ){
  105498. for(i=0; i<n; i++){
  105499. z1[i] = (char)sqlite3Toupper(z2[i]);
  105500. }
  105501. sqlite3_result_text(context, z1, n, sqlite3_free);
  105502. }
  105503. }
  105504. }
  105505. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  105506. char *z1;
  105507. const char *z2;
  105508. int i, n;
  105509. UNUSED_PARAMETER(argc);
  105510. z2 = (char*)sqlite3_value_text(argv[0]);
  105511. n = sqlite3_value_bytes(argv[0]);
  105512. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  105513. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  105514. if( z2 ){
  105515. z1 = contextMalloc(context, ((i64)n)+1);
  105516. if( z1 ){
  105517. for(i=0; i<n; i++){
  105518. z1[i] = sqlite3Tolower(z2[i]);
  105519. }
  105520. sqlite3_result_text(context, z1, n, sqlite3_free);
  105521. }
  105522. }
  105523. }
  105524. /*
  105525. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  105526. ** as VDBE code so that unused argument values do not have to be computed.
  105527. ** However, we still need some kind of function implementation for this
  105528. ** routines in the function table. The noopFunc macro provides this.
  105529. ** noopFunc will never be called so it doesn't matter what the implementation
  105530. ** is. We might as well use the "version()" function as a substitute.
  105531. */
  105532. #define noopFunc versionFunc /* Substitute function - never called */
  105533. /*
  105534. ** Implementation of random(). Return a random integer.
  105535. */
  105536. static void randomFunc(
  105537. sqlite3_context *context,
  105538. int NotUsed,
  105539. sqlite3_value **NotUsed2
  105540. ){
  105541. sqlite_int64 r;
  105542. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  105543. sqlite3_randomness(sizeof(r), &r);
  105544. if( r<0 ){
  105545. /* We need to prevent a random number of 0x8000000000000000
  105546. ** (or -9223372036854775808) since when you do abs() of that
  105547. ** number of you get the same value back again. To do this
  105548. ** in a way that is testable, mask the sign bit off of negative
  105549. ** values, resulting in a positive value. Then take the
  105550. ** 2s complement of that positive value. The end result can
  105551. ** therefore be no less than -9223372036854775807.
  105552. */
  105553. r = -(r & LARGEST_INT64);
  105554. }
  105555. sqlite3_result_int64(context, r);
  105556. }
  105557. /*
  105558. ** Implementation of randomblob(N). Return a random blob
  105559. ** that is N bytes long.
  105560. */
  105561. static void randomBlob(
  105562. sqlite3_context *context,
  105563. int argc,
  105564. sqlite3_value **argv
  105565. ){
  105566. int n;
  105567. unsigned char *p;
  105568. assert( argc==1 );
  105569. UNUSED_PARAMETER(argc);
  105570. n = sqlite3_value_int(argv[0]);
  105571. if( n<1 ){
  105572. n = 1;
  105573. }
  105574. p = contextMalloc(context, n);
  105575. if( p ){
  105576. sqlite3_randomness(n, p);
  105577. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  105578. }
  105579. }
  105580. /*
  105581. ** Implementation of the last_insert_rowid() SQL function. The return
  105582. ** value is the same as the sqlite3_last_insert_rowid() API function.
  105583. */
  105584. static void last_insert_rowid(
  105585. sqlite3_context *context,
  105586. int NotUsed,
  105587. sqlite3_value **NotUsed2
  105588. ){
  105589. sqlite3 *db = sqlite3_context_db_handle(context);
  105590. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  105591. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  105592. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  105593. ** function. */
  105594. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  105595. }
  105596. /*
  105597. ** Implementation of the changes() SQL function.
  105598. **
  105599. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  105600. ** around the sqlite3_changes() C/C++ function and hence follows the same
  105601. ** rules for counting changes.
  105602. */
  105603. static void changes(
  105604. sqlite3_context *context,
  105605. int NotUsed,
  105606. sqlite3_value **NotUsed2
  105607. ){
  105608. sqlite3 *db = sqlite3_context_db_handle(context);
  105609. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  105610. sqlite3_result_int(context, sqlite3_changes(db));
  105611. }
  105612. /*
  105613. ** Implementation of the total_changes() SQL function. The return value is
  105614. ** the same as the sqlite3_total_changes() API function.
  105615. */
  105616. static void total_changes(
  105617. sqlite3_context *context,
  105618. int NotUsed,
  105619. sqlite3_value **NotUsed2
  105620. ){
  105621. sqlite3 *db = sqlite3_context_db_handle(context);
  105622. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  105623. /* IMP: R-52756-41993 This function is a wrapper around the
  105624. ** sqlite3_total_changes() C/C++ interface. */
  105625. sqlite3_result_int(context, sqlite3_total_changes(db));
  105626. }
  105627. /*
  105628. ** A structure defining how to do GLOB-style comparisons.
  105629. */
  105630. struct compareInfo {
  105631. u8 matchAll; /* "*" or "%" */
  105632. u8 matchOne; /* "?" or "_" */
  105633. u8 matchSet; /* "[" or 0 */
  105634. u8 noCase; /* true to ignore case differences */
  105635. };
  105636. /*
  105637. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  105638. ** character is exactly one byte in size. Also, provde the Utf8Read()
  105639. ** macro for fast reading of the next character in the common case where
  105640. ** the next character is ASCII.
  105641. */
  105642. #if defined(SQLITE_EBCDIC)
  105643. # define sqlite3Utf8Read(A) (*((*A)++))
  105644. # define Utf8Read(A) (*(A++))
  105645. #else
  105646. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  105647. #endif
  105648. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  105649. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  105650. ** case. Thus 'a' LIKE 'A' would be true. */
  105651. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  105652. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  105653. ** is case sensitive causing 'a' LIKE 'A' to be false */
  105654. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  105655. /*
  105656. ** Possible error returns from patternMatch()
  105657. */
  105658. #define SQLITE_MATCH 0
  105659. #define SQLITE_NOMATCH 1
  105660. #define SQLITE_NOWILDCARDMATCH 2
  105661. /*
  105662. ** Compare two UTF-8 strings for equality where the first string is
  105663. ** a GLOB or LIKE expression. Return values:
  105664. **
  105665. ** SQLITE_MATCH: Match
  105666. ** SQLITE_NOMATCH: No match
  105667. ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
  105668. **
  105669. ** Globbing rules:
  105670. **
  105671. ** '*' Matches any sequence of zero or more characters.
  105672. **
  105673. ** '?' Matches exactly one character.
  105674. **
  105675. ** [...] Matches one character from the enclosed list of
  105676. ** characters.
  105677. **
  105678. ** [^...] Matches one character not in the enclosed list.
  105679. **
  105680. ** With the [...] and [^...] matching, a ']' character can be included
  105681. ** in the list by making it the first character after '[' or '^'. A
  105682. ** range of characters can be specified using '-'. Example:
  105683. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  105684. ** it the last character in the list.
  105685. **
  105686. ** Like matching rules:
  105687. **
  105688. ** '%' Matches any sequence of zero or more characters
  105689. **
  105690. *** '_' Matches any one character
  105691. **
  105692. ** Ec Where E is the "esc" character and c is any other
  105693. ** character, including '%', '_', and esc, match exactly c.
  105694. **
  105695. ** The comments within this routine usually assume glob matching.
  105696. **
  105697. ** This routine is usually quick, but can be N**2 in the worst case.
  105698. */
  105699. static int patternCompare(
  105700. const u8 *zPattern, /* The glob pattern */
  105701. const u8 *zString, /* The string to compare against the glob */
  105702. const struct compareInfo *pInfo, /* Information about how to do the compare */
  105703. u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
  105704. ){
  105705. u32 c, c2; /* Next pattern and input string chars */
  105706. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  105707. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  105708. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  105709. const u8 *zEscaped = 0; /* One past the last escaped input char */
  105710. while( (c = Utf8Read(zPattern))!=0 ){
  105711. if( c==matchAll ){ /* Match "*" */
  105712. /* Skip over multiple "*" characters in the pattern. If there
  105713. ** are also "?" characters, skip those as well, but consume a
  105714. ** single character of the input string for each "?" skipped */
  105715. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  105716. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  105717. return SQLITE_NOWILDCARDMATCH;
  105718. }
  105719. }
  105720. if( c==0 ){
  105721. return SQLITE_MATCH; /* "*" at the end of the pattern matches */
  105722. }else if( c==matchOther ){
  105723. if( pInfo->matchSet==0 ){
  105724. c = sqlite3Utf8Read(&zPattern);
  105725. if( c==0 ) return SQLITE_NOWILDCARDMATCH;
  105726. }else{
  105727. /* "[...]" immediately follows the "*". We have to do a slow
  105728. ** recursive search in this case, but it is an unusual case. */
  105729. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  105730. while( *zString ){
  105731. int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
  105732. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  105733. SQLITE_SKIP_UTF8(zString);
  105734. }
  105735. return SQLITE_NOWILDCARDMATCH;
  105736. }
  105737. }
  105738. /* At this point variable c contains the first character of the
  105739. ** pattern string past the "*". Search in the input string for the
  105740. ** first matching character and recursively continue the match from
  105741. ** that point.
  105742. **
  105743. ** For a case-insensitive search, set variable cx to be the same as
  105744. ** c but in the other case and search the input string for either
  105745. ** c or cx.
  105746. */
  105747. if( c<=0x80 ){
  105748. char zStop[3];
  105749. int bMatch;
  105750. if( noCase ){
  105751. zStop[0] = sqlite3Toupper(c);
  105752. zStop[1] = sqlite3Tolower(c);
  105753. zStop[2] = 0;
  105754. }else{
  105755. zStop[0] = c;
  105756. zStop[1] = 0;
  105757. }
  105758. while(1){
  105759. zString += strcspn((const char*)zString, zStop);
  105760. if( zString[0]==0 ) break;
  105761. zString++;
  105762. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  105763. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  105764. }
  105765. }else{
  105766. int bMatch;
  105767. while( (c2 = Utf8Read(zString))!=0 ){
  105768. if( c2!=c ) continue;
  105769. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  105770. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  105771. }
  105772. }
  105773. return SQLITE_NOWILDCARDMATCH;
  105774. }
  105775. if( c==matchOther ){
  105776. if( pInfo->matchSet==0 ){
  105777. c = sqlite3Utf8Read(&zPattern);
  105778. if( c==0 ) return SQLITE_NOMATCH;
  105779. zEscaped = zPattern;
  105780. }else{
  105781. u32 prior_c = 0;
  105782. int seen = 0;
  105783. int invert = 0;
  105784. c = sqlite3Utf8Read(&zString);
  105785. if( c==0 ) return SQLITE_NOMATCH;
  105786. c2 = sqlite3Utf8Read(&zPattern);
  105787. if( c2=='^' ){
  105788. invert = 1;
  105789. c2 = sqlite3Utf8Read(&zPattern);
  105790. }
  105791. if( c2==']' ){
  105792. if( c==']' ) seen = 1;
  105793. c2 = sqlite3Utf8Read(&zPattern);
  105794. }
  105795. while( c2 && c2!=']' ){
  105796. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  105797. c2 = sqlite3Utf8Read(&zPattern);
  105798. if( c>=prior_c && c<=c2 ) seen = 1;
  105799. prior_c = 0;
  105800. }else{
  105801. if( c==c2 ){
  105802. seen = 1;
  105803. }
  105804. prior_c = c2;
  105805. }
  105806. c2 = sqlite3Utf8Read(&zPattern);
  105807. }
  105808. if( c2==0 || (seen ^ invert)==0 ){
  105809. return SQLITE_NOMATCH;
  105810. }
  105811. continue;
  105812. }
  105813. }
  105814. c2 = Utf8Read(zString);
  105815. if( c==c2 ) continue;
  105816. if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
  105817. continue;
  105818. }
  105819. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  105820. return SQLITE_NOMATCH;
  105821. }
  105822. return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
  105823. }
  105824. /*
  105825. ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
  105826. ** non-zero if there is no match.
  105827. */
  105828. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  105829. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
  105830. }
  105831. /*
  105832. ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
  105833. ** a miss - like strcmp().
  105834. */
  105835. SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
  105836. return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
  105837. }
  105838. /*
  105839. ** Count the number of times that the LIKE operator (or GLOB which is
  105840. ** just a variation of LIKE) gets called. This is used for testing
  105841. ** only.
  105842. */
  105843. #ifdef SQLITE_TEST
  105844. SQLITE_API int sqlite3_like_count = 0;
  105845. #endif
  105846. /*
  105847. ** Implementation of the like() SQL function. This function implements
  105848. ** the build-in LIKE operator. The first argument to the function is the
  105849. ** pattern and the second argument is the string. So, the SQL statements:
  105850. **
  105851. ** A LIKE B
  105852. **
  105853. ** is implemented as like(B,A).
  105854. **
  105855. ** This same function (with a different compareInfo structure) computes
  105856. ** the GLOB operator.
  105857. */
  105858. static void likeFunc(
  105859. sqlite3_context *context,
  105860. int argc,
  105861. sqlite3_value **argv
  105862. ){
  105863. const unsigned char *zA, *zB;
  105864. u32 escape;
  105865. int nPat;
  105866. sqlite3 *db = sqlite3_context_db_handle(context);
  105867. struct compareInfo *pInfo = sqlite3_user_data(context);
  105868. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  105869. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  105870. || sqlite3_value_type(argv[1])==SQLITE_BLOB
  105871. ){
  105872. #ifdef SQLITE_TEST
  105873. sqlite3_like_count++;
  105874. #endif
  105875. sqlite3_result_int(context, 0);
  105876. return;
  105877. }
  105878. #endif
  105879. zB = sqlite3_value_text(argv[0]);
  105880. zA = sqlite3_value_text(argv[1]);
  105881. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  105882. ** of deep recursion and N*N behavior in patternCompare().
  105883. */
  105884. nPat = sqlite3_value_bytes(argv[0]);
  105885. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  105886. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  105887. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  105888. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  105889. return;
  105890. }
  105891. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  105892. if( argc==3 ){
  105893. /* The escape character string must consist of a single UTF-8 character.
  105894. ** Otherwise, return an error.
  105895. */
  105896. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  105897. if( zEsc==0 ) return;
  105898. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  105899. sqlite3_result_error(context,
  105900. "ESCAPE expression must be a single character", -1);
  105901. return;
  105902. }
  105903. escape = sqlite3Utf8Read(&zEsc);
  105904. }else{
  105905. escape = pInfo->matchSet;
  105906. }
  105907. if( zA && zB ){
  105908. #ifdef SQLITE_TEST
  105909. sqlite3_like_count++;
  105910. #endif
  105911. sqlite3_result_int(context,
  105912. patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
  105913. }
  105914. }
  105915. /*
  105916. ** Implementation of the NULLIF(x,y) function. The result is the first
  105917. ** argument if the arguments are different. The result is NULL if the
  105918. ** arguments are equal to each other.
  105919. */
  105920. static void nullifFunc(
  105921. sqlite3_context *context,
  105922. int NotUsed,
  105923. sqlite3_value **argv
  105924. ){
  105925. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  105926. UNUSED_PARAMETER(NotUsed);
  105927. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  105928. sqlite3_result_value(context, argv[0]);
  105929. }
  105930. }
  105931. /*
  105932. ** Implementation of the sqlite_version() function. The result is the version
  105933. ** of the SQLite library that is running.
  105934. */
  105935. static void versionFunc(
  105936. sqlite3_context *context,
  105937. int NotUsed,
  105938. sqlite3_value **NotUsed2
  105939. ){
  105940. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  105941. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  105942. ** sqlite3_libversion() C-interface. */
  105943. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  105944. }
  105945. /*
  105946. ** Implementation of the sqlite_source_id() function. The result is a string
  105947. ** that identifies the particular version of the source code used to build
  105948. ** SQLite.
  105949. */
  105950. static void sourceidFunc(
  105951. sqlite3_context *context,
  105952. int NotUsed,
  105953. sqlite3_value **NotUsed2
  105954. ){
  105955. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  105956. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  105957. ** sqlite3_sourceid() C interface. */
  105958. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  105959. }
  105960. /*
  105961. ** Implementation of the sqlite_log() function. This is a wrapper around
  105962. ** sqlite3_log(). The return value is NULL. The function exists purely for
  105963. ** its side-effects.
  105964. */
  105965. static void errlogFunc(
  105966. sqlite3_context *context,
  105967. int argc,
  105968. sqlite3_value **argv
  105969. ){
  105970. UNUSED_PARAMETER(argc);
  105971. UNUSED_PARAMETER(context);
  105972. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  105973. }
  105974. /*
  105975. ** Implementation of the sqlite_compileoption_used() function.
  105976. ** The result is an integer that identifies if the compiler option
  105977. ** was used to build SQLite.
  105978. */
  105979. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  105980. static void compileoptionusedFunc(
  105981. sqlite3_context *context,
  105982. int argc,
  105983. sqlite3_value **argv
  105984. ){
  105985. const char *zOptName;
  105986. assert( argc==1 );
  105987. UNUSED_PARAMETER(argc);
  105988. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  105989. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  105990. ** function.
  105991. */
  105992. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  105993. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  105994. }
  105995. }
  105996. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  105997. /*
  105998. ** Implementation of the sqlite_compileoption_get() function.
  105999. ** The result is a string that identifies the compiler options
  106000. ** used to build SQLite.
  106001. */
  106002. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  106003. static void compileoptiongetFunc(
  106004. sqlite3_context *context,
  106005. int argc,
  106006. sqlite3_value **argv
  106007. ){
  106008. int n;
  106009. assert( argc==1 );
  106010. UNUSED_PARAMETER(argc);
  106011. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  106012. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  106013. */
  106014. n = sqlite3_value_int(argv[0]);
  106015. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  106016. }
  106017. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  106018. /* Array for converting from half-bytes (nybbles) into ASCII hex
  106019. ** digits. */
  106020. static const char hexdigits[] = {
  106021. '0', '1', '2', '3', '4', '5', '6', '7',
  106022. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  106023. };
  106024. /*
  106025. ** Implementation of the QUOTE() function. This function takes a single
  106026. ** argument. If the argument is numeric, the return value is the same as
  106027. ** the argument. If the argument is NULL, the return value is the string
  106028. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  106029. ** single-quote escapes.
  106030. */
  106031. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  106032. assert( argc==1 );
  106033. UNUSED_PARAMETER(argc);
  106034. switch( sqlite3_value_type(argv[0]) ){
  106035. case SQLITE_FLOAT: {
  106036. double r1, r2;
  106037. char zBuf[50];
  106038. r1 = sqlite3_value_double(argv[0]);
  106039. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  106040. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  106041. if( r1!=r2 ){
  106042. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  106043. }
  106044. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  106045. break;
  106046. }
  106047. case SQLITE_INTEGER: {
  106048. sqlite3_result_value(context, argv[0]);
  106049. break;
  106050. }
  106051. case SQLITE_BLOB: {
  106052. char *zText = 0;
  106053. char const *zBlob = sqlite3_value_blob(argv[0]);
  106054. int nBlob = sqlite3_value_bytes(argv[0]);
  106055. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  106056. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  106057. if( zText ){
  106058. int i;
  106059. for(i=0; i<nBlob; i++){
  106060. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  106061. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  106062. }
  106063. zText[(nBlob*2)+2] = '\'';
  106064. zText[(nBlob*2)+3] = '\0';
  106065. zText[0] = 'X';
  106066. zText[1] = '\'';
  106067. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  106068. sqlite3_free(zText);
  106069. }
  106070. break;
  106071. }
  106072. case SQLITE_TEXT: {
  106073. int i,j;
  106074. u64 n;
  106075. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  106076. char *z;
  106077. if( zArg==0 ) return;
  106078. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  106079. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  106080. if( z ){
  106081. z[0] = '\'';
  106082. for(i=0, j=1; zArg[i]; i++){
  106083. z[j++] = zArg[i];
  106084. if( zArg[i]=='\'' ){
  106085. z[j++] = '\'';
  106086. }
  106087. }
  106088. z[j++] = '\'';
  106089. z[j] = 0;
  106090. sqlite3_result_text(context, z, j, sqlite3_free);
  106091. }
  106092. break;
  106093. }
  106094. default: {
  106095. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  106096. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  106097. break;
  106098. }
  106099. }
  106100. }
  106101. /*
  106102. ** The unicode() function. Return the integer unicode code-point value
  106103. ** for the first character of the input string.
  106104. */
  106105. static void unicodeFunc(
  106106. sqlite3_context *context,
  106107. int argc,
  106108. sqlite3_value **argv
  106109. ){
  106110. const unsigned char *z = sqlite3_value_text(argv[0]);
  106111. (void)argc;
  106112. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  106113. }
  106114. /*
  106115. ** The char() function takes zero or more arguments, each of which is
  106116. ** an integer. It constructs a string where each character of the string
  106117. ** is the unicode character for the corresponding integer argument.
  106118. */
  106119. static void charFunc(
  106120. sqlite3_context *context,
  106121. int argc,
  106122. sqlite3_value **argv
  106123. ){
  106124. unsigned char *z, *zOut;
  106125. int i;
  106126. zOut = z = sqlite3_malloc64( argc*4+1 );
  106127. if( z==0 ){
  106128. sqlite3_result_error_nomem(context);
  106129. return;
  106130. }
  106131. for(i=0; i<argc; i++){
  106132. sqlite3_int64 x;
  106133. unsigned c;
  106134. x = sqlite3_value_int64(argv[i]);
  106135. if( x<0 || x>0x10ffff ) x = 0xfffd;
  106136. c = (unsigned)(x & 0x1fffff);
  106137. if( c<0x00080 ){
  106138. *zOut++ = (u8)(c&0xFF);
  106139. }else if( c<0x00800 ){
  106140. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  106141. *zOut++ = 0x80 + (u8)(c & 0x3F);
  106142. }else if( c<0x10000 ){
  106143. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  106144. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  106145. *zOut++ = 0x80 + (u8)(c & 0x3F);
  106146. }else{
  106147. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  106148. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  106149. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  106150. *zOut++ = 0x80 + (u8)(c & 0x3F);
  106151. } \
  106152. }
  106153. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  106154. }
  106155. /*
  106156. ** The hex() function. Interpret the argument as a blob. Return
  106157. ** a hexadecimal rendering as text.
  106158. */
  106159. static void hexFunc(
  106160. sqlite3_context *context,
  106161. int argc,
  106162. sqlite3_value **argv
  106163. ){
  106164. int i, n;
  106165. const unsigned char *pBlob;
  106166. char *zHex, *z;
  106167. assert( argc==1 );
  106168. UNUSED_PARAMETER(argc);
  106169. pBlob = sqlite3_value_blob(argv[0]);
  106170. n = sqlite3_value_bytes(argv[0]);
  106171. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  106172. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  106173. if( zHex ){
  106174. for(i=0; i<n; i++, pBlob++){
  106175. unsigned char c = *pBlob;
  106176. *(z++) = hexdigits[(c>>4)&0xf];
  106177. *(z++) = hexdigits[c&0xf];
  106178. }
  106179. *z = 0;
  106180. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  106181. }
  106182. }
  106183. /*
  106184. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  106185. */
  106186. static void zeroblobFunc(
  106187. sqlite3_context *context,
  106188. int argc,
  106189. sqlite3_value **argv
  106190. ){
  106191. i64 n;
  106192. int rc;
  106193. assert( argc==1 );
  106194. UNUSED_PARAMETER(argc);
  106195. n = sqlite3_value_int64(argv[0]);
  106196. if( n<0 ) n = 0;
  106197. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  106198. if( rc ){
  106199. sqlite3_result_error_code(context, rc);
  106200. }
  106201. }
  106202. /*
  106203. ** The replace() function. Three arguments are all strings: call
  106204. ** them A, B, and C. The result is also a string which is derived
  106205. ** from A by replacing every occurrence of B with C. The match
  106206. ** must be exact. Collating sequences are not used.
  106207. */
  106208. static void replaceFunc(
  106209. sqlite3_context *context,
  106210. int argc,
  106211. sqlite3_value **argv
  106212. ){
  106213. const unsigned char *zStr; /* The input string A */
  106214. const unsigned char *zPattern; /* The pattern string B */
  106215. const unsigned char *zRep; /* The replacement string C */
  106216. unsigned char *zOut; /* The output */
  106217. int nStr; /* Size of zStr */
  106218. int nPattern; /* Size of zPattern */
  106219. int nRep; /* Size of zRep */
  106220. i64 nOut; /* Maximum size of zOut */
  106221. int loopLimit; /* Last zStr[] that might match zPattern[] */
  106222. int i, j; /* Loop counters */
  106223. unsigned cntExpand; /* Number zOut expansions */
  106224. sqlite3 *db = sqlite3_context_db_handle(context);
  106225. assert( argc==3 );
  106226. UNUSED_PARAMETER(argc);
  106227. zStr = sqlite3_value_text(argv[0]);
  106228. if( zStr==0 ) return;
  106229. nStr = sqlite3_value_bytes(argv[0]);
  106230. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  106231. zPattern = sqlite3_value_text(argv[1]);
  106232. if( zPattern==0 ){
  106233. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  106234. || sqlite3_context_db_handle(context)->mallocFailed );
  106235. return;
  106236. }
  106237. if( zPattern[0]==0 ){
  106238. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  106239. sqlite3_result_value(context, argv[0]);
  106240. return;
  106241. }
  106242. nPattern = sqlite3_value_bytes(argv[1]);
  106243. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  106244. zRep = sqlite3_value_text(argv[2]);
  106245. if( zRep==0 ) return;
  106246. nRep = sqlite3_value_bytes(argv[2]);
  106247. assert( zRep==sqlite3_value_text(argv[2]) );
  106248. nOut = nStr + 1;
  106249. assert( nOut<SQLITE_MAX_LENGTH );
  106250. zOut = contextMalloc(context, (i64)nOut);
  106251. if( zOut==0 ){
  106252. return;
  106253. }
  106254. loopLimit = nStr - nPattern;
  106255. cntExpand = 0;
  106256. for(i=j=0; i<=loopLimit; i++){
  106257. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  106258. zOut[j++] = zStr[i];
  106259. }else{
  106260. if( nRep>nPattern ){
  106261. nOut += nRep - nPattern;
  106262. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  106263. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  106264. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  106265. sqlite3_result_error_toobig(context);
  106266. sqlite3_free(zOut);
  106267. return;
  106268. }
  106269. cntExpand++;
  106270. if( (cntExpand&(cntExpand-1))==0 ){
  106271. /* Grow the size of the output buffer only on substitutions
  106272. ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
  106273. u8 *zOld;
  106274. zOld = zOut;
  106275. zOut = sqlite3_realloc64(zOut, (int)nOut + (nOut - nStr - 1));
  106276. if( zOut==0 ){
  106277. sqlite3_result_error_nomem(context);
  106278. sqlite3_free(zOld);
  106279. return;
  106280. }
  106281. }
  106282. }
  106283. memcpy(&zOut[j], zRep, nRep);
  106284. j += nRep;
  106285. i += nPattern-1;
  106286. }
  106287. }
  106288. assert( j+nStr-i+1<=nOut );
  106289. memcpy(&zOut[j], &zStr[i], nStr-i);
  106290. j += nStr - i;
  106291. assert( j<=nOut );
  106292. zOut[j] = 0;
  106293. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  106294. }
  106295. /*
  106296. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  106297. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  106298. */
  106299. static void trimFunc(
  106300. sqlite3_context *context,
  106301. int argc,
  106302. sqlite3_value **argv
  106303. ){
  106304. const unsigned char *zIn; /* Input string */
  106305. const unsigned char *zCharSet; /* Set of characters to trim */
  106306. int nIn; /* Number of bytes in input */
  106307. int flags; /* 1: trimleft 2: trimright 3: trim */
  106308. int i; /* Loop counter */
  106309. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  106310. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  106311. int nChar; /* Number of characters in zCharSet */
  106312. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  106313. return;
  106314. }
  106315. zIn = sqlite3_value_text(argv[0]);
  106316. if( zIn==0 ) return;
  106317. nIn = sqlite3_value_bytes(argv[0]);
  106318. assert( zIn==sqlite3_value_text(argv[0]) );
  106319. if( argc==1 ){
  106320. static const unsigned char lenOne[] = { 1 };
  106321. static unsigned char * const azOne[] = { (u8*)" " };
  106322. nChar = 1;
  106323. aLen = (u8*)lenOne;
  106324. azChar = (unsigned char **)azOne;
  106325. zCharSet = 0;
  106326. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  106327. return;
  106328. }else{
  106329. const unsigned char *z;
  106330. for(z=zCharSet, nChar=0; *z; nChar++){
  106331. SQLITE_SKIP_UTF8(z);
  106332. }
  106333. if( nChar>0 ){
  106334. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  106335. if( azChar==0 ){
  106336. return;
  106337. }
  106338. aLen = (unsigned char*)&azChar[nChar];
  106339. for(z=zCharSet, nChar=0; *z; nChar++){
  106340. azChar[nChar] = (unsigned char *)z;
  106341. SQLITE_SKIP_UTF8(z);
  106342. aLen[nChar] = (u8)(z - azChar[nChar]);
  106343. }
  106344. }
  106345. }
  106346. if( nChar>0 ){
  106347. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  106348. if( flags & 1 ){
  106349. while( nIn>0 ){
  106350. int len = 0;
  106351. for(i=0; i<nChar; i++){
  106352. len = aLen[i];
  106353. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  106354. }
  106355. if( i>=nChar ) break;
  106356. zIn += len;
  106357. nIn -= len;
  106358. }
  106359. }
  106360. if( flags & 2 ){
  106361. while( nIn>0 ){
  106362. int len = 0;
  106363. for(i=0; i<nChar; i++){
  106364. len = aLen[i];
  106365. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  106366. }
  106367. if( i>=nChar ) break;
  106368. nIn -= len;
  106369. }
  106370. }
  106371. if( zCharSet ){
  106372. sqlite3_free(azChar);
  106373. }
  106374. }
  106375. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  106376. }
  106377. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  106378. /*
  106379. ** The "unknown" function is automatically substituted in place of
  106380. ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
  106381. ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
  106382. ** When the "sqlite3" command-line shell is built using this functionality,
  106383. ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
  106384. ** involving application-defined functions to be examined in a generic
  106385. ** sqlite3 shell.
  106386. */
  106387. static void unknownFunc(
  106388. sqlite3_context *context,
  106389. int argc,
  106390. sqlite3_value **argv
  106391. ){
  106392. /* no-op */
  106393. }
  106394. #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
  106395. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  106396. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  106397. ** when SQLite is built.
  106398. */
  106399. #ifdef SQLITE_SOUNDEX
  106400. /*
  106401. ** Compute the soundex encoding of a word.
  106402. **
  106403. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  106404. ** soundex encoding of the string X.
  106405. */
  106406. static void soundexFunc(
  106407. sqlite3_context *context,
  106408. int argc,
  106409. sqlite3_value **argv
  106410. ){
  106411. char zResult[8];
  106412. const u8 *zIn;
  106413. int i, j;
  106414. static const unsigned char iCode[] = {
  106415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  106416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  106417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  106418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  106419. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  106420. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  106421. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  106422. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  106423. };
  106424. assert( argc==1 );
  106425. zIn = (u8*)sqlite3_value_text(argv[0]);
  106426. if( zIn==0 ) zIn = (u8*)"";
  106427. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  106428. if( zIn[i] ){
  106429. u8 prevcode = iCode[zIn[i]&0x7f];
  106430. zResult[0] = sqlite3Toupper(zIn[i]);
  106431. for(j=1; j<4 && zIn[i]; i++){
  106432. int code = iCode[zIn[i]&0x7f];
  106433. if( code>0 ){
  106434. if( code!=prevcode ){
  106435. prevcode = code;
  106436. zResult[j++] = code + '0';
  106437. }
  106438. }else{
  106439. prevcode = 0;
  106440. }
  106441. }
  106442. while( j<4 ){
  106443. zResult[j++] = '0';
  106444. }
  106445. zResult[j] = 0;
  106446. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  106447. }else{
  106448. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  106449. ** is NULL or contains no ASCII alphabetic characters. */
  106450. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  106451. }
  106452. }
  106453. #endif /* SQLITE_SOUNDEX */
  106454. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  106455. /*
  106456. ** A function that loads a shared-library extension then returns NULL.
  106457. */
  106458. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  106459. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  106460. const char *zProc;
  106461. sqlite3 *db = sqlite3_context_db_handle(context);
  106462. char *zErrMsg = 0;
  106463. /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
  106464. ** flag is set. See the sqlite3_enable_load_extension() API.
  106465. */
  106466. if( (db->flags & SQLITE_LoadExtFunc)==0 ){
  106467. sqlite3_result_error(context, "not authorized", -1);
  106468. return;
  106469. }
  106470. if( argc==2 ){
  106471. zProc = (const char *)sqlite3_value_text(argv[1]);
  106472. }else{
  106473. zProc = 0;
  106474. }
  106475. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  106476. sqlite3_result_error(context, zErrMsg, -1);
  106477. sqlite3_free(zErrMsg);
  106478. }
  106479. }
  106480. #endif
  106481. /*
  106482. ** An instance of the following structure holds the context of a
  106483. ** sum() or avg() aggregate computation.
  106484. */
  106485. typedef struct SumCtx SumCtx;
  106486. struct SumCtx {
  106487. double rSum; /* Floating point sum */
  106488. i64 iSum; /* Integer sum */
  106489. i64 cnt; /* Number of elements summed */
  106490. u8 overflow; /* True if integer overflow seen */
  106491. u8 approx; /* True if non-integer value was input to the sum */
  106492. };
  106493. /*
  106494. ** Routines used to compute the sum, average, and total.
  106495. **
  106496. ** The SUM() function follows the (broken) SQL standard which means
  106497. ** that it returns NULL if it sums over no inputs. TOTAL returns
  106498. ** 0.0 in that case. In addition, TOTAL always returns a float where
  106499. ** SUM might return an integer if it never encounters a floating point
  106500. ** value. TOTAL never fails, but SUM might through an exception if
  106501. ** it overflows an integer.
  106502. */
  106503. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  106504. SumCtx *p;
  106505. int type;
  106506. assert( argc==1 );
  106507. UNUSED_PARAMETER(argc);
  106508. p = sqlite3_aggregate_context(context, sizeof(*p));
  106509. type = sqlite3_value_numeric_type(argv[0]);
  106510. if( p && type!=SQLITE_NULL ){
  106511. p->cnt++;
  106512. if( type==SQLITE_INTEGER ){
  106513. i64 v = sqlite3_value_int64(argv[0]);
  106514. p->rSum += v;
  106515. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  106516. p->approx = p->overflow = 1;
  106517. }
  106518. }else{
  106519. p->rSum += sqlite3_value_double(argv[0]);
  106520. p->approx = 1;
  106521. }
  106522. }
  106523. }
  106524. #ifndef SQLITE_OMIT_WINDOWFUNC
  106525. static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){
  106526. SumCtx *p;
  106527. int type;
  106528. assert( argc==1 );
  106529. UNUSED_PARAMETER(argc);
  106530. p = sqlite3_aggregate_context(context, sizeof(*p));
  106531. type = sqlite3_value_numeric_type(argv[0]);
  106532. /* p is always non-NULL because sumStep() will have been called first
  106533. ** to initialize it */
  106534. if( ALWAYS(p) && type!=SQLITE_NULL ){
  106535. assert( p->cnt>0 );
  106536. p->cnt--;
  106537. assert( type==SQLITE_INTEGER || p->approx );
  106538. if( type==SQLITE_INTEGER && p->approx==0 ){
  106539. i64 v = sqlite3_value_int64(argv[0]);
  106540. p->rSum -= v;
  106541. p->iSum -= v;
  106542. }else{
  106543. p->rSum -= sqlite3_value_double(argv[0]);
  106544. }
  106545. }
  106546. }
  106547. #else
  106548. # define sumInverse 0
  106549. #endif /* SQLITE_OMIT_WINDOWFUNC */
  106550. static void sumFinalize(sqlite3_context *context){
  106551. SumCtx *p;
  106552. p = sqlite3_aggregate_context(context, 0);
  106553. if( p && p->cnt>0 ){
  106554. if( p->overflow ){
  106555. sqlite3_result_error(context,"integer overflow",-1);
  106556. }else if( p->approx ){
  106557. sqlite3_result_double(context, p->rSum);
  106558. }else{
  106559. sqlite3_result_int64(context, p->iSum);
  106560. }
  106561. }
  106562. }
  106563. static void avgFinalize(sqlite3_context *context){
  106564. SumCtx *p;
  106565. p = sqlite3_aggregate_context(context, 0);
  106566. if( p && p->cnt>0 ){
  106567. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  106568. }
  106569. }
  106570. static void totalFinalize(sqlite3_context *context){
  106571. SumCtx *p;
  106572. p = sqlite3_aggregate_context(context, 0);
  106573. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  106574. sqlite3_result_double(context, p ? p->rSum : (double)0);
  106575. }
  106576. /*
  106577. ** The following structure keeps track of state information for the
  106578. ** count() aggregate function.
  106579. */
  106580. typedef struct CountCtx CountCtx;
  106581. struct CountCtx {
  106582. i64 n;
  106583. #ifdef SQLITE_DEBUG
  106584. int bInverse; /* True if xInverse() ever called */
  106585. #endif
  106586. };
  106587. /*
  106588. ** Routines to implement the count() aggregate function.
  106589. */
  106590. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  106591. CountCtx *p;
  106592. p = sqlite3_aggregate_context(context, sizeof(*p));
  106593. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  106594. p->n++;
  106595. }
  106596. #ifndef SQLITE_OMIT_DEPRECATED
  106597. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  106598. ** sure it still operates correctly, verify that its count agrees with our
  106599. ** internal count when using count(*) and when the total count can be
  106600. ** expressed as a 32-bit integer. */
  106601. assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
  106602. || p->n==sqlite3_aggregate_count(context) );
  106603. #endif
  106604. }
  106605. static void countFinalize(sqlite3_context *context){
  106606. CountCtx *p;
  106607. p = sqlite3_aggregate_context(context, 0);
  106608. sqlite3_result_int64(context, p ? p->n : 0);
  106609. }
  106610. #ifndef SQLITE_OMIT_WINDOWFUNC
  106611. static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
  106612. CountCtx *p;
  106613. p = sqlite3_aggregate_context(ctx, sizeof(*p));
  106614. /* p is always non-NULL since countStep() will have been called first */
  106615. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){
  106616. p->n--;
  106617. #ifdef SQLITE_DEBUG
  106618. p->bInverse = 1;
  106619. #endif
  106620. }
  106621. }
  106622. #else
  106623. # define countInverse 0
  106624. #endif /* SQLITE_OMIT_WINDOWFUNC */
  106625. /*
  106626. ** Routines to implement min() and max() aggregate functions.
  106627. */
  106628. static void minmaxStep(
  106629. sqlite3_context *context,
  106630. int NotUsed,
  106631. sqlite3_value **argv
  106632. ){
  106633. Mem *pArg = (Mem *)argv[0];
  106634. Mem *pBest;
  106635. UNUSED_PARAMETER(NotUsed);
  106636. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  106637. if( !pBest ) return;
  106638. if( sqlite3_value_type(pArg)==SQLITE_NULL ){
  106639. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  106640. }else if( pBest->flags ){
  106641. int max;
  106642. int cmp;
  106643. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  106644. /* This step function is used for both the min() and max() aggregates,
  106645. ** the only difference between the two being that the sense of the
  106646. ** comparison is inverted. For the max() aggregate, the
  106647. ** sqlite3_user_data() function returns (void *)-1. For min() it
  106648. ** returns (void *)db, where db is the sqlite3* database pointer.
  106649. ** Therefore the next statement sets variable 'max' to 1 for the max()
  106650. ** aggregate, or 0 for min().
  106651. */
  106652. max = sqlite3_user_data(context)!=0;
  106653. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  106654. if( (max && cmp<0) || (!max && cmp>0) ){
  106655. sqlite3VdbeMemCopy(pBest, pArg);
  106656. }else{
  106657. sqlite3SkipAccumulatorLoad(context);
  106658. }
  106659. }else{
  106660. pBest->db = sqlite3_context_db_handle(context);
  106661. sqlite3VdbeMemCopy(pBest, pArg);
  106662. }
  106663. }
  106664. static void minMaxValueFinalize(sqlite3_context *context, int bValue){
  106665. sqlite3_value *pRes;
  106666. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  106667. if( pRes ){
  106668. if( pRes->flags ){
  106669. sqlite3_result_value(context, pRes);
  106670. }
  106671. if( bValue==0 ) sqlite3VdbeMemRelease(pRes);
  106672. }
  106673. }
  106674. #ifndef SQLITE_OMIT_WINDOWFUNC
  106675. static void minMaxValue(sqlite3_context *context){
  106676. minMaxValueFinalize(context, 1);
  106677. }
  106678. #else
  106679. # define minMaxValue 0
  106680. #endif /* SQLITE_OMIT_WINDOWFUNC */
  106681. static void minMaxFinalize(sqlite3_context *context){
  106682. minMaxValueFinalize(context, 0);
  106683. }
  106684. /*
  106685. ** group_concat(EXPR, ?SEPARATOR?)
  106686. */
  106687. static void groupConcatStep(
  106688. sqlite3_context *context,
  106689. int argc,
  106690. sqlite3_value **argv
  106691. ){
  106692. const char *zVal;
  106693. StrAccum *pAccum;
  106694. const char *zSep;
  106695. int nVal, nSep;
  106696. assert( argc==1 || argc==2 );
  106697. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  106698. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  106699. if( pAccum ){
  106700. sqlite3 *db = sqlite3_context_db_handle(context);
  106701. int firstTerm = pAccum->mxAlloc==0;
  106702. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  106703. if( !firstTerm ){
  106704. if( argc==2 ){
  106705. zSep = (char*)sqlite3_value_text(argv[1]);
  106706. nSep = sqlite3_value_bytes(argv[1]);
  106707. }else{
  106708. zSep = ",";
  106709. nSep = 1;
  106710. }
  106711. if( zSep ) sqlite3_str_append(pAccum, zSep, nSep);
  106712. }
  106713. zVal = (char*)sqlite3_value_text(argv[0]);
  106714. nVal = sqlite3_value_bytes(argv[0]);
  106715. if( zVal ) sqlite3_str_append(pAccum, zVal, nVal);
  106716. }
  106717. }
  106718. #ifndef SQLITE_OMIT_WINDOWFUNC
  106719. static void groupConcatInverse(
  106720. sqlite3_context *context,
  106721. int argc,
  106722. sqlite3_value **argv
  106723. ){
  106724. int n;
  106725. StrAccum *pAccum;
  106726. assert( argc==1 || argc==2 );
  106727. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  106728. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  106729. /* pAccum is always non-NULL since groupConcatStep() will have always
  106730. ** run frist to initialize it */
  106731. if( ALWAYS(pAccum) ){
  106732. n = sqlite3_value_bytes(argv[0]);
  106733. if( argc==2 ){
  106734. n += sqlite3_value_bytes(argv[1]);
  106735. }else{
  106736. n++;
  106737. }
  106738. if( n>=(int)pAccum->nChar ){
  106739. pAccum->nChar = 0;
  106740. }else{
  106741. pAccum->nChar -= n;
  106742. memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar);
  106743. }
  106744. if( pAccum->nChar==0 ) pAccum->mxAlloc = 0;
  106745. }
  106746. }
  106747. #else
  106748. # define groupConcatInverse 0
  106749. #endif /* SQLITE_OMIT_WINDOWFUNC */
  106750. static void groupConcatFinalize(sqlite3_context *context){
  106751. StrAccum *pAccum;
  106752. pAccum = sqlite3_aggregate_context(context, 0);
  106753. if( pAccum ){
  106754. if( pAccum->accError==SQLITE_TOOBIG ){
  106755. sqlite3_result_error_toobig(context);
  106756. }else if( pAccum->accError==SQLITE_NOMEM ){
  106757. sqlite3_result_error_nomem(context);
  106758. }else{
  106759. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  106760. sqlite3_free);
  106761. }
  106762. }
  106763. }
  106764. #ifndef SQLITE_OMIT_WINDOWFUNC
  106765. static void groupConcatValue(sqlite3_context *context){
  106766. sqlite3_str *pAccum;
  106767. pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0);
  106768. if( pAccum ){
  106769. if( pAccum->accError==SQLITE_TOOBIG ){
  106770. sqlite3_result_error_toobig(context);
  106771. }else if( pAccum->accError==SQLITE_NOMEM ){
  106772. sqlite3_result_error_nomem(context);
  106773. }else{
  106774. const char *zText = sqlite3_str_value(pAccum);
  106775. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  106776. }
  106777. }
  106778. }
  106779. #else
  106780. # define groupConcatValue 0
  106781. #endif /* SQLITE_OMIT_WINDOWFUNC */
  106782. /*
  106783. ** This routine does per-connection function registration. Most
  106784. ** of the built-in functions above are part of the global function set.
  106785. ** This routine only deals with those that are not global.
  106786. */
  106787. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
  106788. int rc = sqlite3_overload_function(db, "MATCH", 2);
  106789. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  106790. if( rc==SQLITE_NOMEM ){
  106791. sqlite3OomFault(db);
  106792. }
  106793. }
  106794. /*
  106795. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  106796. */
  106797. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  106798. FuncDef *pDef;
  106799. pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
  106800. if( ALWAYS(pDef) ){
  106801. pDef->funcFlags |= flagVal;
  106802. }
  106803. }
  106804. /*
  106805. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  106806. ** parameter determines whether or not the LIKE operator is case
  106807. ** sensitive. GLOB is always case sensitive.
  106808. */
  106809. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  106810. struct compareInfo *pInfo;
  106811. if( caseSensitive ){
  106812. pInfo = (struct compareInfo*)&likeInfoAlt;
  106813. }else{
  106814. pInfo = (struct compareInfo*)&likeInfoNorm;
  106815. }
  106816. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
  106817. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
  106818. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  106819. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0, 0, 0);
  106820. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  106821. setLikeOptFlag(db, "like",
  106822. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  106823. }
  106824. /*
  106825. ** pExpr points to an expression which implements a function. If
  106826. ** it is appropriate to apply the LIKE optimization to that function
  106827. ** then set aWc[0] through aWc[2] to the wildcard characters and the
  106828. ** escape character and then return TRUE. If the function is not a
  106829. ** LIKE-style function then return FALSE.
  106830. **
  106831. ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
  106832. ** operator if c is a string literal that is exactly one byte in length.
  106833. ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
  106834. ** no ESCAPE clause.
  106835. **
  106836. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  106837. ** the function (default for LIKE). If the function makes the distinction
  106838. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  106839. ** false.
  106840. */
  106841. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  106842. FuncDef *pDef;
  106843. int nExpr;
  106844. if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
  106845. return 0;
  106846. }
  106847. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  106848. nExpr = pExpr->x.pList->nExpr;
  106849. pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
  106850. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  106851. return 0;
  106852. }
  106853. if( nExpr<3 ){
  106854. aWc[3] = 0;
  106855. }else{
  106856. Expr *pEscape = pExpr->x.pList->a[2].pExpr;
  106857. char *zEscape;
  106858. if( pEscape->op!=TK_STRING ) return 0;
  106859. zEscape = pEscape->u.zToken;
  106860. if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
  106861. aWc[3] = zEscape[0];
  106862. }
  106863. /* The memcpy() statement assumes that the wildcard characters are
  106864. ** the first three statements in the compareInfo structure. The
  106865. ** asserts() that follow verify that assumption
  106866. */
  106867. memcpy(aWc, pDef->pUserData, 3);
  106868. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  106869. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  106870. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  106871. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  106872. return 1;
  106873. }
  106874. /*
  106875. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  106876. ** to the global function hash table. This occurs at start-time (as
  106877. ** a consequence of calling sqlite3_initialize()).
  106878. **
  106879. ** After this routine runs
  106880. */
  106881. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
  106882. /*
  106883. ** The following array holds FuncDef structures for all of the functions
  106884. ** defined in this file.
  106885. **
  106886. ** The array cannot be constant since changes are made to the
  106887. ** FuncDef.pHash elements at start-time. The elements of this array
  106888. ** are read-only after initialization is complete.
  106889. **
  106890. ** For peak efficiency, put the most frequently used function last.
  106891. */
  106892. static FuncDef aBuiltinFunc[] = {
  106893. #ifdef SQLITE_SOUNDEX
  106894. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  106895. #endif
  106896. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  106897. VFUNCTION(load_extension, 1, 0, 0, loadExt ),
  106898. VFUNCTION(load_extension, 2, 0, 0, loadExt ),
  106899. #endif
  106900. #if SQLITE_USER_AUTHENTICATION
  106901. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  106902. #endif
  106903. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  106904. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  106905. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  106906. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  106907. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  106908. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  106909. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  106910. #ifdef SQLITE_DEBUG
  106911. FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY),
  106912. #endif
  106913. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  106914. FUNCTION2(sqlite_offset, 1, 0, 0, noopFunc, SQLITE_FUNC_OFFSET|
  106915. SQLITE_FUNC_TYPEOF),
  106916. #endif
  106917. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  106918. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  106919. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  106920. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  106921. FUNCTION(trim, 1, 3, 0, trimFunc ),
  106922. FUNCTION(trim, 2, 3, 0, trimFunc ),
  106923. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  106924. FUNCTION(min, 0, 0, 1, 0 ),
  106925. WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
  106926. SQLITE_FUNC_MINMAX ),
  106927. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  106928. FUNCTION(max, 0, 1, 1, 0 ),
  106929. WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
  106930. SQLITE_FUNC_MINMAX ),
  106931. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  106932. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  106933. FUNCTION(instr, 2, 0, 0, instrFunc ),
  106934. FUNCTION(printf, -1, 0, 0, printfFunc ),
  106935. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  106936. FUNCTION(char, -1, 0, 0, charFunc ),
  106937. FUNCTION(abs, 1, 0, 0, absFunc ),
  106938. #ifndef SQLITE_OMIT_FLOATING_POINT
  106939. FUNCTION(round, 1, 0, 0, roundFunc ),
  106940. FUNCTION(round, 2, 0, 0, roundFunc ),
  106941. #endif
  106942. FUNCTION(upper, 1, 0, 0, upperFunc ),
  106943. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  106944. FUNCTION(hex, 1, 0, 0, hexFunc ),
  106945. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  106946. VFUNCTION(random, 0, 0, 0, randomFunc ),
  106947. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  106948. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  106949. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  106950. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  106951. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  106952. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  106953. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  106954. VFUNCTION(changes, 0, 0, 0, changes ),
  106955. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  106956. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  106957. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  106958. FUNCTION(substr, 2, 0, 0, substrFunc ),
  106959. FUNCTION(substr, 3, 0, 0, substrFunc ),
  106960. WAGGREGATE(sum, 1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),
  106961. WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
  106962. WAGGREGATE(avg, 1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
  106963. WAGGREGATE(count, 0,0,0, countStep,
  106964. countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT ),
  106965. WAGGREGATE(count, 1,0,0, countStep,
  106966. countFinalize, countFinalize, countInverse, 0 ),
  106967. WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep,
  106968. groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
  106969. WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
  106970. groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
  106971. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  106972. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  106973. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  106974. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  106975. #else
  106976. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  106977. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  106978. #endif
  106979. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  106980. FUNCTION(unknown, -1, 0, 0, unknownFunc ),
  106981. #endif
  106982. FUNCTION(coalesce, 1, 0, 0, 0 ),
  106983. FUNCTION(coalesce, 0, 0, 0, 0 ),
  106984. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  106985. };
  106986. #ifndef SQLITE_OMIT_ALTERTABLE
  106987. sqlite3AlterFunctions();
  106988. #endif
  106989. sqlite3WindowFunctions();
  106990. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  106991. sqlite3AnalyzeFunctions();
  106992. #endif
  106993. sqlite3RegisterDateTimeFunctions();
  106994. sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
  106995. #if 0 /* Enable to print out how the built-in functions are hashed */
  106996. {
  106997. int i;
  106998. FuncDef *p;
  106999. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  107000. printf("FUNC-HASH %02d:", i);
  107001. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
  107002. int n = sqlite3Strlen30(p->zName);
  107003. int h = p->zName[0] + n;
  107004. printf(" %s(%d)", p->zName, h);
  107005. }
  107006. printf("\n");
  107007. }
  107008. }
  107009. #endif
  107010. }
  107011. /************** End of func.c ************************************************/
  107012. /************** Begin file fkey.c ********************************************/
  107013. /*
  107014. **
  107015. ** The author disclaims copyright to this source code. In place of
  107016. ** a legal notice, here is a blessing:
  107017. **
  107018. ** May you do good and not evil.
  107019. ** May you find forgiveness for yourself and forgive others.
  107020. ** May you share freely, never taking more than you give.
  107021. **
  107022. *************************************************************************
  107023. ** This file contains code used by the compiler to add foreign key
  107024. ** support to compiled SQL statements.
  107025. */
  107026. /* #include "sqliteInt.h" */
  107027. #ifndef SQLITE_OMIT_FOREIGN_KEY
  107028. #ifndef SQLITE_OMIT_TRIGGER
  107029. /*
  107030. ** Deferred and Immediate FKs
  107031. ** --------------------------
  107032. **
  107033. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  107034. ** If an immediate foreign key constraint is violated,
  107035. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  107036. ** statement transaction rolled back. If a
  107037. ** deferred foreign key constraint is violated, no action is taken
  107038. ** immediately. However if the application attempts to commit the
  107039. ** transaction before fixing the constraint violation, the attempt fails.
  107040. **
  107041. ** Deferred constraints are implemented using a simple counter associated
  107042. ** with the database handle. The counter is set to zero each time a
  107043. ** database transaction is opened. Each time a statement is executed
  107044. ** that causes a foreign key violation, the counter is incremented. Each
  107045. ** time a statement is executed that removes an existing violation from
  107046. ** the database, the counter is decremented. When the transaction is
  107047. ** committed, the commit fails if the current value of the counter is
  107048. ** greater than zero. This scheme has two big drawbacks:
  107049. **
  107050. ** * When a commit fails due to a deferred foreign key constraint,
  107051. ** there is no way to tell which foreign constraint is not satisfied,
  107052. ** or which row it is not satisfied for.
  107053. **
  107054. ** * If the database contains foreign key violations when the
  107055. ** transaction is opened, this may cause the mechanism to malfunction.
  107056. **
  107057. ** Despite these problems, this approach is adopted as it seems simpler
  107058. ** than the alternatives.
  107059. **
  107060. ** INSERT operations:
  107061. **
  107062. ** I.1) For each FK for which the table is the child table, search
  107063. ** the parent table for a match. If none is found increment the
  107064. ** constraint counter.
  107065. **
  107066. ** I.2) For each FK for which the table is the parent table,
  107067. ** search the child table for rows that correspond to the new
  107068. ** row in the parent table. Decrement the counter for each row
  107069. ** found (as the constraint is now satisfied).
  107070. **
  107071. ** DELETE operations:
  107072. **
  107073. ** D.1) For each FK for which the table is the child table,
  107074. ** search the parent table for a row that corresponds to the
  107075. ** deleted row in the child table. If such a row is not found,
  107076. ** decrement the counter.
  107077. **
  107078. ** D.2) For each FK for which the table is the parent table, search
  107079. ** the child table for rows that correspond to the deleted row
  107080. ** in the parent table. For each found increment the counter.
  107081. **
  107082. ** UPDATE operations:
  107083. **
  107084. ** An UPDATE command requires that all 4 steps above are taken, but only
  107085. ** for FK constraints for which the affected columns are actually
  107086. ** modified (values must be compared at runtime).
  107087. **
  107088. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  107089. ** This simplifies the implementation a bit.
  107090. **
  107091. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  107092. ** resolution is considered to delete rows before the new row is inserted.
  107093. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  107094. ** is thrown, even if the FK constraint would be satisfied after the new
  107095. ** row is inserted.
  107096. **
  107097. ** Immediate constraints are usually handled similarly. The only difference
  107098. ** is that the counter used is stored as part of each individual statement
  107099. ** object (struct Vdbe). If, after the statement has run, its immediate
  107100. ** constraint counter is greater than zero,
  107101. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  107102. ** and the statement transaction is rolled back. An exception is an INSERT
  107103. ** statement that inserts a single row only (no triggers). In this case,
  107104. ** instead of using a counter, an exception is thrown immediately if the
  107105. ** INSERT violates a foreign key constraint. This is necessary as such
  107106. ** an INSERT does not open a statement transaction.
  107107. **
  107108. ** TODO: How should dropping a table be handled? How should renaming a
  107109. ** table be handled?
  107110. **
  107111. **
  107112. ** Query API Notes
  107113. ** ---------------
  107114. **
  107115. ** Before coding an UPDATE or DELETE row operation, the code-generator
  107116. ** for those two operations needs to know whether or not the operation
  107117. ** requires any FK processing and, if so, which columns of the original
  107118. ** row are required by the FK processing VDBE code (i.e. if FKs were
  107119. ** implemented using triggers, which of the old.* columns would be
  107120. ** accessed). No information is required by the code-generator before
  107121. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  107122. ** generation code to query for this information are:
  107123. **
  107124. ** sqlite3FkRequired() - Test to see if FK processing is required.
  107125. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  107126. **
  107127. **
  107128. ** Externally accessible module functions
  107129. ** --------------------------------------
  107130. **
  107131. ** sqlite3FkCheck() - Check for foreign key violations.
  107132. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  107133. ** sqlite3FkDelete() - Delete an FKey structure.
  107134. */
  107135. /*
  107136. ** VDBE Calling Convention
  107137. ** -----------------------
  107138. **
  107139. ** Example:
  107140. **
  107141. ** For the following INSERT statement:
  107142. **
  107143. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  107144. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  107145. **
  107146. ** Register (x): 2 (type integer)
  107147. ** Register (x+1): 1 (type integer)
  107148. ** Register (x+2): NULL (type NULL)
  107149. ** Register (x+3): 3.1 (type real)
  107150. */
  107151. /*
  107152. ** A foreign key constraint requires that the key columns in the parent
  107153. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  107154. ** Given that pParent is the parent table for foreign key constraint pFKey,
  107155. ** search the schema for a unique index on the parent key columns.
  107156. **
  107157. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  107158. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  107159. ** is set to point to the unique index.
  107160. **
  107161. ** If the parent key consists of a single column (the foreign key constraint
  107162. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  107163. ** Otherwise, it is set to point to an allocated array of size N, where
  107164. ** N is the number of columns in the parent key. The first element of the
  107165. ** array is the index of the child table column that is mapped by the FK
  107166. ** constraint to the parent table column stored in the left-most column
  107167. ** of index *ppIdx. The second element of the array is the index of the
  107168. ** child table column that corresponds to the second left-most column of
  107169. ** *ppIdx, and so on.
  107170. **
  107171. ** If the required index cannot be found, either because:
  107172. **
  107173. ** 1) The named parent key columns do not exist, or
  107174. **
  107175. ** 2) The named parent key columns do exist, but are not subject to a
  107176. ** UNIQUE or PRIMARY KEY constraint, or
  107177. **
  107178. ** 3) No parent key columns were provided explicitly as part of the
  107179. ** foreign key definition, and the parent table does not have a
  107180. ** PRIMARY KEY, or
  107181. **
  107182. ** 4) No parent key columns were provided explicitly as part of the
  107183. ** foreign key definition, and the PRIMARY KEY of the parent table
  107184. ** consists of a different number of columns to the child key in
  107185. ** the child table.
  107186. **
  107187. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  107188. ** into pParse. If an OOM error occurs, non-zero is returned and the
  107189. ** pParse->db->mallocFailed flag is set.
  107190. */
  107191. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  107192. Parse *pParse, /* Parse context to store any error in */
  107193. Table *pParent, /* Parent table of FK constraint pFKey */
  107194. FKey *pFKey, /* Foreign key to find index for */
  107195. Index **ppIdx, /* OUT: Unique index on parent table */
  107196. int **paiCol /* OUT: Map of index columns in pFKey */
  107197. ){
  107198. Index *pIdx = 0; /* Value to return via *ppIdx */
  107199. int *aiCol = 0; /* Value to return via *paiCol */
  107200. int nCol = pFKey->nCol; /* Number of columns in parent key */
  107201. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  107202. /* The caller is responsible for zeroing output parameters. */
  107203. assert( ppIdx && *ppIdx==0 );
  107204. assert( !paiCol || *paiCol==0 );
  107205. assert( pParse );
  107206. /* If this is a non-composite (single column) foreign key, check if it
  107207. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  107208. ** and *paiCol set to zero and return early.
  107209. **
  107210. ** Otherwise, for a composite foreign key (more than one column), allocate
  107211. ** space for the aiCol array (returned via output parameter *paiCol).
  107212. ** Non-composite foreign keys do not require the aiCol array.
  107213. */
  107214. if( nCol==1 ){
  107215. /* The FK maps to the IPK if any of the following are true:
  107216. **
  107217. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  107218. ** mapped to the primary key of table pParent, or
  107219. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  107220. ** PRIMARY KEY.
  107221. */
  107222. if( pParent->iPKey>=0 ){
  107223. if( !zKey ) return 0;
  107224. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  107225. }
  107226. }else if( paiCol ){
  107227. assert( nCol>1 );
  107228. aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
  107229. if( !aiCol ) return 1;
  107230. *paiCol = aiCol;
  107231. }
  107232. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  107233. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
  107234. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  107235. ** of columns. If each indexed column corresponds to a foreign key
  107236. ** column of pFKey, then this index is a winner. */
  107237. if( zKey==0 ){
  107238. /* If zKey is NULL, then this foreign key is implicitly mapped to
  107239. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  107240. ** identified by the test. */
  107241. if( IsPrimaryKeyIndex(pIdx) ){
  107242. if( aiCol ){
  107243. int i;
  107244. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  107245. }
  107246. break;
  107247. }
  107248. }else{
  107249. /* If zKey is non-NULL, then this foreign key was declared to
  107250. ** map to an explicit list of columns in table pParent. Check if this
  107251. ** index matches those columns. Also, check that the index uses
  107252. ** the default collation sequences for each column. */
  107253. int i, j;
  107254. for(i=0; i<nCol; i++){
  107255. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  107256. const char *zDfltColl; /* Def. collation for column */
  107257. char *zIdxCol; /* Name of indexed column */
  107258. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  107259. /* If the index uses a collation sequence that is different from
  107260. ** the default collation sequence for the column, this index is
  107261. ** unusable. Bail out early in this case. */
  107262. zDfltColl = pParent->aCol[iCol].zColl;
  107263. if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
  107264. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  107265. zIdxCol = pParent->aCol[iCol].zName;
  107266. for(j=0; j<nCol; j++){
  107267. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  107268. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  107269. break;
  107270. }
  107271. }
  107272. if( j==nCol ) break;
  107273. }
  107274. if( i==nCol ) break; /* pIdx is usable */
  107275. }
  107276. }
  107277. }
  107278. if( !pIdx ){
  107279. if( !pParse->disableTriggers ){
  107280. sqlite3ErrorMsg(pParse,
  107281. "foreign key mismatch - \"%w\" referencing \"%w\"",
  107282. pFKey->pFrom->zName, pFKey->zTo);
  107283. }
  107284. sqlite3DbFree(pParse->db, aiCol);
  107285. return 1;
  107286. }
  107287. *ppIdx = pIdx;
  107288. return 0;
  107289. }
  107290. /*
  107291. ** This function is called when a row is inserted into or deleted from the
  107292. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  107293. ** on the child table of pFKey, this function is invoked twice for each row
  107294. ** affected - once to "delete" the old row, and then again to "insert" the
  107295. ** new row.
  107296. **
  107297. ** Each time it is called, this function generates VDBE code to locate the
  107298. ** row in the parent table that corresponds to the row being inserted into
  107299. ** or deleted from the child table. If the parent row can be found, no
  107300. ** special action is taken. Otherwise, if the parent row can *not* be
  107301. ** found in the parent table:
  107302. **
  107303. ** Operation | FK type | Action taken
  107304. ** --------------------------------------------------------------------------
  107305. ** INSERT immediate Increment the "immediate constraint counter".
  107306. **
  107307. ** DELETE immediate Decrement the "immediate constraint counter".
  107308. **
  107309. ** INSERT deferred Increment the "deferred constraint counter".
  107310. **
  107311. ** DELETE deferred Decrement the "deferred constraint counter".
  107312. **
  107313. ** These operations are identified in the comment at the top of this file
  107314. ** (fkey.c) as "I.1" and "D.1".
  107315. */
  107316. static void fkLookupParent(
  107317. Parse *pParse, /* Parse context */
  107318. int iDb, /* Index of database housing pTab */
  107319. Table *pTab, /* Parent table of FK pFKey */
  107320. Index *pIdx, /* Unique index on parent key columns in pTab */
  107321. FKey *pFKey, /* Foreign key constraint */
  107322. int *aiCol, /* Map from parent key columns to child table columns */
  107323. int regData, /* Address of array containing child table row */
  107324. int nIncr, /* Increment constraint counter by this */
  107325. int isIgnore /* If true, pretend pTab contains all NULL values */
  107326. ){
  107327. int i; /* Iterator variable */
  107328. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  107329. int iCur = pParse->nTab - 1; /* Cursor number to use */
  107330. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  107331. sqlite3VdbeVerifyAbortable(v,
  107332. (!pFKey->isDeferred
  107333. && !(pParse->db->flags & SQLITE_DeferFKs)
  107334. && !pParse->pToplevel
  107335. && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
  107336. /* If nIncr is less than zero, then check at runtime if there are any
  107337. ** outstanding constraints to resolve. If there are not, there is no need
  107338. ** to check if deleting this row resolves any outstanding violations.
  107339. **
  107340. ** Check if any of the key columns in the child table row are NULL. If
  107341. ** any are, then the constraint is considered satisfied. No need to
  107342. ** search for a matching row in the parent table. */
  107343. if( nIncr<0 ){
  107344. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  107345. VdbeCoverage(v);
  107346. }
  107347. for(i=0; i<pFKey->nCol; i++){
  107348. int iReg = aiCol[i] + regData + 1;
  107349. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  107350. }
  107351. if( isIgnore==0 ){
  107352. if( pIdx==0 ){
  107353. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  107354. ** column of the parent table (table pTab). */
  107355. int iMustBeInt; /* Address of MustBeInt instruction */
  107356. int regTemp = sqlite3GetTempReg(pParse);
  107357. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  107358. ** apply the affinity of the parent key). If this fails, then there
  107359. ** is no matching parent key. Before using MustBeInt, make a copy of
  107360. ** the value. Otherwise, the value inserted into the child key column
  107361. ** will have INTEGER affinity applied to it, which may not be correct. */
  107362. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  107363. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  107364. VdbeCoverage(v);
  107365. /* If the parent table is the same as the child table, and we are about
  107366. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  107367. ** then check if the row being inserted matches itself. If so, do not
  107368. ** increment the constraint-counter. */
  107369. if( pTab==pFKey->pFrom && nIncr==1 ){
  107370. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  107371. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  107372. }
  107373. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  107374. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  107375. sqlite3VdbeGoto(v, iOk);
  107376. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  107377. sqlite3VdbeJumpHere(v, iMustBeInt);
  107378. sqlite3ReleaseTempReg(pParse, regTemp);
  107379. }else{
  107380. int nCol = pFKey->nCol;
  107381. int regTemp = sqlite3GetTempRange(pParse, nCol);
  107382. int regRec = sqlite3GetTempReg(pParse);
  107383. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  107384. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  107385. for(i=0; i<nCol; i++){
  107386. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  107387. }
  107388. /* If the parent table is the same as the child table, and we are about
  107389. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  107390. ** then check if the row being inserted matches itself. If so, do not
  107391. ** increment the constraint-counter.
  107392. **
  107393. ** If any of the parent-key values are NULL, then the row cannot match
  107394. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  107395. ** of the parent-key values are NULL (at this point it is known that
  107396. ** none of the child key values are).
  107397. */
  107398. if( pTab==pFKey->pFrom && nIncr==1 ){
  107399. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  107400. for(i=0; i<nCol; i++){
  107401. int iChild = aiCol[i]+1+regData;
  107402. int iParent = pIdx->aiColumn[i]+1+regData;
  107403. assert( pIdx->aiColumn[i]>=0 );
  107404. assert( aiCol[i]!=pTab->iPKey );
  107405. if( pIdx->aiColumn[i]==pTab->iPKey ){
  107406. /* The parent key is a composite key that includes the IPK column */
  107407. iParent = regData;
  107408. }
  107409. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  107410. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  107411. }
  107412. sqlite3VdbeGoto(v, iOk);
  107413. }
  107414. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  107415. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  107416. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  107417. sqlite3ReleaseTempReg(pParse, regRec);
  107418. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  107419. }
  107420. }
  107421. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  107422. && !pParse->pToplevel
  107423. && !pParse->isMultiWrite
  107424. ){
  107425. /* Special case: If this is an INSERT statement that will insert exactly
  107426. ** one row into the table, raise a constraint immediately instead of
  107427. ** incrementing a counter. This is necessary as the VM code is being
  107428. ** generated for will not open a statement transaction. */
  107429. assert( nIncr==1 );
  107430. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  107431. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  107432. }else{
  107433. if( nIncr>0 && pFKey->isDeferred==0 ){
  107434. sqlite3MayAbort(pParse);
  107435. }
  107436. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  107437. }
  107438. sqlite3VdbeResolveLabel(v, iOk);
  107439. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  107440. }
  107441. /*
  107442. ** Return an Expr object that refers to a memory register corresponding
  107443. ** to column iCol of table pTab.
  107444. **
  107445. ** regBase is the first of an array of register that contains the data
  107446. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  107447. ** column. regBase+2 holds the second column, and so forth.
  107448. */
  107449. static Expr *exprTableRegister(
  107450. Parse *pParse, /* Parsing and code generating context */
  107451. Table *pTab, /* The table whose content is at r[regBase]... */
  107452. int regBase, /* Contents of table pTab */
  107453. i16 iCol /* Which column of pTab is desired */
  107454. ){
  107455. Expr *pExpr;
  107456. Column *pCol;
  107457. const char *zColl;
  107458. sqlite3 *db = pParse->db;
  107459. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  107460. if( pExpr ){
  107461. if( iCol>=0 && iCol!=pTab->iPKey ){
  107462. pCol = &pTab->aCol[iCol];
  107463. pExpr->iTable = regBase + iCol + 1;
  107464. pExpr->affinity = pCol->affinity;
  107465. zColl = pCol->zColl;
  107466. if( zColl==0 ) zColl = db->pDfltColl->zName;
  107467. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  107468. }else{
  107469. pExpr->iTable = regBase;
  107470. pExpr->affinity = SQLITE_AFF_INTEGER;
  107471. }
  107472. }
  107473. return pExpr;
  107474. }
  107475. /*
  107476. ** Return an Expr object that refers to column iCol of table pTab which
  107477. ** has cursor iCur.
  107478. */
  107479. static Expr *exprTableColumn(
  107480. sqlite3 *db, /* The database connection */
  107481. Table *pTab, /* The table whose column is desired */
  107482. int iCursor, /* The open cursor on the table */
  107483. i16 iCol /* The column that is wanted */
  107484. ){
  107485. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  107486. if( pExpr ){
  107487. pExpr->y.pTab = pTab;
  107488. pExpr->iTable = iCursor;
  107489. pExpr->iColumn = iCol;
  107490. }
  107491. return pExpr;
  107492. }
  107493. /*
  107494. ** This function is called to generate code executed when a row is deleted
  107495. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  107496. ** deferred, when a row is inserted into the same table. When generating
  107497. ** code for an SQL UPDATE operation, this function may be called twice -
  107498. ** once to "delete" the old row and once to "insert" the new row.
  107499. **
  107500. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  107501. ** the number of FK violations in the db) or +1 when deleting one (as this
  107502. ** may increase the number of FK constraint problems).
  107503. **
  107504. ** The code generated by this function scans through the rows in the child
  107505. ** table that correspond to the parent table row being deleted or inserted.
  107506. ** For each child row found, one of the following actions is taken:
  107507. **
  107508. ** Operation | FK type | Action taken
  107509. ** --------------------------------------------------------------------------
  107510. ** DELETE immediate Increment the "immediate constraint counter".
  107511. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  107512. ** throw a "FOREIGN KEY constraint failed" exception.
  107513. **
  107514. ** INSERT immediate Decrement the "immediate constraint counter".
  107515. **
  107516. ** DELETE deferred Increment the "deferred constraint counter".
  107517. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  107518. ** throw a "FOREIGN KEY constraint failed" exception.
  107519. **
  107520. ** INSERT deferred Decrement the "deferred constraint counter".
  107521. **
  107522. ** These operations are identified in the comment at the top of this file
  107523. ** (fkey.c) as "I.2" and "D.2".
  107524. */
  107525. static void fkScanChildren(
  107526. Parse *pParse, /* Parse context */
  107527. SrcList *pSrc, /* The child table to be scanned */
  107528. Table *pTab, /* The parent table */
  107529. Index *pIdx, /* Index on parent covering the foreign key */
  107530. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  107531. int *aiCol, /* Map from pIdx cols to child table cols */
  107532. int regData, /* Parent row data starts here */
  107533. int nIncr /* Amount to increment deferred counter by */
  107534. ){
  107535. sqlite3 *db = pParse->db; /* Database handle */
  107536. int i; /* Iterator variable */
  107537. Expr *pWhere = 0; /* WHERE clause to scan with */
  107538. NameContext sNameContext; /* Context used to resolve WHERE clause */
  107539. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  107540. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  107541. Vdbe *v = sqlite3GetVdbe(pParse);
  107542. assert( pIdx==0 || pIdx->pTable==pTab );
  107543. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  107544. assert( pIdx!=0 || pFKey->nCol==1 );
  107545. assert( pIdx!=0 || HasRowid(pTab) );
  107546. if( nIncr<0 ){
  107547. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  107548. VdbeCoverage(v);
  107549. }
  107550. /* Create an Expr object representing an SQL expression like:
  107551. **
  107552. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  107553. **
  107554. ** The collation sequence used for the comparison should be that of
  107555. ** the parent key columns. The affinity of the parent key column should
  107556. ** be applied to each child key value before the comparison takes place.
  107557. */
  107558. for(i=0; i<pFKey->nCol; i++){
  107559. Expr *pLeft; /* Value from parent table row */
  107560. Expr *pRight; /* Column ref to child table */
  107561. Expr *pEq; /* Expression (pLeft = pRight) */
  107562. i16 iCol; /* Index of column in child table */
  107563. const char *zCol; /* Name of column in child table */
  107564. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  107565. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  107566. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  107567. assert( iCol>=0 );
  107568. zCol = pFKey->pFrom->aCol[iCol].zName;
  107569. pRight = sqlite3Expr(db, TK_ID, zCol);
  107570. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  107571. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  107572. }
  107573. /* If the child table is the same as the parent table, then add terms
  107574. ** to the WHERE clause that prevent this entry from being scanned.
  107575. ** The added WHERE clause terms are like this:
  107576. **
  107577. ** $current_rowid!=rowid
  107578. ** NOT( $current_a==a AND $current_b==b AND ... )
  107579. **
  107580. ** The first form is used for rowid tables. The second form is used
  107581. ** for WITHOUT ROWID tables. In the second form, the primary key is
  107582. ** (a,b,...)
  107583. */
  107584. if( pTab==pFKey->pFrom && nIncr>0 ){
  107585. Expr *pNe; /* Expression (pLeft != pRight) */
  107586. Expr *pLeft; /* Value from parent table row */
  107587. Expr *pRight; /* Column ref to child table */
  107588. if( HasRowid(pTab) ){
  107589. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  107590. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  107591. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
  107592. }else{
  107593. Expr *pEq, *pAll = 0;
  107594. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  107595. assert( pIdx!=0 );
  107596. for(i=0; i<pPk->nKeyCol; i++){
  107597. i16 iCol = pIdx->aiColumn[i];
  107598. assert( iCol>=0 );
  107599. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  107600. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  107601. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  107602. pAll = sqlite3ExprAnd(db, pAll, pEq);
  107603. }
  107604. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
  107605. }
  107606. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  107607. }
  107608. /* Resolve the references in the WHERE clause. */
  107609. memset(&sNameContext, 0, sizeof(NameContext));
  107610. sNameContext.pSrcList = pSrc;
  107611. sNameContext.pParse = pParse;
  107612. sqlite3ResolveExprNames(&sNameContext, pWhere);
  107613. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  107614. ** clause. For each row found, increment either the deferred or immediate
  107615. ** foreign key constraint counter. */
  107616. if( pParse->nErr==0 ){
  107617. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  107618. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  107619. if( pWInfo ){
  107620. sqlite3WhereEnd(pWInfo);
  107621. }
  107622. }
  107623. /* Clean up the WHERE clause constructed above. */
  107624. sqlite3ExprDelete(db, pWhere);
  107625. if( iFkIfZero ){
  107626. sqlite3VdbeJumpHere(v, iFkIfZero);
  107627. }
  107628. }
  107629. /*
  107630. ** This function returns a linked list of FKey objects (connected by
  107631. ** FKey.pNextTo) holding all children of table pTab. For example,
  107632. ** given the following schema:
  107633. **
  107634. ** CREATE TABLE t1(a PRIMARY KEY);
  107635. ** CREATE TABLE t2(b REFERENCES t1(a);
  107636. **
  107637. ** Calling this function with table "t1" as an argument returns a pointer
  107638. ** to the FKey structure representing the foreign key constraint on table
  107639. ** "t2". Calling this function with "t2" as the argument would return a
  107640. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  107641. ** table).
  107642. */
  107643. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  107644. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  107645. }
  107646. /*
  107647. ** The second argument is a Trigger structure allocated by the
  107648. ** fkActionTrigger() routine. This function deletes the Trigger structure
  107649. ** and all of its sub-components.
  107650. **
  107651. ** The Trigger structure or any of its sub-components may be allocated from
  107652. ** the lookaside buffer belonging to database handle dbMem.
  107653. */
  107654. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  107655. if( p ){
  107656. TriggerStep *pStep = p->step_list;
  107657. sqlite3ExprDelete(dbMem, pStep->pWhere);
  107658. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  107659. sqlite3SelectDelete(dbMem, pStep->pSelect);
  107660. sqlite3ExprDelete(dbMem, p->pWhen);
  107661. sqlite3DbFree(dbMem, p);
  107662. }
  107663. }
  107664. /*
  107665. ** This function is called to generate code that runs when table pTab is
  107666. ** being dropped from the database. The SrcList passed as the second argument
  107667. ** to this function contains a single entry guaranteed to resolve to
  107668. ** table pTab.
  107669. **
  107670. ** Normally, no code is required. However, if either
  107671. **
  107672. ** (a) The table is the parent table of a FK constraint, or
  107673. ** (b) The table is the child table of a deferred FK constraint and it is
  107674. ** determined at runtime that there are outstanding deferred FK
  107675. ** constraint violations in the database,
  107676. **
  107677. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  107678. ** the table from the database. Triggers are disabled while running this
  107679. ** DELETE, but foreign key actions are not.
  107680. */
  107681. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  107682. sqlite3 *db = pParse->db;
  107683. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) ){
  107684. int iSkip = 0;
  107685. Vdbe *v = sqlite3GetVdbe(pParse);
  107686. assert( v ); /* VDBE has already been allocated */
  107687. assert( pTab->pSelect==0 ); /* Not a view */
  107688. if( sqlite3FkReferences(pTab)==0 ){
  107689. /* Search for a deferred foreign key constraint for which this table
  107690. ** is the child table. If one cannot be found, return without
  107691. ** generating any VDBE code. If one can be found, then jump over
  107692. ** the entire DELETE if there are no outstanding deferred constraints
  107693. ** when this statement is run. */
  107694. FKey *p;
  107695. for(p=pTab->pFKey; p; p=p->pNextFrom){
  107696. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  107697. }
  107698. if( !p ) return;
  107699. iSkip = sqlite3VdbeMakeLabel(v);
  107700. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  107701. }
  107702. pParse->disableTriggers = 1;
  107703. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
  107704. pParse->disableTriggers = 0;
  107705. /* If the DELETE has generated immediate foreign key constraint
  107706. ** violations, halt the VDBE and return an error at this point, before
  107707. ** any modifications to the schema are made. This is because statement
  107708. ** transactions are not able to rollback schema changes.
  107709. **
  107710. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  107711. ** the statement transaction will not be rolled back even if FK
  107712. ** constraints are violated.
  107713. */
  107714. if( (db->flags & SQLITE_DeferFKs)==0 ){
  107715. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  107716. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  107717. VdbeCoverage(v);
  107718. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  107719. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  107720. }
  107721. if( iSkip ){
  107722. sqlite3VdbeResolveLabel(v, iSkip);
  107723. }
  107724. }
  107725. }
  107726. /*
  107727. ** The second argument points to an FKey object representing a foreign key
  107728. ** for which pTab is the child table. An UPDATE statement against pTab
  107729. ** is currently being processed. For each column of the table that is
  107730. ** actually updated, the corresponding element in the aChange[] array
  107731. ** is zero or greater (if a column is unmodified the corresponding element
  107732. ** is set to -1). If the rowid column is modified by the UPDATE statement
  107733. ** the bChngRowid argument is non-zero.
  107734. **
  107735. ** This function returns true if any of the columns that are part of the
  107736. ** child key for FK constraint *p are modified.
  107737. */
  107738. static int fkChildIsModified(
  107739. Table *pTab, /* Table being updated */
  107740. FKey *p, /* Foreign key for which pTab is the child */
  107741. int *aChange, /* Array indicating modified columns */
  107742. int bChngRowid /* True if rowid is modified by this update */
  107743. ){
  107744. int i;
  107745. for(i=0; i<p->nCol; i++){
  107746. int iChildKey = p->aCol[i].iFrom;
  107747. if( aChange[iChildKey]>=0 ) return 1;
  107748. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  107749. }
  107750. return 0;
  107751. }
  107752. /*
  107753. ** The second argument points to an FKey object representing a foreign key
  107754. ** for which pTab is the parent table. An UPDATE statement against pTab
  107755. ** is currently being processed. For each column of the table that is
  107756. ** actually updated, the corresponding element in the aChange[] array
  107757. ** is zero or greater (if a column is unmodified the corresponding element
  107758. ** is set to -1). If the rowid column is modified by the UPDATE statement
  107759. ** the bChngRowid argument is non-zero.
  107760. **
  107761. ** This function returns true if any of the columns that are part of the
  107762. ** parent key for FK constraint *p are modified.
  107763. */
  107764. static int fkParentIsModified(
  107765. Table *pTab,
  107766. FKey *p,
  107767. int *aChange,
  107768. int bChngRowid
  107769. ){
  107770. int i;
  107771. for(i=0; i<p->nCol; i++){
  107772. char *zKey = p->aCol[i].zCol;
  107773. int iKey;
  107774. for(iKey=0; iKey<pTab->nCol; iKey++){
  107775. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  107776. Column *pCol = &pTab->aCol[iKey];
  107777. if( zKey ){
  107778. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  107779. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  107780. return 1;
  107781. }
  107782. }
  107783. }
  107784. }
  107785. return 0;
  107786. }
  107787. /*
  107788. ** Return true if the parser passed as the first argument is being
  107789. ** used to code a trigger that is really a "SET NULL" action belonging
  107790. ** to trigger pFKey.
  107791. */
  107792. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  107793. Parse *pTop = sqlite3ParseToplevel(pParse);
  107794. if( pTop->pTriggerPrg ){
  107795. Trigger *p = pTop->pTriggerPrg->pTrigger;
  107796. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  107797. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  107798. ){
  107799. return 1;
  107800. }
  107801. }
  107802. return 0;
  107803. }
  107804. /*
  107805. ** This function is called when inserting, deleting or updating a row of
  107806. ** table pTab to generate VDBE code to perform foreign key constraint
  107807. ** processing for the operation.
  107808. **
  107809. ** For a DELETE operation, parameter regOld is passed the index of the
  107810. ** first register in an array of (pTab->nCol+1) registers containing the
  107811. ** rowid of the row being deleted, followed by each of the column values
  107812. ** of the row being deleted, from left to right. Parameter regNew is passed
  107813. ** zero in this case.
  107814. **
  107815. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  107816. ** first register of an array of (pTab->nCol+1) registers containing the new
  107817. ** row data.
  107818. **
  107819. ** For an UPDATE operation, this function is called twice. Once before
  107820. ** the original record is deleted from the table using the calling convention
  107821. ** described for DELETE. Then again after the original record is deleted
  107822. ** but before the new record is inserted using the INSERT convention.
  107823. */
  107824. SQLITE_PRIVATE void sqlite3FkCheck(
  107825. Parse *pParse, /* Parse context */
  107826. Table *pTab, /* Row is being deleted from this table */
  107827. int regOld, /* Previous row data is stored here */
  107828. int regNew, /* New row data is stored here */
  107829. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  107830. int bChngRowid /* True if rowid is UPDATEd */
  107831. ){
  107832. sqlite3 *db = pParse->db; /* Database handle */
  107833. FKey *pFKey; /* Used to iterate through FKs */
  107834. int iDb; /* Index of database containing pTab */
  107835. const char *zDb; /* Name of database containing pTab */
  107836. int isIgnoreErrors = pParse->disableTriggers;
  107837. /* Exactly one of regOld and regNew should be non-zero. */
  107838. assert( (regOld==0)!=(regNew==0) );
  107839. /* If foreign-keys are disabled, this function is a no-op. */
  107840. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  107841. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  107842. zDb = db->aDb[iDb].zDbSName;
  107843. /* Loop through all the foreign key constraints for which pTab is the
  107844. ** child table (the table that the foreign key definition is part of). */
  107845. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  107846. Table *pTo; /* Parent table of foreign key pFKey */
  107847. Index *pIdx = 0; /* Index on key columns in pTo */
  107848. int *aiFree = 0;
  107849. int *aiCol;
  107850. int iCol;
  107851. int i;
  107852. int bIgnore = 0;
  107853. if( aChange
  107854. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  107855. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  107856. ){
  107857. continue;
  107858. }
  107859. /* Find the parent table of this foreign key. Also find a unique index
  107860. ** on the parent key columns in the parent table. If either of these
  107861. ** schema items cannot be located, set an error in pParse and return
  107862. ** early. */
  107863. if( pParse->disableTriggers ){
  107864. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  107865. }else{
  107866. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  107867. }
  107868. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  107869. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  107870. if( !isIgnoreErrors || db->mallocFailed ) return;
  107871. if( pTo==0 ){
  107872. /* If isIgnoreErrors is true, then a table is being dropped. In this
  107873. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  107874. ** before actually dropping it in order to check FK constraints.
  107875. ** If the parent table of an FK constraint on the current table is
  107876. ** missing, behave as if it is empty. i.e. decrement the relevant
  107877. ** FK counter for each row of the current table with non-NULL keys.
  107878. */
  107879. Vdbe *v = sqlite3GetVdbe(pParse);
  107880. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  107881. for(i=0; i<pFKey->nCol; i++){
  107882. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  107883. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  107884. }
  107885. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  107886. }
  107887. continue;
  107888. }
  107889. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  107890. if( aiFree ){
  107891. aiCol = aiFree;
  107892. }else{
  107893. iCol = pFKey->aCol[0].iFrom;
  107894. aiCol = &iCol;
  107895. }
  107896. for(i=0; i<pFKey->nCol; i++){
  107897. if( aiCol[i]==pTab->iPKey ){
  107898. aiCol[i] = -1;
  107899. }
  107900. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  107901. #ifndef SQLITE_OMIT_AUTHORIZATION
  107902. /* Request permission to read the parent key columns. If the
  107903. ** authorization callback returns SQLITE_IGNORE, behave as if any
  107904. ** values read from the parent table are NULL. */
  107905. if( db->xAuth ){
  107906. int rcauth;
  107907. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  107908. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  107909. bIgnore = (rcauth==SQLITE_IGNORE);
  107910. }
  107911. #endif
  107912. }
  107913. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  107914. ** a cursor to use to search the unique index on the parent key columns
  107915. ** in the parent table. */
  107916. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  107917. pParse->nTab++;
  107918. if( regOld!=0 ){
  107919. /* A row is being removed from the child table. Search for the parent.
  107920. ** If the parent does not exist, removing the child row resolves an
  107921. ** outstanding foreign key constraint violation. */
  107922. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  107923. }
  107924. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  107925. /* A row is being added to the child table. If a parent row cannot
  107926. ** be found, adding the child row has violated the FK constraint.
  107927. **
  107928. ** If this operation is being performed as part of a trigger program
  107929. ** that is actually a "SET NULL" action belonging to this very
  107930. ** foreign key, then omit this scan altogether. As all child key
  107931. ** values are guaranteed to be NULL, it is not possible for adding
  107932. ** this row to cause an FK violation. */
  107933. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  107934. }
  107935. sqlite3DbFree(db, aiFree);
  107936. }
  107937. /* Loop through all the foreign key constraints that refer to this table.
  107938. ** (the "child" constraints) */
  107939. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  107940. Index *pIdx = 0; /* Foreign key index for pFKey */
  107941. SrcList *pSrc;
  107942. int *aiCol = 0;
  107943. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  107944. continue;
  107945. }
  107946. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  107947. && !pParse->pToplevel && !pParse->isMultiWrite
  107948. ){
  107949. assert( regOld==0 && regNew!=0 );
  107950. /* Inserting a single row into a parent table cannot cause (or fix)
  107951. ** an immediate foreign key violation. So do nothing in this case. */
  107952. continue;
  107953. }
  107954. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  107955. if( !isIgnoreErrors || db->mallocFailed ) return;
  107956. continue;
  107957. }
  107958. assert( aiCol || pFKey->nCol==1 );
  107959. /* Create a SrcList structure containing the child table. We need the
  107960. ** child table as a SrcList for sqlite3WhereBegin() */
  107961. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  107962. if( pSrc ){
  107963. struct SrcList_item *pItem = pSrc->a;
  107964. pItem->pTab = pFKey->pFrom;
  107965. pItem->zName = pFKey->pFrom->zName;
  107966. pItem->pTab->nTabRef++;
  107967. pItem->iCursor = pParse->nTab++;
  107968. if( regNew!=0 ){
  107969. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  107970. }
  107971. if( regOld!=0 ){
  107972. int eAction = pFKey->aAction[aChange!=0];
  107973. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  107974. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  107975. ** action applies, then any foreign key violations caused by
  107976. ** removing the parent key will be rectified by the action trigger.
  107977. ** So do not set the "may-abort" flag in this case.
  107978. **
  107979. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  107980. ** may-abort flag will eventually be set on this statement anyway
  107981. ** (when this function is called as part of processing the UPDATE
  107982. ** within the action trigger).
  107983. **
  107984. ** Note 2: At first glance it may seem like SQLite could simply omit
  107985. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  107986. ** applies. The trouble starts if the CASCADE or SET NULL action
  107987. ** trigger causes other triggers or action rules attached to the
  107988. ** child table to fire. In these cases the fk constraint counters
  107989. ** might be set incorrectly if any OP_FkCounter related scans are
  107990. ** omitted. */
  107991. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  107992. sqlite3MayAbort(pParse);
  107993. }
  107994. }
  107995. pItem->zName = 0;
  107996. sqlite3SrcListDelete(db, pSrc);
  107997. }
  107998. sqlite3DbFree(db, aiCol);
  107999. }
  108000. }
  108001. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  108002. /*
  108003. ** This function is called before generating code to update or delete a
  108004. ** row contained in table pTab.
  108005. */
  108006. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  108007. Parse *pParse, /* Parse context */
  108008. Table *pTab /* Table being modified */
  108009. ){
  108010. u32 mask = 0;
  108011. if( pParse->db->flags&SQLITE_ForeignKeys ){
  108012. FKey *p;
  108013. int i;
  108014. for(p=pTab->pFKey; p; p=p->pNextFrom){
  108015. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  108016. }
  108017. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  108018. Index *pIdx = 0;
  108019. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  108020. if( pIdx ){
  108021. for(i=0; i<pIdx->nKeyCol; i++){
  108022. assert( pIdx->aiColumn[i]>=0 );
  108023. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  108024. }
  108025. }
  108026. }
  108027. }
  108028. return mask;
  108029. }
  108030. /*
  108031. ** This function is called before generating code to update or delete a
  108032. ** row contained in table pTab. If the operation is a DELETE, then
  108033. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  108034. ** to an array of size N, where N is the number of columns in table pTab.
  108035. ** If the i'th column is not modified by the UPDATE, then the corresponding
  108036. ** entry in the aChange[] array is set to -1. If the column is modified,
  108037. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  108038. ** UPDATE statement modifies the rowid fields of the table.
  108039. **
  108040. ** If any foreign key processing will be required, this function returns
  108041. ** non-zero. If there is no foreign key related processing, this function
  108042. ** returns zero.
  108043. **
  108044. ** For an UPDATE, this function returns 2 if:
  108045. **
  108046. ** * There are any FKs for which pTab is the child and the parent table, or
  108047. ** * the UPDATE modifies one or more parent keys for which the action is
  108048. ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
  108049. **
  108050. ** Or, assuming some other foreign key processing is required, 1.
  108051. */
  108052. SQLITE_PRIVATE int sqlite3FkRequired(
  108053. Parse *pParse, /* Parse context */
  108054. Table *pTab, /* Table being modified */
  108055. int *aChange, /* Non-NULL for UPDATE operations */
  108056. int chngRowid /* True for UPDATE that affects rowid */
  108057. ){
  108058. int eRet = 0;
  108059. if( pParse->db->flags&SQLITE_ForeignKeys ){
  108060. if( !aChange ){
  108061. /* A DELETE operation. Foreign key processing is required if the
  108062. ** table in question is either the child or parent table for any
  108063. ** foreign key constraint. */
  108064. eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
  108065. }else{
  108066. /* This is an UPDATE. Foreign key processing is only required if the
  108067. ** operation modifies one or more child or parent key columns. */
  108068. FKey *p;
  108069. /* Check if any child key columns are being modified. */
  108070. for(p=pTab->pFKey; p; p=p->pNextFrom){
  108071. if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
  108072. if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
  108073. eRet = 1;
  108074. }
  108075. }
  108076. /* Check if any parent key columns are being modified. */
  108077. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  108078. if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
  108079. if( p->aAction[1]!=OE_None ) return 2;
  108080. eRet = 1;
  108081. }
  108082. }
  108083. }
  108084. }
  108085. return eRet;
  108086. }
  108087. /*
  108088. ** This function is called when an UPDATE or DELETE operation is being
  108089. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  108090. ** If the current operation is an UPDATE, then the pChanges parameter is
  108091. ** passed a pointer to the list of columns being modified. If it is a
  108092. ** DELETE, pChanges is passed a NULL pointer.
  108093. **
  108094. ** It returns a pointer to a Trigger structure containing a trigger
  108095. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  108096. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  108097. ** returned (these actions require no special handling by the triggers
  108098. ** sub-system, code for them is created by fkScanChildren()).
  108099. **
  108100. ** For example, if pFKey is the foreign key and pTab is table "p" in
  108101. ** the following schema:
  108102. **
  108103. ** CREATE TABLE p(pk PRIMARY KEY);
  108104. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  108105. **
  108106. ** then the returned trigger structure is equivalent to:
  108107. **
  108108. ** CREATE TRIGGER ... DELETE ON p BEGIN
  108109. ** DELETE FROM c WHERE ck = old.pk;
  108110. ** END;
  108111. **
  108112. ** The returned pointer is cached as part of the foreign key object. It
  108113. ** is eventually freed along with the rest of the foreign key object by
  108114. ** sqlite3FkDelete().
  108115. */
  108116. static Trigger *fkActionTrigger(
  108117. Parse *pParse, /* Parse context */
  108118. Table *pTab, /* Table being updated or deleted from */
  108119. FKey *pFKey, /* Foreign key to get action for */
  108120. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  108121. ){
  108122. sqlite3 *db = pParse->db; /* Database handle */
  108123. int action; /* One of OE_None, OE_Cascade etc. */
  108124. Trigger *pTrigger; /* Trigger definition to return */
  108125. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  108126. action = pFKey->aAction[iAction];
  108127. if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
  108128. return 0;
  108129. }
  108130. pTrigger = pFKey->apTrigger[iAction];
  108131. if( action!=OE_None && !pTrigger ){
  108132. char const *zFrom; /* Name of child table */
  108133. int nFrom; /* Length in bytes of zFrom */
  108134. Index *pIdx = 0; /* Parent key index for this FK */
  108135. int *aiCol = 0; /* child table cols -> parent key cols */
  108136. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  108137. Expr *pWhere = 0; /* WHERE clause of trigger step */
  108138. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  108139. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  108140. int i; /* Iterator variable */
  108141. Expr *pWhen = 0; /* WHEN clause for the trigger */
  108142. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  108143. assert( aiCol || pFKey->nCol==1 );
  108144. for(i=0; i<pFKey->nCol; i++){
  108145. Token tOld = { "old", 3 }; /* Literal "old" token */
  108146. Token tNew = { "new", 3 }; /* Literal "new" token */
  108147. Token tFromCol; /* Name of column in child table */
  108148. Token tToCol; /* Name of column in parent table */
  108149. int iFromCol; /* Idx of column in child table */
  108150. Expr *pEq; /* tFromCol = OLD.tToCol */
  108151. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  108152. assert( iFromCol>=0 );
  108153. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  108154. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  108155. sqlite3TokenInit(&tToCol,
  108156. pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
  108157. sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
  108158. /* Create the expression "OLD.zToCol = zFromCol". It is important
  108159. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  108160. ** that the affinity and collation sequence associated with the
  108161. ** parent table are used for the comparison. */
  108162. pEq = sqlite3PExpr(pParse, TK_EQ,
  108163. sqlite3PExpr(pParse, TK_DOT,
  108164. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  108165. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  108166. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  108167. );
  108168. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  108169. /* For ON UPDATE, construct the next term of the WHEN clause.
  108170. ** The final WHEN clause will be like this:
  108171. **
  108172. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  108173. */
  108174. if( pChanges ){
  108175. pEq = sqlite3PExpr(pParse, TK_IS,
  108176. sqlite3PExpr(pParse, TK_DOT,
  108177. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  108178. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  108179. sqlite3PExpr(pParse, TK_DOT,
  108180. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  108181. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
  108182. );
  108183. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  108184. }
  108185. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  108186. Expr *pNew;
  108187. if( action==OE_Cascade ){
  108188. pNew = sqlite3PExpr(pParse, TK_DOT,
  108189. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  108190. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
  108191. }else if( action==OE_SetDflt ){
  108192. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  108193. if( pDflt ){
  108194. pNew = sqlite3ExprDup(db, pDflt, 0);
  108195. }else{
  108196. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  108197. }
  108198. }else{
  108199. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  108200. }
  108201. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  108202. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  108203. }
  108204. }
  108205. sqlite3DbFree(db, aiCol);
  108206. zFrom = pFKey->pFrom->zName;
  108207. nFrom = sqlite3Strlen30(zFrom);
  108208. if( action==OE_Restrict ){
  108209. Token tFrom;
  108210. Expr *pRaise;
  108211. tFrom.z = zFrom;
  108212. tFrom.n = nFrom;
  108213. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  108214. if( pRaise ){
  108215. pRaise->affinity = OE_Abort;
  108216. }
  108217. pSelect = sqlite3SelectNew(pParse,
  108218. sqlite3ExprListAppend(pParse, 0, pRaise),
  108219. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  108220. pWhere,
  108221. 0, 0, 0, 0, 0
  108222. );
  108223. pWhere = 0;
  108224. }
  108225. /* Disable lookaside memory allocation */
  108226. db->lookaside.bDisable++;
  108227. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  108228. sizeof(Trigger) + /* struct Trigger */
  108229. sizeof(TriggerStep) + /* Single step in trigger program */
  108230. nFrom + 1 /* Space for pStep->zTarget */
  108231. );
  108232. if( pTrigger ){
  108233. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  108234. pStep->zTarget = (char *)&pStep[1];
  108235. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  108236. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  108237. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  108238. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  108239. if( pWhen ){
  108240. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
  108241. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  108242. }
  108243. }
  108244. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  108245. db->lookaside.bDisable--;
  108246. sqlite3ExprDelete(db, pWhere);
  108247. sqlite3ExprDelete(db, pWhen);
  108248. sqlite3ExprListDelete(db, pList);
  108249. sqlite3SelectDelete(db, pSelect);
  108250. if( db->mallocFailed==1 ){
  108251. fkTriggerDelete(db, pTrigger);
  108252. return 0;
  108253. }
  108254. assert( pStep!=0 );
  108255. switch( action ){
  108256. case OE_Restrict:
  108257. pStep->op = TK_SELECT;
  108258. break;
  108259. case OE_Cascade:
  108260. if( !pChanges ){
  108261. pStep->op = TK_DELETE;
  108262. break;
  108263. }
  108264. default:
  108265. pStep->op = TK_UPDATE;
  108266. }
  108267. pStep->pTrig = pTrigger;
  108268. pTrigger->pSchema = pTab->pSchema;
  108269. pTrigger->pTabSchema = pTab->pSchema;
  108270. pFKey->apTrigger[iAction] = pTrigger;
  108271. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  108272. }
  108273. return pTrigger;
  108274. }
  108275. /*
  108276. ** This function is called when deleting or updating a row to implement
  108277. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  108278. */
  108279. SQLITE_PRIVATE void sqlite3FkActions(
  108280. Parse *pParse, /* Parse context */
  108281. Table *pTab, /* Table being updated or deleted from */
  108282. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  108283. int regOld, /* Address of array containing old row */
  108284. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  108285. int bChngRowid /* True if rowid is UPDATEd */
  108286. ){
  108287. /* If foreign-key support is enabled, iterate through all FKs that
  108288. ** refer to table pTab. If there is an action associated with the FK
  108289. ** for this operation (either update or delete), invoke the associated
  108290. ** trigger sub-program. */
  108291. if( pParse->db->flags&SQLITE_ForeignKeys ){
  108292. FKey *pFKey; /* Iterator variable */
  108293. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  108294. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  108295. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  108296. if( pAct ){
  108297. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  108298. }
  108299. }
  108300. }
  108301. }
  108302. }
  108303. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  108304. /*
  108305. ** Free all memory associated with foreign key definitions attached to
  108306. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  108307. ** hash table.
  108308. */
  108309. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  108310. FKey *pFKey; /* Iterator variable */
  108311. FKey *pNext; /* Copy of pFKey->pNextFrom */
  108312. assert( db==0 || IsVirtual(pTab)
  108313. || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  108314. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  108315. /* Remove the FK from the fkeyHash hash table. */
  108316. if( !db || db->pnBytesFreed==0 ){
  108317. if( pFKey->pPrevTo ){
  108318. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  108319. }else{
  108320. void *p = (void *)pFKey->pNextTo;
  108321. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  108322. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  108323. }
  108324. if( pFKey->pNextTo ){
  108325. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  108326. }
  108327. }
  108328. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  108329. ** classified as either immediate or deferred.
  108330. */
  108331. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  108332. /* Delete any triggers created to implement actions for this FK. */
  108333. #ifndef SQLITE_OMIT_TRIGGER
  108334. fkTriggerDelete(db, pFKey->apTrigger[0]);
  108335. fkTriggerDelete(db, pFKey->apTrigger[1]);
  108336. #endif
  108337. pNext = pFKey->pNextFrom;
  108338. sqlite3DbFree(db, pFKey);
  108339. }
  108340. }
  108341. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  108342. /************** End of fkey.c ************************************************/
  108343. /************** Begin file insert.c ******************************************/
  108344. /*
  108345. ** 2001 September 15
  108346. **
  108347. ** The author disclaims copyright to this source code. In place of
  108348. ** a legal notice, here is a blessing:
  108349. **
  108350. ** May you do good and not evil.
  108351. ** May you find forgiveness for yourself and forgive others.
  108352. ** May you share freely, never taking more than you give.
  108353. **
  108354. *************************************************************************
  108355. ** This file contains C code routines that are called by the parser
  108356. ** to handle INSERT statements in SQLite.
  108357. */
  108358. /* #include "sqliteInt.h" */
  108359. /*
  108360. ** Generate code that will
  108361. **
  108362. ** (1) acquire a lock for table pTab then
  108363. ** (2) open pTab as cursor iCur.
  108364. **
  108365. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  108366. ** for that table that is actually opened.
  108367. */
  108368. SQLITE_PRIVATE void sqlite3OpenTable(
  108369. Parse *pParse, /* Generate code into this VDBE */
  108370. int iCur, /* The cursor number of the table */
  108371. int iDb, /* The database index in sqlite3.aDb[] */
  108372. Table *pTab, /* The table to be opened */
  108373. int opcode /* OP_OpenRead or OP_OpenWrite */
  108374. ){
  108375. Vdbe *v;
  108376. assert( !IsVirtual(pTab) );
  108377. v = sqlite3GetVdbe(pParse);
  108378. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  108379. sqlite3TableLock(pParse, iDb, pTab->tnum,
  108380. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  108381. if( HasRowid(pTab) ){
  108382. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  108383. VdbeComment((v, "%s", pTab->zName));
  108384. }else{
  108385. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  108386. assert( pPk!=0 );
  108387. assert( pPk->tnum==pTab->tnum );
  108388. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  108389. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  108390. VdbeComment((v, "%s", pTab->zName));
  108391. }
  108392. }
  108393. /*
  108394. ** Return a pointer to the column affinity string associated with index
  108395. ** pIdx. A column affinity string has one character for each column in
  108396. ** the table, according to the affinity of the column:
  108397. **
  108398. ** Character Column affinity
  108399. ** ------------------------------
  108400. ** 'A' BLOB
  108401. ** 'B' TEXT
  108402. ** 'C' NUMERIC
  108403. ** 'D' INTEGER
  108404. ** 'F' REAL
  108405. **
  108406. ** An extra 'D' is appended to the end of the string to cover the
  108407. ** rowid that appears as the last column in every index.
  108408. **
  108409. ** Memory for the buffer containing the column index affinity string
  108410. ** is managed along with the rest of the Index structure. It will be
  108411. ** released when sqlite3DeleteIndex() is called.
  108412. */
  108413. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  108414. if( !pIdx->zColAff ){
  108415. /* The first time a column affinity string for a particular index is
  108416. ** required, it is allocated and populated here. It is then stored as
  108417. ** a member of the Index structure for subsequent use.
  108418. **
  108419. ** The column affinity string will eventually be deleted by
  108420. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  108421. ** up.
  108422. */
  108423. int n;
  108424. Table *pTab = pIdx->pTable;
  108425. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  108426. if( !pIdx->zColAff ){
  108427. sqlite3OomFault(db);
  108428. return 0;
  108429. }
  108430. for(n=0; n<pIdx->nColumn; n++){
  108431. i16 x = pIdx->aiColumn[n];
  108432. if( x>=0 ){
  108433. pIdx->zColAff[n] = pTab->aCol[x].affinity;
  108434. }else if( x==XN_ROWID ){
  108435. pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
  108436. }else{
  108437. char aff;
  108438. assert( x==XN_EXPR );
  108439. assert( pIdx->aColExpr!=0 );
  108440. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  108441. if( aff==0 ) aff = SQLITE_AFF_BLOB;
  108442. pIdx->zColAff[n] = aff;
  108443. }
  108444. }
  108445. pIdx->zColAff[n] = 0;
  108446. }
  108447. return pIdx->zColAff;
  108448. }
  108449. /*
  108450. ** Compute the affinity string for table pTab, if it has not already been
  108451. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  108452. **
  108453. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  108454. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  108455. ** for register iReg and following. Or if affinities exists and iReg==0,
  108456. ** then just set the P4 operand of the previous opcode (which should be
  108457. ** an OP_MakeRecord) to the affinity string.
  108458. **
  108459. ** A column affinity string has one character per column:
  108460. **
  108461. ** Character Column affinity
  108462. ** ------------------------------
  108463. ** 'A' BLOB
  108464. ** 'B' TEXT
  108465. ** 'C' NUMERIC
  108466. ** 'D' INTEGER
  108467. ** 'E' REAL
  108468. */
  108469. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  108470. int i;
  108471. char *zColAff = pTab->zColAff;
  108472. if( zColAff==0 ){
  108473. sqlite3 *db = sqlite3VdbeDb(v);
  108474. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  108475. if( !zColAff ){
  108476. sqlite3OomFault(db);
  108477. return;
  108478. }
  108479. for(i=0; i<pTab->nCol; i++){
  108480. zColAff[i] = pTab->aCol[i].affinity;
  108481. }
  108482. do{
  108483. zColAff[i--] = 0;
  108484. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  108485. pTab->zColAff = zColAff;
  108486. }
  108487. assert( zColAff!=0 );
  108488. i = sqlite3Strlen30NN(zColAff);
  108489. if( i ){
  108490. if( iReg ){
  108491. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  108492. }else{
  108493. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  108494. }
  108495. }
  108496. }
  108497. /*
  108498. ** Return non-zero if the table pTab in database iDb or any of its indices
  108499. ** have been opened at any point in the VDBE program. This is used to see if
  108500. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  108501. ** run without using a temporary table for the results of the SELECT.
  108502. */
  108503. static int readsTable(Parse *p, int iDb, Table *pTab){
  108504. Vdbe *v = sqlite3GetVdbe(p);
  108505. int i;
  108506. int iEnd = sqlite3VdbeCurrentAddr(v);
  108507. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108508. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  108509. #endif
  108510. for(i=1; i<iEnd; i++){
  108511. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  108512. assert( pOp!=0 );
  108513. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  108514. Index *pIndex;
  108515. int tnum = pOp->p2;
  108516. if( tnum==pTab->tnum ){
  108517. return 1;
  108518. }
  108519. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  108520. if( tnum==pIndex->tnum ){
  108521. return 1;
  108522. }
  108523. }
  108524. }
  108525. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108526. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  108527. assert( pOp->p4.pVtab!=0 );
  108528. assert( pOp->p4type==P4_VTAB );
  108529. return 1;
  108530. }
  108531. #endif
  108532. }
  108533. return 0;
  108534. }
  108535. #ifndef SQLITE_OMIT_AUTOINCREMENT
  108536. /*
  108537. ** Locate or create an AutoincInfo structure associated with table pTab
  108538. ** which is in database iDb. Return the register number for the register
  108539. ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
  108540. ** table. (Also return zero when doing a VACUUM since we do not want to
  108541. ** update the AUTOINCREMENT counters during a VACUUM.)
  108542. **
  108543. ** There is at most one AutoincInfo structure per table even if the
  108544. ** same table is autoincremented multiple times due to inserts within
  108545. ** triggers. A new AutoincInfo structure is created if this is the
  108546. ** first use of table pTab. On 2nd and subsequent uses, the original
  108547. ** AutoincInfo structure is used.
  108548. **
  108549. ** Four consecutive registers are allocated:
  108550. **
  108551. ** (1) The name of the pTab table.
  108552. ** (2) The maximum ROWID of pTab.
  108553. ** (3) The rowid in sqlite_sequence of pTab
  108554. ** (4) The original value of the max ROWID in pTab, or NULL if none
  108555. **
  108556. ** The 2nd register is the one that is returned. That is all the
  108557. ** insert routine needs to know about.
  108558. */
  108559. static int autoIncBegin(
  108560. Parse *pParse, /* Parsing context */
  108561. int iDb, /* Index of the database holding pTab */
  108562. Table *pTab /* The table we are writing to */
  108563. ){
  108564. int memId = 0; /* Register holding maximum rowid */
  108565. assert( pParse->db->aDb[iDb].pSchema!=0 );
  108566. if( (pTab->tabFlags & TF_Autoincrement)!=0
  108567. && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
  108568. ){
  108569. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  108570. AutoincInfo *pInfo;
  108571. Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
  108572. /* Verify that the sqlite_sequence table exists and is an ordinary
  108573. ** rowid table with exactly two columns.
  108574. ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
  108575. if( pSeqTab==0
  108576. || !HasRowid(pSeqTab)
  108577. || IsVirtual(pSeqTab)
  108578. || pSeqTab->nCol!=2
  108579. ){
  108580. pParse->nErr++;
  108581. pParse->rc = SQLITE_CORRUPT_SEQUENCE;
  108582. return 0;
  108583. }
  108584. pInfo = pToplevel->pAinc;
  108585. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  108586. if( pInfo==0 ){
  108587. pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
  108588. if( pInfo==0 ) return 0;
  108589. pInfo->pNext = pToplevel->pAinc;
  108590. pToplevel->pAinc = pInfo;
  108591. pInfo->pTab = pTab;
  108592. pInfo->iDb = iDb;
  108593. pToplevel->nMem++; /* Register to hold name of table */
  108594. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  108595. pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
  108596. }
  108597. memId = pInfo->regCtr;
  108598. }
  108599. return memId;
  108600. }
  108601. /*
  108602. ** This routine generates code that will initialize all of the
  108603. ** register used by the autoincrement tracker.
  108604. */
  108605. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  108606. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  108607. sqlite3 *db = pParse->db; /* The database connection */
  108608. Db *pDb; /* Database only autoinc table */
  108609. int memId; /* Register holding max rowid */
  108610. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  108611. /* This routine is never called during trigger-generation. It is
  108612. ** only called from the top-level */
  108613. assert( pParse->pTriggerTab==0 );
  108614. assert( sqlite3IsToplevel(pParse) );
  108615. assert( v ); /* We failed long ago if this is not so */
  108616. for(p = pParse->pAinc; p; p = p->pNext){
  108617. static const int iLn = VDBE_OFFSET_LINENO(2);
  108618. static const VdbeOpList autoInc[] = {
  108619. /* 0 */ {OP_Null, 0, 0, 0},
  108620. /* 1 */ {OP_Rewind, 0, 10, 0},
  108621. /* 2 */ {OP_Column, 0, 0, 0},
  108622. /* 3 */ {OP_Ne, 0, 9, 0},
  108623. /* 4 */ {OP_Rowid, 0, 0, 0},
  108624. /* 5 */ {OP_Column, 0, 1, 0},
  108625. /* 6 */ {OP_AddImm, 0, 0, 0},
  108626. /* 7 */ {OP_Copy, 0, 0, 0},
  108627. /* 8 */ {OP_Goto, 0, 11, 0},
  108628. /* 9 */ {OP_Next, 0, 2, 0},
  108629. /* 10 */ {OP_Integer, 0, 0, 0},
  108630. /* 11 */ {OP_Close, 0, 0, 0}
  108631. };
  108632. VdbeOp *aOp;
  108633. pDb = &db->aDb[p->iDb];
  108634. memId = p->regCtr;
  108635. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  108636. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  108637. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  108638. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
  108639. if( aOp==0 ) break;
  108640. aOp[0].p2 = memId;
  108641. aOp[0].p3 = memId+2;
  108642. aOp[2].p3 = memId;
  108643. aOp[3].p1 = memId-1;
  108644. aOp[3].p3 = memId;
  108645. aOp[3].p5 = SQLITE_JUMPIFNULL;
  108646. aOp[4].p2 = memId+1;
  108647. aOp[5].p3 = memId;
  108648. aOp[6].p1 = memId;
  108649. aOp[7].p2 = memId+2;
  108650. aOp[7].p1 = memId;
  108651. aOp[10].p2 = memId;
  108652. }
  108653. }
  108654. /*
  108655. ** Update the maximum rowid for an autoincrement calculation.
  108656. **
  108657. ** This routine should be called when the regRowid register holds a
  108658. ** new rowid that is about to be inserted. If that new rowid is
  108659. ** larger than the maximum rowid in the memId memory cell, then the
  108660. ** memory cell is updated.
  108661. */
  108662. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  108663. if( memId>0 ){
  108664. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  108665. }
  108666. }
  108667. /*
  108668. ** This routine generates the code needed to write autoincrement
  108669. ** maximum rowid values back into the sqlite_sequence register.
  108670. ** Every statement that might do an INSERT into an autoincrement
  108671. ** table (either directly or through triggers) needs to call this
  108672. ** routine just before the "exit" code.
  108673. */
  108674. static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
  108675. AutoincInfo *p;
  108676. Vdbe *v = pParse->pVdbe;
  108677. sqlite3 *db = pParse->db;
  108678. assert( v );
  108679. for(p = pParse->pAinc; p; p = p->pNext){
  108680. static const int iLn = VDBE_OFFSET_LINENO(2);
  108681. static const VdbeOpList autoIncEnd[] = {
  108682. /* 0 */ {OP_NotNull, 0, 2, 0},
  108683. /* 1 */ {OP_NewRowid, 0, 0, 0},
  108684. /* 2 */ {OP_MakeRecord, 0, 2, 0},
  108685. /* 3 */ {OP_Insert, 0, 0, 0},
  108686. /* 4 */ {OP_Close, 0, 0, 0}
  108687. };
  108688. VdbeOp *aOp;
  108689. Db *pDb = &db->aDb[p->iDb];
  108690. int iRec;
  108691. int memId = p->regCtr;
  108692. iRec = sqlite3GetTempReg(pParse);
  108693. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  108694. sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
  108695. VdbeCoverage(v);
  108696. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  108697. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
  108698. if( aOp==0 ) break;
  108699. aOp[0].p1 = memId+1;
  108700. aOp[1].p2 = memId+1;
  108701. aOp[2].p1 = memId-1;
  108702. aOp[2].p3 = iRec;
  108703. aOp[3].p2 = iRec;
  108704. aOp[3].p3 = memId+1;
  108705. aOp[3].p5 = OPFLAG_APPEND;
  108706. sqlite3ReleaseTempReg(pParse, iRec);
  108707. }
  108708. }
  108709. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  108710. if( pParse->pAinc ) autoIncrementEnd(pParse);
  108711. }
  108712. #else
  108713. /*
  108714. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  108715. ** above are all no-ops
  108716. */
  108717. # define autoIncBegin(A,B,C) (0)
  108718. # define autoIncStep(A,B,C)
  108719. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  108720. /* Forward declaration */
  108721. static int xferOptimization(
  108722. Parse *pParse, /* Parser context */
  108723. Table *pDest, /* The table we are inserting into */
  108724. Select *pSelect, /* A SELECT statement to use as the data source */
  108725. int onError, /* How to handle constraint errors */
  108726. int iDbDest /* The database of pDest */
  108727. );
  108728. /*
  108729. ** This routine is called to handle SQL of the following forms:
  108730. **
  108731. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  108732. ** insert into TABLE (IDLIST) select
  108733. ** insert into TABLE (IDLIST) default values
  108734. **
  108735. ** The IDLIST following the table name is always optional. If omitted,
  108736. ** then a list of all (non-hidden) columns for the table is substituted.
  108737. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  108738. ** is omitted.
  108739. **
  108740. ** For the pSelect parameter holds the values to be inserted for the
  108741. ** first two forms shown above. A VALUES clause is really just short-hand
  108742. ** for a SELECT statement that omits the FROM clause and everything else
  108743. ** that follows. If the pSelect parameter is NULL, that means that the
  108744. ** DEFAULT VALUES form of the INSERT statement is intended.
  108745. **
  108746. ** The code generated follows one of four templates. For a simple
  108747. ** insert with data coming from a single-row VALUES clause, the code executes
  108748. ** once straight down through. Pseudo-code follows (we call this
  108749. ** the "1st template"):
  108750. **
  108751. ** open write cursor to <table> and its indices
  108752. ** put VALUES clause expressions into registers
  108753. ** write the resulting record into <table>
  108754. ** cleanup
  108755. **
  108756. ** The three remaining templates assume the statement is of the form
  108757. **
  108758. ** INSERT INTO <table> SELECT ...
  108759. **
  108760. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  108761. ** in other words if the SELECT pulls all columns from a single table
  108762. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  108763. ** if <table2> and <table1> are distinct tables but have identical
  108764. ** schemas, including all the same indices, then a special optimization
  108765. ** is invoked that copies raw records from <table2> over to <table1>.
  108766. ** See the xferOptimization() function for the implementation of this
  108767. ** template. This is the 2nd template.
  108768. **
  108769. ** open a write cursor to <table>
  108770. ** open read cursor on <table2>
  108771. ** transfer all records in <table2> over to <table>
  108772. ** close cursors
  108773. ** foreach index on <table>
  108774. ** open a write cursor on the <table> index
  108775. ** open a read cursor on the corresponding <table2> index
  108776. ** transfer all records from the read to the write cursors
  108777. ** close cursors
  108778. ** end foreach
  108779. **
  108780. ** The 3rd template is for when the second template does not apply
  108781. ** and the SELECT clause does not read from <table> at any time.
  108782. ** The generated code follows this template:
  108783. **
  108784. ** X <- A
  108785. ** goto B
  108786. ** A: setup for the SELECT
  108787. ** loop over the rows in the SELECT
  108788. ** load values into registers R..R+n
  108789. ** yield X
  108790. ** end loop
  108791. ** cleanup after the SELECT
  108792. ** end-coroutine X
  108793. ** B: open write cursor to <table> and its indices
  108794. ** C: yield X, at EOF goto D
  108795. ** insert the select result into <table> from R..R+n
  108796. ** goto C
  108797. ** D: cleanup
  108798. **
  108799. ** The 4th template is used if the insert statement takes its
  108800. ** values from a SELECT but the data is being inserted into a table
  108801. ** that is also read as part of the SELECT. In the third form,
  108802. ** we have to use an intermediate table to store the results of
  108803. ** the select. The template is like this:
  108804. **
  108805. ** X <- A
  108806. ** goto B
  108807. ** A: setup for the SELECT
  108808. ** loop over the tables in the SELECT
  108809. ** load value into register R..R+n
  108810. ** yield X
  108811. ** end loop
  108812. ** cleanup after the SELECT
  108813. ** end co-routine R
  108814. ** B: open temp table
  108815. ** L: yield X, at EOF goto M
  108816. ** insert row from R..R+n into temp table
  108817. ** goto L
  108818. ** M: open write cursor to <table> and its indices
  108819. ** rewind temp table
  108820. ** C: loop over rows of intermediate table
  108821. ** transfer values form intermediate table into <table>
  108822. ** end loop
  108823. ** D: cleanup
  108824. */
  108825. SQLITE_PRIVATE void sqlite3Insert(
  108826. Parse *pParse, /* Parser context */
  108827. SrcList *pTabList, /* Name of table into which we are inserting */
  108828. Select *pSelect, /* A SELECT statement to use as the data source */
  108829. IdList *pColumn, /* Column names corresponding to IDLIST. */
  108830. int onError, /* How to handle constraint errors */
  108831. Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
  108832. ){
  108833. sqlite3 *db; /* The main database structure */
  108834. Table *pTab; /* The table to insert into. aka TABLE */
  108835. int i, j; /* Loop counters */
  108836. Vdbe *v; /* Generate code into this virtual machine */
  108837. Index *pIdx; /* For looping over indices of the table */
  108838. int nColumn; /* Number of columns in the data */
  108839. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  108840. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  108841. int iIdxCur = 0; /* First index cursor */
  108842. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  108843. int endOfLoop; /* Label for the end of the insertion loop */
  108844. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  108845. int addrInsTop = 0; /* Jump to label "D" */
  108846. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  108847. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  108848. int iDb; /* Index of database holding TABLE */
  108849. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  108850. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  108851. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  108852. u8 bIdListInOrder; /* True if IDLIST is in table order */
  108853. ExprList *pList = 0; /* List of VALUES() to be inserted */
  108854. /* Register allocations */
  108855. int regFromSelect = 0;/* Base register for data coming from SELECT */
  108856. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  108857. int regRowCount = 0; /* Memory cell used for the row counter */
  108858. int regIns; /* Block of regs holding rowid+data being inserted */
  108859. int regRowid; /* registers holding insert rowid */
  108860. int regData; /* register holding first column to insert */
  108861. int *aRegIdx = 0; /* One register allocated to each index */
  108862. #ifndef SQLITE_OMIT_TRIGGER
  108863. int isView; /* True if attempting to insert into a view */
  108864. Trigger *pTrigger; /* List of triggers on pTab, if required */
  108865. int tmask; /* Mask of trigger times */
  108866. #endif
  108867. db = pParse->db;
  108868. if( pParse->nErr || db->mallocFailed ){
  108869. goto insert_cleanup;
  108870. }
  108871. dest.iSDParm = 0; /* Suppress a harmless compiler warning */
  108872. /* If the Select object is really just a simple VALUES() list with a
  108873. ** single row (the common case) then keep that one row of values
  108874. ** and discard the other (unused) parts of the pSelect object
  108875. */
  108876. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  108877. pList = pSelect->pEList;
  108878. pSelect->pEList = 0;
  108879. sqlite3SelectDelete(db, pSelect);
  108880. pSelect = 0;
  108881. }
  108882. /* Locate the table into which we will be inserting new information.
  108883. */
  108884. assert( pTabList->nSrc==1 );
  108885. pTab = sqlite3SrcListLookup(pParse, pTabList);
  108886. if( pTab==0 ){
  108887. goto insert_cleanup;
  108888. }
  108889. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  108890. assert( iDb<db->nDb );
  108891. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
  108892. db->aDb[iDb].zDbSName) ){
  108893. goto insert_cleanup;
  108894. }
  108895. withoutRowid = !HasRowid(pTab);
  108896. /* Figure out if we have any triggers and if the table being
  108897. ** inserted into is a view
  108898. */
  108899. #ifndef SQLITE_OMIT_TRIGGER
  108900. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  108901. isView = pTab->pSelect!=0;
  108902. #else
  108903. # define pTrigger 0
  108904. # define tmask 0
  108905. # define isView 0
  108906. #endif
  108907. #ifdef SQLITE_OMIT_VIEW
  108908. # undef isView
  108909. # define isView 0
  108910. #endif
  108911. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  108912. /* If pTab is really a view, make sure it has been initialized.
  108913. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  108914. */
  108915. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  108916. goto insert_cleanup;
  108917. }
  108918. /* Cannot insert into a read-only table.
  108919. */
  108920. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  108921. goto insert_cleanup;
  108922. }
  108923. /* Allocate a VDBE
  108924. */
  108925. v = sqlite3GetVdbe(pParse);
  108926. if( v==0 ) goto insert_cleanup;
  108927. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  108928. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  108929. #ifndef SQLITE_OMIT_XFER_OPT
  108930. /* If the statement is of the form
  108931. **
  108932. ** INSERT INTO <table1> SELECT * FROM <table2>;
  108933. **
  108934. ** Then special optimizations can be applied that make the transfer
  108935. ** very fast and which reduce fragmentation of indices.
  108936. **
  108937. ** This is the 2nd template.
  108938. */
  108939. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  108940. assert( !pTrigger );
  108941. assert( pList==0 );
  108942. goto insert_end;
  108943. }
  108944. #endif /* SQLITE_OMIT_XFER_OPT */
  108945. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  108946. ** sqlite_sequence table and store it in memory cell regAutoinc.
  108947. */
  108948. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  108949. /* Allocate registers for holding the rowid of the new row,
  108950. ** the content of the new row, and the assembled row record.
  108951. */
  108952. regRowid = regIns = pParse->nMem+1;
  108953. pParse->nMem += pTab->nCol + 1;
  108954. if( IsVirtual(pTab) ){
  108955. regRowid++;
  108956. pParse->nMem++;
  108957. }
  108958. regData = regRowid+1;
  108959. /* If the INSERT statement included an IDLIST term, then make sure
  108960. ** all elements of the IDLIST really are columns of the table and
  108961. ** remember the column indices.
  108962. **
  108963. ** If the table has an INTEGER PRIMARY KEY column and that column
  108964. ** is named in the IDLIST, then record in the ipkColumn variable
  108965. ** the index into IDLIST of the primary key column. ipkColumn is
  108966. ** the index of the primary key as it appears in IDLIST, not as
  108967. ** is appears in the original table. (The index of the INTEGER
  108968. ** PRIMARY KEY in the original table is pTab->iPKey.)
  108969. */
  108970. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  108971. if( pColumn ){
  108972. for(i=0; i<pColumn->nId; i++){
  108973. pColumn->a[i].idx = -1;
  108974. }
  108975. for(i=0; i<pColumn->nId; i++){
  108976. for(j=0; j<pTab->nCol; j++){
  108977. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  108978. pColumn->a[i].idx = j;
  108979. if( i!=j ) bIdListInOrder = 0;
  108980. if( j==pTab->iPKey ){
  108981. ipkColumn = i; assert( !withoutRowid );
  108982. }
  108983. break;
  108984. }
  108985. }
  108986. if( j>=pTab->nCol ){
  108987. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  108988. ipkColumn = i;
  108989. bIdListInOrder = 0;
  108990. }else{
  108991. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  108992. pTabList, 0, pColumn->a[i].zName);
  108993. pParse->checkSchema = 1;
  108994. goto insert_cleanup;
  108995. }
  108996. }
  108997. }
  108998. }
  108999. /* Figure out how many columns of data are supplied. If the data
  109000. ** is coming from a SELECT statement, then generate a co-routine that
  109001. ** produces a single row of the SELECT on each invocation. The
  109002. ** co-routine is the common header to the 3rd and 4th templates.
  109003. */
  109004. if( pSelect ){
  109005. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  109006. ** Generate a co-routine to run the SELECT. */
  109007. int regYield; /* Register holding co-routine entry-point */
  109008. int addrTop; /* Top of the co-routine */
  109009. int rc; /* Result code */
  109010. regYield = ++pParse->nMem;
  109011. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  109012. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  109013. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  109014. dest.iSdst = bIdListInOrder ? regData : 0;
  109015. dest.nSdst = pTab->nCol;
  109016. rc = sqlite3Select(pParse, pSelect, &dest);
  109017. regFromSelect = dest.iSdst;
  109018. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  109019. sqlite3VdbeEndCoroutine(v, regYield);
  109020. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  109021. assert( pSelect->pEList );
  109022. nColumn = pSelect->pEList->nExpr;
  109023. /* Set useTempTable to TRUE if the result of the SELECT statement
  109024. ** should be written into a temporary table (template 4). Set to
  109025. ** FALSE if each output row of the SELECT can be written directly into
  109026. ** the destination table (template 3).
  109027. **
  109028. ** A temp table must be used if the table being updated is also one
  109029. ** of the tables being read by the SELECT statement. Also use a
  109030. ** temp table in the case of row triggers.
  109031. */
  109032. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  109033. useTempTable = 1;
  109034. }
  109035. if( useTempTable ){
  109036. /* Invoke the coroutine to extract information from the SELECT
  109037. ** and add it to a transient table srcTab. The code generated
  109038. ** here is from the 4th template:
  109039. **
  109040. ** B: open temp table
  109041. ** L: yield X, goto M at EOF
  109042. ** insert row from R..R+n into temp table
  109043. ** goto L
  109044. ** M: ...
  109045. */
  109046. int regRec; /* Register to hold packed record */
  109047. int regTempRowid; /* Register to hold temp table ROWID */
  109048. int addrL; /* Label "L" */
  109049. srcTab = pParse->nTab++;
  109050. regRec = sqlite3GetTempReg(pParse);
  109051. regTempRowid = sqlite3GetTempReg(pParse);
  109052. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  109053. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  109054. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  109055. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  109056. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  109057. sqlite3VdbeGoto(v, addrL);
  109058. sqlite3VdbeJumpHere(v, addrL);
  109059. sqlite3ReleaseTempReg(pParse, regRec);
  109060. sqlite3ReleaseTempReg(pParse, regTempRowid);
  109061. }
  109062. }else{
  109063. /* This is the case if the data for the INSERT is coming from a
  109064. ** single-row VALUES clause
  109065. */
  109066. NameContext sNC;
  109067. memset(&sNC, 0, sizeof(sNC));
  109068. sNC.pParse = pParse;
  109069. srcTab = -1;
  109070. assert( useTempTable==0 );
  109071. if( pList ){
  109072. nColumn = pList->nExpr;
  109073. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  109074. goto insert_cleanup;
  109075. }
  109076. }else{
  109077. nColumn = 0;
  109078. }
  109079. }
  109080. /* If there is no IDLIST term but the table has an integer primary
  109081. ** key, the set the ipkColumn variable to the integer primary key
  109082. ** column index in the original table definition.
  109083. */
  109084. if( pColumn==0 && nColumn>0 ){
  109085. ipkColumn = pTab->iPKey;
  109086. }
  109087. /* Make sure the number of columns in the source data matches the number
  109088. ** of columns to be inserted into the table.
  109089. */
  109090. for(i=0; i<pTab->nCol; i++){
  109091. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  109092. }
  109093. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  109094. sqlite3ErrorMsg(pParse,
  109095. "table %S has %d columns but %d values were supplied",
  109096. pTabList, 0, pTab->nCol-nHidden, nColumn);
  109097. goto insert_cleanup;
  109098. }
  109099. if( pColumn!=0 && nColumn!=pColumn->nId ){
  109100. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  109101. goto insert_cleanup;
  109102. }
  109103. /* Initialize the count of rows to be inserted
  109104. */
  109105. if( (db->flags & SQLITE_CountRows)!=0
  109106. && !pParse->nested
  109107. && !pParse->pTriggerTab
  109108. ){
  109109. regRowCount = ++pParse->nMem;
  109110. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  109111. }
  109112. /* If this is not a view, open the table and and all indices */
  109113. if( !isView ){
  109114. int nIdx;
  109115. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
  109116. &iDataCur, &iIdxCur);
  109117. aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
  109118. if( aRegIdx==0 ){
  109119. goto insert_cleanup;
  109120. }
  109121. for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
  109122. assert( pIdx );
  109123. aRegIdx[i] = ++pParse->nMem;
  109124. pParse->nMem += pIdx->nColumn;
  109125. }
  109126. }
  109127. #ifndef SQLITE_OMIT_UPSERT
  109128. if( pUpsert ){
  109129. pTabList->a[0].iCursor = iDataCur;
  109130. pUpsert->pUpsertSrc = pTabList;
  109131. pUpsert->regData = regData;
  109132. pUpsert->iDataCur = iDataCur;
  109133. pUpsert->iIdxCur = iIdxCur;
  109134. if( pUpsert->pUpsertTarget ){
  109135. sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
  109136. }
  109137. }
  109138. #endif
  109139. /* This is the top of the main insertion loop */
  109140. if( useTempTable ){
  109141. /* This block codes the top of loop only. The complete loop is the
  109142. ** following pseudocode (template 4):
  109143. **
  109144. ** rewind temp table, if empty goto D
  109145. ** C: loop over rows of intermediate table
  109146. ** transfer values form intermediate table into <table>
  109147. ** end loop
  109148. ** D: ...
  109149. */
  109150. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  109151. addrCont = sqlite3VdbeCurrentAddr(v);
  109152. }else if( pSelect ){
  109153. /* This block codes the top of loop only. The complete loop is the
  109154. ** following pseudocode (template 3):
  109155. **
  109156. ** C: yield X, at EOF goto D
  109157. ** insert the select result into <table> from R..R+n
  109158. ** goto C
  109159. ** D: ...
  109160. */
  109161. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  109162. VdbeCoverage(v);
  109163. }
  109164. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  109165. */
  109166. endOfLoop = sqlite3VdbeMakeLabel(v);
  109167. if( tmask & TRIGGER_BEFORE ){
  109168. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  109169. /* build the NEW.* reference row. Note that if there is an INTEGER
  109170. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  109171. ** translated into a unique ID for the row. But on a BEFORE trigger,
  109172. ** we do not know what the unique ID will be (because the insert has
  109173. ** not happened yet) so we substitute a rowid of -1
  109174. */
  109175. if( ipkColumn<0 ){
  109176. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  109177. }else{
  109178. int addr1;
  109179. assert( !withoutRowid );
  109180. if( useTempTable ){
  109181. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  109182. }else{
  109183. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  109184. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  109185. }
  109186. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  109187. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  109188. sqlite3VdbeJumpHere(v, addr1);
  109189. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  109190. }
  109191. /* Cannot have triggers on a virtual table. If it were possible,
  109192. ** this block would have to account for hidden column.
  109193. */
  109194. assert( !IsVirtual(pTab) );
  109195. /* Create the new column data
  109196. */
  109197. for(i=j=0; i<pTab->nCol; i++){
  109198. if( pColumn ){
  109199. for(j=0; j<pColumn->nId; j++){
  109200. if( pColumn->a[j].idx==i ) break;
  109201. }
  109202. }
  109203. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
  109204. || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
  109205. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  109206. }else if( useTempTable ){
  109207. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  109208. }else{
  109209. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  109210. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  109211. }
  109212. if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
  109213. }
  109214. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  109215. ** do not attempt any conversions before assembling the record.
  109216. ** If this is a real table, attempt conversions as required by the
  109217. ** table column affinities.
  109218. */
  109219. if( !isView ){
  109220. sqlite3TableAffinity(v, pTab, regCols+1);
  109221. }
  109222. /* Fire BEFORE or INSTEAD OF triggers */
  109223. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  109224. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  109225. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  109226. }
  109227. /* Compute the content of the next row to insert into a range of
  109228. ** registers beginning at regIns.
  109229. */
  109230. if( !isView ){
  109231. if( IsVirtual(pTab) ){
  109232. /* The row that the VUpdate opcode will delete: none */
  109233. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  109234. }
  109235. if( ipkColumn>=0 ){
  109236. if( useTempTable ){
  109237. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  109238. }else if( pSelect ){
  109239. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  109240. }else{
  109241. VdbeOp *pOp;
  109242. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  109243. pOp = sqlite3VdbeGetOp(v, -1);
  109244. assert( pOp!=0 );
  109245. if( pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  109246. appendFlag = 1;
  109247. pOp->opcode = OP_NewRowid;
  109248. pOp->p1 = iDataCur;
  109249. pOp->p2 = regRowid;
  109250. pOp->p3 = regAutoinc;
  109251. }
  109252. }
  109253. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  109254. ** to generate a unique primary key value.
  109255. */
  109256. if( !appendFlag ){
  109257. int addr1;
  109258. if( !IsVirtual(pTab) ){
  109259. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  109260. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  109261. sqlite3VdbeJumpHere(v, addr1);
  109262. }else{
  109263. addr1 = sqlite3VdbeCurrentAddr(v);
  109264. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  109265. }
  109266. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  109267. }
  109268. }else if( IsVirtual(pTab) || withoutRowid ){
  109269. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  109270. }else{
  109271. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  109272. appendFlag = 1;
  109273. }
  109274. autoIncStep(pParse, regAutoinc, regRowid);
  109275. /* Compute data for all columns of the new entry, beginning
  109276. ** with the first column.
  109277. */
  109278. nHidden = 0;
  109279. for(i=0; i<pTab->nCol; i++){
  109280. int iRegStore = regRowid+1+i;
  109281. if( i==pTab->iPKey ){
  109282. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  109283. ** Whenever this column is read, the rowid will be substituted
  109284. ** in its place. Hence, fill this column with a NULL to avoid
  109285. ** taking up data space with information that will never be used.
  109286. ** As there may be shallow copies of this value, make it a soft-NULL */
  109287. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  109288. continue;
  109289. }
  109290. if( pColumn==0 ){
  109291. if( IsHiddenColumn(&pTab->aCol[i]) ){
  109292. j = -1;
  109293. nHidden++;
  109294. }else{
  109295. j = i - nHidden;
  109296. }
  109297. }else{
  109298. for(j=0; j<pColumn->nId; j++){
  109299. if( pColumn->a[j].idx==i ) break;
  109300. }
  109301. }
  109302. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  109303. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  109304. }else if( useTempTable ){
  109305. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  109306. }else if( pSelect ){
  109307. if( regFromSelect!=regData ){
  109308. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  109309. }
  109310. }else{
  109311. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  109312. }
  109313. }
  109314. /* Generate code to check constraints and generate index keys and
  109315. ** do the insertion.
  109316. */
  109317. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109318. if( IsVirtual(pTab) ){
  109319. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  109320. sqlite3VtabMakeWritable(pParse, pTab);
  109321. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  109322. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  109323. sqlite3MayAbort(pParse);
  109324. }else
  109325. #endif
  109326. {
  109327. int isReplace; /* Set to true if constraints may cause a replace */
  109328. int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
  109329. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  109330. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
  109331. );
  109332. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  109333. /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
  109334. ** constraints or (b) there are no triggers and this table is not a
  109335. ** parent table in a foreign key constraint. It is safe to set the
  109336. ** flag in the second case as if any REPLACE constraint is hit, an
  109337. ** OP_Delete or OP_IdxDelete instruction will be executed on each
  109338. ** cursor that is disturbed. And these instructions both clear the
  109339. ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
  109340. ** functionality. */
  109341. bUseSeek = (isReplace==0 || (pTrigger==0 &&
  109342. ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
  109343. ));
  109344. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  109345. regIns, aRegIdx, 0, appendFlag, bUseSeek
  109346. );
  109347. }
  109348. }
  109349. /* Update the count of rows that are inserted
  109350. */
  109351. if( regRowCount ){
  109352. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  109353. }
  109354. if( pTrigger ){
  109355. /* Code AFTER triggers */
  109356. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  109357. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  109358. }
  109359. /* The bottom of the main insertion loop, if the data source
  109360. ** is a SELECT statement.
  109361. */
  109362. sqlite3VdbeResolveLabel(v, endOfLoop);
  109363. if( useTempTable ){
  109364. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  109365. sqlite3VdbeJumpHere(v, addrInsTop);
  109366. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  109367. }else if( pSelect ){
  109368. sqlite3VdbeGoto(v, addrCont);
  109369. sqlite3VdbeJumpHere(v, addrInsTop);
  109370. }
  109371. insert_end:
  109372. /* Update the sqlite_sequence table by storing the content of the
  109373. ** maximum rowid counter values recorded while inserting into
  109374. ** autoincrement tables.
  109375. */
  109376. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  109377. sqlite3AutoincrementEnd(pParse);
  109378. }
  109379. /*
  109380. ** Return the number of rows inserted. If this routine is
  109381. ** generating code because of a call to sqlite3NestedParse(), do not
  109382. ** invoke the callback function.
  109383. */
  109384. if( regRowCount ){
  109385. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  109386. sqlite3VdbeSetNumCols(v, 1);
  109387. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  109388. }
  109389. insert_cleanup:
  109390. sqlite3SrcListDelete(db, pTabList);
  109391. sqlite3ExprListDelete(db, pList);
  109392. sqlite3UpsertDelete(db, pUpsert);
  109393. sqlite3SelectDelete(db, pSelect);
  109394. sqlite3IdListDelete(db, pColumn);
  109395. sqlite3DbFree(db, aRegIdx);
  109396. }
  109397. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  109398. ** they may interfere with compilation of other functions in this file
  109399. ** (or in another file, if this file becomes part of the amalgamation). */
  109400. #ifdef isView
  109401. #undef isView
  109402. #endif
  109403. #ifdef pTrigger
  109404. #undef pTrigger
  109405. #endif
  109406. #ifdef tmask
  109407. #undef tmask
  109408. #endif
  109409. /*
  109410. ** Meanings of bits in of pWalker->eCode for
  109411. ** sqlite3ExprReferencesUpdatedColumn()
  109412. */
  109413. #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
  109414. #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
  109415. /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
  109416. * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
  109417. ** expression node references any of the
  109418. ** columns that are being modifed by an UPDATE statement.
  109419. */
  109420. static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
  109421. if( pExpr->op==TK_COLUMN ){
  109422. assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
  109423. if( pExpr->iColumn>=0 ){
  109424. if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
  109425. pWalker->eCode |= CKCNSTRNT_COLUMN;
  109426. }
  109427. }else{
  109428. pWalker->eCode |= CKCNSTRNT_ROWID;
  109429. }
  109430. }
  109431. return WRC_Continue;
  109432. }
  109433. /*
  109434. ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
  109435. ** only columns that are modified by the UPDATE are those for which
  109436. ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
  109437. **
  109438. ** Return true if CHECK constraint pExpr uses any of the
  109439. ** changing columns (or the rowid if it is changing). In other words,
  109440. ** return true if this CHECK constraint must be validated for
  109441. ** the new row in the UPDATE statement.
  109442. **
  109443. ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
  109444. ** The operation of this routine is the same - return true if an only if
  109445. ** the expression uses one or more of columns identified by the second and
  109446. ** third arguments.
  109447. */
  109448. SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(
  109449. Expr *pExpr, /* The expression to be checked */
  109450. int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
  109451. int chngRowid /* True if UPDATE changes the rowid */
  109452. ){
  109453. Walker w;
  109454. memset(&w, 0, sizeof(w));
  109455. w.eCode = 0;
  109456. w.xExprCallback = checkConstraintExprNode;
  109457. w.u.aiCol = aiChng;
  109458. sqlite3WalkExpr(&w, pExpr);
  109459. if( !chngRowid ){
  109460. testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
  109461. w.eCode &= ~CKCNSTRNT_ROWID;
  109462. }
  109463. testcase( w.eCode==0 );
  109464. testcase( w.eCode==CKCNSTRNT_COLUMN );
  109465. testcase( w.eCode==CKCNSTRNT_ROWID );
  109466. testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
  109467. return w.eCode!=0;
  109468. }
  109469. /*
  109470. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  109471. ** on table pTab.
  109472. **
  109473. ** The regNewData parameter is the first register in a range that contains
  109474. ** the data to be inserted or the data after the update. There will be
  109475. ** pTab->nCol+1 registers in this range. The first register (the one
  109476. ** that regNewData points to) will contain the new rowid, or NULL in the
  109477. ** case of a WITHOUT ROWID table. The second register in the range will
  109478. ** contain the content of the first table column. The third register will
  109479. ** contain the content of the second table column. And so forth.
  109480. **
  109481. ** The regOldData parameter is similar to regNewData except that it contains
  109482. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  109483. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  109484. ** checking regOldData for zero.
  109485. **
  109486. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  109487. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  109488. ** might be modified by the UPDATE. If pkChng is false, then the key of
  109489. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  109490. **
  109491. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  109492. ** was explicitly specified as part of the INSERT statement. If pkChng
  109493. ** is zero, it means that the either rowid is computed automatically or
  109494. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  109495. ** pkChng will only be true if the INSERT statement provides an integer
  109496. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  109497. **
  109498. ** The code generated by this routine will store new index entries into
  109499. ** registers identified by aRegIdx[]. No index entry is created for
  109500. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  109501. ** the same as the order of indices on the linked list of indices
  109502. ** at pTab->pIndex.
  109503. **
  109504. ** The caller must have already opened writeable cursors on the main
  109505. ** table and all applicable indices (that is to say, all indices for which
  109506. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  109507. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  109508. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  109509. ** for the first index in the pTab->pIndex list. Cursors for other indices
  109510. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  109511. **
  109512. ** This routine also generates code to check constraints. NOT NULL,
  109513. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  109514. ** then the appropriate action is performed. There are five possible
  109515. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  109516. **
  109517. ** Constraint type Action What Happens
  109518. ** --------------- ---------- ----------------------------------------
  109519. ** any ROLLBACK The current transaction is rolled back and
  109520. ** sqlite3_step() returns immediately with a
  109521. ** return code of SQLITE_CONSTRAINT.
  109522. **
  109523. ** any ABORT Back out changes from the current command
  109524. ** only (do not do a complete rollback) then
  109525. ** cause sqlite3_step() to return immediately
  109526. ** with SQLITE_CONSTRAINT.
  109527. **
  109528. ** any FAIL Sqlite3_step() returns immediately with a
  109529. ** return code of SQLITE_CONSTRAINT. The
  109530. ** transaction is not rolled back and any
  109531. ** changes to prior rows are retained.
  109532. **
  109533. ** any IGNORE The attempt in insert or update the current
  109534. ** row is skipped, without throwing an error.
  109535. ** Processing continues with the next row.
  109536. ** (There is an immediate jump to ignoreDest.)
  109537. **
  109538. ** NOT NULL REPLACE The NULL value is replace by the default
  109539. ** value for that column. If the default value
  109540. ** is NULL, the action is the same as ABORT.
  109541. **
  109542. ** UNIQUE REPLACE The other row that conflicts with the row
  109543. ** being inserted is removed.
  109544. **
  109545. ** CHECK REPLACE Illegal. The results in an exception.
  109546. **
  109547. ** Which action to take is determined by the overrideError parameter.
  109548. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  109549. ** is used. Or if pParse->onError==OE_Default then the onError value
  109550. ** for the constraint is used.
  109551. */
  109552. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  109553. Parse *pParse, /* The parser context */
  109554. Table *pTab, /* The table being inserted or updated */
  109555. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  109556. int iDataCur, /* Canonical data cursor (main table or PK index) */
  109557. int iIdxCur, /* First index cursor */
  109558. int regNewData, /* First register in a range holding values to insert */
  109559. int regOldData, /* Previous content. 0 for INSERTs */
  109560. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  109561. u8 overrideError, /* Override onError to this if not OE_Default */
  109562. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  109563. int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
  109564. int *aiChng, /* column i is unchanged if aiChng[i]<0 */
  109565. Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
  109566. ){
  109567. Vdbe *v; /* VDBE under constrution */
  109568. Index *pIdx; /* Pointer to one of the indices */
  109569. Index *pPk = 0; /* The PRIMARY KEY index */
  109570. sqlite3 *db; /* Database connection */
  109571. int i; /* loop counter */
  109572. int ix; /* Index loop counter */
  109573. int nCol; /* Number of columns */
  109574. int onError; /* Conflict resolution strategy */
  109575. int addr1; /* Address of jump instruction */
  109576. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  109577. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  109578. Index *pUpIdx = 0; /* Index to which to apply the upsert */
  109579. u8 isUpdate; /* True if this is an UPDATE operation */
  109580. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  109581. int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */
  109582. int upsertJump = 0; /* Address of Goto that jumps into upsert subroutine */
  109583. int ipkTop = 0; /* Top of the IPK uniqueness check */
  109584. int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
  109585. isUpdate = regOldData!=0;
  109586. db = pParse->db;
  109587. v = sqlite3GetVdbe(pParse);
  109588. assert( v!=0 );
  109589. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  109590. nCol = pTab->nCol;
  109591. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  109592. ** normal rowid tables. nPkField is the number of key fields in the
  109593. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  109594. ** number of fields in the true primary key of the table. */
  109595. if( HasRowid(pTab) ){
  109596. pPk = 0;
  109597. nPkField = 1;
  109598. }else{
  109599. pPk = sqlite3PrimaryKeyIndex(pTab);
  109600. nPkField = pPk->nKeyCol;
  109601. }
  109602. /* Record that this module has started */
  109603. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  109604. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  109605. /* Test all NOT NULL constraints.
  109606. */
  109607. for(i=0; i<nCol; i++){
  109608. if( i==pTab->iPKey ){
  109609. continue; /* ROWID is never NULL */
  109610. }
  109611. if( aiChng && aiChng[i]<0 ){
  109612. /* Don't bother checking for NOT NULL on columns that do not change */
  109613. continue;
  109614. }
  109615. onError = pTab->aCol[i].notNull;
  109616. if( onError==OE_None ) continue; /* This column is allowed to be NULL */
  109617. if( overrideError!=OE_Default ){
  109618. onError = overrideError;
  109619. }else if( onError==OE_Default ){
  109620. onError = OE_Abort;
  109621. }
  109622. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  109623. onError = OE_Abort;
  109624. }
  109625. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  109626. || onError==OE_Ignore || onError==OE_Replace );
  109627. switch( onError ){
  109628. case OE_Abort:
  109629. sqlite3MayAbort(pParse);
  109630. /* Fall through */
  109631. case OE_Rollback:
  109632. case OE_Fail: {
  109633. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  109634. pTab->aCol[i].zName);
  109635. sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  109636. regNewData+1+i);
  109637. sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
  109638. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  109639. VdbeCoverage(v);
  109640. break;
  109641. }
  109642. case OE_Ignore: {
  109643. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  109644. VdbeCoverage(v);
  109645. break;
  109646. }
  109647. default: {
  109648. assert( onError==OE_Replace );
  109649. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
  109650. VdbeCoverage(v);
  109651. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  109652. sqlite3VdbeJumpHere(v, addr1);
  109653. break;
  109654. }
  109655. }
  109656. }
  109657. /* Test all CHECK constraints
  109658. */
  109659. #ifndef SQLITE_OMIT_CHECK
  109660. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  109661. ExprList *pCheck = pTab->pCheck;
  109662. pParse->iSelfTab = -(regNewData+1);
  109663. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  109664. for(i=0; i<pCheck->nExpr; i++){
  109665. int allOk;
  109666. Expr *pExpr = pCheck->a[i].pExpr;
  109667. if( aiChng
  109668. && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
  109669. ){
  109670. /* The check constraints do not reference any of the columns being
  109671. ** updated so there is no point it verifying the check constraint */
  109672. continue;
  109673. }
  109674. allOk = sqlite3VdbeMakeLabel(v);
  109675. sqlite3VdbeVerifyAbortable(v, onError);
  109676. sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
  109677. if( onError==OE_Ignore ){
  109678. sqlite3VdbeGoto(v, ignoreDest);
  109679. }else{
  109680. char *zName = pCheck->a[i].zName;
  109681. if( zName==0 ) zName = pTab->zName;
  109682. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  109683. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  109684. onError, zName, P4_TRANSIENT,
  109685. P5_ConstraintCheck);
  109686. }
  109687. sqlite3VdbeResolveLabel(v, allOk);
  109688. }
  109689. pParse->iSelfTab = 0;
  109690. }
  109691. #endif /* !defined(SQLITE_OMIT_CHECK) */
  109692. /* UNIQUE and PRIMARY KEY constraints should be handled in the following
  109693. ** order:
  109694. **
  109695. ** (1) OE_Update
  109696. ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
  109697. ** (3) OE_Replace
  109698. **
  109699. ** OE_Fail and OE_Ignore must happen before any changes are made.
  109700. ** OE_Update guarantees that only a single row will change, so it
  109701. ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
  109702. ** could happen in any order, but they are grouped up front for
  109703. ** convenience.
  109704. **
  109705. ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
  109706. ** The order of constraints used to have OE_Update as (2) and OE_Abort
  109707. ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
  109708. ** constraint before any others, so it had to be moved.
  109709. **
  109710. ** Constraint checking code is generated in this order:
  109711. ** (A) The rowid constraint
  109712. ** (B) Unique index constraints that do not have OE_Replace as their
  109713. ** default conflict resolution strategy
  109714. ** (C) Unique index that do use OE_Replace by default.
  109715. **
  109716. ** The ordering of (2) and (3) is accomplished by making sure the linked
  109717. ** list of indexes attached to a table puts all OE_Replace indexes last
  109718. ** in the list. See sqlite3CreateIndex() for where that happens.
  109719. */
  109720. if( pUpsert ){
  109721. if( pUpsert->pUpsertTarget==0 ){
  109722. /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
  109723. ** Make all unique constraint resolution be OE_Ignore */
  109724. assert( pUpsert->pUpsertSet==0 );
  109725. overrideError = OE_Ignore;
  109726. pUpsert = 0;
  109727. }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
  109728. /* If the constraint-target uniqueness check must be run first.
  109729. ** Jump to that uniqueness check now */
  109730. upsertJump = sqlite3VdbeAddOp0(v, OP_Goto);
  109731. VdbeComment((v, "UPSERT constraint goes first"));
  109732. }
  109733. }
  109734. /* If rowid is changing, make sure the new rowid does not previously
  109735. ** exist in the table.
  109736. */
  109737. if( pkChng && pPk==0 ){
  109738. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  109739. /* Figure out what action to take in case of a rowid collision */
  109740. onError = pTab->keyConf;
  109741. if( overrideError!=OE_Default ){
  109742. onError = overrideError;
  109743. }else if( onError==OE_Default ){
  109744. onError = OE_Abort;
  109745. }
  109746. /* figure out whether or not upsert applies in this case */
  109747. if( pUpsert && pUpsert->pUpsertIdx==0 ){
  109748. if( pUpsert->pUpsertSet==0 ){
  109749. onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
  109750. }else{
  109751. onError = OE_Update; /* DO UPDATE */
  109752. }
  109753. }
  109754. /* If the response to a rowid conflict is REPLACE but the response
  109755. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  109756. ** to defer the running of the rowid conflict checking until after
  109757. ** the UNIQUE constraints have run.
  109758. */
  109759. if( onError==OE_Replace /* IPK rule is REPLACE */
  109760. && onError!=overrideError /* Rules for other contraints are different */
  109761. && pTab->pIndex /* There exist other constraints */
  109762. ){
  109763. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
  109764. VdbeComment((v, "defer IPK REPLACE until last"));
  109765. }
  109766. if( isUpdate ){
  109767. /* pkChng!=0 does not mean that the rowid has changed, only that
  109768. ** it might have changed. Skip the conflict logic below if the rowid
  109769. ** is unchanged. */
  109770. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  109771. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  109772. VdbeCoverage(v);
  109773. }
  109774. /* Check to see if the new rowid already exists in the table. Skip
  109775. ** the following conflict logic if it does not. */
  109776. VdbeNoopComment((v, "uniqueness check for ROWID"));
  109777. sqlite3VdbeVerifyAbortable(v, onError);
  109778. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  109779. VdbeCoverage(v);
  109780. switch( onError ){
  109781. default: {
  109782. onError = OE_Abort;
  109783. /* Fall thru into the next case */
  109784. }
  109785. case OE_Rollback:
  109786. case OE_Abort:
  109787. case OE_Fail: {
  109788. testcase( onError==OE_Rollback );
  109789. testcase( onError==OE_Abort );
  109790. testcase( onError==OE_Fail );
  109791. sqlite3RowidConstraint(pParse, onError, pTab);
  109792. break;
  109793. }
  109794. case OE_Replace: {
  109795. /* If there are DELETE triggers on this table and the
  109796. ** recursive-triggers flag is set, call GenerateRowDelete() to
  109797. ** remove the conflicting row from the table. This will fire
  109798. ** the triggers and remove both the table and index b-tree entries.
  109799. **
  109800. ** Otherwise, if there are no triggers or the recursive-triggers
  109801. ** flag is not set, but the table has one or more indexes, call
  109802. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  109803. ** only. The table b-tree entry will be replaced by the new entry
  109804. ** when it is inserted.
  109805. **
  109806. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  109807. ** also invoke MultiWrite() to indicate that this VDBE may require
  109808. ** statement rollback (if the statement is aborted after the delete
  109809. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  109810. ** but being more selective here allows statements like:
  109811. **
  109812. ** REPLACE INTO t(rowid) VALUES($newrowid)
  109813. **
  109814. ** to run without a statement journal if there are no indexes on the
  109815. ** table.
  109816. */
  109817. Trigger *pTrigger = 0;
  109818. if( db->flags&SQLITE_RecTriggers ){
  109819. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  109820. }
  109821. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  109822. sqlite3MultiWrite(pParse);
  109823. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  109824. regNewData, 1, 0, OE_Replace, 1, -1);
  109825. }else{
  109826. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  109827. assert( HasRowid(pTab) );
  109828. /* This OP_Delete opcode fires the pre-update-hook only. It does
  109829. ** not modify the b-tree. It is more efficient to let the coming
  109830. ** OP_Insert replace the existing entry than it is to delete the
  109831. ** existing entry and then insert a new one. */
  109832. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
  109833. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  109834. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  109835. if( pTab->pIndex ){
  109836. sqlite3MultiWrite(pParse);
  109837. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  109838. }
  109839. }
  109840. seenReplace = 1;
  109841. break;
  109842. }
  109843. #ifndef SQLITE_OMIT_UPSERT
  109844. case OE_Update: {
  109845. sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
  109846. /* Fall through */
  109847. }
  109848. #endif
  109849. case OE_Ignore: {
  109850. testcase( onError==OE_Ignore );
  109851. sqlite3VdbeGoto(v, ignoreDest);
  109852. break;
  109853. }
  109854. }
  109855. sqlite3VdbeResolveLabel(v, addrRowidOk);
  109856. if( ipkTop ){
  109857. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  109858. sqlite3VdbeJumpHere(v, ipkTop-1);
  109859. }
  109860. }
  109861. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  109862. ** index and making sure that duplicate entries do not already exist.
  109863. ** Compute the revised record entries for indices as we go.
  109864. **
  109865. ** This loop also handles the case of the PRIMARY KEY index for a
  109866. ** WITHOUT ROWID table.
  109867. */
  109868. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  109869. int regIdx; /* Range of registers hold conent for pIdx */
  109870. int regR; /* Range of registers holding conflicting PK */
  109871. int iThisCur; /* Cursor for this UNIQUE index */
  109872. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  109873. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  109874. if( pUpIdx==pIdx ){
  109875. addrUniqueOk = upsertJump+1;
  109876. upsertBypass = sqlite3VdbeGoto(v, 0);
  109877. VdbeComment((v, "Skip upsert subroutine"));
  109878. sqlite3VdbeJumpHere(v, upsertJump);
  109879. }else{
  109880. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  109881. }
  109882. if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){
  109883. sqlite3TableAffinity(v, pTab, regNewData+1);
  109884. bAffinityDone = 1;
  109885. }
  109886. VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName));
  109887. iThisCur = iIdxCur+ix;
  109888. /* Skip partial indices for which the WHERE clause is not true */
  109889. if( pIdx->pPartIdxWhere ){
  109890. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  109891. pParse->iSelfTab = -(regNewData+1);
  109892. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  109893. SQLITE_JUMPIFNULL);
  109894. pParse->iSelfTab = 0;
  109895. }
  109896. /* Create a record for this index entry as it should appear after
  109897. ** the insert or update. Store that record in the aRegIdx[ix] register
  109898. */
  109899. regIdx = aRegIdx[ix]+1;
  109900. for(i=0; i<pIdx->nColumn; i++){
  109901. int iField = pIdx->aiColumn[i];
  109902. int x;
  109903. if( iField==XN_EXPR ){
  109904. pParse->iSelfTab = -(regNewData+1);
  109905. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  109906. pParse->iSelfTab = 0;
  109907. VdbeComment((v, "%s column %d", pIdx->zName, i));
  109908. }else{
  109909. if( iField==XN_ROWID || iField==pTab->iPKey ){
  109910. x = regNewData;
  109911. }else{
  109912. x = iField + regNewData + 1;
  109913. }
  109914. sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
  109915. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  109916. }
  109917. }
  109918. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  109919. VdbeComment((v, "for %s", pIdx->zName));
  109920. #ifdef SQLITE_ENABLE_NULL_TRIM
  109921. if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
  109922. #endif
  109923. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  109924. ** of a WITHOUT ROWID table and there has been no change the
  109925. ** primary key, then no collision is possible. The collision detection
  109926. ** logic below can all be skipped. */
  109927. if( isUpdate && pPk==pIdx && pkChng==0 ){
  109928. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  109929. continue;
  109930. }
  109931. /* Find out what action to take in case there is a uniqueness conflict */
  109932. onError = pIdx->onError;
  109933. if( onError==OE_None ){
  109934. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  109935. continue; /* pIdx is not a UNIQUE index */
  109936. }
  109937. if( overrideError!=OE_Default ){
  109938. onError = overrideError;
  109939. }else if( onError==OE_Default ){
  109940. onError = OE_Abort;
  109941. }
  109942. /* Figure out if the upsert clause applies to this index */
  109943. if( pUpIdx==pIdx ){
  109944. if( pUpsert->pUpsertSet==0 ){
  109945. onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
  109946. }else{
  109947. onError = OE_Update; /* DO UPDATE */
  109948. }
  109949. }
  109950. /* Collision detection may be omitted if all of the following are true:
  109951. ** (1) The conflict resolution algorithm is REPLACE
  109952. ** (2) The table is a WITHOUT ROWID table
  109953. ** (3) There are no secondary indexes on the table
  109954. ** (4) No delete triggers need to be fired if there is a conflict
  109955. ** (5) No FK constraint counters need to be updated if a conflict occurs.
  109956. */
  109957. if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
  109958. && pPk==pIdx /* Condition 2 */
  109959. && onError==OE_Replace /* Condition 1 */
  109960. && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
  109961. 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
  109962. && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
  109963. (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
  109964. ){
  109965. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  109966. continue;
  109967. }
  109968. /* Check to see if the new index entry will be unique */
  109969. sqlite3VdbeVerifyAbortable(v, onError);
  109970. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  109971. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  109972. /* Generate code to handle collisions */
  109973. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  109974. if( isUpdate || onError==OE_Replace ){
  109975. if( HasRowid(pTab) ){
  109976. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  109977. /* Conflict only if the rowid of the existing index entry
  109978. ** is different from old-rowid */
  109979. if( isUpdate ){
  109980. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  109981. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  109982. VdbeCoverage(v);
  109983. }
  109984. }else{
  109985. int x;
  109986. /* Extract the PRIMARY KEY from the end of the index entry and
  109987. ** store it in registers regR..regR+nPk-1 */
  109988. if( pIdx!=pPk ){
  109989. for(i=0; i<pPk->nKeyCol; i++){
  109990. assert( pPk->aiColumn[i]>=0 );
  109991. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  109992. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  109993. VdbeComment((v, "%s.%s", pTab->zName,
  109994. pTab->aCol[pPk->aiColumn[i]].zName));
  109995. }
  109996. }
  109997. if( isUpdate ){
  109998. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  109999. ** table, only conflict if the new PRIMARY KEY values are actually
  110000. ** different from the old.
  110001. **
  110002. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  110003. ** of the matched index row are different from the original PRIMARY
  110004. ** KEY values of this row before the update. */
  110005. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  110006. int op = OP_Ne;
  110007. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  110008. for(i=0; i<pPk->nKeyCol; i++){
  110009. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  110010. x = pPk->aiColumn[i];
  110011. assert( x>=0 );
  110012. if( i==(pPk->nKeyCol-1) ){
  110013. addrJump = addrUniqueOk;
  110014. op = OP_Eq;
  110015. }
  110016. sqlite3VdbeAddOp4(v, op,
  110017. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  110018. );
  110019. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  110020. VdbeCoverageIf(v, op==OP_Eq);
  110021. VdbeCoverageIf(v, op==OP_Ne);
  110022. }
  110023. }
  110024. }
  110025. }
  110026. /* Generate code that executes if the new index entry is not unique */
  110027. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  110028. || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
  110029. switch( onError ){
  110030. case OE_Rollback:
  110031. case OE_Abort:
  110032. case OE_Fail: {
  110033. testcase( onError==OE_Rollback );
  110034. testcase( onError==OE_Abort );
  110035. testcase( onError==OE_Fail );
  110036. sqlite3UniqueConstraint(pParse, onError, pIdx);
  110037. break;
  110038. }
  110039. #ifndef SQLITE_OMIT_UPSERT
  110040. case OE_Update: {
  110041. sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
  110042. /* Fall through */
  110043. }
  110044. #endif
  110045. case OE_Ignore: {
  110046. testcase( onError==OE_Ignore );
  110047. sqlite3VdbeGoto(v, ignoreDest);
  110048. break;
  110049. }
  110050. default: {
  110051. Trigger *pTrigger = 0;
  110052. assert( onError==OE_Replace );
  110053. if( db->flags&SQLITE_RecTriggers ){
  110054. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  110055. }
  110056. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  110057. sqlite3MultiWrite(pParse);
  110058. }
  110059. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  110060. regR, nPkField, 0, OE_Replace,
  110061. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
  110062. seenReplace = 1;
  110063. break;
  110064. }
  110065. }
  110066. if( pUpIdx==pIdx ){
  110067. sqlite3VdbeGoto(v, upsertJump+1);
  110068. sqlite3VdbeJumpHere(v, upsertBypass);
  110069. }else{
  110070. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  110071. }
  110072. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  110073. }
  110074. /* If the IPK constraint is a REPLACE, run it last */
  110075. if( ipkTop ){
  110076. sqlite3VdbeGoto(v, ipkTop+1);
  110077. VdbeComment((v, "Do IPK REPLACE"));
  110078. sqlite3VdbeJumpHere(v, ipkBottom);
  110079. }
  110080. *pbMayReplace = seenReplace;
  110081. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  110082. }
  110083. #ifdef SQLITE_ENABLE_NULL_TRIM
  110084. /*
  110085. ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
  110086. ** to be the number of columns in table pTab that must not be NULL-trimmed.
  110087. **
  110088. ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
  110089. */
  110090. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
  110091. u16 i;
  110092. /* Records with omitted columns are only allowed for schema format
  110093. ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
  110094. if( pTab->pSchema->file_format<2 ) return;
  110095. for(i=pTab->nCol-1; i>0; i--){
  110096. if( pTab->aCol[i].pDflt!=0 ) break;
  110097. if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
  110098. }
  110099. sqlite3VdbeChangeP5(v, i+1);
  110100. }
  110101. #endif
  110102. /*
  110103. ** This routine generates code to finish the INSERT or UPDATE operation
  110104. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  110105. ** A consecutive range of registers starting at regNewData contains the
  110106. ** rowid and the content to be inserted.
  110107. **
  110108. ** The arguments to this routine should be the same as the first six
  110109. ** arguments to sqlite3GenerateConstraintChecks.
  110110. */
  110111. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  110112. Parse *pParse, /* The parser context */
  110113. Table *pTab, /* the table into which we are inserting */
  110114. int iDataCur, /* Cursor of the canonical data source */
  110115. int iIdxCur, /* First index cursor */
  110116. int regNewData, /* Range of content */
  110117. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  110118. int update_flags, /* True for UPDATE, False for INSERT */
  110119. int appendBias, /* True if this is likely to be an append */
  110120. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  110121. ){
  110122. Vdbe *v; /* Prepared statements under construction */
  110123. Index *pIdx; /* An index being inserted or updated */
  110124. u8 pik_flags; /* flag values passed to the btree insert */
  110125. int regData; /* Content registers (after the rowid) */
  110126. int regRec; /* Register holding assembled record for the table */
  110127. int i; /* Loop counter */
  110128. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  110129. assert( update_flags==0
  110130. || update_flags==OPFLAG_ISUPDATE
  110131. || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
  110132. );
  110133. v = sqlite3GetVdbe(pParse);
  110134. assert( v!=0 );
  110135. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  110136. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  110137. if( aRegIdx[i]==0 ) continue;
  110138. bAffinityDone = 1;
  110139. if( pIdx->pPartIdxWhere ){
  110140. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  110141. VdbeCoverage(v);
  110142. }
  110143. pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
  110144. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  110145. assert( pParse->nested==0 );
  110146. pik_flags |= OPFLAG_NCHANGE;
  110147. pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
  110148. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  110149. if( update_flags==0 ){
  110150. sqlite3VdbeAddOp4(v, OP_InsertInt,
  110151. iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
  110152. );
  110153. sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
  110154. }
  110155. #endif
  110156. }
  110157. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
  110158. aRegIdx[i]+1,
  110159. pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
  110160. sqlite3VdbeChangeP5(v, pik_flags);
  110161. }
  110162. if( !HasRowid(pTab) ) return;
  110163. regData = regNewData + 1;
  110164. regRec = sqlite3GetTempReg(pParse);
  110165. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  110166. sqlite3SetMakeRecordP5(v, pTab);
  110167. if( !bAffinityDone ){
  110168. sqlite3TableAffinity(v, pTab, 0);
  110169. }
  110170. if( pParse->nested ){
  110171. pik_flags = 0;
  110172. }else{
  110173. pik_flags = OPFLAG_NCHANGE;
  110174. pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
  110175. }
  110176. if( appendBias ){
  110177. pik_flags |= OPFLAG_APPEND;
  110178. }
  110179. if( useSeekResult ){
  110180. pik_flags |= OPFLAG_USESEEKRESULT;
  110181. }
  110182. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  110183. if( !pParse->nested ){
  110184. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  110185. }
  110186. sqlite3VdbeChangeP5(v, pik_flags);
  110187. }
  110188. /*
  110189. ** Allocate cursors for the pTab table and all its indices and generate
  110190. ** code to open and initialized those cursors.
  110191. **
  110192. ** The cursor for the object that contains the complete data (normally
  110193. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  110194. ** ROWID table) is returned in *piDataCur. The first index cursor is
  110195. ** returned in *piIdxCur. The number of indices is returned.
  110196. **
  110197. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  110198. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  110199. ** If iBase is negative, then allocate the next available cursor.
  110200. **
  110201. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  110202. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  110203. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  110204. ** pTab->pIndex list.
  110205. **
  110206. ** If pTab is a virtual table, then this routine is a no-op and the
  110207. ** *piDataCur and *piIdxCur values are left uninitialized.
  110208. */
  110209. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  110210. Parse *pParse, /* Parsing context */
  110211. Table *pTab, /* Table to be opened */
  110212. int op, /* OP_OpenRead or OP_OpenWrite */
  110213. u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
  110214. int iBase, /* Use this for the table cursor, if there is one */
  110215. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  110216. int *piDataCur, /* Write the database source cursor number here */
  110217. int *piIdxCur /* Write the first index cursor number here */
  110218. ){
  110219. int i;
  110220. int iDb;
  110221. int iDataCur;
  110222. Index *pIdx;
  110223. Vdbe *v;
  110224. assert( op==OP_OpenRead || op==OP_OpenWrite );
  110225. assert( op==OP_OpenWrite || p5==0 );
  110226. if( IsVirtual(pTab) ){
  110227. /* This routine is a no-op for virtual tables. Leave the output
  110228. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  110229. ** can detect if they are used by mistake in the caller. */
  110230. return 0;
  110231. }
  110232. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  110233. v = sqlite3GetVdbe(pParse);
  110234. assert( v!=0 );
  110235. if( iBase<0 ) iBase = pParse->nTab;
  110236. iDataCur = iBase++;
  110237. if( piDataCur ) *piDataCur = iDataCur;
  110238. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  110239. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  110240. }else{
  110241. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  110242. }
  110243. if( piIdxCur ) *piIdxCur = iBase;
  110244. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  110245. int iIdxCur = iBase++;
  110246. assert( pIdx->pSchema==pTab->pSchema );
  110247. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  110248. if( piDataCur ) *piDataCur = iIdxCur;
  110249. p5 = 0;
  110250. }
  110251. if( aToOpen==0 || aToOpen[i+1] ){
  110252. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  110253. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  110254. sqlite3VdbeChangeP5(v, p5);
  110255. VdbeComment((v, "%s", pIdx->zName));
  110256. }
  110257. }
  110258. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  110259. return i;
  110260. }
  110261. #ifdef SQLITE_TEST
  110262. /*
  110263. ** The following global variable is incremented whenever the
  110264. ** transfer optimization is used. This is used for testing
  110265. ** purposes only - to make sure the transfer optimization really
  110266. ** is happening when it is supposed to.
  110267. */
  110268. SQLITE_API int sqlite3_xferopt_count;
  110269. #endif /* SQLITE_TEST */
  110270. #ifndef SQLITE_OMIT_XFER_OPT
  110271. /*
  110272. ** Check to see if index pSrc is compatible as a source of data
  110273. ** for index pDest in an insert transfer optimization. The rules
  110274. ** for a compatible index:
  110275. **
  110276. ** * The index is over the same set of columns
  110277. ** * The same DESC and ASC markings occurs on all columns
  110278. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  110279. ** * The same collating sequence on each column
  110280. ** * The index has the exact same WHERE clause
  110281. */
  110282. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  110283. int i;
  110284. assert( pDest && pSrc );
  110285. assert( pDest->pTable!=pSrc->pTable );
  110286. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  110287. return 0; /* Different number of columns */
  110288. }
  110289. if( pDest->onError!=pSrc->onError ){
  110290. return 0; /* Different conflict resolution strategies */
  110291. }
  110292. for(i=0; i<pSrc->nKeyCol; i++){
  110293. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  110294. return 0; /* Different columns indexed */
  110295. }
  110296. if( pSrc->aiColumn[i]==XN_EXPR ){
  110297. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  110298. if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
  110299. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  110300. return 0; /* Different expressions in the index */
  110301. }
  110302. }
  110303. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  110304. return 0; /* Different sort orders */
  110305. }
  110306. if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
  110307. return 0; /* Different collating sequences */
  110308. }
  110309. }
  110310. if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  110311. return 0; /* Different WHERE clauses */
  110312. }
  110313. /* If no test above fails then the indices must be compatible */
  110314. return 1;
  110315. }
  110316. /*
  110317. ** Attempt the transfer optimization on INSERTs of the form
  110318. **
  110319. ** INSERT INTO tab1 SELECT * FROM tab2;
  110320. **
  110321. ** The xfer optimization transfers raw records from tab2 over to tab1.
  110322. ** Columns are not decoded and reassembled, which greatly improves
  110323. ** performance. Raw index records are transferred in the same way.
  110324. **
  110325. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  110326. ** There are lots of rules for determining compatibility - see comments
  110327. ** embedded in the code for details.
  110328. **
  110329. ** This routine returns TRUE if the optimization is guaranteed to be used.
  110330. ** Sometimes the xfer optimization will only work if the destination table
  110331. ** is empty - a factor that can only be determined at run-time. In that
  110332. ** case, this routine generates code for the xfer optimization but also
  110333. ** does a test to see if the destination table is empty and jumps over the
  110334. ** xfer optimization code if the test fails. In that case, this routine
  110335. ** returns FALSE so that the caller will know to go ahead and generate
  110336. ** an unoptimized transfer. This routine also returns FALSE if there
  110337. ** is no chance that the xfer optimization can be applied.
  110338. **
  110339. ** This optimization is particularly useful at making VACUUM run faster.
  110340. */
  110341. static int xferOptimization(
  110342. Parse *pParse, /* Parser context */
  110343. Table *pDest, /* The table we are inserting into */
  110344. Select *pSelect, /* A SELECT statement to use as the data source */
  110345. int onError, /* How to handle constraint errors */
  110346. int iDbDest /* The database of pDest */
  110347. ){
  110348. sqlite3 *db = pParse->db;
  110349. ExprList *pEList; /* The result set of the SELECT */
  110350. Table *pSrc; /* The table in the FROM clause of SELECT */
  110351. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  110352. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  110353. int i; /* Loop counter */
  110354. int iDbSrc; /* The database of pSrc */
  110355. int iSrc, iDest; /* Cursors from source and destination */
  110356. int addr1, addr2; /* Loop addresses */
  110357. int emptyDestTest = 0; /* Address of test for empty pDest */
  110358. int emptySrcTest = 0; /* Address of test for empty pSrc */
  110359. Vdbe *v; /* The VDBE we are building */
  110360. int regAutoinc; /* Memory register used by AUTOINC */
  110361. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  110362. int regData, regRowid; /* Registers holding data and rowid */
  110363. if( pSelect==0 ){
  110364. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  110365. }
  110366. if( pParse->pWith || pSelect->pWith ){
  110367. /* Do not attempt to process this query if there are an WITH clauses
  110368. ** attached to it. Proceeding may generate a false "no such table: xxx"
  110369. ** error if pSelect reads from a CTE named "xxx". */
  110370. return 0;
  110371. }
  110372. if( sqlite3TriggerList(pParse, pDest) ){
  110373. return 0; /* tab1 must not have triggers */
  110374. }
  110375. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110376. if( IsVirtual(pDest) ){
  110377. return 0; /* tab1 must not be a virtual table */
  110378. }
  110379. #endif
  110380. if( onError==OE_Default ){
  110381. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  110382. if( onError==OE_Default ) onError = OE_Abort;
  110383. }
  110384. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  110385. if( pSelect->pSrc->nSrc!=1 ){
  110386. return 0; /* FROM clause must have exactly one term */
  110387. }
  110388. if( pSelect->pSrc->a[0].pSelect ){
  110389. return 0; /* FROM clause cannot contain a subquery */
  110390. }
  110391. if( pSelect->pWhere ){
  110392. return 0; /* SELECT may not have a WHERE clause */
  110393. }
  110394. if( pSelect->pOrderBy ){
  110395. return 0; /* SELECT may not have an ORDER BY clause */
  110396. }
  110397. /* Do not need to test for a HAVING clause. If HAVING is present but
  110398. ** there is no ORDER BY, we will get an error. */
  110399. if( pSelect->pGroupBy ){
  110400. return 0; /* SELECT may not have a GROUP BY clause */
  110401. }
  110402. if( pSelect->pLimit ){
  110403. return 0; /* SELECT may not have a LIMIT clause */
  110404. }
  110405. if( pSelect->pPrior ){
  110406. return 0; /* SELECT may not be a compound query */
  110407. }
  110408. if( pSelect->selFlags & SF_Distinct ){
  110409. return 0; /* SELECT may not be DISTINCT */
  110410. }
  110411. pEList = pSelect->pEList;
  110412. assert( pEList!=0 );
  110413. if( pEList->nExpr!=1 ){
  110414. return 0; /* The result set must have exactly one column */
  110415. }
  110416. assert( pEList->a[0].pExpr );
  110417. if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
  110418. return 0; /* The result set must be the special operator "*" */
  110419. }
  110420. /* At this point we have established that the statement is of the
  110421. ** correct syntactic form to participate in this optimization. Now
  110422. ** we have to check the semantics.
  110423. */
  110424. pItem = pSelect->pSrc->a;
  110425. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  110426. if( pSrc==0 ){
  110427. return 0; /* FROM clause does not contain a real table */
  110428. }
  110429. if( pSrc==pDest ){
  110430. return 0; /* tab1 and tab2 may not be the same table */
  110431. }
  110432. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  110433. return 0; /* source and destination must both be WITHOUT ROWID or not */
  110434. }
  110435. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110436. if( IsVirtual(pSrc) ){
  110437. return 0; /* tab2 must not be a virtual table */
  110438. }
  110439. #endif
  110440. if( pSrc->pSelect ){
  110441. return 0; /* tab2 may not be a view */
  110442. }
  110443. if( pDest->nCol!=pSrc->nCol ){
  110444. return 0; /* Number of columns must be the same in tab1 and tab2 */
  110445. }
  110446. if( pDest->iPKey!=pSrc->iPKey ){
  110447. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  110448. }
  110449. for(i=0; i<pDest->nCol; i++){
  110450. Column *pDestCol = &pDest->aCol[i];
  110451. Column *pSrcCol = &pSrc->aCol[i];
  110452. #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
  110453. if( (db->mDbFlags & DBFLAG_Vacuum)==0
  110454. && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
  110455. ){
  110456. return 0; /* Neither table may have __hidden__ columns */
  110457. }
  110458. #endif
  110459. if( pDestCol->affinity!=pSrcCol->affinity ){
  110460. return 0; /* Affinity must be the same on all columns */
  110461. }
  110462. if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
  110463. return 0; /* Collating sequence must be the same on all columns */
  110464. }
  110465. if( pDestCol->notNull && !pSrcCol->notNull ){
  110466. return 0; /* tab2 must be NOT NULL if tab1 is */
  110467. }
  110468. /* Default values for second and subsequent columns need to match. */
  110469. if( i>0 ){
  110470. assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
  110471. assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
  110472. if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
  110473. || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
  110474. pSrcCol->pDflt->u.zToken)!=0)
  110475. ){
  110476. return 0; /* Default values must be the same for all columns */
  110477. }
  110478. }
  110479. }
  110480. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  110481. if( IsUniqueIndex(pDestIdx) ){
  110482. destHasUniqueIdx = 1;
  110483. }
  110484. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  110485. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  110486. }
  110487. if( pSrcIdx==0 ){
  110488. return 0; /* pDestIdx has no corresponding index in pSrc */
  110489. }
  110490. }
  110491. #ifndef SQLITE_OMIT_CHECK
  110492. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  110493. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  110494. }
  110495. #endif
  110496. #ifndef SQLITE_OMIT_FOREIGN_KEY
  110497. /* Disallow the transfer optimization if the destination table constains
  110498. ** any foreign key constraints. This is more restrictive than necessary.
  110499. ** But the main beneficiary of the transfer optimization is the VACUUM
  110500. ** command, and the VACUUM command disables foreign key constraints. So
  110501. ** the extra complication to make this rule less restrictive is probably
  110502. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  110503. */
  110504. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  110505. return 0;
  110506. }
  110507. #endif
  110508. if( (db->flags & SQLITE_CountRows)!=0 ){
  110509. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  110510. }
  110511. /* If we get this far, it means that the xfer optimization is at
  110512. ** least a possibility, though it might only work if the destination
  110513. ** table (tab1) is initially empty.
  110514. */
  110515. #ifdef SQLITE_TEST
  110516. sqlite3_xferopt_count++;
  110517. #endif
  110518. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  110519. v = sqlite3GetVdbe(pParse);
  110520. sqlite3CodeVerifySchema(pParse, iDbSrc);
  110521. iSrc = pParse->nTab++;
  110522. iDest = pParse->nTab++;
  110523. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  110524. regData = sqlite3GetTempReg(pParse);
  110525. regRowid = sqlite3GetTempReg(pParse);
  110526. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  110527. assert( HasRowid(pDest) || destHasUniqueIdx );
  110528. if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
  110529. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  110530. || destHasUniqueIdx /* (2) */
  110531. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  110532. )){
  110533. /* In some circumstances, we are able to run the xfer optimization
  110534. ** only if the destination table is initially empty. Unless the
  110535. ** DBFLAG_Vacuum flag is set, this block generates code to make
  110536. ** that determination. If DBFLAG_Vacuum is set, then the destination
  110537. ** table is always empty.
  110538. **
  110539. ** Conditions under which the destination must be empty:
  110540. **
  110541. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  110542. ** (If the destination is not initially empty, the rowid fields
  110543. ** of index entries might need to change.)
  110544. **
  110545. ** (2) The destination has a unique index. (The xfer optimization
  110546. ** is unable to test uniqueness.)
  110547. **
  110548. ** (3) onError is something other than OE_Abort and OE_Rollback.
  110549. */
  110550. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  110551. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  110552. sqlite3VdbeJumpHere(v, addr1);
  110553. }
  110554. if( HasRowid(pSrc) ){
  110555. u8 insFlags;
  110556. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  110557. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  110558. if( pDest->iPKey>=0 ){
  110559. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  110560. sqlite3VdbeVerifyAbortable(v, onError);
  110561. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  110562. VdbeCoverage(v);
  110563. sqlite3RowidConstraint(pParse, onError, pDest);
  110564. sqlite3VdbeJumpHere(v, addr2);
  110565. autoIncStep(pParse, regAutoinc, regRowid);
  110566. }else if( pDest->pIndex==0 ){
  110567. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  110568. }else{
  110569. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  110570. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  110571. }
  110572. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  110573. if( db->mDbFlags & DBFLAG_Vacuum ){
  110574. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  110575. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
  110576. OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
  110577. }else{
  110578. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
  110579. }
  110580. sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
  110581. (char*)pDest, P4_TABLE);
  110582. sqlite3VdbeChangeP5(v, insFlags);
  110583. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  110584. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  110585. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  110586. }else{
  110587. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  110588. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  110589. }
  110590. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  110591. u8 idxInsFlags = 0;
  110592. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  110593. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  110594. }
  110595. assert( pSrcIdx );
  110596. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  110597. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  110598. VdbeComment((v, "%s", pSrcIdx->zName));
  110599. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  110600. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  110601. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  110602. VdbeComment((v, "%s", pDestIdx->zName));
  110603. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  110604. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  110605. if( db->mDbFlags & DBFLAG_Vacuum ){
  110606. /* This INSERT command is part of a VACUUM operation, which guarantees
  110607. ** that the destination table is empty. If all indexed columns use
  110608. ** collation sequence BINARY, then it can also be assumed that the
  110609. ** index will be populated by inserting keys in strictly sorted
  110610. ** order. In this case, instead of seeking within the b-tree as part
  110611. ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
  110612. ** OP_IdxInsert to seek to the point within the b-tree where each key
  110613. ** should be inserted. This is faster.
  110614. **
  110615. ** If any of the indexed columns use a collation sequence other than
  110616. ** BINARY, this optimization is disabled. This is because the user
  110617. ** might change the definition of a collation sequence and then run
  110618. ** a VACUUM command. In that case keys may not be written in strictly
  110619. ** sorted order. */
  110620. for(i=0; i<pSrcIdx->nColumn; i++){
  110621. const char *zColl = pSrcIdx->azColl[i];
  110622. if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
  110623. }
  110624. if( i==pSrcIdx->nColumn ){
  110625. idxInsFlags = OPFLAG_USESEEKRESULT;
  110626. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  110627. }
  110628. }
  110629. if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
  110630. idxInsFlags |= OPFLAG_NCHANGE;
  110631. }
  110632. sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
  110633. sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
  110634. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  110635. sqlite3VdbeJumpHere(v, addr1);
  110636. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  110637. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  110638. }
  110639. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  110640. sqlite3ReleaseTempReg(pParse, regRowid);
  110641. sqlite3ReleaseTempReg(pParse, regData);
  110642. if( emptyDestTest ){
  110643. sqlite3AutoincrementEnd(pParse);
  110644. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  110645. sqlite3VdbeJumpHere(v, emptyDestTest);
  110646. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  110647. return 0;
  110648. }else{
  110649. return 1;
  110650. }
  110651. }
  110652. #endif /* SQLITE_OMIT_XFER_OPT */
  110653. /************** End of insert.c **********************************************/
  110654. /************** Begin file legacy.c ******************************************/
  110655. /*
  110656. ** 2001 September 15
  110657. **
  110658. ** The author disclaims copyright to this source code. In place of
  110659. ** a legal notice, here is a blessing:
  110660. **
  110661. ** May you do good and not evil.
  110662. ** May you find forgiveness for yourself and forgive others.
  110663. ** May you share freely, never taking more than you give.
  110664. **
  110665. *************************************************************************
  110666. ** Main file for the SQLite library. The routines in this file
  110667. ** implement the programmer interface to the library. Routines in
  110668. ** other files are for internal use by SQLite and should not be
  110669. ** accessed by users of the library.
  110670. */
  110671. /* #include "sqliteInt.h" */
  110672. /*
  110673. ** Execute SQL code. Return one of the SQLITE_ success/failure
  110674. ** codes. Also write an error message into memory obtained from
  110675. ** malloc() and make *pzErrMsg point to that message.
  110676. **
  110677. ** If the SQL is a query, then for each row in the query result
  110678. ** the xCallback() function is called. pArg becomes the first
  110679. ** argument to xCallback(). If xCallback=NULL then no callback
  110680. ** is invoked, even for queries.
  110681. */
  110682. SQLITE_API int sqlite3_exec(
  110683. sqlite3 *db, /* The database on which the SQL executes */
  110684. const char *zSql, /* The SQL to be executed */
  110685. sqlite3_callback xCallback, /* Invoke this callback routine */
  110686. void *pArg, /* First argument to xCallback() */
  110687. char **pzErrMsg /* Write error messages here */
  110688. ){
  110689. int rc = SQLITE_OK; /* Return code */
  110690. const char *zLeftover; /* Tail of unprocessed SQL */
  110691. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  110692. char **azCols = 0; /* Names of result columns */
  110693. int callbackIsInit; /* True if callback data is initialized */
  110694. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  110695. if( zSql==0 ) zSql = "";
  110696. sqlite3_mutex_enter(db->mutex);
  110697. sqlite3Error(db, SQLITE_OK);
  110698. while( rc==SQLITE_OK && zSql[0] ){
  110699. int nCol;
  110700. char **azVals = 0;
  110701. pStmt = 0;
  110702. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  110703. assert( rc==SQLITE_OK || pStmt==0 );
  110704. if( rc!=SQLITE_OK ){
  110705. continue;
  110706. }
  110707. if( !pStmt ){
  110708. /* this happens for a comment or white-space */
  110709. zSql = zLeftover;
  110710. continue;
  110711. }
  110712. callbackIsInit = 0;
  110713. nCol = sqlite3_column_count(pStmt);
  110714. while( 1 ){
  110715. int i;
  110716. rc = sqlite3_step(pStmt);
  110717. /* Invoke the callback function if required */
  110718. if( xCallback && (SQLITE_ROW==rc ||
  110719. (SQLITE_DONE==rc && !callbackIsInit
  110720. && db->flags&SQLITE_NullCallback)) ){
  110721. if( !callbackIsInit ){
  110722. azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
  110723. if( azCols==0 ){
  110724. goto exec_out;
  110725. }
  110726. for(i=0; i<nCol; i++){
  110727. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  110728. /* sqlite3VdbeSetColName() installs column names as UTF8
  110729. ** strings so there is no way for sqlite3_column_name() to fail. */
  110730. assert( azCols[i]!=0 );
  110731. }
  110732. callbackIsInit = 1;
  110733. }
  110734. if( rc==SQLITE_ROW ){
  110735. azVals = &azCols[nCol];
  110736. for(i=0; i<nCol; i++){
  110737. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  110738. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  110739. sqlite3OomFault(db);
  110740. goto exec_out;
  110741. }
  110742. }
  110743. azVals[i] = 0;
  110744. }
  110745. if( xCallback(pArg, nCol, azVals, azCols) ){
  110746. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  110747. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  110748. ** return SQLITE_ABORT. */
  110749. rc = SQLITE_ABORT;
  110750. sqlite3VdbeFinalize((Vdbe *)pStmt);
  110751. pStmt = 0;
  110752. sqlite3Error(db, SQLITE_ABORT);
  110753. goto exec_out;
  110754. }
  110755. }
  110756. if( rc!=SQLITE_ROW ){
  110757. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  110758. pStmt = 0;
  110759. zSql = zLeftover;
  110760. while( sqlite3Isspace(zSql[0]) ) zSql++;
  110761. break;
  110762. }
  110763. }
  110764. sqlite3DbFree(db, azCols);
  110765. azCols = 0;
  110766. }
  110767. exec_out:
  110768. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  110769. sqlite3DbFree(db, azCols);
  110770. rc = sqlite3ApiExit(db, rc);
  110771. if( rc!=SQLITE_OK && pzErrMsg ){
  110772. *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
  110773. if( *pzErrMsg==0 ){
  110774. rc = SQLITE_NOMEM_BKPT;
  110775. sqlite3Error(db, SQLITE_NOMEM);
  110776. }
  110777. }else if( pzErrMsg ){
  110778. *pzErrMsg = 0;
  110779. }
  110780. assert( (rc&db->errMask)==rc );
  110781. sqlite3_mutex_leave(db->mutex);
  110782. return rc;
  110783. }
  110784. /************** End of legacy.c **********************************************/
  110785. /************** Begin file loadext.c *****************************************/
  110786. /*
  110787. ** 2006 June 7
  110788. **
  110789. ** The author disclaims copyright to this source code. In place of
  110790. ** a legal notice, here is a blessing:
  110791. **
  110792. ** May you do good and not evil.
  110793. ** May you find forgiveness for yourself and forgive others.
  110794. ** May you share freely, never taking more than you give.
  110795. **
  110796. *************************************************************************
  110797. ** This file contains code used to dynamically load extensions into
  110798. ** the SQLite library.
  110799. */
  110800. #ifndef SQLITE_CORE
  110801. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  110802. #endif
  110803. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  110804. /************** Begin file sqlite3ext.h **************************************/
  110805. /*
  110806. ** 2006 June 7
  110807. **
  110808. ** The author disclaims copyright to this source code. In place of
  110809. ** a legal notice, here is a blessing:
  110810. **
  110811. ** May you do good and not evil.
  110812. ** May you find forgiveness for yourself and forgive others.
  110813. ** May you share freely, never taking more than you give.
  110814. **
  110815. *************************************************************************
  110816. ** This header file defines the SQLite interface for use by
  110817. ** shared libraries that want to be imported as extensions into
  110818. ** an SQLite instance. Shared libraries that intend to be loaded
  110819. ** as extensions by SQLite should #include this file instead of
  110820. ** sqlite3.h.
  110821. */
  110822. #ifndef SQLITE3EXT_H
  110823. #define SQLITE3EXT_H
  110824. /* #include "sqlite3.h" */
  110825. /*
  110826. ** The following structure holds pointers to all of the SQLite API
  110827. ** routines.
  110828. **
  110829. ** WARNING: In order to maintain backwards compatibility, add new
  110830. ** interfaces to the end of this structure only. If you insert new
  110831. ** interfaces in the middle of this structure, then older different
  110832. ** versions of SQLite will not be able to load each other's shared
  110833. ** libraries!
  110834. */
  110835. struct sqlite3_api_routines {
  110836. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  110837. int (*aggregate_count)(sqlite3_context*);
  110838. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  110839. int (*bind_double)(sqlite3_stmt*,int,double);
  110840. int (*bind_int)(sqlite3_stmt*,int,int);
  110841. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  110842. int (*bind_null)(sqlite3_stmt*,int);
  110843. int (*bind_parameter_count)(sqlite3_stmt*);
  110844. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  110845. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  110846. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  110847. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  110848. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  110849. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  110850. int (*busy_timeout)(sqlite3*,int ms);
  110851. int (*changes)(sqlite3*);
  110852. int (*close)(sqlite3*);
  110853. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  110854. int eTextRep,const char*));
  110855. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  110856. int eTextRep,const void*));
  110857. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  110858. int (*column_bytes)(sqlite3_stmt*,int iCol);
  110859. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  110860. int (*column_count)(sqlite3_stmt*pStmt);
  110861. const char * (*column_database_name)(sqlite3_stmt*,int);
  110862. const void * (*column_database_name16)(sqlite3_stmt*,int);
  110863. const char * (*column_decltype)(sqlite3_stmt*,int i);
  110864. const void * (*column_decltype16)(sqlite3_stmt*,int);
  110865. double (*column_double)(sqlite3_stmt*,int iCol);
  110866. int (*column_int)(sqlite3_stmt*,int iCol);
  110867. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  110868. const char * (*column_name)(sqlite3_stmt*,int);
  110869. const void * (*column_name16)(sqlite3_stmt*,int);
  110870. const char * (*column_origin_name)(sqlite3_stmt*,int);
  110871. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  110872. const char * (*column_table_name)(sqlite3_stmt*,int);
  110873. const void * (*column_table_name16)(sqlite3_stmt*,int);
  110874. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  110875. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  110876. int (*column_type)(sqlite3_stmt*,int iCol);
  110877. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  110878. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  110879. int (*complete)(const char*sql);
  110880. int (*complete16)(const void*sql);
  110881. int (*create_collation)(sqlite3*,const char*,int,void*,
  110882. int(*)(void*,int,const void*,int,const void*));
  110883. int (*create_collation16)(sqlite3*,const void*,int,void*,
  110884. int(*)(void*,int,const void*,int,const void*));
  110885. int (*create_function)(sqlite3*,const char*,int,int,void*,
  110886. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  110887. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  110888. void (*xFinal)(sqlite3_context*));
  110889. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  110890. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  110891. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  110892. void (*xFinal)(sqlite3_context*));
  110893. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  110894. int (*data_count)(sqlite3_stmt*pStmt);
  110895. sqlite3 * (*db_handle)(sqlite3_stmt*);
  110896. int (*declare_vtab)(sqlite3*,const char*);
  110897. int (*enable_shared_cache)(int);
  110898. int (*errcode)(sqlite3*db);
  110899. const char * (*errmsg)(sqlite3*);
  110900. const void * (*errmsg16)(sqlite3*);
  110901. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  110902. int (*expired)(sqlite3_stmt*);
  110903. int (*finalize)(sqlite3_stmt*pStmt);
  110904. void (*free)(void*);
  110905. void (*free_table)(char**result);
  110906. int (*get_autocommit)(sqlite3*);
  110907. void * (*get_auxdata)(sqlite3_context*,int);
  110908. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  110909. int (*global_recover)(void);
  110910. void (*interruptx)(sqlite3*);
  110911. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  110912. const char * (*libversion)(void);
  110913. int (*libversion_number)(void);
  110914. void *(*malloc)(int);
  110915. char * (*mprintf)(const char*,...);
  110916. int (*open)(const char*,sqlite3**);
  110917. int (*open16)(const void*,sqlite3**);
  110918. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  110919. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  110920. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  110921. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  110922. void *(*realloc)(void*,int);
  110923. int (*reset)(sqlite3_stmt*pStmt);
  110924. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  110925. void (*result_double)(sqlite3_context*,double);
  110926. void (*result_error)(sqlite3_context*,const char*,int);
  110927. void (*result_error16)(sqlite3_context*,const void*,int);
  110928. void (*result_int)(sqlite3_context*,int);
  110929. void (*result_int64)(sqlite3_context*,sqlite_int64);
  110930. void (*result_null)(sqlite3_context*);
  110931. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  110932. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  110933. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  110934. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  110935. void (*result_value)(sqlite3_context*,sqlite3_value*);
  110936. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  110937. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  110938. const char*,const char*),void*);
  110939. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  110940. char * (*xsnprintf)(int,char*,const char*,...);
  110941. int (*step)(sqlite3_stmt*);
  110942. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  110943. char const**,char const**,int*,int*,int*);
  110944. void (*thread_cleanup)(void);
  110945. int (*total_changes)(sqlite3*);
  110946. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  110947. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  110948. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  110949. sqlite_int64),void*);
  110950. void * (*user_data)(sqlite3_context*);
  110951. const void * (*value_blob)(sqlite3_value*);
  110952. int (*value_bytes)(sqlite3_value*);
  110953. int (*value_bytes16)(sqlite3_value*);
  110954. double (*value_double)(sqlite3_value*);
  110955. int (*value_int)(sqlite3_value*);
  110956. sqlite_int64 (*value_int64)(sqlite3_value*);
  110957. int (*value_numeric_type)(sqlite3_value*);
  110958. const unsigned char * (*value_text)(sqlite3_value*);
  110959. const void * (*value_text16)(sqlite3_value*);
  110960. const void * (*value_text16be)(sqlite3_value*);
  110961. const void * (*value_text16le)(sqlite3_value*);
  110962. int (*value_type)(sqlite3_value*);
  110963. char *(*vmprintf)(const char*,va_list);
  110964. /* Added ??? */
  110965. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  110966. /* Added by 3.3.13 */
  110967. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  110968. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  110969. int (*clear_bindings)(sqlite3_stmt*);
  110970. /* Added by 3.4.1 */
  110971. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  110972. void (*xDestroy)(void *));
  110973. /* Added by 3.5.0 */
  110974. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  110975. int (*blob_bytes)(sqlite3_blob*);
  110976. int (*blob_close)(sqlite3_blob*);
  110977. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  110978. int,sqlite3_blob**);
  110979. int (*blob_read)(sqlite3_blob*,void*,int,int);
  110980. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  110981. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  110982. int(*)(void*,int,const void*,int,const void*),
  110983. void(*)(void*));
  110984. int (*file_control)(sqlite3*,const char*,int,void*);
  110985. sqlite3_int64 (*memory_highwater)(int);
  110986. sqlite3_int64 (*memory_used)(void);
  110987. sqlite3_mutex *(*mutex_alloc)(int);
  110988. void (*mutex_enter)(sqlite3_mutex*);
  110989. void (*mutex_free)(sqlite3_mutex*);
  110990. void (*mutex_leave)(sqlite3_mutex*);
  110991. int (*mutex_try)(sqlite3_mutex*);
  110992. int (*open_v2)(const char*,sqlite3**,int,const char*);
  110993. int (*release_memory)(int);
  110994. void (*result_error_nomem)(sqlite3_context*);
  110995. void (*result_error_toobig)(sqlite3_context*);
  110996. int (*sleep)(int);
  110997. void (*soft_heap_limit)(int);
  110998. sqlite3_vfs *(*vfs_find)(const char*);
  110999. int (*vfs_register)(sqlite3_vfs*,int);
  111000. int (*vfs_unregister)(sqlite3_vfs*);
  111001. int (*xthreadsafe)(void);
  111002. void (*result_zeroblob)(sqlite3_context*,int);
  111003. void (*result_error_code)(sqlite3_context*,int);
  111004. int (*test_control)(int, ...);
  111005. void (*randomness)(int,void*);
  111006. sqlite3 *(*context_db_handle)(sqlite3_context*);
  111007. int (*extended_result_codes)(sqlite3*,int);
  111008. int (*limit)(sqlite3*,int,int);
  111009. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  111010. const char *(*sql)(sqlite3_stmt*);
  111011. int (*status)(int,int*,int*,int);
  111012. int (*backup_finish)(sqlite3_backup*);
  111013. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  111014. int (*backup_pagecount)(sqlite3_backup*);
  111015. int (*backup_remaining)(sqlite3_backup*);
  111016. int (*backup_step)(sqlite3_backup*,int);
  111017. const char *(*compileoption_get)(int);
  111018. int (*compileoption_used)(const char*);
  111019. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  111020. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  111021. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  111022. void (*xFinal)(sqlite3_context*),
  111023. void(*xDestroy)(void*));
  111024. int (*db_config)(sqlite3*,int,...);
  111025. sqlite3_mutex *(*db_mutex)(sqlite3*);
  111026. int (*db_status)(sqlite3*,int,int*,int*,int);
  111027. int (*extended_errcode)(sqlite3*);
  111028. void (*log)(int,const char*,...);
  111029. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  111030. const char *(*sourceid)(void);
  111031. int (*stmt_status)(sqlite3_stmt*,int,int);
  111032. int (*strnicmp)(const char*,const char*,int);
  111033. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  111034. int (*wal_autocheckpoint)(sqlite3*,int);
  111035. int (*wal_checkpoint)(sqlite3*,const char*);
  111036. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  111037. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  111038. int (*vtab_config)(sqlite3*,int op,...);
  111039. int (*vtab_on_conflict)(sqlite3*);
  111040. /* Version 3.7.16 and later */
  111041. int (*close_v2)(sqlite3*);
  111042. const char *(*db_filename)(sqlite3*,const char*);
  111043. int (*db_readonly)(sqlite3*,const char*);
  111044. int (*db_release_memory)(sqlite3*);
  111045. const char *(*errstr)(int);
  111046. int (*stmt_busy)(sqlite3_stmt*);
  111047. int (*stmt_readonly)(sqlite3_stmt*);
  111048. int (*stricmp)(const char*,const char*);
  111049. int (*uri_boolean)(const char*,const char*,int);
  111050. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  111051. const char *(*uri_parameter)(const char*,const char*);
  111052. char *(*xvsnprintf)(int,char*,const char*,va_list);
  111053. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  111054. /* Version 3.8.7 and later */
  111055. int (*auto_extension)(void(*)(void));
  111056. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  111057. void(*)(void*));
  111058. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  111059. void(*)(void*),unsigned char);
  111060. int (*cancel_auto_extension)(void(*)(void));
  111061. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  111062. void *(*malloc64)(sqlite3_uint64);
  111063. sqlite3_uint64 (*msize)(void*);
  111064. void *(*realloc64)(void*,sqlite3_uint64);
  111065. void (*reset_auto_extension)(void);
  111066. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  111067. void(*)(void*));
  111068. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  111069. void(*)(void*), unsigned char);
  111070. int (*strglob)(const char*,const char*);
  111071. /* Version 3.8.11 and later */
  111072. sqlite3_value *(*value_dup)(const sqlite3_value*);
  111073. void (*value_free)(sqlite3_value*);
  111074. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  111075. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  111076. /* Version 3.9.0 and later */
  111077. unsigned int (*value_subtype)(sqlite3_value*);
  111078. void (*result_subtype)(sqlite3_context*,unsigned int);
  111079. /* Version 3.10.0 and later */
  111080. int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  111081. int (*strlike)(const char*,const char*,unsigned int);
  111082. int (*db_cacheflush)(sqlite3*);
  111083. /* Version 3.12.0 and later */
  111084. int (*system_errno)(sqlite3*);
  111085. /* Version 3.14.0 and later */
  111086. int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
  111087. char *(*expanded_sql)(sqlite3_stmt*);
  111088. /* Version 3.18.0 and later */
  111089. void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
  111090. /* Version 3.20.0 and later */
  111091. int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
  111092. sqlite3_stmt**,const char**);
  111093. int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
  111094. sqlite3_stmt**,const void**);
  111095. int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
  111096. void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
  111097. void *(*value_pointer)(sqlite3_value*,const char*);
  111098. int (*vtab_nochange)(sqlite3_context*);
  111099. int (*value_nochange)(sqlite3_value*);
  111100. const char *(*vtab_collation)(sqlite3_index_info*,int);
  111101. /* Version 3.24.0 and later */
  111102. int (*keyword_count)(void);
  111103. int (*keyword_name)(int,const char**,int*);
  111104. int (*keyword_check)(const char*,int);
  111105. sqlite3_str *(*str_new)(sqlite3*);
  111106. char *(*str_finish)(sqlite3_str*);
  111107. void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
  111108. void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
  111109. void (*str_append)(sqlite3_str*, const char *zIn, int N);
  111110. void (*str_appendall)(sqlite3_str*, const char *zIn);
  111111. void (*str_appendchar)(sqlite3_str*, int N, char C);
  111112. void (*str_reset)(sqlite3_str*);
  111113. int (*str_errcode)(sqlite3_str*);
  111114. int (*str_length)(sqlite3_str*);
  111115. char *(*str_value)(sqlite3_str*);
  111116. /* Version 3.25.0 and later */
  111117. int (*create_window_function)(sqlite3*,const char*,int,int,void*,
  111118. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  111119. void (*xFinal)(sqlite3_context*),
  111120. void (*xValue)(sqlite3_context*),
  111121. void (*xInv)(sqlite3_context*,int,sqlite3_value**),
  111122. void(*xDestroy)(void*));
  111123. /* Version 3.26.0 and later */
  111124. const char *(*normalized_sql)(sqlite3_stmt*);
  111125. };
  111126. /*
  111127. ** This is the function signature used for all extension entry points. It
  111128. ** is also defined in the file "loadext.c".
  111129. */
  111130. typedef int (*sqlite3_loadext_entry)(
  111131. sqlite3 *db, /* Handle to the database. */
  111132. char **pzErrMsg, /* Used to set error string on failure. */
  111133. const sqlite3_api_routines *pThunk /* Extension API function pointers. */
  111134. );
  111135. /*
  111136. ** The following macros redefine the API routines so that they are
  111137. ** redirected through the global sqlite3_api structure.
  111138. **
  111139. ** This header file is also used by the loadext.c source file
  111140. ** (part of the main SQLite library - not an extension) so that
  111141. ** it can get access to the sqlite3_api_routines structure
  111142. ** definition. But the main library does not want to redefine
  111143. ** the API. So the redefinition macros are only valid if the
  111144. ** SQLITE_CORE macros is undefined.
  111145. */
  111146. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  111147. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  111148. #ifndef SQLITE_OMIT_DEPRECATED
  111149. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  111150. #endif
  111151. #define sqlite3_bind_blob sqlite3_api->bind_blob
  111152. #define sqlite3_bind_double sqlite3_api->bind_double
  111153. #define sqlite3_bind_int sqlite3_api->bind_int
  111154. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  111155. #define sqlite3_bind_null sqlite3_api->bind_null
  111156. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  111157. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  111158. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  111159. #define sqlite3_bind_text sqlite3_api->bind_text
  111160. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  111161. #define sqlite3_bind_value sqlite3_api->bind_value
  111162. #define sqlite3_busy_handler sqlite3_api->busy_handler
  111163. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  111164. #define sqlite3_changes sqlite3_api->changes
  111165. #define sqlite3_close sqlite3_api->close
  111166. #define sqlite3_collation_needed sqlite3_api->collation_needed
  111167. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  111168. #define sqlite3_column_blob sqlite3_api->column_blob
  111169. #define sqlite3_column_bytes sqlite3_api->column_bytes
  111170. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  111171. #define sqlite3_column_count sqlite3_api->column_count
  111172. #define sqlite3_column_database_name sqlite3_api->column_database_name
  111173. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  111174. #define sqlite3_column_decltype sqlite3_api->column_decltype
  111175. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  111176. #define sqlite3_column_double sqlite3_api->column_double
  111177. #define sqlite3_column_int sqlite3_api->column_int
  111178. #define sqlite3_column_int64 sqlite3_api->column_int64
  111179. #define sqlite3_column_name sqlite3_api->column_name
  111180. #define sqlite3_column_name16 sqlite3_api->column_name16
  111181. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  111182. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  111183. #define sqlite3_column_table_name sqlite3_api->column_table_name
  111184. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  111185. #define sqlite3_column_text sqlite3_api->column_text
  111186. #define sqlite3_column_text16 sqlite3_api->column_text16
  111187. #define sqlite3_column_type sqlite3_api->column_type
  111188. #define sqlite3_column_value sqlite3_api->column_value
  111189. #define sqlite3_commit_hook sqlite3_api->commit_hook
  111190. #define sqlite3_complete sqlite3_api->complete
  111191. #define sqlite3_complete16 sqlite3_api->complete16
  111192. #define sqlite3_create_collation sqlite3_api->create_collation
  111193. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  111194. #define sqlite3_create_function sqlite3_api->create_function
  111195. #define sqlite3_create_function16 sqlite3_api->create_function16
  111196. #define sqlite3_create_module sqlite3_api->create_module
  111197. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  111198. #define sqlite3_data_count sqlite3_api->data_count
  111199. #define sqlite3_db_handle sqlite3_api->db_handle
  111200. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  111201. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  111202. #define sqlite3_errcode sqlite3_api->errcode
  111203. #define sqlite3_errmsg sqlite3_api->errmsg
  111204. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  111205. #define sqlite3_exec sqlite3_api->exec
  111206. #ifndef SQLITE_OMIT_DEPRECATED
  111207. #define sqlite3_expired sqlite3_api->expired
  111208. #endif
  111209. #define sqlite3_finalize sqlite3_api->finalize
  111210. #define sqlite3_free sqlite3_api->free
  111211. #define sqlite3_free_table sqlite3_api->free_table
  111212. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  111213. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  111214. #define sqlite3_get_table sqlite3_api->get_table
  111215. #ifndef SQLITE_OMIT_DEPRECATED
  111216. #define sqlite3_global_recover sqlite3_api->global_recover
  111217. #endif
  111218. #define sqlite3_interrupt sqlite3_api->interruptx
  111219. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  111220. #define sqlite3_libversion sqlite3_api->libversion
  111221. #define sqlite3_libversion_number sqlite3_api->libversion_number
  111222. #define sqlite3_malloc sqlite3_api->malloc
  111223. #define sqlite3_mprintf sqlite3_api->mprintf
  111224. #define sqlite3_open sqlite3_api->open
  111225. #define sqlite3_open16 sqlite3_api->open16
  111226. #define sqlite3_prepare sqlite3_api->prepare
  111227. #define sqlite3_prepare16 sqlite3_api->prepare16
  111228. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  111229. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  111230. #define sqlite3_profile sqlite3_api->profile
  111231. #define sqlite3_progress_handler sqlite3_api->progress_handler
  111232. #define sqlite3_realloc sqlite3_api->realloc
  111233. #define sqlite3_reset sqlite3_api->reset
  111234. #define sqlite3_result_blob sqlite3_api->result_blob
  111235. #define sqlite3_result_double sqlite3_api->result_double
  111236. #define sqlite3_result_error sqlite3_api->result_error
  111237. #define sqlite3_result_error16 sqlite3_api->result_error16
  111238. #define sqlite3_result_int sqlite3_api->result_int
  111239. #define sqlite3_result_int64 sqlite3_api->result_int64
  111240. #define sqlite3_result_null sqlite3_api->result_null
  111241. #define sqlite3_result_text sqlite3_api->result_text
  111242. #define sqlite3_result_text16 sqlite3_api->result_text16
  111243. #define sqlite3_result_text16be sqlite3_api->result_text16be
  111244. #define sqlite3_result_text16le sqlite3_api->result_text16le
  111245. #define sqlite3_result_value sqlite3_api->result_value
  111246. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  111247. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  111248. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  111249. #define sqlite3_snprintf sqlite3_api->xsnprintf
  111250. #define sqlite3_step sqlite3_api->step
  111251. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  111252. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  111253. #define sqlite3_total_changes sqlite3_api->total_changes
  111254. #define sqlite3_trace sqlite3_api->trace
  111255. #ifndef SQLITE_OMIT_DEPRECATED
  111256. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  111257. #endif
  111258. #define sqlite3_update_hook sqlite3_api->update_hook
  111259. #define sqlite3_user_data sqlite3_api->user_data
  111260. #define sqlite3_value_blob sqlite3_api->value_blob
  111261. #define sqlite3_value_bytes sqlite3_api->value_bytes
  111262. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  111263. #define sqlite3_value_double sqlite3_api->value_double
  111264. #define sqlite3_value_int sqlite3_api->value_int
  111265. #define sqlite3_value_int64 sqlite3_api->value_int64
  111266. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  111267. #define sqlite3_value_text sqlite3_api->value_text
  111268. #define sqlite3_value_text16 sqlite3_api->value_text16
  111269. #define sqlite3_value_text16be sqlite3_api->value_text16be
  111270. #define sqlite3_value_text16le sqlite3_api->value_text16le
  111271. #define sqlite3_value_type sqlite3_api->value_type
  111272. #define sqlite3_vmprintf sqlite3_api->vmprintf
  111273. #define sqlite3_vsnprintf sqlite3_api->xvsnprintf
  111274. #define sqlite3_overload_function sqlite3_api->overload_function
  111275. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  111276. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  111277. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  111278. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  111279. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  111280. #define sqlite3_blob_close sqlite3_api->blob_close
  111281. #define sqlite3_blob_open sqlite3_api->blob_open
  111282. #define sqlite3_blob_read sqlite3_api->blob_read
  111283. #define sqlite3_blob_write sqlite3_api->blob_write
  111284. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  111285. #define sqlite3_file_control sqlite3_api->file_control
  111286. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  111287. #define sqlite3_memory_used sqlite3_api->memory_used
  111288. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  111289. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  111290. #define sqlite3_mutex_free sqlite3_api->mutex_free
  111291. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  111292. #define sqlite3_mutex_try sqlite3_api->mutex_try
  111293. #define sqlite3_open_v2 sqlite3_api->open_v2
  111294. #define sqlite3_release_memory sqlite3_api->release_memory
  111295. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  111296. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  111297. #define sqlite3_sleep sqlite3_api->sleep
  111298. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  111299. #define sqlite3_vfs_find sqlite3_api->vfs_find
  111300. #define sqlite3_vfs_register sqlite3_api->vfs_register
  111301. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  111302. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  111303. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  111304. #define sqlite3_result_error_code sqlite3_api->result_error_code
  111305. #define sqlite3_test_control sqlite3_api->test_control
  111306. #define sqlite3_randomness sqlite3_api->randomness
  111307. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  111308. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  111309. #define sqlite3_limit sqlite3_api->limit
  111310. #define sqlite3_next_stmt sqlite3_api->next_stmt
  111311. #define sqlite3_sql sqlite3_api->sql
  111312. #define sqlite3_status sqlite3_api->status
  111313. #define sqlite3_backup_finish sqlite3_api->backup_finish
  111314. #define sqlite3_backup_init sqlite3_api->backup_init
  111315. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  111316. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  111317. #define sqlite3_backup_step sqlite3_api->backup_step
  111318. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  111319. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  111320. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  111321. #define sqlite3_db_config sqlite3_api->db_config
  111322. #define sqlite3_db_mutex sqlite3_api->db_mutex
  111323. #define sqlite3_db_status sqlite3_api->db_status
  111324. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  111325. #define sqlite3_log sqlite3_api->log
  111326. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  111327. #define sqlite3_sourceid sqlite3_api->sourceid
  111328. #define sqlite3_stmt_status sqlite3_api->stmt_status
  111329. #define sqlite3_strnicmp sqlite3_api->strnicmp
  111330. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  111331. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  111332. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  111333. #define sqlite3_wal_hook sqlite3_api->wal_hook
  111334. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  111335. #define sqlite3_vtab_config sqlite3_api->vtab_config
  111336. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  111337. /* Version 3.7.16 and later */
  111338. #define sqlite3_close_v2 sqlite3_api->close_v2
  111339. #define sqlite3_db_filename sqlite3_api->db_filename
  111340. #define sqlite3_db_readonly sqlite3_api->db_readonly
  111341. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  111342. #define sqlite3_errstr sqlite3_api->errstr
  111343. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  111344. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  111345. #define sqlite3_stricmp sqlite3_api->stricmp
  111346. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  111347. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  111348. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  111349. #define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
  111350. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  111351. /* Version 3.8.7 and later */
  111352. #define sqlite3_auto_extension sqlite3_api->auto_extension
  111353. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  111354. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  111355. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  111356. #define sqlite3_load_extension sqlite3_api->load_extension
  111357. #define sqlite3_malloc64 sqlite3_api->malloc64
  111358. #define sqlite3_msize sqlite3_api->msize
  111359. #define sqlite3_realloc64 sqlite3_api->realloc64
  111360. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  111361. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  111362. #define sqlite3_result_text64 sqlite3_api->result_text64
  111363. #define sqlite3_strglob sqlite3_api->strglob
  111364. /* Version 3.8.11 and later */
  111365. #define sqlite3_value_dup sqlite3_api->value_dup
  111366. #define sqlite3_value_free sqlite3_api->value_free
  111367. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  111368. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  111369. /* Version 3.9.0 and later */
  111370. #define sqlite3_value_subtype sqlite3_api->value_subtype
  111371. #define sqlite3_result_subtype sqlite3_api->result_subtype
  111372. /* Version 3.10.0 and later */
  111373. #define sqlite3_status64 sqlite3_api->status64
  111374. #define sqlite3_strlike sqlite3_api->strlike
  111375. #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
  111376. /* Version 3.12.0 and later */
  111377. #define sqlite3_system_errno sqlite3_api->system_errno
  111378. /* Version 3.14.0 and later */
  111379. #define sqlite3_trace_v2 sqlite3_api->trace_v2
  111380. #define sqlite3_expanded_sql sqlite3_api->expanded_sql
  111381. /* Version 3.18.0 and later */
  111382. #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
  111383. /* Version 3.20.0 and later */
  111384. #define sqlite3_prepare_v3 sqlite3_api->prepare_v3
  111385. #define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
  111386. #define sqlite3_bind_pointer sqlite3_api->bind_pointer
  111387. #define sqlite3_result_pointer sqlite3_api->result_pointer
  111388. #define sqlite3_value_pointer sqlite3_api->value_pointer
  111389. /* Version 3.22.0 and later */
  111390. #define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
  111391. #define sqlite3_value_nochange sqlite3_api->value_nochange
  111392. #define sqlite3_vtab_collation sqlite3_api->vtab_collation
  111393. /* Version 3.24.0 and later */
  111394. #define sqlite3_keyword_count sqlite3_api->keyword_count
  111395. #define sqlite3_keyword_name sqlite3_api->keyword_name
  111396. #define sqlite3_keyword_check sqlite3_api->keyword_check
  111397. #define sqlite3_str_new sqlite3_api->str_new
  111398. #define sqlite3_str_finish sqlite3_api->str_finish
  111399. #define sqlite3_str_appendf sqlite3_api->str_appendf
  111400. #define sqlite3_str_vappendf sqlite3_api->str_vappendf
  111401. #define sqlite3_str_append sqlite3_api->str_append
  111402. #define sqlite3_str_appendall sqlite3_api->str_appendall
  111403. #define sqlite3_str_appendchar sqlite3_api->str_appendchar
  111404. #define sqlite3_str_reset sqlite3_api->str_reset
  111405. #define sqlite3_str_errcode sqlite3_api->str_errcode
  111406. #define sqlite3_str_length sqlite3_api->str_length
  111407. #define sqlite3_str_value sqlite3_api->str_value
  111408. /* Version 3.25.0 and later */
  111409. #define sqlite3_create_window_function sqlite3_api->create_window_function
  111410. /* Version 3.26.0 and later */
  111411. #define sqlite3_normalized_sql sqlite3_api->normalized_sql
  111412. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  111413. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  111414. /* This case when the file really is being compiled as a loadable
  111415. ** extension */
  111416. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  111417. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  111418. # define SQLITE_EXTENSION_INIT3 \
  111419. extern const sqlite3_api_routines *sqlite3_api;
  111420. #else
  111421. /* This case when the file is being statically linked into the
  111422. ** application */
  111423. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  111424. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  111425. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  111426. #endif
  111427. #endif /* SQLITE3EXT_H */
  111428. /************** End of sqlite3ext.h ******************************************/
  111429. /************** Continuing where we left off in loadext.c ********************/
  111430. /* #include "sqliteInt.h" */
  111431. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  111432. /*
  111433. ** Some API routines are omitted when various features are
  111434. ** excluded from a build of SQLite. Substitute a NULL pointer
  111435. ** for any missing APIs.
  111436. */
  111437. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  111438. # define sqlite3_column_database_name 0
  111439. # define sqlite3_column_database_name16 0
  111440. # define sqlite3_column_table_name 0
  111441. # define sqlite3_column_table_name16 0
  111442. # define sqlite3_column_origin_name 0
  111443. # define sqlite3_column_origin_name16 0
  111444. #endif
  111445. #ifdef SQLITE_OMIT_AUTHORIZATION
  111446. # define sqlite3_set_authorizer 0
  111447. #endif
  111448. #ifdef SQLITE_OMIT_UTF16
  111449. # define sqlite3_bind_text16 0
  111450. # define sqlite3_collation_needed16 0
  111451. # define sqlite3_column_decltype16 0
  111452. # define sqlite3_column_name16 0
  111453. # define sqlite3_column_text16 0
  111454. # define sqlite3_complete16 0
  111455. # define sqlite3_create_collation16 0
  111456. # define sqlite3_create_function16 0
  111457. # define sqlite3_errmsg16 0
  111458. # define sqlite3_open16 0
  111459. # define sqlite3_prepare16 0
  111460. # define sqlite3_prepare16_v2 0
  111461. # define sqlite3_prepare16_v3 0
  111462. # define sqlite3_result_error16 0
  111463. # define sqlite3_result_text16 0
  111464. # define sqlite3_result_text16be 0
  111465. # define sqlite3_result_text16le 0
  111466. # define sqlite3_value_text16 0
  111467. # define sqlite3_value_text16be 0
  111468. # define sqlite3_value_text16le 0
  111469. # define sqlite3_column_database_name16 0
  111470. # define sqlite3_column_table_name16 0
  111471. # define sqlite3_column_origin_name16 0
  111472. #endif
  111473. #ifdef SQLITE_OMIT_COMPLETE
  111474. # define sqlite3_complete 0
  111475. # define sqlite3_complete16 0
  111476. #endif
  111477. #ifdef SQLITE_OMIT_DECLTYPE
  111478. # define sqlite3_column_decltype16 0
  111479. # define sqlite3_column_decltype 0
  111480. #endif
  111481. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  111482. # define sqlite3_progress_handler 0
  111483. #endif
  111484. #ifdef SQLITE_OMIT_VIRTUALTABLE
  111485. # define sqlite3_create_module 0
  111486. # define sqlite3_create_module_v2 0
  111487. # define sqlite3_declare_vtab 0
  111488. # define sqlite3_vtab_config 0
  111489. # define sqlite3_vtab_on_conflict 0
  111490. # define sqlite3_vtab_collation 0
  111491. #endif
  111492. #ifdef SQLITE_OMIT_SHARED_CACHE
  111493. # define sqlite3_enable_shared_cache 0
  111494. #endif
  111495. #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
  111496. # define sqlite3_profile 0
  111497. # define sqlite3_trace 0
  111498. #endif
  111499. #ifdef SQLITE_OMIT_GET_TABLE
  111500. # define sqlite3_free_table 0
  111501. # define sqlite3_get_table 0
  111502. #endif
  111503. #ifdef SQLITE_OMIT_INCRBLOB
  111504. #define sqlite3_bind_zeroblob 0
  111505. #define sqlite3_blob_bytes 0
  111506. #define sqlite3_blob_close 0
  111507. #define sqlite3_blob_open 0
  111508. #define sqlite3_blob_read 0
  111509. #define sqlite3_blob_write 0
  111510. #define sqlite3_blob_reopen 0
  111511. #endif
  111512. #if defined(SQLITE_OMIT_TRACE)
  111513. # define sqlite3_trace_v2 0
  111514. #endif
  111515. /*
  111516. ** The following structure contains pointers to all SQLite API routines.
  111517. ** A pointer to this structure is passed into extensions when they are
  111518. ** loaded so that the extension can make calls back into the SQLite
  111519. ** library.
  111520. **
  111521. ** When adding new APIs, add them to the bottom of this structure
  111522. ** in order to preserve backwards compatibility.
  111523. **
  111524. ** Extensions that use newer APIs should first call the
  111525. ** sqlite3_libversion_number() to make sure that the API they
  111526. ** intend to use is supported by the library. Extensions should
  111527. ** also check to make sure that the pointer to the function is
  111528. ** not NULL before calling it.
  111529. */
  111530. static const sqlite3_api_routines sqlite3Apis = {
  111531. sqlite3_aggregate_context,
  111532. #ifndef SQLITE_OMIT_DEPRECATED
  111533. sqlite3_aggregate_count,
  111534. #else
  111535. 0,
  111536. #endif
  111537. sqlite3_bind_blob,
  111538. sqlite3_bind_double,
  111539. sqlite3_bind_int,
  111540. sqlite3_bind_int64,
  111541. sqlite3_bind_null,
  111542. sqlite3_bind_parameter_count,
  111543. sqlite3_bind_parameter_index,
  111544. sqlite3_bind_parameter_name,
  111545. sqlite3_bind_text,
  111546. sqlite3_bind_text16,
  111547. sqlite3_bind_value,
  111548. sqlite3_busy_handler,
  111549. sqlite3_busy_timeout,
  111550. sqlite3_changes,
  111551. sqlite3_close,
  111552. sqlite3_collation_needed,
  111553. sqlite3_collation_needed16,
  111554. sqlite3_column_blob,
  111555. sqlite3_column_bytes,
  111556. sqlite3_column_bytes16,
  111557. sqlite3_column_count,
  111558. sqlite3_column_database_name,
  111559. sqlite3_column_database_name16,
  111560. sqlite3_column_decltype,
  111561. sqlite3_column_decltype16,
  111562. sqlite3_column_double,
  111563. sqlite3_column_int,
  111564. sqlite3_column_int64,
  111565. sqlite3_column_name,
  111566. sqlite3_column_name16,
  111567. sqlite3_column_origin_name,
  111568. sqlite3_column_origin_name16,
  111569. sqlite3_column_table_name,
  111570. sqlite3_column_table_name16,
  111571. sqlite3_column_text,
  111572. sqlite3_column_text16,
  111573. sqlite3_column_type,
  111574. sqlite3_column_value,
  111575. sqlite3_commit_hook,
  111576. sqlite3_complete,
  111577. sqlite3_complete16,
  111578. sqlite3_create_collation,
  111579. sqlite3_create_collation16,
  111580. sqlite3_create_function,
  111581. sqlite3_create_function16,
  111582. sqlite3_create_module,
  111583. sqlite3_data_count,
  111584. sqlite3_db_handle,
  111585. sqlite3_declare_vtab,
  111586. sqlite3_enable_shared_cache,
  111587. sqlite3_errcode,
  111588. sqlite3_errmsg,
  111589. sqlite3_errmsg16,
  111590. sqlite3_exec,
  111591. #ifndef SQLITE_OMIT_DEPRECATED
  111592. sqlite3_expired,
  111593. #else
  111594. 0,
  111595. #endif
  111596. sqlite3_finalize,
  111597. sqlite3_free,
  111598. sqlite3_free_table,
  111599. sqlite3_get_autocommit,
  111600. sqlite3_get_auxdata,
  111601. sqlite3_get_table,
  111602. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  111603. sqlite3_interrupt,
  111604. sqlite3_last_insert_rowid,
  111605. sqlite3_libversion,
  111606. sqlite3_libversion_number,
  111607. sqlite3_malloc,
  111608. sqlite3_mprintf,
  111609. sqlite3_open,
  111610. sqlite3_open16,
  111611. sqlite3_prepare,
  111612. sqlite3_prepare16,
  111613. sqlite3_profile,
  111614. sqlite3_progress_handler,
  111615. sqlite3_realloc,
  111616. sqlite3_reset,
  111617. sqlite3_result_blob,
  111618. sqlite3_result_double,
  111619. sqlite3_result_error,
  111620. sqlite3_result_error16,
  111621. sqlite3_result_int,
  111622. sqlite3_result_int64,
  111623. sqlite3_result_null,
  111624. sqlite3_result_text,
  111625. sqlite3_result_text16,
  111626. sqlite3_result_text16be,
  111627. sqlite3_result_text16le,
  111628. sqlite3_result_value,
  111629. sqlite3_rollback_hook,
  111630. sqlite3_set_authorizer,
  111631. sqlite3_set_auxdata,
  111632. sqlite3_snprintf,
  111633. sqlite3_step,
  111634. sqlite3_table_column_metadata,
  111635. #ifndef SQLITE_OMIT_DEPRECATED
  111636. sqlite3_thread_cleanup,
  111637. #else
  111638. 0,
  111639. #endif
  111640. sqlite3_total_changes,
  111641. sqlite3_trace,
  111642. #ifndef SQLITE_OMIT_DEPRECATED
  111643. sqlite3_transfer_bindings,
  111644. #else
  111645. 0,
  111646. #endif
  111647. sqlite3_update_hook,
  111648. sqlite3_user_data,
  111649. sqlite3_value_blob,
  111650. sqlite3_value_bytes,
  111651. sqlite3_value_bytes16,
  111652. sqlite3_value_double,
  111653. sqlite3_value_int,
  111654. sqlite3_value_int64,
  111655. sqlite3_value_numeric_type,
  111656. sqlite3_value_text,
  111657. sqlite3_value_text16,
  111658. sqlite3_value_text16be,
  111659. sqlite3_value_text16le,
  111660. sqlite3_value_type,
  111661. sqlite3_vmprintf,
  111662. /*
  111663. ** The original API set ends here. All extensions can call any
  111664. ** of the APIs above provided that the pointer is not NULL. But
  111665. ** before calling APIs that follow, extension should check the
  111666. ** sqlite3_libversion_number() to make sure they are dealing with
  111667. ** a library that is new enough to support that API.
  111668. *************************************************************************
  111669. */
  111670. sqlite3_overload_function,
  111671. /*
  111672. ** Added after 3.3.13
  111673. */
  111674. sqlite3_prepare_v2,
  111675. sqlite3_prepare16_v2,
  111676. sqlite3_clear_bindings,
  111677. /*
  111678. ** Added for 3.4.1
  111679. */
  111680. sqlite3_create_module_v2,
  111681. /*
  111682. ** Added for 3.5.0
  111683. */
  111684. sqlite3_bind_zeroblob,
  111685. sqlite3_blob_bytes,
  111686. sqlite3_blob_close,
  111687. sqlite3_blob_open,
  111688. sqlite3_blob_read,
  111689. sqlite3_blob_write,
  111690. sqlite3_create_collation_v2,
  111691. sqlite3_file_control,
  111692. sqlite3_memory_highwater,
  111693. sqlite3_memory_used,
  111694. #ifdef SQLITE_MUTEX_OMIT
  111695. 0,
  111696. 0,
  111697. 0,
  111698. 0,
  111699. 0,
  111700. #else
  111701. sqlite3_mutex_alloc,
  111702. sqlite3_mutex_enter,
  111703. sqlite3_mutex_free,
  111704. sqlite3_mutex_leave,
  111705. sqlite3_mutex_try,
  111706. #endif
  111707. sqlite3_open_v2,
  111708. sqlite3_release_memory,
  111709. sqlite3_result_error_nomem,
  111710. sqlite3_result_error_toobig,
  111711. sqlite3_sleep,
  111712. sqlite3_soft_heap_limit,
  111713. sqlite3_vfs_find,
  111714. sqlite3_vfs_register,
  111715. sqlite3_vfs_unregister,
  111716. /*
  111717. ** Added for 3.5.8
  111718. */
  111719. sqlite3_threadsafe,
  111720. sqlite3_result_zeroblob,
  111721. sqlite3_result_error_code,
  111722. sqlite3_test_control,
  111723. sqlite3_randomness,
  111724. sqlite3_context_db_handle,
  111725. /*
  111726. ** Added for 3.6.0
  111727. */
  111728. sqlite3_extended_result_codes,
  111729. sqlite3_limit,
  111730. sqlite3_next_stmt,
  111731. sqlite3_sql,
  111732. sqlite3_status,
  111733. /*
  111734. ** Added for 3.7.4
  111735. */
  111736. sqlite3_backup_finish,
  111737. sqlite3_backup_init,
  111738. sqlite3_backup_pagecount,
  111739. sqlite3_backup_remaining,
  111740. sqlite3_backup_step,
  111741. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  111742. sqlite3_compileoption_get,
  111743. sqlite3_compileoption_used,
  111744. #else
  111745. 0,
  111746. 0,
  111747. #endif
  111748. sqlite3_create_function_v2,
  111749. sqlite3_db_config,
  111750. sqlite3_db_mutex,
  111751. sqlite3_db_status,
  111752. sqlite3_extended_errcode,
  111753. sqlite3_log,
  111754. sqlite3_soft_heap_limit64,
  111755. sqlite3_sourceid,
  111756. sqlite3_stmt_status,
  111757. sqlite3_strnicmp,
  111758. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  111759. sqlite3_unlock_notify,
  111760. #else
  111761. 0,
  111762. #endif
  111763. #ifndef SQLITE_OMIT_WAL
  111764. sqlite3_wal_autocheckpoint,
  111765. sqlite3_wal_checkpoint,
  111766. sqlite3_wal_hook,
  111767. #else
  111768. 0,
  111769. 0,
  111770. 0,
  111771. #endif
  111772. sqlite3_blob_reopen,
  111773. sqlite3_vtab_config,
  111774. sqlite3_vtab_on_conflict,
  111775. sqlite3_close_v2,
  111776. sqlite3_db_filename,
  111777. sqlite3_db_readonly,
  111778. sqlite3_db_release_memory,
  111779. sqlite3_errstr,
  111780. sqlite3_stmt_busy,
  111781. sqlite3_stmt_readonly,
  111782. sqlite3_stricmp,
  111783. sqlite3_uri_boolean,
  111784. sqlite3_uri_int64,
  111785. sqlite3_uri_parameter,
  111786. sqlite3_vsnprintf,
  111787. sqlite3_wal_checkpoint_v2,
  111788. /* Version 3.8.7 and later */
  111789. sqlite3_auto_extension,
  111790. sqlite3_bind_blob64,
  111791. sqlite3_bind_text64,
  111792. sqlite3_cancel_auto_extension,
  111793. sqlite3_load_extension,
  111794. sqlite3_malloc64,
  111795. sqlite3_msize,
  111796. sqlite3_realloc64,
  111797. sqlite3_reset_auto_extension,
  111798. sqlite3_result_blob64,
  111799. sqlite3_result_text64,
  111800. sqlite3_strglob,
  111801. /* Version 3.8.11 and later */
  111802. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  111803. sqlite3_value_free,
  111804. sqlite3_result_zeroblob64,
  111805. sqlite3_bind_zeroblob64,
  111806. /* Version 3.9.0 and later */
  111807. sqlite3_value_subtype,
  111808. sqlite3_result_subtype,
  111809. /* Version 3.10.0 and later */
  111810. sqlite3_status64,
  111811. sqlite3_strlike,
  111812. sqlite3_db_cacheflush,
  111813. /* Version 3.12.0 and later */
  111814. sqlite3_system_errno,
  111815. /* Version 3.14.0 and later */
  111816. sqlite3_trace_v2,
  111817. sqlite3_expanded_sql,
  111818. /* Version 3.18.0 and later */
  111819. sqlite3_set_last_insert_rowid,
  111820. /* Version 3.20.0 and later */
  111821. sqlite3_prepare_v3,
  111822. sqlite3_prepare16_v3,
  111823. sqlite3_bind_pointer,
  111824. sqlite3_result_pointer,
  111825. sqlite3_value_pointer,
  111826. /* Version 3.22.0 and later */
  111827. sqlite3_vtab_nochange,
  111828. sqlite3_value_nochange,
  111829. sqlite3_vtab_collation,
  111830. /* Version 3.24.0 and later */
  111831. sqlite3_keyword_count,
  111832. sqlite3_keyword_name,
  111833. sqlite3_keyword_check,
  111834. sqlite3_str_new,
  111835. sqlite3_str_finish,
  111836. sqlite3_str_appendf,
  111837. sqlite3_str_vappendf,
  111838. sqlite3_str_append,
  111839. sqlite3_str_appendall,
  111840. sqlite3_str_appendchar,
  111841. sqlite3_str_reset,
  111842. sqlite3_str_errcode,
  111843. sqlite3_str_length,
  111844. sqlite3_str_value,
  111845. /* Version 3.25.0 and later */
  111846. sqlite3_create_window_function,
  111847. /* Version 3.26.0 and later */
  111848. #ifdef SQLITE_ENABLE_NORMALIZE
  111849. sqlite3_normalized_sql
  111850. #else
  111851. 0
  111852. #endif
  111853. };
  111854. /*
  111855. ** Attempt to load an SQLite extension library contained in the file
  111856. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  111857. ** default entry point name (sqlite3_extension_init) is used. Use
  111858. ** of the default name is recommended.
  111859. **
  111860. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  111861. **
  111862. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  111863. ** error message text. The calling function should free this memory
  111864. ** by calling sqlite3DbFree(db, ).
  111865. */
  111866. static int sqlite3LoadExtension(
  111867. sqlite3 *db, /* Load the extension into this database connection */
  111868. const char *zFile, /* Name of the shared library containing extension */
  111869. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  111870. char **pzErrMsg /* Put error message here if not 0 */
  111871. ){
  111872. sqlite3_vfs *pVfs = db->pVfs;
  111873. void *handle;
  111874. sqlite3_loadext_entry xInit;
  111875. char *zErrmsg = 0;
  111876. const char *zEntry;
  111877. char *zAltEntry = 0;
  111878. void **aHandle;
  111879. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  111880. int ii;
  111881. int rc;
  111882. /* Shared library endings to try if zFile cannot be loaded as written */
  111883. static const char *azEndings[] = {
  111884. #if SQLITE_OS_WIN
  111885. "dll"
  111886. #elif defined(__APPLE__)
  111887. "dylib"
  111888. #else
  111889. "so"
  111890. #endif
  111891. };
  111892. if( pzErrMsg ) *pzErrMsg = 0;
  111893. /* Ticket #1863. To avoid a creating security problems for older
  111894. ** applications that relink against newer versions of SQLite, the
  111895. ** ability to run load_extension is turned off by default. One
  111896. ** must call either sqlite3_enable_load_extension(db) or
  111897. ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
  111898. ** to turn on extension loading.
  111899. */
  111900. if( (db->flags & SQLITE_LoadExtension)==0 ){
  111901. if( pzErrMsg ){
  111902. *pzErrMsg = sqlite3_mprintf("not authorized");
  111903. }
  111904. return SQLITE_ERROR;
  111905. }
  111906. zEntry = zProc ? zProc : "sqlite3_extension_init";
  111907. handle = sqlite3OsDlOpen(pVfs, zFile);
  111908. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  111909. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  111910. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  111911. if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
  111912. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  111913. sqlite3_free(zAltFile);
  111914. }
  111915. #endif
  111916. if( handle==0 ){
  111917. if( pzErrMsg ){
  111918. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  111919. if( zErrmsg ){
  111920. sqlite3_snprintf(nMsg, zErrmsg,
  111921. "unable to open shared library [%s]", zFile);
  111922. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  111923. }
  111924. }
  111925. return SQLITE_ERROR;
  111926. }
  111927. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  111928. /* If no entry point was specified and the default legacy
  111929. ** entry point name "sqlite3_extension_init" was not found, then
  111930. ** construct an entry point name "sqlite3_X_init" where the X is
  111931. ** replaced by the lowercase value of every ASCII alphabetic
  111932. ** character in the filename after the last "/" upto the first ".",
  111933. ** and eliding the first three characters if they are "lib".
  111934. ** Examples:
  111935. **
  111936. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  111937. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  111938. */
  111939. if( xInit==0 && zProc==0 ){
  111940. int iFile, iEntry, c;
  111941. int ncFile = sqlite3Strlen30(zFile);
  111942. zAltEntry = sqlite3_malloc64(ncFile+30);
  111943. if( zAltEntry==0 ){
  111944. sqlite3OsDlClose(pVfs, handle);
  111945. return SQLITE_NOMEM_BKPT;
  111946. }
  111947. memcpy(zAltEntry, "sqlite3_", 8);
  111948. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  111949. iFile++;
  111950. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  111951. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  111952. if( sqlite3Isalpha(c) ){
  111953. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  111954. }
  111955. }
  111956. memcpy(zAltEntry+iEntry, "_init", 6);
  111957. zEntry = zAltEntry;
  111958. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  111959. }
  111960. if( xInit==0 ){
  111961. if( pzErrMsg ){
  111962. nMsg += sqlite3Strlen30(zEntry);
  111963. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  111964. if( zErrmsg ){
  111965. sqlite3_snprintf(nMsg, zErrmsg,
  111966. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  111967. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  111968. }
  111969. }
  111970. sqlite3OsDlClose(pVfs, handle);
  111971. sqlite3_free(zAltEntry);
  111972. return SQLITE_ERROR;
  111973. }
  111974. sqlite3_free(zAltEntry);
  111975. rc = xInit(db, &zErrmsg, &sqlite3Apis);
  111976. if( rc ){
  111977. if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
  111978. if( pzErrMsg ){
  111979. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  111980. }
  111981. sqlite3_free(zErrmsg);
  111982. sqlite3OsDlClose(pVfs, handle);
  111983. return SQLITE_ERROR;
  111984. }
  111985. /* Append the new shared library handle to the db->aExtension array. */
  111986. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  111987. if( aHandle==0 ){
  111988. return SQLITE_NOMEM_BKPT;
  111989. }
  111990. if( db->nExtension>0 ){
  111991. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  111992. }
  111993. sqlite3DbFree(db, db->aExtension);
  111994. db->aExtension = aHandle;
  111995. db->aExtension[db->nExtension++] = handle;
  111996. return SQLITE_OK;
  111997. }
  111998. SQLITE_API int sqlite3_load_extension(
  111999. sqlite3 *db, /* Load the extension into this database connection */
  112000. const char *zFile, /* Name of the shared library containing extension */
  112001. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  112002. char **pzErrMsg /* Put error message here if not 0 */
  112003. ){
  112004. int rc;
  112005. sqlite3_mutex_enter(db->mutex);
  112006. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  112007. rc = sqlite3ApiExit(db, rc);
  112008. sqlite3_mutex_leave(db->mutex);
  112009. return rc;
  112010. }
  112011. /*
  112012. ** Call this routine when the database connection is closing in order
  112013. ** to clean up loaded extensions
  112014. */
  112015. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  112016. int i;
  112017. assert( sqlite3_mutex_held(db->mutex) );
  112018. for(i=0; i<db->nExtension; i++){
  112019. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  112020. }
  112021. sqlite3DbFree(db, db->aExtension);
  112022. }
  112023. /*
  112024. ** Enable or disable extension loading. Extension loading is disabled by
  112025. ** default so as not to open security holes in older applications.
  112026. */
  112027. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  112028. sqlite3_mutex_enter(db->mutex);
  112029. if( onoff ){
  112030. db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
  112031. }else{
  112032. db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
  112033. }
  112034. sqlite3_mutex_leave(db->mutex);
  112035. return SQLITE_OK;
  112036. }
  112037. #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  112038. /*
  112039. ** The following object holds the list of automatically loaded
  112040. ** extensions.
  112041. **
  112042. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  112043. ** mutex must be held while accessing this list.
  112044. */
  112045. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  112046. static SQLITE_WSD struct sqlite3AutoExtList {
  112047. u32 nExt; /* Number of entries in aExt[] */
  112048. void (**aExt)(void); /* Pointers to the extension init functions */
  112049. } sqlite3Autoext = { 0, 0 };
  112050. /* The "wsdAutoext" macro will resolve to the autoextension
  112051. ** state vector. If writable static data is unsupported on the target,
  112052. ** we have to locate the state vector at run-time. In the more common
  112053. ** case where writable static data is supported, wsdStat can refer directly
  112054. ** to the "sqlite3Autoext" state vector declared above.
  112055. */
  112056. #ifdef SQLITE_OMIT_WSD
  112057. # define wsdAutoextInit \
  112058. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  112059. # define wsdAutoext x[0]
  112060. #else
  112061. # define wsdAutoextInit
  112062. # define wsdAutoext sqlite3Autoext
  112063. #endif
  112064. /*
  112065. ** Register a statically linked extension that is automatically
  112066. ** loaded by every new database connection.
  112067. */
  112068. SQLITE_API int sqlite3_auto_extension(
  112069. void (*xInit)(void)
  112070. ){
  112071. int rc = SQLITE_OK;
  112072. #ifndef SQLITE_OMIT_AUTOINIT
  112073. rc = sqlite3_initialize();
  112074. if( rc ){
  112075. return rc;
  112076. }else
  112077. #endif
  112078. {
  112079. u32 i;
  112080. #if SQLITE_THREADSAFE
  112081. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  112082. #endif
  112083. wsdAutoextInit;
  112084. sqlite3_mutex_enter(mutex);
  112085. for(i=0; i<wsdAutoext.nExt; i++){
  112086. if( wsdAutoext.aExt[i]==xInit ) break;
  112087. }
  112088. if( i==wsdAutoext.nExt ){
  112089. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  112090. void (**aNew)(void);
  112091. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  112092. if( aNew==0 ){
  112093. rc = SQLITE_NOMEM_BKPT;
  112094. }else{
  112095. wsdAutoext.aExt = aNew;
  112096. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  112097. wsdAutoext.nExt++;
  112098. }
  112099. }
  112100. sqlite3_mutex_leave(mutex);
  112101. assert( (rc&0xff)==rc );
  112102. return rc;
  112103. }
  112104. }
  112105. /*
  112106. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  112107. ** set of routines that is invoked for each new database connection, if it
  112108. ** is currently on the list. If xInit is not on the list, then this
  112109. ** routine is a no-op.
  112110. **
  112111. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  112112. ** was not on the list.
  112113. */
  112114. SQLITE_API int sqlite3_cancel_auto_extension(
  112115. void (*xInit)(void)
  112116. ){
  112117. #if SQLITE_THREADSAFE
  112118. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  112119. #endif
  112120. int i;
  112121. int n = 0;
  112122. wsdAutoextInit;
  112123. sqlite3_mutex_enter(mutex);
  112124. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  112125. if( wsdAutoext.aExt[i]==xInit ){
  112126. wsdAutoext.nExt--;
  112127. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  112128. n++;
  112129. break;
  112130. }
  112131. }
  112132. sqlite3_mutex_leave(mutex);
  112133. return n;
  112134. }
  112135. /*
  112136. ** Reset the automatic extension loading mechanism.
  112137. */
  112138. SQLITE_API void sqlite3_reset_auto_extension(void){
  112139. #ifndef SQLITE_OMIT_AUTOINIT
  112140. if( sqlite3_initialize()==SQLITE_OK )
  112141. #endif
  112142. {
  112143. #if SQLITE_THREADSAFE
  112144. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  112145. #endif
  112146. wsdAutoextInit;
  112147. sqlite3_mutex_enter(mutex);
  112148. sqlite3_free(wsdAutoext.aExt);
  112149. wsdAutoext.aExt = 0;
  112150. wsdAutoext.nExt = 0;
  112151. sqlite3_mutex_leave(mutex);
  112152. }
  112153. }
  112154. /*
  112155. ** Load all automatic extensions.
  112156. **
  112157. ** If anything goes wrong, set an error in the database connection.
  112158. */
  112159. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  112160. u32 i;
  112161. int go = 1;
  112162. int rc;
  112163. sqlite3_loadext_entry xInit;
  112164. wsdAutoextInit;
  112165. if( wsdAutoext.nExt==0 ){
  112166. /* Common case: early out without every having to acquire a mutex */
  112167. return;
  112168. }
  112169. for(i=0; go; i++){
  112170. char *zErrmsg;
  112171. #if SQLITE_THREADSAFE
  112172. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  112173. #endif
  112174. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  112175. const sqlite3_api_routines *pThunk = 0;
  112176. #else
  112177. const sqlite3_api_routines *pThunk = &sqlite3Apis;
  112178. #endif
  112179. sqlite3_mutex_enter(mutex);
  112180. if( i>=wsdAutoext.nExt ){
  112181. xInit = 0;
  112182. go = 0;
  112183. }else{
  112184. xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
  112185. }
  112186. sqlite3_mutex_leave(mutex);
  112187. zErrmsg = 0;
  112188. if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
  112189. sqlite3ErrorWithMsg(db, rc,
  112190. "automatic extension loading failed: %s", zErrmsg);
  112191. go = 0;
  112192. }
  112193. sqlite3_free(zErrmsg);
  112194. }
  112195. }
  112196. /************** End of loadext.c *********************************************/
  112197. /************** Begin file pragma.c ******************************************/
  112198. /*
  112199. ** 2003 April 6
  112200. **
  112201. ** The author disclaims copyright to this source code. In place of
  112202. ** a legal notice, here is a blessing:
  112203. **
  112204. ** May you do good and not evil.
  112205. ** May you find forgiveness for yourself and forgive others.
  112206. ** May you share freely, never taking more than you give.
  112207. **
  112208. *************************************************************************
  112209. ** This file contains code used to implement the PRAGMA command.
  112210. */
  112211. /* #include "sqliteInt.h" */
  112212. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  112213. # if defined(__APPLE__)
  112214. # define SQLITE_ENABLE_LOCKING_STYLE 1
  112215. # else
  112216. # define SQLITE_ENABLE_LOCKING_STYLE 0
  112217. # endif
  112218. #endif
  112219. /***************************************************************************
  112220. ** The "pragma.h" include file is an automatically generated file that
  112221. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  112222. ** object. This ensures that the aPragmaName[] table is arranged in
  112223. ** lexicographical order to facility a binary search of the pragma name.
  112224. ** Do not edit pragma.h directly. Edit and rerun the script in at
  112225. ** ../tool/mkpragmatab.tcl. */
  112226. /************** Include pragma.h in the middle of pragma.c *******************/
  112227. /************** Begin file pragma.h ******************************************/
  112228. /* DO NOT EDIT!
  112229. ** This file is automatically generated by the script at
  112230. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  112231. ** that script and rerun it.
  112232. */
  112233. /* The various pragma types */
  112234. #define PragTyp_HEADER_VALUE 0
  112235. #define PragTyp_AUTO_VACUUM 1
  112236. #define PragTyp_FLAG 2
  112237. #define PragTyp_BUSY_TIMEOUT 3
  112238. #define PragTyp_CACHE_SIZE 4
  112239. #define PragTyp_CACHE_SPILL 5
  112240. #define PragTyp_CASE_SENSITIVE_LIKE 6
  112241. #define PragTyp_COLLATION_LIST 7
  112242. #define PragTyp_COMPILE_OPTIONS 8
  112243. #define PragTyp_DATA_STORE_DIRECTORY 9
  112244. #define PragTyp_DATABASE_LIST 10
  112245. #define PragTyp_DEFAULT_CACHE_SIZE 11
  112246. #define PragTyp_ENCODING 12
  112247. #define PragTyp_FOREIGN_KEY_CHECK 13
  112248. #define PragTyp_FOREIGN_KEY_LIST 14
  112249. #define PragTyp_FUNCTION_LIST 15
  112250. #define PragTyp_INCREMENTAL_VACUUM 16
  112251. #define PragTyp_INDEX_INFO 17
  112252. #define PragTyp_INDEX_LIST 18
  112253. #define PragTyp_INTEGRITY_CHECK 19
  112254. #define PragTyp_JOURNAL_MODE 20
  112255. #define PragTyp_JOURNAL_SIZE_LIMIT 21
  112256. #define PragTyp_LOCK_PROXY_FILE 22
  112257. #define PragTyp_LOCKING_MODE 23
  112258. #define PragTyp_PAGE_COUNT 24
  112259. #define PragTyp_MMAP_SIZE 25
  112260. #define PragTyp_MODULE_LIST 26
  112261. #define PragTyp_OPTIMIZE 27
  112262. #define PragTyp_PAGE_SIZE 28
  112263. #define PragTyp_PRAGMA_LIST 29
  112264. #define PragTyp_SECURE_DELETE 30
  112265. #define PragTyp_SHRINK_MEMORY 31
  112266. #define PragTyp_SOFT_HEAP_LIMIT 32
  112267. #define PragTyp_SYNCHRONOUS 33
  112268. #define PragTyp_TABLE_INFO 34
  112269. #define PragTyp_TEMP_STORE 35
  112270. #define PragTyp_TEMP_STORE_DIRECTORY 36
  112271. #define PragTyp_THREADS 37
  112272. #define PragTyp_WAL_AUTOCHECKPOINT 38
  112273. #define PragTyp_WAL_CHECKPOINT 39
  112274. #define PragTyp_ACTIVATE_EXTENSIONS 40
  112275. #define PragTyp_HEXKEY 41
  112276. #define PragTyp_KEY 42
  112277. #define PragTyp_LOCK_STATUS 43
  112278. #define PragTyp_PARSER_TRACE 44
  112279. #define PragTyp_STATS 45
  112280. /* Property flags associated with various pragma. */
  112281. #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
  112282. #define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */
  112283. #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
  112284. #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
  112285. #define PragFlg_Result0 0x10 /* Acts as query when no argument */
  112286. #define PragFlg_Result1 0x20 /* Acts as query when has one argument */
  112287. #define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */
  112288. #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
  112289. /* Names of columns for pragmas that return multi-column result
  112290. ** or that return single-column results where the name of the
  112291. ** result column is different from the name of the pragma
  112292. */
  112293. static const char *const pragCName[] = {
  112294. /* 0 */ "id", /* Used by: foreign_key_list */
  112295. /* 1 */ "seq",
  112296. /* 2 */ "table",
  112297. /* 3 */ "from",
  112298. /* 4 */ "to",
  112299. /* 5 */ "on_update",
  112300. /* 6 */ "on_delete",
  112301. /* 7 */ "match",
  112302. /* 8 */ "cid", /* Used by: table_xinfo */
  112303. /* 9 */ "name",
  112304. /* 10 */ "type",
  112305. /* 11 */ "notnull",
  112306. /* 12 */ "dflt_value",
  112307. /* 13 */ "pk",
  112308. /* 14 */ "hidden",
  112309. /* table_info reuses 8 */
  112310. /* 15 */ "seqno", /* Used by: index_xinfo */
  112311. /* 16 */ "cid",
  112312. /* 17 */ "name",
  112313. /* 18 */ "desc",
  112314. /* 19 */ "coll",
  112315. /* 20 */ "key",
  112316. /* 21 */ "tbl", /* Used by: stats */
  112317. /* 22 */ "idx",
  112318. /* 23 */ "wdth",
  112319. /* 24 */ "hght",
  112320. /* 25 */ "flgs",
  112321. /* 26 */ "seq", /* Used by: index_list */
  112322. /* 27 */ "name",
  112323. /* 28 */ "unique",
  112324. /* 29 */ "origin",
  112325. /* 30 */ "partial",
  112326. /* 31 */ "table", /* Used by: foreign_key_check */
  112327. /* 32 */ "rowid",
  112328. /* 33 */ "parent",
  112329. /* 34 */ "fkid",
  112330. /* index_info reuses 15 */
  112331. /* 35 */ "seq", /* Used by: database_list */
  112332. /* 36 */ "name",
  112333. /* 37 */ "file",
  112334. /* 38 */ "busy", /* Used by: wal_checkpoint */
  112335. /* 39 */ "log",
  112336. /* 40 */ "checkpointed",
  112337. /* 41 */ "name", /* Used by: function_list */
  112338. /* 42 */ "builtin",
  112339. /* collation_list reuses 26 */
  112340. /* 43 */ "database", /* Used by: lock_status */
  112341. /* 44 */ "status",
  112342. /* 45 */ "cache_size", /* Used by: default_cache_size */
  112343. /* module_list pragma_list reuses 9 */
  112344. /* 46 */ "timeout", /* Used by: busy_timeout */
  112345. };
  112346. /* Definitions of all built-in pragmas */
  112347. typedef struct PragmaName {
  112348. const char *const zName; /* Name of pragma */
  112349. u8 ePragTyp; /* PragTyp_XXX value */
  112350. u8 mPragFlg; /* Zero or more PragFlg_XXX values */
  112351. u8 iPragCName; /* Start of column names in pragCName[] */
  112352. u8 nPragCName; /* Num of col names. 0 means use pragma name */
  112353. u64 iArg; /* Extra argument */
  112354. } PragmaName;
  112355. static const PragmaName aPragmaName[] = {
  112356. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  112357. {/* zName: */ "activate_extensions",
  112358. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  112359. /* ePragFlg: */ 0,
  112360. /* ColNames: */ 0, 0,
  112361. /* iArg: */ 0 },
  112362. #endif
  112363. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  112364. {/* zName: */ "application_id",
  112365. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  112366. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  112367. /* ColNames: */ 0, 0,
  112368. /* iArg: */ BTREE_APPLICATION_ID },
  112369. #endif
  112370. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  112371. {/* zName: */ "auto_vacuum",
  112372. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  112373. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  112374. /* ColNames: */ 0, 0,
  112375. /* iArg: */ 0 },
  112376. #endif
  112377. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112378. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  112379. {/* zName: */ "automatic_index",
  112380. /* ePragTyp: */ PragTyp_FLAG,
  112381. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112382. /* ColNames: */ 0, 0,
  112383. /* iArg: */ SQLITE_AutoIndex },
  112384. #endif
  112385. #endif
  112386. {/* zName: */ "busy_timeout",
  112387. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  112388. /* ePragFlg: */ PragFlg_Result0,
  112389. /* ColNames: */ 46, 1,
  112390. /* iArg: */ 0 },
  112391. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  112392. {/* zName: */ "cache_size",
  112393. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  112394. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  112395. /* ColNames: */ 0, 0,
  112396. /* iArg: */ 0 },
  112397. #endif
  112398. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112399. {/* zName: */ "cache_spill",
  112400. /* ePragTyp: */ PragTyp_CACHE_SPILL,
  112401. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  112402. /* ColNames: */ 0, 0,
  112403. /* iArg: */ 0 },
  112404. #endif
  112405. {/* zName: */ "case_sensitive_like",
  112406. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  112407. /* ePragFlg: */ PragFlg_NoColumns,
  112408. /* ColNames: */ 0, 0,
  112409. /* iArg: */ 0 },
  112410. {/* zName: */ "cell_size_check",
  112411. /* ePragTyp: */ PragTyp_FLAG,
  112412. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112413. /* ColNames: */ 0, 0,
  112414. /* iArg: */ SQLITE_CellSizeCk },
  112415. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112416. {/* zName: */ "checkpoint_fullfsync",
  112417. /* ePragTyp: */ PragTyp_FLAG,
  112418. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112419. /* ColNames: */ 0, 0,
  112420. /* iArg: */ SQLITE_CkptFullFSync },
  112421. #endif
  112422. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  112423. {/* zName: */ "collation_list",
  112424. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  112425. /* ePragFlg: */ PragFlg_Result0,
  112426. /* ColNames: */ 26, 2,
  112427. /* iArg: */ 0 },
  112428. #endif
  112429. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  112430. {/* zName: */ "compile_options",
  112431. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  112432. /* ePragFlg: */ PragFlg_Result0,
  112433. /* ColNames: */ 0, 0,
  112434. /* iArg: */ 0 },
  112435. #endif
  112436. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112437. {/* zName: */ "count_changes",
  112438. /* ePragTyp: */ PragTyp_FLAG,
  112439. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112440. /* ColNames: */ 0, 0,
  112441. /* iArg: */ SQLITE_CountRows },
  112442. #endif
  112443. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  112444. {/* zName: */ "data_store_directory",
  112445. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  112446. /* ePragFlg: */ PragFlg_NoColumns1,
  112447. /* ColNames: */ 0, 0,
  112448. /* iArg: */ 0 },
  112449. #endif
  112450. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  112451. {/* zName: */ "data_version",
  112452. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  112453. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  112454. /* ColNames: */ 0, 0,
  112455. /* iArg: */ BTREE_DATA_VERSION },
  112456. #endif
  112457. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  112458. {/* zName: */ "database_list",
  112459. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  112460. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  112461. /* ColNames: */ 35, 3,
  112462. /* iArg: */ 0 },
  112463. #endif
  112464. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  112465. {/* zName: */ "default_cache_size",
  112466. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  112467. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  112468. /* ColNames: */ 45, 1,
  112469. /* iArg: */ 0 },
  112470. #endif
  112471. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112472. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  112473. {/* zName: */ "defer_foreign_keys",
  112474. /* ePragTyp: */ PragTyp_FLAG,
  112475. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112476. /* ColNames: */ 0, 0,
  112477. /* iArg: */ SQLITE_DeferFKs },
  112478. #endif
  112479. #endif
  112480. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112481. {/* zName: */ "empty_result_callbacks",
  112482. /* ePragTyp: */ PragTyp_FLAG,
  112483. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112484. /* ColNames: */ 0, 0,
  112485. /* iArg: */ SQLITE_NullCallback },
  112486. #endif
  112487. #if !defined(SQLITE_OMIT_UTF16)
  112488. {/* zName: */ "encoding",
  112489. /* ePragTyp: */ PragTyp_ENCODING,
  112490. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112491. /* ColNames: */ 0, 0,
  112492. /* iArg: */ 0 },
  112493. #endif
  112494. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  112495. {/* zName: */ "foreign_key_check",
  112496. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  112497. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  112498. /* ColNames: */ 31, 4,
  112499. /* iArg: */ 0 },
  112500. #endif
  112501. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  112502. {/* zName: */ "foreign_key_list",
  112503. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  112504. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  112505. /* ColNames: */ 0, 8,
  112506. /* iArg: */ 0 },
  112507. #endif
  112508. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112509. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  112510. {/* zName: */ "foreign_keys",
  112511. /* ePragTyp: */ PragTyp_FLAG,
  112512. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112513. /* ColNames: */ 0, 0,
  112514. /* iArg: */ SQLITE_ForeignKeys },
  112515. #endif
  112516. #endif
  112517. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  112518. {/* zName: */ "freelist_count",
  112519. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  112520. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  112521. /* ColNames: */ 0, 0,
  112522. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  112523. #endif
  112524. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112525. {/* zName: */ "full_column_names",
  112526. /* ePragTyp: */ PragTyp_FLAG,
  112527. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112528. /* ColNames: */ 0, 0,
  112529. /* iArg: */ SQLITE_FullColNames },
  112530. {/* zName: */ "fullfsync",
  112531. /* ePragTyp: */ PragTyp_FLAG,
  112532. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112533. /* ColNames: */ 0, 0,
  112534. /* iArg: */ SQLITE_FullFSync },
  112535. #endif
  112536. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  112537. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  112538. {/* zName: */ "function_list",
  112539. /* ePragTyp: */ PragTyp_FUNCTION_LIST,
  112540. /* ePragFlg: */ PragFlg_Result0,
  112541. /* ColNames: */ 41, 2,
  112542. /* iArg: */ 0 },
  112543. #endif
  112544. #endif
  112545. #if defined(SQLITE_HAS_CODEC)
  112546. {/* zName: */ "hexkey",
  112547. /* ePragTyp: */ PragTyp_HEXKEY,
  112548. /* ePragFlg: */ 0,
  112549. /* ColNames: */ 0, 0,
  112550. /* iArg: */ 2 },
  112551. {/* zName: */ "hexrekey",
  112552. /* ePragTyp: */ PragTyp_HEXKEY,
  112553. /* ePragFlg: */ 0,
  112554. /* ColNames: */ 0, 0,
  112555. /* iArg: */ 3 },
  112556. #endif
  112557. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112558. #if !defined(SQLITE_OMIT_CHECK)
  112559. {/* zName: */ "ignore_check_constraints",
  112560. /* ePragTyp: */ PragTyp_FLAG,
  112561. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112562. /* ColNames: */ 0, 0,
  112563. /* iArg: */ SQLITE_IgnoreChecks },
  112564. #endif
  112565. #endif
  112566. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  112567. {/* zName: */ "incremental_vacuum",
  112568. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  112569. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns,
  112570. /* ColNames: */ 0, 0,
  112571. /* iArg: */ 0 },
  112572. #endif
  112573. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  112574. {/* zName: */ "index_info",
  112575. /* ePragTyp: */ PragTyp_INDEX_INFO,
  112576. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  112577. /* ColNames: */ 15, 3,
  112578. /* iArg: */ 0 },
  112579. {/* zName: */ "index_list",
  112580. /* ePragTyp: */ PragTyp_INDEX_LIST,
  112581. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  112582. /* ColNames: */ 26, 5,
  112583. /* iArg: */ 0 },
  112584. {/* zName: */ "index_xinfo",
  112585. /* ePragTyp: */ PragTyp_INDEX_INFO,
  112586. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  112587. /* ColNames: */ 15, 6,
  112588. /* iArg: */ 1 },
  112589. #endif
  112590. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  112591. {/* zName: */ "integrity_check",
  112592. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  112593. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  112594. /* ColNames: */ 0, 0,
  112595. /* iArg: */ 0 },
  112596. #endif
  112597. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  112598. {/* zName: */ "journal_mode",
  112599. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  112600. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  112601. /* ColNames: */ 0, 0,
  112602. /* iArg: */ 0 },
  112603. {/* zName: */ "journal_size_limit",
  112604. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  112605. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  112606. /* ColNames: */ 0, 0,
  112607. /* iArg: */ 0 },
  112608. #endif
  112609. #if defined(SQLITE_HAS_CODEC)
  112610. {/* zName: */ "key",
  112611. /* ePragTyp: */ PragTyp_KEY,
  112612. /* ePragFlg: */ 0,
  112613. /* ColNames: */ 0, 0,
  112614. /* iArg: */ 0 },
  112615. #endif
  112616. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112617. {/* zName: */ "legacy_alter_table",
  112618. /* ePragTyp: */ PragTyp_FLAG,
  112619. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112620. /* ColNames: */ 0, 0,
  112621. /* iArg: */ SQLITE_LegacyAlter },
  112622. {/* zName: */ "legacy_file_format",
  112623. /* ePragTyp: */ PragTyp_FLAG,
  112624. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112625. /* ColNames: */ 0, 0,
  112626. /* iArg: */ SQLITE_LegacyFileFmt },
  112627. #endif
  112628. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  112629. {/* zName: */ "lock_proxy_file",
  112630. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  112631. /* ePragFlg: */ PragFlg_NoColumns1,
  112632. /* ColNames: */ 0, 0,
  112633. /* iArg: */ 0 },
  112634. #endif
  112635. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  112636. {/* zName: */ "lock_status",
  112637. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  112638. /* ePragFlg: */ PragFlg_Result0,
  112639. /* ColNames: */ 43, 2,
  112640. /* iArg: */ 0 },
  112641. #endif
  112642. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  112643. {/* zName: */ "locking_mode",
  112644. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  112645. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  112646. /* ColNames: */ 0, 0,
  112647. /* iArg: */ 0 },
  112648. {/* zName: */ "max_page_count",
  112649. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  112650. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  112651. /* ColNames: */ 0, 0,
  112652. /* iArg: */ 0 },
  112653. {/* zName: */ "mmap_size",
  112654. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  112655. /* ePragFlg: */ 0,
  112656. /* ColNames: */ 0, 0,
  112657. /* iArg: */ 0 },
  112658. #endif
  112659. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  112660. #if !defined(SQLITE_OMIT_VIRTUALTABLE)
  112661. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  112662. {/* zName: */ "module_list",
  112663. /* ePragTyp: */ PragTyp_MODULE_LIST,
  112664. /* ePragFlg: */ PragFlg_Result0,
  112665. /* ColNames: */ 9, 1,
  112666. /* iArg: */ 0 },
  112667. #endif
  112668. #endif
  112669. #endif
  112670. {/* zName: */ "optimize",
  112671. /* ePragTyp: */ PragTyp_OPTIMIZE,
  112672. /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema,
  112673. /* ColNames: */ 0, 0,
  112674. /* iArg: */ 0 },
  112675. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  112676. {/* zName: */ "page_count",
  112677. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  112678. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  112679. /* ColNames: */ 0, 0,
  112680. /* iArg: */ 0 },
  112681. {/* zName: */ "page_size",
  112682. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  112683. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  112684. /* ColNames: */ 0, 0,
  112685. /* iArg: */ 0 },
  112686. #endif
  112687. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
  112688. {/* zName: */ "parser_trace",
  112689. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  112690. /* ePragFlg: */ 0,
  112691. /* ColNames: */ 0, 0,
  112692. /* iArg: */ 0 },
  112693. #endif
  112694. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  112695. {/* zName: */ "pragma_list",
  112696. /* ePragTyp: */ PragTyp_PRAGMA_LIST,
  112697. /* ePragFlg: */ PragFlg_Result0,
  112698. /* ColNames: */ 9, 1,
  112699. /* iArg: */ 0 },
  112700. #endif
  112701. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112702. {/* zName: */ "query_only",
  112703. /* ePragTyp: */ PragTyp_FLAG,
  112704. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112705. /* ColNames: */ 0, 0,
  112706. /* iArg: */ SQLITE_QueryOnly },
  112707. #endif
  112708. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  112709. {/* zName: */ "quick_check",
  112710. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  112711. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  112712. /* ColNames: */ 0, 0,
  112713. /* iArg: */ 0 },
  112714. #endif
  112715. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112716. {/* zName: */ "read_uncommitted",
  112717. /* ePragTyp: */ PragTyp_FLAG,
  112718. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112719. /* ColNames: */ 0, 0,
  112720. /* iArg: */ SQLITE_ReadUncommit },
  112721. {/* zName: */ "recursive_triggers",
  112722. /* ePragTyp: */ PragTyp_FLAG,
  112723. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112724. /* ColNames: */ 0, 0,
  112725. /* iArg: */ SQLITE_RecTriggers },
  112726. #endif
  112727. #if defined(SQLITE_HAS_CODEC)
  112728. {/* zName: */ "rekey",
  112729. /* ePragTyp: */ PragTyp_KEY,
  112730. /* ePragFlg: */ 0,
  112731. /* ColNames: */ 0, 0,
  112732. /* iArg: */ 1 },
  112733. #endif
  112734. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112735. {/* zName: */ "reverse_unordered_selects",
  112736. /* ePragTyp: */ PragTyp_FLAG,
  112737. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112738. /* ColNames: */ 0, 0,
  112739. /* iArg: */ SQLITE_ReverseOrder },
  112740. #endif
  112741. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  112742. {/* zName: */ "schema_version",
  112743. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  112744. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  112745. /* ColNames: */ 0, 0,
  112746. /* iArg: */ BTREE_SCHEMA_VERSION },
  112747. #endif
  112748. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  112749. {/* zName: */ "secure_delete",
  112750. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  112751. /* ePragFlg: */ PragFlg_Result0,
  112752. /* ColNames: */ 0, 0,
  112753. /* iArg: */ 0 },
  112754. #endif
  112755. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112756. {/* zName: */ "short_column_names",
  112757. /* ePragTyp: */ PragTyp_FLAG,
  112758. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112759. /* ColNames: */ 0, 0,
  112760. /* iArg: */ SQLITE_ShortColNames },
  112761. #endif
  112762. {/* zName: */ "shrink_memory",
  112763. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  112764. /* ePragFlg: */ PragFlg_NoColumns,
  112765. /* ColNames: */ 0, 0,
  112766. /* iArg: */ 0 },
  112767. {/* zName: */ "soft_heap_limit",
  112768. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  112769. /* ePragFlg: */ PragFlg_Result0,
  112770. /* ColNames: */ 0, 0,
  112771. /* iArg: */ 0 },
  112772. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112773. #if defined(SQLITE_DEBUG)
  112774. {/* zName: */ "sql_trace",
  112775. /* ePragTyp: */ PragTyp_FLAG,
  112776. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112777. /* ColNames: */ 0, 0,
  112778. /* iArg: */ SQLITE_SqlTrace },
  112779. #endif
  112780. #endif
  112781. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
  112782. {/* zName: */ "stats",
  112783. /* ePragTyp: */ PragTyp_STATS,
  112784. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  112785. /* ColNames: */ 21, 5,
  112786. /* iArg: */ 0 },
  112787. #endif
  112788. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  112789. {/* zName: */ "synchronous",
  112790. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  112791. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  112792. /* ColNames: */ 0, 0,
  112793. /* iArg: */ 0 },
  112794. #endif
  112795. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  112796. {/* zName: */ "table_info",
  112797. /* ePragTyp: */ PragTyp_TABLE_INFO,
  112798. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  112799. /* ColNames: */ 8, 6,
  112800. /* iArg: */ 0 },
  112801. {/* zName: */ "table_xinfo",
  112802. /* ePragTyp: */ PragTyp_TABLE_INFO,
  112803. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  112804. /* ColNames: */ 8, 7,
  112805. /* iArg: */ 1 },
  112806. #endif
  112807. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  112808. {/* zName: */ "temp_store",
  112809. /* ePragTyp: */ PragTyp_TEMP_STORE,
  112810. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112811. /* ColNames: */ 0, 0,
  112812. /* iArg: */ 0 },
  112813. {/* zName: */ "temp_store_directory",
  112814. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  112815. /* ePragFlg: */ PragFlg_NoColumns1,
  112816. /* ColNames: */ 0, 0,
  112817. /* iArg: */ 0 },
  112818. #endif
  112819. #if defined(SQLITE_HAS_CODEC)
  112820. {/* zName: */ "textkey",
  112821. /* ePragTyp: */ PragTyp_KEY,
  112822. /* ePragFlg: */ 0,
  112823. /* ColNames: */ 0, 0,
  112824. /* iArg: */ 4 },
  112825. {/* zName: */ "textrekey",
  112826. /* ePragTyp: */ PragTyp_KEY,
  112827. /* ePragFlg: */ 0,
  112828. /* ColNames: */ 0, 0,
  112829. /* iArg: */ 5 },
  112830. #endif
  112831. {/* zName: */ "threads",
  112832. /* ePragTyp: */ PragTyp_THREADS,
  112833. /* ePragFlg: */ PragFlg_Result0,
  112834. /* ColNames: */ 0, 0,
  112835. /* iArg: */ 0 },
  112836. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  112837. {/* zName: */ "user_version",
  112838. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  112839. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  112840. /* ColNames: */ 0, 0,
  112841. /* iArg: */ BTREE_USER_VERSION },
  112842. #endif
  112843. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112844. #if defined(SQLITE_DEBUG)
  112845. {/* zName: */ "vdbe_addoptrace",
  112846. /* ePragTyp: */ PragTyp_FLAG,
  112847. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112848. /* ColNames: */ 0, 0,
  112849. /* iArg: */ SQLITE_VdbeAddopTrace },
  112850. {/* zName: */ "vdbe_debug",
  112851. /* ePragTyp: */ PragTyp_FLAG,
  112852. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112853. /* ColNames: */ 0, 0,
  112854. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  112855. {/* zName: */ "vdbe_eqp",
  112856. /* ePragTyp: */ PragTyp_FLAG,
  112857. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112858. /* ColNames: */ 0, 0,
  112859. /* iArg: */ SQLITE_VdbeEQP },
  112860. {/* zName: */ "vdbe_listing",
  112861. /* ePragTyp: */ PragTyp_FLAG,
  112862. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112863. /* ColNames: */ 0, 0,
  112864. /* iArg: */ SQLITE_VdbeListing },
  112865. {/* zName: */ "vdbe_trace",
  112866. /* ePragTyp: */ PragTyp_FLAG,
  112867. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112868. /* ColNames: */ 0, 0,
  112869. /* iArg: */ SQLITE_VdbeTrace },
  112870. #endif
  112871. #endif
  112872. #if !defined(SQLITE_OMIT_WAL)
  112873. {/* zName: */ "wal_autocheckpoint",
  112874. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  112875. /* ePragFlg: */ 0,
  112876. /* ColNames: */ 0, 0,
  112877. /* iArg: */ 0 },
  112878. {/* zName: */ "wal_checkpoint",
  112879. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  112880. /* ePragFlg: */ PragFlg_NeedSchema,
  112881. /* ColNames: */ 38, 3,
  112882. /* iArg: */ 0 },
  112883. #endif
  112884. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  112885. {/* zName: */ "writable_schema",
  112886. /* ePragTyp: */ PragTyp_FLAG,
  112887. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  112888. /* ColNames: */ 0, 0,
  112889. /* iArg: */ SQLITE_WriteSchema|SQLITE_NoSchemaError },
  112890. #endif
  112891. };
  112892. /* Number of pragmas: 62 on by default, 81 total. */
  112893. /************** End of pragma.h **********************************************/
  112894. /************** Continuing where we left off in pragma.c *********************/
  112895. /*
  112896. ** Interpret the given string as a safety level. Return 0 for OFF,
  112897. ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
  112898. ** unrecognized string argument. The FULL and EXTRA option is disallowed
  112899. ** if the omitFull parameter it 1.
  112900. **
  112901. ** Note that the values returned are one less that the values that
  112902. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  112903. ** to support legacy SQL code. The safety level used to be boolean
  112904. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  112905. */
  112906. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  112907. /* 123456789 123456789 123 */
  112908. static const char zText[] = "onoffalseyestruextrafull";
  112909. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
  112910. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
  112911. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
  112912. /* on no off false yes true extra full */
  112913. int i, n;
  112914. if( sqlite3Isdigit(*z) ){
  112915. return (u8)sqlite3Atoi(z);
  112916. }
  112917. n = sqlite3Strlen30(z);
  112918. for(i=0; i<ArraySize(iLength); i++){
  112919. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
  112920. && (!omitFull || iValue[i]<=1)
  112921. ){
  112922. return iValue[i];
  112923. }
  112924. }
  112925. return dflt;
  112926. }
  112927. /*
  112928. ** Interpret the given string as a boolean value.
  112929. */
  112930. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  112931. return getSafetyLevel(z,1,dflt)!=0;
  112932. }
  112933. /* The sqlite3GetBoolean() function is used by other modules but the
  112934. ** remainder of this file is specific to PRAGMA processing. So omit
  112935. ** the rest of the file if PRAGMAs are omitted from the build.
  112936. */
  112937. #if !defined(SQLITE_OMIT_PRAGMA)
  112938. /*
  112939. ** Interpret the given string as a locking mode value.
  112940. */
  112941. static int getLockingMode(const char *z){
  112942. if( z ){
  112943. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  112944. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  112945. }
  112946. return PAGER_LOCKINGMODE_QUERY;
  112947. }
  112948. #ifndef SQLITE_OMIT_AUTOVACUUM
  112949. /*
  112950. ** Interpret the given string as an auto-vacuum mode value.
  112951. **
  112952. ** The following strings, "none", "full" and "incremental" are
  112953. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  112954. */
  112955. static int getAutoVacuum(const char *z){
  112956. int i;
  112957. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  112958. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  112959. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  112960. i = sqlite3Atoi(z);
  112961. return (u8)((i>=0&&i<=2)?i:0);
  112962. }
  112963. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  112964. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  112965. /*
  112966. ** Interpret the given string as a temp db location. Return 1 for file
  112967. ** backed temporary databases, 2 for the Red-Black tree in memory database
  112968. ** and 0 to use the compile-time default.
  112969. */
  112970. static int getTempStore(const char *z){
  112971. if( z[0]>='0' && z[0]<='2' ){
  112972. return z[0] - '0';
  112973. }else if( sqlite3StrICmp(z, "file")==0 ){
  112974. return 1;
  112975. }else if( sqlite3StrICmp(z, "memory")==0 ){
  112976. return 2;
  112977. }else{
  112978. return 0;
  112979. }
  112980. }
  112981. #endif /* SQLITE_PAGER_PRAGMAS */
  112982. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  112983. /*
  112984. ** Invalidate temp storage, either when the temp storage is changed
  112985. ** from default, or when 'file' and the temp_store_directory has changed
  112986. */
  112987. static int invalidateTempStorage(Parse *pParse){
  112988. sqlite3 *db = pParse->db;
  112989. if( db->aDb[1].pBt!=0 ){
  112990. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  112991. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  112992. "from within a transaction");
  112993. return SQLITE_ERROR;
  112994. }
  112995. sqlite3BtreeClose(db->aDb[1].pBt);
  112996. db->aDb[1].pBt = 0;
  112997. sqlite3ResetAllSchemasOfConnection(db);
  112998. }
  112999. return SQLITE_OK;
  113000. }
  113001. #endif /* SQLITE_PAGER_PRAGMAS */
  113002. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  113003. /*
  113004. ** If the TEMP database is open, close it and mark the database schema
  113005. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  113006. ** or DEFAULT_TEMP_STORE pragmas.
  113007. */
  113008. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  113009. int ts = getTempStore(zStorageType);
  113010. sqlite3 *db = pParse->db;
  113011. if( db->temp_store==ts ) return SQLITE_OK;
  113012. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  113013. return SQLITE_ERROR;
  113014. }
  113015. db->temp_store = (u8)ts;
  113016. return SQLITE_OK;
  113017. }
  113018. #endif /* SQLITE_PAGER_PRAGMAS */
  113019. /*
  113020. ** Set result column names for a pragma.
  113021. */
  113022. static void setPragmaResultColumnNames(
  113023. Vdbe *v, /* The query under construction */
  113024. const PragmaName *pPragma /* The pragma */
  113025. ){
  113026. u8 n = pPragma->nPragCName;
  113027. sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
  113028. if( n==0 ){
  113029. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
  113030. }else{
  113031. int i, j;
  113032. for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
  113033. sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
  113034. }
  113035. }
  113036. }
  113037. /*
  113038. ** Generate code to return a single integer value.
  113039. */
  113040. static void returnSingleInt(Vdbe *v, i64 value){
  113041. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  113042. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  113043. }
  113044. /*
  113045. ** Generate code to return a single text value.
  113046. */
  113047. static void returnSingleText(
  113048. Vdbe *v, /* Prepared statement under construction */
  113049. const char *zValue /* Value to be returned */
  113050. ){
  113051. if( zValue ){
  113052. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  113053. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  113054. }
  113055. }
  113056. /*
  113057. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  113058. ** set these values for all pagers.
  113059. */
  113060. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  113061. static void setAllPagerFlags(sqlite3 *db){
  113062. if( db->autoCommit ){
  113063. Db *pDb = db->aDb;
  113064. int n = db->nDb;
  113065. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  113066. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  113067. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  113068. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  113069. == PAGER_FLAGS_MASK );
  113070. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  113071. while( (n--) > 0 ){
  113072. if( pDb->pBt ){
  113073. sqlite3BtreeSetPagerFlags(pDb->pBt,
  113074. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  113075. }
  113076. pDb++;
  113077. }
  113078. }
  113079. }
  113080. #else
  113081. # define setAllPagerFlags(X) /* no-op */
  113082. #endif
  113083. /*
  113084. ** Return a human-readable name for a constraint resolution action.
  113085. */
  113086. #ifndef SQLITE_OMIT_FOREIGN_KEY
  113087. static const char *actionName(u8 action){
  113088. const char *zName;
  113089. switch( action ){
  113090. case OE_SetNull: zName = "SET NULL"; break;
  113091. case OE_SetDflt: zName = "SET DEFAULT"; break;
  113092. case OE_Cascade: zName = "CASCADE"; break;
  113093. case OE_Restrict: zName = "RESTRICT"; break;
  113094. default: zName = "NO ACTION";
  113095. assert( action==OE_None ); break;
  113096. }
  113097. return zName;
  113098. }
  113099. #endif
  113100. /*
  113101. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  113102. ** defined in pager.h. This function returns the associated lowercase
  113103. ** journal-mode name.
  113104. */
  113105. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  113106. static char * const azModeName[] = {
  113107. "delete", "persist", "off", "truncate", "memory"
  113108. #ifndef SQLITE_OMIT_WAL
  113109. , "wal"
  113110. #endif
  113111. };
  113112. assert( PAGER_JOURNALMODE_DELETE==0 );
  113113. assert( PAGER_JOURNALMODE_PERSIST==1 );
  113114. assert( PAGER_JOURNALMODE_OFF==2 );
  113115. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  113116. assert( PAGER_JOURNALMODE_MEMORY==4 );
  113117. assert( PAGER_JOURNALMODE_WAL==5 );
  113118. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  113119. if( eMode==ArraySize(azModeName) ) return 0;
  113120. return azModeName[eMode];
  113121. }
  113122. /*
  113123. ** Locate a pragma in the aPragmaName[] array.
  113124. */
  113125. static const PragmaName *pragmaLocate(const char *zName){
  113126. int upr, lwr, mid = 0, rc;
  113127. lwr = 0;
  113128. upr = ArraySize(aPragmaName)-1;
  113129. while( lwr<=upr ){
  113130. mid = (lwr+upr)/2;
  113131. rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
  113132. if( rc==0 ) break;
  113133. if( rc<0 ){
  113134. upr = mid - 1;
  113135. }else{
  113136. lwr = mid + 1;
  113137. }
  113138. }
  113139. return lwr>upr ? 0 : &aPragmaName[mid];
  113140. }
  113141. /*
  113142. ** Helper subroutine for PRAGMA integrity_check:
  113143. **
  113144. ** Generate code to output a single-column result row with a value of the
  113145. ** string held in register 3. Decrement the result count in register 1
  113146. ** and halt if the maximum number of result rows have been issued.
  113147. */
  113148. static int integrityCheckResultRow(Vdbe *v){
  113149. int addr;
  113150. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  113151. addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
  113152. VdbeCoverage(v);
  113153. sqlite3VdbeAddOp0(v, OP_Halt);
  113154. return addr;
  113155. }
  113156. /*
  113157. ** Process a pragma statement.
  113158. **
  113159. ** Pragmas are of this form:
  113160. **
  113161. ** PRAGMA [schema.]id [= value]
  113162. **
  113163. ** The identifier might also be a string. The value is a string, and
  113164. ** identifier, or a number. If minusFlag is true, then the value is
  113165. ** a number that was preceded by a minus sign.
  113166. **
  113167. ** If the left side is "database.id" then pId1 is the database name
  113168. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  113169. ** id and pId2 is any empty string.
  113170. */
  113171. SQLITE_PRIVATE void sqlite3Pragma(
  113172. Parse *pParse,
  113173. Token *pId1, /* First part of [schema.]id field */
  113174. Token *pId2, /* Second part of [schema.]id field, or NULL */
  113175. Token *pValue, /* Token for <value>, or NULL */
  113176. int minusFlag /* True if a '-' sign preceded <value> */
  113177. ){
  113178. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  113179. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  113180. const char *zDb = 0; /* The database name */
  113181. Token *pId; /* Pointer to <id> token */
  113182. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  113183. int iDb; /* Database index for <database> */
  113184. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  113185. sqlite3 *db = pParse->db; /* The database connection */
  113186. Db *pDb; /* The specific database being pragmaed */
  113187. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  113188. const PragmaName *pPragma; /* The pragma */
  113189. if( v==0 ) return;
  113190. sqlite3VdbeRunOnlyOnce(v);
  113191. pParse->nMem = 2;
  113192. /* Interpret the [schema.] part of the pragma statement. iDb is the
  113193. ** index of the database this pragma is being applied to in db.aDb[]. */
  113194. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  113195. if( iDb<0 ) return;
  113196. pDb = &db->aDb[iDb];
  113197. /* If the temp database has been explicitly named as part of the
  113198. ** pragma, make sure it is open.
  113199. */
  113200. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  113201. return;
  113202. }
  113203. zLeft = sqlite3NameFromToken(db, pId);
  113204. if( !zLeft ) return;
  113205. if( minusFlag ){
  113206. zRight = sqlite3MPrintf(db, "-%T", pValue);
  113207. }else{
  113208. zRight = sqlite3NameFromToken(db, pValue);
  113209. }
  113210. assert( pId2 );
  113211. zDb = pId2->n>0 ? pDb->zDbSName : 0;
  113212. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  113213. goto pragma_out;
  113214. }
  113215. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  113216. ** connection. If it returns SQLITE_OK, then assume that the VFS
  113217. ** handled the pragma and generate a no-op prepared statement.
  113218. **
  113219. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  113220. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  113221. ** object corresponding to the database file to which the pragma
  113222. ** statement refers.
  113223. **
  113224. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  113225. ** file control is an array of pointers to strings (char**) in which the
  113226. ** second element of the array is the name of the pragma and the third
  113227. ** element is the argument to the pragma or NULL if the pragma has no
  113228. ** argument.
  113229. */
  113230. aFcntl[0] = 0;
  113231. aFcntl[1] = zLeft;
  113232. aFcntl[2] = zRight;
  113233. aFcntl[3] = 0;
  113234. db->busyHandler.nBusy = 0;
  113235. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  113236. if( rc==SQLITE_OK ){
  113237. sqlite3VdbeSetNumCols(v, 1);
  113238. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
  113239. returnSingleText(v, aFcntl[0]);
  113240. sqlite3_free(aFcntl[0]);
  113241. goto pragma_out;
  113242. }
  113243. if( rc!=SQLITE_NOTFOUND ){
  113244. if( aFcntl[0] ){
  113245. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  113246. sqlite3_free(aFcntl[0]);
  113247. }
  113248. pParse->nErr++;
  113249. pParse->rc = rc;
  113250. goto pragma_out;
  113251. }
  113252. /* Locate the pragma in the lookup table */
  113253. pPragma = pragmaLocate(zLeft);
  113254. if( pPragma==0 ) goto pragma_out;
  113255. /* Make sure the database schema is loaded if the pragma requires that */
  113256. if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
  113257. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  113258. }
  113259. /* Register the result column names for pragmas that return results */
  113260. if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
  113261. && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
  113262. ){
  113263. setPragmaResultColumnNames(v, pPragma);
  113264. }
  113265. /* Jump to the appropriate pragma handler */
  113266. switch( pPragma->ePragTyp ){
  113267. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  113268. /*
  113269. ** PRAGMA [schema.]default_cache_size
  113270. ** PRAGMA [schema.]default_cache_size=N
  113271. **
  113272. ** The first form reports the current persistent setting for the
  113273. ** page cache size. The value returned is the maximum number of
  113274. ** pages in the page cache. The second form sets both the current
  113275. ** page cache size value and the persistent page cache size value
  113276. ** stored in the database file.
  113277. **
  113278. ** Older versions of SQLite would set the default cache size to a
  113279. ** negative number to indicate synchronous=OFF. These days, synchronous
  113280. ** is always on by default regardless of the sign of the default cache
  113281. ** size. But continue to take the absolute value of the default cache
  113282. ** size of historical compatibility.
  113283. */
  113284. case PragTyp_DEFAULT_CACHE_SIZE: {
  113285. static const int iLn = VDBE_OFFSET_LINENO(2);
  113286. static const VdbeOpList getCacheSize[] = {
  113287. { OP_Transaction, 0, 0, 0}, /* 0 */
  113288. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  113289. { OP_IfPos, 1, 8, 0},
  113290. { OP_Integer, 0, 2, 0},
  113291. { OP_Subtract, 1, 2, 1},
  113292. { OP_IfPos, 1, 8, 0},
  113293. { OP_Integer, 0, 1, 0}, /* 6 */
  113294. { OP_Noop, 0, 0, 0},
  113295. { OP_ResultRow, 1, 1, 0},
  113296. };
  113297. VdbeOp *aOp;
  113298. sqlite3VdbeUsesBtree(v, iDb);
  113299. if( !zRight ){
  113300. pParse->nMem += 2;
  113301. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
  113302. aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
  113303. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  113304. aOp[0].p1 = iDb;
  113305. aOp[1].p1 = iDb;
  113306. aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
  113307. }else{
  113308. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  113309. sqlite3BeginWriteOperation(pParse, 0, iDb);
  113310. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
  113311. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  113312. pDb->pSchema->cache_size = size;
  113313. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  113314. }
  113315. break;
  113316. }
  113317. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  113318. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  113319. /*
  113320. ** PRAGMA [schema.]page_size
  113321. ** PRAGMA [schema.]page_size=N
  113322. **
  113323. ** The first form reports the current setting for the
  113324. ** database page size in bytes. The second form sets the
  113325. ** database page size value. The value can only be set if
  113326. ** the database has not yet been created.
  113327. */
  113328. case PragTyp_PAGE_SIZE: {
  113329. Btree *pBt = pDb->pBt;
  113330. assert( pBt!=0 );
  113331. if( !zRight ){
  113332. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  113333. returnSingleInt(v, size);
  113334. }else{
  113335. /* Malloc may fail when setting the page-size, as there is an internal
  113336. ** buffer that the pager module resizes using sqlite3_realloc().
  113337. */
  113338. db->nextPagesize = sqlite3Atoi(zRight);
  113339. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  113340. sqlite3OomFault(db);
  113341. }
  113342. }
  113343. break;
  113344. }
  113345. /*
  113346. ** PRAGMA [schema.]secure_delete
  113347. ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
  113348. **
  113349. ** The first form reports the current setting for the
  113350. ** secure_delete flag. The second form changes the secure_delete
  113351. ** flag setting and reports the new value.
  113352. */
  113353. case PragTyp_SECURE_DELETE: {
  113354. Btree *pBt = pDb->pBt;
  113355. int b = -1;
  113356. assert( pBt!=0 );
  113357. if( zRight ){
  113358. if( sqlite3_stricmp(zRight, "fast")==0 ){
  113359. b = 2;
  113360. }else{
  113361. b = sqlite3GetBoolean(zRight, 0);
  113362. }
  113363. }
  113364. if( pId2->n==0 && b>=0 ){
  113365. int ii;
  113366. for(ii=0; ii<db->nDb; ii++){
  113367. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  113368. }
  113369. }
  113370. b = sqlite3BtreeSecureDelete(pBt, b);
  113371. returnSingleInt(v, b);
  113372. break;
  113373. }
  113374. /*
  113375. ** PRAGMA [schema.]max_page_count
  113376. ** PRAGMA [schema.]max_page_count=N
  113377. **
  113378. ** The first form reports the current setting for the
  113379. ** maximum number of pages in the database file. The
  113380. ** second form attempts to change this setting. Both
  113381. ** forms return the current setting.
  113382. **
  113383. ** The absolute value of N is used. This is undocumented and might
  113384. ** change. The only purpose is to provide an easy way to test
  113385. ** the sqlite3AbsInt32() function.
  113386. **
  113387. ** PRAGMA [schema.]page_count
  113388. **
  113389. ** Return the number of pages in the specified database.
  113390. */
  113391. case PragTyp_PAGE_COUNT: {
  113392. int iReg;
  113393. sqlite3CodeVerifySchema(pParse, iDb);
  113394. iReg = ++pParse->nMem;
  113395. if( sqlite3Tolower(zLeft[0])=='p' ){
  113396. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  113397. }else{
  113398. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  113399. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  113400. }
  113401. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  113402. break;
  113403. }
  113404. /*
  113405. ** PRAGMA [schema.]locking_mode
  113406. ** PRAGMA [schema.]locking_mode = (normal|exclusive)
  113407. */
  113408. case PragTyp_LOCKING_MODE: {
  113409. const char *zRet = "normal";
  113410. int eMode = getLockingMode(zRight);
  113411. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  113412. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  113413. ** the current default locking mode (which may be different to
  113414. ** the locking-mode of the main database).
  113415. */
  113416. eMode = db->dfltLockMode;
  113417. }else{
  113418. Pager *pPager;
  113419. if( pId2->n==0 ){
  113420. /* This indicates that no database name was specified as part
  113421. ** of the PRAGMA command. In this case the locking-mode must be
  113422. ** set on all attached databases, as well as the main db file.
  113423. **
  113424. ** Also, the sqlite3.dfltLockMode variable is set so that
  113425. ** any subsequently attached databases also use the specified
  113426. ** locking mode.
  113427. */
  113428. int ii;
  113429. assert(pDb==&db->aDb[0]);
  113430. for(ii=2; ii<db->nDb; ii++){
  113431. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  113432. sqlite3PagerLockingMode(pPager, eMode);
  113433. }
  113434. db->dfltLockMode = (u8)eMode;
  113435. }
  113436. pPager = sqlite3BtreePager(pDb->pBt);
  113437. eMode = sqlite3PagerLockingMode(pPager, eMode);
  113438. }
  113439. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  113440. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  113441. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  113442. zRet = "exclusive";
  113443. }
  113444. returnSingleText(v, zRet);
  113445. break;
  113446. }
  113447. /*
  113448. ** PRAGMA [schema.]journal_mode
  113449. ** PRAGMA [schema.]journal_mode =
  113450. ** (delete|persist|off|truncate|memory|wal|off)
  113451. */
  113452. case PragTyp_JOURNAL_MODE: {
  113453. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  113454. int ii; /* Loop counter */
  113455. if( zRight==0 ){
  113456. /* If there is no "=MODE" part of the pragma, do a query for the
  113457. ** current mode */
  113458. eMode = PAGER_JOURNALMODE_QUERY;
  113459. }else{
  113460. const char *zMode;
  113461. int n = sqlite3Strlen30(zRight);
  113462. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  113463. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  113464. }
  113465. if( !zMode ){
  113466. /* If the "=MODE" part does not match any known journal mode,
  113467. ** then do a query */
  113468. eMode = PAGER_JOURNALMODE_QUERY;
  113469. }
  113470. }
  113471. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  113472. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  113473. iDb = 0;
  113474. pId2->n = 1;
  113475. }
  113476. for(ii=db->nDb-1; ii>=0; ii--){
  113477. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  113478. sqlite3VdbeUsesBtree(v, ii);
  113479. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  113480. }
  113481. }
  113482. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  113483. break;
  113484. }
  113485. /*
  113486. ** PRAGMA [schema.]journal_size_limit
  113487. ** PRAGMA [schema.]journal_size_limit=N
  113488. **
  113489. ** Get or set the size limit on rollback journal files.
  113490. */
  113491. case PragTyp_JOURNAL_SIZE_LIMIT: {
  113492. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  113493. i64 iLimit = -2;
  113494. if( zRight ){
  113495. sqlite3DecOrHexToI64(zRight, &iLimit);
  113496. if( iLimit<-1 ) iLimit = -1;
  113497. }
  113498. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  113499. returnSingleInt(v, iLimit);
  113500. break;
  113501. }
  113502. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  113503. /*
  113504. ** PRAGMA [schema.]auto_vacuum
  113505. ** PRAGMA [schema.]auto_vacuum=N
  113506. **
  113507. ** Get or set the value of the database 'auto-vacuum' parameter.
  113508. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  113509. */
  113510. #ifndef SQLITE_OMIT_AUTOVACUUM
  113511. case PragTyp_AUTO_VACUUM: {
  113512. Btree *pBt = pDb->pBt;
  113513. assert( pBt!=0 );
  113514. if( !zRight ){
  113515. returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
  113516. }else{
  113517. int eAuto = getAutoVacuum(zRight);
  113518. assert( eAuto>=0 && eAuto<=2 );
  113519. db->nextAutovac = (u8)eAuto;
  113520. /* Call SetAutoVacuum() to set initialize the internal auto and
  113521. ** incr-vacuum flags. This is required in case this connection
  113522. ** creates the database file. It is important that it is created
  113523. ** as an auto-vacuum capable db.
  113524. */
  113525. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  113526. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  113527. /* When setting the auto_vacuum mode to either "full" or
  113528. ** "incremental", write the value of meta[6] in the database
  113529. ** file. Before writing to meta[6], check that meta[3] indicates
  113530. ** that this really is an auto-vacuum capable database.
  113531. */
  113532. static const int iLn = VDBE_OFFSET_LINENO(2);
  113533. static const VdbeOpList setMeta6[] = {
  113534. { OP_Transaction, 0, 1, 0}, /* 0 */
  113535. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  113536. { OP_If, 1, 0, 0}, /* 2 */
  113537. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  113538. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
  113539. };
  113540. VdbeOp *aOp;
  113541. int iAddr = sqlite3VdbeCurrentAddr(v);
  113542. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
  113543. aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  113544. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  113545. aOp[0].p1 = iDb;
  113546. aOp[1].p1 = iDb;
  113547. aOp[2].p2 = iAddr+4;
  113548. aOp[4].p1 = iDb;
  113549. aOp[4].p3 = eAuto - 1;
  113550. sqlite3VdbeUsesBtree(v, iDb);
  113551. }
  113552. }
  113553. break;
  113554. }
  113555. #endif
  113556. /*
  113557. ** PRAGMA [schema.]incremental_vacuum(N)
  113558. **
  113559. ** Do N steps of incremental vacuuming on a database.
  113560. */
  113561. #ifndef SQLITE_OMIT_AUTOVACUUM
  113562. case PragTyp_INCREMENTAL_VACUUM: {
  113563. int iLimit, addr;
  113564. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  113565. iLimit = 0x7fffffff;
  113566. }
  113567. sqlite3BeginWriteOperation(pParse, 0, iDb);
  113568. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  113569. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  113570. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  113571. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  113572. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  113573. sqlite3VdbeJumpHere(v, addr);
  113574. break;
  113575. }
  113576. #endif
  113577. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  113578. /*
  113579. ** PRAGMA [schema.]cache_size
  113580. ** PRAGMA [schema.]cache_size=N
  113581. **
  113582. ** The first form reports the current local setting for the
  113583. ** page cache size. The second form sets the local
  113584. ** page cache size value. If N is positive then that is the
  113585. ** number of pages in the cache. If N is negative, then the
  113586. ** number of pages is adjusted so that the cache uses -N kibibytes
  113587. ** of memory.
  113588. */
  113589. case PragTyp_CACHE_SIZE: {
  113590. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  113591. if( !zRight ){
  113592. returnSingleInt(v, pDb->pSchema->cache_size);
  113593. }else{
  113594. int size = sqlite3Atoi(zRight);
  113595. pDb->pSchema->cache_size = size;
  113596. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  113597. }
  113598. break;
  113599. }
  113600. /*
  113601. ** PRAGMA [schema.]cache_spill
  113602. ** PRAGMA cache_spill=BOOLEAN
  113603. ** PRAGMA [schema.]cache_spill=N
  113604. **
  113605. ** The first form reports the current local setting for the
  113606. ** page cache spill size. The second form turns cache spill on
  113607. ** or off. When turnning cache spill on, the size is set to the
  113608. ** current cache_size. The third form sets a spill size that
  113609. ** may be different form the cache size.
  113610. ** If N is positive then that is the
  113611. ** number of pages in the cache. If N is negative, then the
  113612. ** number of pages is adjusted so that the cache uses -N kibibytes
  113613. ** of memory.
  113614. **
  113615. ** If the number of cache_spill pages is less then the number of
  113616. ** cache_size pages, no spilling occurs until the page count exceeds
  113617. ** the number of cache_size pages.
  113618. **
  113619. ** The cache_spill=BOOLEAN setting applies to all attached schemas,
  113620. ** not just the schema specified.
  113621. */
  113622. case PragTyp_CACHE_SPILL: {
  113623. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  113624. if( !zRight ){
  113625. returnSingleInt(v,
  113626. (db->flags & SQLITE_CacheSpill)==0 ? 0 :
  113627. sqlite3BtreeSetSpillSize(pDb->pBt,0));
  113628. }else{
  113629. int size = 1;
  113630. if( sqlite3GetInt32(zRight, &size) ){
  113631. sqlite3BtreeSetSpillSize(pDb->pBt, size);
  113632. }
  113633. if( sqlite3GetBoolean(zRight, size!=0) ){
  113634. db->flags |= SQLITE_CacheSpill;
  113635. }else{
  113636. db->flags &= ~SQLITE_CacheSpill;
  113637. }
  113638. setAllPagerFlags(db);
  113639. }
  113640. break;
  113641. }
  113642. /*
  113643. ** PRAGMA [schema.]mmap_size(N)
  113644. **
  113645. ** Used to set mapping size limit. The mapping size limit is
  113646. ** used to limit the aggregate size of all memory mapped regions of the
  113647. ** database file. If this parameter is set to zero, then memory mapping
  113648. ** is not used at all. If N is negative, then the default memory map
  113649. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  113650. ** The parameter N is measured in bytes.
  113651. **
  113652. ** This value is advisory. The underlying VFS is free to memory map
  113653. ** as little or as much as it wants. Except, if N is set to 0 then the
  113654. ** upper layers will never invoke the xFetch interfaces to the VFS.
  113655. */
  113656. case PragTyp_MMAP_SIZE: {
  113657. sqlite3_int64 sz;
  113658. #if SQLITE_MAX_MMAP_SIZE>0
  113659. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  113660. if( zRight ){
  113661. int ii;
  113662. sqlite3DecOrHexToI64(zRight, &sz);
  113663. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  113664. if( pId2->n==0 ) db->szMmap = sz;
  113665. for(ii=db->nDb-1; ii>=0; ii--){
  113666. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  113667. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  113668. }
  113669. }
  113670. }
  113671. sz = -1;
  113672. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  113673. #else
  113674. sz = 0;
  113675. rc = SQLITE_OK;
  113676. #endif
  113677. if( rc==SQLITE_OK ){
  113678. returnSingleInt(v, sz);
  113679. }else if( rc!=SQLITE_NOTFOUND ){
  113680. pParse->nErr++;
  113681. pParse->rc = rc;
  113682. }
  113683. break;
  113684. }
  113685. /*
  113686. ** PRAGMA temp_store
  113687. ** PRAGMA temp_store = "default"|"memory"|"file"
  113688. **
  113689. ** Return or set the local value of the temp_store flag. Changing
  113690. ** the local value does not make changes to the disk file and the default
  113691. ** value will be restored the next time the database is opened.
  113692. **
  113693. ** Note that it is possible for the library compile-time options to
  113694. ** override this setting
  113695. */
  113696. case PragTyp_TEMP_STORE: {
  113697. if( !zRight ){
  113698. returnSingleInt(v, db->temp_store);
  113699. }else{
  113700. changeTempStorage(pParse, zRight);
  113701. }
  113702. break;
  113703. }
  113704. /*
  113705. ** PRAGMA temp_store_directory
  113706. ** PRAGMA temp_store_directory = ""|"directory_name"
  113707. **
  113708. ** Return or set the local value of the temp_store_directory flag. Changing
  113709. ** the value sets a specific directory to be used for temporary files.
  113710. ** Setting to a null string reverts to the default temporary directory search.
  113711. ** If temporary directory is changed, then invalidateTempStorage.
  113712. **
  113713. */
  113714. case PragTyp_TEMP_STORE_DIRECTORY: {
  113715. if( !zRight ){
  113716. returnSingleText(v, sqlite3_temp_directory);
  113717. }else{
  113718. #ifndef SQLITE_OMIT_WSD
  113719. if( zRight[0] ){
  113720. int res;
  113721. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  113722. if( rc!=SQLITE_OK || res==0 ){
  113723. sqlite3ErrorMsg(pParse, "not a writable directory");
  113724. goto pragma_out;
  113725. }
  113726. }
  113727. if( SQLITE_TEMP_STORE==0
  113728. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  113729. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  113730. ){
  113731. invalidateTempStorage(pParse);
  113732. }
  113733. sqlite3_free(sqlite3_temp_directory);
  113734. if( zRight[0] ){
  113735. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  113736. }else{
  113737. sqlite3_temp_directory = 0;
  113738. }
  113739. #endif /* SQLITE_OMIT_WSD */
  113740. }
  113741. break;
  113742. }
  113743. #if SQLITE_OS_WIN
  113744. /*
  113745. ** PRAGMA data_store_directory
  113746. ** PRAGMA data_store_directory = ""|"directory_name"
  113747. **
  113748. ** Return or set the local value of the data_store_directory flag. Changing
  113749. ** the value sets a specific directory to be used for database files that
  113750. ** were specified with a relative pathname. Setting to a null string reverts
  113751. ** to the default database directory, which for database files specified with
  113752. ** a relative path will probably be based on the current directory for the
  113753. ** process. Database file specified with an absolute path are not impacted
  113754. ** by this setting, regardless of its value.
  113755. **
  113756. */
  113757. case PragTyp_DATA_STORE_DIRECTORY: {
  113758. if( !zRight ){
  113759. returnSingleText(v, sqlite3_data_directory);
  113760. }else{
  113761. #ifndef SQLITE_OMIT_WSD
  113762. if( zRight[0] ){
  113763. int res;
  113764. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  113765. if( rc!=SQLITE_OK || res==0 ){
  113766. sqlite3ErrorMsg(pParse, "not a writable directory");
  113767. goto pragma_out;
  113768. }
  113769. }
  113770. sqlite3_free(sqlite3_data_directory);
  113771. if( zRight[0] ){
  113772. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  113773. }else{
  113774. sqlite3_data_directory = 0;
  113775. }
  113776. #endif /* SQLITE_OMIT_WSD */
  113777. }
  113778. break;
  113779. }
  113780. #endif
  113781. #if SQLITE_ENABLE_LOCKING_STYLE
  113782. /*
  113783. ** PRAGMA [schema.]lock_proxy_file
  113784. ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
  113785. **
  113786. ** Return or set the value of the lock_proxy_file flag. Changing
  113787. ** the value sets a specific file to be used for database access locks.
  113788. **
  113789. */
  113790. case PragTyp_LOCK_PROXY_FILE: {
  113791. if( !zRight ){
  113792. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  113793. char *proxy_file_path = NULL;
  113794. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  113795. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  113796. &proxy_file_path);
  113797. returnSingleText(v, proxy_file_path);
  113798. }else{
  113799. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  113800. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  113801. int res;
  113802. if( zRight[0] ){
  113803. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  113804. zRight);
  113805. } else {
  113806. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  113807. NULL);
  113808. }
  113809. if( res!=SQLITE_OK ){
  113810. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  113811. goto pragma_out;
  113812. }
  113813. }
  113814. break;
  113815. }
  113816. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  113817. /*
  113818. ** PRAGMA [schema.]synchronous
  113819. ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
  113820. **
  113821. ** Return or set the local value of the synchronous flag. Changing
  113822. ** the local value does not make changes to the disk file and the
  113823. ** default value will be restored the next time the database is
  113824. ** opened.
  113825. */
  113826. case PragTyp_SYNCHRONOUS: {
  113827. if( !zRight ){
  113828. returnSingleInt(v, pDb->safety_level-1);
  113829. }else{
  113830. if( !db->autoCommit ){
  113831. sqlite3ErrorMsg(pParse,
  113832. "Safety level may not be changed inside a transaction");
  113833. }else if( iDb!=1 ){
  113834. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  113835. if( iLevel==0 ) iLevel = 1;
  113836. pDb->safety_level = iLevel;
  113837. pDb->bSyncSet = 1;
  113838. setAllPagerFlags(db);
  113839. }
  113840. }
  113841. break;
  113842. }
  113843. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  113844. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  113845. case PragTyp_FLAG: {
  113846. if( zRight==0 ){
  113847. setPragmaResultColumnNames(v, pPragma);
  113848. returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
  113849. }else{
  113850. u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */
  113851. if( db->autoCommit==0 ){
  113852. /* Foreign key support may not be enabled or disabled while not
  113853. ** in auto-commit mode. */
  113854. mask &= ~(SQLITE_ForeignKeys);
  113855. }
  113856. #if SQLITE_USER_AUTHENTICATION
  113857. if( db->auth.authLevel==UAUTH_User ){
  113858. /* Do not allow non-admin users to modify the schema arbitrarily */
  113859. mask &= ~(SQLITE_WriteSchema);
  113860. }
  113861. #endif
  113862. if( sqlite3GetBoolean(zRight, 0) ){
  113863. db->flags |= mask;
  113864. }else{
  113865. db->flags &= ~mask;
  113866. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  113867. }
  113868. /* Many of the flag-pragmas modify the code generated by the SQL
  113869. ** compiler (eg. count_changes). So add an opcode to expire all
  113870. ** compiled SQL statements after modifying a pragma value.
  113871. */
  113872. sqlite3VdbeAddOp0(v, OP_Expire);
  113873. setAllPagerFlags(db);
  113874. }
  113875. break;
  113876. }
  113877. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  113878. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  113879. /*
  113880. ** PRAGMA table_info(<table>)
  113881. **
  113882. ** Return a single row for each column of the named table. The columns of
  113883. ** the returned data set are:
  113884. **
  113885. ** cid: Column id (numbered from left to right, starting at 0)
  113886. ** name: Column name
  113887. ** type: Column declaration type.
  113888. ** notnull: True if 'NOT NULL' is part of column declaration
  113889. ** dflt_value: The default value for the column, if any.
  113890. ** pk: Non-zero for PK fields.
  113891. */
  113892. case PragTyp_TABLE_INFO: if( zRight ){
  113893. Table *pTab;
  113894. pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
  113895. if( pTab ){
  113896. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  113897. int i, k;
  113898. int nHidden = 0;
  113899. Column *pCol;
  113900. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  113901. pParse->nMem = 7;
  113902. sqlite3CodeVerifySchema(pParse, iTabDb);
  113903. sqlite3ViewGetColumnNames(pParse, pTab);
  113904. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  113905. int isHidden = IsHiddenColumn(pCol);
  113906. if( isHidden && pPragma->iArg==0 ){
  113907. nHidden++;
  113908. continue;
  113909. }
  113910. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  113911. k = 0;
  113912. }else if( pPk==0 ){
  113913. k = 1;
  113914. }else{
  113915. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  113916. }
  113917. assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
  113918. sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
  113919. i-nHidden,
  113920. pCol->zName,
  113921. sqlite3ColumnType(pCol,""),
  113922. pCol->notNull ? 1 : 0,
  113923. pCol->pDflt ? pCol->pDflt->u.zToken : 0,
  113924. k,
  113925. isHidden);
  113926. }
  113927. }
  113928. }
  113929. break;
  113930. #ifdef SQLITE_DEBUG
  113931. case PragTyp_STATS: {
  113932. Index *pIdx;
  113933. HashElem *i;
  113934. pParse->nMem = 5;
  113935. sqlite3CodeVerifySchema(pParse, iDb);
  113936. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  113937. Table *pTab = sqliteHashData(i);
  113938. sqlite3VdbeMultiLoad(v, 1, "ssiii",
  113939. pTab->zName,
  113940. 0,
  113941. pTab->szTabRow,
  113942. pTab->nRowLogEst,
  113943. pTab->tabFlags);
  113944. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  113945. sqlite3VdbeMultiLoad(v, 2, "siiiX",
  113946. pIdx->zName,
  113947. pIdx->szIdxRow,
  113948. pIdx->aiRowLogEst[0],
  113949. pIdx->hasStat1);
  113950. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  113951. }
  113952. }
  113953. }
  113954. break;
  113955. #endif
  113956. case PragTyp_INDEX_INFO: if( zRight ){
  113957. Index *pIdx;
  113958. Table *pTab;
  113959. pIdx = sqlite3FindIndex(db, zRight, zDb);
  113960. if( pIdx ){
  113961. int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
  113962. int i;
  113963. int mx;
  113964. if( pPragma->iArg ){
  113965. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  113966. mx = pIdx->nColumn;
  113967. pParse->nMem = 6;
  113968. }else{
  113969. /* PRAGMA index_info (legacy version) */
  113970. mx = pIdx->nKeyCol;
  113971. pParse->nMem = 3;
  113972. }
  113973. pTab = pIdx->pTable;
  113974. sqlite3CodeVerifySchema(pParse, iIdxDb);
  113975. assert( pParse->nMem<=pPragma->nPragCName );
  113976. for(i=0; i<mx; i++){
  113977. i16 cnum = pIdx->aiColumn[i];
  113978. sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
  113979. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  113980. if( pPragma->iArg ){
  113981. sqlite3VdbeMultiLoad(v, 4, "isiX",
  113982. pIdx->aSortOrder[i],
  113983. pIdx->azColl[i],
  113984. i<pIdx->nKeyCol);
  113985. }
  113986. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  113987. }
  113988. }
  113989. }
  113990. break;
  113991. case PragTyp_INDEX_LIST: if( zRight ){
  113992. Index *pIdx;
  113993. Table *pTab;
  113994. int i;
  113995. pTab = sqlite3FindTable(db, zRight, zDb);
  113996. if( pTab ){
  113997. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  113998. pParse->nMem = 5;
  113999. sqlite3CodeVerifySchema(pParse, iTabDb);
  114000. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  114001. const char *azOrigin[] = { "c", "u", "pk" };
  114002. sqlite3VdbeMultiLoad(v, 1, "isisi",
  114003. i,
  114004. pIdx->zName,
  114005. IsUniqueIndex(pIdx),
  114006. azOrigin[pIdx->idxType],
  114007. pIdx->pPartIdxWhere!=0);
  114008. }
  114009. }
  114010. }
  114011. break;
  114012. case PragTyp_DATABASE_LIST: {
  114013. int i;
  114014. pParse->nMem = 3;
  114015. for(i=0; i<db->nDb; i++){
  114016. if( db->aDb[i].pBt==0 ) continue;
  114017. assert( db->aDb[i].zDbSName!=0 );
  114018. sqlite3VdbeMultiLoad(v, 1, "iss",
  114019. i,
  114020. db->aDb[i].zDbSName,
  114021. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  114022. }
  114023. }
  114024. break;
  114025. case PragTyp_COLLATION_LIST: {
  114026. int i = 0;
  114027. HashElem *p;
  114028. pParse->nMem = 2;
  114029. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  114030. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  114031. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  114032. }
  114033. }
  114034. break;
  114035. #ifdef SQLITE_INTROSPECTION_PRAGMAS
  114036. case PragTyp_FUNCTION_LIST: {
  114037. int i;
  114038. HashElem *j;
  114039. FuncDef *p;
  114040. pParse->nMem = 2;
  114041. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  114042. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
  114043. if( p->funcFlags & SQLITE_FUNC_INTERNAL ) continue;
  114044. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
  114045. }
  114046. }
  114047. for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
  114048. p = (FuncDef*)sqliteHashData(j);
  114049. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
  114050. }
  114051. }
  114052. break;
  114053. #ifndef SQLITE_OMIT_VIRTUALTABLE
  114054. case PragTyp_MODULE_LIST: {
  114055. HashElem *j;
  114056. pParse->nMem = 1;
  114057. for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
  114058. Module *pMod = (Module*)sqliteHashData(j);
  114059. sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
  114060. }
  114061. }
  114062. break;
  114063. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  114064. case PragTyp_PRAGMA_LIST: {
  114065. int i;
  114066. for(i=0; i<ArraySize(aPragmaName); i++){
  114067. sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
  114068. }
  114069. }
  114070. break;
  114071. #endif /* SQLITE_INTROSPECTION_PRAGMAS */
  114072. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  114073. #ifndef SQLITE_OMIT_FOREIGN_KEY
  114074. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  114075. FKey *pFK;
  114076. Table *pTab;
  114077. pTab = sqlite3FindTable(db, zRight, zDb);
  114078. if( pTab ){
  114079. pFK = pTab->pFKey;
  114080. if( pFK ){
  114081. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  114082. int i = 0;
  114083. pParse->nMem = 8;
  114084. sqlite3CodeVerifySchema(pParse, iTabDb);
  114085. while(pFK){
  114086. int j;
  114087. for(j=0; j<pFK->nCol; j++){
  114088. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  114089. i,
  114090. j,
  114091. pFK->zTo,
  114092. pTab->aCol[pFK->aCol[j].iFrom].zName,
  114093. pFK->aCol[j].zCol,
  114094. actionName(pFK->aAction[1]), /* ON UPDATE */
  114095. actionName(pFK->aAction[0]), /* ON DELETE */
  114096. "NONE");
  114097. }
  114098. ++i;
  114099. pFK = pFK->pNextFrom;
  114100. }
  114101. }
  114102. }
  114103. }
  114104. break;
  114105. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  114106. #ifndef SQLITE_OMIT_FOREIGN_KEY
  114107. #ifndef SQLITE_OMIT_TRIGGER
  114108. case PragTyp_FOREIGN_KEY_CHECK: {
  114109. FKey *pFK; /* A foreign key constraint */
  114110. Table *pTab; /* Child table contain "REFERENCES" keyword */
  114111. Table *pParent; /* Parent table that child points to */
  114112. Index *pIdx; /* Index in the parent table */
  114113. int i; /* Loop counter: Foreign key number for pTab */
  114114. int j; /* Loop counter: Field of the foreign key */
  114115. HashElem *k; /* Loop counter: Next table in schema */
  114116. int x; /* result variable */
  114117. int regResult; /* 3 registers to hold a result row */
  114118. int regKey; /* Register to hold key for checking the FK */
  114119. int regRow; /* Registers to hold a row from pTab */
  114120. int addrTop; /* Top of a loop checking foreign keys */
  114121. int addrOk; /* Jump here if the key is OK */
  114122. int *aiCols; /* child to parent column mapping */
  114123. regResult = pParse->nMem+1;
  114124. pParse->nMem += 4;
  114125. regKey = ++pParse->nMem;
  114126. regRow = ++pParse->nMem;
  114127. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  114128. while( k ){
  114129. int iTabDb;
  114130. if( zRight ){
  114131. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  114132. k = 0;
  114133. }else{
  114134. pTab = (Table*)sqliteHashData(k);
  114135. k = sqliteHashNext(k);
  114136. }
  114137. if( pTab==0 || pTab->pFKey==0 ) continue;
  114138. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  114139. sqlite3CodeVerifySchema(pParse, iTabDb);
  114140. sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName);
  114141. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  114142. sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead);
  114143. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  114144. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  114145. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  114146. if( pParent==0 ) continue;
  114147. pIdx = 0;
  114148. sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName);
  114149. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  114150. if( x==0 ){
  114151. if( pIdx==0 ){
  114152. sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead);
  114153. }else{
  114154. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb);
  114155. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  114156. }
  114157. }else{
  114158. k = 0;
  114159. break;
  114160. }
  114161. }
  114162. assert( pParse->nErr>0 || pFK==0 );
  114163. if( pFK ) break;
  114164. if( pParse->nTab<i ) pParse->nTab = i;
  114165. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  114166. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  114167. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  114168. pIdx = 0;
  114169. aiCols = 0;
  114170. if( pParent ){
  114171. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  114172. assert( x==0 );
  114173. }
  114174. addrOk = sqlite3VdbeMakeLabel(v);
  114175. /* Generate code to read the child key values into registers
  114176. ** regRow..regRow+n. If any of the child key values are NULL, this
  114177. ** row cannot cause an FK violation. Jump directly to addrOk in
  114178. ** this case. */
  114179. for(j=0; j<pFK->nCol; j++){
  114180. int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
  114181. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
  114182. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  114183. }
  114184. /* Generate code to query the parent index for a matching parent
  114185. ** key. If a match is found, jump to addrOk. */
  114186. if( pIdx ){
  114187. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  114188. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  114189. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  114190. VdbeCoverage(v);
  114191. }else if( pParent ){
  114192. int jmp = sqlite3VdbeCurrentAddr(v)+2;
  114193. sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
  114194. sqlite3VdbeGoto(v, addrOk);
  114195. assert( pFK->nCol==1 );
  114196. }
  114197. /* Generate code to report an FK violation to the caller. */
  114198. if( HasRowid(pTab) ){
  114199. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  114200. }else{
  114201. sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
  114202. }
  114203. sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
  114204. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  114205. sqlite3VdbeResolveLabel(v, addrOk);
  114206. sqlite3DbFree(db, aiCols);
  114207. }
  114208. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  114209. sqlite3VdbeJumpHere(v, addrTop);
  114210. }
  114211. }
  114212. break;
  114213. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  114214. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  114215. #ifndef NDEBUG
  114216. case PragTyp_PARSER_TRACE: {
  114217. if( zRight ){
  114218. if( sqlite3GetBoolean(zRight, 0) ){
  114219. sqlite3ParserTrace(stdout, "parser: ");
  114220. }else{
  114221. sqlite3ParserTrace(0, 0);
  114222. }
  114223. }
  114224. }
  114225. break;
  114226. #endif
  114227. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  114228. ** used will be case sensitive or not depending on the RHS.
  114229. */
  114230. case PragTyp_CASE_SENSITIVE_LIKE: {
  114231. if( zRight ){
  114232. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  114233. }
  114234. }
  114235. break;
  114236. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  114237. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  114238. #endif
  114239. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  114240. /* PRAGMA integrity_check
  114241. ** PRAGMA integrity_check(N)
  114242. ** PRAGMA quick_check
  114243. ** PRAGMA quick_check(N)
  114244. **
  114245. ** Verify the integrity of the database.
  114246. **
  114247. ** The "quick_check" is reduced version of
  114248. ** integrity_check designed to detect most database corruption
  114249. ** without the overhead of cross-checking indexes. Quick_check
  114250. ** is linear time wherease integrity_check is O(NlogN).
  114251. */
  114252. case PragTyp_INTEGRITY_CHECK: {
  114253. int i, j, addr, mxErr;
  114254. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  114255. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  114256. ** then iDb is set to the index of the database identified by <db>.
  114257. ** In this case, the integrity of database iDb only is verified by
  114258. ** the VDBE created below.
  114259. **
  114260. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  114261. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  114262. ** to -1 here, to indicate that the VDBE should verify the integrity
  114263. ** of all attached databases. */
  114264. assert( iDb>=0 );
  114265. assert( iDb==0 || pId2->z );
  114266. if( pId2->z==0 ) iDb = -1;
  114267. /* Initialize the VDBE program */
  114268. pParse->nMem = 6;
  114269. /* Set the maximum error count */
  114270. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  114271. if( zRight ){
  114272. sqlite3GetInt32(zRight, &mxErr);
  114273. if( mxErr<=0 ){
  114274. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  114275. }
  114276. }
  114277. sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
  114278. /* Do an integrity check on each database file */
  114279. for(i=0; i<db->nDb; i++){
  114280. HashElem *x; /* For looping over tables in the schema */
  114281. Hash *pTbls; /* Set of all tables in the schema */
  114282. int *aRoot; /* Array of root page numbers of all btrees */
  114283. int cnt = 0; /* Number of entries in aRoot[] */
  114284. int mxIdx = 0; /* Maximum number of indexes for any table */
  114285. if( OMIT_TEMPDB && i==1 ) continue;
  114286. if( iDb>=0 && i!=iDb ) continue;
  114287. sqlite3CodeVerifySchema(pParse, i);
  114288. /* Do an integrity check of the B-Tree
  114289. **
  114290. ** Begin by finding the root pages numbers
  114291. ** for all tables and indices in the database.
  114292. */
  114293. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  114294. pTbls = &db->aDb[i].pSchema->tblHash;
  114295. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  114296. Table *pTab = sqliteHashData(x); /* Current table */
  114297. Index *pIdx; /* An index on pTab */
  114298. int nIdx; /* Number of indexes on pTab */
  114299. if( HasRowid(pTab) ) cnt++;
  114300. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
  114301. if( nIdx>mxIdx ) mxIdx = nIdx;
  114302. }
  114303. aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
  114304. if( aRoot==0 ) break;
  114305. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  114306. Table *pTab = sqliteHashData(x);
  114307. Index *pIdx;
  114308. if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
  114309. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  114310. aRoot[++cnt] = pIdx->tnum;
  114311. }
  114312. }
  114313. aRoot[0] = cnt;
  114314. /* Make sure sufficient number of registers have been allocated */
  114315. pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
  114316. sqlite3ClearTempRegCache(pParse);
  114317. /* Do the b-tree integrity checks */
  114318. sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
  114319. sqlite3VdbeChangeP5(v, (u8)i);
  114320. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  114321. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  114322. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
  114323. P4_DYNAMIC);
  114324. sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
  114325. integrityCheckResultRow(v);
  114326. sqlite3VdbeJumpHere(v, addr);
  114327. /* Make sure all the indices are constructed correctly.
  114328. */
  114329. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  114330. Table *pTab = sqliteHashData(x);
  114331. Index *pIdx, *pPk;
  114332. Index *pPrior = 0;
  114333. int loopTop;
  114334. int iDataCur, iIdxCur;
  114335. int r1 = -1;
  114336. if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
  114337. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  114338. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
  114339. 1, 0, &iDataCur, &iIdxCur);
  114340. /* reg[7] counts the number of entries in the table.
  114341. ** reg[8+i] counts the number of entries in the i-th index
  114342. */
  114343. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  114344. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  114345. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  114346. }
  114347. assert( pParse->nMem>=8+j );
  114348. assert( sqlite3NoTempsInRange(pParse,1,7+j) );
  114349. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  114350. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  114351. if( !isQuick ){
  114352. /* Sanity check on record header decoding */
  114353. sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
  114354. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  114355. }
  114356. /* Verify that all NOT NULL columns really are NOT NULL */
  114357. for(j=0; j<pTab->nCol; j++){
  114358. char *zErr;
  114359. int jmp2;
  114360. if( j==pTab->iPKey ) continue;
  114361. if( pTab->aCol[j].notNull==0 ) continue;
  114362. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  114363. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  114364. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  114365. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  114366. pTab->aCol[j].zName);
  114367. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  114368. integrityCheckResultRow(v);
  114369. sqlite3VdbeJumpHere(v, jmp2);
  114370. }
  114371. /* Verify CHECK constraints */
  114372. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  114373. ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
  114374. if( db->mallocFailed==0 ){
  114375. int addrCkFault = sqlite3VdbeMakeLabel(v);
  114376. int addrCkOk = sqlite3VdbeMakeLabel(v);
  114377. char *zErr;
  114378. int k;
  114379. pParse->iSelfTab = iDataCur + 1;
  114380. for(k=pCheck->nExpr-1; k>0; k--){
  114381. sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
  114382. }
  114383. sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
  114384. SQLITE_JUMPIFNULL);
  114385. sqlite3VdbeResolveLabel(v, addrCkFault);
  114386. pParse->iSelfTab = 0;
  114387. zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
  114388. pTab->zName);
  114389. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  114390. integrityCheckResultRow(v);
  114391. sqlite3VdbeResolveLabel(v, addrCkOk);
  114392. }
  114393. sqlite3ExprListDelete(db, pCheck);
  114394. }
  114395. if( !isQuick ){ /* Omit the remaining tests for quick_check */
  114396. /* Validate index entries for the current row */
  114397. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  114398. int jmp2, jmp3, jmp4, jmp5;
  114399. int ckUniq = sqlite3VdbeMakeLabel(v);
  114400. if( pPk==pIdx ) continue;
  114401. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  114402. pPrior, r1);
  114403. pPrior = pIdx;
  114404. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
  114405. /* Verify that an index entry exists for the current table row */
  114406. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  114407. pIdx->nColumn); VdbeCoverage(v);
  114408. sqlite3VdbeLoadString(v, 3, "row ");
  114409. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  114410. sqlite3VdbeLoadString(v, 4, " missing from index ");
  114411. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  114412. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  114413. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  114414. jmp4 = integrityCheckResultRow(v);
  114415. sqlite3VdbeJumpHere(v, jmp2);
  114416. /* For UNIQUE indexes, verify that only one entry exists with the
  114417. ** current key. The entry is unique if (1) any column is NULL
  114418. ** or (2) the next entry has a different key */
  114419. if( IsUniqueIndex(pIdx) ){
  114420. int uniqOk = sqlite3VdbeMakeLabel(v);
  114421. int jmp6;
  114422. int kk;
  114423. for(kk=0; kk<pIdx->nKeyCol; kk++){
  114424. int iCol = pIdx->aiColumn[kk];
  114425. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  114426. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  114427. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  114428. VdbeCoverage(v);
  114429. }
  114430. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  114431. sqlite3VdbeGoto(v, uniqOk);
  114432. sqlite3VdbeJumpHere(v, jmp6);
  114433. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  114434. pIdx->nKeyCol); VdbeCoverage(v);
  114435. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  114436. sqlite3VdbeGoto(v, jmp5);
  114437. sqlite3VdbeResolveLabel(v, uniqOk);
  114438. }
  114439. sqlite3VdbeJumpHere(v, jmp4);
  114440. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  114441. }
  114442. }
  114443. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  114444. sqlite3VdbeJumpHere(v, loopTop-1);
  114445. #ifndef SQLITE_OMIT_BTREECOUNT
  114446. if( !isQuick ){
  114447. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  114448. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  114449. if( pPk==pIdx ) continue;
  114450. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  114451. addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
  114452. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  114453. sqlite3VdbeLoadString(v, 4, pIdx->zName);
  114454. sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
  114455. integrityCheckResultRow(v);
  114456. sqlite3VdbeJumpHere(v, addr);
  114457. }
  114458. }
  114459. #endif /* SQLITE_OMIT_BTREECOUNT */
  114460. }
  114461. }
  114462. {
  114463. static const int iLn = VDBE_OFFSET_LINENO(2);
  114464. static const VdbeOpList endCode[] = {
  114465. { OP_AddImm, 1, 0, 0}, /* 0 */
  114466. { OP_IfNotZero, 1, 4, 0}, /* 1 */
  114467. { OP_String8, 0, 3, 0}, /* 2 */
  114468. { OP_ResultRow, 3, 1, 0}, /* 3 */
  114469. { OP_Halt, 0, 0, 0}, /* 4 */
  114470. { OP_String8, 0, 3, 0}, /* 5 */
  114471. { OP_Goto, 0, 3, 0}, /* 6 */
  114472. };
  114473. VdbeOp *aOp;
  114474. aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  114475. if( aOp ){
  114476. aOp[0].p2 = 1-mxErr;
  114477. aOp[2].p4type = P4_STATIC;
  114478. aOp[2].p4.z = "ok";
  114479. aOp[5].p4type = P4_STATIC;
  114480. aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
  114481. }
  114482. sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
  114483. }
  114484. }
  114485. break;
  114486. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  114487. #ifndef SQLITE_OMIT_UTF16
  114488. /*
  114489. ** PRAGMA encoding
  114490. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  114491. **
  114492. ** In its first form, this pragma returns the encoding of the main
  114493. ** database. If the database is not initialized, it is initialized now.
  114494. **
  114495. ** The second form of this pragma is a no-op if the main database file
  114496. ** has not already been initialized. In this case it sets the default
  114497. ** encoding that will be used for the main database file if a new file
  114498. ** is created. If an existing main database file is opened, then the
  114499. ** default text encoding for the existing database is used.
  114500. **
  114501. ** In all cases new databases created using the ATTACH command are
  114502. ** created to use the same default text encoding as the main database. If
  114503. ** the main database has not been initialized and/or created when ATTACH
  114504. ** is executed, this is done before the ATTACH operation.
  114505. **
  114506. ** In the second form this pragma sets the text encoding to be used in
  114507. ** new database files created using this database handle. It is only
  114508. ** useful if invoked immediately after the main database i
  114509. */
  114510. case PragTyp_ENCODING: {
  114511. static const struct EncName {
  114512. char *zName;
  114513. u8 enc;
  114514. } encnames[] = {
  114515. { "UTF8", SQLITE_UTF8 },
  114516. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  114517. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  114518. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  114519. { "UTF16le", SQLITE_UTF16LE },
  114520. { "UTF16be", SQLITE_UTF16BE },
  114521. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  114522. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  114523. { 0, 0 }
  114524. };
  114525. const struct EncName *pEnc;
  114526. if( !zRight ){ /* "PRAGMA encoding" */
  114527. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  114528. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  114529. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  114530. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  114531. returnSingleText(v, encnames[ENC(pParse->db)].zName);
  114532. }else{ /* "PRAGMA encoding = XXX" */
  114533. /* Only change the value of sqlite.enc if the database handle is not
  114534. ** initialized. If the main database exists, the new sqlite.enc value
  114535. ** will be overwritten when the schema is next loaded. If it does not
  114536. ** already exists, it will be created to use the new encoding value.
  114537. */
  114538. if(
  114539. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  114540. DbHasProperty(db, 0, DB_Empty)
  114541. ){
  114542. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  114543. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  114544. SCHEMA_ENC(db) = ENC(db) =
  114545. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  114546. break;
  114547. }
  114548. }
  114549. if( !pEnc->zName ){
  114550. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  114551. }
  114552. }
  114553. }
  114554. }
  114555. break;
  114556. #endif /* SQLITE_OMIT_UTF16 */
  114557. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  114558. /*
  114559. ** PRAGMA [schema.]schema_version
  114560. ** PRAGMA [schema.]schema_version = <integer>
  114561. **
  114562. ** PRAGMA [schema.]user_version
  114563. ** PRAGMA [schema.]user_version = <integer>
  114564. **
  114565. ** PRAGMA [schema.]freelist_count
  114566. **
  114567. ** PRAGMA [schema.]data_version
  114568. **
  114569. ** PRAGMA [schema.]application_id
  114570. ** PRAGMA [schema.]application_id = <integer>
  114571. **
  114572. ** The pragma's schema_version and user_version are used to set or get
  114573. ** the value of the schema-version and user-version, respectively. Both
  114574. ** the schema-version and the user-version are 32-bit signed integers
  114575. ** stored in the database header.
  114576. **
  114577. ** The schema-cookie is usually only manipulated internally by SQLite. It
  114578. ** is incremented by SQLite whenever the database schema is modified (by
  114579. ** creating or dropping a table or index). The schema version is used by
  114580. ** SQLite each time a query is executed to ensure that the internal cache
  114581. ** of the schema used when compiling the SQL query matches the schema of
  114582. ** the database against which the compiled query is actually executed.
  114583. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  114584. ** the schema-version is potentially dangerous and may lead to program
  114585. ** crashes or database corruption. Use with caution!
  114586. **
  114587. ** The user-version is not used internally by SQLite. It may be used by
  114588. ** applications for any purpose.
  114589. */
  114590. case PragTyp_HEADER_VALUE: {
  114591. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  114592. sqlite3VdbeUsesBtree(v, iDb);
  114593. if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
  114594. /* Write the specified cookie value */
  114595. static const VdbeOpList setCookie[] = {
  114596. { OP_Transaction, 0, 1, 0}, /* 0 */
  114597. { OP_SetCookie, 0, 0, 0}, /* 1 */
  114598. };
  114599. VdbeOp *aOp;
  114600. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
  114601. aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  114602. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  114603. aOp[0].p1 = iDb;
  114604. aOp[1].p1 = iDb;
  114605. aOp[1].p2 = iCookie;
  114606. aOp[1].p3 = sqlite3Atoi(zRight);
  114607. }else{
  114608. /* Read the specified cookie value */
  114609. static const VdbeOpList readCookie[] = {
  114610. { OP_Transaction, 0, 0, 0}, /* 0 */
  114611. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  114612. { OP_ResultRow, 1, 1, 0}
  114613. };
  114614. VdbeOp *aOp;
  114615. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
  114616. aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
  114617. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  114618. aOp[0].p1 = iDb;
  114619. aOp[1].p1 = iDb;
  114620. aOp[1].p3 = iCookie;
  114621. sqlite3VdbeReusable(v);
  114622. }
  114623. }
  114624. break;
  114625. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  114626. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  114627. /*
  114628. ** PRAGMA compile_options
  114629. **
  114630. ** Return the names of all compile-time options used in this build,
  114631. ** one option per row.
  114632. */
  114633. case PragTyp_COMPILE_OPTIONS: {
  114634. int i = 0;
  114635. const char *zOpt;
  114636. pParse->nMem = 1;
  114637. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  114638. sqlite3VdbeLoadString(v, 1, zOpt);
  114639. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  114640. }
  114641. sqlite3VdbeReusable(v);
  114642. }
  114643. break;
  114644. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  114645. #ifndef SQLITE_OMIT_WAL
  114646. /*
  114647. ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
  114648. **
  114649. ** Checkpoint the database.
  114650. */
  114651. case PragTyp_WAL_CHECKPOINT: {
  114652. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  114653. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  114654. if( zRight ){
  114655. if( sqlite3StrICmp(zRight, "full")==0 ){
  114656. eMode = SQLITE_CHECKPOINT_FULL;
  114657. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  114658. eMode = SQLITE_CHECKPOINT_RESTART;
  114659. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  114660. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  114661. }
  114662. }
  114663. pParse->nMem = 3;
  114664. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  114665. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  114666. }
  114667. break;
  114668. /*
  114669. ** PRAGMA wal_autocheckpoint
  114670. ** PRAGMA wal_autocheckpoint = N
  114671. **
  114672. ** Configure a database connection to automatically checkpoint a database
  114673. ** after accumulating N frames in the log. Or query for the current value
  114674. ** of N.
  114675. */
  114676. case PragTyp_WAL_AUTOCHECKPOINT: {
  114677. if( zRight ){
  114678. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  114679. }
  114680. returnSingleInt(v,
  114681. db->xWalCallback==sqlite3WalDefaultHook ?
  114682. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  114683. }
  114684. break;
  114685. #endif
  114686. /*
  114687. ** PRAGMA shrink_memory
  114688. **
  114689. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  114690. ** connection on which it is invoked to free up as much memory as it
  114691. ** can, by calling sqlite3_db_release_memory().
  114692. */
  114693. case PragTyp_SHRINK_MEMORY: {
  114694. sqlite3_db_release_memory(db);
  114695. break;
  114696. }
  114697. /*
  114698. ** PRAGMA optimize
  114699. ** PRAGMA optimize(MASK)
  114700. ** PRAGMA schema.optimize
  114701. ** PRAGMA schema.optimize(MASK)
  114702. **
  114703. ** Attempt to optimize the database. All schemas are optimized in the first
  114704. ** two forms, and only the specified schema is optimized in the latter two.
  114705. **
  114706. ** The details of optimizations performed by this pragma are expected
  114707. ** to change and improve over time. Applications should anticipate that
  114708. ** this pragma will perform new optimizations in future releases.
  114709. **
  114710. ** The optional argument is a bitmask of optimizations to perform:
  114711. **
  114712. ** 0x0001 Debugging mode. Do not actually perform any optimizations
  114713. ** but instead return one line of text for each optimization
  114714. ** that would have been done. Off by default.
  114715. **
  114716. ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
  114717. ** See below for additional information.
  114718. **
  114719. ** 0x0004 (Not yet implemented) Record usage and performance
  114720. ** information from the current session in the
  114721. ** database file so that it will be available to "optimize"
  114722. ** pragmas run by future database connections.
  114723. **
  114724. ** 0x0008 (Not yet implemented) Create indexes that might have
  114725. ** been helpful to recent queries
  114726. **
  114727. ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
  114728. ** of the optimizations listed above except Debug Mode, including new
  114729. ** optimizations that have not yet been invented. If new optimizations are
  114730. ** ever added that should be off by default, those off-by-default
  114731. ** optimizations will have bitmasks of 0x10000 or larger.
  114732. **
  114733. ** DETERMINATION OF WHEN TO RUN ANALYZE
  114734. **
  114735. ** In the current implementation, a table is analyzed if only if all of
  114736. ** the following are true:
  114737. **
  114738. ** (1) MASK bit 0x02 is set.
  114739. **
  114740. ** (2) The query planner used sqlite_stat1-style statistics for one or
  114741. ** more indexes of the table at some point during the lifetime of
  114742. ** the current connection.
  114743. **
  114744. ** (3) One or more indexes of the table are currently unanalyzed OR
  114745. ** the number of rows in the table has increased by 25 times or more
  114746. ** since the last time ANALYZE was run.
  114747. **
  114748. ** The rules for when tables are analyzed are likely to change in
  114749. ** future releases.
  114750. */
  114751. case PragTyp_OPTIMIZE: {
  114752. int iDbLast; /* Loop termination point for the schema loop */
  114753. int iTabCur; /* Cursor for a table whose size needs checking */
  114754. HashElem *k; /* Loop over tables of a schema */
  114755. Schema *pSchema; /* The current schema */
  114756. Table *pTab; /* A table in the schema */
  114757. Index *pIdx; /* An index of the table */
  114758. LogEst szThreshold; /* Size threshold above which reanalysis is needd */
  114759. char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
  114760. u32 opMask; /* Mask of operations to perform */
  114761. if( zRight ){
  114762. opMask = (u32)sqlite3Atoi(zRight);
  114763. if( (opMask & 0x02)==0 ) break;
  114764. }else{
  114765. opMask = 0xfffe;
  114766. }
  114767. iTabCur = pParse->nTab++;
  114768. for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
  114769. if( iDb==1 ) continue;
  114770. sqlite3CodeVerifySchema(pParse, iDb);
  114771. pSchema = db->aDb[iDb].pSchema;
  114772. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  114773. pTab = (Table*)sqliteHashData(k);
  114774. /* If table pTab has not been used in a way that would benefit from
  114775. ** having analysis statistics during the current session, then skip it.
  114776. ** This also has the effect of skipping virtual tables and views */
  114777. if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
  114778. /* Reanalyze if the table is 25 times larger than the last analysis */
  114779. szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
  114780. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  114781. if( !pIdx->hasStat1 ){
  114782. szThreshold = 0; /* Always analyze if any index lacks statistics */
  114783. break;
  114784. }
  114785. }
  114786. if( szThreshold ){
  114787. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  114788. sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
  114789. sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
  114790. VdbeCoverage(v);
  114791. }
  114792. zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
  114793. db->aDb[iDb].zDbSName, pTab->zName);
  114794. if( opMask & 0x01 ){
  114795. int r1 = sqlite3GetTempReg(pParse);
  114796. sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
  114797. sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
  114798. }else{
  114799. sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
  114800. }
  114801. }
  114802. }
  114803. sqlite3VdbeAddOp0(v, OP_Expire);
  114804. break;
  114805. }
  114806. /*
  114807. ** PRAGMA busy_timeout
  114808. ** PRAGMA busy_timeout = N
  114809. **
  114810. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  114811. ** if one is set. If no busy handler or a different busy handler is set
  114812. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  114813. ** disables the timeout.
  114814. */
  114815. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  114816. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  114817. if( zRight ){
  114818. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  114819. }
  114820. returnSingleInt(v, db->busyTimeout);
  114821. break;
  114822. }
  114823. /*
  114824. ** PRAGMA soft_heap_limit
  114825. ** PRAGMA soft_heap_limit = N
  114826. **
  114827. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  114828. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  114829. ** specified and is a non-negative integer.
  114830. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  114831. ** returns the same integer that would be returned by the
  114832. ** sqlite3_soft_heap_limit64(-1) C-language function.
  114833. */
  114834. case PragTyp_SOFT_HEAP_LIMIT: {
  114835. sqlite3_int64 N;
  114836. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  114837. sqlite3_soft_heap_limit64(N);
  114838. }
  114839. returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
  114840. break;
  114841. }
  114842. /*
  114843. ** PRAGMA threads
  114844. ** PRAGMA threads = N
  114845. **
  114846. ** Configure the maximum number of worker threads. Return the new
  114847. ** maximum, which might be less than requested.
  114848. */
  114849. case PragTyp_THREADS: {
  114850. sqlite3_int64 N;
  114851. if( zRight
  114852. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  114853. && N>=0
  114854. ){
  114855. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  114856. }
  114857. returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  114858. break;
  114859. }
  114860. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  114861. /*
  114862. ** Report the current state of file logs for all databases
  114863. */
  114864. case PragTyp_LOCK_STATUS: {
  114865. static const char *const azLockName[] = {
  114866. "unlocked", "shared", "reserved", "pending", "exclusive"
  114867. };
  114868. int i;
  114869. pParse->nMem = 2;
  114870. for(i=0; i<db->nDb; i++){
  114871. Btree *pBt;
  114872. const char *zState = "unknown";
  114873. int j;
  114874. if( db->aDb[i].zDbSName==0 ) continue;
  114875. pBt = db->aDb[i].pBt;
  114876. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  114877. zState = "closed";
  114878. }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
  114879. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  114880. zState = azLockName[j];
  114881. }
  114882. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
  114883. }
  114884. break;
  114885. }
  114886. #endif
  114887. #ifdef SQLITE_HAS_CODEC
  114888. /* Pragma iArg
  114889. ** ---------- ------
  114890. ** key 0
  114891. ** rekey 1
  114892. ** hexkey 2
  114893. ** hexrekey 3
  114894. ** textkey 4
  114895. ** textrekey 5
  114896. */
  114897. case PragTyp_KEY: {
  114898. if( zRight ){
  114899. int n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1;
  114900. if( (pPragma->iArg & 1)==0 ){
  114901. sqlite3_key_v2(db, zDb, zRight, n);
  114902. }else{
  114903. sqlite3_rekey_v2(db, zDb, zRight, n);
  114904. }
  114905. }
  114906. break;
  114907. }
  114908. case PragTyp_HEXKEY: {
  114909. if( zRight ){
  114910. u8 iByte;
  114911. int i;
  114912. char zKey[40];
  114913. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  114914. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  114915. if( (i&1)!=0 ) zKey[i/2] = iByte;
  114916. }
  114917. if( (pPragma->iArg & 1)==0 ){
  114918. sqlite3_key_v2(db, zDb, zKey, i/2);
  114919. }else{
  114920. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  114921. }
  114922. }
  114923. break;
  114924. }
  114925. #endif
  114926. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  114927. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  114928. #ifdef SQLITE_HAS_CODEC
  114929. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  114930. sqlite3_activate_see(&zRight[4]);
  114931. }
  114932. #endif
  114933. #ifdef SQLITE_ENABLE_CEROD
  114934. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  114935. sqlite3_activate_cerod(&zRight[6]);
  114936. }
  114937. #endif
  114938. }
  114939. break;
  114940. #endif
  114941. } /* End of the PRAGMA switch */
  114942. /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
  114943. ** purpose is to execute assert() statements to verify that if the
  114944. ** PragFlg_NoColumns1 flag is set and the caller specified an argument
  114945. ** to the PRAGMA, the implementation has not added any OP_ResultRow
  114946. ** instructions to the VM. */
  114947. if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
  114948. sqlite3VdbeVerifyNoResultRow(v);
  114949. }
  114950. pragma_out:
  114951. sqlite3DbFree(db, zLeft);
  114952. sqlite3DbFree(db, zRight);
  114953. }
  114954. #ifndef SQLITE_OMIT_VIRTUALTABLE
  114955. /*****************************************************************************
  114956. ** Implementation of an eponymous virtual table that runs a pragma.
  114957. **
  114958. */
  114959. typedef struct PragmaVtab PragmaVtab;
  114960. typedef struct PragmaVtabCursor PragmaVtabCursor;
  114961. struct PragmaVtab {
  114962. sqlite3_vtab base; /* Base class. Must be first */
  114963. sqlite3 *db; /* The database connection to which it belongs */
  114964. const PragmaName *pName; /* Name of the pragma */
  114965. u8 nHidden; /* Number of hidden columns */
  114966. u8 iHidden; /* Index of the first hidden column */
  114967. };
  114968. struct PragmaVtabCursor {
  114969. sqlite3_vtab_cursor base; /* Base class. Must be first */
  114970. sqlite3_stmt *pPragma; /* The pragma statement to run */
  114971. sqlite_int64 iRowid; /* Current rowid */
  114972. char *azArg[2]; /* Value of the argument and schema */
  114973. };
  114974. /*
  114975. ** Pragma virtual table module xConnect method.
  114976. */
  114977. static int pragmaVtabConnect(
  114978. sqlite3 *db,
  114979. void *pAux,
  114980. int argc, const char *const*argv,
  114981. sqlite3_vtab **ppVtab,
  114982. char **pzErr
  114983. ){
  114984. const PragmaName *pPragma = (const PragmaName*)pAux;
  114985. PragmaVtab *pTab = 0;
  114986. int rc;
  114987. int i, j;
  114988. char cSep = '(';
  114989. StrAccum acc;
  114990. char zBuf[200];
  114991. UNUSED_PARAMETER(argc);
  114992. UNUSED_PARAMETER(argv);
  114993. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  114994. sqlite3_str_appendall(&acc, "CREATE TABLE x");
  114995. for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
  114996. sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
  114997. cSep = ',';
  114998. }
  114999. if( i==0 ){
  115000. sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
  115001. i++;
  115002. }
  115003. j = 0;
  115004. if( pPragma->mPragFlg & PragFlg_Result1 ){
  115005. sqlite3_str_appendall(&acc, ",arg HIDDEN");
  115006. j++;
  115007. }
  115008. if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
  115009. sqlite3_str_appendall(&acc, ",schema HIDDEN");
  115010. j++;
  115011. }
  115012. sqlite3_str_append(&acc, ")", 1);
  115013. sqlite3StrAccumFinish(&acc);
  115014. assert( strlen(zBuf) < sizeof(zBuf)-1 );
  115015. rc = sqlite3_declare_vtab(db, zBuf);
  115016. if( rc==SQLITE_OK ){
  115017. pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
  115018. if( pTab==0 ){
  115019. rc = SQLITE_NOMEM;
  115020. }else{
  115021. memset(pTab, 0, sizeof(PragmaVtab));
  115022. pTab->pName = pPragma;
  115023. pTab->db = db;
  115024. pTab->iHidden = i;
  115025. pTab->nHidden = j;
  115026. }
  115027. }else{
  115028. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  115029. }
  115030. *ppVtab = (sqlite3_vtab*)pTab;
  115031. return rc;
  115032. }
  115033. /*
  115034. ** Pragma virtual table module xDisconnect method.
  115035. */
  115036. static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
  115037. PragmaVtab *pTab = (PragmaVtab*)pVtab;
  115038. sqlite3_free(pTab);
  115039. return SQLITE_OK;
  115040. }
  115041. /* Figure out the best index to use to search a pragma virtual table.
  115042. **
  115043. ** There are not really any index choices. But we want to encourage the
  115044. ** query planner to give == constraints on as many hidden parameters as
  115045. ** possible, and especially on the first hidden parameter. So return a
  115046. ** high cost if hidden parameters are unconstrained.
  115047. */
  115048. static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  115049. PragmaVtab *pTab = (PragmaVtab*)tab;
  115050. const struct sqlite3_index_constraint *pConstraint;
  115051. int i, j;
  115052. int seen[2];
  115053. pIdxInfo->estimatedCost = (double)1;
  115054. if( pTab->nHidden==0 ){ return SQLITE_OK; }
  115055. pConstraint = pIdxInfo->aConstraint;
  115056. seen[0] = 0;
  115057. seen[1] = 0;
  115058. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  115059. if( pConstraint->usable==0 ) continue;
  115060. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  115061. if( pConstraint->iColumn < pTab->iHidden ) continue;
  115062. j = pConstraint->iColumn - pTab->iHidden;
  115063. assert( j < 2 );
  115064. seen[j] = i+1;
  115065. }
  115066. if( seen[0]==0 ){
  115067. pIdxInfo->estimatedCost = (double)2147483647;
  115068. pIdxInfo->estimatedRows = 2147483647;
  115069. return SQLITE_OK;
  115070. }
  115071. j = seen[0]-1;
  115072. pIdxInfo->aConstraintUsage[j].argvIndex = 1;
  115073. pIdxInfo->aConstraintUsage[j].omit = 1;
  115074. if( seen[1]==0 ) return SQLITE_OK;
  115075. pIdxInfo->estimatedCost = (double)20;
  115076. pIdxInfo->estimatedRows = 20;
  115077. j = seen[1]-1;
  115078. pIdxInfo->aConstraintUsage[j].argvIndex = 2;
  115079. pIdxInfo->aConstraintUsage[j].omit = 1;
  115080. return SQLITE_OK;
  115081. }
  115082. /* Create a new cursor for the pragma virtual table */
  115083. static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
  115084. PragmaVtabCursor *pCsr;
  115085. pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
  115086. if( pCsr==0 ) return SQLITE_NOMEM;
  115087. memset(pCsr, 0, sizeof(PragmaVtabCursor));
  115088. pCsr->base.pVtab = pVtab;
  115089. *ppCursor = &pCsr->base;
  115090. return SQLITE_OK;
  115091. }
  115092. /* Clear all content from pragma virtual table cursor. */
  115093. static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
  115094. int i;
  115095. sqlite3_finalize(pCsr->pPragma);
  115096. pCsr->pPragma = 0;
  115097. for(i=0; i<ArraySize(pCsr->azArg); i++){
  115098. sqlite3_free(pCsr->azArg[i]);
  115099. pCsr->azArg[i] = 0;
  115100. }
  115101. }
  115102. /* Close a pragma virtual table cursor */
  115103. static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
  115104. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
  115105. pragmaVtabCursorClear(pCsr);
  115106. sqlite3_free(pCsr);
  115107. return SQLITE_OK;
  115108. }
  115109. /* Advance the pragma virtual table cursor to the next row */
  115110. static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
  115111. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  115112. int rc = SQLITE_OK;
  115113. /* Increment the xRowid value */
  115114. pCsr->iRowid++;
  115115. assert( pCsr->pPragma );
  115116. if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
  115117. rc = sqlite3_finalize(pCsr->pPragma);
  115118. pCsr->pPragma = 0;
  115119. pragmaVtabCursorClear(pCsr);
  115120. }
  115121. return rc;
  115122. }
  115123. /*
  115124. ** Pragma virtual table module xFilter method.
  115125. */
  115126. static int pragmaVtabFilter(
  115127. sqlite3_vtab_cursor *pVtabCursor,
  115128. int idxNum, const char *idxStr,
  115129. int argc, sqlite3_value **argv
  115130. ){
  115131. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  115132. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  115133. int rc;
  115134. int i, j;
  115135. StrAccum acc;
  115136. char *zSql;
  115137. UNUSED_PARAMETER(idxNum);
  115138. UNUSED_PARAMETER(idxStr);
  115139. pragmaVtabCursorClear(pCsr);
  115140. j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
  115141. for(i=0; i<argc; i++, j++){
  115142. const char *zText = (const char*)sqlite3_value_text(argv[i]);
  115143. assert( j<ArraySize(pCsr->azArg) );
  115144. assert( pCsr->azArg[j]==0 );
  115145. if( zText ){
  115146. pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
  115147. if( pCsr->azArg[j]==0 ){
  115148. return SQLITE_NOMEM;
  115149. }
  115150. }
  115151. }
  115152. sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
  115153. sqlite3_str_appendall(&acc, "PRAGMA ");
  115154. if( pCsr->azArg[1] ){
  115155. sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
  115156. }
  115157. sqlite3_str_appendall(&acc, pTab->pName->zName);
  115158. if( pCsr->azArg[0] ){
  115159. sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
  115160. }
  115161. zSql = sqlite3StrAccumFinish(&acc);
  115162. if( zSql==0 ) return SQLITE_NOMEM;
  115163. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
  115164. sqlite3_free(zSql);
  115165. if( rc!=SQLITE_OK ){
  115166. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  115167. return rc;
  115168. }
  115169. return pragmaVtabNext(pVtabCursor);
  115170. }
  115171. /*
  115172. ** Pragma virtual table module xEof method.
  115173. */
  115174. static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
  115175. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  115176. return (pCsr->pPragma==0);
  115177. }
  115178. /* The xColumn method simply returns the corresponding column from
  115179. ** the PRAGMA.
  115180. */
  115181. static int pragmaVtabColumn(
  115182. sqlite3_vtab_cursor *pVtabCursor,
  115183. sqlite3_context *ctx,
  115184. int i
  115185. ){
  115186. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  115187. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  115188. if( i<pTab->iHidden ){
  115189. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
  115190. }else{
  115191. sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
  115192. }
  115193. return SQLITE_OK;
  115194. }
  115195. /*
  115196. ** Pragma virtual table module xRowid method.
  115197. */
  115198. static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
  115199. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  115200. *p = pCsr->iRowid;
  115201. return SQLITE_OK;
  115202. }
  115203. /* The pragma virtual table object */
  115204. static const sqlite3_module pragmaVtabModule = {
  115205. 0, /* iVersion */
  115206. 0, /* xCreate - create a table */
  115207. pragmaVtabConnect, /* xConnect - connect to an existing table */
  115208. pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
  115209. pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
  115210. 0, /* xDestroy - Drop a table */
  115211. pragmaVtabOpen, /* xOpen - open a cursor */
  115212. pragmaVtabClose, /* xClose - close a cursor */
  115213. pragmaVtabFilter, /* xFilter - configure scan constraints */
  115214. pragmaVtabNext, /* xNext - advance a cursor */
  115215. pragmaVtabEof, /* xEof */
  115216. pragmaVtabColumn, /* xColumn - read data */
  115217. pragmaVtabRowid, /* xRowid - read data */
  115218. 0, /* xUpdate - write data */
  115219. 0, /* xBegin - begin transaction */
  115220. 0, /* xSync - sync transaction */
  115221. 0, /* xCommit - commit transaction */
  115222. 0, /* xRollback - rollback transaction */
  115223. 0, /* xFindFunction - function overloading */
  115224. 0, /* xRename - rename the table */
  115225. 0, /* xSavepoint */
  115226. 0, /* xRelease */
  115227. 0, /* xRollbackTo */
  115228. 0 /* xShadowName */
  115229. };
  115230. /*
  115231. ** Check to see if zTabName is really the name of a pragma. If it is,
  115232. ** then register an eponymous virtual table for that pragma and return
  115233. ** a pointer to the Module object for the new virtual table.
  115234. */
  115235. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
  115236. const PragmaName *pName;
  115237. assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
  115238. pName = pragmaLocate(zName+7);
  115239. if( pName==0 ) return 0;
  115240. if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
  115241. assert( sqlite3HashFind(&db->aModule, zName)==0 );
  115242. return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
  115243. }
  115244. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  115245. #endif /* SQLITE_OMIT_PRAGMA */
  115246. /************** End of pragma.c **********************************************/
  115247. /************** Begin file prepare.c *****************************************/
  115248. /*
  115249. ** 2005 May 25
  115250. **
  115251. ** The author disclaims copyright to this source code. In place of
  115252. ** a legal notice, here is a blessing:
  115253. **
  115254. ** May you do good and not evil.
  115255. ** May you find forgiveness for yourself and forgive others.
  115256. ** May you share freely, never taking more than you give.
  115257. **
  115258. *************************************************************************
  115259. ** This file contains the implementation of the sqlite3_prepare()
  115260. ** interface, and routines that contribute to loading the database schema
  115261. ** from disk.
  115262. */
  115263. /* #include "sqliteInt.h" */
  115264. /*
  115265. ** Fill the InitData structure with an error message that indicates
  115266. ** that the database is corrupt.
  115267. */
  115268. static void corruptSchema(
  115269. InitData *pData, /* Initialization context */
  115270. const char *zObj, /* Object being parsed at the point of error */
  115271. const char *zExtra /* Error information */
  115272. ){
  115273. sqlite3 *db = pData->db;
  115274. if( db->mallocFailed ){
  115275. pData->rc = SQLITE_NOMEM_BKPT;
  115276. }else if( pData->pzErrMsg[0]!=0 ){
  115277. /* A error message has already been generated. Do not overwrite it */
  115278. }else if( pData->mInitFlags & INITFLAG_AlterTable ){
  115279. *pData->pzErrMsg = sqlite3DbStrDup(db, zExtra);
  115280. pData->rc = SQLITE_ERROR;
  115281. }else if( db->flags & SQLITE_WriteSchema ){
  115282. pData->rc = SQLITE_CORRUPT_BKPT;
  115283. }else{
  115284. char *z;
  115285. if( zObj==0 ) zObj = "?";
  115286. z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
  115287. if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
  115288. *pData->pzErrMsg = z;
  115289. pData->rc = SQLITE_CORRUPT_BKPT;
  115290. }
  115291. }
  115292. /*
  115293. ** This is the callback routine for the code that initializes the
  115294. ** database. See sqlite3Init() below for additional information.
  115295. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  115296. **
  115297. ** Each callback contains the following information:
  115298. **
  115299. ** argv[0] = name of thing being created
  115300. ** argv[1] = root page number for table or index. 0 for trigger or view.
  115301. ** argv[2] = SQL text for the CREATE statement.
  115302. **
  115303. */
  115304. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  115305. InitData *pData = (InitData*)pInit;
  115306. sqlite3 *db = pData->db;
  115307. int iDb = pData->iDb;
  115308. assert( argc==3 );
  115309. UNUSED_PARAMETER2(NotUsed, argc);
  115310. assert( sqlite3_mutex_held(db->mutex) );
  115311. DbClearProperty(db, iDb, DB_Empty);
  115312. if( db->mallocFailed ){
  115313. corruptSchema(pData, argv[0], 0);
  115314. return 1;
  115315. }
  115316. assert( iDb>=0 && iDb<db->nDb );
  115317. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  115318. if( argv[1]==0 ){
  115319. corruptSchema(pData, argv[0], 0);
  115320. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  115321. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  115322. ** But because db->init.busy is set to 1, no VDBE code is generated
  115323. ** or executed. All the parser does is build the internal data
  115324. ** structures that describe the table, index, or view.
  115325. */
  115326. int rc;
  115327. u8 saved_iDb = db->init.iDb;
  115328. sqlite3_stmt *pStmt;
  115329. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  115330. assert( db->init.busy );
  115331. db->init.iDb = iDb;
  115332. db->init.newTnum = sqlite3Atoi(argv[1]);
  115333. db->init.orphanTrigger = 0;
  115334. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  115335. rc = db->errCode;
  115336. assert( (rc&0xFF)==(rcp&0xFF) );
  115337. db->init.iDb = saved_iDb;
  115338. /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
  115339. if( SQLITE_OK!=rc ){
  115340. if( db->init.orphanTrigger ){
  115341. assert( iDb==1 );
  115342. }else{
  115343. pData->rc = rc;
  115344. if( rc==SQLITE_NOMEM ){
  115345. sqlite3OomFault(db);
  115346. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  115347. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  115348. }
  115349. }
  115350. }
  115351. sqlite3_finalize(pStmt);
  115352. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  115353. corruptSchema(pData, argv[0], 0);
  115354. }else{
  115355. /* If the SQL column is blank it means this is an index that
  115356. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  115357. ** constraint for a CREATE TABLE. The index should have already
  115358. ** been created when we processed the CREATE TABLE. All we have
  115359. ** to do here is record the root page number for that index.
  115360. */
  115361. Index *pIndex;
  115362. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
  115363. if( pIndex==0 ){
  115364. /* This can occur if there exists an index on a TEMP table which
  115365. ** has the same name as another index on a permanent index. Since
  115366. ** the permanent table is hidden by the TEMP table, we can also
  115367. ** safely ignore the index on the permanent table.
  115368. */
  115369. /* Do Nothing */;
  115370. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  115371. corruptSchema(pData, argv[0], "invalid rootpage");
  115372. }
  115373. }
  115374. return 0;
  115375. }
  115376. /*
  115377. ** Attempt to read the database schema and initialize internal
  115378. ** data structures for a single database file. The index of the
  115379. ** database file is given by iDb. iDb==0 is used for the main
  115380. ** database. iDb==1 should never be used. iDb>=2 is used for
  115381. ** auxiliary databases. Return one of the SQLITE_ error codes to
  115382. ** indicate success or failure.
  115383. */
  115384. SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){
  115385. int rc;
  115386. int i;
  115387. #ifndef SQLITE_OMIT_DEPRECATED
  115388. int size;
  115389. #endif
  115390. Db *pDb;
  115391. char const *azArg[4];
  115392. int meta[5];
  115393. InitData initData;
  115394. const char *zMasterName;
  115395. int openedTransaction = 0;
  115396. assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
  115397. assert( iDb>=0 && iDb<db->nDb );
  115398. assert( db->aDb[iDb].pSchema );
  115399. assert( sqlite3_mutex_held(db->mutex) );
  115400. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  115401. db->init.busy = 1;
  115402. /* Construct the in-memory representation schema tables (sqlite_master or
  115403. ** sqlite_temp_master) by invoking the parser directly. The appropriate
  115404. ** table name will be inserted automatically by the parser so we can just
  115405. ** use the abbreviation "x" here. The parser will also automatically tag
  115406. ** the schema table as read-only. */
  115407. azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
  115408. azArg[1] = "1";
  115409. azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
  115410. "rootpage int,sql text)";
  115411. azArg[3] = 0;
  115412. initData.db = db;
  115413. initData.iDb = iDb;
  115414. initData.rc = SQLITE_OK;
  115415. initData.pzErrMsg = pzErrMsg;
  115416. initData.mInitFlags = mFlags;
  115417. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  115418. if( initData.rc ){
  115419. rc = initData.rc;
  115420. goto error_out;
  115421. }
  115422. /* Create a cursor to hold the database open
  115423. */
  115424. pDb = &db->aDb[iDb];
  115425. if( pDb->pBt==0 ){
  115426. assert( iDb==1 );
  115427. DbSetProperty(db, 1, DB_SchemaLoaded);
  115428. rc = SQLITE_OK;
  115429. goto error_out;
  115430. }
  115431. /* If there is not already a read-only (or read-write) transaction opened
  115432. ** on the b-tree database, open one now. If a transaction is opened, it
  115433. ** will be closed before this function returns. */
  115434. sqlite3BtreeEnter(pDb->pBt);
  115435. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  115436. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
  115437. if( rc!=SQLITE_OK ){
  115438. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  115439. goto initone_error_out;
  115440. }
  115441. openedTransaction = 1;
  115442. }
  115443. /* Get the database meta information.
  115444. **
  115445. ** Meta values are as follows:
  115446. ** meta[0] Schema cookie. Changes with each schema change.
  115447. ** meta[1] File format of schema layer.
  115448. ** meta[2] Size of the page cache.
  115449. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  115450. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  115451. ** meta[5] User version
  115452. ** meta[6] Incremental vacuum mode
  115453. ** meta[7] unused
  115454. ** meta[8] unused
  115455. ** meta[9] unused
  115456. **
  115457. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  115458. ** the possible values of meta[4].
  115459. */
  115460. for(i=0; i<ArraySize(meta); i++){
  115461. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  115462. }
  115463. if( (db->flags & SQLITE_ResetDatabase)!=0 ){
  115464. memset(meta, 0, sizeof(meta));
  115465. }
  115466. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  115467. /* If opening a non-empty database, check the text encoding. For the
  115468. ** main database, set sqlite3.enc to the encoding of the main database.
  115469. ** For an attached db, it is an error if the encoding is not the same
  115470. ** as sqlite3.enc.
  115471. */
  115472. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  115473. if( iDb==0 ){
  115474. #ifndef SQLITE_OMIT_UTF16
  115475. u8 encoding;
  115476. /* If opening the main database, set ENC(db). */
  115477. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  115478. if( encoding==0 ) encoding = SQLITE_UTF8;
  115479. ENC(db) = encoding;
  115480. #else
  115481. ENC(db) = SQLITE_UTF8;
  115482. #endif
  115483. }else{
  115484. /* If opening an attached database, the encoding much match ENC(db) */
  115485. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  115486. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  115487. " text encoding as main database");
  115488. rc = SQLITE_ERROR;
  115489. goto initone_error_out;
  115490. }
  115491. }
  115492. }else{
  115493. DbSetProperty(db, iDb, DB_Empty);
  115494. }
  115495. pDb->pSchema->enc = ENC(db);
  115496. if( pDb->pSchema->cache_size==0 ){
  115497. #ifndef SQLITE_OMIT_DEPRECATED
  115498. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  115499. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  115500. pDb->pSchema->cache_size = size;
  115501. #else
  115502. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  115503. #endif
  115504. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  115505. }
  115506. /*
  115507. ** file_format==1 Version 3.0.0.
  115508. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  115509. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  115510. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  115511. */
  115512. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  115513. if( pDb->pSchema->file_format==0 ){
  115514. pDb->pSchema->file_format = 1;
  115515. }
  115516. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  115517. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  115518. rc = SQLITE_ERROR;
  115519. goto initone_error_out;
  115520. }
  115521. /* Ticket #2804: When we open a database in the newer file format,
  115522. ** clear the legacy_file_format pragma flag so that a VACUUM will
  115523. ** not downgrade the database and thus invalidate any descending
  115524. ** indices that the user might have created.
  115525. */
  115526. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  115527. db->flags &= ~SQLITE_LegacyFileFmt;
  115528. }
  115529. /* Read the schema information out of the schema tables
  115530. */
  115531. assert( db->init.busy );
  115532. {
  115533. char *zSql;
  115534. zSql = sqlite3MPrintf(db,
  115535. "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
  115536. db->aDb[iDb].zDbSName, zMasterName);
  115537. #ifndef SQLITE_OMIT_AUTHORIZATION
  115538. {
  115539. sqlite3_xauth xAuth;
  115540. xAuth = db->xAuth;
  115541. db->xAuth = 0;
  115542. #endif
  115543. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  115544. #ifndef SQLITE_OMIT_AUTHORIZATION
  115545. db->xAuth = xAuth;
  115546. }
  115547. #endif
  115548. if( rc==SQLITE_OK ) rc = initData.rc;
  115549. sqlite3DbFree(db, zSql);
  115550. #ifndef SQLITE_OMIT_ANALYZE
  115551. if( rc==SQLITE_OK ){
  115552. sqlite3AnalysisLoad(db, iDb);
  115553. }
  115554. #endif
  115555. }
  115556. if( db->mallocFailed ){
  115557. rc = SQLITE_NOMEM_BKPT;
  115558. sqlite3ResetAllSchemasOfConnection(db);
  115559. }
  115560. if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){
  115561. /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider
  115562. ** the schema loaded, even if errors occurred. In this situation the
  115563. ** current sqlite3_prepare() operation will fail, but the following one
  115564. ** will attempt to compile the supplied statement against whatever subset
  115565. ** of the schema was loaded before the error occurred. The primary
  115566. ** purpose of this is to allow access to the sqlite_master table
  115567. ** even when its contents have been corrupted.
  115568. */
  115569. DbSetProperty(db, iDb, DB_SchemaLoaded);
  115570. rc = SQLITE_OK;
  115571. }
  115572. /* Jump here for an error that occurs after successfully allocating
  115573. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  115574. ** before that point, jump to error_out.
  115575. */
  115576. initone_error_out:
  115577. if( openedTransaction ){
  115578. sqlite3BtreeCommit(pDb->pBt);
  115579. }
  115580. sqlite3BtreeLeave(pDb->pBt);
  115581. error_out:
  115582. if( rc ){
  115583. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  115584. sqlite3OomFault(db);
  115585. }
  115586. sqlite3ResetOneSchema(db, iDb);
  115587. }
  115588. db->init.busy = 0;
  115589. return rc;
  115590. }
  115591. /*
  115592. ** Initialize all database files - the main database file, the file
  115593. ** used to store temporary tables, and any additional database files
  115594. ** created using ATTACH statements. Return a success code. If an
  115595. ** error occurs, write an error message into *pzErrMsg.
  115596. **
  115597. ** After a database is initialized, the DB_SchemaLoaded bit is set
  115598. ** bit is set in the flags field of the Db structure. If the database
  115599. ** file was of zero-length, then the DB_Empty flag is also set.
  115600. */
  115601. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  115602. int i, rc;
  115603. int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
  115604. assert( sqlite3_mutex_held(db->mutex) );
  115605. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  115606. assert( db->init.busy==0 );
  115607. ENC(db) = SCHEMA_ENC(db);
  115608. assert( db->nDb>0 );
  115609. /* Do the main schema first */
  115610. if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
  115611. rc = sqlite3InitOne(db, 0, pzErrMsg, 0);
  115612. if( rc ) return rc;
  115613. }
  115614. /* All other schemas after the main schema. The "temp" schema must be last */
  115615. for(i=db->nDb-1; i>0; i--){
  115616. assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
  115617. if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
  115618. rc = sqlite3InitOne(db, i, pzErrMsg, 0);
  115619. if( rc ) return rc;
  115620. }
  115621. }
  115622. if( commit_internal ){
  115623. sqlite3CommitInternalChanges(db);
  115624. }
  115625. return SQLITE_OK;
  115626. }
  115627. /*
  115628. ** This routine is a no-op if the database schema is already initialized.
  115629. ** Otherwise, the schema is loaded. An error code is returned.
  115630. */
  115631. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  115632. int rc = SQLITE_OK;
  115633. sqlite3 *db = pParse->db;
  115634. assert( sqlite3_mutex_held(db->mutex) );
  115635. if( !db->init.busy ){
  115636. rc = sqlite3Init(db, &pParse->zErrMsg);
  115637. if( rc!=SQLITE_OK ){
  115638. pParse->rc = rc;
  115639. pParse->nErr++;
  115640. }else if( db->noSharedCache ){
  115641. db->mDbFlags |= DBFLAG_SchemaKnownOk;
  115642. }
  115643. }
  115644. return rc;
  115645. }
  115646. /*
  115647. ** Check schema cookies in all databases. If any cookie is out
  115648. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  115649. ** make no changes to pParse->rc.
  115650. */
  115651. static void schemaIsValid(Parse *pParse){
  115652. sqlite3 *db = pParse->db;
  115653. int iDb;
  115654. int rc;
  115655. int cookie;
  115656. assert( pParse->checkSchema );
  115657. assert( sqlite3_mutex_held(db->mutex) );
  115658. for(iDb=0; iDb<db->nDb; iDb++){
  115659. int openedTransaction = 0; /* True if a transaction is opened */
  115660. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  115661. if( pBt==0 ) continue;
  115662. /* If there is not already a read-only (or read-write) transaction opened
  115663. ** on the b-tree database, open one now. If a transaction is opened, it
  115664. ** will be closed immediately after reading the meta-value. */
  115665. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  115666. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  115667. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  115668. sqlite3OomFault(db);
  115669. }
  115670. if( rc!=SQLITE_OK ) return;
  115671. openedTransaction = 1;
  115672. }
  115673. /* Read the schema cookie from the database. If it does not match the
  115674. ** value stored as part of the in-memory schema representation,
  115675. ** set Parse.rc to SQLITE_SCHEMA. */
  115676. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  115677. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  115678. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  115679. sqlite3ResetOneSchema(db, iDb);
  115680. pParse->rc = SQLITE_SCHEMA;
  115681. }
  115682. /* Close the transaction, if one was opened. */
  115683. if( openedTransaction ){
  115684. sqlite3BtreeCommit(pBt);
  115685. }
  115686. }
  115687. }
  115688. /*
  115689. ** Convert a schema pointer into the iDb index that indicates
  115690. ** which database file in db->aDb[] the schema refers to.
  115691. **
  115692. ** If the same database is attached more than once, the first
  115693. ** attached database is returned.
  115694. */
  115695. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  115696. int i = -1000000;
  115697. /* If pSchema is NULL, then return -1000000. This happens when code in
  115698. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  115699. ** created by a sub-select). In this case the return value of this
  115700. ** function should never be used.
  115701. **
  115702. ** We return -1000000 instead of the more usual -1 simply because using
  115703. ** -1000000 as the incorrect index into db->aDb[] is much
  115704. ** more likely to cause a segfault than -1 (of course there are assert()
  115705. ** statements too, but it never hurts to play the odds).
  115706. */
  115707. assert( sqlite3_mutex_held(db->mutex) );
  115708. if( pSchema ){
  115709. for(i=0; 1; i++){
  115710. assert( i<db->nDb );
  115711. if( db->aDb[i].pSchema==pSchema ){
  115712. break;
  115713. }
  115714. }
  115715. assert( i>=0 && i<db->nDb );
  115716. }
  115717. return i;
  115718. }
  115719. /*
  115720. ** Free all memory allocations in the pParse object
  115721. */
  115722. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  115723. sqlite3 *db = pParse->db;
  115724. sqlite3DbFree(db, pParse->aLabel);
  115725. sqlite3ExprListDelete(db, pParse->pConstExpr);
  115726. if( db ){
  115727. assert( db->lookaside.bDisable >= pParse->disableLookaside );
  115728. db->lookaside.bDisable -= pParse->disableLookaside;
  115729. }
  115730. pParse->disableLookaside = 0;
  115731. }
  115732. /*
  115733. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  115734. */
  115735. static int sqlite3Prepare(
  115736. sqlite3 *db, /* Database handle. */
  115737. const char *zSql, /* UTF-8 encoded SQL statement. */
  115738. int nBytes, /* Length of zSql in bytes. */
  115739. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  115740. Vdbe *pReprepare, /* VM being reprepared */
  115741. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  115742. const char **pzTail /* OUT: End of parsed string */
  115743. ){
  115744. char *zErrMsg = 0; /* Error message */
  115745. int rc = SQLITE_OK; /* Result code */
  115746. int i; /* Loop counter */
  115747. Parse sParse; /* Parsing context */
  115748. memset(&sParse, 0, PARSE_HDR_SZ);
  115749. memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
  115750. sParse.pReprepare = pReprepare;
  115751. assert( ppStmt && *ppStmt==0 );
  115752. /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
  115753. assert( sqlite3_mutex_held(db->mutex) );
  115754. /* For a long-term use prepared statement avoid the use of
  115755. ** lookaside memory.
  115756. */
  115757. if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
  115758. sParse.disableLookaside++;
  115759. db->lookaside.bDisable++;
  115760. }
  115761. /* Check to verify that it is possible to get a read lock on all
  115762. ** database schemas. The inability to get a read lock indicates that
  115763. ** some other database connection is holding a write-lock, which in
  115764. ** turn means that the other connection has made uncommitted changes
  115765. ** to the schema.
  115766. **
  115767. ** Were we to proceed and prepare the statement against the uncommitted
  115768. ** schema changes and if those schema changes are subsequently rolled
  115769. ** back and different changes are made in their place, then when this
  115770. ** prepared statement goes to run the schema cookie would fail to detect
  115771. ** the schema change. Disaster would follow.
  115772. **
  115773. ** This thread is currently holding mutexes on all Btrees (because
  115774. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  115775. ** is not possible for another thread to start a new schema change
  115776. ** while this routine is running. Hence, we do not need to hold
  115777. ** locks on the schema, we just need to make sure nobody else is
  115778. ** holding them.
  115779. **
  115780. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  115781. ** but it does *not* override schema lock detection, so this all still
  115782. ** works even if READ_UNCOMMITTED is set.
  115783. */
  115784. for(i=0; i<db->nDb; i++) {
  115785. Btree *pBt = db->aDb[i].pBt;
  115786. if( pBt ){
  115787. assert( sqlite3BtreeHoldsMutex(pBt) );
  115788. rc = sqlite3BtreeSchemaLocked(pBt);
  115789. if( rc ){
  115790. const char *zDb = db->aDb[i].zDbSName;
  115791. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  115792. testcase( db->flags & SQLITE_ReadUncommit );
  115793. goto end_prepare;
  115794. }
  115795. }
  115796. }
  115797. sqlite3VtabUnlockList(db);
  115798. sParse.db = db;
  115799. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  115800. char *zSqlCopy;
  115801. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  115802. testcase( nBytes==mxLen );
  115803. testcase( nBytes==mxLen+1 );
  115804. if( nBytes>mxLen ){
  115805. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  115806. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  115807. goto end_prepare;
  115808. }
  115809. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  115810. if( zSqlCopy ){
  115811. sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
  115812. sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
  115813. sqlite3DbFree(db, zSqlCopy);
  115814. }else{
  115815. sParse.zTail = &zSql[nBytes];
  115816. }
  115817. }else{
  115818. sqlite3RunParser(&sParse, zSql, &zErrMsg);
  115819. }
  115820. assert( 0==sParse.nQueryLoop );
  115821. if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  115822. if( sParse.checkSchema ){
  115823. schemaIsValid(&sParse);
  115824. }
  115825. if( db->mallocFailed ){
  115826. sParse.rc = SQLITE_NOMEM_BKPT;
  115827. }
  115828. if( pzTail ){
  115829. *pzTail = sParse.zTail;
  115830. }
  115831. rc = sParse.rc;
  115832. #ifndef SQLITE_OMIT_EXPLAIN
  115833. if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
  115834. static const char * const azColName[] = {
  115835. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  115836. "id", "parent", "notused", "detail"
  115837. };
  115838. int iFirst, mx;
  115839. if( sParse.explain==2 ){
  115840. sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
  115841. iFirst = 8;
  115842. mx = 12;
  115843. }else{
  115844. sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
  115845. iFirst = 0;
  115846. mx = 8;
  115847. }
  115848. for(i=iFirst; i<mx; i++){
  115849. sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
  115850. azColName[i], SQLITE_STATIC);
  115851. }
  115852. }
  115853. #endif
  115854. if( db->init.busy==0 ){
  115855. sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
  115856. }
  115857. if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  115858. sqlite3VdbeFinalize(sParse.pVdbe);
  115859. assert(!(*ppStmt));
  115860. }else{
  115861. *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
  115862. }
  115863. if( zErrMsg ){
  115864. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  115865. sqlite3DbFree(db, zErrMsg);
  115866. }else{
  115867. sqlite3Error(db, rc);
  115868. }
  115869. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  115870. while( sParse.pTriggerPrg ){
  115871. TriggerPrg *pT = sParse.pTriggerPrg;
  115872. sParse.pTriggerPrg = pT->pNext;
  115873. sqlite3DbFree(db, pT);
  115874. }
  115875. end_prepare:
  115876. sqlite3ParserReset(&sParse);
  115877. return rc;
  115878. }
  115879. static int sqlite3LockAndPrepare(
  115880. sqlite3 *db, /* Database handle. */
  115881. const char *zSql, /* UTF-8 encoded SQL statement. */
  115882. int nBytes, /* Length of zSql in bytes. */
  115883. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  115884. Vdbe *pOld, /* VM being reprepared */
  115885. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  115886. const char **pzTail /* OUT: End of parsed string */
  115887. ){
  115888. int rc;
  115889. int cnt = 0;
  115890. #ifdef SQLITE_ENABLE_API_ARMOR
  115891. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  115892. #endif
  115893. *ppStmt = 0;
  115894. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  115895. return SQLITE_MISUSE_BKPT;
  115896. }
  115897. sqlite3_mutex_enter(db->mutex);
  115898. sqlite3BtreeEnterAll(db);
  115899. do{
  115900. /* Make multiple attempts to compile the SQL, until it either succeeds
  115901. ** or encounters a permanent error. A schema problem after one schema
  115902. ** reset is considered a permanent error. */
  115903. rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
  115904. assert( rc==SQLITE_OK || *ppStmt==0 );
  115905. }while( rc==SQLITE_ERROR_RETRY
  115906. || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
  115907. sqlite3BtreeLeaveAll(db);
  115908. rc = sqlite3ApiExit(db, rc);
  115909. assert( (rc&db->errMask)==rc );
  115910. sqlite3_mutex_leave(db->mutex);
  115911. return rc;
  115912. }
  115913. #ifdef SQLITE_ENABLE_NORMALIZE
  115914. /*
  115915. ** Checks if the specified token is a table, column, or function name,
  115916. ** based on the databases associated with the statement being prepared.
  115917. ** If the function fails, zero is returned and pRc is filled with the
  115918. ** error code.
  115919. */
  115920. static int shouldTreatAsIdentifier(
  115921. sqlite3 *db, /* Database handle. */
  115922. const char *zToken, /* Pointer to start of token to be checked */
  115923. int nToken, /* Length of token to be checked */
  115924. int *pRc /* Pointer to error code upon failure */
  115925. ){
  115926. int bFound = 0; /* Non-zero if token is an identifier name. */
  115927. int i, j; /* Database and column loop indexes. */
  115928. Schema *pSchema; /* Schema for current database. */
  115929. Hash *pHash; /* Hash table of tables for current database. */
  115930. HashElem *e; /* Hash element for hash table iteration. */
  115931. Table *pTab; /* Database table for columns being checked. */
  115932. if( sqlite3IsRowidN(zToken, nToken) ){
  115933. return 1;
  115934. }
  115935. if( nToken>0 ){
  115936. int hash = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zToken[0]], nToken);
  115937. if( sqlite3FunctionSearchN(hash, zToken, nToken) ) return 1;
  115938. }
  115939. assert( db!=0 );
  115940. sqlite3_mutex_enter(db->mutex);
  115941. sqlite3BtreeEnterAll(db);
  115942. for(i=0; i<db->nDb; i++){
  115943. pHash = &db->aFunc;
  115944. if( sqlite3HashFindN(pHash, zToken, nToken) ){
  115945. bFound = 1;
  115946. break;
  115947. }
  115948. pSchema = db->aDb[i].pSchema;
  115949. if( pSchema==0 ) continue;
  115950. pHash = &pSchema->tblHash;
  115951. if( sqlite3HashFindN(pHash, zToken, nToken) ){
  115952. bFound = 1;
  115953. break;
  115954. }
  115955. for(e=sqliteHashFirst(pHash); e; e=sqliteHashNext(e)){
  115956. pTab = sqliteHashData(e);
  115957. if( pTab==0 ) continue;
  115958. pHash = pTab->pColHash;
  115959. if( pHash==0 ){
  115960. pTab->pColHash = pHash = sqlite3_malloc(sizeof(Hash));
  115961. if( pHash ){
  115962. sqlite3HashInit(pHash);
  115963. for(j=0; j<pTab->nCol; j++){
  115964. Column *pCol = &pTab->aCol[j];
  115965. sqlite3HashInsert(pHash, pCol->zName, pCol);
  115966. }
  115967. }else{
  115968. *pRc = SQLITE_NOMEM_BKPT;
  115969. bFound = 0;
  115970. goto done;
  115971. }
  115972. }
  115973. if( pHash && sqlite3HashFindN(pHash, zToken, nToken) ){
  115974. bFound = 1;
  115975. goto done;
  115976. }
  115977. }
  115978. }
  115979. done:
  115980. sqlite3BtreeLeaveAll(db);
  115981. sqlite3_mutex_leave(db->mutex);
  115982. return bFound;
  115983. }
  115984. /*
  115985. ** Attempt to estimate the final output buffer size needed for the fully
  115986. ** normalized version of the specified SQL string. This should take into
  115987. ** account any potential expansion that could occur (e.g. via IN clauses
  115988. ** being expanded, etc). This size returned is the total number of bytes
  115989. ** including the NUL terminator.
  115990. */
  115991. static int estimateNormalizedSize(
  115992. const char *zSql, /* The original SQL string */
  115993. int nSql, /* Length of original SQL string */
  115994. u8 prepFlags /* The flags passed to sqlite3_prepare_v3() */
  115995. ){
  115996. int nOut = nSql + 4;
  115997. const char *z = zSql;
  115998. while( nOut<nSql*5 ){
  115999. while( z[0]!=0 && z[0]!='I' && z[0]!='i' ){ z++; }
  116000. if( z[0]==0 ) break;
  116001. z++;
  116002. if( z[0]!='N' && z[0]!='n' ) break;
  116003. z++;
  116004. while( sqlite3Isspace(z[0]) ){ z++; }
  116005. if( z[0]!='(' ) break;
  116006. z++;
  116007. nOut += 5; /* ?,?,? */
  116008. }
  116009. return nOut;
  116010. }
  116011. /*
  116012. ** Copy the current token into the output buffer while dealing with quoted
  116013. ** identifiers. By default, all letters will be converted into lowercase.
  116014. ** If the bUpper flag is set, uppercase will be used. The piOut argument
  116015. ** will be used to update the target index into the output string.
  116016. */
  116017. static void copyNormalizedToken(
  116018. const char *zSql, /* The original SQL string */
  116019. int iIn, /* Current index into the original SQL string */
  116020. int nToken, /* Number of bytes in the current token */
  116021. int tokenFlags, /* Flags returned by the tokenizer */
  116022. char *zOut, /* The output string */
  116023. int *piOut /* Pointer to target index into the output string */
  116024. ){
  116025. int bQuoted = tokenFlags & SQLITE_TOKEN_QUOTED;
  116026. int bKeyword = tokenFlags & SQLITE_TOKEN_KEYWORD;
  116027. int j = *piOut, k = 0;
  116028. for(; k<nToken; k++){
  116029. if( bQuoted ){
  116030. if( k==0 && iIn>0 ){
  116031. zOut[j++] = '"';
  116032. continue;
  116033. }else if( k==nToken-1 ){
  116034. zOut[j++] = '"';
  116035. continue;
  116036. }
  116037. }
  116038. if( bKeyword ){
  116039. zOut[j++] = sqlite3Toupper(zSql[iIn+k]);
  116040. }else{
  116041. zOut[j++] = sqlite3Tolower(zSql[iIn+k]);
  116042. }
  116043. }
  116044. *piOut = j;
  116045. }
  116046. /*
  116047. ** Perform normalization of the SQL contained in the prepared statement and
  116048. ** store the result in the zNormSql field. The schema for the associated
  116049. ** databases are consulted while performing the normalization in order to
  116050. ** determine if a token appears to be an identifier. All identifiers are
  116051. ** left intact in the normalized SQL and all literals are replaced with a
  116052. ** single '?'.
  116053. */
  116054. SQLITE_PRIVATE void sqlite3Normalize(
  116055. Vdbe *pVdbe, /* VM being reprepared */
  116056. const char *zSql, /* The original SQL string */
  116057. int nSql, /* Size of the input string in bytes */
  116058. u8 prepFlags /* The flags passed to sqlite3_prepare_v3() */
  116059. ){
  116060. sqlite3 *db; /* Database handle. */
  116061. char *z; /* The output string */
  116062. int nZ; /* Size of the output string in bytes */
  116063. int i; /* Next character to read from zSql[] */
  116064. int j; /* Next character to fill in on z[] */
  116065. int tokenType = 0; /* Type of the next token */
  116066. int prevTokenType = 0; /* Type of the previous token, except spaces */
  116067. int n; /* Size of the next token */
  116068. int nParen = 0; /* Nesting level of parenthesis */
  116069. Hash inHash; /* Table of parenthesis levels to output index. */
  116070. db = sqlite3VdbeDb(pVdbe);
  116071. assert( db!=0 );
  116072. assert( pVdbe->zNormSql==0 );
  116073. if( zSql==0 ) return;
  116074. nZ = estimateNormalizedSize(zSql, nSql, prepFlags);
  116075. z = sqlite3DbMallocRawNN(db, nZ);
  116076. if( z==0 ) return;
  116077. sqlite3HashInit(&inHash);
  116078. for(i=j=0; i<nSql && zSql[i]; i+=n){
  116079. int flags = 0;
  116080. if( tokenType!=TK_SPACE ) prevTokenType = tokenType;
  116081. n = sqlite3GetTokenNormalized((unsigned char*)zSql+i, &tokenType, &flags);
  116082. switch( tokenType ){
  116083. case TK_SPACE: {
  116084. break;
  116085. }
  116086. case TK_ILLEGAL: {
  116087. sqlite3DbFree(db, z);
  116088. sqlite3HashClear(&inHash);
  116089. return;
  116090. }
  116091. case TK_STRING:
  116092. case TK_INTEGER:
  116093. case TK_FLOAT:
  116094. case TK_VARIABLE:
  116095. case TK_BLOB: {
  116096. z[j++] = '?';
  116097. break;
  116098. }
  116099. case TK_LP:
  116100. case TK_RP: {
  116101. if( tokenType==TK_LP ){
  116102. nParen++;
  116103. if( prevTokenType==TK_IN ){
  116104. assert( nParen<nSql );
  116105. sqlite3HashInsert(&inHash, zSql+nParen, SQLITE_INT_TO_PTR(j));
  116106. }
  116107. }else{
  116108. int jj;
  116109. assert( nParen<nSql );
  116110. jj = SQLITE_PTR_TO_INT(sqlite3HashFind(&inHash, zSql+nParen));
  116111. if( jj>0 ){
  116112. sqlite3HashInsert(&inHash, zSql+nParen, 0);
  116113. assert( jj+6<nZ );
  116114. memcpy(z+jj+1, "?,?,?", 5);
  116115. j = jj+6;
  116116. assert( nZ-1-j>=0 );
  116117. assert( nZ-1-j<nZ );
  116118. memset(z+j, 0, nZ-1-j);
  116119. }
  116120. nParen--;
  116121. }
  116122. assert( nParen>=0 );
  116123. /* Fall through */
  116124. }
  116125. case TK_MINUS:
  116126. case TK_SEMI:
  116127. case TK_PLUS:
  116128. case TK_STAR:
  116129. case TK_SLASH:
  116130. case TK_REM:
  116131. case TK_EQ:
  116132. case TK_LE:
  116133. case TK_NE:
  116134. case TK_LSHIFT:
  116135. case TK_LT:
  116136. case TK_RSHIFT:
  116137. case TK_GT:
  116138. case TK_GE:
  116139. case TK_BITOR:
  116140. case TK_CONCAT:
  116141. case TK_COMMA:
  116142. case TK_BITAND:
  116143. case TK_BITNOT:
  116144. case TK_DOT:
  116145. case TK_IN:
  116146. case TK_IS:
  116147. case TK_NOT:
  116148. case TK_NULL:
  116149. case TK_ID: {
  116150. if( tokenType==TK_NULL ){
  116151. if( prevTokenType==TK_IS || prevTokenType==TK_NOT ){
  116152. /* NULL is a keyword in this case, not a literal value */
  116153. }else{
  116154. /* Here the NULL is a literal value */
  116155. z[j++] = '?';
  116156. break;
  116157. }
  116158. }
  116159. if( j>0 && sqlite3IsIdChar(z[j-1]) && sqlite3IsIdChar(zSql[i]) ){
  116160. z[j++] = ' ';
  116161. }
  116162. if( tokenType==TK_ID ){
  116163. int i2 = i, n2 = n, rc = SQLITE_OK;
  116164. if( nParen>0 ){
  116165. assert( nParen<nSql );
  116166. sqlite3HashInsert(&inHash, zSql+nParen, 0);
  116167. }
  116168. if( flags&SQLITE_TOKEN_QUOTED ){ i2++; n2-=2; }
  116169. if( shouldTreatAsIdentifier(db, zSql+i2, n2, &rc)==0 ){
  116170. if( rc!=SQLITE_OK ){
  116171. sqlite3DbFree(db, z);
  116172. sqlite3HashClear(&inHash);
  116173. return;
  116174. }
  116175. if( sqlite3_keyword_check(zSql+i2, n2)==0 ){
  116176. z[j++] = '?';
  116177. break;
  116178. }
  116179. }
  116180. }
  116181. copyNormalizedToken(zSql, i, n, flags, z, &j);
  116182. break;
  116183. }
  116184. }
  116185. }
  116186. assert( j<nZ && "one" );
  116187. while( j>0 && z[j-1]==' ' ){ j--; }
  116188. if( j>0 && z[j-1]!=';' ){ z[j++] = ';'; }
  116189. z[j] = 0;
  116190. assert( j<nZ && "two" );
  116191. pVdbe->zNormSql = z;
  116192. sqlite3HashClear(&inHash);
  116193. }
  116194. #endif /* SQLITE_ENABLE_NORMALIZE */
  116195. /*
  116196. ** Rerun the compilation of a statement after a schema change.
  116197. **
  116198. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  116199. ** if the statement cannot be recompiled because another connection has
  116200. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  116201. ** occurs, return SQLITE_SCHEMA.
  116202. */
  116203. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  116204. int rc;
  116205. sqlite3_stmt *pNew;
  116206. const char *zSql;
  116207. sqlite3 *db;
  116208. u8 prepFlags;
  116209. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  116210. zSql = sqlite3_sql((sqlite3_stmt *)p);
  116211. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  116212. db = sqlite3VdbeDb(p);
  116213. assert( sqlite3_mutex_held(db->mutex) );
  116214. prepFlags = sqlite3VdbePrepareFlags(p);
  116215. rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
  116216. if( rc ){
  116217. if( rc==SQLITE_NOMEM ){
  116218. sqlite3OomFault(db);
  116219. }
  116220. assert( pNew==0 );
  116221. return rc;
  116222. }else{
  116223. assert( pNew!=0 );
  116224. }
  116225. sqlite3VdbeSwap((Vdbe*)pNew, p);
  116226. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  116227. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  116228. sqlite3VdbeFinalize((Vdbe*)pNew);
  116229. return SQLITE_OK;
  116230. }
  116231. /*
  116232. ** Two versions of the official API. Legacy and new use. In the legacy
  116233. ** version, the original SQL text is not saved in the prepared statement
  116234. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  116235. ** sqlite3_step(). In the new version, the original SQL text is retained
  116236. ** and the statement is automatically recompiled if an schema change
  116237. ** occurs.
  116238. */
  116239. SQLITE_API int sqlite3_prepare(
  116240. sqlite3 *db, /* Database handle. */
  116241. const char *zSql, /* UTF-8 encoded SQL statement. */
  116242. int nBytes, /* Length of zSql in bytes. */
  116243. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116244. const char **pzTail /* OUT: End of parsed string */
  116245. ){
  116246. int rc;
  116247. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  116248. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  116249. return rc;
  116250. }
  116251. SQLITE_API int sqlite3_prepare_v2(
  116252. sqlite3 *db, /* Database handle. */
  116253. const char *zSql, /* UTF-8 encoded SQL statement. */
  116254. int nBytes, /* Length of zSql in bytes. */
  116255. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116256. const char **pzTail /* OUT: End of parsed string */
  116257. ){
  116258. int rc;
  116259. /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
  116260. ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
  116261. ** parameter.
  116262. **
  116263. ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
  116264. rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
  116265. ppStmt,pzTail);
  116266. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  116267. return rc;
  116268. }
  116269. SQLITE_API int sqlite3_prepare_v3(
  116270. sqlite3 *db, /* Database handle. */
  116271. const char *zSql, /* UTF-8 encoded SQL statement. */
  116272. int nBytes, /* Length of zSql in bytes. */
  116273. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  116274. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116275. const char **pzTail /* OUT: End of parsed string */
  116276. ){
  116277. int rc;
  116278. /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
  116279. ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
  116280. ** which is a bit array consisting of zero or more of the
  116281. ** SQLITE_PREPARE_* flags.
  116282. **
  116283. ** Proof by comparison to the implementation of sqlite3_prepare_v2()
  116284. ** directly above. */
  116285. rc = sqlite3LockAndPrepare(db,zSql,nBytes,
  116286. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  116287. 0,ppStmt,pzTail);
  116288. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  116289. return rc;
  116290. }
  116291. #ifndef SQLITE_OMIT_UTF16
  116292. /*
  116293. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  116294. */
  116295. static int sqlite3Prepare16(
  116296. sqlite3 *db, /* Database handle. */
  116297. const void *zSql, /* UTF-16 encoded SQL statement. */
  116298. int nBytes, /* Length of zSql in bytes. */
  116299. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  116300. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116301. const void **pzTail /* OUT: End of parsed string */
  116302. ){
  116303. /* This function currently works by first transforming the UTF-16
  116304. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  116305. ** tricky bit is figuring out the pointer to return in *pzTail.
  116306. */
  116307. char *zSql8;
  116308. const char *zTail8 = 0;
  116309. int rc = SQLITE_OK;
  116310. #ifdef SQLITE_ENABLE_API_ARMOR
  116311. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  116312. #endif
  116313. *ppStmt = 0;
  116314. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  116315. return SQLITE_MISUSE_BKPT;
  116316. }
  116317. if( nBytes>=0 ){
  116318. int sz;
  116319. const char *z = (const char*)zSql;
  116320. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  116321. nBytes = sz;
  116322. }
  116323. sqlite3_mutex_enter(db->mutex);
  116324. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  116325. if( zSql8 ){
  116326. rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
  116327. }
  116328. if( zTail8 && pzTail ){
  116329. /* If sqlite3_prepare returns a tail pointer, we calculate the
  116330. ** equivalent pointer into the UTF-16 string by counting the unicode
  116331. ** characters between zSql8 and zTail8, and then returning a pointer
  116332. ** the same number of characters into the UTF-16 string.
  116333. */
  116334. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  116335. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  116336. }
  116337. sqlite3DbFree(db, zSql8);
  116338. rc = sqlite3ApiExit(db, rc);
  116339. sqlite3_mutex_leave(db->mutex);
  116340. return rc;
  116341. }
  116342. /*
  116343. ** Two versions of the official API. Legacy and new use. In the legacy
  116344. ** version, the original SQL text is not saved in the prepared statement
  116345. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  116346. ** sqlite3_step(). In the new version, the original SQL text is retained
  116347. ** and the statement is automatically recompiled if an schema change
  116348. ** occurs.
  116349. */
  116350. SQLITE_API int sqlite3_prepare16(
  116351. sqlite3 *db, /* Database handle. */
  116352. const void *zSql, /* UTF-16 encoded SQL statement. */
  116353. int nBytes, /* Length of zSql in bytes. */
  116354. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116355. const void **pzTail /* OUT: End of parsed string */
  116356. ){
  116357. int rc;
  116358. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  116359. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  116360. return rc;
  116361. }
  116362. SQLITE_API int sqlite3_prepare16_v2(
  116363. sqlite3 *db, /* Database handle. */
  116364. const void *zSql, /* UTF-16 encoded SQL statement. */
  116365. int nBytes, /* Length of zSql in bytes. */
  116366. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116367. const void **pzTail /* OUT: End of parsed string */
  116368. ){
  116369. int rc;
  116370. rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
  116371. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  116372. return rc;
  116373. }
  116374. SQLITE_API int sqlite3_prepare16_v3(
  116375. sqlite3 *db, /* Database handle. */
  116376. const void *zSql, /* UTF-16 encoded SQL statement. */
  116377. int nBytes, /* Length of zSql in bytes. */
  116378. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  116379. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116380. const void **pzTail /* OUT: End of parsed string */
  116381. ){
  116382. int rc;
  116383. rc = sqlite3Prepare16(db,zSql,nBytes,
  116384. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  116385. ppStmt,pzTail);
  116386. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  116387. return rc;
  116388. }
  116389. #endif /* SQLITE_OMIT_UTF16 */
  116390. /************** End of prepare.c *********************************************/
  116391. /************** Begin file select.c ******************************************/
  116392. /*
  116393. ** 2001 September 15
  116394. **
  116395. ** The author disclaims copyright to this source code. In place of
  116396. ** a legal notice, here is a blessing:
  116397. **
  116398. ** May you do good and not evil.
  116399. ** May you find forgiveness for yourself and forgive others.
  116400. ** May you share freely, never taking more than you give.
  116401. **
  116402. *************************************************************************
  116403. ** This file contains C code routines that are called by the parser
  116404. ** to handle SELECT statements in SQLite.
  116405. */
  116406. /* #include "sqliteInt.h" */
  116407. /*
  116408. ** Trace output macros
  116409. */
  116410. #if SELECTTRACE_ENABLED
  116411. /***/ int sqlite3SelectTrace = 0;
  116412. # define SELECTTRACE(K,P,S,X) \
  116413. if(sqlite3SelectTrace&(K)) \
  116414. sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
  116415. sqlite3DebugPrintf X
  116416. #else
  116417. # define SELECTTRACE(K,P,S,X)
  116418. #endif
  116419. /*
  116420. ** An instance of the following object is used to record information about
  116421. ** how to process the DISTINCT keyword, to simplify passing that information
  116422. ** into the selectInnerLoop() routine.
  116423. */
  116424. typedef struct DistinctCtx DistinctCtx;
  116425. struct DistinctCtx {
  116426. u8 isTnct; /* True if the DISTINCT keyword is present */
  116427. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  116428. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  116429. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  116430. };
  116431. /*
  116432. ** An instance of the following object is used to record information about
  116433. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  116434. **
  116435. ** The aDefer[] array is used by the sorter-references optimization. For
  116436. ** example, assuming there is no index that can be used for the ORDER BY,
  116437. ** for the query:
  116438. **
  116439. ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
  116440. **
  116441. ** it may be more efficient to add just the "a" values to the sorter, and
  116442. ** retrieve the associated "bigblob" values directly from table t1 as the
  116443. ** 10 smallest "a" values are extracted from the sorter.
  116444. **
  116445. ** When the sorter-reference optimization is used, there is one entry in the
  116446. ** aDefer[] array for each database table that may be read as values are
  116447. ** extracted from the sorter.
  116448. */
  116449. typedef struct SortCtx SortCtx;
  116450. struct SortCtx {
  116451. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  116452. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  116453. int iECursor; /* Cursor number for the sorter */
  116454. int regReturn; /* Register holding block-output return address */
  116455. int labelBkOut; /* Start label for the block-output subroutine */
  116456. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  116457. int labelDone; /* Jump here when done, ex: LIMIT reached */
  116458. int labelOBLopt; /* Jump here when sorter is full */
  116459. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  116460. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  116461. u8 nDefer; /* Number of valid entries in aDefer[] */
  116462. struct DeferredCsr {
  116463. Table *pTab; /* Table definition */
  116464. int iCsr; /* Cursor number for table */
  116465. int nKey; /* Number of PK columns for table pTab (>=1) */
  116466. } aDefer[4];
  116467. #endif
  116468. struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */
  116469. };
  116470. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  116471. /*
  116472. ** Delete all the content of a Select structure. Deallocate the structure
  116473. ** itself only if bFree is true.
  116474. */
  116475. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  116476. while( p ){
  116477. Select *pPrior = p->pPrior;
  116478. sqlite3ExprListDelete(db, p->pEList);
  116479. sqlite3SrcListDelete(db, p->pSrc);
  116480. sqlite3ExprDelete(db, p->pWhere);
  116481. sqlite3ExprListDelete(db, p->pGroupBy);
  116482. sqlite3ExprDelete(db, p->pHaving);
  116483. sqlite3ExprListDelete(db, p->pOrderBy);
  116484. sqlite3ExprDelete(db, p->pLimit);
  116485. #ifndef SQLITE_OMIT_WINDOWFUNC
  116486. if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
  116487. sqlite3WindowListDelete(db, p->pWinDefn);
  116488. }
  116489. #endif
  116490. if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
  116491. if( bFree ) sqlite3DbFreeNN(db, p);
  116492. p = pPrior;
  116493. bFree = 1;
  116494. }
  116495. }
  116496. /*
  116497. ** Initialize a SelectDest structure.
  116498. */
  116499. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  116500. pDest->eDest = (u8)eDest;
  116501. pDest->iSDParm = iParm;
  116502. pDest->zAffSdst = 0;
  116503. pDest->iSdst = 0;
  116504. pDest->nSdst = 0;
  116505. }
  116506. /*
  116507. ** Allocate a new Select structure and return a pointer to that
  116508. ** structure.
  116509. */
  116510. SQLITE_PRIVATE Select *sqlite3SelectNew(
  116511. Parse *pParse, /* Parsing context */
  116512. ExprList *pEList, /* which columns to include in the result */
  116513. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  116514. Expr *pWhere, /* the WHERE clause */
  116515. ExprList *pGroupBy, /* the GROUP BY clause */
  116516. Expr *pHaving, /* the HAVING clause */
  116517. ExprList *pOrderBy, /* the ORDER BY clause */
  116518. u32 selFlags, /* Flag parameters, such as SF_Distinct */
  116519. Expr *pLimit /* LIMIT value. NULL means not used */
  116520. ){
  116521. Select *pNew;
  116522. Select standin;
  116523. pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
  116524. if( pNew==0 ){
  116525. assert( pParse->db->mallocFailed );
  116526. pNew = &standin;
  116527. }
  116528. if( pEList==0 ){
  116529. pEList = sqlite3ExprListAppend(pParse, 0,
  116530. sqlite3Expr(pParse->db,TK_ASTERISK,0));
  116531. }
  116532. pNew->pEList = pEList;
  116533. pNew->op = TK_SELECT;
  116534. pNew->selFlags = selFlags;
  116535. pNew->iLimit = 0;
  116536. pNew->iOffset = 0;
  116537. pNew->selId = ++pParse->nSelect;
  116538. pNew->addrOpenEphm[0] = -1;
  116539. pNew->addrOpenEphm[1] = -1;
  116540. pNew->nSelectRow = 0;
  116541. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
  116542. pNew->pSrc = pSrc;
  116543. pNew->pWhere = pWhere;
  116544. pNew->pGroupBy = pGroupBy;
  116545. pNew->pHaving = pHaving;
  116546. pNew->pOrderBy = pOrderBy;
  116547. pNew->pPrior = 0;
  116548. pNew->pNext = 0;
  116549. pNew->pLimit = pLimit;
  116550. pNew->pWith = 0;
  116551. #ifndef SQLITE_OMIT_WINDOWFUNC
  116552. pNew->pWin = 0;
  116553. pNew->pWinDefn = 0;
  116554. #endif
  116555. if( pParse->db->mallocFailed ) {
  116556. clearSelect(pParse->db, pNew, pNew!=&standin);
  116557. pNew = 0;
  116558. }else{
  116559. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  116560. }
  116561. assert( pNew!=&standin );
  116562. return pNew;
  116563. }
  116564. /*
  116565. ** Delete the given Select structure and all of its substructures.
  116566. */
  116567. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  116568. if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
  116569. }
  116570. /*
  116571. ** Return a pointer to the right-most SELECT statement in a compound.
  116572. */
  116573. static Select *findRightmost(Select *p){
  116574. while( p->pNext ) p = p->pNext;
  116575. return p;
  116576. }
  116577. /*
  116578. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  116579. ** type of join. Return an integer constant that expresses that type
  116580. ** in terms of the following bit values:
  116581. **
  116582. ** JT_INNER
  116583. ** JT_CROSS
  116584. ** JT_OUTER
  116585. ** JT_NATURAL
  116586. ** JT_LEFT
  116587. ** JT_RIGHT
  116588. **
  116589. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  116590. **
  116591. ** If an illegal or unsupported join type is seen, then still return
  116592. ** a join type, but put an error in the pParse structure.
  116593. */
  116594. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  116595. int jointype = 0;
  116596. Token *apAll[3];
  116597. Token *p;
  116598. /* 0123456789 123456789 123456789 123 */
  116599. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  116600. static const struct {
  116601. u8 i; /* Beginning of keyword text in zKeyText[] */
  116602. u8 nChar; /* Length of the keyword in characters */
  116603. u8 code; /* Join type mask */
  116604. } aKeyword[] = {
  116605. /* natural */ { 0, 7, JT_NATURAL },
  116606. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  116607. /* outer */ { 10, 5, JT_OUTER },
  116608. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  116609. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  116610. /* inner */ { 23, 5, JT_INNER },
  116611. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  116612. };
  116613. int i, j;
  116614. apAll[0] = pA;
  116615. apAll[1] = pB;
  116616. apAll[2] = pC;
  116617. for(i=0; i<3 && apAll[i]; i++){
  116618. p = apAll[i];
  116619. for(j=0; j<ArraySize(aKeyword); j++){
  116620. if( p->n==aKeyword[j].nChar
  116621. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  116622. jointype |= aKeyword[j].code;
  116623. break;
  116624. }
  116625. }
  116626. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  116627. if( j>=ArraySize(aKeyword) ){
  116628. jointype |= JT_ERROR;
  116629. break;
  116630. }
  116631. }
  116632. if(
  116633. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  116634. (jointype & JT_ERROR)!=0
  116635. ){
  116636. const char *zSp = " ";
  116637. assert( pB!=0 );
  116638. if( pC==0 ){ zSp++; }
  116639. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  116640. "%T %T%s%T", pA, pB, zSp, pC);
  116641. jointype = JT_INNER;
  116642. }else if( (jointype & JT_OUTER)!=0
  116643. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  116644. sqlite3ErrorMsg(pParse,
  116645. "RIGHT and FULL OUTER JOINs are not currently supported");
  116646. jointype = JT_INNER;
  116647. }
  116648. return jointype;
  116649. }
  116650. /*
  116651. ** Return the index of a column in a table. Return -1 if the column
  116652. ** is not contained in the table.
  116653. */
  116654. static int columnIndex(Table *pTab, const char *zCol){
  116655. int i;
  116656. for(i=0; i<pTab->nCol; i++){
  116657. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  116658. }
  116659. return -1;
  116660. }
  116661. /*
  116662. ** Search the first N tables in pSrc, from left to right, looking for a
  116663. ** table that has a column named zCol.
  116664. **
  116665. ** When found, set *piTab and *piCol to the table index and column index
  116666. ** of the matching column and return TRUE.
  116667. **
  116668. ** If not found, return FALSE.
  116669. */
  116670. static int tableAndColumnIndex(
  116671. SrcList *pSrc, /* Array of tables to search */
  116672. int N, /* Number of tables in pSrc->a[] to search */
  116673. const char *zCol, /* Name of the column we are looking for */
  116674. int *piTab, /* Write index of pSrc->a[] here */
  116675. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  116676. ){
  116677. int i; /* For looping over tables in pSrc */
  116678. int iCol; /* Index of column matching zCol */
  116679. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  116680. for(i=0; i<N; i++){
  116681. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  116682. if( iCol>=0 ){
  116683. if( piTab ){
  116684. *piTab = i;
  116685. *piCol = iCol;
  116686. }
  116687. return 1;
  116688. }
  116689. }
  116690. return 0;
  116691. }
  116692. /*
  116693. ** This function is used to add terms implied by JOIN syntax to the
  116694. ** WHERE clause expression of a SELECT statement. The new term, which
  116695. ** is ANDed with the existing WHERE clause, is of the form:
  116696. **
  116697. ** (tab1.col1 = tab2.col2)
  116698. **
  116699. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  116700. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  116701. ** column iColRight of tab2.
  116702. */
  116703. static void addWhereTerm(
  116704. Parse *pParse, /* Parsing context */
  116705. SrcList *pSrc, /* List of tables in FROM clause */
  116706. int iLeft, /* Index of first table to join in pSrc */
  116707. int iColLeft, /* Index of column in first table */
  116708. int iRight, /* Index of second table in pSrc */
  116709. int iColRight, /* Index of column in second table */
  116710. int isOuterJoin, /* True if this is an OUTER join */
  116711. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  116712. ){
  116713. sqlite3 *db = pParse->db;
  116714. Expr *pE1;
  116715. Expr *pE2;
  116716. Expr *pEq;
  116717. assert( iLeft<iRight );
  116718. assert( pSrc->nSrc>iRight );
  116719. assert( pSrc->a[iLeft].pTab );
  116720. assert( pSrc->a[iRight].pTab );
  116721. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  116722. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  116723. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
  116724. if( pEq && isOuterJoin ){
  116725. ExprSetProperty(pEq, EP_FromJoin);
  116726. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  116727. ExprSetVVAProperty(pEq, EP_NoReduce);
  116728. pEq->iRightJoinTable = (i16)pE2->iTable;
  116729. }
  116730. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  116731. }
  116732. /*
  116733. ** Set the EP_FromJoin property on all terms of the given expression.
  116734. ** And set the Expr.iRightJoinTable to iTable for every term in the
  116735. ** expression.
  116736. **
  116737. ** The EP_FromJoin property is used on terms of an expression to tell
  116738. ** the LEFT OUTER JOIN processing logic that this term is part of the
  116739. ** join restriction specified in the ON or USING clause and not a part
  116740. ** of the more general WHERE clause. These terms are moved over to the
  116741. ** WHERE clause during join processing but we need to remember that they
  116742. ** originated in the ON or USING clause.
  116743. **
  116744. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  116745. ** expression depends on table iRightJoinTable even if that table is not
  116746. ** explicitly mentioned in the expression. That information is needed
  116747. ** for cases like this:
  116748. **
  116749. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  116750. **
  116751. ** The where clause needs to defer the handling of the t1.x=5
  116752. ** term until after the t2 loop of the join. In that way, a
  116753. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  116754. ** defer the handling of t1.x=5, it will be processed immediately
  116755. ** after the t1 loop and rows with t1.x!=5 will never appear in
  116756. ** the output, which is incorrect.
  116757. */
  116758. static void setJoinExpr(Expr *p, int iTable){
  116759. while( p ){
  116760. ExprSetProperty(p, EP_FromJoin);
  116761. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  116762. ExprSetVVAProperty(p, EP_NoReduce);
  116763. p->iRightJoinTable = (i16)iTable;
  116764. if( p->op==TK_FUNCTION && p->x.pList ){
  116765. int i;
  116766. for(i=0; i<p->x.pList->nExpr; i++){
  116767. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  116768. }
  116769. }
  116770. setJoinExpr(p->pLeft, iTable);
  116771. p = p->pRight;
  116772. }
  116773. }
  116774. /* Undo the work of setJoinExpr(). In the expression tree p, convert every
  116775. ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
  116776. ** an ordinary term that omits the EP_FromJoin mark.
  116777. **
  116778. ** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
  116779. */
  116780. static void unsetJoinExpr(Expr *p, int iTable){
  116781. while( p ){
  116782. if( ExprHasProperty(p, EP_FromJoin)
  116783. && (iTable<0 || p->iRightJoinTable==iTable) ){
  116784. ExprClearProperty(p, EP_FromJoin);
  116785. }
  116786. if( p->op==TK_FUNCTION && p->x.pList ){
  116787. int i;
  116788. for(i=0; i<p->x.pList->nExpr; i++){
  116789. unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
  116790. }
  116791. }
  116792. unsetJoinExpr(p->pLeft, iTable);
  116793. p = p->pRight;
  116794. }
  116795. }
  116796. /*
  116797. ** This routine processes the join information for a SELECT statement.
  116798. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  116799. ** NATURAL joins also create extra WHERE clause terms.
  116800. **
  116801. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  116802. ** The left most table is the first entry in Select.pSrc. The right-most
  116803. ** table is the last entry. The join operator is held in the entry to
  116804. ** the left. Thus entry 0 contains the join operator for the join between
  116805. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  116806. ** also attached to the left entry.
  116807. **
  116808. ** This routine returns the number of errors encountered.
  116809. */
  116810. static int sqliteProcessJoin(Parse *pParse, Select *p){
  116811. SrcList *pSrc; /* All tables in the FROM clause */
  116812. int i, j; /* Loop counters */
  116813. struct SrcList_item *pLeft; /* Left table being joined */
  116814. struct SrcList_item *pRight; /* Right table being joined */
  116815. pSrc = p->pSrc;
  116816. pLeft = &pSrc->a[0];
  116817. pRight = &pLeft[1];
  116818. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  116819. Table *pRightTab = pRight->pTab;
  116820. int isOuter;
  116821. if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
  116822. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  116823. /* When the NATURAL keyword is present, add WHERE clause terms for
  116824. ** every column that the two tables have in common.
  116825. */
  116826. if( pRight->fg.jointype & JT_NATURAL ){
  116827. if( pRight->pOn || pRight->pUsing ){
  116828. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  116829. "an ON or USING clause", 0);
  116830. return 1;
  116831. }
  116832. for(j=0; j<pRightTab->nCol; j++){
  116833. char *zName; /* Name of column in the right table */
  116834. int iLeft; /* Matching left table */
  116835. int iLeftCol; /* Matching column in the left table */
  116836. zName = pRightTab->aCol[j].zName;
  116837. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  116838. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  116839. isOuter, &p->pWhere);
  116840. }
  116841. }
  116842. }
  116843. /* Disallow both ON and USING clauses in the same join
  116844. */
  116845. if( pRight->pOn && pRight->pUsing ){
  116846. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  116847. "clauses in the same join");
  116848. return 1;
  116849. }
  116850. /* Add the ON clause to the end of the WHERE clause, connected by
  116851. ** an AND operator.
  116852. */
  116853. if( pRight->pOn ){
  116854. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  116855. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  116856. pRight->pOn = 0;
  116857. }
  116858. /* Create extra terms on the WHERE clause for each column named
  116859. ** in the USING clause. Example: If the two tables to be joined are
  116860. ** A and B and the USING clause names X, Y, and Z, then add this
  116861. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  116862. ** Report an error if any column mentioned in the USING clause is
  116863. ** not contained in both tables to be joined.
  116864. */
  116865. if( pRight->pUsing ){
  116866. IdList *pList = pRight->pUsing;
  116867. for(j=0; j<pList->nId; j++){
  116868. char *zName; /* Name of the term in the USING clause */
  116869. int iLeft; /* Table on the left with matching column name */
  116870. int iLeftCol; /* Column number of matching column on the left */
  116871. int iRightCol; /* Column number of matching column on the right */
  116872. zName = pList->a[j].zName;
  116873. iRightCol = columnIndex(pRightTab, zName);
  116874. if( iRightCol<0
  116875. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  116876. ){
  116877. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  116878. "not present in both tables", zName);
  116879. return 1;
  116880. }
  116881. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  116882. isOuter, &p->pWhere);
  116883. }
  116884. }
  116885. }
  116886. return 0;
  116887. }
  116888. /*
  116889. ** An instance of this object holds information (beyond pParse and pSelect)
  116890. ** needed to load the next result row that is to be added to the sorter.
  116891. */
  116892. typedef struct RowLoadInfo RowLoadInfo;
  116893. struct RowLoadInfo {
  116894. int regResult; /* Store results in array of registers here */
  116895. u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
  116896. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  116897. ExprList *pExtra; /* Extra columns needed by sorter refs */
  116898. int regExtraResult; /* Where to load the extra columns */
  116899. #endif
  116900. };
  116901. /*
  116902. ** This routine does the work of loading query data into an array of
  116903. ** registers so that it can be added to the sorter.
  116904. */
  116905. static void innerLoopLoadRow(
  116906. Parse *pParse, /* Statement under construction */
  116907. Select *pSelect, /* The query being coded */
  116908. RowLoadInfo *pInfo /* Info needed to complete the row load */
  116909. ){
  116910. sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
  116911. 0, pInfo->ecelFlags);
  116912. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  116913. if( pInfo->pExtra ){
  116914. sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
  116915. sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
  116916. }
  116917. #endif
  116918. }
  116919. /*
  116920. ** Code the OP_MakeRecord instruction that generates the entry to be
  116921. ** added into the sorter.
  116922. **
  116923. ** Return the register in which the result is stored.
  116924. */
  116925. static int makeSorterRecord(
  116926. Parse *pParse,
  116927. SortCtx *pSort,
  116928. Select *pSelect,
  116929. int regBase,
  116930. int nBase
  116931. ){
  116932. int nOBSat = pSort->nOBSat;
  116933. Vdbe *v = pParse->pVdbe;
  116934. int regOut = ++pParse->nMem;
  116935. if( pSort->pDeferredRowLoad ){
  116936. innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
  116937. }
  116938. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
  116939. return regOut;
  116940. }
  116941. /*
  116942. ** Generate code that will push the record in registers regData
  116943. ** through regData+nData-1 onto the sorter.
  116944. */
  116945. static void pushOntoSorter(
  116946. Parse *pParse, /* Parser context */
  116947. SortCtx *pSort, /* Information about the ORDER BY clause */
  116948. Select *pSelect, /* The whole SELECT statement */
  116949. int regData, /* First register holding data to be sorted */
  116950. int regOrigData, /* First register holding data before packing */
  116951. int nData, /* Number of elements in the regData data array */
  116952. int nPrefixReg /* No. of reg prior to regData available for use */
  116953. ){
  116954. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  116955. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  116956. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  116957. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  116958. int regBase; /* Regs for sorter record */
  116959. int regRecord = 0; /* Assembled sorter record */
  116960. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  116961. int op; /* Opcode to add sorter record to sorter */
  116962. int iLimit; /* LIMIT counter */
  116963. int iSkip = 0; /* End of the sorter insert loop */
  116964. assert( bSeq==0 || bSeq==1 );
  116965. /* Three cases:
  116966. ** (1) The data to be sorted has already been packed into a Record
  116967. ** by a prior OP_MakeRecord. In this case nData==1 and regData
  116968. ** will be completely unrelated to regOrigData.
  116969. ** (2) All output columns are included in the sort record. In that
  116970. ** case regData==regOrigData.
  116971. ** (3) Some output columns are omitted from the sort record due to
  116972. ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
  116973. ** SQLITE_ECEL_OMITREF optimization, or due to the
  116974. ** SortCtx.pDeferredRowLoad optimiation. In any of these cases
  116975. ** regOrigData is 0 to prevent this routine from trying to copy
  116976. ** values that might not yet exist.
  116977. */
  116978. assert( nData==1 || regData==regOrigData || regOrigData==0 );
  116979. if( nPrefixReg ){
  116980. assert( nPrefixReg==nExpr+bSeq );
  116981. regBase = regData - nPrefixReg;
  116982. }else{
  116983. regBase = pParse->nMem + 1;
  116984. pParse->nMem += nBase;
  116985. }
  116986. assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
  116987. iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
  116988. pSort->labelDone = sqlite3VdbeMakeLabel(v);
  116989. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  116990. SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
  116991. if( bSeq ){
  116992. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  116993. }
  116994. if( nPrefixReg==0 && nData>0 ){
  116995. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  116996. }
  116997. if( nOBSat>0 ){
  116998. int regPrevKey; /* The first nOBSat columns of the previous row */
  116999. int addrFirst; /* Address of the OP_IfNot opcode */
  117000. int addrJmp; /* Address of the OP_Jump opcode */
  117001. VdbeOp *pOp; /* Opcode that opens the sorter */
  117002. int nKey; /* Number of sorting key columns, including OP_Sequence */
  117003. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  117004. regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
  117005. regPrevKey = pParse->nMem+1;
  117006. pParse->nMem += pSort->nOBSat;
  117007. nKey = nExpr - pSort->nOBSat + bSeq;
  117008. if( bSeq ){
  117009. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  117010. }else{
  117011. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  117012. }
  117013. VdbeCoverage(v);
  117014. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  117015. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  117016. if( pParse->db->mallocFailed ) return;
  117017. pOp->p2 = nKey + nData;
  117018. pKI = pOp->p4.pKeyInfo;
  117019. memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */
  117020. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  117021. testcase( pKI->nAllField > pKI->nKeyField+2 );
  117022. pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
  117023. pKI->nAllField-pKI->nKeyField-1);
  117024. addrJmp = sqlite3VdbeCurrentAddr(v);
  117025. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  117026. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  117027. pSort->regReturn = ++pParse->nMem;
  117028. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  117029. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  117030. if( iLimit ){
  117031. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
  117032. VdbeCoverage(v);
  117033. }
  117034. sqlite3VdbeJumpHere(v, addrFirst);
  117035. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  117036. sqlite3VdbeJumpHere(v, addrJmp);
  117037. }
  117038. if( iLimit ){
  117039. /* At this point the values for the new sorter entry are stored
  117040. ** in an array of registers. They need to be composed into a record
  117041. ** and inserted into the sorter if either (a) there are currently
  117042. ** less than LIMIT+OFFSET items or (b) the new record is smaller than
  117043. ** the largest record currently in the sorter. If (b) is true and there
  117044. ** are already LIMIT+OFFSET items in the sorter, delete the largest
  117045. ** entry before inserting the new one. This way there are never more
  117046. ** than LIMIT+OFFSET items in the sorter.
  117047. **
  117048. ** If the new record does not need to be inserted into the sorter,
  117049. ** jump to the next iteration of the loop. If the pSort->labelOBLopt
  117050. ** value is not zero, then it is a label of where to jump. Otherwise,
  117051. ** just bypass the row insert logic. See the header comment on the
  117052. ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
  117053. */
  117054. int iCsr = pSort->iECursor;
  117055. sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
  117056. VdbeCoverage(v);
  117057. sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
  117058. iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
  117059. iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
  117060. VdbeCoverage(v);
  117061. sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
  117062. }
  117063. if( regRecord==0 ){
  117064. regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
  117065. }
  117066. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  117067. op = OP_SorterInsert;
  117068. }else{
  117069. op = OP_IdxInsert;
  117070. }
  117071. sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
  117072. regBase+nOBSat, nBase-nOBSat);
  117073. if( iSkip ){
  117074. sqlite3VdbeChangeP2(v, iSkip,
  117075. pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
  117076. }
  117077. }
  117078. /*
  117079. ** Add code to implement the OFFSET
  117080. */
  117081. static void codeOffset(
  117082. Vdbe *v, /* Generate code into this VM */
  117083. int iOffset, /* Register holding the offset counter */
  117084. int iContinue /* Jump here to skip the current record */
  117085. ){
  117086. if( iOffset>0 ){
  117087. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  117088. VdbeComment((v, "OFFSET"));
  117089. }
  117090. }
  117091. /*
  117092. ** Add code that will check to make sure the N registers starting at iMem
  117093. ** form a distinct entry. iTab is a sorting index that holds previously
  117094. ** seen combinations of the N values. A new entry is made in iTab
  117095. ** if the current N values are new.
  117096. **
  117097. ** A jump to addrRepeat is made and the N+1 values are popped from the
  117098. ** stack if the top N elements are not distinct.
  117099. */
  117100. static void codeDistinct(
  117101. Parse *pParse, /* Parsing and code generating context */
  117102. int iTab, /* A sorting index used to test for distinctness */
  117103. int addrRepeat, /* Jump to here if not distinct */
  117104. int N, /* Number of elements */
  117105. int iMem /* First element */
  117106. ){
  117107. Vdbe *v;
  117108. int r1;
  117109. v = pParse->pVdbe;
  117110. r1 = sqlite3GetTempReg(pParse);
  117111. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  117112. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  117113. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
  117114. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  117115. sqlite3ReleaseTempReg(pParse, r1);
  117116. }
  117117. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117118. /*
  117119. ** This function is called as part of inner-loop generation for a SELECT
  117120. ** statement with an ORDER BY that is not optimized by an index. It
  117121. ** determines the expressions, if any, that the sorter-reference
  117122. ** optimization should be used for. The sorter-reference optimization
  117123. ** is used for SELECT queries like:
  117124. **
  117125. ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
  117126. **
  117127. ** If the optimization is used for expression "bigblob", then instead of
  117128. ** storing values read from that column in the sorter records, the PK of
  117129. ** the row from table t1 is stored instead. Then, as records are extracted from
  117130. ** the sorter to return to the user, the required value of bigblob is
  117131. ** retrieved directly from table t1. If the values are very large, this
  117132. ** can be more efficient than storing them directly in the sorter records.
  117133. **
  117134. ** The ExprList_item.bSorterRef flag is set for each expression in pEList
  117135. ** for which the sorter-reference optimization should be enabled.
  117136. ** Additionally, the pSort->aDefer[] array is populated with entries
  117137. ** for all cursors required to evaluate all selected expressions. Finally.
  117138. ** output variable (*ppExtra) is set to an expression list containing
  117139. ** expressions for all extra PK values that should be stored in the
  117140. ** sorter records.
  117141. */
  117142. static void selectExprDefer(
  117143. Parse *pParse, /* Leave any error here */
  117144. SortCtx *pSort, /* Sorter context */
  117145. ExprList *pEList, /* Expressions destined for sorter */
  117146. ExprList **ppExtra /* Expressions to append to sorter record */
  117147. ){
  117148. int i;
  117149. int nDefer = 0;
  117150. ExprList *pExtra = 0;
  117151. for(i=0; i<pEList->nExpr; i++){
  117152. struct ExprList_item *pItem = &pEList->a[i];
  117153. if( pItem->u.x.iOrderByCol==0 ){
  117154. Expr *pExpr = pItem->pExpr;
  117155. Table *pTab = pExpr->y.pTab;
  117156. if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
  117157. && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
  117158. ){
  117159. int j;
  117160. for(j=0; j<nDefer; j++){
  117161. if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
  117162. }
  117163. if( j==nDefer ){
  117164. if( nDefer==ArraySize(pSort->aDefer) ){
  117165. continue;
  117166. }else{
  117167. int nKey = 1;
  117168. int k;
  117169. Index *pPk = 0;
  117170. if( !HasRowid(pTab) ){
  117171. pPk = sqlite3PrimaryKeyIndex(pTab);
  117172. nKey = pPk->nKeyCol;
  117173. }
  117174. for(k=0; k<nKey; k++){
  117175. Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
  117176. if( pNew ){
  117177. pNew->iTable = pExpr->iTable;
  117178. pNew->y.pTab = pExpr->y.pTab;
  117179. pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
  117180. pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
  117181. }
  117182. }
  117183. pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
  117184. pSort->aDefer[nDefer].iCsr = pExpr->iTable;
  117185. pSort->aDefer[nDefer].nKey = nKey;
  117186. nDefer++;
  117187. }
  117188. }
  117189. pItem->bSorterRef = 1;
  117190. }
  117191. }
  117192. }
  117193. pSort->nDefer = (u8)nDefer;
  117194. *ppExtra = pExtra;
  117195. }
  117196. #endif
  117197. /*
  117198. ** This routine generates the code for the inside of the inner loop
  117199. ** of a SELECT.
  117200. **
  117201. ** If srcTab is negative, then the p->pEList expressions
  117202. ** are evaluated in order to get the data for this row. If srcTab is
  117203. ** zero or more, then data is pulled from srcTab and p->pEList is used only
  117204. ** to get the number of columns and the collation sequence for each column.
  117205. */
  117206. static void selectInnerLoop(
  117207. Parse *pParse, /* The parser context */
  117208. Select *p, /* The complete select statement being coded */
  117209. int srcTab, /* Pull data from this table if non-negative */
  117210. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  117211. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  117212. SelectDest *pDest, /* How to dispose of the results */
  117213. int iContinue, /* Jump here to continue with next row */
  117214. int iBreak /* Jump here to break out of the inner loop */
  117215. ){
  117216. Vdbe *v = pParse->pVdbe;
  117217. int i;
  117218. int hasDistinct; /* True if the DISTINCT keyword is present */
  117219. int eDest = pDest->eDest; /* How to dispose of results */
  117220. int iParm = pDest->iSDParm; /* First argument to disposal method */
  117221. int nResultCol; /* Number of result columns */
  117222. int nPrefixReg = 0; /* Number of extra registers before regResult */
  117223. RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
  117224. /* Usually, regResult is the first cell in an array of memory cells
  117225. ** containing the current result row. In this case regOrig is set to the
  117226. ** same value. However, if the results are being sent to the sorter, the
  117227. ** values for any expressions that are also part of the sort-key are omitted
  117228. ** from this array. In this case regOrig is set to zero. */
  117229. int regResult; /* Start of memory holding current results */
  117230. int regOrig; /* Start of memory holding full result (or 0) */
  117231. assert( v );
  117232. assert( p->pEList!=0 );
  117233. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  117234. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  117235. if( pSort==0 && !hasDistinct ){
  117236. assert( iContinue!=0 );
  117237. codeOffset(v, p->iOffset, iContinue);
  117238. }
  117239. /* Pull the requested columns.
  117240. */
  117241. nResultCol = p->pEList->nExpr;
  117242. if( pDest->iSdst==0 ){
  117243. if( pSort ){
  117244. nPrefixReg = pSort->pOrderBy->nExpr;
  117245. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  117246. pParse->nMem += nPrefixReg;
  117247. }
  117248. pDest->iSdst = pParse->nMem+1;
  117249. pParse->nMem += nResultCol;
  117250. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  117251. /* This is an error condition that can result, for example, when a SELECT
  117252. ** on the right-hand side of an INSERT contains more result columns than
  117253. ** there are columns in the table on the left. The error will be caught
  117254. ** and reported later. But we need to make sure enough memory is allocated
  117255. ** to avoid other spurious errors in the meantime. */
  117256. pParse->nMem += nResultCol;
  117257. }
  117258. pDest->nSdst = nResultCol;
  117259. regOrig = regResult = pDest->iSdst;
  117260. if( srcTab>=0 ){
  117261. for(i=0; i<nResultCol; i++){
  117262. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  117263. VdbeComment((v, "%s", p->pEList->a[i].zName));
  117264. }
  117265. }else if( eDest!=SRT_Exists ){
  117266. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117267. ExprList *pExtra = 0;
  117268. #endif
  117269. /* If the destination is an EXISTS(...) expression, the actual
  117270. ** values returned by the SELECT are not required.
  117271. */
  117272. u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
  117273. ExprList *pEList;
  117274. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  117275. ecelFlags = SQLITE_ECEL_DUP;
  117276. }else{
  117277. ecelFlags = 0;
  117278. }
  117279. if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
  117280. /* For each expression in p->pEList that is a copy of an expression in
  117281. ** the ORDER BY clause (pSort->pOrderBy), set the associated
  117282. ** iOrderByCol value to one more than the index of the ORDER BY
  117283. ** expression within the sort-key that pushOntoSorter() will generate.
  117284. ** This allows the p->pEList field to be omitted from the sorted record,
  117285. ** saving space and CPU cycles. */
  117286. ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
  117287. for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
  117288. int j;
  117289. if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
  117290. p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
  117291. }
  117292. }
  117293. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117294. selectExprDefer(pParse, pSort, p->pEList, &pExtra);
  117295. if( pExtra && pParse->db->mallocFailed==0 ){
  117296. /* If there are any extra PK columns to add to the sorter records,
  117297. ** allocate extra memory cells and adjust the OpenEphemeral
  117298. ** instruction to account for the larger records. This is only
  117299. ** required if there are one or more WITHOUT ROWID tables with
  117300. ** composite primary keys in the SortCtx.aDefer[] array. */
  117301. VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  117302. pOp->p2 += (pExtra->nExpr - pSort->nDefer);
  117303. pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
  117304. pParse->nMem += pExtra->nExpr;
  117305. }
  117306. #endif
  117307. /* Adjust nResultCol to account for columns that are omitted
  117308. ** from the sorter by the optimizations in this branch */
  117309. pEList = p->pEList;
  117310. for(i=0; i<pEList->nExpr; i++){
  117311. if( pEList->a[i].u.x.iOrderByCol>0
  117312. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117313. || pEList->a[i].bSorterRef
  117314. #endif
  117315. ){
  117316. nResultCol--;
  117317. regOrig = 0;
  117318. }
  117319. }
  117320. testcase( regOrig );
  117321. testcase( eDest==SRT_Set );
  117322. testcase( eDest==SRT_Mem );
  117323. testcase( eDest==SRT_Coroutine );
  117324. testcase( eDest==SRT_Output );
  117325. assert( eDest==SRT_Set || eDest==SRT_Mem
  117326. || eDest==SRT_Coroutine || eDest==SRT_Output );
  117327. }
  117328. sRowLoadInfo.regResult = regResult;
  117329. sRowLoadInfo.ecelFlags = ecelFlags;
  117330. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117331. sRowLoadInfo.pExtra = pExtra;
  117332. sRowLoadInfo.regExtraResult = regResult + nResultCol;
  117333. if( pExtra ) nResultCol += pExtra->nExpr;
  117334. #endif
  117335. if( p->iLimit
  117336. && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
  117337. && nPrefixReg>0
  117338. ){
  117339. assert( pSort!=0 );
  117340. assert( hasDistinct==0 );
  117341. pSort->pDeferredRowLoad = &sRowLoadInfo;
  117342. regOrig = 0;
  117343. }else{
  117344. innerLoopLoadRow(pParse, p, &sRowLoadInfo);
  117345. }
  117346. }
  117347. /* If the DISTINCT keyword was present on the SELECT statement
  117348. ** and this row has been seen before, then do not make this row
  117349. ** part of the result.
  117350. */
  117351. if( hasDistinct ){
  117352. switch( pDistinct->eTnctType ){
  117353. case WHERE_DISTINCT_ORDERED: {
  117354. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  117355. int iJump; /* Jump destination */
  117356. int regPrev; /* Previous row content */
  117357. /* Allocate space for the previous row */
  117358. regPrev = pParse->nMem+1;
  117359. pParse->nMem += nResultCol;
  117360. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  117361. ** sets the MEM_Cleared bit on the first register of the
  117362. ** previous value. This will cause the OP_Ne below to always
  117363. ** fail on the first iteration of the loop even if the first
  117364. ** row is all NULLs.
  117365. */
  117366. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  117367. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  117368. pOp->opcode = OP_Null;
  117369. pOp->p1 = 1;
  117370. pOp->p2 = regPrev;
  117371. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  117372. for(i=0; i<nResultCol; i++){
  117373. CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
  117374. if( i<nResultCol-1 ){
  117375. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  117376. VdbeCoverage(v);
  117377. }else{
  117378. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  117379. VdbeCoverage(v);
  117380. }
  117381. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  117382. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  117383. }
  117384. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  117385. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  117386. break;
  117387. }
  117388. case WHERE_DISTINCT_UNIQUE: {
  117389. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  117390. break;
  117391. }
  117392. default: {
  117393. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  117394. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  117395. regResult);
  117396. break;
  117397. }
  117398. }
  117399. if( pSort==0 ){
  117400. codeOffset(v, p->iOffset, iContinue);
  117401. }
  117402. }
  117403. switch( eDest ){
  117404. /* In this mode, write each query result to the key of the temporary
  117405. ** table iParm.
  117406. */
  117407. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  117408. case SRT_Union: {
  117409. int r1;
  117410. r1 = sqlite3GetTempReg(pParse);
  117411. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  117412. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  117413. sqlite3ReleaseTempReg(pParse, r1);
  117414. break;
  117415. }
  117416. /* Construct a record from the query result, but instead of
  117417. ** saving that record, use it as a key to delete elements from
  117418. ** the temporary table iParm.
  117419. */
  117420. case SRT_Except: {
  117421. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  117422. break;
  117423. }
  117424. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  117425. /* Store the result as data using a unique key.
  117426. */
  117427. case SRT_Fifo:
  117428. case SRT_DistFifo:
  117429. case SRT_Table:
  117430. case SRT_EphemTab: {
  117431. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  117432. testcase( eDest==SRT_Table );
  117433. testcase( eDest==SRT_EphemTab );
  117434. testcase( eDest==SRT_Fifo );
  117435. testcase( eDest==SRT_DistFifo );
  117436. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  117437. #ifndef SQLITE_OMIT_CTE
  117438. if( eDest==SRT_DistFifo ){
  117439. /* If the destination is DistFifo, then cursor (iParm+1) is open
  117440. ** on an ephemeral index. If the current row is already present
  117441. ** in the index, do not write it to the output. If not, add the
  117442. ** current row to the index and proceed with writing it to the
  117443. ** output table as well. */
  117444. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  117445. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  117446. VdbeCoverage(v);
  117447. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
  117448. assert( pSort==0 );
  117449. }
  117450. #endif
  117451. if( pSort ){
  117452. assert( regResult==regOrig );
  117453. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
  117454. }else{
  117455. int r2 = sqlite3GetTempReg(pParse);
  117456. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  117457. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  117458. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  117459. sqlite3ReleaseTempReg(pParse, r2);
  117460. }
  117461. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  117462. break;
  117463. }
  117464. #ifndef SQLITE_OMIT_SUBQUERY
  117465. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  117466. ** then there should be a single item on the stack. Write this
  117467. ** item into the set table with bogus data.
  117468. */
  117469. case SRT_Set: {
  117470. if( pSort ){
  117471. /* At first glance you would think we could optimize out the
  117472. ** ORDER BY in this case since the order of entries in the set
  117473. ** does not matter. But there might be a LIMIT clause, in which
  117474. ** case the order does matter */
  117475. pushOntoSorter(
  117476. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  117477. }else{
  117478. int r1 = sqlite3GetTempReg(pParse);
  117479. assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
  117480. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
  117481. r1, pDest->zAffSdst, nResultCol);
  117482. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  117483. sqlite3ReleaseTempReg(pParse, r1);
  117484. }
  117485. break;
  117486. }
  117487. /* If any row exist in the result set, record that fact and abort.
  117488. */
  117489. case SRT_Exists: {
  117490. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  117491. /* The LIMIT clause will terminate the loop for us */
  117492. break;
  117493. }
  117494. /* If this is a scalar select that is part of an expression, then
  117495. ** store the results in the appropriate memory cell or array of
  117496. ** memory cells and break out of the scan loop.
  117497. */
  117498. case SRT_Mem: {
  117499. if( pSort ){
  117500. assert( nResultCol<=pDest->nSdst );
  117501. pushOntoSorter(
  117502. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  117503. }else{
  117504. assert( nResultCol==pDest->nSdst );
  117505. assert( regResult==iParm );
  117506. /* The LIMIT clause will jump out of the loop for us */
  117507. }
  117508. break;
  117509. }
  117510. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  117511. case SRT_Coroutine: /* Send data to a co-routine */
  117512. case SRT_Output: { /* Return the results */
  117513. testcase( eDest==SRT_Coroutine );
  117514. testcase( eDest==SRT_Output );
  117515. if( pSort ){
  117516. pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
  117517. nPrefixReg);
  117518. }else if( eDest==SRT_Coroutine ){
  117519. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  117520. }else{
  117521. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  117522. }
  117523. break;
  117524. }
  117525. #ifndef SQLITE_OMIT_CTE
  117526. /* Write the results into a priority queue that is order according to
  117527. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  117528. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  117529. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  117530. ** final OP_Sequence column. The last column is the record as a blob.
  117531. */
  117532. case SRT_DistQueue:
  117533. case SRT_Queue: {
  117534. int nKey;
  117535. int r1, r2, r3;
  117536. int addrTest = 0;
  117537. ExprList *pSO;
  117538. pSO = pDest->pOrderBy;
  117539. assert( pSO );
  117540. nKey = pSO->nExpr;
  117541. r1 = sqlite3GetTempReg(pParse);
  117542. r2 = sqlite3GetTempRange(pParse, nKey+2);
  117543. r3 = r2+nKey+1;
  117544. if( eDest==SRT_DistQueue ){
  117545. /* If the destination is DistQueue, then cursor (iParm+1) is open
  117546. ** on a second ephemeral index that holds all values every previously
  117547. ** added to the queue. */
  117548. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  117549. regResult, nResultCol);
  117550. VdbeCoverage(v);
  117551. }
  117552. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  117553. if( eDest==SRT_DistQueue ){
  117554. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  117555. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  117556. }
  117557. for(i=0; i<nKey; i++){
  117558. sqlite3VdbeAddOp2(v, OP_SCopy,
  117559. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  117560. r2+i);
  117561. }
  117562. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  117563. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  117564. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
  117565. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  117566. sqlite3ReleaseTempReg(pParse, r1);
  117567. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  117568. break;
  117569. }
  117570. #endif /* SQLITE_OMIT_CTE */
  117571. #if !defined(SQLITE_OMIT_TRIGGER)
  117572. /* Discard the results. This is used for SELECT statements inside
  117573. ** the body of a TRIGGER. The purpose of such selects is to call
  117574. ** user-defined functions that have side effects. We do not care
  117575. ** about the actual results of the select.
  117576. */
  117577. default: {
  117578. assert( eDest==SRT_Discard );
  117579. break;
  117580. }
  117581. #endif
  117582. }
  117583. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  117584. ** there is a sorter, in which case the sorter has already limited
  117585. ** the output for us.
  117586. */
  117587. if( pSort==0 && p->iLimit ){
  117588. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  117589. }
  117590. }
  117591. /*
  117592. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  117593. ** X extra columns.
  117594. */
  117595. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  117596. int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
  117597. KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
  117598. if( p ){
  117599. p->aSortOrder = (u8*)&p->aColl[N+X];
  117600. p->nKeyField = (u16)N;
  117601. p->nAllField = (u16)(N+X);
  117602. p->enc = ENC(db);
  117603. p->db = db;
  117604. p->nRef = 1;
  117605. memset(&p[1], 0, nExtra);
  117606. }else{
  117607. sqlite3OomFault(db);
  117608. }
  117609. return p;
  117610. }
  117611. /*
  117612. ** Deallocate a KeyInfo object
  117613. */
  117614. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  117615. if( p ){
  117616. assert( p->nRef>0 );
  117617. p->nRef--;
  117618. if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
  117619. }
  117620. }
  117621. /*
  117622. ** Make a new pointer to a KeyInfo object
  117623. */
  117624. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  117625. if( p ){
  117626. assert( p->nRef>0 );
  117627. p->nRef++;
  117628. }
  117629. return p;
  117630. }
  117631. #ifdef SQLITE_DEBUG
  117632. /*
  117633. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  117634. ** can only be changed if this is just a single reference to the object.
  117635. **
  117636. ** This routine is used only inside of assert() statements.
  117637. */
  117638. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  117639. #endif /* SQLITE_DEBUG */
  117640. /*
  117641. ** Given an expression list, generate a KeyInfo structure that records
  117642. ** the collating sequence for each expression in that expression list.
  117643. **
  117644. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  117645. ** KeyInfo structure is appropriate for initializing a virtual index to
  117646. ** implement that clause. If the ExprList is the result set of a SELECT
  117647. ** then the KeyInfo structure is appropriate for initializing a virtual
  117648. ** index to implement a DISTINCT test.
  117649. **
  117650. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  117651. ** function is responsible for seeing that this structure is eventually
  117652. ** freed.
  117653. */
  117654. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(
  117655. Parse *pParse, /* Parsing context */
  117656. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  117657. int iStart, /* Begin with this column of pList */
  117658. int nExtra /* Add this many extra columns to the end */
  117659. ){
  117660. int nExpr;
  117661. KeyInfo *pInfo;
  117662. struct ExprList_item *pItem;
  117663. sqlite3 *db = pParse->db;
  117664. int i;
  117665. nExpr = pList->nExpr;
  117666. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  117667. if( pInfo ){
  117668. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  117669. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  117670. pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
  117671. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  117672. }
  117673. }
  117674. return pInfo;
  117675. }
  117676. /*
  117677. ** Name of the connection operator, used for error messages.
  117678. */
  117679. static const char *selectOpName(int id){
  117680. char *z;
  117681. switch( id ){
  117682. case TK_ALL: z = "UNION ALL"; break;
  117683. case TK_INTERSECT: z = "INTERSECT"; break;
  117684. case TK_EXCEPT: z = "EXCEPT"; break;
  117685. default: z = "UNION"; break;
  117686. }
  117687. return z;
  117688. }
  117689. #ifndef SQLITE_OMIT_EXPLAIN
  117690. /*
  117691. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  117692. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  117693. ** where the caption is of the form:
  117694. **
  117695. ** "USE TEMP B-TREE FOR xxx"
  117696. **
  117697. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  117698. ** is determined by the zUsage argument.
  117699. */
  117700. static void explainTempTable(Parse *pParse, const char *zUsage){
  117701. ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
  117702. }
  117703. /*
  117704. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  117705. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  117706. ** in sqlite3Select() to assign values to structure member variables that
  117707. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  117708. ** code with #ifndef directives.
  117709. */
  117710. # define explainSetInteger(a, b) a = b
  117711. #else
  117712. /* No-op versions of the explainXXX() functions and macros. */
  117713. # define explainTempTable(y,z)
  117714. # define explainSetInteger(y,z)
  117715. #endif
  117716. /*
  117717. ** If the inner loop was generated using a non-null pOrderBy argument,
  117718. ** then the results were placed in a sorter. After the loop is terminated
  117719. ** we need to run the sorter and output the results. The following
  117720. ** routine generates the code needed to do that.
  117721. */
  117722. static void generateSortTail(
  117723. Parse *pParse, /* Parsing context */
  117724. Select *p, /* The SELECT statement */
  117725. SortCtx *pSort, /* Information on the ORDER BY clause */
  117726. int nColumn, /* Number of columns of data */
  117727. SelectDest *pDest /* Write the sorted results here */
  117728. ){
  117729. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  117730. int addrBreak = pSort->labelDone; /* Jump here to exit loop */
  117731. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  117732. int addr; /* Top of output loop. Jump for Next. */
  117733. int addrOnce = 0;
  117734. int iTab;
  117735. ExprList *pOrderBy = pSort->pOrderBy;
  117736. int eDest = pDest->eDest;
  117737. int iParm = pDest->iSDParm;
  117738. int regRow;
  117739. int regRowid;
  117740. int iCol;
  117741. int nKey; /* Number of key columns in sorter record */
  117742. int iSortTab; /* Sorter cursor to read from */
  117743. int i;
  117744. int bSeq; /* True if sorter record includes seq. no. */
  117745. int nRefKey = 0;
  117746. struct ExprList_item *aOutEx = p->pEList->a;
  117747. assert( addrBreak<0 );
  117748. if( pSort->labelBkOut ){
  117749. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  117750. sqlite3VdbeGoto(v, addrBreak);
  117751. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  117752. }
  117753. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117754. /* Open any cursors needed for sorter-reference expressions */
  117755. for(i=0; i<pSort->nDefer; i++){
  117756. Table *pTab = pSort->aDefer[i].pTab;
  117757. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  117758. sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
  117759. nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
  117760. }
  117761. #endif
  117762. iTab = pSort->iECursor;
  117763. if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
  117764. regRowid = 0;
  117765. regRow = pDest->iSdst;
  117766. }else{
  117767. regRowid = sqlite3GetTempReg(pParse);
  117768. regRow = sqlite3GetTempRange(pParse, nColumn);
  117769. }
  117770. nKey = pOrderBy->nExpr - pSort->nOBSat;
  117771. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  117772. int regSortOut = ++pParse->nMem;
  117773. iSortTab = pParse->nTab++;
  117774. if( pSort->labelBkOut ){
  117775. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  117776. }
  117777. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
  117778. nKey+1+nColumn+nRefKey);
  117779. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  117780. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  117781. VdbeCoverage(v);
  117782. codeOffset(v, p->iOffset, addrContinue);
  117783. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  117784. bSeq = 0;
  117785. }else{
  117786. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  117787. codeOffset(v, p->iOffset, addrContinue);
  117788. iSortTab = iTab;
  117789. bSeq = 1;
  117790. }
  117791. for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
  117792. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117793. if( aOutEx[i].bSorterRef ) continue;
  117794. #endif
  117795. if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
  117796. }
  117797. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117798. if( pSort->nDefer ){
  117799. int iKey = iCol+1;
  117800. int regKey = sqlite3GetTempRange(pParse, nRefKey);
  117801. for(i=0; i<pSort->nDefer; i++){
  117802. int iCsr = pSort->aDefer[i].iCsr;
  117803. Table *pTab = pSort->aDefer[i].pTab;
  117804. int nKey = pSort->aDefer[i].nKey;
  117805. sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
  117806. if( HasRowid(pTab) ){
  117807. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
  117808. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
  117809. sqlite3VdbeCurrentAddr(v)+1, regKey);
  117810. }else{
  117811. int k;
  117812. int iJmp;
  117813. assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
  117814. for(k=0; k<nKey; k++){
  117815. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
  117816. }
  117817. iJmp = sqlite3VdbeCurrentAddr(v);
  117818. sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
  117819. sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
  117820. sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
  117821. }
  117822. }
  117823. sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
  117824. }
  117825. #endif
  117826. for(i=nColumn-1; i>=0; i--){
  117827. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117828. if( aOutEx[i].bSorterRef ){
  117829. sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
  117830. }else
  117831. #endif
  117832. {
  117833. int iRead;
  117834. if( aOutEx[i].u.x.iOrderByCol ){
  117835. iRead = aOutEx[i].u.x.iOrderByCol-1;
  117836. }else{
  117837. iRead = iCol--;
  117838. }
  117839. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
  117840. VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan));
  117841. }
  117842. }
  117843. switch( eDest ){
  117844. case SRT_Table:
  117845. case SRT_EphemTab: {
  117846. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  117847. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  117848. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  117849. break;
  117850. }
  117851. #ifndef SQLITE_OMIT_SUBQUERY
  117852. case SRT_Set: {
  117853. assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
  117854. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
  117855. pDest->zAffSdst, nColumn);
  117856. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
  117857. break;
  117858. }
  117859. case SRT_Mem: {
  117860. /* The LIMIT clause will terminate the loop for us */
  117861. break;
  117862. }
  117863. #endif
  117864. default: {
  117865. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  117866. testcase( eDest==SRT_Output );
  117867. testcase( eDest==SRT_Coroutine );
  117868. if( eDest==SRT_Output ){
  117869. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  117870. }else{
  117871. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  117872. }
  117873. break;
  117874. }
  117875. }
  117876. if( regRowid ){
  117877. if( eDest==SRT_Set ){
  117878. sqlite3ReleaseTempRange(pParse, regRow, nColumn);
  117879. }else{
  117880. sqlite3ReleaseTempReg(pParse, regRow);
  117881. }
  117882. sqlite3ReleaseTempReg(pParse, regRowid);
  117883. }
  117884. /* The bottom of the loop
  117885. */
  117886. sqlite3VdbeResolveLabel(v, addrContinue);
  117887. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  117888. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  117889. }else{
  117890. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  117891. }
  117892. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  117893. sqlite3VdbeResolveLabel(v, addrBreak);
  117894. }
  117895. /*
  117896. ** Return a pointer to a string containing the 'declaration type' of the
  117897. ** expression pExpr. The string may be treated as static by the caller.
  117898. **
  117899. ** Also try to estimate the size of the returned value and return that
  117900. ** result in *pEstWidth.
  117901. **
  117902. ** The declaration type is the exact datatype definition extracted from the
  117903. ** original CREATE TABLE statement if the expression is a column. The
  117904. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  117905. ** is considered a column can be complex in the presence of subqueries. The
  117906. ** result-set expression in all of the following SELECT statements is
  117907. ** considered a column by this function.
  117908. **
  117909. ** SELECT col FROM tbl;
  117910. ** SELECT (SELECT col FROM tbl;
  117911. ** SELECT (SELECT col FROM tbl);
  117912. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  117913. **
  117914. ** The declaration type for any expression other than a column is NULL.
  117915. **
  117916. ** This routine has either 3 or 6 parameters depending on whether or not
  117917. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  117918. */
  117919. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  117920. # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
  117921. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  117922. # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
  117923. #endif
  117924. static const char *columnTypeImpl(
  117925. NameContext *pNC,
  117926. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  117927. Expr *pExpr
  117928. #else
  117929. Expr *pExpr,
  117930. const char **pzOrigDb,
  117931. const char **pzOrigTab,
  117932. const char **pzOrigCol
  117933. #endif
  117934. ){
  117935. char const *zType = 0;
  117936. int j;
  117937. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  117938. char const *zOrigDb = 0;
  117939. char const *zOrigTab = 0;
  117940. char const *zOrigCol = 0;
  117941. #endif
  117942. assert( pExpr!=0 );
  117943. assert( pNC->pSrcList!=0 );
  117944. assert( pExpr->op!=TK_AGG_COLUMN ); /* This routine runes before aggregates
  117945. ** are processed */
  117946. switch( pExpr->op ){
  117947. case TK_COLUMN: {
  117948. /* The expression is a column. Locate the table the column is being
  117949. ** extracted from in NameContext.pSrcList. This table may be real
  117950. ** database table or a subquery.
  117951. */
  117952. Table *pTab = 0; /* Table structure column is extracted from */
  117953. Select *pS = 0; /* Select the column is extracted from */
  117954. int iCol = pExpr->iColumn; /* Index of column in pTab */
  117955. while( pNC && !pTab ){
  117956. SrcList *pTabList = pNC->pSrcList;
  117957. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  117958. if( j<pTabList->nSrc ){
  117959. pTab = pTabList->a[j].pTab;
  117960. pS = pTabList->a[j].pSelect;
  117961. }else{
  117962. pNC = pNC->pNext;
  117963. }
  117964. }
  117965. if( pTab==0 ){
  117966. /* At one time, code such as "SELECT new.x" within a trigger would
  117967. ** cause this condition to run. Since then, we have restructured how
  117968. ** trigger code is generated and so this condition is no longer
  117969. ** possible. However, it can still be true for statements like
  117970. ** the following:
  117971. **
  117972. ** CREATE TABLE t1(col INTEGER);
  117973. ** SELECT (SELECT t1.col) FROM FROM t1;
  117974. **
  117975. ** when columnType() is called on the expression "t1.col" in the
  117976. ** sub-select. In this case, set the column type to NULL, even
  117977. ** though it should really be "INTEGER".
  117978. **
  117979. ** This is not a problem, as the column type of "t1.col" is never
  117980. ** used. When columnType() is called on the expression
  117981. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  117982. ** branch below. */
  117983. break;
  117984. }
  117985. assert( pTab && pExpr->y.pTab==pTab );
  117986. if( pS ){
  117987. /* The "table" is actually a sub-select or a view in the FROM clause
  117988. ** of the SELECT statement. Return the declaration type and origin
  117989. ** data for the result-set column of the sub-select.
  117990. */
  117991. if( iCol>=0 && iCol<pS->pEList->nExpr ){
  117992. /* If iCol is less than zero, then the expression requests the
  117993. ** rowid of the sub-select or view. This expression is legal (see
  117994. ** test case misc2.2.2) - it always evaluates to NULL.
  117995. */
  117996. NameContext sNC;
  117997. Expr *p = pS->pEList->a[iCol].pExpr;
  117998. sNC.pSrcList = pS->pSrc;
  117999. sNC.pNext = pNC;
  118000. sNC.pParse = pNC->pParse;
  118001. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
  118002. }
  118003. }else{
  118004. /* A real table or a CTE table */
  118005. assert( !pS );
  118006. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  118007. if( iCol<0 ) iCol = pTab->iPKey;
  118008. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  118009. if( iCol<0 ){
  118010. zType = "INTEGER";
  118011. zOrigCol = "rowid";
  118012. }else{
  118013. zOrigCol = pTab->aCol[iCol].zName;
  118014. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  118015. }
  118016. zOrigTab = pTab->zName;
  118017. if( pNC->pParse && pTab->pSchema ){
  118018. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  118019. zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
  118020. }
  118021. #else
  118022. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  118023. if( iCol<0 ){
  118024. zType = "INTEGER";
  118025. }else{
  118026. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  118027. }
  118028. #endif
  118029. }
  118030. break;
  118031. }
  118032. #ifndef SQLITE_OMIT_SUBQUERY
  118033. case TK_SELECT: {
  118034. /* The expression is a sub-select. Return the declaration type and
  118035. ** origin info for the single column in the result set of the SELECT
  118036. ** statement.
  118037. */
  118038. NameContext sNC;
  118039. Select *pS = pExpr->x.pSelect;
  118040. Expr *p = pS->pEList->a[0].pExpr;
  118041. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  118042. sNC.pSrcList = pS->pSrc;
  118043. sNC.pNext = pNC;
  118044. sNC.pParse = pNC->pParse;
  118045. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  118046. break;
  118047. }
  118048. #endif
  118049. }
  118050. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  118051. if( pzOrigDb ){
  118052. assert( pzOrigTab && pzOrigCol );
  118053. *pzOrigDb = zOrigDb;
  118054. *pzOrigTab = zOrigTab;
  118055. *pzOrigCol = zOrigCol;
  118056. }
  118057. #endif
  118058. return zType;
  118059. }
  118060. /*
  118061. ** Generate code that will tell the VDBE the declaration types of columns
  118062. ** in the result set.
  118063. */
  118064. static void generateColumnTypes(
  118065. Parse *pParse, /* Parser context */
  118066. SrcList *pTabList, /* List of tables */
  118067. ExprList *pEList /* Expressions defining the result set */
  118068. ){
  118069. #ifndef SQLITE_OMIT_DECLTYPE
  118070. Vdbe *v = pParse->pVdbe;
  118071. int i;
  118072. NameContext sNC;
  118073. sNC.pSrcList = pTabList;
  118074. sNC.pParse = pParse;
  118075. sNC.pNext = 0;
  118076. for(i=0; i<pEList->nExpr; i++){
  118077. Expr *p = pEList->a[i].pExpr;
  118078. const char *zType;
  118079. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  118080. const char *zOrigDb = 0;
  118081. const char *zOrigTab = 0;
  118082. const char *zOrigCol = 0;
  118083. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  118084. /* The vdbe must make its own copy of the column-type and other
  118085. ** column specific strings, in case the schema is reset before this
  118086. ** virtual machine is deleted.
  118087. */
  118088. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  118089. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  118090. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  118091. #else
  118092. zType = columnType(&sNC, p, 0, 0, 0);
  118093. #endif
  118094. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  118095. }
  118096. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  118097. }
  118098. /*
  118099. ** Compute the column names for a SELECT statement.
  118100. **
  118101. ** The only guarantee that SQLite makes about column names is that if the
  118102. ** column has an AS clause assigning it a name, that will be the name used.
  118103. ** That is the only documented guarantee. However, countless applications
  118104. ** developed over the years have made baseless assumptions about column names
  118105. ** and will break if those assumptions changes. Hence, use extreme caution
  118106. ** when modifying this routine to avoid breaking legacy.
  118107. **
  118108. ** See Also: sqlite3ColumnsFromExprList()
  118109. **
  118110. ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
  118111. ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
  118112. ** applications should operate this way. Nevertheless, we need to support the
  118113. ** other modes for legacy:
  118114. **
  118115. ** short=OFF, full=OFF: Column name is the text of the expression has it
  118116. ** originally appears in the SELECT statement. In
  118117. ** other words, the zSpan of the result expression.
  118118. **
  118119. ** short=ON, full=OFF: (This is the default setting). If the result
  118120. ** refers directly to a table column, then the
  118121. ** result column name is just the table column
  118122. ** name: COLUMN. Otherwise use zSpan.
  118123. **
  118124. ** full=ON, short=ANY: If the result refers directly to a table column,
  118125. ** then the result column name with the table name
  118126. ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
  118127. */
  118128. static void generateColumnNames(
  118129. Parse *pParse, /* Parser context */
  118130. Select *pSelect /* Generate column names for this SELECT statement */
  118131. ){
  118132. Vdbe *v = pParse->pVdbe;
  118133. int i;
  118134. Table *pTab;
  118135. SrcList *pTabList;
  118136. ExprList *pEList;
  118137. sqlite3 *db = pParse->db;
  118138. int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
  118139. int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
  118140. #ifndef SQLITE_OMIT_EXPLAIN
  118141. /* If this is an EXPLAIN, skip this step */
  118142. if( pParse->explain ){
  118143. return;
  118144. }
  118145. #endif
  118146. if( pParse->colNamesSet ) return;
  118147. /* Column names are determined by the left-most term of a compound select */
  118148. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  118149. SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
  118150. pTabList = pSelect->pSrc;
  118151. pEList = pSelect->pEList;
  118152. assert( v!=0 );
  118153. assert( pTabList!=0 );
  118154. pParse->colNamesSet = 1;
  118155. fullName = (db->flags & SQLITE_FullColNames)!=0;
  118156. srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
  118157. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  118158. for(i=0; i<pEList->nExpr; i++){
  118159. Expr *p = pEList->a[i].pExpr;
  118160. assert( p!=0 );
  118161. assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
  118162. assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
  118163. if( pEList->a[i].zName ){
  118164. /* An AS clause always takes first priority */
  118165. char *zName = pEList->a[i].zName;
  118166. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  118167. }else if( srcName && p->op==TK_COLUMN ){
  118168. char *zCol;
  118169. int iCol = p->iColumn;
  118170. pTab = p->y.pTab;
  118171. assert( pTab!=0 );
  118172. if( iCol<0 ) iCol = pTab->iPKey;
  118173. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  118174. if( iCol<0 ){
  118175. zCol = "rowid";
  118176. }else{
  118177. zCol = pTab->aCol[iCol].zName;
  118178. }
  118179. if( fullName ){
  118180. char *zName = 0;
  118181. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  118182. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  118183. }else{
  118184. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  118185. }
  118186. }else{
  118187. const char *z = pEList->a[i].zSpan;
  118188. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  118189. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  118190. }
  118191. }
  118192. generateColumnTypes(pParse, pTabList, pEList);
  118193. }
  118194. /*
  118195. ** Given an expression list (which is really the list of expressions
  118196. ** that form the result set of a SELECT statement) compute appropriate
  118197. ** column names for a table that would hold the expression list.
  118198. **
  118199. ** All column names will be unique.
  118200. **
  118201. ** Only the column names are computed. Column.zType, Column.zColl,
  118202. ** and other fields of Column are zeroed.
  118203. **
  118204. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  118205. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  118206. **
  118207. ** The only guarantee that SQLite makes about column names is that if the
  118208. ** column has an AS clause assigning it a name, that will be the name used.
  118209. ** That is the only documented guarantee. However, countless applications
  118210. ** developed over the years have made baseless assumptions about column names
  118211. ** and will break if those assumptions changes. Hence, use extreme caution
  118212. ** when modifying this routine to avoid breaking legacy.
  118213. **
  118214. ** See Also: generateColumnNames()
  118215. */
  118216. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  118217. Parse *pParse, /* Parsing context */
  118218. ExprList *pEList, /* Expr list from which to derive column names */
  118219. i16 *pnCol, /* Write the number of columns here */
  118220. Column **paCol /* Write the new column list here */
  118221. ){
  118222. sqlite3 *db = pParse->db; /* Database connection */
  118223. int i, j; /* Loop counters */
  118224. u32 cnt; /* Index added to make the name unique */
  118225. Column *aCol, *pCol; /* For looping over result columns */
  118226. int nCol; /* Number of columns in the result set */
  118227. char *zName; /* Column name */
  118228. int nName; /* Size of name in zName[] */
  118229. Hash ht; /* Hash table of column names */
  118230. sqlite3HashInit(&ht);
  118231. if( pEList ){
  118232. nCol = pEList->nExpr;
  118233. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  118234. testcase( aCol==0 );
  118235. if( nCol>32767 ) nCol = 32767;
  118236. }else{
  118237. nCol = 0;
  118238. aCol = 0;
  118239. }
  118240. assert( nCol==(i16)nCol );
  118241. *pnCol = nCol;
  118242. *paCol = aCol;
  118243. for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
  118244. /* Get an appropriate name for the column
  118245. */
  118246. if( (zName = pEList->a[i].zName)!=0 ){
  118247. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  118248. }else{
  118249. Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  118250. while( pColExpr->op==TK_DOT ){
  118251. pColExpr = pColExpr->pRight;
  118252. assert( pColExpr!=0 );
  118253. }
  118254. assert( pColExpr->op!=TK_AGG_COLUMN );
  118255. if( pColExpr->op==TK_COLUMN ){
  118256. /* For columns use the column name name */
  118257. int iCol = pColExpr->iColumn;
  118258. Table *pTab = pColExpr->y.pTab;
  118259. assert( pTab!=0 );
  118260. if( iCol<0 ) iCol = pTab->iPKey;
  118261. zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
  118262. }else if( pColExpr->op==TK_ID ){
  118263. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  118264. zName = pColExpr->u.zToken;
  118265. }else{
  118266. /* Use the original text of the column expression as its name */
  118267. zName = pEList->a[i].zSpan;
  118268. }
  118269. }
  118270. if( zName ){
  118271. zName = sqlite3DbStrDup(db, zName);
  118272. }else{
  118273. zName = sqlite3MPrintf(db,"column%d",i+1);
  118274. }
  118275. /* Make sure the column name is unique. If the name is not unique,
  118276. ** append an integer to the name so that it becomes unique.
  118277. */
  118278. cnt = 0;
  118279. while( zName && sqlite3HashFind(&ht, zName)!=0 ){
  118280. nName = sqlite3Strlen30(zName);
  118281. if( nName>0 ){
  118282. for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
  118283. if( zName[j]==':' ) nName = j;
  118284. }
  118285. zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  118286. if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  118287. }
  118288. pCol->zName = zName;
  118289. sqlite3ColumnPropertiesFromName(0, pCol);
  118290. if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  118291. sqlite3OomFault(db);
  118292. }
  118293. }
  118294. sqlite3HashClear(&ht);
  118295. if( db->mallocFailed ){
  118296. for(j=0; j<i; j++){
  118297. sqlite3DbFree(db, aCol[j].zName);
  118298. }
  118299. sqlite3DbFree(db, aCol);
  118300. *paCol = 0;
  118301. *pnCol = 0;
  118302. return SQLITE_NOMEM_BKPT;
  118303. }
  118304. return SQLITE_OK;
  118305. }
  118306. /*
  118307. ** Add type and collation information to a column list based on
  118308. ** a SELECT statement.
  118309. **
  118310. ** The column list presumably came from selectColumnNamesFromExprList().
  118311. ** The column list has only names, not types or collations. This
  118312. ** routine goes through and adds the types and collations.
  118313. **
  118314. ** This routine requires that all identifiers in the SELECT
  118315. ** statement be resolved.
  118316. */
  118317. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
  118318. Parse *pParse, /* Parsing contexts */
  118319. Table *pTab, /* Add column type information to this table */
  118320. Select *pSelect /* SELECT used to determine types and collations */
  118321. ){
  118322. sqlite3 *db = pParse->db;
  118323. NameContext sNC;
  118324. Column *pCol;
  118325. CollSeq *pColl;
  118326. int i;
  118327. Expr *p;
  118328. struct ExprList_item *a;
  118329. assert( pSelect!=0 );
  118330. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  118331. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  118332. if( db->mallocFailed ) return;
  118333. memset(&sNC, 0, sizeof(sNC));
  118334. sNC.pSrcList = pSelect->pSrc;
  118335. a = pSelect->pEList->a;
  118336. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  118337. const char *zType;
  118338. int n, m;
  118339. p = a[i].pExpr;
  118340. zType = columnType(&sNC, p, 0, 0, 0);
  118341. /* pCol->szEst = ... // Column size est for SELECT tables never used */
  118342. pCol->affinity = sqlite3ExprAffinity(p);
  118343. if( zType ){
  118344. m = sqlite3Strlen30(zType);
  118345. n = sqlite3Strlen30(pCol->zName);
  118346. pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
  118347. if( pCol->zName ){
  118348. memcpy(&pCol->zName[n+1], zType, m+1);
  118349. pCol->colFlags |= COLFLAG_HASTYPE;
  118350. }
  118351. }
  118352. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  118353. pColl = sqlite3ExprCollSeq(pParse, p);
  118354. if( pColl && pCol->zColl==0 ){
  118355. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  118356. }
  118357. }
  118358. pTab->szTabRow = 1; /* Any non-zero value works */
  118359. }
  118360. /*
  118361. ** Given a SELECT statement, generate a Table structure that describes
  118362. ** the result set of that SELECT.
  118363. */
  118364. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  118365. Table *pTab;
  118366. sqlite3 *db = pParse->db;
  118367. int savedFlags;
  118368. savedFlags = db->flags;
  118369. db->flags &= ~SQLITE_FullColNames;
  118370. db->flags |= SQLITE_ShortColNames;
  118371. sqlite3SelectPrep(pParse, pSelect, 0);
  118372. if( pParse->nErr ) return 0;
  118373. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  118374. db->flags = savedFlags;
  118375. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  118376. if( pTab==0 ){
  118377. return 0;
  118378. }
  118379. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  118380. ** is disabled */
  118381. assert( db->lookaside.bDisable );
  118382. pTab->nTabRef = 1;
  118383. pTab->zName = 0;
  118384. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  118385. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  118386. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  118387. pTab->iPKey = -1;
  118388. if( db->mallocFailed ){
  118389. sqlite3DeleteTable(db, pTab);
  118390. return 0;
  118391. }
  118392. return pTab;
  118393. }
  118394. /*
  118395. ** Get a VDBE for the given parser context. Create a new one if necessary.
  118396. ** If an error occurs, return NULL and leave a message in pParse.
  118397. */
  118398. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  118399. if( pParse->pVdbe ){
  118400. return pParse->pVdbe;
  118401. }
  118402. if( pParse->pToplevel==0
  118403. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  118404. ){
  118405. pParse->okConstFactor = 1;
  118406. }
  118407. return sqlite3VdbeCreate(pParse);
  118408. }
  118409. /*
  118410. ** Compute the iLimit and iOffset fields of the SELECT based on the
  118411. ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
  118412. ** that appear in the original SQL statement after the LIMIT and OFFSET
  118413. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  118414. ** are the integer memory register numbers for counters used to compute
  118415. ** the limit and offset. If there is no limit and/or offset, then
  118416. ** iLimit and iOffset are negative.
  118417. **
  118418. ** This routine changes the values of iLimit and iOffset only if
  118419. ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
  118420. ** and iOffset should have been preset to appropriate default values (zero)
  118421. ** prior to calling this routine.
  118422. **
  118423. ** The iOffset register (if it exists) is initialized to the value
  118424. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  118425. ** iOffset+1 is initialized to LIMIT+OFFSET.
  118426. **
  118427. ** Only if pLimit->pLeft!=0 do the limit registers get
  118428. ** redefined. The UNION ALL operator uses this property to force
  118429. ** the reuse of the same limit and offset registers across multiple
  118430. ** SELECT statements.
  118431. */
  118432. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  118433. Vdbe *v = 0;
  118434. int iLimit = 0;
  118435. int iOffset;
  118436. int n;
  118437. Expr *pLimit = p->pLimit;
  118438. if( p->iLimit ) return;
  118439. /*
  118440. ** "LIMIT -1" always shows all rows. There is some
  118441. ** controversy about what the correct behavior should be.
  118442. ** The current implementation interprets "LIMIT 0" to mean
  118443. ** no rows.
  118444. */
  118445. if( pLimit ){
  118446. assert( pLimit->op==TK_LIMIT );
  118447. assert( pLimit->pLeft!=0 );
  118448. p->iLimit = iLimit = ++pParse->nMem;
  118449. v = sqlite3GetVdbe(pParse);
  118450. assert( v!=0 );
  118451. if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
  118452. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  118453. VdbeComment((v, "LIMIT counter"));
  118454. if( n==0 ){
  118455. sqlite3VdbeGoto(v, iBreak);
  118456. }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
  118457. p->nSelectRow = sqlite3LogEst((u64)n);
  118458. p->selFlags |= SF_FixedLimit;
  118459. }
  118460. }else{
  118461. sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
  118462. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  118463. VdbeComment((v, "LIMIT counter"));
  118464. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  118465. }
  118466. if( pLimit->pRight ){
  118467. p->iOffset = iOffset = ++pParse->nMem;
  118468. pParse->nMem++; /* Allocate an extra register for limit+offset */
  118469. sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
  118470. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  118471. VdbeComment((v, "OFFSET counter"));
  118472. sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
  118473. VdbeComment((v, "LIMIT+OFFSET"));
  118474. }
  118475. }
  118476. }
  118477. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  118478. /*
  118479. ** Return the appropriate collating sequence for the iCol-th column of
  118480. ** the result set for the compound-select statement "p". Return NULL if
  118481. ** the column has no default collating sequence.
  118482. **
  118483. ** The collating sequence for the compound select is taken from the
  118484. ** left-most term of the select that has a collating sequence.
  118485. */
  118486. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  118487. CollSeq *pRet;
  118488. if( p->pPrior ){
  118489. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  118490. }else{
  118491. pRet = 0;
  118492. }
  118493. assert( iCol>=0 );
  118494. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  118495. ** have been thrown during name resolution and we would not have gotten
  118496. ** this far */
  118497. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  118498. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  118499. }
  118500. return pRet;
  118501. }
  118502. /*
  118503. ** The select statement passed as the second parameter is a compound SELECT
  118504. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  118505. ** structure suitable for implementing the ORDER BY.
  118506. **
  118507. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  118508. ** function is responsible for ensuring that this structure is eventually
  118509. ** freed.
  118510. */
  118511. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  118512. ExprList *pOrderBy = p->pOrderBy;
  118513. int nOrderBy = p->pOrderBy->nExpr;
  118514. sqlite3 *db = pParse->db;
  118515. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  118516. if( pRet ){
  118517. int i;
  118518. for(i=0; i<nOrderBy; i++){
  118519. struct ExprList_item *pItem = &pOrderBy->a[i];
  118520. Expr *pTerm = pItem->pExpr;
  118521. CollSeq *pColl;
  118522. if( pTerm->flags & EP_Collate ){
  118523. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  118524. }else{
  118525. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  118526. if( pColl==0 ) pColl = db->pDfltColl;
  118527. pOrderBy->a[i].pExpr =
  118528. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  118529. }
  118530. assert( sqlite3KeyInfoIsWriteable(pRet) );
  118531. pRet->aColl[i] = pColl;
  118532. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  118533. }
  118534. }
  118535. return pRet;
  118536. }
  118537. #ifndef SQLITE_OMIT_CTE
  118538. /*
  118539. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  118540. ** query of the form:
  118541. **
  118542. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  118543. ** \___________/ \_______________/
  118544. ** p->pPrior p
  118545. **
  118546. **
  118547. ** There is exactly one reference to the recursive-table in the FROM clause
  118548. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  118549. **
  118550. ** The setup-query runs once to generate an initial set of rows that go
  118551. ** into a Queue table. Rows are extracted from the Queue table one by
  118552. ** one. Each row extracted from Queue is output to pDest. Then the single
  118553. ** extracted row (now in the iCurrent table) becomes the content of the
  118554. ** recursive-table for a recursive-query run. The output of the recursive-query
  118555. ** is added back into the Queue table. Then another row is extracted from Queue
  118556. ** and the iteration continues until the Queue table is empty.
  118557. **
  118558. ** If the compound query operator is UNION then no duplicate rows are ever
  118559. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  118560. ** that have ever been inserted into Queue and causes duplicates to be
  118561. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  118562. **
  118563. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  118564. ** ORDER BY order and the first entry is extracted for each cycle. Without
  118565. ** an ORDER BY, the Queue table is just a FIFO.
  118566. **
  118567. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  118568. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  118569. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  118570. ** with a positive value, then the first OFFSET outputs are discarded rather
  118571. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  118572. ** rows have been skipped.
  118573. */
  118574. static void generateWithRecursiveQuery(
  118575. Parse *pParse, /* Parsing context */
  118576. Select *p, /* The recursive SELECT to be coded */
  118577. SelectDest *pDest /* What to do with query results */
  118578. ){
  118579. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  118580. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  118581. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  118582. Select *pSetup = p->pPrior; /* The setup query */
  118583. int addrTop; /* Top of the loop */
  118584. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  118585. int iCurrent = 0; /* The Current table */
  118586. int regCurrent; /* Register holding Current table */
  118587. int iQueue; /* The Queue table */
  118588. int iDistinct = 0; /* To ensure unique results if UNION */
  118589. int eDest = SRT_Fifo; /* How to write to Queue */
  118590. SelectDest destQueue; /* SelectDest targetting the Queue table */
  118591. int i; /* Loop counter */
  118592. int rc; /* Result code */
  118593. ExprList *pOrderBy; /* The ORDER BY clause */
  118594. Expr *pLimit; /* Saved LIMIT and OFFSET */
  118595. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  118596. #ifndef SQLITE_OMIT_WINDOWFUNC
  118597. if( p->pWin ){
  118598. sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
  118599. return;
  118600. }
  118601. #endif
  118602. /* Obtain authorization to do a recursive query */
  118603. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  118604. /* Process the LIMIT and OFFSET clauses, if they exist */
  118605. addrBreak = sqlite3VdbeMakeLabel(v);
  118606. p->nSelectRow = 320; /* 4 billion rows */
  118607. computeLimitRegisters(pParse, p, addrBreak);
  118608. pLimit = p->pLimit;
  118609. regLimit = p->iLimit;
  118610. regOffset = p->iOffset;
  118611. p->pLimit = 0;
  118612. p->iLimit = p->iOffset = 0;
  118613. pOrderBy = p->pOrderBy;
  118614. /* Locate the cursor number of the Current table */
  118615. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  118616. if( pSrc->a[i].fg.isRecursive ){
  118617. iCurrent = pSrc->a[i].iCursor;
  118618. break;
  118619. }
  118620. }
  118621. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  118622. ** the Distinct table must be exactly one greater than Queue in order
  118623. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  118624. iQueue = pParse->nTab++;
  118625. if( p->op==TK_UNION ){
  118626. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  118627. iDistinct = pParse->nTab++;
  118628. }else{
  118629. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  118630. }
  118631. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  118632. /* Allocate cursors for Current, Queue, and Distinct. */
  118633. regCurrent = ++pParse->nMem;
  118634. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  118635. if( pOrderBy ){
  118636. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  118637. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  118638. (char*)pKeyInfo, P4_KEYINFO);
  118639. destQueue.pOrderBy = pOrderBy;
  118640. }else{
  118641. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  118642. }
  118643. VdbeComment((v, "Queue table"));
  118644. if( iDistinct ){
  118645. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  118646. p->selFlags |= SF_UsesEphemeral;
  118647. }
  118648. /* Detach the ORDER BY clause from the compound SELECT */
  118649. p->pOrderBy = 0;
  118650. /* Store the results of the setup-query in Queue. */
  118651. pSetup->pNext = 0;
  118652. ExplainQueryPlan((pParse, 1, "SETUP"));
  118653. rc = sqlite3Select(pParse, pSetup, &destQueue);
  118654. pSetup->pNext = p;
  118655. if( rc ) goto end_of_recursive_query;
  118656. /* Find the next row in the Queue and output that row */
  118657. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  118658. /* Transfer the next row in Queue over to Current */
  118659. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  118660. if( pOrderBy ){
  118661. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  118662. }else{
  118663. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  118664. }
  118665. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  118666. /* Output the single row in Current */
  118667. addrCont = sqlite3VdbeMakeLabel(v);
  118668. codeOffset(v, regOffset, addrCont);
  118669. selectInnerLoop(pParse, p, iCurrent,
  118670. 0, 0, pDest, addrCont, addrBreak);
  118671. if( regLimit ){
  118672. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  118673. VdbeCoverage(v);
  118674. }
  118675. sqlite3VdbeResolveLabel(v, addrCont);
  118676. /* Execute the recursive SELECT taking the single row in Current as
  118677. ** the value for the recursive-table. Store the results in the Queue.
  118678. */
  118679. if( p->selFlags & SF_Aggregate ){
  118680. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  118681. }else{
  118682. p->pPrior = 0;
  118683. ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
  118684. sqlite3Select(pParse, p, &destQueue);
  118685. assert( p->pPrior==0 );
  118686. p->pPrior = pSetup;
  118687. }
  118688. /* Keep running the loop until the Queue is empty */
  118689. sqlite3VdbeGoto(v, addrTop);
  118690. sqlite3VdbeResolveLabel(v, addrBreak);
  118691. end_of_recursive_query:
  118692. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  118693. p->pOrderBy = pOrderBy;
  118694. p->pLimit = pLimit;
  118695. return;
  118696. }
  118697. #endif /* SQLITE_OMIT_CTE */
  118698. /* Forward references */
  118699. static int multiSelectOrderBy(
  118700. Parse *pParse, /* Parsing context */
  118701. Select *p, /* The right-most of SELECTs to be coded */
  118702. SelectDest *pDest /* What to do with query results */
  118703. );
  118704. /*
  118705. ** Handle the special case of a compound-select that originates from a
  118706. ** VALUES clause. By handling this as a special case, we avoid deep
  118707. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  118708. ** on a VALUES clause.
  118709. **
  118710. ** Because the Select object originates from a VALUES clause:
  118711. ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
  118712. ** (2) All terms are UNION ALL
  118713. ** (3) There is no ORDER BY clause
  118714. **
  118715. ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
  118716. ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
  118717. ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
  118718. ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
  118719. */
  118720. static int multiSelectValues(
  118721. Parse *pParse, /* Parsing context */
  118722. Select *p, /* The right-most of SELECTs to be coded */
  118723. SelectDest *pDest /* What to do with query results */
  118724. ){
  118725. int nRow = 1;
  118726. int rc = 0;
  118727. int bShowAll = p->pLimit==0;
  118728. assert( p->selFlags & SF_MultiValue );
  118729. do{
  118730. assert( p->selFlags & SF_Values );
  118731. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  118732. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  118733. if( p->pPrior==0 ) break;
  118734. assert( p->pPrior->pNext==p );
  118735. p = p->pPrior;
  118736. nRow += bShowAll;
  118737. }while(1);
  118738. ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
  118739. nRow==1 ? "" : "S"));
  118740. while( p ){
  118741. selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
  118742. if( !bShowAll ) break;
  118743. p->nSelectRow = nRow;
  118744. p = p->pNext;
  118745. }
  118746. return rc;
  118747. }
  118748. /*
  118749. ** This routine is called to process a compound query form from
  118750. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  118751. ** INTERSECT
  118752. **
  118753. ** "p" points to the right-most of the two queries. the query on the
  118754. ** left is p->pPrior. The left query could also be a compound query
  118755. ** in which case this routine will be called recursively.
  118756. **
  118757. ** The results of the total query are to be written into a destination
  118758. ** of type eDest with parameter iParm.
  118759. **
  118760. ** Example 1: Consider a three-way compound SQL statement.
  118761. **
  118762. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  118763. **
  118764. ** This statement is parsed up as follows:
  118765. **
  118766. ** SELECT c FROM t3
  118767. ** |
  118768. ** `-----> SELECT b FROM t2
  118769. ** |
  118770. ** `------> SELECT a FROM t1
  118771. **
  118772. ** The arrows in the diagram above represent the Select.pPrior pointer.
  118773. ** So if this routine is called with p equal to the t3 query, then
  118774. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  118775. **
  118776. ** Notice that because of the way SQLite parses compound SELECTs, the
  118777. ** individual selects always group from left to right.
  118778. */
  118779. static int multiSelect(
  118780. Parse *pParse, /* Parsing context */
  118781. Select *p, /* The right-most of SELECTs to be coded */
  118782. SelectDest *pDest /* What to do with query results */
  118783. ){
  118784. int rc = SQLITE_OK; /* Success code from a subroutine */
  118785. Select *pPrior; /* Another SELECT immediately to our left */
  118786. Vdbe *v; /* Generate code to this VDBE */
  118787. SelectDest dest; /* Alternative data destination */
  118788. Select *pDelete = 0; /* Chain of simple selects to delete */
  118789. sqlite3 *db; /* Database connection */
  118790. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  118791. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  118792. */
  118793. assert( p && p->pPrior ); /* Calling function guarantees this much */
  118794. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  118795. db = pParse->db;
  118796. pPrior = p->pPrior;
  118797. dest = *pDest;
  118798. if( pPrior->pOrderBy || pPrior->pLimit ){
  118799. sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
  118800. pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
  118801. rc = 1;
  118802. goto multi_select_end;
  118803. }
  118804. v = sqlite3GetVdbe(pParse);
  118805. assert( v!=0 ); /* The VDBE already created by calling function */
  118806. /* Create the destination temporary table if necessary
  118807. */
  118808. if( dest.eDest==SRT_EphemTab ){
  118809. assert( p->pEList );
  118810. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  118811. dest.eDest = SRT_Table;
  118812. }
  118813. /* Special handling for a compound-select that originates as a VALUES clause.
  118814. */
  118815. if( p->selFlags & SF_MultiValue ){
  118816. rc = multiSelectValues(pParse, p, &dest);
  118817. goto multi_select_end;
  118818. }
  118819. /* Make sure all SELECTs in the statement have the same number of elements
  118820. ** in their result sets.
  118821. */
  118822. assert( p->pEList && pPrior->pEList );
  118823. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  118824. #ifndef SQLITE_OMIT_CTE
  118825. if( p->selFlags & SF_Recursive ){
  118826. generateWithRecursiveQuery(pParse, p, &dest);
  118827. }else
  118828. #endif
  118829. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  118830. */
  118831. if( p->pOrderBy ){
  118832. return multiSelectOrderBy(pParse, p, pDest);
  118833. }else{
  118834. #ifndef SQLITE_OMIT_EXPLAIN
  118835. if( pPrior->pPrior==0 ){
  118836. ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
  118837. ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
  118838. }
  118839. #endif
  118840. /* Generate code for the left and right SELECT statements.
  118841. */
  118842. switch( p->op ){
  118843. case TK_ALL: {
  118844. int addr = 0;
  118845. int nLimit;
  118846. assert( !pPrior->pLimit );
  118847. pPrior->iLimit = p->iLimit;
  118848. pPrior->iOffset = p->iOffset;
  118849. pPrior->pLimit = p->pLimit;
  118850. rc = sqlite3Select(pParse, pPrior, &dest);
  118851. p->pLimit = 0;
  118852. if( rc ){
  118853. goto multi_select_end;
  118854. }
  118855. p->pPrior = 0;
  118856. p->iLimit = pPrior->iLimit;
  118857. p->iOffset = pPrior->iOffset;
  118858. if( p->iLimit ){
  118859. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  118860. VdbeComment((v, "Jump ahead if LIMIT reached"));
  118861. if( p->iOffset ){
  118862. sqlite3VdbeAddOp3(v, OP_OffsetLimit,
  118863. p->iLimit, p->iOffset+1, p->iOffset);
  118864. }
  118865. }
  118866. ExplainQueryPlan((pParse, 1, "UNION ALL"));
  118867. rc = sqlite3Select(pParse, p, &dest);
  118868. testcase( rc!=SQLITE_OK );
  118869. pDelete = p->pPrior;
  118870. p->pPrior = pPrior;
  118871. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  118872. if( pPrior->pLimit
  118873. && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
  118874. && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
  118875. ){
  118876. p->nSelectRow = sqlite3LogEst((u64)nLimit);
  118877. }
  118878. if( addr ){
  118879. sqlite3VdbeJumpHere(v, addr);
  118880. }
  118881. break;
  118882. }
  118883. case TK_EXCEPT:
  118884. case TK_UNION: {
  118885. int unionTab; /* Cursor number of the temp table holding result */
  118886. u8 op = 0; /* One of the SRT_ operations to apply to self */
  118887. int priorOp; /* The SRT_ operation to apply to prior selects */
  118888. Expr *pLimit; /* Saved values of p->nLimit */
  118889. int addr;
  118890. SelectDest uniondest;
  118891. testcase( p->op==TK_EXCEPT );
  118892. testcase( p->op==TK_UNION );
  118893. priorOp = SRT_Union;
  118894. if( dest.eDest==priorOp ){
  118895. /* We can reuse a temporary table generated by a SELECT to our
  118896. ** right.
  118897. */
  118898. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  118899. unionTab = dest.iSDParm;
  118900. }else{
  118901. /* We will need to create our own temporary table to hold the
  118902. ** intermediate results.
  118903. */
  118904. unionTab = pParse->nTab++;
  118905. assert( p->pOrderBy==0 );
  118906. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  118907. assert( p->addrOpenEphm[0] == -1 );
  118908. p->addrOpenEphm[0] = addr;
  118909. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  118910. assert( p->pEList );
  118911. }
  118912. /* Code the SELECT statements to our left
  118913. */
  118914. assert( !pPrior->pOrderBy );
  118915. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  118916. rc = sqlite3Select(pParse, pPrior, &uniondest);
  118917. if( rc ){
  118918. goto multi_select_end;
  118919. }
  118920. /* Code the current SELECT statement
  118921. */
  118922. if( p->op==TK_EXCEPT ){
  118923. op = SRT_Except;
  118924. }else{
  118925. assert( p->op==TK_UNION );
  118926. op = SRT_Union;
  118927. }
  118928. p->pPrior = 0;
  118929. pLimit = p->pLimit;
  118930. p->pLimit = 0;
  118931. uniondest.eDest = op;
  118932. ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
  118933. selectOpName(p->op)));
  118934. rc = sqlite3Select(pParse, p, &uniondest);
  118935. testcase( rc!=SQLITE_OK );
  118936. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  118937. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  118938. sqlite3ExprListDelete(db, p->pOrderBy);
  118939. pDelete = p->pPrior;
  118940. p->pPrior = pPrior;
  118941. p->pOrderBy = 0;
  118942. if( p->op==TK_UNION ){
  118943. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  118944. }
  118945. sqlite3ExprDelete(db, p->pLimit);
  118946. p->pLimit = pLimit;
  118947. p->iLimit = 0;
  118948. p->iOffset = 0;
  118949. /* Convert the data in the temporary table into whatever form
  118950. ** it is that we currently need.
  118951. */
  118952. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  118953. if( dest.eDest!=priorOp ){
  118954. int iCont, iBreak, iStart;
  118955. assert( p->pEList );
  118956. iBreak = sqlite3VdbeMakeLabel(v);
  118957. iCont = sqlite3VdbeMakeLabel(v);
  118958. computeLimitRegisters(pParse, p, iBreak);
  118959. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  118960. iStart = sqlite3VdbeCurrentAddr(v);
  118961. selectInnerLoop(pParse, p, unionTab,
  118962. 0, 0, &dest, iCont, iBreak);
  118963. sqlite3VdbeResolveLabel(v, iCont);
  118964. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  118965. sqlite3VdbeResolveLabel(v, iBreak);
  118966. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  118967. }
  118968. break;
  118969. }
  118970. default: assert( p->op==TK_INTERSECT ); {
  118971. int tab1, tab2;
  118972. int iCont, iBreak, iStart;
  118973. Expr *pLimit;
  118974. int addr;
  118975. SelectDest intersectdest;
  118976. int r1;
  118977. /* INTERSECT is different from the others since it requires
  118978. ** two temporary tables. Hence it has its own case. Begin
  118979. ** by allocating the tables we will need.
  118980. */
  118981. tab1 = pParse->nTab++;
  118982. tab2 = pParse->nTab++;
  118983. assert( p->pOrderBy==0 );
  118984. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  118985. assert( p->addrOpenEphm[0] == -1 );
  118986. p->addrOpenEphm[0] = addr;
  118987. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  118988. assert( p->pEList );
  118989. /* Code the SELECTs to our left into temporary table "tab1".
  118990. */
  118991. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  118992. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  118993. if( rc ){
  118994. goto multi_select_end;
  118995. }
  118996. /* Code the current SELECT into temporary table "tab2"
  118997. */
  118998. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  118999. assert( p->addrOpenEphm[1] == -1 );
  119000. p->addrOpenEphm[1] = addr;
  119001. p->pPrior = 0;
  119002. pLimit = p->pLimit;
  119003. p->pLimit = 0;
  119004. intersectdest.iSDParm = tab2;
  119005. ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
  119006. selectOpName(p->op)));
  119007. rc = sqlite3Select(pParse, p, &intersectdest);
  119008. testcase( rc!=SQLITE_OK );
  119009. pDelete = p->pPrior;
  119010. p->pPrior = pPrior;
  119011. if( p->nSelectRow>pPrior->nSelectRow ){
  119012. p->nSelectRow = pPrior->nSelectRow;
  119013. }
  119014. sqlite3ExprDelete(db, p->pLimit);
  119015. p->pLimit = pLimit;
  119016. /* Generate code to take the intersection of the two temporary
  119017. ** tables.
  119018. */
  119019. assert( p->pEList );
  119020. iBreak = sqlite3VdbeMakeLabel(v);
  119021. iCont = sqlite3VdbeMakeLabel(v);
  119022. computeLimitRegisters(pParse, p, iBreak);
  119023. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  119024. r1 = sqlite3GetTempReg(pParse);
  119025. iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
  119026. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  119027. VdbeCoverage(v);
  119028. sqlite3ReleaseTempReg(pParse, r1);
  119029. selectInnerLoop(pParse, p, tab1,
  119030. 0, 0, &dest, iCont, iBreak);
  119031. sqlite3VdbeResolveLabel(v, iCont);
  119032. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  119033. sqlite3VdbeResolveLabel(v, iBreak);
  119034. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  119035. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  119036. break;
  119037. }
  119038. }
  119039. #ifndef SQLITE_OMIT_EXPLAIN
  119040. if( p->pNext==0 ){
  119041. ExplainQueryPlanPop(pParse);
  119042. }
  119043. #endif
  119044. }
  119045. /* Compute collating sequences used by
  119046. ** temporary tables needed to implement the compound select.
  119047. ** Attach the KeyInfo structure to all temporary tables.
  119048. **
  119049. ** This section is run by the right-most SELECT statement only.
  119050. ** SELECT statements to the left always skip this part. The right-most
  119051. ** SELECT might also skip this part if it has no ORDER BY clause and
  119052. ** no temp tables are required.
  119053. */
  119054. if( p->selFlags & SF_UsesEphemeral ){
  119055. int i; /* Loop counter */
  119056. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  119057. Select *pLoop; /* For looping through SELECT statements */
  119058. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  119059. int nCol; /* Number of columns in result set */
  119060. assert( p->pNext==0 );
  119061. nCol = p->pEList->nExpr;
  119062. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  119063. if( !pKeyInfo ){
  119064. rc = SQLITE_NOMEM_BKPT;
  119065. goto multi_select_end;
  119066. }
  119067. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  119068. *apColl = multiSelectCollSeq(pParse, p, i);
  119069. if( 0==*apColl ){
  119070. *apColl = db->pDfltColl;
  119071. }
  119072. }
  119073. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  119074. for(i=0; i<2; i++){
  119075. int addr = pLoop->addrOpenEphm[i];
  119076. if( addr<0 ){
  119077. /* If [0] is unused then [1] is also unused. So we can
  119078. ** always safely abort as soon as the first unused slot is found */
  119079. assert( pLoop->addrOpenEphm[1]<0 );
  119080. break;
  119081. }
  119082. sqlite3VdbeChangeP2(v, addr, nCol);
  119083. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  119084. P4_KEYINFO);
  119085. pLoop->addrOpenEphm[i] = -1;
  119086. }
  119087. }
  119088. sqlite3KeyInfoUnref(pKeyInfo);
  119089. }
  119090. multi_select_end:
  119091. pDest->iSdst = dest.iSdst;
  119092. pDest->nSdst = dest.nSdst;
  119093. sqlite3SelectDelete(db, pDelete);
  119094. return rc;
  119095. }
  119096. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  119097. /*
  119098. ** Error message for when two or more terms of a compound select have different
  119099. ** size result sets.
  119100. */
  119101. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  119102. if( p->selFlags & SF_Values ){
  119103. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  119104. }else{
  119105. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  119106. " do not have the same number of result columns", selectOpName(p->op));
  119107. }
  119108. }
  119109. /*
  119110. ** Code an output subroutine for a coroutine implementation of a
  119111. ** SELECT statment.
  119112. **
  119113. ** The data to be output is contained in pIn->iSdst. There are
  119114. ** pIn->nSdst columns to be output. pDest is where the output should
  119115. ** be sent.
  119116. **
  119117. ** regReturn is the number of the register holding the subroutine
  119118. ** return address.
  119119. **
  119120. ** If regPrev>0 then it is the first register in a vector that
  119121. ** records the previous output. mem[regPrev] is a flag that is false
  119122. ** if there has been no previous output. If regPrev>0 then code is
  119123. ** generated to suppress duplicates. pKeyInfo is used for comparing
  119124. ** keys.
  119125. **
  119126. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  119127. ** iBreak.
  119128. */
  119129. static int generateOutputSubroutine(
  119130. Parse *pParse, /* Parsing context */
  119131. Select *p, /* The SELECT statement */
  119132. SelectDest *pIn, /* Coroutine supplying data */
  119133. SelectDest *pDest, /* Where to send the data */
  119134. int regReturn, /* The return address register */
  119135. int regPrev, /* Previous result register. No uniqueness if 0 */
  119136. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  119137. int iBreak /* Jump here if we hit the LIMIT */
  119138. ){
  119139. Vdbe *v = pParse->pVdbe;
  119140. int iContinue;
  119141. int addr;
  119142. addr = sqlite3VdbeCurrentAddr(v);
  119143. iContinue = sqlite3VdbeMakeLabel(v);
  119144. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  119145. */
  119146. if( regPrev ){
  119147. int addr1, addr2;
  119148. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  119149. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  119150. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  119151. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  119152. sqlite3VdbeJumpHere(v, addr1);
  119153. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  119154. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  119155. }
  119156. if( pParse->db->mallocFailed ) return 0;
  119157. /* Suppress the first OFFSET entries if there is an OFFSET clause
  119158. */
  119159. codeOffset(v, p->iOffset, iContinue);
  119160. assert( pDest->eDest!=SRT_Exists );
  119161. assert( pDest->eDest!=SRT_Table );
  119162. switch( pDest->eDest ){
  119163. /* Store the result as data using a unique key.
  119164. */
  119165. case SRT_EphemTab: {
  119166. int r1 = sqlite3GetTempReg(pParse);
  119167. int r2 = sqlite3GetTempReg(pParse);
  119168. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  119169. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  119170. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  119171. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  119172. sqlite3ReleaseTempReg(pParse, r2);
  119173. sqlite3ReleaseTempReg(pParse, r1);
  119174. break;
  119175. }
  119176. #ifndef SQLITE_OMIT_SUBQUERY
  119177. /* If we are creating a set for an "expr IN (SELECT ...)".
  119178. */
  119179. case SRT_Set: {
  119180. int r1;
  119181. testcase( pIn->nSdst>1 );
  119182. r1 = sqlite3GetTempReg(pParse);
  119183. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
  119184. r1, pDest->zAffSdst, pIn->nSdst);
  119185. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
  119186. pIn->iSdst, pIn->nSdst);
  119187. sqlite3ReleaseTempReg(pParse, r1);
  119188. break;
  119189. }
  119190. /* If this is a scalar select that is part of an expression, then
  119191. ** store the results in the appropriate memory cell and break out
  119192. ** of the scan loop.
  119193. */
  119194. case SRT_Mem: {
  119195. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  119196. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  119197. /* The LIMIT clause will jump out of the loop for us */
  119198. break;
  119199. }
  119200. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  119201. /* The results are stored in a sequence of registers
  119202. ** starting at pDest->iSdst. Then the co-routine yields.
  119203. */
  119204. case SRT_Coroutine: {
  119205. if( pDest->iSdst==0 ){
  119206. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  119207. pDest->nSdst = pIn->nSdst;
  119208. }
  119209. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  119210. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  119211. break;
  119212. }
  119213. /* If none of the above, then the result destination must be
  119214. ** SRT_Output. This routine is never called with any other
  119215. ** destination other than the ones handled above or SRT_Output.
  119216. **
  119217. ** For SRT_Output, results are stored in a sequence of registers.
  119218. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  119219. ** return the next row of result.
  119220. */
  119221. default: {
  119222. assert( pDest->eDest==SRT_Output );
  119223. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  119224. break;
  119225. }
  119226. }
  119227. /* Jump to the end of the loop if the LIMIT is reached.
  119228. */
  119229. if( p->iLimit ){
  119230. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  119231. }
  119232. /* Generate the subroutine return
  119233. */
  119234. sqlite3VdbeResolveLabel(v, iContinue);
  119235. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  119236. return addr;
  119237. }
  119238. /*
  119239. ** Alternative compound select code generator for cases when there
  119240. ** is an ORDER BY clause.
  119241. **
  119242. ** We assume a query of the following form:
  119243. **
  119244. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  119245. **
  119246. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  119247. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  119248. ** co-routines. Then run the co-routines in parallel and merge the results
  119249. ** into the output. In addition to the two coroutines (called selectA and
  119250. ** selectB) there are 7 subroutines:
  119251. **
  119252. ** outA: Move the output of the selectA coroutine into the output
  119253. ** of the compound query.
  119254. **
  119255. ** outB: Move the output of the selectB coroutine into the output
  119256. ** of the compound query. (Only generated for UNION and
  119257. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  119258. ** appears only in B.)
  119259. **
  119260. ** AltB: Called when there is data from both coroutines and A<B.
  119261. **
  119262. ** AeqB: Called when there is data from both coroutines and A==B.
  119263. **
  119264. ** AgtB: Called when there is data from both coroutines and A>B.
  119265. **
  119266. ** EofA: Called when data is exhausted from selectA.
  119267. **
  119268. ** EofB: Called when data is exhausted from selectB.
  119269. **
  119270. ** The implementation of the latter five subroutines depend on which
  119271. ** <operator> is used:
  119272. **
  119273. **
  119274. ** UNION ALL UNION EXCEPT INTERSECT
  119275. ** ------------- ----------------- -------------- -----------------
  119276. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  119277. **
  119278. ** AeqB: outA, nextA nextA nextA outA, nextA
  119279. **
  119280. ** AgtB: outB, nextB outB, nextB nextB nextB
  119281. **
  119282. ** EofA: outB, nextB outB, nextB halt halt
  119283. **
  119284. ** EofB: outA, nextA outA, nextA outA, nextA halt
  119285. **
  119286. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  119287. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  119288. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  119289. ** following nextX causes a jump to the end of the select processing.
  119290. **
  119291. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  119292. ** within the output subroutine. The regPrev register set holds the previously
  119293. ** output value. A comparison is made against this value and the output
  119294. ** is skipped if the next results would be the same as the previous.
  119295. **
  119296. ** The implementation plan is to implement the two coroutines and seven
  119297. ** subroutines first, then put the control logic at the bottom. Like this:
  119298. **
  119299. ** goto Init
  119300. ** coA: coroutine for left query (A)
  119301. ** coB: coroutine for right query (B)
  119302. ** outA: output one row of A
  119303. ** outB: output one row of B (UNION and UNION ALL only)
  119304. ** EofA: ...
  119305. ** EofB: ...
  119306. ** AltB: ...
  119307. ** AeqB: ...
  119308. ** AgtB: ...
  119309. ** Init: initialize coroutine registers
  119310. ** yield coA
  119311. ** if eof(A) goto EofA
  119312. ** yield coB
  119313. ** if eof(B) goto EofB
  119314. ** Cmpr: Compare A, B
  119315. ** Jump AltB, AeqB, AgtB
  119316. ** End: ...
  119317. **
  119318. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  119319. ** actually called using Gosub and they do not Return. EofA and EofB loop
  119320. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  119321. ** and AgtB jump to either L2 or to one of EofA or EofB.
  119322. */
  119323. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  119324. static int multiSelectOrderBy(
  119325. Parse *pParse, /* Parsing context */
  119326. Select *p, /* The right-most of SELECTs to be coded */
  119327. SelectDest *pDest /* What to do with query results */
  119328. ){
  119329. int i, j; /* Loop counters */
  119330. Select *pPrior; /* Another SELECT immediately to our left */
  119331. Vdbe *v; /* Generate code to this VDBE */
  119332. SelectDest destA; /* Destination for coroutine A */
  119333. SelectDest destB; /* Destination for coroutine B */
  119334. int regAddrA; /* Address register for select-A coroutine */
  119335. int regAddrB; /* Address register for select-B coroutine */
  119336. int addrSelectA; /* Address of the select-A coroutine */
  119337. int addrSelectB; /* Address of the select-B coroutine */
  119338. int regOutA; /* Address register for the output-A subroutine */
  119339. int regOutB; /* Address register for the output-B subroutine */
  119340. int addrOutA; /* Address of the output-A subroutine */
  119341. int addrOutB = 0; /* Address of the output-B subroutine */
  119342. int addrEofA; /* Address of the select-A-exhausted subroutine */
  119343. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  119344. int addrEofB; /* Address of the select-B-exhausted subroutine */
  119345. int addrAltB; /* Address of the A<B subroutine */
  119346. int addrAeqB; /* Address of the A==B subroutine */
  119347. int addrAgtB; /* Address of the A>B subroutine */
  119348. int regLimitA; /* Limit register for select-A */
  119349. int regLimitB; /* Limit register for select-A */
  119350. int regPrev; /* A range of registers to hold previous output */
  119351. int savedLimit; /* Saved value of p->iLimit */
  119352. int savedOffset; /* Saved value of p->iOffset */
  119353. int labelCmpr; /* Label for the start of the merge algorithm */
  119354. int labelEnd; /* Label for the end of the overall SELECT stmt */
  119355. int addr1; /* Jump instructions that get retargetted */
  119356. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  119357. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  119358. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  119359. sqlite3 *db; /* Database connection */
  119360. ExprList *pOrderBy; /* The ORDER BY clause */
  119361. int nOrderBy; /* Number of terms in the ORDER BY clause */
  119362. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  119363. assert( p->pOrderBy!=0 );
  119364. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  119365. db = pParse->db;
  119366. v = pParse->pVdbe;
  119367. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  119368. labelEnd = sqlite3VdbeMakeLabel(v);
  119369. labelCmpr = sqlite3VdbeMakeLabel(v);
  119370. /* Patch up the ORDER BY clause
  119371. */
  119372. op = p->op;
  119373. pPrior = p->pPrior;
  119374. assert( pPrior->pOrderBy==0 );
  119375. pOrderBy = p->pOrderBy;
  119376. assert( pOrderBy );
  119377. nOrderBy = pOrderBy->nExpr;
  119378. /* For operators other than UNION ALL we have to make sure that
  119379. ** the ORDER BY clause covers every term of the result set. Add
  119380. ** terms to the ORDER BY clause as necessary.
  119381. */
  119382. if( op!=TK_ALL ){
  119383. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  119384. struct ExprList_item *pItem;
  119385. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  119386. assert( pItem->u.x.iOrderByCol>0 );
  119387. if( pItem->u.x.iOrderByCol==i ) break;
  119388. }
  119389. if( j==nOrderBy ){
  119390. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  119391. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  119392. pNew->flags |= EP_IntValue;
  119393. pNew->u.iValue = i;
  119394. p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  119395. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  119396. }
  119397. }
  119398. }
  119399. /* Compute the comparison permutation and keyinfo that is used with
  119400. ** the permutation used to determine if the next
  119401. ** row of results comes from selectA or selectB. Also add explicit
  119402. ** collations to the ORDER BY clause terms so that when the subqueries
  119403. ** to the right and the left are evaluated, they use the correct
  119404. ** collation.
  119405. */
  119406. aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
  119407. if( aPermute ){
  119408. struct ExprList_item *pItem;
  119409. aPermute[0] = nOrderBy;
  119410. for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
  119411. assert( pItem->u.x.iOrderByCol>0 );
  119412. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  119413. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  119414. }
  119415. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  119416. }else{
  119417. pKeyMerge = 0;
  119418. }
  119419. /* Reattach the ORDER BY clause to the query.
  119420. */
  119421. p->pOrderBy = pOrderBy;
  119422. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  119423. /* Allocate a range of temporary registers and the KeyInfo needed
  119424. ** for the logic that removes duplicate result rows when the
  119425. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  119426. */
  119427. if( op==TK_ALL ){
  119428. regPrev = 0;
  119429. }else{
  119430. int nExpr = p->pEList->nExpr;
  119431. assert( nOrderBy>=nExpr || db->mallocFailed );
  119432. regPrev = pParse->nMem+1;
  119433. pParse->nMem += nExpr+1;
  119434. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  119435. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  119436. if( pKeyDup ){
  119437. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  119438. for(i=0; i<nExpr; i++){
  119439. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  119440. pKeyDup->aSortOrder[i] = 0;
  119441. }
  119442. }
  119443. }
  119444. /* Separate the left and the right query from one another
  119445. */
  119446. p->pPrior = 0;
  119447. pPrior->pNext = 0;
  119448. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  119449. if( pPrior->pPrior==0 ){
  119450. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  119451. }
  119452. /* Compute the limit registers */
  119453. computeLimitRegisters(pParse, p, labelEnd);
  119454. if( p->iLimit && op==TK_ALL ){
  119455. regLimitA = ++pParse->nMem;
  119456. regLimitB = ++pParse->nMem;
  119457. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  119458. regLimitA);
  119459. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  119460. }else{
  119461. regLimitA = regLimitB = 0;
  119462. }
  119463. sqlite3ExprDelete(db, p->pLimit);
  119464. p->pLimit = 0;
  119465. regAddrA = ++pParse->nMem;
  119466. regAddrB = ++pParse->nMem;
  119467. regOutA = ++pParse->nMem;
  119468. regOutB = ++pParse->nMem;
  119469. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  119470. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  119471. ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
  119472. /* Generate a coroutine to evaluate the SELECT statement to the
  119473. ** left of the compound operator - the "A" select.
  119474. */
  119475. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  119476. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  119477. VdbeComment((v, "left SELECT"));
  119478. pPrior->iLimit = regLimitA;
  119479. ExplainQueryPlan((pParse, 1, "LEFT"));
  119480. sqlite3Select(pParse, pPrior, &destA);
  119481. sqlite3VdbeEndCoroutine(v, regAddrA);
  119482. sqlite3VdbeJumpHere(v, addr1);
  119483. /* Generate a coroutine to evaluate the SELECT statement on
  119484. ** the right - the "B" select
  119485. */
  119486. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  119487. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  119488. VdbeComment((v, "right SELECT"));
  119489. savedLimit = p->iLimit;
  119490. savedOffset = p->iOffset;
  119491. p->iLimit = regLimitB;
  119492. p->iOffset = 0;
  119493. ExplainQueryPlan((pParse, 1, "RIGHT"));
  119494. sqlite3Select(pParse, p, &destB);
  119495. p->iLimit = savedLimit;
  119496. p->iOffset = savedOffset;
  119497. sqlite3VdbeEndCoroutine(v, regAddrB);
  119498. /* Generate a subroutine that outputs the current row of the A
  119499. ** select as the next output row of the compound select.
  119500. */
  119501. VdbeNoopComment((v, "Output routine for A"));
  119502. addrOutA = generateOutputSubroutine(pParse,
  119503. p, &destA, pDest, regOutA,
  119504. regPrev, pKeyDup, labelEnd);
  119505. /* Generate a subroutine that outputs the current row of the B
  119506. ** select as the next output row of the compound select.
  119507. */
  119508. if( op==TK_ALL || op==TK_UNION ){
  119509. VdbeNoopComment((v, "Output routine for B"));
  119510. addrOutB = generateOutputSubroutine(pParse,
  119511. p, &destB, pDest, regOutB,
  119512. regPrev, pKeyDup, labelEnd);
  119513. }
  119514. sqlite3KeyInfoUnref(pKeyDup);
  119515. /* Generate a subroutine to run when the results from select A
  119516. ** are exhausted and only data in select B remains.
  119517. */
  119518. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  119519. addrEofA_noB = addrEofA = labelEnd;
  119520. }else{
  119521. VdbeNoopComment((v, "eof-A subroutine"));
  119522. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  119523. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  119524. VdbeCoverage(v);
  119525. sqlite3VdbeGoto(v, addrEofA);
  119526. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  119527. }
  119528. /* Generate a subroutine to run when the results from select B
  119529. ** are exhausted and only data in select A remains.
  119530. */
  119531. if( op==TK_INTERSECT ){
  119532. addrEofB = addrEofA;
  119533. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  119534. }else{
  119535. VdbeNoopComment((v, "eof-B subroutine"));
  119536. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  119537. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  119538. sqlite3VdbeGoto(v, addrEofB);
  119539. }
  119540. /* Generate code to handle the case of A<B
  119541. */
  119542. VdbeNoopComment((v, "A-lt-B subroutine"));
  119543. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  119544. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  119545. sqlite3VdbeGoto(v, labelCmpr);
  119546. /* Generate code to handle the case of A==B
  119547. */
  119548. if( op==TK_ALL ){
  119549. addrAeqB = addrAltB;
  119550. }else if( op==TK_INTERSECT ){
  119551. addrAeqB = addrAltB;
  119552. addrAltB++;
  119553. }else{
  119554. VdbeNoopComment((v, "A-eq-B subroutine"));
  119555. addrAeqB =
  119556. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  119557. sqlite3VdbeGoto(v, labelCmpr);
  119558. }
  119559. /* Generate code to handle the case of A>B
  119560. */
  119561. VdbeNoopComment((v, "A-gt-B subroutine"));
  119562. addrAgtB = sqlite3VdbeCurrentAddr(v);
  119563. if( op==TK_ALL || op==TK_UNION ){
  119564. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  119565. }
  119566. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  119567. sqlite3VdbeGoto(v, labelCmpr);
  119568. /* This code runs once to initialize everything.
  119569. */
  119570. sqlite3VdbeJumpHere(v, addr1);
  119571. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  119572. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  119573. /* Implement the main merge loop
  119574. */
  119575. sqlite3VdbeResolveLabel(v, labelCmpr);
  119576. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  119577. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  119578. (char*)pKeyMerge, P4_KEYINFO);
  119579. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  119580. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  119581. /* Jump to the this point in order to terminate the query.
  119582. */
  119583. sqlite3VdbeResolveLabel(v, labelEnd);
  119584. /* Reassembly the compound query so that it will be freed correctly
  119585. ** by the calling function */
  119586. if( p->pPrior ){
  119587. sqlite3SelectDelete(db, p->pPrior);
  119588. }
  119589. p->pPrior = pPrior;
  119590. pPrior->pNext = p;
  119591. /*** TBD: Insert subroutine calls to close cursors on incomplete
  119592. **** subqueries ****/
  119593. ExplainQueryPlanPop(pParse);
  119594. return pParse->nErr!=0;
  119595. }
  119596. #endif
  119597. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  119598. /* An instance of the SubstContext object describes an substitution edit
  119599. ** to be performed on a parse tree.
  119600. **
  119601. ** All references to columns in table iTable are to be replaced by corresponding
  119602. ** expressions in pEList.
  119603. */
  119604. typedef struct SubstContext {
  119605. Parse *pParse; /* The parsing context */
  119606. int iTable; /* Replace references to this table */
  119607. int iNewTable; /* New table number */
  119608. int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
  119609. ExprList *pEList; /* Replacement expressions */
  119610. } SubstContext;
  119611. /* Forward Declarations */
  119612. static void substExprList(SubstContext*, ExprList*);
  119613. static void substSelect(SubstContext*, Select*, int);
  119614. /*
  119615. ** Scan through the expression pExpr. Replace every reference to
  119616. ** a column in table number iTable with a copy of the iColumn-th
  119617. ** entry in pEList. (But leave references to the ROWID column
  119618. ** unchanged.)
  119619. **
  119620. ** This routine is part of the flattening procedure. A subquery
  119621. ** whose result set is defined by pEList appears as entry in the
  119622. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  119623. ** FORM clause entry is iTable. This routine makes the necessary
  119624. ** changes to pExpr so that it refers directly to the source table
  119625. ** of the subquery rather the result set of the subquery.
  119626. */
  119627. static Expr *substExpr(
  119628. SubstContext *pSubst, /* Description of the substitution */
  119629. Expr *pExpr /* Expr in which substitution occurs */
  119630. ){
  119631. if( pExpr==0 ) return 0;
  119632. if( ExprHasProperty(pExpr, EP_FromJoin)
  119633. && pExpr->iRightJoinTable==pSubst->iTable
  119634. ){
  119635. pExpr->iRightJoinTable = pSubst->iNewTable;
  119636. }
  119637. if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
  119638. if( pExpr->iColumn<0 ){
  119639. pExpr->op = TK_NULL;
  119640. }else{
  119641. Expr *pNew;
  119642. Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
  119643. Expr ifNullRow;
  119644. assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
  119645. assert( pExpr->pRight==0 );
  119646. if( sqlite3ExprIsVector(pCopy) ){
  119647. sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
  119648. }else{
  119649. sqlite3 *db = pSubst->pParse->db;
  119650. if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
  119651. memset(&ifNullRow, 0, sizeof(ifNullRow));
  119652. ifNullRow.op = TK_IF_NULL_ROW;
  119653. ifNullRow.pLeft = pCopy;
  119654. ifNullRow.iTable = pSubst->iNewTable;
  119655. pCopy = &ifNullRow;
  119656. }
  119657. pNew = sqlite3ExprDup(db, pCopy, 0);
  119658. if( pNew && pSubst->isLeftJoin ){
  119659. ExprSetProperty(pNew, EP_CanBeNull);
  119660. }
  119661. if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
  119662. pNew->iRightJoinTable = pExpr->iRightJoinTable;
  119663. ExprSetProperty(pNew, EP_FromJoin);
  119664. }
  119665. sqlite3ExprDelete(db, pExpr);
  119666. pExpr = pNew;
  119667. }
  119668. }
  119669. }else{
  119670. if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
  119671. pExpr->iTable = pSubst->iNewTable;
  119672. }
  119673. pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
  119674. pExpr->pRight = substExpr(pSubst, pExpr->pRight);
  119675. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  119676. substSelect(pSubst, pExpr->x.pSelect, 1);
  119677. }else{
  119678. substExprList(pSubst, pExpr->x.pList);
  119679. }
  119680. }
  119681. return pExpr;
  119682. }
  119683. static void substExprList(
  119684. SubstContext *pSubst, /* Description of the substitution */
  119685. ExprList *pList /* List to scan and in which to make substitutes */
  119686. ){
  119687. int i;
  119688. if( pList==0 ) return;
  119689. for(i=0; i<pList->nExpr; i++){
  119690. pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
  119691. }
  119692. }
  119693. static void substSelect(
  119694. SubstContext *pSubst, /* Description of the substitution */
  119695. Select *p, /* SELECT statement in which to make substitutions */
  119696. int doPrior /* Do substitutes on p->pPrior too */
  119697. ){
  119698. SrcList *pSrc;
  119699. struct SrcList_item *pItem;
  119700. int i;
  119701. if( !p ) return;
  119702. do{
  119703. substExprList(pSubst, p->pEList);
  119704. substExprList(pSubst, p->pGroupBy);
  119705. substExprList(pSubst, p->pOrderBy);
  119706. p->pHaving = substExpr(pSubst, p->pHaving);
  119707. p->pWhere = substExpr(pSubst, p->pWhere);
  119708. pSrc = p->pSrc;
  119709. assert( pSrc!=0 );
  119710. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  119711. substSelect(pSubst, pItem->pSelect, 1);
  119712. if( pItem->fg.isTabFunc ){
  119713. substExprList(pSubst, pItem->u1.pFuncArg);
  119714. }
  119715. }
  119716. }while( doPrior && (p = p->pPrior)!=0 );
  119717. }
  119718. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  119719. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  119720. /*
  119721. ** This routine attempts to flatten subqueries as a performance optimization.
  119722. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  119723. **
  119724. ** To understand the concept of flattening, consider the following
  119725. ** query:
  119726. **
  119727. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  119728. **
  119729. ** The default way of implementing this query is to execute the
  119730. ** subquery first and store the results in a temporary table, then
  119731. ** run the outer query on that temporary table. This requires two
  119732. ** passes over the data. Furthermore, because the temporary table
  119733. ** has no indices, the WHERE clause on the outer query cannot be
  119734. ** optimized.
  119735. **
  119736. ** This routine attempts to rewrite queries such as the above into
  119737. ** a single flat select, like this:
  119738. **
  119739. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  119740. **
  119741. ** The code generated for this simplification gives the same result
  119742. ** but only has to scan the data once. And because indices might
  119743. ** exist on the table t1, a complete scan of the data might be
  119744. ** avoided.
  119745. **
  119746. ** Flattening is subject to the following constraints:
  119747. **
  119748. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  119749. ** The subquery and the outer query cannot both be aggregates.
  119750. **
  119751. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  119752. ** (2) If the subquery is an aggregate then
  119753. ** (2a) the outer query must not be a join and
  119754. ** (2b) the outer query must not use subqueries
  119755. ** other than the one FROM-clause subquery that is a candidate
  119756. ** for flattening. (This is due to ticket [2f7170d73bf9abf80]
  119757. ** from 2015-02-09.)
  119758. **
  119759. ** (3) If the subquery is the right operand of a LEFT JOIN then
  119760. ** (3a) the subquery may not be a join and
  119761. ** (3b) the FROM clause of the subquery may not contain a virtual
  119762. ** table and
  119763. ** (3c) the outer query may not be an aggregate.
  119764. **
  119765. ** (4) The subquery can not be DISTINCT.
  119766. **
  119767. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  119768. ** sub-queries that were excluded from this optimization. Restriction
  119769. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  119770. **
  119771. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  119772. ** If the subquery is aggregate, the outer query may not be DISTINCT.
  119773. **
  119774. ** (7) The subquery must have a FROM clause. TODO: For subqueries without
  119775. ** A FROM clause, consider adding a FROM clause with the special
  119776. ** table sqlite_once that consists of a single row containing a
  119777. ** single NULL.
  119778. **
  119779. ** (8) If the subquery uses LIMIT then the outer query may not be a join.
  119780. **
  119781. ** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
  119782. **
  119783. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  119784. ** accidently carried the comment forward until 2014-09-15. Original
  119785. ** constraint: "If the subquery is aggregate then the outer query
  119786. ** may not use LIMIT."
  119787. **
  119788. ** (11) The subquery and the outer query may not both have ORDER BY clauses.
  119789. **
  119790. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  119791. ** a separate restriction deriving from ticket #350.
  119792. **
  119793. ** (13) The subquery and outer query may not both use LIMIT.
  119794. **
  119795. ** (14) The subquery may not use OFFSET.
  119796. **
  119797. ** (15) If the outer query is part of a compound select, then the
  119798. ** subquery may not use LIMIT.
  119799. ** (See ticket #2339 and ticket [02a8e81d44]).
  119800. **
  119801. ** (16) If the outer query is aggregate, then the subquery may not
  119802. ** use ORDER BY. (Ticket #2942) This used to not matter
  119803. ** until we introduced the group_concat() function.
  119804. **
  119805. ** (17) If the subquery is a compound select, then
  119806. ** (17a) all compound operators must be a UNION ALL, and
  119807. ** (17b) no terms within the subquery compound may be aggregate
  119808. ** or DISTINCT, and
  119809. ** (17c) every term within the subquery compound must have a FROM clause
  119810. ** (17d) the outer query may not be
  119811. ** (17d1) aggregate, or
  119812. ** (17d2) DISTINCT, or
  119813. ** (17d3) a join.
  119814. **
  119815. ** The parent and sub-query may contain WHERE clauses. Subject to
  119816. ** rules (11), (13) and (14), they may also contain ORDER BY,
  119817. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  119818. ** operator other than UNION ALL because all the other compound
  119819. ** operators have an implied DISTINCT which is disallowed by
  119820. ** restriction (4).
  119821. **
  119822. ** Also, each component of the sub-query must return the same number
  119823. ** of result columns. This is actually a requirement for any compound
  119824. ** SELECT statement, but all the code here does is make sure that no
  119825. ** such (illegal) sub-query is flattened. The caller will detect the
  119826. ** syntax error and return a detailed message.
  119827. **
  119828. ** (18) If the sub-query is a compound select, then all terms of the
  119829. ** ORDER BY clause of the parent must be simple references to
  119830. ** columns of the sub-query.
  119831. **
  119832. ** (19) If the subquery uses LIMIT then the outer query may not
  119833. ** have a WHERE clause.
  119834. **
  119835. ** (20) If the sub-query is a compound select, then it must not use
  119836. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  119837. ** somewhat by saying that the terms of the ORDER BY clause must
  119838. ** appear as unmodified result columns in the outer query. But we
  119839. ** have other optimizations in mind to deal with that case.
  119840. **
  119841. ** (21) If the subquery uses LIMIT then the outer query may not be
  119842. ** DISTINCT. (See ticket [752e1646fc]).
  119843. **
  119844. ** (22) The subquery may not be a recursive CTE.
  119845. **
  119846. ** (**) Subsumed into restriction (17d3). Was: If the outer query is
  119847. ** a recursive CTE, then the sub-query may not be a compound query.
  119848. ** This restriction is because transforming the
  119849. ** parent to a compound query confuses the code that handles
  119850. ** recursive queries in multiSelect().
  119851. **
  119852. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  119853. ** The subquery may not be an aggregate that uses the built-in min() or
  119854. ** or max() functions. (Without this restriction, a query like:
  119855. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  119856. ** return the value X for which Y was maximal.)
  119857. **
  119858. ** (25) If either the subquery or the parent query contains a window
  119859. ** function in the select list or ORDER BY clause, flattening
  119860. ** is not attempted.
  119861. **
  119862. **
  119863. ** In this routine, the "p" parameter is a pointer to the outer query.
  119864. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  119865. ** uses aggregates.
  119866. **
  119867. ** If flattening is not attempted, this routine is a no-op and returns 0.
  119868. ** If flattening is attempted this routine returns 1.
  119869. **
  119870. ** All of the expression analysis must occur on both the outer query and
  119871. ** the subquery before this routine runs.
  119872. */
  119873. static int flattenSubquery(
  119874. Parse *pParse, /* Parsing context */
  119875. Select *p, /* The parent or outer SELECT statement */
  119876. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  119877. int isAgg /* True if outer SELECT uses aggregate functions */
  119878. ){
  119879. const char *zSavedAuthContext = pParse->zAuthContext;
  119880. Select *pParent; /* Current UNION ALL term of the other query */
  119881. Select *pSub; /* The inner query or "subquery" */
  119882. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  119883. SrcList *pSrc; /* The FROM clause of the outer query */
  119884. SrcList *pSubSrc; /* The FROM clause of the subquery */
  119885. int iParent; /* VDBE cursor number of the pSub result set temp table */
  119886. int iNewParent = -1;/* Replacement table for iParent */
  119887. int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
  119888. int i; /* Loop counter */
  119889. Expr *pWhere; /* The WHERE clause */
  119890. struct SrcList_item *pSubitem; /* The subquery */
  119891. sqlite3 *db = pParse->db;
  119892. /* Check to see if flattening is permitted. Return 0 if not.
  119893. */
  119894. assert( p!=0 );
  119895. assert( p->pPrior==0 );
  119896. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  119897. pSrc = p->pSrc;
  119898. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  119899. pSubitem = &pSrc->a[iFrom];
  119900. iParent = pSubitem->iCursor;
  119901. pSub = pSubitem->pSelect;
  119902. assert( pSub!=0 );
  119903. #ifndef SQLITE_OMIT_WINDOWFUNC
  119904. if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
  119905. #endif
  119906. pSubSrc = pSub->pSrc;
  119907. assert( pSubSrc );
  119908. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  119909. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  119910. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  119911. ** became arbitrary expressions, we were forced to add restrictions (13)
  119912. ** and (14). */
  119913. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  119914. if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
  119915. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  119916. return 0; /* Restriction (15) */
  119917. }
  119918. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  119919. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
  119920. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  119921. return 0; /* Restrictions (8)(9) */
  119922. }
  119923. if( p->pOrderBy && pSub->pOrderBy ){
  119924. return 0; /* Restriction (11) */
  119925. }
  119926. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  119927. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  119928. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  119929. return 0; /* Restriction (21) */
  119930. }
  119931. if( pSub->selFlags & (SF_Recursive) ){
  119932. return 0; /* Restrictions (22) */
  119933. }
  119934. /*
  119935. ** If the subquery is the right operand of a LEFT JOIN, then the
  119936. ** subquery may not be a join itself (3a). Example of why this is not
  119937. ** allowed:
  119938. **
  119939. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  119940. **
  119941. ** If we flatten the above, we would get
  119942. **
  119943. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  119944. **
  119945. ** which is not at all the same thing.
  119946. **
  119947. ** If the subquery is the right operand of a LEFT JOIN, then the outer
  119948. ** query cannot be an aggregate. (3c) This is an artifact of the way
  119949. ** aggregates are processed - there is no mechanism to determine if
  119950. ** the LEFT JOIN table should be all-NULL.
  119951. **
  119952. ** See also tickets #306, #350, and #3300.
  119953. */
  119954. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  119955. isLeftJoin = 1;
  119956. if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
  119957. /* (3a) (3c) (3b) */
  119958. return 0;
  119959. }
  119960. }
  119961. #ifdef SQLITE_EXTRA_IFNULLROW
  119962. else if( iFrom>0 && !isAgg ){
  119963. /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
  119964. ** every reference to any result column from subquery in a join, even
  119965. ** though they are not necessary. This will stress-test the OP_IfNullRow
  119966. ** opcode. */
  119967. isLeftJoin = -1;
  119968. }
  119969. #endif
  119970. /* Restriction (17): If the sub-query is a compound SELECT, then it must
  119971. ** use only the UNION ALL operator. And none of the simple select queries
  119972. ** that make up the compound SELECT are allowed to be aggregate or distinct
  119973. ** queries.
  119974. */
  119975. if( pSub->pPrior ){
  119976. if( pSub->pOrderBy ){
  119977. return 0; /* Restriction (20) */
  119978. }
  119979. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  119980. return 0; /* (17d1), (17d2), or (17d3) */
  119981. }
  119982. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  119983. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  119984. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  119985. assert( pSub->pSrc!=0 );
  119986. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  119987. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
  119988. || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
  119989. || pSub1->pSrc->nSrc<1 /* (17c) */
  119990. ){
  119991. return 0;
  119992. }
  119993. testcase( pSub1->pSrc->nSrc>1 );
  119994. }
  119995. /* Restriction (18). */
  119996. if( p->pOrderBy ){
  119997. int ii;
  119998. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  119999. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  120000. }
  120001. }
  120002. }
  120003. /* Ex-restriction (23):
  120004. ** The only way that the recursive part of a CTE can contain a compound
  120005. ** subquery is for the subquery to be one term of a join. But if the
  120006. ** subquery is a join, then the flattening has already been stopped by
  120007. ** restriction (17d3)
  120008. */
  120009. assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
  120010. /***** If we reach this point, flattening is permitted. *****/
  120011. SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
  120012. pSub->selId, pSub, iFrom));
  120013. /* Authorize the subquery */
  120014. pParse->zAuthContext = pSubitem->zName;
  120015. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  120016. testcase( i==SQLITE_DENY );
  120017. pParse->zAuthContext = zSavedAuthContext;
  120018. /* If the sub-query is a compound SELECT statement, then (by restrictions
  120019. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  120020. ** be of the form:
  120021. **
  120022. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  120023. **
  120024. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  120025. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  120026. ** OFFSET clauses and joins them to the left-hand-side of the original
  120027. ** using UNION ALL operators. In this case N is the number of simple
  120028. ** select statements in the compound sub-query.
  120029. **
  120030. ** Example:
  120031. **
  120032. ** SELECT a+1 FROM (
  120033. ** SELECT x FROM tab
  120034. ** UNION ALL
  120035. ** SELECT y FROM tab
  120036. ** UNION ALL
  120037. ** SELECT abs(z*2) FROM tab2
  120038. ** ) WHERE a!=5 ORDER BY 1
  120039. **
  120040. ** Transformed into:
  120041. **
  120042. ** SELECT x+1 FROM tab WHERE x+1!=5
  120043. ** UNION ALL
  120044. ** SELECT y+1 FROM tab WHERE y+1!=5
  120045. ** UNION ALL
  120046. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  120047. ** ORDER BY 1
  120048. **
  120049. ** We call this the "compound-subquery flattening".
  120050. */
  120051. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  120052. Select *pNew;
  120053. ExprList *pOrderBy = p->pOrderBy;
  120054. Expr *pLimit = p->pLimit;
  120055. Select *pPrior = p->pPrior;
  120056. p->pOrderBy = 0;
  120057. p->pSrc = 0;
  120058. p->pPrior = 0;
  120059. p->pLimit = 0;
  120060. pNew = sqlite3SelectDup(db, p, 0);
  120061. p->pLimit = pLimit;
  120062. p->pOrderBy = pOrderBy;
  120063. p->pSrc = pSrc;
  120064. p->op = TK_ALL;
  120065. if( pNew==0 ){
  120066. p->pPrior = pPrior;
  120067. }else{
  120068. pNew->pPrior = pPrior;
  120069. if( pPrior ) pPrior->pNext = pNew;
  120070. pNew->pNext = p;
  120071. p->pPrior = pNew;
  120072. SELECTTRACE(2,pParse,p,("compound-subquery flattener"
  120073. " creates %u as peer\n",pNew->selId));
  120074. }
  120075. if( db->mallocFailed ) return 1;
  120076. }
  120077. /* Begin flattening the iFrom-th entry of the FROM clause
  120078. ** in the outer query.
  120079. */
  120080. pSub = pSub1 = pSubitem->pSelect;
  120081. /* Delete the transient table structure associated with the
  120082. ** subquery
  120083. */
  120084. sqlite3DbFree(db, pSubitem->zDatabase);
  120085. sqlite3DbFree(db, pSubitem->zName);
  120086. sqlite3DbFree(db, pSubitem->zAlias);
  120087. pSubitem->zDatabase = 0;
  120088. pSubitem->zName = 0;
  120089. pSubitem->zAlias = 0;
  120090. pSubitem->pSelect = 0;
  120091. /* Defer deleting the Table object associated with the
  120092. ** subquery until code generation is
  120093. ** complete, since there may still exist Expr.pTab entries that
  120094. ** refer to the subquery even after flattening. Ticket #3346.
  120095. **
  120096. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  120097. */
  120098. if( ALWAYS(pSubitem->pTab!=0) ){
  120099. Table *pTabToDel = pSubitem->pTab;
  120100. if( pTabToDel->nTabRef==1 ){
  120101. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  120102. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  120103. pToplevel->pZombieTab = pTabToDel;
  120104. }else{
  120105. pTabToDel->nTabRef--;
  120106. }
  120107. pSubitem->pTab = 0;
  120108. }
  120109. /* The following loop runs once for each term in a compound-subquery
  120110. ** flattening (as described above). If we are doing a different kind
  120111. ** of flattening - a flattening other than a compound-subquery flattening -
  120112. ** then this loop only runs once.
  120113. **
  120114. ** This loop moves all of the FROM elements of the subquery into the
  120115. ** the FROM clause of the outer query. Before doing this, remember
  120116. ** the cursor number for the original outer query FROM element in
  120117. ** iParent. The iParent cursor will never be used. Subsequent code
  120118. ** will scan expressions looking for iParent references and replace
  120119. ** those references with expressions that resolve to the subquery FROM
  120120. ** elements we are now copying in.
  120121. */
  120122. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  120123. int nSubSrc;
  120124. u8 jointype = 0;
  120125. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  120126. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  120127. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  120128. if( pSrc ){
  120129. assert( pParent==p ); /* First time through the loop */
  120130. jointype = pSubitem->fg.jointype;
  120131. }else{
  120132. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  120133. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  120134. if( pSrc==0 ){
  120135. assert( db->mallocFailed );
  120136. break;
  120137. }
  120138. }
  120139. /* The subquery uses a single slot of the FROM clause of the outer
  120140. ** query. If the subquery has more than one element in its FROM clause,
  120141. ** then expand the outer query to make space for it to hold all elements
  120142. ** of the subquery.
  120143. **
  120144. ** Example:
  120145. **
  120146. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  120147. **
  120148. ** The outer query has 3 slots in its FROM clause. One slot of the
  120149. ** outer query (the middle slot) is used by the subquery. The next
  120150. ** block of code will expand the outer query FROM clause to 4 slots.
  120151. ** The middle slot is expanded to two slots in order to make space
  120152. ** for the two elements in the FROM clause of the subquery.
  120153. */
  120154. if( nSubSrc>1 ){
  120155. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  120156. if( db->mallocFailed ){
  120157. break;
  120158. }
  120159. }
  120160. /* Transfer the FROM clause terms from the subquery into the
  120161. ** outer query.
  120162. */
  120163. for(i=0; i<nSubSrc; i++){
  120164. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  120165. assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
  120166. pSrc->a[i+iFrom] = pSubSrc->a[i];
  120167. iNewParent = pSubSrc->a[i].iCursor;
  120168. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  120169. }
  120170. pSrc->a[iFrom].fg.jointype = jointype;
  120171. /* Now begin substituting subquery result set expressions for
  120172. ** references to the iParent in the outer query.
  120173. **
  120174. ** Example:
  120175. **
  120176. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  120177. ** \ \_____________ subquery __________/ /
  120178. ** \_____________________ outer query ______________________________/
  120179. **
  120180. ** We look at every expression in the outer query and every place we see
  120181. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  120182. */
  120183. if( pSub->pOrderBy ){
  120184. /* At this point, any non-zero iOrderByCol values indicate that the
  120185. ** ORDER BY column expression is identical to the iOrderByCol'th
  120186. ** expression returned by SELECT statement pSub. Since these values
  120187. ** do not necessarily correspond to columns in SELECT statement pParent,
  120188. ** zero them before transfering the ORDER BY clause.
  120189. **
  120190. ** Not doing this may cause an error if a subsequent call to this
  120191. ** function attempts to flatten a compound sub-query into pParent
  120192. ** (the only way this can happen is if the compound sub-query is
  120193. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  120194. ExprList *pOrderBy = pSub->pOrderBy;
  120195. for(i=0; i<pOrderBy->nExpr; i++){
  120196. pOrderBy->a[i].u.x.iOrderByCol = 0;
  120197. }
  120198. assert( pParent->pOrderBy==0 );
  120199. pParent->pOrderBy = pOrderBy;
  120200. pSub->pOrderBy = 0;
  120201. }
  120202. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  120203. if( isLeftJoin>0 ){
  120204. setJoinExpr(pWhere, iNewParent);
  120205. }
  120206. pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
  120207. if( db->mallocFailed==0 ){
  120208. SubstContext x;
  120209. x.pParse = pParse;
  120210. x.iTable = iParent;
  120211. x.iNewTable = iNewParent;
  120212. x.isLeftJoin = isLeftJoin;
  120213. x.pEList = pSub->pEList;
  120214. substSelect(&x, pParent, 0);
  120215. }
  120216. /* The flattened query is distinct if either the inner or the
  120217. ** outer query is distinct.
  120218. */
  120219. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  120220. /*
  120221. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  120222. **
  120223. ** One is tempted to try to add a and b to combine the limits. But this
  120224. ** does not work if either limit is negative.
  120225. */
  120226. if( pSub->pLimit ){
  120227. pParent->pLimit = pSub->pLimit;
  120228. pSub->pLimit = 0;
  120229. }
  120230. }
  120231. /* Finially, delete what is left of the subquery and return
  120232. ** success.
  120233. */
  120234. sqlite3SelectDelete(db, pSub1);
  120235. #if SELECTTRACE_ENABLED
  120236. if( sqlite3SelectTrace & 0x100 ){
  120237. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  120238. sqlite3TreeViewSelect(0, p, 0);
  120239. }
  120240. #endif
  120241. return 1;
  120242. }
  120243. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  120244. /*
  120245. ** A structure to keep track of all of the column values that are fixed to
  120246. ** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
  120247. */
  120248. typedef struct WhereConst WhereConst;
  120249. struct WhereConst {
  120250. Parse *pParse; /* Parsing context */
  120251. int nConst; /* Number for COLUMN=CONSTANT terms */
  120252. int nChng; /* Number of times a constant is propagated */
  120253. Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
  120254. };
  120255. /*
  120256. ** Add a new entry to the pConst object. Except, do not add duplicate
  120257. ** pColumn entires.
  120258. */
  120259. static void constInsert(
  120260. WhereConst *pConst, /* The WhereConst into which we are inserting */
  120261. Expr *pColumn, /* The COLUMN part of the constraint */
  120262. Expr *pValue /* The VALUE part of the constraint */
  120263. ){
  120264. int i;
  120265. assert( pColumn->op==TK_COLUMN );
  120266. /* 2018-10-25 ticket [cf5ed20f]
  120267. ** Make sure the same pColumn is not inserted more than once */
  120268. for(i=0; i<pConst->nConst; i++){
  120269. const Expr *pExpr = pConst->apExpr[i*2];
  120270. assert( pExpr->op==TK_COLUMN );
  120271. if( pExpr->iTable==pColumn->iTable
  120272. && pExpr->iColumn==pColumn->iColumn
  120273. ){
  120274. return; /* Already present. Return without doing anything. */
  120275. }
  120276. }
  120277. pConst->nConst++;
  120278. pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
  120279. pConst->nConst*2*sizeof(Expr*));
  120280. if( pConst->apExpr==0 ){
  120281. pConst->nConst = 0;
  120282. }else{
  120283. if( ExprHasProperty(pValue, EP_FixedCol) ) pValue = pValue->pLeft;
  120284. pConst->apExpr[pConst->nConst*2-2] = pColumn;
  120285. pConst->apExpr[pConst->nConst*2-1] = pValue;
  120286. }
  120287. }
  120288. /*
  120289. ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
  120290. ** is a constant expression and where the term must be true because it
  120291. ** is part of the AND-connected terms of the expression. For each term
  120292. ** found, add it to the pConst structure.
  120293. */
  120294. static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
  120295. Expr *pRight, *pLeft;
  120296. if( pExpr==0 ) return;
  120297. if( ExprHasProperty(pExpr, EP_FromJoin) ) return;
  120298. if( pExpr->op==TK_AND ){
  120299. findConstInWhere(pConst, pExpr->pRight);
  120300. findConstInWhere(pConst, pExpr->pLeft);
  120301. return;
  120302. }
  120303. if( pExpr->op!=TK_EQ ) return;
  120304. pRight = pExpr->pRight;
  120305. pLeft = pExpr->pLeft;
  120306. assert( pRight!=0 );
  120307. assert( pLeft!=0 );
  120308. if( pRight->op==TK_COLUMN
  120309. && !ExprHasProperty(pRight, EP_FixedCol)
  120310. && sqlite3ExprIsConstant(pLeft)
  120311. && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight))
  120312. ){
  120313. constInsert(pConst, pRight, pLeft);
  120314. }else
  120315. if( pLeft->op==TK_COLUMN
  120316. && !ExprHasProperty(pLeft, EP_FixedCol)
  120317. && sqlite3ExprIsConstant(pRight)
  120318. && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight))
  120319. ){
  120320. constInsert(pConst, pLeft, pRight);
  120321. }
  120322. }
  120323. /*
  120324. ** This is a Walker expression callback. pExpr is a candidate expression
  120325. ** to be replaced by a value. If pExpr is equivalent to one of the
  120326. ** columns named in pWalker->u.pConst, then overwrite it with its
  120327. ** corresponding value.
  120328. */
  120329. static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
  120330. int i;
  120331. WhereConst *pConst;
  120332. if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
  120333. if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue;
  120334. pConst = pWalker->u.pConst;
  120335. for(i=0; i<pConst->nConst; i++){
  120336. Expr *pColumn = pConst->apExpr[i*2];
  120337. if( pColumn==pExpr ) continue;
  120338. if( pColumn->iTable!=pExpr->iTable ) continue;
  120339. if( pColumn->iColumn!=pExpr->iColumn ) continue;
  120340. /* A match is found. Add the EP_FixedCol property */
  120341. pConst->nChng++;
  120342. ExprClearProperty(pExpr, EP_Leaf);
  120343. ExprSetProperty(pExpr, EP_FixedCol);
  120344. assert( pExpr->pLeft==0 );
  120345. pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
  120346. break;
  120347. }
  120348. return WRC_Prune;
  120349. }
  120350. /*
  120351. ** The WHERE-clause constant propagation optimization.
  120352. **
  120353. ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
  120354. ** CONSTANT=COLUMN that must be tree (in other words, if the terms top-level
  120355. ** AND-connected terms that are not part of a ON clause from a LEFT JOIN)
  120356. ** then throughout the query replace all other occurrences of COLUMN
  120357. ** with CONSTANT within the WHERE clause.
  120358. **
  120359. ** For example, the query:
  120360. **
  120361. ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
  120362. **
  120363. ** Is transformed into
  120364. **
  120365. ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
  120366. **
  120367. ** Return true if any transformations where made and false if not.
  120368. **
  120369. ** Implementation note: Constant propagation is tricky due to affinity
  120370. ** and collating sequence interactions. Consider this example:
  120371. **
  120372. ** CREATE TABLE t1(a INT,b TEXT);
  120373. ** INSERT INTO t1 VALUES(123,'0123');
  120374. ** SELECT * FROM t1 WHERE a=123 AND b=a;
  120375. ** SELECT * FROM t1 WHERE a=123 AND b=123;
  120376. **
  120377. ** The two SELECT statements above should return different answers. b=a
  120378. ** is alway true because the comparison uses numeric affinity, but b=123
  120379. ** is false because it uses text affinity and '0123' is not the same as '123'.
  120380. ** To work around this, the expression tree is not actually changed from
  120381. ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
  120382. ** and the "123" value is hung off of the pLeft pointer. Code generator
  120383. ** routines know to generate the constant "123" instead of looking up the
  120384. ** column value. Also, to avoid collation problems, this optimization is
  120385. ** only attempted if the "a=123" term uses the default BINARY collation.
  120386. */
  120387. static int propagateConstants(
  120388. Parse *pParse, /* The parsing context */
  120389. Select *p /* The query in which to propagate constants */
  120390. ){
  120391. WhereConst x;
  120392. Walker w;
  120393. int nChng = 0;
  120394. x.pParse = pParse;
  120395. do{
  120396. x.nConst = 0;
  120397. x.nChng = 0;
  120398. x.apExpr = 0;
  120399. findConstInWhere(&x, p->pWhere);
  120400. if( x.nConst ){
  120401. memset(&w, 0, sizeof(w));
  120402. w.pParse = pParse;
  120403. w.xExprCallback = propagateConstantExprRewrite;
  120404. w.xSelectCallback = sqlite3SelectWalkNoop;
  120405. w.xSelectCallback2 = 0;
  120406. w.walkerDepth = 0;
  120407. w.u.pConst = &x;
  120408. sqlite3WalkExpr(&w, p->pWhere);
  120409. sqlite3DbFree(x.pParse->db, x.apExpr);
  120410. nChng += x.nChng;
  120411. }
  120412. }while( x.nChng );
  120413. return nChng;
  120414. }
  120415. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  120416. /*
  120417. ** Make copies of relevant WHERE clause terms of the outer query into
  120418. ** the WHERE clause of subquery. Example:
  120419. **
  120420. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  120421. **
  120422. ** Transformed into:
  120423. **
  120424. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  120425. ** WHERE x=5 AND y=10;
  120426. **
  120427. ** The hope is that the terms added to the inner query will make it more
  120428. ** efficient.
  120429. **
  120430. ** Do not attempt this optimization if:
  120431. **
  120432. ** (1) (** This restriction was removed on 2017-09-29. We used to
  120433. ** disallow this optimization for aggregate subqueries, but now
  120434. ** it is allowed by putting the extra terms on the HAVING clause.
  120435. ** The added HAVING clause is pointless if the subquery lacks
  120436. ** a GROUP BY clause. But such a HAVING clause is also harmless
  120437. ** so there does not appear to be any reason to add extra logic
  120438. ** to suppress it. **)
  120439. **
  120440. ** (2) The inner query is the recursive part of a common table expression.
  120441. **
  120442. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  120443. ** clause would change the meaning of the LIMIT).
  120444. **
  120445. ** (4) The inner query is the right operand of a LEFT JOIN and the
  120446. ** expression to be pushed down does not come from the ON clause
  120447. ** on that LEFT JOIN.
  120448. **
  120449. ** (5) The WHERE clause expression originates in the ON or USING clause
  120450. ** of a LEFT JOIN where iCursor is not the right-hand table of that
  120451. ** left join. An example:
  120452. **
  120453. ** SELECT *
  120454. ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
  120455. ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
  120456. ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
  120457. **
  120458. ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
  120459. ** But if the (b2=2) term were to be pushed down into the bb subquery,
  120460. ** then the (1,1,NULL) row would be suppressed.
  120461. **
  120462. ** (6) The inner query features one or more window-functions (since
  120463. ** changes to the WHERE clause of the inner query could change the
  120464. ** window over which window functions are calculated).
  120465. **
  120466. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  120467. ** terms are duplicated into the subquery.
  120468. */
  120469. static int pushDownWhereTerms(
  120470. Parse *pParse, /* Parse context (for malloc() and error reporting) */
  120471. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  120472. Expr *pWhere, /* The WHERE clause of the outer query */
  120473. int iCursor, /* Cursor number of the subquery */
  120474. int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */
  120475. ){
  120476. Expr *pNew;
  120477. int nChng = 0;
  120478. if( pWhere==0 ) return 0;
  120479. if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
  120480. #ifndef SQLITE_OMIT_WINDOWFUNC
  120481. if( pSubq->pWin ) return 0; /* restriction (6) */
  120482. #endif
  120483. #ifdef SQLITE_DEBUG
  120484. /* Only the first term of a compound can have a WITH clause. But make
  120485. ** sure no other terms are marked SF_Recursive in case something changes
  120486. ** in the future.
  120487. */
  120488. {
  120489. Select *pX;
  120490. for(pX=pSubq; pX; pX=pX->pPrior){
  120491. assert( (pX->selFlags & (SF_Recursive))==0 );
  120492. }
  120493. }
  120494. #endif
  120495. if( pSubq->pLimit!=0 ){
  120496. return 0; /* restriction (3) */
  120497. }
  120498. while( pWhere->op==TK_AND ){
  120499. nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
  120500. iCursor, isLeftJoin);
  120501. pWhere = pWhere->pLeft;
  120502. }
  120503. if( isLeftJoin
  120504. && (ExprHasProperty(pWhere,EP_FromJoin)==0
  120505. || pWhere->iRightJoinTable!=iCursor)
  120506. ){
  120507. return 0; /* restriction (4) */
  120508. }
  120509. if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
  120510. return 0; /* restriction (5) */
  120511. }
  120512. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  120513. nChng++;
  120514. while( pSubq ){
  120515. SubstContext x;
  120516. pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
  120517. unsetJoinExpr(pNew, -1);
  120518. x.pParse = pParse;
  120519. x.iTable = iCursor;
  120520. x.iNewTable = iCursor;
  120521. x.isLeftJoin = 0;
  120522. x.pEList = pSubq->pEList;
  120523. pNew = substExpr(&x, pNew);
  120524. if( pSubq->selFlags & SF_Aggregate ){
  120525. pSubq->pHaving = sqlite3ExprAnd(pParse->db, pSubq->pHaving, pNew);
  120526. }else{
  120527. pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
  120528. }
  120529. pSubq = pSubq->pPrior;
  120530. }
  120531. }
  120532. return nChng;
  120533. }
  120534. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  120535. /*
  120536. ** The pFunc is the only aggregate function in the query. Check to see
  120537. ** if the query is a candidate for the min/max optimization.
  120538. **
  120539. ** If the query is a candidate for the min/max optimization, then set
  120540. ** *ppMinMax to be an ORDER BY clause to be used for the optimization
  120541. ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
  120542. ** whether pFunc is a min() or max() function.
  120543. **
  120544. ** If the query is not a candidate for the min/max optimization, return
  120545. ** WHERE_ORDERBY_NORMAL (which must be zero).
  120546. **
  120547. ** This routine must be called after aggregate functions have been
  120548. ** located but before their arguments have been subjected to aggregate
  120549. ** analysis.
  120550. */
  120551. static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
  120552. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  120553. ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */
  120554. const char *zFunc; /* Name of aggregate function pFunc */
  120555. ExprList *pOrderBy;
  120556. u8 sortOrder;
  120557. assert( *ppMinMax==0 );
  120558. assert( pFunc->op==TK_AGG_FUNCTION );
  120559. if( pEList==0 || pEList->nExpr!=1 ) return eRet;
  120560. zFunc = pFunc->u.zToken;
  120561. if( sqlite3StrICmp(zFunc, "min")==0 ){
  120562. eRet = WHERE_ORDERBY_MIN;
  120563. sortOrder = SQLITE_SO_ASC;
  120564. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  120565. eRet = WHERE_ORDERBY_MAX;
  120566. sortOrder = SQLITE_SO_DESC;
  120567. }else{
  120568. return eRet;
  120569. }
  120570. *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
  120571. assert( pOrderBy!=0 || db->mallocFailed );
  120572. if( pOrderBy ) pOrderBy->a[0].sortOrder = sortOrder;
  120573. return eRet;
  120574. }
  120575. /*
  120576. ** The select statement passed as the first argument is an aggregate query.
  120577. ** The second argument is the associated aggregate-info object. This
  120578. ** function tests if the SELECT is of the form:
  120579. **
  120580. ** SELECT count(*) FROM <tbl>
  120581. **
  120582. ** where table is a database table, not a sub-select or view. If the query
  120583. ** does match this pattern, then a pointer to the Table object representing
  120584. ** <tbl> is returned. Otherwise, 0 is returned.
  120585. */
  120586. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  120587. Table *pTab;
  120588. Expr *pExpr;
  120589. assert( !p->pGroupBy );
  120590. if( p->pWhere || p->pEList->nExpr!=1
  120591. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  120592. ){
  120593. return 0;
  120594. }
  120595. pTab = p->pSrc->a[0].pTab;
  120596. pExpr = p->pEList->a[0].pExpr;
  120597. assert( pTab && !pTab->pSelect && pExpr );
  120598. if( IsVirtual(pTab) ) return 0;
  120599. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  120600. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  120601. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  120602. if( pExpr->flags&EP_Distinct ) return 0;
  120603. return pTab;
  120604. }
  120605. /*
  120606. ** If the source-list item passed as an argument was augmented with an
  120607. ** INDEXED BY clause, then try to locate the specified index. If there
  120608. ** was such a clause and the named index cannot be found, return
  120609. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  120610. ** pFrom->pIndex and return SQLITE_OK.
  120611. */
  120612. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  120613. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  120614. Table *pTab = pFrom->pTab;
  120615. char *zIndexedBy = pFrom->u1.zIndexedBy;
  120616. Index *pIdx;
  120617. for(pIdx=pTab->pIndex;
  120618. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  120619. pIdx=pIdx->pNext
  120620. );
  120621. if( !pIdx ){
  120622. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  120623. pParse->checkSchema = 1;
  120624. return SQLITE_ERROR;
  120625. }
  120626. pFrom->pIBIndex = pIdx;
  120627. }
  120628. return SQLITE_OK;
  120629. }
  120630. /*
  120631. ** Detect compound SELECT statements that use an ORDER BY clause with
  120632. ** an alternative collating sequence.
  120633. **
  120634. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  120635. **
  120636. ** These are rewritten as a subquery:
  120637. **
  120638. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  120639. ** ORDER BY ... COLLATE ...
  120640. **
  120641. ** This transformation is necessary because the multiSelectOrderBy() routine
  120642. ** above that generates the code for a compound SELECT with an ORDER BY clause
  120643. ** uses a merge algorithm that requires the same collating sequence on the
  120644. ** result columns as on the ORDER BY clause. See ticket
  120645. ** http://www.sqlite.org/src/info/6709574d2a
  120646. **
  120647. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  120648. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  120649. ** there are COLLATE terms in the ORDER BY.
  120650. */
  120651. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  120652. int i;
  120653. Select *pNew;
  120654. Select *pX;
  120655. sqlite3 *db;
  120656. struct ExprList_item *a;
  120657. SrcList *pNewSrc;
  120658. Parse *pParse;
  120659. Token dummy;
  120660. if( p->pPrior==0 ) return WRC_Continue;
  120661. if( p->pOrderBy==0 ) return WRC_Continue;
  120662. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  120663. if( pX==0 ) return WRC_Continue;
  120664. a = p->pOrderBy->a;
  120665. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  120666. if( a[i].pExpr->flags & EP_Collate ) break;
  120667. }
  120668. if( i<0 ) return WRC_Continue;
  120669. /* If we reach this point, that means the transformation is required. */
  120670. pParse = pWalker->pParse;
  120671. db = pParse->db;
  120672. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  120673. if( pNew==0 ) return WRC_Abort;
  120674. memset(&dummy, 0, sizeof(dummy));
  120675. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  120676. if( pNewSrc==0 ) return WRC_Abort;
  120677. *pNew = *p;
  120678. p->pSrc = pNewSrc;
  120679. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
  120680. p->op = TK_SELECT;
  120681. p->pWhere = 0;
  120682. pNew->pGroupBy = 0;
  120683. pNew->pHaving = 0;
  120684. pNew->pOrderBy = 0;
  120685. p->pPrior = 0;
  120686. p->pNext = 0;
  120687. p->pWith = 0;
  120688. p->selFlags &= ~SF_Compound;
  120689. assert( (p->selFlags & SF_Converted)==0 );
  120690. p->selFlags |= SF_Converted;
  120691. assert( pNew->pPrior!=0 );
  120692. pNew->pPrior->pNext = pNew;
  120693. pNew->pLimit = 0;
  120694. return WRC_Continue;
  120695. }
  120696. /*
  120697. ** Check to see if the FROM clause term pFrom has table-valued function
  120698. ** arguments. If it does, leave an error message in pParse and return
  120699. ** non-zero, since pFrom is not allowed to be a table-valued function.
  120700. */
  120701. static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
  120702. if( pFrom->fg.isTabFunc ){
  120703. sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
  120704. return 1;
  120705. }
  120706. return 0;
  120707. }
  120708. #ifndef SQLITE_OMIT_CTE
  120709. /*
  120710. ** Argument pWith (which may be NULL) points to a linked list of nested
  120711. ** WITH contexts, from inner to outermost. If the table identified by
  120712. ** FROM clause element pItem is really a common-table-expression (CTE)
  120713. ** then return a pointer to the CTE definition for that table. Otherwise
  120714. ** return NULL.
  120715. **
  120716. ** If a non-NULL value is returned, set *ppContext to point to the With
  120717. ** object that the returned CTE belongs to.
  120718. */
  120719. static struct Cte *searchWith(
  120720. With *pWith, /* Current innermost WITH clause */
  120721. struct SrcList_item *pItem, /* FROM clause element to resolve */
  120722. With **ppContext /* OUT: WITH clause return value belongs to */
  120723. ){
  120724. const char *zName;
  120725. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  120726. With *p;
  120727. for(p=pWith; p; p=p->pOuter){
  120728. int i;
  120729. for(i=0; i<p->nCte; i++){
  120730. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  120731. *ppContext = p;
  120732. return &p->a[i];
  120733. }
  120734. }
  120735. }
  120736. }
  120737. return 0;
  120738. }
  120739. /* The code generator maintains a stack of active WITH clauses
  120740. ** with the inner-most WITH clause being at the top of the stack.
  120741. **
  120742. ** This routine pushes the WITH clause passed as the second argument
  120743. ** onto the top of the stack. If argument bFree is true, then this
  120744. ** WITH clause will never be popped from the stack. In this case it
  120745. ** should be freed along with the Parse object. In other cases, when
  120746. ** bFree==0, the With object will be freed along with the SELECT
  120747. ** statement with which it is associated.
  120748. */
  120749. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  120750. assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
  120751. if( pWith ){
  120752. assert( pParse->pWith!=pWith );
  120753. pWith->pOuter = pParse->pWith;
  120754. pParse->pWith = pWith;
  120755. if( bFree ) pParse->pWithToFree = pWith;
  120756. }
  120757. }
  120758. /*
  120759. ** This function checks if argument pFrom refers to a CTE declared by
  120760. ** a WITH clause on the stack currently maintained by the parser. And,
  120761. ** if currently processing a CTE expression, if it is a recursive
  120762. ** reference to the current CTE.
  120763. **
  120764. ** If pFrom falls into either of the two categories above, pFrom->pTab
  120765. ** and other fields are populated accordingly. The caller should check
  120766. ** (pFrom->pTab!=0) to determine whether or not a successful match
  120767. ** was found.
  120768. **
  120769. ** Whether or not a match is found, SQLITE_OK is returned if no error
  120770. ** occurs. If an error does occur, an error message is stored in the
  120771. ** parser and some error code other than SQLITE_OK returned.
  120772. */
  120773. static int withExpand(
  120774. Walker *pWalker,
  120775. struct SrcList_item *pFrom
  120776. ){
  120777. Parse *pParse = pWalker->pParse;
  120778. sqlite3 *db = pParse->db;
  120779. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  120780. With *pWith; /* WITH clause that pCte belongs to */
  120781. assert( pFrom->pTab==0 );
  120782. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  120783. if( pCte ){
  120784. Table *pTab;
  120785. ExprList *pEList;
  120786. Select *pSel;
  120787. Select *pLeft; /* Left-most SELECT statement */
  120788. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  120789. With *pSavedWith; /* Initial value of pParse->pWith */
  120790. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  120791. ** recursive reference to CTE pCte. Leave an error in pParse and return
  120792. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  120793. ** In this case, proceed. */
  120794. if( pCte->zCteErr ){
  120795. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  120796. return SQLITE_ERROR;
  120797. }
  120798. if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
  120799. assert( pFrom->pTab==0 );
  120800. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  120801. if( pTab==0 ) return WRC_Abort;
  120802. pTab->nTabRef = 1;
  120803. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  120804. pTab->iPKey = -1;
  120805. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  120806. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  120807. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  120808. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  120809. assert( pFrom->pSelect );
  120810. /* Check if this is a recursive CTE. */
  120811. pSel = pFrom->pSelect;
  120812. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  120813. if( bMayRecursive ){
  120814. int i;
  120815. SrcList *pSrc = pFrom->pSelect->pSrc;
  120816. for(i=0; i<pSrc->nSrc; i++){
  120817. struct SrcList_item *pItem = &pSrc->a[i];
  120818. if( pItem->zDatabase==0
  120819. && pItem->zName!=0
  120820. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  120821. ){
  120822. pItem->pTab = pTab;
  120823. pItem->fg.isRecursive = 1;
  120824. pTab->nTabRef++;
  120825. pSel->selFlags |= SF_Recursive;
  120826. }
  120827. }
  120828. }
  120829. /* Only one recursive reference is permitted. */
  120830. if( pTab->nTabRef>2 ){
  120831. sqlite3ErrorMsg(
  120832. pParse, "multiple references to recursive table: %s", pCte->zName
  120833. );
  120834. return SQLITE_ERROR;
  120835. }
  120836. assert( pTab->nTabRef==1 ||
  120837. ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
  120838. pCte->zCteErr = "circular reference: %s";
  120839. pSavedWith = pParse->pWith;
  120840. pParse->pWith = pWith;
  120841. if( bMayRecursive ){
  120842. Select *pPrior = pSel->pPrior;
  120843. assert( pPrior->pWith==0 );
  120844. pPrior->pWith = pSel->pWith;
  120845. sqlite3WalkSelect(pWalker, pPrior);
  120846. pPrior->pWith = 0;
  120847. }else{
  120848. sqlite3WalkSelect(pWalker, pSel);
  120849. }
  120850. pParse->pWith = pWith;
  120851. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  120852. pEList = pLeft->pEList;
  120853. if( pCte->pCols ){
  120854. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  120855. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  120856. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  120857. );
  120858. pParse->pWith = pSavedWith;
  120859. return SQLITE_ERROR;
  120860. }
  120861. pEList = pCte->pCols;
  120862. }
  120863. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  120864. if( bMayRecursive ){
  120865. if( pSel->selFlags & SF_Recursive ){
  120866. pCte->zCteErr = "multiple recursive references: %s";
  120867. }else{
  120868. pCte->zCteErr = "recursive reference in a subquery: %s";
  120869. }
  120870. sqlite3WalkSelect(pWalker, pSel);
  120871. }
  120872. pCte->zCteErr = 0;
  120873. pParse->pWith = pSavedWith;
  120874. }
  120875. return SQLITE_OK;
  120876. }
  120877. #endif
  120878. #ifndef SQLITE_OMIT_CTE
  120879. /*
  120880. ** If the SELECT passed as the second argument has an associated WITH
  120881. ** clause, pop it from the stack stored as part of the Parse object.
  120882. **
  120883. ** This function is used as the xSelectCallback2() callback by
  120884. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  120885. ** names and other FROM clause elements.
  120886. */
  120887. static void selectPopWith(Walker *pWalker, Select *p){
  120888. Parse *pParse = pWalker->pParse;
  120889. if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
  120890. With *pWith = findRightmost(p)->pWith;
  120891. if( pWith!=0 ){
  120892. assert( pParse->pWith==pWith );
  120893. pParse->pWith = pWith->pOuter;
  120894. }
  120895. }
  120896. }
  120897. #else
  120898. #define selectPopWith 0
  120899. #endif
  120900. /*
  120901. ** The SrcList_item structure passed as the second argument represents a
  120902. ** sub-query in the FROM clause of a SELECT statement. This function
  120903. ** allocates and populates the SrcList_item.pTab object. If successful,
  120904. ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
  120905. ** SQLITE_NOMEM.
  120906. */
  120907. SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){
  120908. Select *pSel = pFrom->pSelect;
  120909. Table *pTab;
  120910. assert( pSel );
  120911. pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
  120912. if( pTab==0 ) return SQLITE_NOMEM;
  120913. pTab->nTabRef = 1;
  120914. if( pFrom->zAlias ){
  120915. pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
  120916. }else{
  120917. pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId);
  120918. }
  120919. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  120920. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  120921. pTab->iPKey = -1;
  120922. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  120923. pTab->tabFlags |= TF_Ephemeral;
  120924. return SQLITE_OK;
  120925. }
  120926. /*
  120927. ** This routine is a Walker callback for "expanding" a SELECT statement.
  120928. ** "Expanding" means to do the following:
  120929. **
  120930. ** (1) Make sure VDBE cursor numbers have been assigned to every
  120931. ** element of the FROM clause.
  120932. **
  120933. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  120934. ** defines FROM clause. When views appear in the FROM clause,
  120935. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  120936. ** that implements the view. A copy is made of the view's SELECT
  120937. ** statement so that we can freely modify or delete that statement
  120938. ** without worrying about messing up the persistent representation
  120939. ** of the view.
  120940. **
  120941. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  120942. ** on joins and the ON and USING clause of joins.
  120943. **
  120944. ** (4) Scan the list of columns in the result set (pEList) looking
  120945. ** for instances of the "*" operator or the TABLE.* operator.
  120946. ** If found, expand each "*" to be every column in every table
  120947. ** and TABLE.* to be every column in TABLE.
  120948. **
  120949. */
  120950. static int selectExpander(Walker *pWalker, Select *p){
  120951. Parse *pParse = pWalker->pParse;
  120952. int i, j, k;
  120953. SrcList *pTabList;
  120954. ExprList *pEList;
  120955. struct SrcList_item *pFrom;
  120956. sqlite3 *db = pParse->db;
  120957. Expr *pE, *pRight, *pExpr;
  120958. u16 selFlags = p->selFlags;
  120959. u32 elistFlags = 0;
  120960. p->selFlags |= SF_Expanded;
  120961. if( db->mallocFailed ){
  120962. return WRC_Abort;
  120963. }
  120964. assert( p->pSrc!=0 );
  120965. if( (selFlags & SF_Expanded)!=0 ){
  120966. return WRC_Prune;
  120967. }
  120968. pTabList = p->pSrc;
  120969. pEList = p->pEList;
  120970. sqlite3WithPush(pParse, p->pWith, 0);
  120971. /* Make sure cursor numbers have been assigned to all entries in
  120972. ** the FROM clause of the SELECT statement.
  120973. */
  120974. sqlite3SrcListAssignCursors(pParse, pTabList);
  120975. /* Look up every table named in the FROM clause of the select. If
  120976. ** an entry of the FROM clause is a subquery instead of a table or view,
  120977. ** then create a transient table structure to describe the subquery.
  120978. */
  120979. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  120980. Table *pTab;
  120981. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  120982. if( pFrom->fg.isRecursive ) continue;
  120983. assert( pFrom->pTab==0 );
  120984. #ifndef SQLITE_OMIT_CTE
  120985. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  120986. if( pFrom->pTab ) {} else
  120987. #endif
  120988. if( pFrom->zName==0 ){
  120989. #ifndef SQLITE_OMIT_SUBQUERY
  120990. Select *pSel = pFrom->pSelect;
  120991. /* A sub-query in the FROM clause of a SELECT */
  120992. assert( pSel!=0 );
  120993. assert( pFrom->pTab==0 );
  120994. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  120995. if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
  120996. #endif
  120997. }else{
  120998. /* An ordinary table or view name in the FROM clause */
  120999. assert( pFrom->pTab==0 );
  121000. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  121001. if( pTab==0 ) return WRC_Abort;
  121002. if( pTab->nTabRef>=0xffff ){
  121003. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  121004. pTab->zName);
  121005. pFrom->pTab = 0;
  121006. return WRC_Abort;
  121007. }
  121008. pTab->nTabRef++;
  121009. if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
  121010. return WRC_Abort;
  121011. }
  121012. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  121013. if( IsVirtual(pTab) || pTab->pSelect ){
  121014. i16 nCol;
  121015. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  121016. assert( pFrom->pSelect==0 );
  121017. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  121018. nCol = pTab->nCol;
  121019. pTab->nCol = -1;
  121020. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  121021. pTab->nCol = nCol;
  121022. }
  121023. #endif
  121024. }
  121025. /* Locate the index named by the INDEXED BY clause, if any. */
  121026. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  121027. return WRC_Abort;
  121028. }
  121029. }
  121030. /* Process NATURAL keywords, and ON and USING clauses of joins.
  121031. */
  121032. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  121033. return WRC_Abort;
  121034. }
  121035. /* For every "*" that occurs in the column list, insert the names of
  121036. ** all columns in all tables. And for every TABLE.* insert the names
  121037. ** of all columns in TABLE. The parser inserted a special expression
  121038. ** with the TK_ASTERISK operator for each "*" that it found in the column
  121039. ** list. The following code just has to locate the TK_ASTERISK
  121040. ** expressions and expand each one to the list of all columns in
  121041. ** all tables.
  121042. **
  121043. ** The first loop just checks to see if there are any "*" operators
  121044. ** that need expanding.
  121045. */
  121046. for(k=0; k<pEList->nExpr; k++){
  121047. pE = pEList->a[k].pExpr;
  121048. if( pE->op==TK_ASTERISK ) break;
  121049. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  121050. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  121051. if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
  121052. elistFlags |= pE->flags;
  121053. }
  121054. if( k<pEList->nExpr ){
  121055. /*
  121056. ** If we get here it means the result set contains one or more "*"
  121057. ** operators that need to be expanded. Loop through each expression
  121058. ** in the result set and expand them one by one.
  121059. */
  121060. struct ExprList_item *a = pEList->a;
  121061. ExprList *pNew = 0;
  121062. int flags = pParse->db->flags;
  121063. int longNames = (flags & SQLITE_FullColNames)!=0
  121064. && (flags & SQLITE_ShortColNames)==0;
  121065. for(k=0; k<pEList->nExpr; k++){
  121066. pE = a[k].pExpr;
  121067. elistFlags |= pE->flags;
  121068. pRight = pE->pRight;
  121069. assert( pE->op!=TK_DOT || pRight!=0 );
  121070. if( pE->op!=TK_ASTERISK
  121071. && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
  121072. ){
  121073. /* This particular expression does not need to be expanded.
  121074. */
  121075. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  121076. if( pNew ){
  121077. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  121078. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  121079. a[k].zName = 0;
  121080. a[k].zSpan = 0;
  121081. }
  121082. a[k].pExpr = 0;
  121083. }else{
  121084. /* This expression is a "*" or a "TABLE.*" and needs to be
  121085. ** expanded. */
  121086. int tableSeen = 0; /* Set to 1 when TABLE matches */
  121087. char *zTName = 0; /* text of name of TABLE */
  121088. if( pE->op==TK_DOT ){
  121089. assert( pE->pLeft!=0 );
  121090. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  121091. zTName = pE->pLeft->u.zToken;
  121092. }
  121093. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  121094. Table *pTab = pFrom->pTab;
  121095. Select *pSub = pFrom->pSelect;
  121096. char *zTabName = pFrom->zAlias;
  121097. const char *zSchemaName = 0;
  121098. int iDb;
  121099. if( zTabName==0 ){
  121100. zTabName = pTab->zName;
  121101. }
  121102. if( db->mallocFailed ) break;
  121103. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  121104. pSub = 0;
  121105. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  121106. continue;
  121107. }
  121108. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  121109. zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
  121110. }
  121111. for(j=0; j<pTab->nCol; j++){
  121112. char *zName = pTab->aCol[j].zName;
  121113. char *zColname; /* The computed column name */
  121114. char *zToFree; /* Malloced string that needs to be freed */
  121115. Token sColname; /* Computed column name as a token */
  121116. assert( zName );
  121117. if( zTName && pSub
  121118. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  121119. ){
  121120. continue;
  121121. }
  121122. /* If a column is marked as 'hidden', omit it from the expanded
  121123. ** result-set list unless the SELECT has the SF_IncludeHidden
  121124. ** bit set.
  121125. */
  121126. if( (p->selFlags & SF_IncludeHidden)==0
  121127. && IsHiddenColumn(&pTab->aCol[j])
  121128. ){
  121129. continue;
  121130. }
  121131. tableSeen = 1;
  121132. if( i>0 && zTName==0 ){
  121133. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  121134. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  121135. ){
  121136. /* In a NATURAL join, omit the join columns from the
  121137. ** table to the right of the join */
  121138. continue;
  121139. }
  121140. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  121141. /* In a join with a USING clause, omit columns in the
  121142. ** using clause from the table on the right. */
  121143. continue;
  121144. }
  121145. }
  121146. pRight = sqlite3Expr(db, TK_ID, zName);
  121147. zColname = zName;
  121148. zToFree = 0;
  121149. if( longNames || pTabList->nSrc>1 ){
  121150. Expr *pLeft;
  121151. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  121152. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  121153. if( zSchemaName ){
  121154. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  121155. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
  121156. }
  121157. if( longNames ){
  121158. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  121159. zToFree = zColname;
  121160. }
  121161. }else{
  121162. pExpr = pRight;
  121163. }
  121164. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  121165. sqlite3TokenInit(&sColname, zColname);
  121166. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  121167. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  121168. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  121169. if( pSub ){
  121170. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  121171. testcase( pX->zSpan==0 );
  121172. }else{
  121173. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  121174. zSchemaName, zTabName, zColname);
  121175. testcase( pX->zSpan==0 );
  121176. }
  121177. pX->bSpanIsTab = 1;
  121178. }
  121179. sqlite3DbFree(db, zToFree);
  121180. }
  121181. }
  121182. if( !tableSeen ){
  121183. if( zTName ){
  121184. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  121185. }else{
  121186. sqlite3ErrorMsg(pParse, "no tables specified");
  121187. }
  121188. }
  121189. }
  121190. }
  121191. sqlite3ExprListDelete(db, pEList);
  121192. p->pEList = pNew;
  121193. }
  121194. if( p->pEList ){
  121195. if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  121196. sqlite3ErrorMsg(pParse, "too many columns in result set");
  121197. return WRC_Abort;
  121198. }
  121199. if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
  121200. p->selFlags |= SF_ComplexResult;
  121201. }
  121202. }
  121203. return WRC_Continue;
  121204. }
  121205. /*
  121206. ** No-op routine for the parse-tree walker.
  121207. **
  121208. ** When this routine is the Walker.xExprCallback then expression trees
  121209. ** are walked without any actions being taken at each node. Presumably,
  121210. ** when this routine is used for Walker.xExprCallback then
  121211. ** Walker.xSelectCallback is set to do something useful for every
  121212. ** subquery in the parser tree.
  121213. */
  121214. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  121215. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  121216. return WRC_Continue;
  121217. }
  121218. /*
  121219. ** No-op routine for the parse-tree walker for SELECT statements.
  121220. ** subquery in the parser tree.
  121221. */
  121222. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
  121223. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  121224. return WRC_Continue;
  121225. }
  121226. #if SQLITE_DEBUG
  121227. /*
  121228. ** Always assert. This xSelectCallback2 implementation proves that the
  121229. ** xSelectCallback2 is never invoked.
  121230. */
  121231. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
  121232. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  121233. assert( 0 );
  121234. }
  121235. #endif
  121236. /*
  121237. ** This routine "expands" a SELECT statement and all of its subqueries.
  121238. ** For additional information on what it means to "expand" a SELECT
  121239. ** statement, see the comment on the selectExpand worker callback above.
  121240. **
  121241. ** Expanding a SELECT statement is the first step in processing a
  121242. ** SELECT statement. The SELECT statement must be expanded before
  121243. ** name resolution is performed.
  121244. **
  121245. ** If anything goes wrong, an error message is written into pParse.
  121246. ** The calling function can detect the problem by looking at pParse->nErr
  121247. ** and/or pParse->db->mallocFailed.
  121248. */
  121249. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  121250. Walker w;
  121251. w.xExprCallback = sqlite3ExprWalkNoop;
  121252. w.pParse = pParse;
  121253. if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
  121254. w.xSelectCallback = convertCompoundSelectToSubquery;
  121255. w.xSelectCallback2 = 0;
  121256. sqlite3WalkSelect(&w, pSelect);
  121257. }
  121258. w.xSelectCallback = selectExpander;
  121259. w.xSelectCallback2 = selectPopWith;
  121260. sqlite3WalkSelect(&w, pSelect);
  121261. }
  121262. #ifndef SQLITE_OMIT_SUBQUERY
  121263. /*
  121264. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  121265. ** interface.
  121266. **
  121267. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  121268. ** information to the Table structure that represents the result set
  121269. ** of that subquery.
  121270. **
  121271. ** The Table structure that represents the result set was constructed
  121272. ** by selectExpander() but the type and collation information was omitted
  121273. ** at that point because identifiers had not yet been resolved. This
  121274. ** routine is called after identifier resolution.
  121275. */
  121276. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  121277. Parse *pParse;
  121278. int i;
  121279. SrcList *pTabList;
  121280. struct SrcList_item *pFrom;
  121281. assert( p->selFlags & SF_Resolved );
  121282. if( p->selFlags & SF_HasTypeInfo ) return;
  121283. p->selFlags |= SF_HasTypeInfo;
  121284. pParse = pWalker->pParse;
  121285. pTabList = p->pSrc;
  121286. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  121287. Table *pTab = pFrom->pTab;
  121288. assert( pTab!=0 );
  121289. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  121290. /* A sub-query in the FROM clause of a SELECT */
  121291. Select *pSel = pFrom->pSelect;
  121292. if( pSel ){
  121293. while( pSel->pPrior ) pSel = pSel->pPrior;
  121294. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
  121295. }
  121296. }
  121297. }
  121298. }
  121299. #endif
  121300. /*
  121301. ** This routine adds datatype and collating sequence information to
  121302. ** the Table structures of all FROM-clause subqueries in a
  121303. ** SELECT statement.
  121304. **
  121305. ** Use this routine after name resolution.
  121306. */
  121307. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  121308. #ifndef SQLITE_OMIT_SUBQUERY
  121309. Walker w;
  121310. w.xSelectCallback = sqlite3SelectWalkNoop;
  121311. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  121312. w.xExprCallback = sqlite3ExprWalkNoop;
  121313. w.pParse = pParse;
  121314. sqlite3WalkSelect(&w, pSelect);
  121315. #endif
  121316. }
  121317. /*
  121318. ** This routine sets up a SELECT statement for processing. The
  121319. ** following is accomplished:
  121320. **
  121321. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  121322. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  121323. ** * ON and USING clauses are shifted into WHERE statements
  121324. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  121325. ** * Identifiers in expression are matched to tables.
  121326. **
  121327. ** This routine acts recursively on all subqueries within the SELECT.
  121328. */
  121329. SQLITE_PRIVATE void sqlite3SelectPrep(
  121330. Parse *pParse, /* The parser context */
  121331. Select *p, /* The SELECT statement being coded. */
  121332. NameContext *pOuterNC /* Name context for container */
  121333. ){
  121334. assert( p!=0 || pParse->db->mallocFailed );
  121335. if( pParse->db->mallocFailed ) return;
  121336. if( p->selFlags & SF_HasTypeInfo ) return;
  121337. sqlite3SelectExpand(pParse, p);
  121338. if( pParse->nErr || pParse->db->mallocFailed ) return;
  121339. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  121340. if( pParse->nErr || pParse->db->mallocFailed ) return;
  121341. sqlite3SelectAddTypeInfo(pParse, p);
  121342. }
  121343. /*
  121344. ** Reset the aggregate accumulator.
  121345. **
  121346. ** The aggregate accumulator is a set of memory cells that hold
  121347. ** intermediate results while calculating an aggregate. This
  121348. ** routine generates code that stores NULLs in all of those memory
  121349. ** cells.
  121350. */
  121351. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  121352. Vdbe *v = pParse->pVdbe;
  121353. int i;
  121354. struct AggInfo_func *pFunc;
  121355. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  121356. if( nReg==0 ) return;
  121357. #ifdef SQLITE_DEBUG
  121358. /* Verify that all AggInfo registers are within the range specified by
  121359. ** AggInfo.mnReg..AggInfo.mxReg */
  121360. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  121361. for(i=0; i<pAggInfo->nColumn; i++){
  121362. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  121363. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  121364. }
  121365. for(i=0; i<pAggInfo->nFunc; i++){
  121366. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  121367. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  121368. }
  121369. #endif
  121370. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  121371. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  121372. if( pFunc->iDistinct>=0 ){
  121373. Expr *pE = pFunc->pExpr;
  121374. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  121375. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  121376. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  121377. "argument");
  121378. pFunc->iDistinct = -1;
  121379. }else{
  121380. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
  121381. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  121382. (char*)pKeyInfo, P4_KEYINFO);
  121383. }
  121384. }
  121385. }
  121386. }
  121387. /*
  121388. ** Invoke the OP_AggFinalize opcode for every aggregate function
  121389. ** in the AggInfo structure.
  121390. */
  121391. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  121392. Vdbe *v = pParse->pVdbe;
  121393. int i;
  121394. struct AggInfo_func *pF;
  121395. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  121396. ExprList *pList = pF->pExpr->x.pList;
  121397. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  121398. sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
  121399. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  121400. }
  121401. }
  121402. /*
  121403. ** Update the accumulator memory cells for an aggregate based on
  121404. ** the current cursor position.
  121405. **
  121406. ** If regAcc is non-zero and there are no min() or max() aggregates
  121407. ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
  121408. ** registers i register regAcc contains 0. The caller will take care
  121409. ** of setting and clearing regAcc.
  121410. */
  121411. static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
  121412. Vdbe *v = pParse->pVdbe;
  121413. int i;
  121414. int regHit = 0;
  121415. int addrHitTest = 0;
  121416. struct AggInfo_func *pF;
  121417. struct AggInfo_col *pC;
  121418. pAggInfo->directMode = 1;
  121419. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  121420. int nArg;
  121421. int addrNext = 0;
  121422. int regAgg;
  121423. ExprList *pList = pF->pExpr->x.pList;
  121424. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  121425. if( pList ){
  121426. nArg = pList->nExpr;
  121427. regAgg = sqlite3GetTempRange(pParse, nArg);
  121428. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  121429. }else{
  121430. nArg = 0;
  121431. regAgg = 0;
  121432. }
  121433. if( pF->iDistinct>=0 ){
  121434. addrNext = sqlite3VdbeMakeLabel(v);
  121435. testcase( nArg==0 ); /* Error condition */
  121436. testcase( nArg>1 ); /* Also an error */
  121437. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  121438. }
  121439. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  121440. CollSeq *pColl = 0;
  121441. struct ExprList_item *pItem;
  121442. int j;
  121443. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  121444. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  121445. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  121446. }
  121447. if( !pColl ){
  121448. pColl = pParse->db->pDfltColl;
  121449. }
  121450. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  121451. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  121452. }
  121453. sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
  121454. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  121455. sqlite3VdbeChangeP5(v, (u8)nArg);
  121456. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  121457. if( addrNext ){
  121458. sqlite3VdbeResolveLabel(v, addrNext);
  121459. }
  121460. }
  121461. if( regHit==0 && pAggInfo->nAccumulator ){
  121462. regHit = regAcc;
  121463. }
  121464. if( regHit ){
  121465. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  121466. }
  121467. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  121468. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  121469. }
  121470. pAggInfo->directMode = 0;
  121471. if( addrHitTest ){
  121472. sqlite3VdbeJumpHere(v, addrHitTest);
  121473. }
  121474. }
  121475. /*
  121476. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  121477. ** count(*) query ("SELECT count(*) FROM pTab").
  121478. */
  121479. #ifndef SQLITE_OMIT_EXPLAIN
  121480. static void explainSimpleCount(
  121481. Parse *pParse, /* Parse context */
  121482. Table *pTab, /* Table being queried */
  121483. Index *pIdx /* Index used to optimize scan, or NULL */
  121484. ){
  121485. if( pParse->explain==2 ){
  121486. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  121487. sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
  121488. pTab->zName,
  121489. bCover ? " USING COVERING INDEX " : "",
  121490. bCover ? pIdx->zName : ""
  121491. );
  121492. }
  121493. }
  121494. #else
  121495. # define explainSimpleCount(a,b,c)
  121496. #endif
  121497. /*
  121498. ** sqlite3WalkExpr() callback used by havingToWhere().
  121499. **
  121500. ** If the node passed to the callback is a TK_AND node, return
  121501. ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
  121502. **
  121503. ** Otherwise, return WRC_Prune. In this case, also check if the
  121504. ** sub-expression matches the criteria for being moved to the WHERE
  121505. ** clause. If so, add it to the WHERE clause and replace the sub-expression
  121506. ** within the HAVING expression with a constant "1".
  121507. */
  121508. static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
  121509. if( pExpr->op!=TK_AND ){
  121510. Select *pS = pWalker->u.pSelect;
  121511. if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
  121512. sqlite3 *db = pWalker->pParse->db;
  121513. Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
  121514. if( pNew ){
  121515. Expr *pWhere = pS->pWhere;
  121516. SWAP(Expr, *pNew, *pExpr);
  121517. pNew = sqlite3ExprAnd(db, pWhere, pNew);
  121518. pS->pWhere = pNew;
  121519. pWalker->eCode = 1;
  121520. }
  121521. }
  121522. return WRC_Prune;
  121523. }
  121524. return WRC_Continue;
  121525. }
  121526. /*
  121527. ** Transfer eligible terms from the HAVING clause of a query, which is
  121528. ** processed after grouping, to the WHERE clause, which is processed before
  121529. ** grouping. For example, the query:
  121530. **
  121531. ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
  121532. **
  121533. ** can be rewritten as:
  121534. **
  121535. ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
  121536. **
  121537. ** A term of the HAVING expression is eligible for transfer if it consists
  121538. ** entirely of constants and expressions that are also GROUP BY terms that
  121539. ** use the "BINARY" collation sequence.
  121540. */
  121541. static void havingToWhere(Parse *pParse, Select *p){
  121542. Walker sWalker;
  121543. memset(&sWalker, 0, sizeof(sWalker));
  121544. sWalker.pParse = pParse;
  121545. sWalker.xExprCallback = havingToWhereExprCb;
  121546. sWalker.u.pSelect = p;
  121547. sqlite3WalkExpr(&sWalker, p->pHaving);
  121548. #if SELECTTRACE_ENABLED
  121549. if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){
  121550. SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
  121551. sqlite3TreeViewSelect(0, p, 0);
  121552. }
  121553. #endif
  121554. }
  121555. /*
  121556. ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
  121557. ** If it is, then return the SrcList_item for the prior view. If it is not,
  121558. ** then return 0.
  121559. */
  121560. static struct SrcList_item *isSelfJoinView(
  121561. SrcList *pTabList, /* Search for self-joins in this FROM clause */
  121562. struct SrcList_item *pThis /* Search for prior reference to this subquery */
  121563. ){
  121564. struct SrcList_item *pItem;
  121565. for(pItem = pTabList->a; pItem<pThis; pItem++){
  121566. if( pItem->pSelect==0 ) continue;
  121567. if( pItem->fg.viaCoroutine ) continue;
  121568. if( pItem->zName==0 ) continue;
  121569. if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
  121570. if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
  121571. if( sqlite3ExprCompare(0,
  121572. pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1)
  121573. ){
  121574. /* The view was modified by some other optimization such as
  121575. ** pushDownWhereTerms() */
  121576. continue;
  121577. }
  121578. return pItem;
  121579. }
  121580. return 0;
  121581. }
  121582. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  121583. /*
  121584. ** Attempt to transform a query of the form
  121585. **
  121586. ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
  121587. **
  121588. ** Into this:
  121589. **
  121590. ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
  121591. **
  121592. ** The transformation only works if all of the following are true:
  121593. **
  121594. ** * The subquery is a UNION ALL of two or more terms
  121595. ** * The subquery does not have a LIMIT clause
  121596. ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
  121597. ** * The outer query is a simple count(*)
  121598. **
  121599. ** Return TRUE if the optimization is undertaken.
  121600. */
  121601. static int countOfViewOptimization(Parse *pParse, Select *p){
  121602. Select *pSub, *pPrior;
  121603. Expr *pExpr;
  121604. Expr *pCount;
  121605. sqlite3 *db;
  121606. if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
  121607. if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
  121608. pExpr = p->pEList->a[0].pExpr;
  121609. if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
  121610. if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
  121611. if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
  121612. if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
  121613. pSub = p->pSrc->a[0].pSelect;
  121614. if( pSub==0 ) return 0; /* The FROM is a subquery */
  121615. if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
  121616. do{
  121617. if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
  121618. if( pSub->pWhere ) return 0; /* No WHERE clause */
  121619. if( pSub->pLimit ) return 0; /* No LIMIT clause */
  121620. if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
  121621. pSub = pSub->pPrior; /* Repeat over compound */
  121622. }while( pSub );
  121623. /* If we reach this point then it is OK to perform the transformation */
  121624. db = pParse->db;
  121625. pCount = pExpr;
  121626. pExpr = 0;
  121627. pSub = p->pSrc->a[0].pSelect;
  121628. p->pSrc->a[0].pSelect = 0;
  121629. sqlite3SrcListDelete(db, p->pSrc);
  121630. p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
  121631. while( pSub ){
  121632. Expr *pTerm;
  121633. pPrior = pSub->pPrior;
  121634. pSub->pPrior = 0;
  121635. pSub->pNext = 0;
  121636. pSub->selFlags |= SF_Aggregate;
  121637. pSub->selFlags &= ~SF_Compound;
  121638. pSub->nSelectRow = 0;
  121639. sqlite3ExprListDelete(db, pSub->pEList);
  121640. pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
  121641. pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
  121642. pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  121643. sqlite3PExprAddSelect(pParse, pTerm, pSub);
  121644. if( pExpr==0 ){
  121645. pExpr = pTerm;
  121646. }else{
  121647. pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
  121648. }
  121649. pSub = pPrior;
  121650. }
  121651. p->pEList->a[0].pExpr = pExpr;
  121652. p->selFlags &= ~SF_Aggregate;
  121653. #if SELECTTRACE_ENABLED
  121654. if( sqlite3SelectTrace & 0x400 ){
  121655. SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
  121656. sqlite3TreeViewSelect(0, p, 0);
  121657. }
  121658. #endif
  121659. return 1;
  121660. }
  121661. #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
  121662. /*
  121663. ** Generate code for the SELECT statement given in the p argument.
  121664. **
  121665. ** The results are returned according to the SelectDest structure.
  121666. ** See comments in sqliteInt.h for further information.
  121667. **
  121668. ** This routine returns the number of errors. If any errors are
  121669. ** encountered, then an appropriate error message is left in
  121670. ** pParse->zErrMsg.
  121671. **
  121672. ** This routine does NOT free the Select structure passed in. The
  121673. ** calling function needs to do that.
  121674. */
  121675. SQLITE_PRIVATE int sqlite3Select(
  121676. Parse *pParse, /* The parser context */
  121677. Select *p, /* The SELECT statement being coded. */
  121678. SelectDest *pDest /* What to do with the query results */
  121679. ){
  121680. int i, j; /* Loop counters */
  121681. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  121682. Vdbe *v; /* The virtual machine under construction */
  121683. int isAgg; /* True for select lists like "count(*)" */
  121684. ExprList *pEList = 0; /* List of columns to extract. */
  121685. SrcList *pTabList; /* List of tables to select from */
  121686. Expr *pWhere; /* The WHERE clause. May be NULL */
  121687. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  121688. Expr *pHaving; /* The HAVING clause. May be NULL */
  121689. int rc = 1; /* Value to return from this function */
  121690. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  121691. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  121692. AggInfo sAggInfo; /* Information used by aggregate queries */
  121693. int iEnd; /* Address of the end of the query */
  121694. sqlite3 *db; /* The database connection */
  121695. ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
  121696. u8 minMaxFlag; /* Flag for min/max queries */
  121697. db = pParse->db;
  121698. v = sqlite3GetVdbe(pParse);
  121699. if( p==0 || db->mallocFailed || pParse->nErr ){
  121700. return 1;
  121701. }
  121702. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  121703. memset(&sAggInfo, 0, sizeof(sAggInfo));
  121704. #if SELECTTRACE_ENABLED
  121705. SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
  121706. if( sqlite3SelectTrace & 0x100 ){
  121707. sqlite3TreeViewSelect(0, p, 0);
  121708. }
  121709. #endif
  121710. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  121711. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  121712. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  121713. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  121714. if( IgnorableOrderby(pDest) ){
  121715. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  121716. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  121717. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  121718. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  121719. /* If ORDER BY makes no difference in the output then neither does
  121720. ** DISTINCT so it can be removed too. */
  121721. sqlite3ExprListDelete(db, p->pOrderBy);
  121722. p->pOrderBy = 0;
  121723. p->selFlags &= ~SF_Distinct;
  121724. }
  121725. sqlite3SelectPrep(pParse, p, 0);
  121726. if( pParse->nErr || db->mallocFailed ){
  121727. goto select_end;
  121728. }
  121729. assert( p->pEList!=0 );
  121730. #if SELECTTRACE_ENABLED
  121731. if( sqlite3SelectTrace & 0x104 ){
  121732. SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
  121733. sqlite3TreeViewSelect(0, p, 0);
  121734. }
  121735. #endif
  121736. if( pDest->eDest==SRT_Output ){
  121737. generateColumnNames(pParse, p);
  121738. }
  121739. #ifndef SQLITE_OMIT_WINDOWFUNC
  121740. if( sqlite3WindowRewrite(pParse, p) ){
  121741. goto select_end;
  121742. }
  121743. #if SELECTTRACE_ENABLED
  121744. if( sqlite3SelectTrace & 0x108 ){
  121745. SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
  121746. sqlite3TreeViewSelect(0, p, 0);
  121747. }
  121748. #endif
  121749. #endif /* SQLITE_OMIT_WINDOWFUNC */
  121750. pTabList = p->pSrc;
  121751. isAgg = (p->selFlags & SF_Aggregate)!=0;
  121752. memset(&sSort, 0, sizeof(sSort));
  121753. sSort.pOrderBy = p->pOrderBy;
  121754. /* Try to various optimizations (flattening subqueries, and strength
  121755. ** reduction of join operators) in the FROM clause up into the main query
  121756. */
  121757. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  121758. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  121759. struct SrcList_item *pItem = &pTabList->a[i];
  121760. Select *pSub = pItem->pSelect;
  121761. Table *pTab = pItem->pTab;
  121762. /* Convert LEFT JOIN into JOIN if there are terms of the right table
  121763. ** of the LEFT JOIN used in the WHERE clause.
  121764. */
  121765. if( (pItem->fg.jointype & JT_LEFT)!=0
  121766. && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
  121767. && OptimizationEnabled(db, SQLITE_SimplifyJoin)
  121768. ){
  121769. SELECTTRACE(0x100,pParse,p,
  121770. ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
  121771. pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
  121772. unsetJoinExpr(p->pWhere, pItem->iCursor);
  121773. }
  121774. /* No futher action if this term of the FROM clause is no a subquery */
  121775. if( pSub==0 ) continue;
  121776. /* Catch mismatch in the declared columns of a view and the number of
  121777. ** columns in the SELECT on the RHS */
  121778. if( pTab->nCol!=pSub->pEList->nExpr ){
  121779. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  121780. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  121781. goto select_end;
  121782. }
  121783. /* Do not try to flatten an aggregate subquery.
  121784. **
  121785. ** Flattening an aggregate subquery is only possible if the outer query
  121786. ** is not a join. But if the outer query is not a join, then the subquery
  121787. ** will be implemented as a co-routine and there is no advantage to
  121788. ** flattening in that case.
  121789. */
  121790. if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
  121791. assert( pSub->pGroupBy==0 );
  121792. /* If the outer query contains a "complex" result set (that is,
  121793. ** if the result set of the outer query uses functions or subqueries)
  121794. ** and if the subquery contains an ORDER BY clause and if
  121795. ** it will be implemented as a co-routine, then do not flatten. This
  121796. ** restriction allows SQL constructs like this:
  121797. **
  121798. ** SELECT expensive_function(x)
  121799. ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  121800. **
  121801. ** The expensive_function() is only computed on the 10 rows that
  121802. ** are output, rather than every row of the table.
  121803. **
  121804. ** The requirement that the outer query have a complex result set
  121805. ** means that flattening does occur on simpler SQL constraints without
  121806. ** the expensive_function() like:
  121807. **
  121808. ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  121809. */
  121810. if( pSub->pOrderBy!=0
  121811. && i==0
  121812. && (p->selFlags & SF_ComplexResult)!=0
  121813. && (pTabList->nSrc==1
  121814. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
  121815. ){
  121816. continue;
  121817. }
  121818. if( flattenSubquery(pParse, p, i, isAgg) ){
  121819. /* This subquery can be absorbed into its parent. */
  121820. i = -1;
  121821. }
  121822. pTabList = p->pSrc;
  121823. if( db->mallocFailed ) goto select_end;
  121824. if( !IgnorableOrderby(pDest) ){
  121825. sSort.pOrderBy = p->pOrderBy;
  121826. }
  121827. }
  121828. #endif
  121829. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  121830. /* Handle compound SELECT statements using the separate multiSelect()
  121831. ** procedure.
  121832. */
  121833. if( p->pPrior ){
  121834. rc = multiSelect(pParse, p, pDest);
  121835. #if SELECTTRACE_ENABLED
  121836. SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
  121837. if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
  121838. sqlite3TreeViewSelect(0, p, 0);
  121839. }
  121840. #endif
  121841. if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
  121842. return rc;
  121843. }
  121844. #endif
  121845. /* Do the WHERE-clause constant propagation optimization if this is
  121846. ** a join. No need to speed time on this operation for non-join queries
  121847. ** as the equivalent optimization will be handled by query planner in
  121848. ** sqlite3WhereBegin().
  121849. */
  121850. if( pTabList->nSrc>1
  121851. && OptimizationEnabled(db, SQLITE_PropagateConst)
  121852. && propagateConstants(pParse, p)
  121853. ){
  121854. #if SELECTTRACE_ENABLED
  121855. if( sqlite3SelectTrace & 0x100 ){
  121856. SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
  121857. sqlite3TreeViewSelect(0, p, 0);
  121858. }
  121859. #endif
  121860. }else{
  121861. SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n"));
  121862. }
  121863. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  121864. if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
  121865. && countOfViewOptimization(pParse, p)
  121866. ){
  121867. if( db->mallocFailed ) goto select_end;
  121868. pEList = p->pEList;
  121869. pTabList = p->pSrc;
  121870. }
  121871. #endif
  121872. /* For each term in the FROM clause, do two things:
  121873. ** (1) Authorized unreferenced tables
  121874. ** (2) Generate code for all sub-queries
  121875. */
  121876. for(i=0; i<pTabList->nSrc; i++){
  121877. struct SrcList_item *pItem = &pTabList->a[i];
  121878. SelectDest dest;
  121879. Select *pSub;
  121880. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  121881. const char *zSavedAuthContext;
  121882. #endif
  121883. /* Issue SQLITE_READ authorizations with a fake column name for any
  121884. ** tables that are referenced but from which no values are extracted.
  121885. ** Examples of where these kinds of null SQLITE_READ authorizations
  121886. ** would occur:
  121887. **
  121888. ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
  121889. ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
  121890. **
  121891. ** The fake column name is an empty string. It is possible for a table to
  121892. ** have a column named by the empty string, in which case there is no way to
  121893. ** distinguish between an unreferenced table and an actual reference to the
  121894. ** "" column. The original design was for the fake column name to be a NULL,
  121895. ** which would be unambiguous. But legacy authorization callbacks might
  121896. ** assume the column name is non-NULL and segfault. The use of an empty
  121897. ** string for the fake column name seems safer.
  121898. */
  121899. if( pItem->colUsed==0 ){
  121900. sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
  121901. }
  121902. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  121903. /* Generate code for all sub-queries in the FROM clause
  121904. */
  121905. pSub = pItem->pSelect;
  121906. if( pSub==0 ) continue;
  121907. /* Sometimes the code for a subquery will be generated more than
  121908. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  121909. ** for example. In that case, do not regenerate the code to manifest
  121910. ** a view or the co-routine to implement a view. The first instance
  121911. ** is sufficient, though the subroutine to manifest the view does need
  121912. ** to be invoked again. */
  121913. if( pItem->addrFillSub ){
  121914. if( pItem->fg.viaCoroutine==0 ){
  121915. /* The subroutine that manifests the view might be a one-time routine,
  121916. ** or it might need to be rerun on each iteration because it
  121917. ** encodes a correlated subquery. */
  121918. testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once );
  121919. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  121920. }
  121921. continue;
  121922. }
  121923. /* Increment Parse.nHeight by the height of the largest expression
  121924. ** tree referred to by this, the parent select. The child select
  121925. ** may contain expression trees of at most
  121926. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  121927. ** more conservative than necessary, but much easier than enforcing
  121928. ** an exact limit.
  121929. */
  121930. pParse->nHeight += sqlite3SelectExprHeight(p);
  121931. /* Make copies of constant WHERE-clause terms in the outer query down
  121932. ** inside the subquery. This can help the subquery to run more efficiently.
  121933. */
  121934. if( OptimizationEnabled(db, SQLITE_PushDown)
  121935. && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
  121936. (pItem->fg.jointype & JT_OUTER)!=0)
  121937. ){
  121938. #if SELECTTRACE_ENABLED
  121939. if( sqlite3SelectTrace & 0x100 ){
  121940. SELECTTRACE(0x100,pParse,p,
  121941. ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
  121942. sqlite3TreeViewSelect(0, p, 0);
  121943. }
  121944. #endif
  121945. }else{
  121946. SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
  121947. }
  121948. zSavedAuthContext = pParse->zAuthContext;
  121949. pParse->zAuthContext = pItem->zName;
  121950. /* Generate code to implement the subquery
  121951. **
  121952. ** The subquery is implemented as a co-routine if the subquery is
  121953. ** guaranteed to be the outer loop (so that it does not need to be
  121954. ** computed more than once)
  121955. **
  121956. ** TODO: Are there other reasons beside (1) to use a co-routine
  121957. ** implementation?
  121958. */
  121959. if( i==0
  121960. && (pTabList->nSrc==1
  121961. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
  121962. ){
  121963. /* Implement a co-routine that will return a single row of the result
  121964. ** set on each invocation.
  121965. */
  121966. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  121967. pItem->regReturn = ++pParse->nMem;
  121968. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  121969. VdbeComment((v, "%s", pItem->pTab->zName));
  121970. pItem->addrFillSub = addrTop;
  121971. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  121972. ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId));
  121973. sqlite3Select(pParse, pSub, &dest);
  121974. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  121975. pItem->fg.viaCoroutine = 1;
  121976. pItem->regResult = dest.iSdst;
  121977. sqlite3VdbeEndCoroutine(v, pItem->regReturn);
  121978. sqlite3VdbeJumpHere(v, addrTop-1);
  121979. sqlite3ClearTempRegCache(pParse);
  121980. }else{
  121981. /* Generate a subroutine that will fill an ephemeral table with
  121982. ** the content of this subquery. pItem->addrFillSub will point
  121983. ** to the address of the generated subroutine. pItem->regReturn
  121984. ** is a register allocated to hold the subroutine return address
  121985. */
  121986. int topAddr;
  121987. int onceAddr = 0;
  121988. int retAddr;
  121989. struct SrcList_item *pPrior;
  121990. assert( pItem->addrFillSub==0 );
  121991. pItem->regReturn = ++pParse->nMem;
  121992. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  121993. pItem->addrFillSub = topAddr+1;
  121994. if( pItem->fg.isCorrelated==0 ){
  121995. /* If the subquery is not correlated and if we are not inside of
  121996. ** a trigger, then we only need to compute the value of the subquery
  121997. ** once. */
  121998. onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  121999. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  122000. }else{
  122001. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  122002. }
  122003. pPrior = isSelfJoinView(pTabList, pItem);
  122004. if( pPrior ){
  122005. sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
  122006. assert( pPrior->pSelect!=0 );
  122007. pSub->nSelectRow = pPrior->pSelect->nSelectRow;
  122008. }else{
  122009. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  122010. ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
  122011. sqlite3Select(pParse, pSub, &dest);
  122012. }
  122013. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  122014. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  122015. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  122016. VdbeComment((v, "end %s", pItem->pTab->zName));
  122017. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  122018. sqlite3ClearTempRegCache(pParse);
  122019. }
  122020. if( db->mallocFailed ) goto select_end;
  122021. pParse->nHeight -= sqlite3SelectExprHeight(p);
  122022. pParse->zAuthContext = zSavedAuthContext;
  122023. #endif
  122024. }
  122025. /* Various elements of the SELECT copied into local variables for
  122026. ** convenience */
  122027. pEList = p->pEList;
  122028. pWhere = p->pWhere;
  122029. pGroupBy = p->pGroupBy;
  122030. pHaving = p->pHaving;
  122031. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  122032. #if SELECTTRACE_ENABLED
  122033. if( sqlite3SelectTrace & 0x400 ){
  122034. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  122035. sqlite3TreeViewSelect(0, p, 0);
  122036. }
  122037. #endif
  122038. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  122039. ** if the select-list is the same as the ORDER BY list, then this query
  122040. ** can be rewritten as a GROUP BY. In other words, this:
  122041. **
  122042. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  122043. **
  122044. ** is transformed to:
  122045. **
  122046. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  122047. **
  122048. ** The second form is preferred as a single index (or temp-table) may be
  122049. ** used for both the ORDER BY and DISTINCT processing. As originally
  122050. ** written the query must use a temp-table for at least one of the ORDER
  122051. ** BY and DISTINCT, and an index or separate temp-table for the other.
  122052. */
  122053. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  122054. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  122055. ){
  122056. p->selFlags &= ~SF_Distinct;
  122057. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  122058. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  122059. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  122060. ** original setting of the SF_Distinct flag, not the current setting */
  122061. assert( sDistinct.isTnct );
  122062. #if SELECTTRACE_ENABLED
  122063. if( sqlite3SelectTrace & 0x400 ){
  122064. SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
  122065. sqlite3TreeViewSelect(0, p, 0);
  122066. }
  122067. #endif
  122068. }
  122069. /* If there is an ORDER BY clause, then create an ephemeral index to
  122070. ** do the sorting. But this sorting ephemeral index might end up
  122071. ** being unused if the data can be extracted in pre-sorted order.
  122072. ** If that is the case, then the OP_OpenEphemeral instruction will be
  122073. ** changed to an OP_Noop once we figure out that the sorting index is
  122074. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  122075. ** that change.
  122076. */
  122077. if( sSort.pOrderBy ){
  122078. KeyInfo *pKeyInfo;
  122079. pKeyInfo = sqlite3KeyInfoFromExprList(
  122080. pParse, sSort.pOrderBy, 0, pEList->nExpr);
  122081. sSort.iECursor = pParse->nTab++;
  122082. sSort.addrSortIndex =
  122083. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  122084. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  122085. (char*)pKeyInfo, P4_KEYINFO
  122086. );
  122087. }else{
  122088. sSort.addrSortIndex = -1;
  122089. }
  122090. /* If the output is destined for a temporary table, open that table.
  122091. */
  122092. if( pDest->eDest==SRT_EphemTab ){
  122093. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  122094. }
  122095. /* Set the limiter.
  122096. */
  122097. iEnd = sqlite3VdbeMakeLabel(v);
  122098. if( (p->selFlags & SF_FixedLimit)==0 ){
  122099. p->nSelectRow = 320; /* 4 billion rows */
  122100. }
  122101. computeLimitRegisters(pParse, p, iEnd);
  122102. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  122103. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  122104. sSort.sortFlags |= SORTFLAG_UseSorter;
  122105. }
  122106. /* Open an ephemeral index to use for the distinct set.
  122107. */
  122108. if( p->selFlags & SF_Distinct ){
  122109. sDistinct.tabTnct = pParse->nTab++;
  122110. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  122111. sDistinct.tabTnct, 0, 0,
  122112. (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
  122113. P4_KEYINFO);
  122114. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  122115. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  122116. }else{
  122117. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  122118. }
  122119. if( !isAgg && pGroupBy==0 ){
  122120. /* No aggregate functions and no GROUP BY clause */
  122121. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
  122122. | (p->selFlags & SF_FixedLimit);
  122123. #ifndef SQLITE_OMIT_WINDOWFUNC
  122124. Window *pWin = p->pWin; /* Master window object (or NULL) */
  122125. if( pWin ){
  122126. sqlite3WindowCodeInit(pParse, pWin);
  122127. }
  122128. #endif
  122129. assert( WHERE_USE_LIMIT==SF_FixedLimit );
  122130. /* Begin the database scan. */
  122131. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  122132. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  122133. p->pEList, wctrlFlags, p->nSelectRow);
  122134. if( pWInfo==0 ) goto select_end;
  122135. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  122136. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  122137. }
  122138. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  122139. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  122140. }
  122141. if( sSort.pOrderBy ){
  122142. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  122143. sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
  122144. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  122145. sSort.pOrderBy = 0;
  122146. }
  122147. }
  122148. /* If sorting index that was created by a prior OP_OpenEphemeral
  122149. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  122150. ** into an OP_Noop.
  122151. */
  122152. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  122153. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  122154. }
  122155. assert( p->pEList==pEList );
  122156. #ifndef SQLITE_OMIT_WINDOWFUNC
  122157. if( pWin ){
  122158. int addrGosub = sqlite3VdbeMakeLabel(v);
  122159. int iCont = sqlite3VdbeMakeLabel(v);
  122160. int iBreak = sqlite3VdbeMakeLabel(v);
  122161. int regGosub = ++pParse->nMem;
  122162. sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
  122163. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  122164. sqlite3VdbeResolveLabel(v, addrGosub);
  122165. VdbeNoopComment((v, "inner-loop subroutine"));
  122166. sSort.labelOBLopt = 0;
  122167. selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
  122168. sqlite3VdbeResolveLabel(v, iCont);
  122169. sqlite3VdbeAddOp1(v, OP_Return, regGosub);
  122170. VdbeComment((v, "end inner-loop subroutine"));
  122171. sqlite3VdbeResolveLabel(v, iBreak);
  122172. }else
  122173. #endif /* SQLITE_OMIT_WINDOWFUNC */
  122174. {
  122175. /* Use the standard inner loop. */
  122176. selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
  122177. sqlite3WhereContinueLabel(pWInfo),
  122178. sqlite3WhereBreakLabel(pWInfo));
  122179. /* End the database scan loop.
  122180. */
  122181. sqlite3WhereEnd(pWInfo);
  122182. }
  122183. }else{
  122184. /* This case when there exist aggregate functions or a GROUP BY clause
  122185. ** or both */
  122186. NameContext sNC; /* Name context for processing aggregate information */
  122187. int iAMem; /* First Mem address for storing current GROUP BY */
  122188. int iBMem; /* First Mem address for previous GROUP BY */
  122189. int iUseFlag; /* Mem address holding flag indicating that at least
  122190. ** one row of the input to the aggregator has been
  122191. ** processed */
  122192. int iAbortFlag; /* Mem address which causes query abort if positive */
  122193. int groupBySort; /* Rows come from source in GROUP BY order */
  122194. int addrEnd; /* End of processing for this SELECT */
  122195. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  122196. int sortOut = 0; /* Output register from the sorter */
  122197. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  122198. /* Remove any and all aliases between the result set and the
  122199. ** GROUP BY clause.
  122200. */
  122201. if( pGroupBy ){
  122202. int k; /* Loop counter */
  122203. struct ExprList_item *pItem; /* For looping over expression in a list */
  122204. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  122205. pItem->u.x.iAlias = 0;
  122206. }
  122207. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  122208. pItem->u.x.iAlias = 0;
  122209. }
  122210. assert( 66==sqlite3LogEst(100) );
  122211. if( p->nSelectRow>66 ) p->nSelectRow = 66;
  122212. }else{
  122213. assert( 0==sqlite3LogEst(1) );
  122214. p->nSelectRow = 0;
  122215. }
  122216. /* If there is both a GROUP BY and an ORDER BY clause and they are
  122217. ** identical, then it may be possible to disable the ORDER BY clause
  122218. ** on the grounds that the GROUP BY will cause elements to come out
  122219. ** in the correct order. It also may not - the GROUP BY might use a
  122220. ** database index that causes rows to be grouped together as required
  122221. ** but not actually sorted. Either way, record the fact that the
  122222. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  122223. ** variable. */
  122224. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  122225. orderByGrp = 1;
  122226. }
  122227. /* Create a label to jump to when we want to abort the query */
  122228. addrEnd = sqlite3VdbeMakeLabel(v);
  122229. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  122230. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  122231. ** SELECT statement.
  122232. */
  122233. memset(&sNC, 0, sizeof(sNC));
  122234. sNC.pParse = pParse;
  122235. sNC.pSrcList = pTabList;
  122236. sNC.uNC.pAggInfo = &sAggInfo;
  122237. VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
  122238. sAggInfo.mnReg = pParse->nMem+1;
  122239. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  122240. sAggInfo.pGroupBy = pGroupBy;
  122241. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  122242. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  122243. if( pHaving ){
  122244. if( pGroupBy ){
  122245. assert( pWhere==p->pWhere );
  122246. assert( pHaving==p->pHaving );
  122247. assert( pGroupBy==p->pGroupBy );
  122248. havingToWhere(pParse, p);
  122249. pWhere = p->pWhere;
  122250. }
  122251. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  122252. }
  122253. sAggInfo.nAccumulator = sAggInfo.nColumn;
  122254. if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
  122255. minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
  122256. }else{
  122257. minMaxFlag = WHERE_ORDERBY_NORMAL;
  122258. }
  122259. for(i=0; i<sAggInfo.nFunc; i++){
  122260. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  122261. sNC.ncFlags |= NC_InAggFunc;
  122262. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  122263. sNC.ncFlags &= ~NC_InAggFunc;
  122264. }
  122265. sAggInfo.mxReg = pParse->nMem;
  122266. if( db->mallocFailed ) goto select_end;
  122267. #if SELECTTRACE_ENABLED
  122268. if( sqlite3SelectTrace & 0x400 ){
  122269. int ii;
  122270. SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n"));
  122271. sqlite3TreeViewSelect(0, p, 0);
  122272. for(ii=0; ii<sAggInfo.nColumn; ii++){
  122273. sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
  122274. ii, sAggInfo.aCol[ii].iMem);
  122275. sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
  122276. }
  122277. for(ii=0; ii<sAggInfo.nFunc; ii++){
  122278. sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
  122279. ii, sAggInfo.aFunc[ii].iMem);
  122280. sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
  122281. }
  122282. }
  122283. #endif
  122284. /* Processing for aggregates with GROUP BY is very different and
  122285. ** much more complex than aggregates without a GROUP BY.
  122286. */
  122287. if( pGroupBy ){
  122288. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  122289. int addr1; /* A-vs-B comparision jump */
  122290. int addrOutputRow; /* Start of subroutine that outputs a result row */
  122291. int regOutputRow; /* Return address register for output subroutine */
  122292. int addrSetAbort; /* Set the abort flag and return */
  122293. int addrTopOfLoop; /* Top of the input loop */
  122294. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  122295. int addrReset; /* Subroutine for resetting the accumulator */
  122296. int regReset; /* Return address register for reset subroutine */
  122297. /* If there is a GROUP BY clause we might need a sorting index to
  122298. ** implement it. Allocate that sorting index now. If it turns out
  122299. ** that we do not need it after all, the OP_SorterOpen instruction
  122300. ** will be converted into a Noop.
  122301. */
  122302. sAggInfo.sortingIdx = pParse->nTab++;
  122303. pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn);
  122304. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  122305. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  122306. 0, (char*)pKeyInfo, P4_KEYINFO);
  122307. /* Initialize memory locations used by GROUP BY aggregate processing
  122308. */
  122309. iUseFlag = ++pParse->nMem;
  122310. iAbortFlag = ++pParse->nMem;
  122311. regOutputRow = ++pParse->nMem;
  122312. addrOutputRow = sqlite3VdbeMakeLabel(v);
  122313. regReset = ++pParse->nMem;
  122314. addrReset = sqlite3VdbeMakeLabel(v);
  122315. iAMem = pParse->nMem + 1;
  122316. pParse->nMem += pGroupBy->nExpr;
  122317. iBMem = pParse->nMem + 1;
  122318. pParse->nMem += pGroupBy->nExpr;
  122319. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  122320. VdbeComment((v, "clear abort flag"));
  122321. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  122322. /* Begin a loop that will extract all source rows in GROUP BY order.
  122323. ** This might involve two separate loops with an OP_Sort in between, or
  122324. ** it might be a single loop that uses an index to extract information
  122325. ** in the right order to begin with.
  122326. */
  122327. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  122328. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  122329. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  122330. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  122331. );
  122332. if( pWInfo==0 ) goto select_end;
  122333. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  122334. /* The optimizer is able to deliver rows in group by order so
  122335. ** we do not have to sort. The OP_OpenEphemeral table will be
  122336. ** cancelled later because we still need to use the pKeyInfo
  122337. */
  122338. groupBySort = 0;
  122339. }else{
  122340. /* Rows are coming out in undetermined order. We have to push
  122341. ** each row into a sorting index, terminate the first loop,
  122342. ** then loop over the sorting index in order to get the output
  122343. ** in sorted order
  122344. */
  122345. int regBase;
  122346. int regRecord;
  122347. int nCol;
  122348. int nGroupBy;
  122349. explainTempTable(pParse,
  122350. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  122351. "DISTINCT" : "GROUP BY");
  122352. groupBySort = 1;
  122353. nGroupBy = pGroupBy->nExpr;
  122354. nCol = nGroupBy;
  122355. j = nGroupBy;
  122356. for(i=0; i<sAggInfo.nColumn; i++){
  122357. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  122358. nCol++;
  122359. j++;
  122360. }
  122361. }
  122362. regBase = sqlite3GetTempRange(pParse, nCol);
  122363. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  122364. j = nGroupBy;
  122365. for(i=0; i<sAggInfo.nColumn; i++){
  122366. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  122367. if( pCol->iSorterColumn>=j ){
  122368. int r1 = j + regBase;
  122369. sqlite3ExprCodeGetColumnOfTable(v,
  122370. pCol->pTab, pCol->iTable, pCol->iColumn, r1);
  122371. j++;
  122372. }
  122373. }
  122374. regRecord = sqlite3GetTempReg(pParse);
  122375. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  122376. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  122377. sqlite3ReleaseTempReg(pParse, regRecord);
  122378. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  122379. sqlite3WhereEnd(pWInfo);
  122380. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  122381. sortOut = sqlite3GetTempReg(pParse);
  122382. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  122383. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  122384. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  122385. sAggInfo.useSortingIdx = 1;
  122386. }
  122387. /* If the index or temporary table used by the GROUP BY sort
  122388. ** will naturally deliver rows in the order required by the ORDER BY
  122389. ** clause, cancel the ephemeral table open coded earlier.
  122390. **
  122391. ** This is an optimization - the correct answer should result regardless.
  122392. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  122393. ** disable this optimization for testing purposes. */
  122394. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  122395. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  122396. ){
  122397. sSort.pOrderBy = 0;
  122398. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  122399. }
  122400. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  122401. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  122402. ** Then compare the current GROUP BY terms against the GROUP BY terms
  122403. ** from the previous row currently stored in a0, a1, a2...
  122404. */
  122405. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  122406. if( groupBySort ){
  122407. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  122408. sortOut, sortPTab);
  122409. }
  122410. for(j=0; j<pGroupBy->nExpr; j++){
  122411. if( groupBySort ){
  122412. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  122413. }else{
  122414. sAggInfo.directMode = 1;
  122415. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  122416. }
  122417. }
  122418. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  122419. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  122420. addr1 = sqlite3VdbeCurrentAddr(v);
  122421. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  122422. /* Generate code that runs whenever the GROUP BY changes.
  122423. ** Changes in the GROUP BY are detected by the previous code
  122424. ** block. If there were no changes, this block is skipped.
  122425. **
  122426. ** This code copies current group by terms in b0,b1,b2,...
  122427. ** over to a0,a1,a2. It then calls the output subroutine
  122428. ** and resets the aggregate accumulator registers in preparation
  122429. ** for the next GROUP BY batch.
  122430. */
  122431. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  122432. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  122433. VdbeComment((v, "output one row"));
  122434. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  122435. VdbeComment((v, "check abort flag"));
  122436. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  122437. VdbeComment((v, "reset accumulator"));
  122438. /* Update the aggregate accumulators based on the content of
  122439. ** the current row
  122440. */
  122441. sqlite3VdbeJumpHere(v, addr1);
  122442. updateAccumulator(pParse, iUseFlag, &sAggInfo);
  122443. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  122444. VdbeComment((v, "indicate data in accumulator"));
  122445. /* End of the loop
  122446. */
  122447. if( groupBySort ){
  122448. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  122449. VdbeCoverage(v);
  122450. }else{
  122451. sqlite3WhereEnd(pWInfo);
  122452. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  122453. }
  122454. /* Output the final row of result
  122455. */
  122456. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  122457. VdbeComment((v, "output final row"));
  122458. /* Jump over the subroutines
  122459. */
  122460. sqlite3VdbeGoto(v, addrEnd);
  122461. /* Generate a subroutine that outputs a single row of the result
  122462. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  122463. ** is less than or equal to zero, the subroutine is a no-op. If
  122464. ** the processing calls for the query to abort, this subroutine
  122465. ** increments the iAbortFlag memory location before returning in
  122466. ** order to signal the caller to abort.
  122467. */
  122468. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  122469. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  122470. VdbeComment((v, "set abort flag"));
  122471. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  122472. sqlite3VdbeResolveLabel(v, addrOutputRow);
  122473. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  122474. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  122475. VdbeCoverage(v);
  122476. VdbeComment((v, "Groupby result generator entry point"));
  122477. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  122478. finalizeAggFunctions(pParse, &sAggInfo);
  122479. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  122480. selectInnerLoop(pParse, p, -1, &sSort,
  122481. &sDistinct, pDest,
  122482. addrOutputRow+1, addrSetAbort);
  122483. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  122484. VdbeComment((v, "end groupby result generator"));
  122485. /* Generate a subroutine that will reset the group-by accumulator
  122486. */
  122487. sqlite3VdbeResolveLabel(v, addrReset);
  122488. resetAccumulator(pParse, &sAggInfo);
  122489. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  122490. VdbeComment((v, "indicate accumulator empty"));
  122491. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  122492. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  122493. else {
  122494. #ifndef SQLITE_OMIT_BTREECOUNT
  122495. Table *pTab;
  122496. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  122497. /* If isSimpleCount() returns a pointer to a Table structure, then
  122498. ** the SQL statement is of the form:
  122499. **
  122500. ** SELECT count(*) FROM <tbl>
  122501. **
  122502. ** where the Table structure returned represents table <tbl>.
  122503. **
  122504. ** This statement is so common that it is optimized specially. The
  122505. ** OP_Count instruction is executed either on the intkey table that
  122506. ** contains the data for table <tbl> or on one of its indexes. It
  122507. ** is better to execute the op on an index, as indexes are almost
  122508. ** always spread across less pages than their corresponding tables.
  122509. */
  122510. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  122511. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  122512. Index *pIdx; /* Iterator variable */
  122513. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  122514. Index *pBest = 0; /* Best index found so far */
  122515. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  122516. sqlite3CodeVerifySchema(pParse, iDb);
  122517. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  122518. /* Search for the index that has the lowest scan cost.
  122519. **
  122520. ** (2011-04-15) Do not do a full scan of an unordered index.
  122521. **
  122522. ** (2013-10-03) Do not count the entries in a partial index.
  122523. **
  122524. ** In practice the KeyInfo structure will not be used. It is only
  122525. ** passed to keep OP_OpenRead happy.
  122526. */
  122527. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  122528. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  122529. if( pIdx->bUnordered==0
  122530. && pIdx->szIdxRow<pTab->szTabRow
  122531. && pIdx->pPartIdxWhere==0
  122532. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  122533. ){
  122534. pBest = pIdx;
  122535. }
  122536. }
  122537. if( pBest ){
  122538. iRoot = pBest->tnum;
  122539. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  122540. }
  122541. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  122542. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  122543. if( pKeyInfo ){
  122544. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  122545. }
  122546. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  122547. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  122548. explainSimpleCount(pParse, pTab, pBest);
  122549. }else
  122550. #endif /* SQLITE_OMIT_BTREECOUNT */
  122551. {
  122552. int regAcc = 0; /* "populate accumulators" flag */
  122553. /* If there are accumulator registers but no min() or max() functions,
  122554. ** allocate register regAcc. Register regAcc will contain 0 the first
  122555. ** time the inner loop runs, and 1 thereafter. The code generated
  122556. ** by updateAccumulator() only updates the accumulator registers if
  122557. ** regAcc contains 0. */
  122558. if( sAggInfo.nAccumulator ){
  122559. for(i=0; i<sAggInfo.nFunc; i++){
  122560. if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break;
  122561. }
  122562. if( i==sAggInfo.nFunc ){
  122563. regAcc = ++pParse->nMem;
  122564. sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
  122565. }
  122566. }
  122567. /* This case runs if the aggregate has no GROUP BY clause. The
  122568. ** processing is much simpler since there is only a single row
  122569. ** of output.
  122570. */
  122571. assert( p->pGroupBy==0 );
  122572. resetAccumulator(pParse, &sAggInfo);
  122573. /* If this query is a candidate for the min/max optimization, then
  122574. ** minMaxFlag will have been previously set to either
  122575. ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
  122576. ** be an appropriate ORDER BY expression for the optimization.
  122577. */
  122578. assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
  122579. assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
  122580. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  122581. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
  122582. 0, minMaxFlag, 0);
  122583. if( pWInfo==0 ){
  122584. goto select_end;
  122585. }
  122586. updateAccumulator(pParse, regAcc, &sAggInfo);
  122587. if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
  122588. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  122589. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  122590. VdbeComment((v, "%s() by index",
  122591. (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
  122592. }
  122593. sqlite3WhereEnd(pWInfo);
  122594. finalizeAggFunctions(pParse, &sAggInfo);
  122595. }
  122596. sSort.pOrderBy = 0;
  122597. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  122598. selectInnerLoop(pParse, p, -1, 0, 0,
  122599. pDest, addrEnd, addrEnd);
  122600. }
  122601. sqlite3VdbeResolveLabel(v, addrEnd);
  122602. } /* endif aggregate query */
  122603. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  122604. explainTempTable(pParse, "DISTINCT");
  122605. }
  122606. /* If there is an ORDER BY clause, then we need to sort the results
  122607. ** and send them to the callback one by one.
  122608. */
  122609. if( sSort.pOrderBy ){
  122610. explainTempTable(pParse,
  122611. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  122612. assert( p->pEList==pEList );
  122613. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  122614. }
  122615. /* Jump here to skip this query
  122616. */
  122617. sqlite3VdbeResolveLabel(v, iEnd);
  122618. /* The SELECT has been coded. If there is an error in the Parse structure,
  122619. ** set the return code to 1. Otherwise 0. */
  122620. rc = (pParse->nErr>0);
  122621. /* Control jumps to here if an error is encountered above, or upon
  122622. ** successful coding of the SELECT.
  122623. */
  122624. select_end:
  122625. sqlite3ExprListDelete(db, pMinMaxOrderBy);
  122626. sqlite3DbFree(db, sAggInfo.aCol);
  122627. sqlite3DbFree(db, sAggInfo.aFunc);
  122628. #if SELECTTRACE_ENABLED
  122629. SELECTTRACE(0x1,pParse,p,("end processing\n"));
  122630. if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
  122631. sqlite3TreeViewSelect(0, p, 0);
  122632. }
  122633. #endif
  122634. ExplainQueryPlanPop(pParse);
  122635. return rc;
  122636. }
  122637. /************** End of select.c **********************************************/
  122638. /************** Begin file table.c *******************************************/
  122639. /*
  122640. ** 2001 September 15
  122641. **
  122642. ** The author disclaims copyright to this source code. In place of
  122643. ** a legal notice, here is a blessing:
  122644. **
  122645. ** May you do good and not evil.
  122646. ** May you find forgiveness for yourself and forgive others.
  122647. ** May you share freely, never taking more than you give.
  122648. **
  122649. *************************************************************************
  122650. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  122651. ** interface routines. These are just wrappers around the main
  122652. ** interface routine of sqlite3_exec().
  122653. **
  122654. ** These routines are in a separate files so that they will not be linked
  122655. ** if they are not used.
  122656. */
  122657. /* #include "sqliteInt.h" */
  122658. #ifndef SQLITE_OMIT_GET_TABLE
  122659. /*
  122660. ** This structure is used to pass data from sqlite3_get_table() through
  122661. ** to the callback function is uses to build the result.
  122662. */
  122663. typedef struct TabResult {
  122664. char **azResult; /* Accumulated output */
  122665. char *zErrMsg; /* Error message text, if an error occurs */
  122666. u32 nAlloc; /* Slots allocated for azResult[] */
  122667. u32 nRow; /* Number of rows in the result */
  122668. u32 nColumn; /* Number of columns in the result */
  122669. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  122670. int rc; /* Return code from sqlite3_exec() */
  122671. } TabResult;
  122672. /*
  122673. ** This routine is called once for each row in the result table. Its job
  122674. ** is to fill in the TabResult structure appropriately, allocating new
  122675. ** memory as necessary.
  122676. */
  122677. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  122678. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  122679. int need; /* Slots needed in p->azResult[] */
  122680. int i; /* Loop counter */
  122681. char *z; /* A single column of result */
  122682. /* Make sure there is enough space in p->azResult to hold everything
  122683. ** we need to remember from this invocation of the callback.
  122684. */
  122685. if( p->nRow==0 && argv!=0 ){
  122686. need = nCol*2;
  122687. }else{
  122688. need = nCol;
  122689. }
  122690. if( p->nData + need > p->nAlloc ){
  122691. char **azNew;
  122692. p->nAlloc = p->nAlloc*2 + need;
  122693. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  122694. if( azNew==0 ) goto malloc_failed;
  122695. p->azResult = azNew;
  122696. }
  122697. /* If this is the first row, then generate an extra row containing
  122698. ** the names of all columns.
  122699. */
  122700. if( p->nRow==0 ){
  122701. p->nColumn = nCol;
  122702. for(i=0; i<nCol; i++){
  122703. z = sqlite3_mprintf("%s", colv[i]);
  122704. if( z==0 ) goto malloc_failed;
  122705. p->azResult[p->nData++] = z;
  122706. }
  122707. }else if( (int)p->nColumn!=nCol ){
  122708. sqlite3_free(p->zErrMsg);
  122709. p->zErrMsg = sqlite3_mprintf(
  122710. "sqlite3_get_table() called with two or more incompatible queries"
  122711. );
  122712. p->rc = SQLITE_ERROR;
  122713. return 1;
  122714. }
  122715. /* Copy over the row data
  122716. */
  122717. if( argv!=0 ){
  122718. for(i=0; i<nCol; i++){
  122719. if( argv[i]==0 ){
  122720. z = 0;
  122721. }else{
  122722. int n = sqlite3Strlen30(argv[i])+1;
  122723. z = sqlite3_malloc64( n );
  122724. if( z==0 ) goto malloc_failed;
  122725. memcpy(z, argv[i], n);
  122726. }
  122727. p->azResult[p->nData++] = z;
  122728. }
  122729. p->nRow++;
  122730. }
  122731. return 0;
  122732. malloc_failed:
  122733. p->rc = SQLITE_NOMEM_BKPT;
  122734. return 1;
  122735. }
  122736. /*
  122737. ** Query the database. But instead of invoking a callback for each row,
  122738. ** malloc() for space to hold the result and return the entire results
  122739. ** at the conclusion of the call.
  122740. **
  122741. ** The result that is written to ***pazResult is held in memory obtained
  122742. ** from malloc(). But the caller cannot free this memory directly.
  122743. ** Instead, the entire table should be passed to sqlite3_free_table() when
  122744. ** the calling procedure is finished using it.
  122745. */
  122746. SQLITE_API int sqlite3_get_table(
  122747. sqlite3 *db, /* The database on which the SQL executes */
  122748. const char *zSql, /* The SQL to be executed */
  122749. char ***pazResult, /* Write the result table here */
  122750. int *pnRow, /* Write the number of rows in the result here */
  122751. int *pnColumn, /* Write the number of columns of result here */
  122752. char **pzErrMsg /* Write error messages here */
  122753. ){
  122754. int rc;
  122755. TabResult res;
  122756. #ifdef SQLITE_ENABLE_API_ARMOR
  122757. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  122758. #endif
  122759. *pazResult = 0;
  122760. if( pnColumn ) *pnColumn = 0;
  122761. if( pnRow ) *pnRow = 0;
  122762. if( pzErrMsg ) *pzErrMsg = 0;
  122763. res.zErrMsg = 0;
  122764. res.nRow = 0;
  122765. res.nColumn = 0;
  122766. res.nData = 1;
  122767. res.nAlloc = 20;
  122768. res.rc = SQLITE_OK;
  122769. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  122770. if( res.azResult==0 ){
  122771. db->errCode = SQLITE_NOMEM;
  122772. return SQLITE_NOMEM_BKPT;
  122773. }
  122774. res.azResult[0] = 0;
  122775. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  122776. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  122777. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  122778. if( (rc&0xff)==SQLITE_ABORT ){
  122779. sqlite3_free_table(&res.azResult[1]);
  122780. if( res.zErrMsg ){
  122781. if( pzErrMsg ){
  122782. sqlite3_free(*pzErrMsg);
  122783. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  122784. }
  122785. sqlite3_free(res.zErrMsg);
  122786. }
  122787. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  122788. return res.rc;
  122789. }
  122790. sqlite3_free(res.zErrMsg);
  122791. if( rc!=SQLITE_OK ){
  122792. sqlite3_free_table(&res.azResult[1]);
  122793. return rc;
  122794. }
  122795. if( res.nAlloc>res.nData ){
  122796. char **azNew;
  122797. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  122798. if( azNew==0 ){
  122799. sqlite3_free_table(&res.azResult[1]);
  122800. db->errCode = SQLITE_NOMEM;
  122801. return SQLITE_NOMEM_BKPT;
  122802. }
  122803. res.azResult = azNew;
  122804. }
  122805. *pazResult = &res.azResult[1];
  122806. if( pnColumn ) *pnColumn = res.nColumn;
  122807. if( pnRow ) *pnRow = res.nRow;
  122808. return rc;
  122809. }
  122810. /*
  122811. ** This routine frees the space the sqlite3_get_table() malloced.
  122812. */
  122813. SQLITE_API void sqlite3_free_table(
  122814. char **azResult /* Result returned from sqlite3_get_table() */
  122815. ){
  122816. if( azResult ){
  122817. int i, n;
  122818. azResult--;
  122819. assert( azResult!=0 );
  122820. n = SQLITE_PTR_TO_INT(azResult[0]);
  122821. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  122822. sqlite3_free(azResult);
  122823. }
  122824. }
  122825. #endif /* SQLITE_OMIT_GET_TABLE */
  122826. /************** End of table.c ***********************************************/
  122827. /************** Begin file trigger.c *****************************************/
  122828. /*
  122829. **
  122830. ** The author disclaims copyright to this source code. In place of
  122831. ** a legal notice, here is a blessing:
  122832. **
  122833. ** May you do good and not evil.
  122834. ** May you find forgiveness for yourself and forgive others.
  122835. ** May you share freely, never taking more than you give.
  122836. **
  122837. *************************************************************************
  122838. ** This file contains the implementation for TRIGGERs
  122839. */
  122840. /* #include "sqliteInt.h" */
  122841. #ifndef SQLITE_OMIT_TRIGGER
  122842. /*
  122843. ** Delete a linked list of TriggerStep structures.
  122844. */
  122845. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  122846. while( pTriggerStep ){
  122847. TriggerStep * pTmp = pTriggerStep;
  122848. pTriggerStep = pTriggerStep->pNext;
  122849. sqlite3ExprDelete(db, pTmp->pWhere);
  122850. sqlite3ExprListDelete(db, pTmp->pExprList);
  122851. sqlite3SelectDelete(db, pTmp->pSelect);
  122852. sqlite3IdListDelete(db, pTmp->pIdList);
  122853. sqlite3UpsertDelete(db, pTmp->pUpsert);
  122854. sqlite3DbFree(db, pTmp->zSpan);
  122855. sqlite3DbFree(db, pTmp);
  122856. }
  122857. }
  122858. /*
  122859. ** Given table pTab, return a list of all the triggers attached to
  122860. ** the table. The list is connected by Trigger.pNext pointers.
  122861. **
  122862. ** All of the triggers on pTab that are in the same database as pTab
  122863. ** are already attached to pTab->pTrigger. But there might be additional
  122864. ** triggers on pTab in the TEMP schema. This routine prepends all
  122865. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  122866. ** and returns the combined list.
  122867. **
  122868. ** To state it another way: This routine returns a list of all triggers
  122869. ** that fire off of pTab. The list will include any TEMP triggers on
  122870. ** pTab as well as the triggers lised in pTab->pTrigger.
  122871. */
  122872. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  122873. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  122874. Trigger *pList = 0; /* List of triggers to return */
  122875. if( pParse->disableTriggers ){
  122876. return 0;
  122877. }
  122878. if( pTmpSchema!=pTab->pSchema ){
  122879. HashElem *p;
  122880. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  122881. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  122882. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  122883. if( pTrig->pTabSchema==pTab->pSchema
  122884. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  122885. ){
  122886. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  122887. pList = pTrig;
  122888. }
  122889. }
  122890. }
  122891. return (pList ? pList : pTab->pTrigger);
  122892. }
  122893. /*
  122894. ** This is called by the parser when it sees a CREATE TRIGGER statement
  122895. ** up to the point of the BEGIN before the trigger actions. A Trigger
  122896. ** structure is generated based on the information available and stored
  122897. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  122898. ** sqlite3FinishTrigger() function is called to complete the trigger
  122899. ** construction process.
  122900. */
  122901. SQLITE_PRIVATE void sqlite3BeginTrigger(
  122902. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  122903. Token *pName1, /* The name of the trigger */
  122904. Token *pName2, /* The name of the trigger */
  122905. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  122906. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  122907. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  122908. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  122909. Expr *pWhen, /* WHEN clause */
  122910. int isTemp, /* True if the TEMPORARY keyword is present */
  122911. int noErr /* Suppress errors if the trigger already exists */
  122912. ){
  122913. Trigger *pTrigger = 0; /* The new trigger */
  122914. Table *pTab; /* Table that the trigger fires off of */
  122915. char *zName = 0; /* Name of the trigger */
  122916. sqlite3 *db = pParse->db; /* The database connection */
  122917. int iDb; /* The database to store the trigger in */
  122918. Token *pName; /* The unqualified db name */
  122919. DbFixer sFix; /* State vector for the DB fixer */
  122920. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  122921. assert( pName2!=0 );
  122922. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  122923. assert( op>0 && op<0xff );
  122924. if( isTemp ){
  122925. /* If TEMP was specified, then the trigger name may not be qualified. */
  122926. if( pName2->n>0 ){
  122927. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  122928. goto trigger_cleanup;
  122929. }
  122930. iDb = 1;
  122931. pName = pName1;
  122932. }else{
  122933. /* Figure out the db that the trigger will be created in */
  122934. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  122935. if( iDb<0 ){
  122936. goto trigger_cleanup;
  122937. }
  122938. }
  122939. if( !pTableName || db->mallocFailed ){
  122940. goto trigger_cleanup;
  122941. }
  122942. /* A long-standing parser bug is that this syntax was allowed:
  122943. **
  122944. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  122945. ** ^^^^^^^^
  122946. **
  122947. ** To maintain backwards compatibility, ignore the database
  122948. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  122949. */
  122950. if( db->init.busy && iDb!=1 ){
  122951. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  122952. pTableName->a[0].zDatabase = 0;
  122953. }
  122954. /* If the trigger name was unqualified, and the table is a temp table,
  122955. ** then set iDb to 1 to create the trigger in the temporary database.
  122956. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  122957. ** exist, the error is caught by the block below.
  122958. */
  122959. pTab = sqlite3SrcListLookup(pParse, pTableName);
  122960. if( db->init.busy==0 && pName2->n==0 && pTab
  122961. && pTab->pSchema==db->aDb[1].pSchema ){
  122962. iDb = 1;
  122963. }
  122964. /* Ensure the table name matches database name and that the table exists */
  122965. if( db->mallocFailed ) goto trigger_cleanup;
  122966. assert( pTableName->nSrc==1 );
  122967. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  122968. if( sqlite3FixSrcList(&sFix, pTableName) ){
  122969. goto trigger_cleanup;
  122970. }
  122971. pTab = sqlite3SrcListLookup(pParse, pTableName);
  122972. if( !pTab ){
  122973. /* The table does not exist. */
  122974. if( db->init.iDb==1 ){
  122975. /* Ticket #3810.
  122976. ** Normally, whenever a table is dropped, all associated triggers are
  122977. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  122978. ** and the table is dropped by a different database connection, the
  122979. ** trigger is not visible to the database connection that does the
  122980. ** drop so the trigger cannot be dropped. This results in an
  122981. ** "orphaned trigger" - a trigger whose associated table is missing.
  122982. */
  122983. db->init.orphanTrigger = 1;
  122984. }
  122985. goto trigger_cleanup;
  122986. }
  122987. if( IsVirtual(pTab) ){
  122988. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  122989. goto trigger_cleanup;
  122990. }
  122991. /* Check that the trigger name is not reserved and that no trigger of the
  122992. ** specified name exists */
  122993. zName = sqlite3NameFromToken(db, pName);
  122994. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  122995. goto trigger_cleanup;
  122996. }
  122997. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  122998. if( !IN_RENAME_OBJECT ){
  122999. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  123000. if( !noErr ){
  123001. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  123002. }else{
  123003. assert( !db->init.busy );
  123004. sqlite3CodeVerifySchema(pParse, iDb);
  123005. }
  123006. goto trigger_cleanup;
  123007. }
  123008. }
  123009. /* Do not create a trigger on a system table */
  123010. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  123011. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  123012. goto trigger_cleanup;
  123013. }
  123014. /* INSTEAD of triggers are only for views and views only support INSTEAD
  123015. ** of triggers.
  123016. */
  123017. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  123018. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  123019. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  123020. goto trigger_cleanup;
  123021. }
  123022. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  123023. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  123024. " trigger on table: %S", pTableName, 0);
  123025. goto trigger_cleanup;
  123026. }
  123027. #ifndef SQLITE_OMIT_AUTHORIZATION
  123028. if( !IN_RENAME_OBJECT ){
  123029. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  123030. int code = SQLITE_CREATE_TRIGGER;
  123031. const char *zDb = db->aDb[iTabDb].zDbSName;
  123032. const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
  123033. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  123034. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  123035. goto trigger_cleanup;
  123036. }
  123037. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  123038. goto trigger_cleanup;
  123039. }
  123040. }
  123041. #endif
  123042. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  123043. ** cannot appear on views. So we might as well translate every
  123044. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  123045. ** elsewhere.
  123046. */
  123047. if (tr_tm == TK_INSTEAD){
  123048. tr_tm = TK_BEFORE;
  123049. }
  123050. /* Build the Trigger object */
  123051. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  123052. if( pTrigger==0 ) goto trigger_cleanup;
  123053. pTrigger->zName = zName;
  123054. zName = 0;
  123055. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  123056. pTrigger->pSchema = db->aDb[iDb].pSchema;
  123057. pTrigger->pTabSchema = pTab->pSchema;
  123058. pTrigger->op = (u8)op;
  123059. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  123060. if( IN_RENAME_OBJECT ){
  123061. sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName);
  123062. pTrigger->pWhen = pWhen;
  123063. pWhen = 0;
  123064. }else{
  123065. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  123066. }
  123067. pTrigger->pColumns = pColumns;
  123068. pColumns = 0;
  123069. assert( pParse->pNewTrigger==0 );
  123070. pParse->pNewTrigger = pTrigger;
  123071. trigger_cleanup:
  123072. sqlite3DbFree(db, zName);
  123073. sqlite3SrcListDelete(db, pTableName);
  123074. sqlite3IdListDelete(db, pColumns);
  123075. sqlite3ExprDelete(db, pWhen);
  123076. if( !pParse->pNewTrigger ){
  123077. sqlite3DeleteTrigger(db, pTrigger);
  123078. }else{
  123079. assert( pParse->pNewTrigger==pTrigger );
  123080. }
  123081. }
  123082. /*
  123083. ** This routine is called after all of the trigger actions have been parsed
  123084. ** in order to complete the process of building the trigger.
  123085. */
  123086. SQLITE_PRIVATE void sqlite3FinishTrigger(
  123087. Parse *pParse, /* Parser context */
  123088. TriggerStep *pStepList, /* The triggered program */
  123089. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  123090. ){
  123091. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  123092. char *zName; /* Name of trigger */
  123093. sqlite3 *db = pParse->db; /* The database */
  123094. DbFixer sFix; /* Fixer object */
  123095. int iDb; /* Database containing the trigger */
  123096. Token nameToken; /* Trigger name for error reporting */
  123097. pParse->pNewTrigger = 0;
  123098. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  123099. zName = pTrig->zName;
  123100. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  123101. pTrig->step_list = pStepList;
  123102. while( pStepList ){
  123103. pStepList->pTrig = pTrig;
  123104. pStepList = pStepList->pNext;
  123105. }
  123106. sqlite3TokenInit(&nameToken, pTrig->zName);
  123107. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  123108. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  123109. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  123110. ){
  123111. goto triggerfinish_cleanup;
  123112. }
  123113. #ifndef SQLITE_OMIT_ALTERTABLE
  123114. if( IN_RENAME_OBJECT ){
  123115. assert( !db->init.busy );
  123116. pParse->pNewTrigger = pTrig;
  123117. pTrig = 0;
  123118. }else
  123119. #endif
  123120. /* if we are not initializing,
  123121. ** build the sqlite_master entry
  123122. */
  123123. if( !db->init.busy ){
  123124. Vdbe *v;
  123125. char *z;
  123126. /* Make an entry in the sqlite_master table */
  123127. v = sqlite3GetVdbe(pParse);
  123128. if( v==0 ) goto triggerfinish_cleanup;
  123129. sqlite3BeginWriteOperation(pParse, 0, iDb);
  123130. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  123131. testcase( z==0 );
  123132. sqlite3NestedParse(pParse,
  123133. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  123134. db->aDb[iDb].zDbSName, MASTER_NAME, zName,
  123135. pTrig->table, z);
  123136. sqlite3DbFree(db, z);
  123137. sqlite3ChangeCookie(pParse, iDb);
  123138. sqlite3VdbeAddParseSchemaOp(v, iDb,
  123139. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  123140. }
  123141. if( db->init.busy ){
  123142. Trigger *pLink = pTrig;
  123143. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  123144. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  123145. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  123146. if( pTrig ){
  123147. sqlite3OomFault(db);
  123148. }else if( pLink->pSchema==pLink->pTabSchema ){
  123149. Table *pTab;
  123150. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  123151. assert( pTab!=0 );
  123152. pLink->pNext = pTab->pTrigger;
  123153. pTab->pTrigger = pLink;
  123154. }
  123155. }
  123156. triggerfinish_cleanup:
  123157. sqlite3DeleteTrigger(db, pTrig);
  123158. assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );
  123159. sqlite3DeleteTriggerStep(db, pStepList);
  123160. }
  123161. /*
  123162. ** Duplicate a range of text from an SQL statement, then convert all
  123163. ** whitespace characters into ordinary space characters.
  123164. */
  123165. static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  123166. char *z = sqlite3DbSpanDup(db, zStart, zEnd);
  123167. int i;
  123168. if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
  123169. return z;
  123170. }
  123171. /*
  123172. ** Turn a SELECT statement (that the pSelect parameter points to) into
  123173. ** a trigger step. Return a pointer to a TriggerStep structure.
  123174. **
  123175. ** The parser calls this routine when it finds a SELECT statement in
  123176. ** body of a TRIGGER.
  123177. */
  123178. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(
  123179. sqlite3 *db, /* Database connection */
  123180. Select *pSelect, /* The SELECT statement */
  123181. const char *zStart, /* Start of SQL text */
  123182. const char *zEnd /* End of SQL text */
  123183. ){
  123184. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  123185. if( pTriggerStep==0 ) {
  123186. sqlite3SelectDelete(db, pSelect);
  123187. return 0;
  123188. }
  123189. pTriggerStep->op = TK_SELECT;
  123190. pTriggerStep->pSelect = pSelect;
  123191. pTriggerStep->orconf = OE_Default;
  123192. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  123193. return pTriggerStep;
  123194. }
  123195. /*
  123196. ** Allocate space to hold a new trigger step. The allocated space
  123197. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  123198. **
  123199. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  123200. */
  123201. static TriggerStep *triggerStepAllocate(
  123202. Parse *pParse, /* Parser context */
  123203. u8 op, /* Trigger opcode */
  123204. Token *pName, /* The target name */
  123205. const char *zStart, /* Start of SQL text */
  123206. const char *zEnd /* End of SQL text */
  123207. ){
  123208. sqlite3 *db = pParse->db;
  123209. TriggerStep *pTriggerStep;
  123210. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  123211. if( pTriggerStep ){
  123212. char *z = (char*)&pTriggerStep[1];
  123213. memcpy(z, pName->z, pName->n);
  123214. sqlite3Dequote(z);
  123215. pTriggerStep->zTarget = z;
  123216. pTriggerStep->op = op;
  123217. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  123218. if( IN_RENAME_OBJECT ){
  123219. sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);
  123220. }
  123221. }
  123222. return pTriggerStep;
  123223. }
  123224. /*
  123225. ** Build a trigger step out of an INSERT statement. Return a pointer
  123226. ** to the new trigger step.
  123227. **
  123228. ** The parser calls this routine when it sees an INSERT inside the
  123229. ** body of a trigger.
  123230. */
  123231. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  123232. Parse *pParse, /* Parser */
  123233. Token *pTableName, /* Name of the table into which we insert */
  123234. IdList *pColumn, /* List of columns in pTableName to insert into */
  123235. Select *pSelect, /* A SELECT statement that supplies values */
  123236. u8 orconf, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  123237. Upsert *pUpsert, /* ON CONFLICT clauses for upsert */
  123238. const char *zStart, /* Start of SQL text */
  123239. const char *zEnd /* End of SQL text */
  123240. ){
  123241. sqlite3 *db = pParse->db;
  123242. TriggerStep *pTriggerStep;
  123243. assert(pSelect != 0 || db->mallocFailed);
  123244. pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd);
  123245. if( pTriggerStep ){
  123246. if( IN_RENAME_OBJECT ){
  123247. pTriggerStep->pSelect = pSelect;
  123248. pSelect = 0;
  123249. }else{
  123250. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  123251. }
  123252. pTriggerStep->pIdList = pColumn;
  123253. pTriggerStep->pUpsert = pUpsert;
  123254. pTriggerStep->orconf = orconf;
  123255. }else{
  123256. testcase( pColumn );
  123257. sqlite3IdListDelete(db, pColumn);
  123258. testcase( pUpsert );
  123259. sqlite3UpsertDelete(db, pUpsert);
  123260. }
  123261. sqlite3SelectDelete(db, pSelect);
  123262. return pTriggerStep;
  123263. }
  123264. /*
  123265. ** Construct a trigger step that implements an UPDATE statement and return
  123266. ** a pointer to that trigger step. The parser calls this routine when it
  123267. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  123268. */
  123269. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  123270. Parse *pParse, /* Parser */
  123271. Token *pTableName, /* Name of the table to be updated */
  123272. ExprList *pEList, /* The SET clause: list of column and new values */
  123273. Expr *pWhere, /* The WHERE clause */
  123274. u8 orconf, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  123275. const char *zStart, /* Start of SQL text */
  123276. const char *zEnd /* End of SQL text */
  123277. ){
  123278. sqlite3 *db = pParse->db;
  123279. TriggerStep *pTriggerStep;
  123280. pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd);
  123281. if( pTriggerStep ){
  123282. if( IN_RENAME_OBJECT ){
  123283. pTriggerStep->pExprList = pEList;
  123284. pTriggerStep->pWhere = pWhere;
  123285. pEList = 0;
  123286. pWhere = 0;
  123287. }else{
  123288. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  123289. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  123290. }
  123291. pTriggerStep->orconf = orconf;
  123292. }
  123293. sqlite3ExprListDelete(db, pEList);
  123294. sqlite3ExprDelete(db, pWhere);
  123295. return pTriggerStep;
  123296. }
  123297. /*
  123298. ** Construct a trigger step that implements a DELETE statement and return
  123299. ** a pointer to that trigger step. The parser calls this routine when it
  123300. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  123301. */
  123302. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  123303. Parse *pParse, /* Parser */
  123304. Token *pTableName, /* The table from which rows are deleted */
  123305. Expr *pWhere, /* The WHERE clause */
  123306. const char *zStart, /* Start of SQL text */
  123307. const char *zEnd /* End of SQL text */
  123308. ){
  123309. sqlite3 *db = pParse->db;
  123310. TriggerStep *pTriggerStep;
  123311. pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd);
  123312. if( pTriggerStep ){
  123313. if( IN_RENAME_OBJECT ){
  123314. pTriggerStep->pWhere = pWhere;
  123315. pWhere = 0;
  123316. }else{
  123317. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  123318. }
  123319. pTriggerStep->orconf = OE_Default;
  123320. }
  123321. sqlite3ExprDelete(db, pWhere);
  123322. return pTriggerStep;
  123323. }
  123324. /*
  123325. ** Recursively delete a Trigger structure
  123326. */
  123327. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  123328. if( pTrigger==0 ) return;
  123329. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  123330. sqlite3DbFree(db, pTrigger->zName);
  123331. sqlite3DbFree(db, pTrigger->table);
  123332. sqlite3ExprDelete(db, pTrigger->pWhen);
  123333. sqlite3IdListDelete(db, pTrigger->pColumns);
  123334. sqlite3DbFree(db, pTrigger);
  123335. }
  123336. /*
  123337. ** This function is called to drop a trigger from the database schema.
  123338. **
  123339. ** This may be called directly from the parser and therefore identifies
  123340. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  123341. ** same job as this routine except it takes a pointer to the trigger
  123342. ** instead of the trigger name.
  123343. **/
  123344. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  123345. Trigger *pTrigger = 0;
  123346. int i;
  123347. const char *zDb;
  123348. const char *zName;
  123349. sqlite3 *db = pParse->db;
  123350. if( db->mallocFailed ) goto drop_trigger_cleanup;
  123351. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  123352. goto drop_trigger_cleanup;
  123353. }
  123354. assert( pName->nSrc==1 );
  123355. zDb = pName->a[0].zDatabase;
  123356. zName = pName->a[0].zName;
  123357. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  123358. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  123359. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  123360. if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
  123361. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  123362. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  123363. if( pTrigger ) break;
  123364. }
  123365. if( !pTrigger ){
  123366. if( !noErr ){
  123367. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  123368. }else{
  123369. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  123370. }
  123371. pParse->checkSchema = 1;
  123372. goto drop_trigger_cleanup;
  123373. }
  123374. sqlite3DropTriggerPtr(pParse, pTrigger);
  123375. drop_trigger_cleanup:
  123376. sqlite3SrcListDelete(db, pName);
  123377. }
  123378. /*
  123379. ** Return a pointer to the Table structure for the table that a trigger
  123380. ** is set on.
  123381. */
  123382. static Table *tableOfTrigger(Trigger *pTrigger){
  123383. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  123384. }
  123385. /*
  123386. ** Drop a trigger given a pointer to that trigger.
  123387. */
  123388. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  123389. Table *pTable;
  123390. Vdbe *v;
  123391. sqlite3 *db = pParse->db;
  123392. int iDb;
  123393. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  123394. assert( iDb>=0 && iDb<db->nDb );
  123395. pTable = tableOfTrigger(pTrigger);
  123396. assert( pTable );
  123397. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  123398. #ifndef SQLITE_OMIT_AUTHORIZATION
  123399. {
  123400. int code = SQLITE_DROP_TRIGGER;
  123401. const char *zDb = db->aDb[iDb].zDbSName;
  123402. const char *zTab = SCHEMA_TABLE(iDb);
  123403. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  123404. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  123405. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  123406. return;
  123407. }
  123408. }
  123409. #endif
  123410. /* Generate code to destroy the database record of the trigger.
  123411. */
  123412. assert( pTable!=0 );
  123413. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  123414. sqlite3NestedParse(pParse,
  123415. "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
  123416. db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
  123417. );
  123418. sqlite3ChangeCookie(pParse, iDb);
  123419. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  123420. }
  123421. }
  123422. /*
  123423. ** Remove a trigger from the hash tables of the sqlite* pointer.
  123424. */
  123425. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  123426. Trigger *pTrigger;
  123427. Hash *pHash;
  123428. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  123429. pHash = &(db->aDb[iDb].pSchema->trigHash);
  123430. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  123431. if( ALWAYS(pTrigger) ){
  123432. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  123433. Table *pTab = tableOfTrigger(pTrigger);
  123434. Trigger **pp;
  123435. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  123436. *pp = (*pp)->pNext;
  123437. }
  123438. sqlite3DeleteTrigger(db, pTrigger);
  123439. db->mDbFlags |= DBFLAG_SchemaChange;
  123440. }
  123441. }
  123442. /*
  123443. ** pEList is the SET clause of an UPDATE statement. Each entry
  123444. ** in pEList is of the format <id>=<expr>. If any of the entries
  123445. ** in pEList have an <id> which matches an identifier in pIdList,
  123446. ** then return TRUE. If pIdList==NULL, then it is considered a
  123447. ** wildcard that matches anything. Likewise if pEList==NULL then
  123448. ** it matches anything so always return true. Return false only
  123449. ** if there is no match.
  123450. */
  123451. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  123452. int e;
  123453. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  123454. for(e=0; e<pEList->nExpr; e++){
  123455. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  123456. }
  123457. return 0;
  123458. }
  123459. /*
  123460. ** Return a list of all triggers on table pTab if there exists at least
  123461. ** one trigger that must be fired when an operation of type 'op' is
  123462. ** performed on the table, and, if that operation is an UPDATE, if at
  123463. ** least one of the columns in pChanges is being modified.
  123464. */
  123465. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  123466. Parse *pParse, /* Parse context */
  123467. Table *pTab, /* The table the contains the triggers */
  123468. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  123469. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  123470. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  123471. ){
  123472. int mask = 0;
  123473. Trigger *pList = 0;
  123474. Trigger *p;
  123475. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  123476. pList = sqlite3TriggerList(pParse, pTab);
  123477. }
  123478. assert( pList==0 || IsVirtual(pTab)==0 );
  123479. for(p=pList; p; p=p->pNext){
  123480. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  123481. mask |= p->tr_tm;
  123482. }
  123483. }
  123484. if( pMask ){
  123485. *pMask = mask;
  123486. }
  123487. return (mask ? pList : 0);
  123488. }
  123489. /*
  123490. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  123491. ** to that SrcList.
  123492. **
  123493. ** This routine adds a specific database name, if needed, to the target when
  123494. ** forming the SrcList. This prevents a trigger in one database from
  123495. ** referring to a target in another database. An exception is when the
  123496. ** trigger is in TEMP in which case it can refer to any other database it
  123497. ** wants.
  123498. */
  123499. static SrcList *targetSrcList(
  123500. Parse *pParse, /* The parsing context */
  123501. TriggerStep *pStep /* The trigger containing the target token */
  123502. ){
  123503. sqlite3 *db = pParse->db;
  123504. int iDb; /* Index of the database to use */
  123505. SrcList *pSrc; /* SrcList to be returned */
  123506. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  123507. if( pSrc ){
  123508. assert( pSrc->nSrc>0 );
  123509. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  123510. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  123511. if( iDb==0 || iDb>=2 ){
  123512. const char *zDb;
  123513. assert( iDb<db->nDb );
  123514. zDb = db->aDb[iDb].zDbSName;
  123515. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
  123516. }
  123517. }
  123518. return pSrc;
  123519. }
  123520. /*
  123521. ** Generate VDBE code for the statements inside the body of a single
  123522. ** trigger.
  123523. */
  123524. static int codeTriggerProgram(
  123525. Parse *pParse, /* The parser context */
  123526. TriggerStep *pStepList, /* List of statements inside the trigger body */
  123527. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  123528. ){
  123529. TriggerStep *pStep;
  123530. Vdbe *v = pParse->pVdbe;
  123531. sqlite3 *db = pParse->db;
  123532. assert( pParse->pTriggerTab && pParse->pToplevel );
  123533. assert( pStepList );
  123534. assert( v!=0 );
  123535. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  123536. /* Figure out the ON CONFLICT policy that will be used for this step
  123537. ** of the trigger program. If the statement that caused this trigger
  123538. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  123539. ** the ON CONFLICT policy that was specified as part of the trigger
  123540. ** step statement. Example:
  123541. **
  123542. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  123543. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  123544. ** END;
  123545. **
  123546. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  123547. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  123548. */
  123549. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  123550. assert( pParse->okConstFactor==0 );
  123551. #ifndef SQLITE_OMIT_TRACE
  123552. if( pStep->zSpan ){
  123553. sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
  123554. sqlite3MPrintf(db, "-- %s", pStep->zSpan),
  123555. P4_DYNAMIC);
  123556. }
  123557. #endif
  123558. switch( pStep->op ){
  123559. case TK_UPDATE: {
  123560. sqlite3Update(pParse,
  123561. targetSrcList(pParse, pStep),
  123562. sqlite3ExprListDup(db, pStep->pExprList, 0),
  123563. sqlite3ExprDup(db, pStep->pWhere, 0),
  123564. pParse->eOrconf, 0, 0, 0
  123565. );
  123566. break;
  123567. }
  123568. case TK_INSERT: {
  123569. sqlite3Insert(pParse,
  123570. targetSrcList(pParse, pStep),
  123571. sqlite3SelectDup(db, pStep->pSelect, 0),
  123572. sqlite3IdListDup(db, pStep->pIdList),
  123573. pParse->eOrconf,
  123574. sqlite3UpsertDup(db, pStep->pUpsert)
  123575. );
  123576. break;
  123577. }
  123578. case TK_DELETE: {
  123579. sqlite3DeleteFrom(pParse,
  123580. targetSrcList(pParse, pStep),
  123581. sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
  123582. );
  123583. break;
  123584. }
  123585. default: assert( pStep->op==TK_SELECT ); {
  123586. SelectDest sDest;
  123587. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  123588. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  123589. sqlite3Select(pParse, pSelect, &sDest);
  123590. sqlite3SelectDelete(db, pSelect);
  123591. break;
  123592. }
  123593. }
  123594. if( pStep->op!=TK_SELECT ){
  123595. sqlite3VdbeAddOp0(v, OP_ResetCount);
  123596. }
  123597. }
  123598. return 0;
  123599. }
  123600. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  123601. /*
  123602. ** This function is used to add VdbeComment() annotations to a VDBE
  123603. ** program. It is not used in production code, only for debugging.
  123604. */
  123605. static const char *onErrorText(int onError){
  123606. switch( onError ){
  123607. case OE_Abort: return "abort";
  123608. case OE_Rollback: return "rollback";
  123609. case OE_Fail: return "fail";
  123610. case OE_Replace: return "replace";
  123611. case OE_Ignore: return "ignore";
  123612. case OE_Default: return "default";
  123613. }
  123614. return "n/a";
  123615. }
  123616. #endif
  123617. /*
  123618. ** Parse context structure pFrom has just been used to create a sub-vdbe
  123619. ** (trigger program). If an error has occurred, transfer error information
  123620. ** from pFrom to pTo.
  123621. */
  123622. static void transferParseError(Parse *pTo, Parse *pFrom){
  123623. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  123624. assert( pTo->zErrMsg==0 || pTo->nErr );
  123625. if( pTo->nErr==0 ){
  123626. pTo->zErrMsg = pFrom->zErrMsg;
  123627. pTo->nErr = pFrom->nErr;
  123628. pTo->rc = pFrom->rc;
  123629. }else{
  123630. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  123631. }
  123632. }
  123633. /*
  123634. ** Create and populate a new TriggerPrg object with a sub-program
  123635. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  123636. */
  123637. static TriggerPrg *codeRowTrigger(
  123638. Parse *pParse, /* Current parse context */
  123639. Trigger *pTrigger, /* Trigger to code */
  123640. Table *pTab, /* The table pTrigger is attached to */
  123641. int orconf /* ON CONFLICT policy to code trigger program with */
  123642. ){
  123643. Parse *pTop = sqlite3ParseToplevel(pParse);
  123644. sqlite3 *db = pParse->db; /* Database handle */
  123645. TriggerPrg *pPrg; /* Value to return */
  123646. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  123647. Vdbe *v; /* Temporary VM */
  123648. NameContext sNC; /* Name context for sub-vdbe */
  123649. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  123650. Parse *pSubParse; /* Parse context for sub-vdbe */
  123651. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  123652. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  123653. assert( pTop->pVdbe );
  123654. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  123655. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  123656. ** list of the top-level Parse object sooner rather than later. */
  123657. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  123658. if( !pPrg ) return 0;
  123659. pPrg->pNext = pTop->pTriggerPrg;
  123660. pTop->pTriggerPrg = pPrg;
  123661. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  123662. if( !pProgram ) return 0;
  123663. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  123664. pPrg->pTrigger = pTrigger;
  123665. pPrg->orconf = orconf;
  123666. pPrg->aColmask[0] = 0xffffffff;
  123667. pPrg->aColmask[1] = 0xffffffff;
  123668. /* Allocate and populate a new Parse context to use for coding the
  123669. ** trigger sub-program. */
  123670. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  123671. if( !pSubParse ) return 0;
  123672. memset(&sNC, 0, sizeof(sNC));
  123673. sNC.pParse = pSubParse;
  123674. pSubParse->db = db;
  123675. pSubParse->pTriggerTab = pTab;
  123676. pSubParse->pToplevel = pTop;
  123677. pSubParse->zAuthContext = pTrigger->zName;
  123678. pSubParse->eTriggerOp = pTrigger->op;
  123679. pSubParse->nQueryLoop = pParse->nQueryLoop;
  123680. v = sqlite3GetVdbe(pSubParse);
  123681. if( v ){
  123682. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  123683. pTrigger->zName, onErrorText(orconf),
  123684. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  123685. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  123686. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  123687. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  123688. pTab->zName
  123689. ));
  123690. #ifndef SQLITE_OMIT_TRACE
  123691. if( pTrigger->zName ){
  123692. sqlite3VdbeChangeP4(v, -1,
  123693. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  123694. );
  123695. }
  123696. #endif
  123697. /* If one was specified, code the WHEN clause. If it evaluates to false
  123698. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  123699. ** OP_Halt inserted at the end of the program. */
  123700. if( pTrigger->pWhen ){
  123701. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  123702. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  123703. && db->mallocFailed==0
  123704. ){
  123705. iEndTrigger = sqlite3VdbeMakeLabel(v);
  123706. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  123707. }
  123708. sqlite3ExprDelete(db, pWhen);
  123709. }
  123710. /* Code the trigger program into the sub-vdbe. */
  123711. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  123712. /* Insert an OP_Halt at the end of the sub-program. */
  123713. if( iEndTrigger ){
  123714. sqlite3VdbeResolveLabel(v, iEndTrigger);
  123715. }
  123716. sqlite3VdbeAddOp0(v, OP_Halt);
  123717. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  123718. transferParseError(pParse, pSubParse);
  123719. if( db->mallocFailed==0 && pParse->nErr==0 ){
  123720. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  123721. }
  123722. pProgram->nMem = pSubParse->nMem;
  123723. pProgram->nCsr = pSubParse->nTab;
  123724. pProgram->token = (void *)pTrigger;
  123725. pPrg->aColmask[0] = pSubParse->oldmask;
  123726. pPrg->aColmask[1] = pSubParse->newmask;
  123727. sqlite3VdbeDelete(v);
  123728. }
  123729. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  123730. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  123731. sqlite3ParserReset(pSubParse);
  123732. sqlite3StackFree(db, pSubParse);
  123733. return pPrg;
  123734. }
  123735. /*
  123736. ** Return a pointer to a TriggerPrg object containing the sub-program for
  123737. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  123738. ** TriggerPrg object exists, a new object is allocated and populated before
  123739. ** being returned.
  123740. */
  123741. static TriggerPrg *getRowTrigger(
  123742. Parse *pParse, /* Current parse context */
  123743. Trigger *pTrigger, /* Trigger to code */
  123744. Table *pTab, /* The table trigger pTrigger is attached to */
  123745. int orconf /* ON CONFLICT algorithm. */
  123746. ){
  123747. Parse *pRoot = sqlite3ParseToplevel(pParse);
  123748. TriggerPrg *pPrg;
  123749. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  123750. /* It may be that this trigger has already been coded (or is in the
  123751. ** process of being coded). If this is the case, then an entry with
  123752. ** a matching TriggerPrg.pTrigger field will be present somewhere
  123753. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  123754. for(pPrg=pRoot->pTriggerPrg;
  123755. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  123756. pPrg=pPrg->pNext
  123757. );
  123758. /* If an existing TriggerPrg could not be located, create a new one. */
  123759. if( !pPrg ){
  123760. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  123761. }
  123762. return pPrg;
  123763. }
  123764. /*
  123765. ** Generate code for the trigger program associated with trigger p on
  123766. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  123767. ** function are the same as those described in the header function for
  123768. ** sqlite3CodeRowTrigger()
  123769. */
  123770. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  123771. Parse *pParse, /* Parse context */
  123772. Trigger *p, /* Trigger to code */
  123773. Table *pTab, /* The table to code triggers from */
  123774. int reg, /* Reg array containing OLD.* and NEW.* values */
  123775. int orconf, /* ON CONFLICT policy */
  123776. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  123777. ){
  123778. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  123779. TriggerPrg *pPrg;
  123780. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  123781. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  123782. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  123783. ** is a pointer to the sub-vdbe containing the trigger program. */
  123784. if( pPrg ){
  123785. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  123786. sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
  123787. (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  123788. VdbeComment(
  123789. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  123790. /* Set the P5 operand of the OP_Program instruction to non-zero if
  123791. ** recursive invocation of this trigger program is disallowed. Recursive
  123792. ** invocation is disallowed if (a) the sub-program is really a trigger,
  123793. ** not a foreign key action, and (b) the flag to enable recursive triggers
  123794. ** is clear. */
  123795. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  123796. }
  123797. }
  123798. /*
  123799. ** This is called to code the required FOR EACH ROW triggers for an operation
  123800. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  123801. ** is given by the op parameter. The tr_tm parameter determines whether the
  123802. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  123803. ** parameter pChanges is passed the list of columns being modified.
  123804. **
  123805. ** If there are no triggers that fire at the specified time for the specified
  123806. ** operation on pTab, this function is a no-op.
  123807. **
  123808. ** The reg argument is the address of the first in an array of registers
  123809. ** that contain the values substituted for the new.* and old.* references
  123810. ** in the trigger program. If N is the number of columns in table pTab
  123811. ** (a copy of pTab->nCol), then registers are populated as follows:
  123812. **
  123813. ** Register Contains
  123814. ** ------------------------------------------------------
  123815. ** reg+0 OLD.rowid
  123816. ** reg+1 OLD.* value of left-most column of pTab
  123817. ** ... ...
  123818. ** reg+N OLD.* value of right-most column of pTab
  123819. ** reg+N+1 NEW.rowid
  123820. ** reg+N+2 OLD.* value of left-most column of pTab
  123821. ** ... ...
  123822. ** reg+N+N+1 NEW.* value of right-most column of pTab
  123823. **
  123824. ** For ON DELETE triggers, the registers containing the NEW.* values will
  123825. ** never be accessed by the trigger program, so they are not allocated or
  123826. ** populated by the caller (there is no data to populate them with anyway).
  123827. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  123828. ** are never accessed, and so are not allocated by the caller. So, for an
  123829. ** ON INSERT trigger, the value passed to this function as parameter reg
  123830. ** is not a readable register, although registers (reg+N) through
  123831. ** (reg+N+N+1) are.
  123832. **
  123833. ** Parameter orconf is the default conflict resolution algorithm for the
  123834. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  123835. ** is the instruction that control should jump to if a trigger program
  123836. ** raises an IGNORE exception.
  123837. */
  123838. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  123839. Parse *pParse, /* Parse context */
  123840. Trigger *pTrigger, /* List of triggers on table pTab */
  123841. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  123842. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  123843. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  123844. Table *pTab, /* The table to code triggers from */
  123845. int reg, /* The first in an array of registers (see above) */
  123846. int orconf, /* ON CONFLICT policy */
  123847. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  123848. ){
  123849. Trigger *p; /* Used to iterate through pTrigger list */
  123850. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  123851. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  123852. assert( (op==TK_UPDATE)==(pChanges!=0) );
  123853. for(p=pTrigger; p; p=p->pNext){
  123854. /* Sanity checking: The schema for the trigger and for the table are
  123855. ** always defined. The trigger must be in the same schema as the table
  123856. ** or else it must be a TEMP trigger. */
  123857. assert( p->pSchema!=0 );
  123858. assert( p->pTabSchema!=0 );
  123859. assert( p->pSchema==p->pTabSchema
  123860. || p->pSchema==pParse->db->aDb[1].pSchema );
  123861. /* Determine whether we should code this trigger */
  123862. if( p->op==op
  123863. && p->tr_tm==tr_tm
  123864. && checkColumnOverlap(p->pColumns, pChanges)
  123865. ){
  123866. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  123867. }
  123868. }
  123869. }
  123870. /*
  123871. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  123872. ** This function returns a 32-bit bitmask indicating which columns of the
  123873. ** old.* or new.* tables actually are used by triggers. This information
  123874. ** may be used by the caller, for example, to avoid having to load the entire
  123875. ** old.* record into memory when executing an UPDATE or DELETE command.
  123876. **
  123877. ** Bit 0 of the returned mask is set if the left-most column of the
  123878. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  123879. ** the second leftmost column value is required, and so on. If there
  123880. ** are more than 32 columns in the table, and at least one of the columns
  123881. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  123882. **
  123883. ** It is not possible to determine if the old.rowid or new.rowid column is
  123884. ** accessed by triggers. The caller must always assume that it is.
  123885. **
  123886. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  123887. ** applies to the old.* table. If 1, the new.* table.
  123888. **
  123889. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  123890. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  123891. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  123892. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  123893. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  123894. */
  123895. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  123896. Parse *pParse, /* Parse context */
  123897. Trigger *pTrigger, /* List of triggers on table pTab */
  123898. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  123899. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  123900. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  123901. Table *pTab, /* The table to code triggers from */
  123902. int orconf /* Default ON CONFLICT policy for trigger steps */
  123903. ){
  123904. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  123905. u32 mask = 0;
  123906. Trigger *p;
  123907. assert( isNew==1 || isNew==0 );
  123908. for(p=pTrigger; p; p=p->pNext){
  123909. if( p->op==op && (tr_tm&p->tr_tm)
  123910. && checkColumnOverlap(p->pColumns,pChanges)
  123911. ){
  123912. TriggerPrg *pPrg;
  123913. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  123914. if( pPrg ){
  123915. mask |= pPrg->aColmask[isNew];
  123916. }
  123917. }
  123918. }
  123919. return mask;
  123920. }
  123921. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  123922. /************** End of trigger.c *********************************************/
  123923. /************** Begin file update.c ******************************************/
  123924. /*
  123925. ** 2001 September 15
  123926. **
  123927. ** The author disclaims copyright to this source code. In place of
  123928. ** a legal notice, here is a blessing:
  123929. **
  123930. ** May you do good and not evil.
  123931. ** May you find forgiveness for yourself and forgive others.
  123932. ** May you share freely, never taking more than you give.
  123933. **
  123934. *************************************************************************
  123935. ** This file contains C code routines that are called by the parser
  123936. ** to handle UPDATE statements.
  123937. */
  123938. /* #include "sqliteInt.h" */
  123939. #ifndef SQLITE_OMIT_VIRTUALTABLE
  123940. /* Forward declaration */
  123941. static void updateVirtualTable(
  123942. Parse *pParse, /* The parsing context */
  123943. SrcList *pSrc, /* The virtual table to be modified */
  123944. Table *pTab, /* The virtual table */
  123945. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  123946. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  123947. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  123948. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  123949. int onError /* ON CONFLICT strategy */
  123950. );
  123951. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  123952. /*
  123953. ** The most recently coded instruction was an OP_Column to retrieve the
  123954. ** i-th column of table pTab. This routine sets the P4 parameter of the
  123955. ** OP_Column to the default value, if any.
  123956. **
  123957. ** The default value of a column is specified by a DEFAULT clause in the
  123958. ** column definition. This was either supplied by the user when the table
  123959. ** was created, or added later to the table definition by an ALTER TABLE
  123960. ** command. If the latter, then the row-records in the table btree on disk
  123961. ** may not contain a value for the column and the default value, taken
  123962. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  123963. ** If the former, then all row-records are guaranteed to include a value
  123964. ** for the column and the P4 value is not required.
  123965. **
  123966. ** Column definitions created by an ALTER TABLE command may only have
  123967. ** literal default values specified: a number, null or a string. (If a more
  123968. ** complicated default expression value was provided, it is evaluated
  123969. ** when the ALTER TABLE is executed and one of the literal values written
  123970. ** into the sqlite_master table.)
  123971. **
  123972. ** Therefore, the P4 parameter is only required if the default value for
  123973. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  123974. ** function is capable of transforming these types of expressions into
  123975. ** sqlite3_value objects.
  123976. **
  123977. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  123978. ** on register iReg. This is used when an equivalent integer value is
  123979. ** stored in place of an 8-byte floating point value in order to save
  123980. ** space.
  123981. */
  123982. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  123983. assert( pTab!=0 );
  123984. if( !pTab->pSelect ){
  123985. sqlite3_value *pValue = 0;
  123986. u8 enc = ENC(sqlite3VdbeDb(v));
  123987. Column *pCol = &pTab->aCol[i];
  123988. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  123989. assert( i<pTab->nCol );
  123990. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  123991. pCol->affinity, &pValue);
  123992. if( pValue ){
  123993. sqlite3VdbeAppendP4(v, pValue, P4_MEM);
  123994. }
  123995. }
  123996. #ifndef SQLITE_OMIT_FLOATING_POINT
  123997. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  123998. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  123999. }
  124000. #endif
  124001. }
  124002. /*
  124003. ** Check to see if column iCol of index pIdx references any of the
  124004. ** columns defined by aXRef and chngRowid. Return true if it does
  124005. ** and false if not. This is an optimization. False-positives are a
  124006. ** performance degradation, but false-negatives can result in a corrupt
  124007. ** index and incorrect answers.
  124008. **
  124009. ** aXRef[j] will be non-negative if column j of the original table is
  124010. ** being updated. chngRowid will be true if the rowid of the table is
  124011. ** being updated.
  124012. */
  124013. static int indexColumnIsBeingUpdated(
  124014. Index *pIdx, /* The index to check */
  124015. int iCol, /* Which column of the index to check */
  124016. int *aXRef, /* aXRef[j]>=0 if column j is being updated */
  124017. int chngRowid /* true if the rowid is being updated */
  124018. ){
  124019. i16 iIdxCol = pIdx->aiColumn[iCol];
  124020. assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */
  124021. if( iIdxCol>=0 ){
  124022. return aXRef[iIdxCol]>=0;
  124023. }
  124024. assert( iIdxCol==XN_EXPR );
  124025. assert( pIdx->aColExpr!=0 );
  124026. assert( pIdx->aColExpr->a[iCol].pExpr!=0 );
  124027. return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,
  124028. aXRef,chngRowid);
  124029. }
  124030. /*
  124031. ** Check to see if index pIdx is a partial index whose conditional
  124032. ** expression might change values due to an UPDATE. Return true if
  124033. ** the index is subject to change and false if the index is guaranteed
  124034. ** to be unchanged. This is an optimization. False-positives are a
  124035. ** performance degradation, but false-negatives can result in a corrupt
  124036. ** index and incorrect answers.
  124037. **
  124038. ** aXRef[j] will be non-negative if column j of the original table is
  124039. ** being updated. chngRowid will be true if the rowid of the table is
  124040. ** being updated.
  124041. */
  124042. static int indexWhereClauseMightChange(
  124043. Index *pIdx, /* The index to check */
  124044. int *aXRef, /* aXRef[j]>=0 if column j is being updated */
  124045. int chngRowid /* true if the rowid is being updated */
  124046. ){
  124047. if( pIdx->pPartIdxWhere==0 ) return 0;
  124048. return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,
  124049. aXRef, chngRowid);
  124050. }
  124051. /*
  124052. ** Process an UPDATE statement.
  124053. **
  124054. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  124055. ** \_______/ \________/ \______/ \________________/
  124056. * onError pTabList pChanges pWhere
  124057. */
  124058. SQLITE_PRIVATE void sqlite3Update(
  124059. Parse *pParse, /* The parser context */
  124060. SrcList *pTabList, /* The table in which we should change things */
  124061. ExprList *pChanges, /* Things to be changed */
  124062. Expr *pWhere, /* The WHERE clause. May be null */
  124063. int onError, /* How to handle constraint errors */
  124064. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  124065. Expr *pLimit, /* LIMIT clause. May be null */
  124066. Upsert *pUpsert /* ON CONFLICT clause, or null */
  124067. ){
  124068. int i, j; /* Loop counters */
  124069. Table *pTab; /* The table to be updated */
  124070. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  124071. WhereInfo *pWInfo; /* Information about the WHERE clause */
  124072. Vdbe *v; /* The virtual database engine */
  124073. Index *pIdx; /* For looping over indices */
  124074. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  124075. int nIdx; /* Number of indices that need updating */
  124076. int iBaseCur; /* Base cursor number */
  124077. int iDataCur; /* Cursor for the canonical data btree */
  124078. int iIdxCur; /* Cursor for the first index */
  124079. sqlite3 *db; /* The database structure */
  124080. int *aRegIdx = 0; /* First register in array assigned to each index */
  124081. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  124082. ** an expression for the i-th column of the table.
  124083. ** aXRef[i]==-1 if the i-th column is not changed. */
  124084. u8 *aToOpen; /* 1 for tables and indices to be opened */
  124085. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  124086. u8 chngRowid; /* Rowid changed in a normal table */
  124087. u8 chngKey; /* Either chngPk or chngRowid */
  124088. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  124089. AuthContext sContext; /* The authorization context */
  124090. NameContext sNC; /* The name-context to resolve expressions in */
  124091. int iDb; /* Database containing the table being updated */
  124092. int eOnePass; /* ONEPASS_XXX value from where.c */
  124093. int hasFK; /* True if foreign key processing is required */
  124094. int labelBreak; /* Jump here to break out of UPDATE loop */
  124095. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  124096. int flags; /* Flags for sqlite3WhereBegin() */
  124097. #ifndef SQLITE_OMIT_TRIGGER
  124098. int isView; /* True when updating a view (INSTEAD OF trigger) */
  124099. Trigger *pTrigger; /* List of triggers on pTab, if required */
  124100. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  124101. #endif
  124102. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  124103. int iEph = 0; /* Ephemeral table holding all primary key values */
  124104. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  124105. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  124106. int addrOpen = 0; /* Address of OP_OpenEphemeral */
  124107. int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
  124108. i16 nPk = 0; /* Number of components of the PRIMARY KEY */
  124109. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  124110. /* Register Allocations */
  124111. int regRowCount = 0; /* A count of rows changed */
  124112. int regOldRowid = 0; /* The old rowid */
  124113. int regNewRowid = 0; /* The new rowid */
  124114. int regNew = 0; /* Content of the NEW.* table in triggers */
  124115. int regOld = 0; /* Content of OLD.* table in triggers */
  124116. int regRowSet = 0; /* Rowset of rows to be updated */
  124117. int regKey = 0; /* composite PRIMARY KEY value */
  124118. memset(&sContext, 0, sizeof(sContext));
  124119. db = pParse->db;
  124120. if( pParse->nErr || db->mallocFailed ){
  124121. goto update_cleanup;
  124122. }
  124123. assert( pTabList->nSrc==1 );
  124124. /* Locate the table which we want to update.
  124125. */
  124126. pTab = sqlite3SrcListLookup(pParse, pTabList);
  124127. if( pTab==0 ) goto update_cleanup;
  124128. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  124129. /* Figure out if we have any triggers and if the table being
  124130. ** updated is a view.
  124131. */
  124132. #ifndef SQLITE_OMIT_TRIGGER
  124133. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  124134. isView = pTab->pSelect!=0;
  124135. assert( pTrigger || tmask==0 );
  124136. #else
  124137. # define pTrigger 0
  124138. # define isView 0
  124139. # define tmask 0
  124140. #endif
  124141. #ifdef SQLITE_OMIT_VIEW
  124142. # undef isView
  124143. # define isView 0
  124144. #endif
  124145. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  124146. if( !isView ){
  124147. pWhere = sqlite3LimitWhere(
  124148. pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
  124149. );
  124150. pOrderBy = 0;
  124151. pLimit = 0;
  124152. }
  124153. #endif
  124154. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  124155. goto update_cleanup;
  124156. }
  124157. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  124158. goto update_cleanup;
  124159. }
  124160. /* Allocate a cursors for the main database table and for all indices.
  124161. ** The index cursors might not be used, but if they are used they
  124162. ** need to occur right after the database cursor. So go ahead and
  124163. ** allocate enough space, just in case.
  124164. */
  124165. iBaseCur = iDataCur = pParse->nTab++;
  124166. iIdxCur = iDataCur+1;
  124167. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  124168. testcase( pPk!=0 && pPk!=pTab->pIndex );
  124169. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  124170. if( pPk==pIdx ){
  124171. iDataCur = pParse->nTab;
  124172. }
  124173. pParse->nTab++;
  124174. }
  124175. if( pUpsert ){
  124176. /* On an UPSERT, reuse the same cursors already opened by INSERT */
  124177. iDataCur = pUpsert->iDataCur;
  124178. iIdxCur = pUpsert->iIdxCur;
  124179. pParse->nTab = iBaseCur;
  124180. }
  124181. pTabList->a[0].iCursor = iDataCur;
  124182. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  124183. ** Initialize aXRef[] and aToOpen[] to their default values.
  124184. */
  124185. aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  124186. if( aXRef==0 ) goto update_cleanup;
  124187. aRegIdx = aXRef+pTab->nCol;
  124188. aToOpen = (u8*)(aRegIdx+nIdx);
  124189. memset(aToOpen, 1, nIdx+1);
  124190. aToOpen[nIdx+1] = 0;
  124191. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  124192. /* Initialize the name-context */
  124193. memset(&sNC, 0, sizeof(sNC));
  124194. sNC.pParse = pParse;
  124195. sNC.pSrcList = pTabList;
  124196. sNC.uNC.pUpsert = pUpsert;
  124197. sNC.ncFlags = NC_UUpsert;
  124198. /* Resolve the column names in all the expressions of the
  124199. ** of the UPDATE statement. Also find the column index
  124200. ** for each column to be updated in the pChanges array. For each
  124201. ** column to be updated, make sure we have authorization to change
  124202. ** that column.
  124203. */
  124204. chngRowid = chngPk = 0;
  124205. for(i=0; i<pChanges->nExpr; i++){
  124206. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  124207. goto update_cleanup;
  124208. }
  124209. for(j=0; j<pTab->nCol; j++){
  124210. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  124211. if( j==pTab->iPKey ){
  124212. chngRowid = 1;
  124213. pRowidExpr = pChanges->a[i].pExpr;
  124214. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  124215. chngPk = 1;
  124216. }
  124217. aXRef[j] = i;
  124218. break;
  124219. }
  124220. }
  124221. if( j>=pTab->nCol ){
  124222. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  124223. j = -1;
  124224. chngRowid = 1;
  124225. pRowidExpr = pChanges->a[i].pExpr;
  124226. }else{
  124227. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  124228. pParse->checkSchema = 1;
  124229. goto update_cleanup;
  124230. }
  124231. }
  124232. #ifndef SQLITE_OMIT_AUTHORIZATION
  124233. {
  124234. int rc;
  124235. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  124236. j<0 ? "ROWID" : pTab->aCol[j].zName,
  124237. db->aDb[iDb].zDbSName);
  124238. if( rc==SQLITE_DENY ){
  124239. goto update_cleanup;
  124240. }else if( rc==SQLITE_IGNORE ){
  124241. aXRef[j] = -1;
  124242. }
  124243. }
  124244. #endif
  124245. }
  124246. assert( (chngRowid & chngPk)==0 );
  124247. assert( chngRowid==0 || chngRowid==1 );
  124248. assert( chngPk==0 || chngPk==1 );
  124249. chngKey = chngRowid + chngPk;
  124250. /* The SET expressions are not actually used inside the WHERE loop.
  124251. ** So reset the colUsed mask. Unless this is a virtual table. In that
  124252. ** case, set all bits of the colUsed mask (to ensure that the virtual
  124253. ** table implementation makes all columns available).
  124254. */
  124255. pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
  124256. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  124257. /* There is one entry in the aRegIdx[] array for each index on the table
  124258. ** being updated. Fill in aRegIdx[] with a register number that will hold
  124259. ** the key for accessing each index.
  124260. */
  124261. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  124262. int reg;
  124263. if( chngKey || hasFK>1 || pIdx==pPk
  124264. || indexWhereClauseMightChange(pIdx,aXRef,chngRowid)
  124265. ){
  124266. reg = ++pParse->nMem;
  124267. pParse->nMem += pIdx->nColumn;
  124268. }else{
  124269. reg = 0;
  124270. for(i=0; i<pIdx->nKeyCol; i++){
  124271. if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){
  124272. reg = ++pParse->nMem;
  124273. pParse->nMem += pIdx->nColumn;
  124274. if( (onError==OE_Replace)
  124275. || (onError==OE_Default && pIdx->onError==OE_Replace)
  124276. ){
  124277. bReplace = 1;
  124278. }
  124279. break;
  124280. }
  124281. }
  124282. }
  124283. if( reg==0 ) aToOpen[j+1] = 0;
  124284. aRegIdx[j] = reg;
  124285. }
  124286. if( bReplace ){
  124287. /* If REPLACE conflict resolution might be invoked, open cursors on all
  124288. ** indexes in case they are needed to delete records. */
  124289. memset(aToOpen, 1, nIdx+1);
  124290. }
  124291. /* Begin generating code. */
  124292. v = sqlite3GetVdbe(pParse);
  124293. if( v==0 ) goto update_cleanup;
  124294. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  124295. sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
  124296. /* Allocate required registers. */
  124297. if( !IsVirtual(pTab) ){
  124298. regRowSet = ++pParse->nMem;
  124299. regOldRowid = regNewRowid = ++pParse->nMem;
  124300. if( chngPk || pTrigger || hasFK ){
  124301. regOld = pParse->nMem + 1;
  124302. pParse->nMem += pTab->nCol;
  124303. }
  124304. if( chngKey || pTrigger || hasFK ){
  124305. regNewRowid = ++pParse->nMem;
  124306. }
  124307. regNew = pParse->nMem + 1;
  124308. pParse->nMem += pTab->nCol;
  124309. }
  124310. /* Start the view context. */
  124311. if( isView ){
  124312. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  124313. }
  124314. /* If we are trying to update a view, realize that view into
  124315. ** an ephemeral table.
  124316. */
  124317. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  124318. if( isView ){
  124319. sqlite3MaterializeView(pParse, pTab,
  124320. pWhere, pOrderBy, pLimit, iDataCur
  124321. );
  124322. pOrderBy = 0;
  124323. pLimit = 0;
  124324. }
  124325. #endif
  124326. /* Resolve the column names in all the expressions in the
  124327. ** WHERE clause.
  124328. */
  124329. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  124330. goto update_cleanup;
  124331. }
  124332. #ifndef SQLITE_OMIT_VIRTUALTABLE
  124333. /* Virtual tables must be handled separately */
  124334. if( IsVirtual(pTab) ){
  124335. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  124336. pWhere, onError);
  124337. goto update_cleanup;
  124338. }
  124339. #endif
  124340. /* Jump to labelBreak to abandon further processing of this UPDATE */
  124341. labelContinue = labelBreak = sqlite3VdbeMakeLabel(v);
  124342. /* Not an UPSERT. Normal processing. Begin by
  124343. ** initialize the count of updated rows */
  124344. if( (db->flags&SQLITE_CountRows)!=0
  124345. && !pParse->pTriggerTab
  124346. && !pParse->nested
  124347. && pUpsert==0
  124348. ){
  124349. regRowCount = ++pParse->nMem;
  124350. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  124351. }
  124352. if( HasRowid(pTab) ){
  124353. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  124354. }else{
  124355. assert( pPk!=0 );
  124356. nPk = pPk->nKeyCol;
  124357. iPk = pParse->nMem+1;
  124358. pParse->nMem += nPk;
  124359. regKey = ++pParse->nMem;
  124360. if( pUpsert==0 ){
  124361. iEph = pParse->nTab++;
  124362. sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
  124363. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  124364. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  124365. }
  124366. }
  124367. if( pUpsert ){
  124368. /* If this is an UPSERT, then all cursors have already been opened by
  124369. ** the outer INSERT and the data cursor should be pointing at the row
  124370. ** that is to be updated. So bypass the code that searches for the
  124371. ** row(s) to be updated.
  124372. */
  124373. pWInfo = 0;
  124374. eOnePass = ONEPASS_SINGLE;
  124375. sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
  124376. }else{
  124377. /* Begin the database scan.
  124378. **
  124379. ** Do not consider a single-pass strategy for a multi-row update if
  124380. ** there are any triggers or foreign keys to process, or rows may
  124381. ** be deleted as a result of REPLACE conflict handling. Any of these
  124382. ** things might disturb a cursor being used to scan through the table
  124383. ** or index, causing a single-pass approach to malfunction. */
  124384. flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
  124385. if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
  124386. flags |= WHERE_ONEPASS_MULTIROW;
  124387. }
  124388. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
  124389. if( pWInfo==0 ) goto update_cleanup;
  124390. /* A one-pass strategy that might update more than one row may not
  124391. ** be used if any column of the index used for the scan is being
  124392. ** updated. Otherwise, if there is an index on "b", statements like
  124393. ** the following could create an infinite loop:
  124394. **
  124395. ** UPDATE t1 SET b=b+1 WHERE b>?
  124396. **
  124397. ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
  124398. ** strategy that uses an index for which one or more columns are being
  124399. ** updated. */
  124400. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  124401. if( eOnePass!=ONEPASS_SINGLE ){
  124402. sqlite3MultiWrite(pParse);
  124403. if( eOnePass==ONEPASS_MULTI ){
  124404. int iCur = aiCurOnePass[1];
  124405. if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
  124406. eOnePass = ONEPASS_OFF;
  124407. }
  124408. assert( iCur!=iDataCur || !HasRowid(pTab) );
  124409. }
  124410. }
  124411. }
  124412. if( HasRowid(pTab) ){
  124413. /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
  124414. ** mode, write the rowid into the FIFO. In either of the one-pass modes,
  124415. ** leave it in register regOldRowid. */
  124416. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  124417. if( eOnePass==ONEPASS_OFF ){
  124418. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  124419. }
  124420. }else{
  124421. /* Read the PK of the current row into an array of registers. In
  124422. ** ONEPASS_OFF mode, serialize the array into a record and store it in
  124423. ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
  124424. ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
  124425. ** is not required) and leave the PK fields in the array of registers. */
  124426. for(i=0; i<nPk; i++){
  124427. assert( pPk->aiColumn[i]>=0 );
  124428. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
  124429. }
  124430. if( eOnePass ){
  124431. if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
  124432. nKey = nPk;
  124433. regKey = iPk;
  124434. }else{
  124435. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  124436. sqlite3IndexAffinityStr(db, pPk), nPk);
  124437. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
  124438. }
  124439. }
  124440. if( pUpsert==0 ){
  124441. if( eOnePass!=ONEPASS_MULTI ){
  124442. sqlite3WhereEnd(pWInfo);
  124443. }
  124444. if( !isView ){
  124445. int addrOnce = 0;
  124446. /* Open every index that needs updating. */
  124447. if( eOnePass!=ONEPASS_OFF ){
  124448. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  124449. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  124450. }
  124451. if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
  124452. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  124453. }
  124454. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
  124455. aToOpen, 0, 0);
  124456. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  124457. }
  124458. /* Top of the update loop */
  124459. if( eOnePass!=ONEPASS_OFF ){
  124460. if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
  124461. assert( pPk );
  124462. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
  124463. VdbeCoverage(v);
  124464. }
  124465. if( eOnePass!=ONEPASS_SINGLE ){
  124466. labelContinue = sqlite3VdbeMakeLabel(v);
  124467. }
  124468. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  124469. VdbeCoverageIf(v, pPk==0);
  124470. VdbeCoverageIf(v, pPk!=0);
  124471. }else if( pPk ){
  124472. labelContinue = sqlite3VdbeMakeLabel(v);
  124473. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  124474. addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
  124475. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  124476. VdbeCoverage(v);
  124477. }else{
  124478. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet,labelBreak,
  124479. regOldRowid);
  124480. VdbeCoverage(v);
  124481. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  124482. VdbeCoverage(v);
  124483. }
  124484. }
  124485. /* If the rowid value will change, set register regNewRowid to
  124486. ** contain the new value. If the rowid is not being modified,
  124487. ** then regNewRowid is the same register as regOldRowid, which is
  124488. ** already populated. */
  124489. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  124490. if( chngRowid ){
  124491. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  124492. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  124493. }
  124494. /* Compute the old pre-UPDATE content of the row being changed, if that
  124495. ** information is needed */
  124496. if( chngPk || hasFK || pTrigger ){
  124497. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  124498. oldmask |= sqlite3TriggerColmask(pParse,
  124499. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  124500. );
  124501. for(i=0; i<pTab->nCol; i++){
  124502. if( oldmask==0xffffffff
  124503. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  124504. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  124505. ){
  124506. testcase( oldmask!=0xffffffff && i==31 );
  124507. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  124508. }else{
  124509. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  124510. }
  124511. }
  124512. if( chngRowid==0 && pPk==0 ){
  124513. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  124514. }
  124515. }
  124516. /* Populate the array of registers beginning at regNew with the new
  124517. ** row data. This array is used to check constants, create the new
  124518. ** table and index records, and as the values for any new.* references
  124519. ** made by triggers.
  124520. **
  124521. ** If there are one or more BEFORE triggers, then do not populate the
  124522. ** registers associated with columns that are (a) not modified by
  124523. ** this UPDATE statement and (b) not accessed by new.* references. The
  124524. ** values for registers not modified by the UPDATE must be reloaded from
  124525. ** the database after the BEFORE triggers are fired anyway (as the trigger
  124526. ** may have modified them). So not loading those that are not going to
  124527. ** be used eliminates some redundant opcodes.
  124528. */
  124529. newmask = sqlite3TriggerColmask(
  124530. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  124531. );
  124532. for(i=0; i<pTab->nCol; i++){
  124533. if( i==pTab->iPKey ){
  124534. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  124535. }else{
  124536. j = aXRef[i];
  124537. if( j>=0 ){
  124538. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  124539. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  124540. /* This branch loads the value of a column that will not be changed
  124541. ** into a register. This is done if there are no BEFORE triggers, or
  124542. ** if there are one or more BEFORE triggers that use this value via
  124543. ** a new.* reference in a trigger program.
  124544. */
  124545. testcase( i==31 );
  124546. testcase( i==32 );
  124547. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  124548. }else{
  124549. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  124550. }
  124551. }
  124552. }
  124553. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  124554. ** verified. One could argue that this is wrong.
  124555. */
  124556. if( tmask&TRIGGER_BEFORE ){
  124557. sqlite3TableAffinity(v, pTab, regNew);
  124558. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  124559. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  124560. /* The row-trigger may have deleted the row being updated. In this
  124561. ** case, jump to the next row. No updates or AFTER triggers are
  124562. ** required. This behavior - what happens when the row being updated
  124563. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  124564. ** documentation.
  124565. */
  124566. if( pPk ){
  124567. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  124568. VdbeCoverage(v);
  124569. }else{
  124570. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  124571. VdbeCoverage(v);
  124572. }
  124573. /* After-BEFORE-trigger-reload-loop:
  124574. ** If it did not delete it, the BEFORE trigger may still have modified
  124575. ** some of the columns of the row being updated. Load the values for
  124576. ** all columns not modified by the update statement into their registers
  124577. ** in case this has happened. Only unmodified columns are reloaded.
  124578. ** The values computed for modified columns use the values before the
  124579. ** BEFORE trigger runs. See test case trigger1-18.0 (added 2018-04-26)
  124580. ** for an example.
  124581. */
  124582. for(i=0; i<pTab->nCol; i++){
  124583. if( aXRef[i]<0 && i!=pTab->iPKey ){
  124584. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  124585. }
  124586. }
  124587. }
  124588. if( !isView ){
  124589. int addr1 = 0; /* Address of jump instruction */
  124590. /* Do constraint checks. */
  124591. assert( regOldRowid>0 );
  124592. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  124593. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
  124594. aXRef, 0);
  124595. /* Do FK constraint checks. */
  124596. if( hasFK ){
  124597. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  124598. }
  124599. /* Delete the index entries associated with the current record. */
  124600. if( bReplace || chngKey ){
  124601. if( pPk ){
  124602. addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  124603. }else{
  124604. addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  124605. }
  124606. VdbeCoverageNeverTaken(v);
  124607. }
  124608. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  124609. /* If changing the rowid value, or if there are foreign key constraints
  124610. ** to process, delete the old record. Otherwise, add a noop OP_Delete
  124611. ** to invoke the pre-update hook.
  124612. **
  124613. ** That (regNew==regnewRowid+1) is true is also important for the
  124614. ** pre-update hook. If the caller invokes preupdate_new(), the returned
  124615. ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
  124616. ** is the column index supplied by the user.
  124617. */
  124618. assert( regNew==regNewRowid+1 );
  124619. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  124620. sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
  124621. OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
  124622. regNewRowid
  124623. );
  124624. if( eOnePass==ONEPASS_MULTI ){
  124625. assert( hasFK==0 && chngKey==0 );
  124626. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  124627. }
  124628. if( !pParse->nested ){
  124629. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  124630. }
  124631. #else
  124632. if( hasFK>1 || chngKey ){
  124633. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  124634. }
  124635. #endif
  124636. if( bReplace || chngKey ){
  124637. sqlite3VdbeJumpHere(v, addr1);
  124638. }
  124639. if( hasFK ){
  124640. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  124641. }
  124642. /* Insert the new index entries and the new record. */
  124643. sqlite3CompleteInsertion(
  124644. pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
  124645. OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
  124646. 0, 0
  124647. );
  124648. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  124649. ** handle rows (possibly in other tables) that refer via a foreign key
  124650. ** to the row just updated. */
  124651. if( hasFK ){
  124652. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  124653. }
  124654. }
  124655. /* Increment the row counter
  124656. */
  124657. if( regRowCount ){
  124658. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  124659. }
  124660. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  124661. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  124662. /* Repeat the above with the next record to be updated, until
  124663. ** all record selected by the WHERE clause have been updated.
  124664. */
  124665. if( eOnePass==ONEPASS_SINGLE ){
  124666. /* Nothing to do at end-of-loop for a single-pass */
  124667. }else if( eOnePass==ONEPASS_MULTI ){
  124668. sqlite3VdbeResolveLabel(v, labelContinue);
  124669. sqlite3WhereEnd(pWInfo);
  124670. }else if( pPk ){
  124671. sqlite3VdbeResolveLabel(v, labelContinue);
  124672. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  124673. }else{
  124674. sqlite3VdbeGoto(v, labelContinue);
  124675. }
  124676. sqlite3VdbeResolveLabel(v, labelBreak);
  124677. /* Update the sqlite_sequence table by storing the content of the
  124678. ** maximum rowid counter values recorded while inserting into
  124679. ** autoincrement tables.
  124680. */
  124681. if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
  124682. sqlite3AutoincrementEnd(pParse);
  124683. }
  124684. /*
  124685. ** Return the number of rows that were changed, if we are tracking
  124686. ** that information.
  124687. */
  124688. if( regRowCount ){
  124689. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  124690. sqlite3VdbeSetNumCols(v, 1);
  124691. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  124692. }
  124693. update_cleanup:
  124694. sqlite3AuthContextPop(&sContext);
  124695. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  124696. sqlite3SrcListDelete(db, pTabList);
  124697. sqlite3ExprListDelete(db, pChanges);
  124698. sqlite3ExprDelete(db, pWhere);
  124699. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  124700. sqlite3ExprListDelete(db, pOrderBy);
  124701. sqlite3ExprDelete(db, pLimit);
  124702. #endif
  124703. return;
  124704. }
  124705. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  124706. ** they may interfere with compilation of other functions in this file
  124707. ** (or in another file, if this file becomes part of the amalgamation). */
  124708. #ifdef isView
  124709. #undef isView
  124710. #endif
  124711. #ifdef pTrigger
  124712. #undef pTrigger
  124713. #endif
  124714. #ifndef SQLITE_OMIT_VIRTUALTABLE
  124715. /*
  124716. ** Generate code for an UPDATE of a virtual table.
  124717. **
  124718. ** There are two possible strategies - the default and the special
  124719. ** "onepass" strategy. Onepass is only used if the virtual table
  124720. ** implementation indicates that pWhere may match at most one row.
  124721. **
  124722. ** The default strategy is to create an ephemeral table that contains
  124723. ** for each row to be changed:
  124724. **
  124725. ** (A) The original rowid of that row.
  124726. ** (B) The revised rowid for the row.
  124727. ** (C) The content of every column in the row.
  124728. **
  124729. ** Then loop through the contents of this ephemeral table executing a
  124730. ** VUpdate for each row. When finished, drop the ephemeral table.
  124731. **
  124732. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  124733. ** stores the same values (A, B and C above) in a register array and
  124734. ** makes a single invocation of VUpdate.
  124735. */
  124736. static void updateVirtualTable(
  124737. Parse *pParse, /* The parsing context */
  124738. SrcList *pSrc, /* The virtual table to be modified */
  124739. Table *pTab, /* The virtual table */
  124740. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  124741. Expr *pRowid, /* Expression used to recompute the rowid */
  124742. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  124743. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  124744. int onError /* ON CONFLICT strategy */
  124745. ){
  124746. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  124747. int ephemTab; /* Table holding the result of the SELECT */
  124748. int i; /* Loop counter */
  124749. sqlite3 *db = pParse->db; /* Database connection */
  124750. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  124751. WhereInfo *pWInfo;
  124752. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  124753. int regArg; /* First register in VUpdate arg array */
  124754. int regRec; /* Register in which to assemble record */
  124755. int regRowid; /* Register for ephem table rowid */
  124756. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  124757. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  124758. int eOnePass; /* True to use onepass strategy */
  124759. int addr; /* Address of OP_OpenEphemeral */
  124760. /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
  124761. ** create and open the ephemeral table in which the records created from
  124762. ** these arguments will be temporarily stored. */
  124763. assert( v );
  124764. ephemTab = pParse->nTab++;
  124765. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  124766. regArg = pParse->nMem + 1;
  124767. pParse->nMem += nArg;
  124768. regRec = ++pParse->nMem;
  124769. regRowid = ++pParse->nMem;
  124770. /* Start scanning the virtual table */
  124771. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  124772. if( pWInfo==0 ) return;
  124773. /* Populate the argument registers. */
  124774. for(i=0; i<pTab->nCol; i++){
  124775. if( aXRef[i]>=0 ){
  124776. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  124777. }else{
  124778. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  124779. sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* Enable sqlite3_vtab_nochange() */
  124780. }
  124781. }
  124782. if( HasRowid(pTab) ){
  124783. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  124784. if( pRowid ){
  124785. sqlite3ExprCode(pParse, pRowid, regArg+1);
  124786. }else{
  124787. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  124788. }
  124789. }else{
  124790. Index *pPk; /* PRIMARY KEY index */
  124791. i16 iPk; /* PRIMARY KEY column */
  124792. pPk = sqlite3PrimaryKeyIndex(pTab);
  124793. assert( pPk!=0 );
  124794. assert( pPk->nKeyCol==1 );
  124795. iPk = pPk->aiColumn[0];
  124796. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
  124797. sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
  124798. }
  124799. eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  124800. /* There is no ONEPASS_MULTI on virtual tables */
  124801. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  124802. if( eOnePass ){
  124803. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  124804. ** above. */
  124805. sqlite3VdbeChangeToNoop(v, addr);
  124806. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  124807. }else{
  124808. /* Create a record from the argument register contents and insert it into
  124809. ** the ephemeral table. */
  124810. sqlite3MultiWrite(pParse);
  124811. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  124812. #ifdef SQLITE_DEBUG
  124813. /* Signal an assert() within OP_MakeRecord that it is allowed to
  124814. ** accept no-change records with serial_type 10 */
  124815. sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
  124816. #endif
  124817. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  124818. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  124819. }
  124820. if( eOnePass==ONEPASS_OFF ){
  124821. /* End the virtual table scan */
  124822. sqlite3WhereEnd(pWInfo);
  124823. /* Begin scannning through the ephemeral table. */
  124824. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  124825. /* Extract arguments from the current row of the ephemeral table and
  124826. ** invoke the VUpdate method. */
  124827. for(i=0; i<nArg; i++){
  124828. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  124829. }
  124830. }
  124831. sqlite3VtabMakeWritable(pParse, pTab);
  124832. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  124833. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  124834. sqlite3MayAbort(pParse);
  124835. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  124836. ** jump to here if the scan visited zero rows. */
  124837. if( eOnePass==ONEPASS_OFF ){
  124838. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  124839. sqlite3VdbeJumpHere(v, addr);
  124840. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  124841. }else{
  124842. sqlite3WhereEnd(pWInfo);
  124843. }
  124844. }
  124845. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  124846. /************** End of update.c **********************************************/
  124847. /************** Begin file upsert.c ******************************************/
  124848. /*
  124849. ** 2018-04-12
  124850. **
  124851. ** The author disclaims copyright to this source code. In place of
  124852. ** a legal notice, here is a blessing:
  124853. **
  124854. ** May you do good and not evil.
  124855. ** May you find forgiveness for yourself and forgive others.
  124856. ** May you share freely, never taking more than you give.
  124857. **
  124858. *************************************************************************
  124859. ** This file contains code to implement various aspects of UPSERT
  124860. ** processing and handling of the Upsert object.
  124861. */
  124862. /* #include "sqliteInt.h" */
  124863. #ifndef SQLITE_OMIT_UPSERT
  124864. /*
  124865. ** Free a list of Upsert objects
  124866. */
  124867. SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3 *db, Upsert *p){
  124868. if( p ){
  124869. sqlite3ExprListDelete(db, p->pUpsertTarget);
  124870. sqlite3ExprDelete(db, p->pUpsertTargetWhere);
  124871. sqlite3ExprListDelete(db, p->pUpsertSet);
  124872. sqlite3ExprDelete(db, p->pUpsertWhere);
  124873. sqlite3DbFree(db, p);
  124874. }
  124875. }
  124876. /*
  124877. ** Duplicate an Upsert object.
  124878. */
  124879. SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3 *db, Upsert *p){
  124880. if( p==0 ) return 0;
  124881. return sqlite3UpsertNew(db,
  124882. sqlite3ExprListDup(db, p->pUpsertTarget, 0),
  124883. sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),
  124884. sqlite3ExprListDup(db, p->pUpsertSet, 0),
  124885. sqlite3ExprDup(db, p->pUpsertWhere, 0)
  124886. );
  124887. }
  124888. /*
  124889. ** Create a new Upsert object.
  124890. */
  124891. SQLITE_PRIVATE Upsert *sqlite3UpsertNew(
  124892. sqlite3 *db, /* Determines which memory allocator to use */
  124893. ExprList *pTarget, /* Target argument to ON CONFLICT, or NULL */
  124894. Expr *pTargetWhere, /* Optional WHERE clause on the target */
  124895. ExprList *pSet, /* UPDATE columns, or NULL for a DO NOTHING */
  124896. Expr *pWhere /* WHERE clause for the ON CONFLICT UPDATE */
  124897. ){
  124898. Upsert *pNew;
  124899. pNew = sqlite3DbMallocRaw(db, sizeof(Upsert));
  124900. if( pNew==0 ){
  124901. sqlite3ExprListDelete(db, pTarget);
  124902. sqlite3ExprDelete(db, pTargetWhere);
  124903. sqlite3ExprListDelete(db, pSet);
  124904. sqlite3ExprDelete(db, pWhere);
  124905. return 0;
  124906. }else{
  124907. pNew->pUpsertTarget = pTarget;
  124908. pNew->pUpsertTargetWhere = pTargetWhere;
  124909. pNew->pUpsertSet = pSet;
  124910. pNew->pUpsertWhere = pWhere;
  124911. pNew->pUpsertIdx = 0;
  124912. }
  124913. return pNew;
  124914. }
  124915. /*
  124916. ** Analyze the ON CONFLICT clause described by pUpsert. Resolve all
  124917. ** symbols in the conflict-target.
  124918. **
  124919. ** Return SQLITE_OK if everything works, or an error code is something
  124920. ** is wrong.
  124921. */
  124922. SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(
  124923. Parse *pParse, /* The parsing context */
  124924. SrcList *pTabList, /* Table into which we are inserting */
  124925. Upsert *pUpsert /* The ON CONFLICT clauses */
  124926. ){
  124927. Table *pTab; /* That table into which we are inserting */
  124928. int rc; /* Result code */
  124929. int iCursor; /* Cursor used by pTab */
  124930. Index *pIdx; /* One of the indexes of pTab */
  124931. ExprList *pTarget; /* The conflict-target clause */
  124932. Expr *pTerm; /* One term of the conflict-target clause */
  124933. NameContext sNC; /* Context for resolving symbolic names */
  124934. Expr sCol[2]; /* Index column converted into an Expr */
  124935. assert( pTabList->nSrc==1 );
  124936. assert( pTabList->a[0].pTab!=0 );
  124937. assert( pUpsert!=0 );
  124938. assert( pUpsert->pUpsertTarget!=0 );
  124939. /* Resolve all symbolic names in the conflict-target clause, which
  124940. ** includes both the list of columns and the optional partial-index
  124941. ** WHERE clause.
  124942. */
  124943. memset(&sNC, 0, sizeof(sNC));
  124944. sNC.pParse = pParse;
  124945. sNC.pSrcList = pTabList;
  124946. rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
  124947. if( rc ) return rc;
  124948. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
  124949. if( rc ) return rc;
  124950. /* Check to see if the conflict target matches the rowid. */
  124951. pTab = pTabList->a[0].pTab;
  124952. pTarget = pUpsert->pUpsertTarget;
  124953. iCursor = pTabList->a[0].iCursor;
  124954. if( HasRowid(pTab)
  124955. && pTarget->nExpr==1
  124956. && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
  124957. && pTerm->iColumn==XN_ROWID
  124958. ){
  124959. /* The conflict-target is the rowid of the primary table */
  124960. assert( pUpsert->pUpsertIdx==0 );
  124961. return SQLITE_OK;
  124962. }
  124963. /* Initialize sCol[0..1] to be an expression parse tree for a
  124964. ** single column of an index. The sCol[0] node will be the TK_COLLATE
  124965. ** operator and sCol[1] will be the TK_COLUMN operator. Code below
  124966. ** will populate the specific collation and column number values
  124967. ** prior to comparing against the conflict-target expression.
  124968. */
  124969. memset(sCol, 0, sizeof(sCol));
  124970. sCol[0].op = TK_COLLATE;
  124971. sCol[0].pLeft = &sCol[1];
  124972. sCol[1].op = TK_COLUMN;
  124973. sCol[1].iTable = pTabList->a[0].iCursor;
  124974. /* Check for matches against other indexes */
  124975. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  124976. int ii, jj, nn;
  124977. if( !IsUniqueIndex(pIdx) ) continue;
  124978. if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
  124979. if( pIdx->pPartIdxWhere ){
  124980. if( pUpsert->pUpsertTargetWhere==0 ) continue;
  124981. if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
  124982. pIdx->pPartIdxWhere, iCursor)!=0 ){
  124983. continue;
  124984. }
  124985. }
  124986. nn = pIdx->nKeyCol;
  124987. for(ii=0; ii<nn; ii++){
  124988. Expr *pExpr;
  124989. sCol[0].u.zToken = (char*)pIdx->azColl[ii];
  124990. if( pIdx->aiColumn[ii]==XN_EXPR ){
  124991. assert( pIdx->aColExpr!=0 );
  124992. assert( pIdx->aColExpr->nExpr>ii );
  124993. pExpr = pIdx->aColExpr->a[ii].pExpr;
  124994. if( pExpr->op!=TK_COLLATE ){
  124995. sCol[0].pLeft = pExpr;
  124996. pExpr = &sCol[0];
  124997. }
  124998. }else{
  124999. sCol[0].pLeft = &sCol[1];
  125000. sCol[1].iColumn = pIdx->aiColumn[ii];
  125001. pExpr = &sCol[0];
  125002. }
  125003. for(jj=0; jj<nn; jj++){
  125004. if( sqlite3ExprCompare(pParse, pTarget->a[jj].pExpr, pExpr,iCursor)<2 ){
  125005. break; /* Column ii of the index matches column jj of target */
  125006. }
  125007. }
  125008. if( jj>=nn ){
  125009. /* The target contains no match for column jj of the index */
  125010. break;
  125011. }
  125012. }
  125013. if( ii<nn ){
  125014. /* Column ii of the index did not match any term of the conflict target.
  125015. ** Continue the search with the next index. */
  125016. continue;
  125017. }
  125018. pUpsert->pUpsertIdx = pIdx;
  125019. return SQLITE_OK;
  125020. }
  125021. sqlite3ErrorMsg(pParse, "ON CONFLICT clause does not match any "
  125022. "PRIMARY KEY or UNIQUE constraint");
  125023. return SQLITE_ERROR;
  125024. }
  125025. /*
  125026. ** Generate bytecode that does an UPDATE as part of an upsert.
  125027. **
  125028. ** If pIdx is NULL, then the UNIQUE constraint that failed was the IPK.
  125029. ** In this case parameter iCur is a cursor open on the table b-tree that
  125030. ** currently points to the conflicting table row. Otherwise, if pIdx
  125031. ** is not NULL, then pIdx is the constraint that failed and iCur is a
  125032. ** cursor points to the conflicting row.
  125033. */
  125034. SQLITE_PRIVATE void sqlite3UpsertDoUpdate(
  125035. Parse *pParse, /* The parsing and code-generating context */
  125036. Upsert *pUpsert, /* The ON CONFLICT clause for the upsert */
  125037. Table *pTab, /* The table being updated */
  125038. Index *pIdx, /* The UNIQUE constraint that failed */
  125039. int iCur /* Cursor for pIdx (or pTab if pIdx==NULL) */
  125040. ){
  125041. Vdbe *v = pParse->pVdbe;
  125042. sqlite3 *db = pParse->db;
  125043. SrcList *pSrc; /* FROM clause for the UPDATE */
  125044. int iDataCur;
  125045. assert( v!=0 );
  125046. assert( pUpsert!=0 );
  125047. VdbeNoopComment((v, "Begin DO UPDATE of UPSERT"));
  125048. iDataCur = pUpsert->iDataCur;
  125049. if( pIdx && iCur!=iDataCur ){
  125050. if( HasRowid(pTab) ){
  125051. int regRowid = sqlite3GetTempReg(pParse);
  125052. sqlite3VdbeAddOp2(v, OP_IdxRowid, iCur, regRowid);
  125053. sqlite3VdbeAddOp3(v, OP_SeekRowid, iDataCur, 0, regRowid);
  125054. VdbeCoverage(v);
  125055. sqlite3ReleaseTempReg(pParse, regRowid);
  125056. }else{
  125057. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  125058. int nPk = pPk->nKeyCol;
  125059. int iPk = pParse->nMem+1;
  125060. int i;
  125061. pParse->nMem += nPk;
  125062. for(i=0; i<nPk; i++){
  125063. int k;
  125064. assert( pPk->aiColumn[i]>=0 );
  125065. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  125066. sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);
  125067. VdbeComment((v, "%s.%s", pIdx->zName,
  125068. pTab->aCol[pPk->aiColumn[i]].zName));
  125069. }
  125070. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  125071. i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);
  125072. VdbeCoverage(v);
  125073. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0,
  125074. "corrupt database", P4_STATIC);
  125075. sqlite3VdbeJumpHere(v, i);
  125076. }
  125077. }
  125078. /* pUpsert does not own pUpsertSrc - the outer INSERT statement does. So
  125079. ** we have to make a copy before passing it down into sqlite3Update() */
  125080. pSrc = sqlite3SrcListDup(db, pUpsert->pUpsertSrc, 0);
  125081. sqlite3Update(pParse, pSrc, pUpsert->pUpsertSet,
  125082. pUpsert->pUpsertWhere, OE_Abort, 0, 0, pUpsert);
  125083. pUpsert->pUpsertSet = 0; /* Will have been deleted by sqlite3Update() */
  125084. pUpsert->pUpsertWhere = 0; /* Will have been deleted by sqlite3Update() */
  125085. VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
  125086. }
  125087. #endif /* SQLITE_OMIT_UPSERT */
  125088. /************** End of upsert.c **********************************************/
  125089. /************** Begin file vacuum.c ******************************************/
  125090. /*
  125091. ** 2003 April 6
  125092. **
  125093. ** The author disclaims copyright to this source code. In place of
  125094. ** a legal notice, here is a blessing:
  125095. **
  125096. ** May you do good and not evil.
  125097. ** May you find forgiveness for yourself and forgive others.
  125098. ** May you share freely, never taking more than you give.
  125099. **
  125100. *************************************************************************
  125101. ** This file contains code used to implement the VACUUM command.
  125102. **
  125103. ** Most of the code in this file may be omitted by defining the
  125104. ** SQLITE_OMIT_VACUUM macro.
  125105. */
  125106. /* #include "sqliteInt.h" */
  125107. /* #include "vdbeInt.h" */
  125108. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  125109. /*
  125110. ** Execute zSql on database db.
  125111. **
  125112. ** If zSql returns rows, then each row will have exactly one
  125113. ** column. (This will only happen if zSql begins with "SELECT".)
  125114. ** Take each row of result and call execSql() again recursively.
  125115. **
  125116. ** The execSqlF() routine does the same thing, except it accepts
  125117. ** a format string as its third argument
  125118. */
  125119. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  125120. sqlite3_stmt *pStmt;
  125121. int rc;
  125122. /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
  125123. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  125124. if( rc!=SQLITE_OK ) return rc;
  125125. while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  125126. const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
  125127. assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
  125128. /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX,
  125129. ** or INSERT. Historically there have been attacks that first
  125130. ** corrupt the sqlite_master.sql field with other kinds of statements
  125131. ** then run VACUUM to get those statements to execute at inappropriate
  125132. ** times. */
  125133. if( zSubSql
  125134. && (strncmp(zSubSql,"CRE",3)==0 || strncmp(zSubSql,"INS",3)==0)
  125135. ){
  125136. rc = execSql(db, pzErrMsg, zSubSql);
  125137. if( rc!=SQLITE_OK ) break;
  125138. }
  125139. }
  125140. assert( rc!=SQLITE_ROW );
  125141. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  125142. if( rc ){
  125143. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  125144. }
  125145. (void)sqlite3_finalize(pStmt);
  125146. return rc;
  125147. }
  125148. static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
  125149. char *z;
  125150. va_list ap;
  125151. int rc;
  125152. va_start(ap, zSql);
  125153. z = sqlite3VMPrintf(db, zSql, ap);
  125154. va_end(ap);
  125155. if( z==0 ) return SQLITE_NOMEM;
  125156. rc = execSql(db, pzErrMsg, z);
  125157. sqlite3DbFree(db, z);
  125158. return rc;
  125159. }
  125160. /*
  125161. ** The VACUUM command is used to clean up the database,
  125162. ** collapse free space, etc. It is modelled after the VACUUM command
  125163. ** in PostgreSQL. The VACUUM command works as follows:
  125164. **
  125165. ** (1) Create a new transient database file
  125166. ** (2) Copy all content from the database being vacuumed into
  125167. ** the new transient database file
  125168. ** (3) Copy content from the transient database back into the
  125169. ** original database.
  125170. **
  125171. ** The transient database requires temporary disk space approximately
  125172. ** equal to the size of the original database. The copy operation of
  125173. ** step (3) requires additional temporary disk space approximately equal
  125174. ** to the size of the original database for the rollback journal.
  125175. ** Hence, temporary disk space that is approximately 2x the size of the
  125176. ** original database is required. Every page of the database is written
  125177. ** approximately 3 times: Once for step (2) and twice for step (3).
  125178. ** Two writes per page are required in step (3) because the original
  125179. ** database content must be written into the rollback journal prior to
  125180. ** overwriting the database with the vacuumed content.
  125181. **
  125182. ** Only 1x temporary space and only 1x writes would be required if
  125183. ** the copy of step (3) were replaced by deleting the original database
  125184. ** and renaming the transient database as the original. But that will
  125185. ** not work if other processes are attached to the original database.
  125186. ** And a power loss in between deleting the original and renaming the
  125187. ** transient would cause the database file to appear to be deleted
  125188. ** following reboot.
  125189. */
  125190. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
  125191. Vdbe *v = sqlite3GetVdbe(pParse);
  125192. int iDb = 0;
  125193. if( v==0 ) return;
  125194. if( pNm ){
  125195. #ifndef SQLITE_BUG_COMPATIBLE_20160819
  125196. /* Default behavior: Report an error if the argument to VACUUM is
  125197. ** not recognized */
  125198. iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
  125199. if( iDb<0 ) return;
  125200. #else
  125201. /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
  125202. ** to VACUUM are silently ignored. This is a back-out of a bug fix that
  125203. ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
  125204. ** The buggy behavior is required for binary compatibility with some
  125205. ** legacy applications. */
  125206. iDb = sqlite3FindDb(pParse->db, pNm);
  125207. if( iDb<0 ) iDb = 0;
  125208. #endif
  125209. }
  125210. if( iDb!=1 ){
  125211. sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
  125212. sqlite3VdbeUsesBtree(v, iDb);
  125213. }
  125214. return;
  125215. }
  125216. /*
  125217. ** This routine implements the OP_Vacuum opcode of the VDBE.
  125218. */
  125219. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
  125220. int rc = SQLITE_OK; /* Return code from service routines */
  125221. Btree *pMain; /* The database being vacuumed */
  125222. Btree *pTemp; /* The temporary database we vacuum into */
  125223. u16 saved_mDbFlags; /* Saved value of db->mDbFlags */
  125224. u32 saved_flags; /* Saved value of db->flags */
  125225. int saved_nChange; /* Saved value of db->nChange */
  125226. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  125227. u8 saved_mTrace; /* Saved trace settings */
  125228. Db *pDb = 0; /* Database to detach at end of vacuum */
  125229. int isMemDb; /* True if vacuuming a :memory: database */
  125230. int nRes; /* Bytes of reserved space at the end of each page */
  125231. int nDb; /* Number of attached databases */
  125232. const char *zDbMain; /* Schema name of database to vacuum */
  125233. if( !db->autoCommit ){
  125234. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  125235. return SQLITE_ERROR;
  125236. }
  125237. if( db->nVdbeActive>1 ){
  125238. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  125239. return SQLITE_ERROR;
  125240. }
  125241. /* Save the current value of the database flags so that it can be
  125242. ** restored before returning. Then set the writable-schema flag, and
  125243. ** disable CHECK and foreign key constraints. */
  125244. saved_flags = db->flags;
  125245. saved_mDbFlags = db->mDbFlags;
  125246. saved_nChange = db->nChange;
  125247. saved_nTotalChange = db->nTotalChange;
  125248. saved_mTrace = db->mTrace;
  125249. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
  125250. db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
  125251. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder
  125252. | SQLITE_Defensive | SQLITE_CountRows);
  125253. db->mTrace = 0;
  125254. zDbMain = db->aDb[iDb].zDbSName;
  125255. pMain = db->aDb[iDb].pBt;
  125256. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  125257. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  125258. ** can be set to 'off' for this file, as it is not recovered if a crash
  125259. ** occurs anyway. The integrity of the database is maintained by a
  125260. ** (possibly synchronous) transaction opened on the main database before
  125261. ** sqlite3BtreeCopyFile() is called.
  125262. **
  125263. ** An optimisation would be to use a non-journaled pager.
  125264. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  125265. ** that actually made the VACUUM run slower. Very little journalling
  125266. ** actually occurs when doing a vacuum since the vacuum_db is initially
  125267. ** empty. Only the journal header is written. Apparently it takes more
  125268. ** time to parse and run the PRAGMA to turn journalling off than it does
  125269. ** to write the journal header file.
  125270. */
  125271. nDb = db->nDb;
  125272. rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
  125273. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  125274. assert( (db->nDb-1)==nDb );
  125275. pDb = &db->aDb[nDb];
  125276. assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
  125277. pTemp = pDb->pBt;
  125278. /* The call to execSql() to attach the temp database has left the file
  125279. ** locked (as there was more than one active statement when the transaction
  125280. ** to read the schema was concluded. Unlock it here so that this doesn't
  125281. ** cause problems for the call to BtreeSetPageSize() below. */
  125282. sqlite3BtreeCommit(pTemp);
  125283. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  125284. /* A VACUUM cannot change the pagesize of an encrypted database. */
  125285. #ifdef SQLITE_HAS_CODEC
  125286. if( db->nextPagesize ){
  125287. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  125288. int nKey;
  125289. char *zKey;
  125290. sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
  125291. if( nKey ) db->nextPagesize = 0;
  125292. }
  125293. #endif
  125294. sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
  125295. sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
  125296. sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
  125297. /* Begin a transaction and take an exclusive lock on the main database
  125298. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  125299. ** to ensure that we do not try to change the page-size on a WAL database.
  125300. */
  125301. rc = execSql(db, pzErrMsg, "BEGIN");
  125302. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  125303. rc = sqlite3BtreeBeginTrans(pMain, 2, 0);
  125304. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  125305. /* Do not attempt to change the page size for a WAL database */
  125306. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  125307. ==PAGER_JOURNALMODE_WAL ){
  125308. db->nextPagesize = 0;
  125309. }
  125310. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  125311. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  125312. || NEVER(db->mallocFailed)
  125313. ){
  125314. rc = SQLITE_NOMEM_BKPT;
  125315. goto end_of_vacuum;
  125316. }
  125317. #ifndef SQLITE_OMIT_AUTOVACUUM
  125318. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  125319. sqlite3BtreeGetAutoVacuum(pMain));
  125320. #endif
  125321. /* Query the schema of the main database. Create a mirror schema
  125322. ** in the temporary database.
  125323. */
  125324. db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
  125325. rc = execSqlF(db, pzErrMsg,
  125326. "SELECT sql FROM \"%w\".sqlite_master"
  125327. " WHERE type='table'AND name<>'sqlite_sequence'"
  125328. " AND coalesce(rootpage,1)>0",
  125329. zDbMain
  125330. );
  125331. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  125332. rc = execSqlF(db, pzErrMsg,
  125333. "SELECT sql FROM \"%w\".sqlite_master"
  125334. " WHERE type='index'",
  125335. zDbMain
  125336. );
  125337. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  125338. db->init.iDb = 0;
  125339. /* Loop through the tables in the main database. For each, do
  125340. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  125341. ** the contents to the temporary database.
  125342. */
  125343. rc = execSqlF(db, pzErrMsg,
  125344. "SELECT'INSERT INTO vacuum_db.'||quote(name)"
  125345. "||' SELECT*FROM\"%w\".'||quote(name)"
  125346. "FROM vacuum_db.sqlite_master "
  125347. "WHERE type='table'AND coalesce(rootpage,1)>0",
  125348. zDbMain
  125349. );
  125350. assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
  125351. db->mDbFlags &= ~DBFLAG_Vacuum;
  125352. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  125353. /* Copy the triggers, views, and virtual tables from the main database
  125354. ** over to the temporary database. None of these objects has any
  125355. ** associated storage, so all we have to do is copy their entries
  125356. ** from the SQLITE_MASTER table.
  125357. */
  125358. rc = execSqlF(db, pzErrMsg,
  125359. "INSERT INTO vacuum_db.sqlite_master"
  125360. " SELECT*FROM \"%w\".sqlite_master"
  125361. " WHERE type IN('view','trigger')"
  125362. " OR(type='table'AND rootpage=0)",
  125363. zDbMain
  125364. );
  125365. if( rc ) goto end_of_vacuum;
  125366. /* At this point, there is a write transaction open on both the
  125367. ** vacuum database and the main database. Assuming no error occurs,
  125368. ** both transactions are closed by this block - the main database
  125369. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  125370. ** call to sqlite3BtreeCommit().
  125371. */
  125372. {
  125373. u32 meta;
  125374. int i;
  125375. /* This array determines which meta meta values are preserved in the
  125376. ** vacuum. Even entries are the meta value number and odd entries
  125377. ** are an increment to apply to the meta value after the vacuum.
  125378. ** The increment is used to increase the schema cookie so that other
  125379. ** connections to the same database will know to reread the schema.
  125380. */
  125381. static const unsigned char aCopy[] = {
  125382. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  125383. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  125384. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  125385. BTREE_USER_VERSION, 0, /* Preserve the user version */
  125386. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  125387. };
  125388. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  125389. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  125390. /* Copy Btree meta values */
  125391. for(i=0; i<ArraySize(aCopy); i+=2){
  125392. /* GetMeta() and UpdateMeta() cannot fail in this context because
  125393. ** we already have page 1 loaded into cache and marked dirty. */
  125394. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  125395. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  125396. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  125397. }
  125398. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  125399. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  125400. rc = sqlite3BtreeCommit(pTemp);
  125401. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  125402. #ifndef SQLITE_OMIT_AUTOVACUUM
  125403. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  125404. #endif
  125405. }
  125406. assert( rc==SQLITE_OK );
  125407. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  125408. end_of_vacuum:
  125409. /* Restore the original value of db->flags */
  125410. db->init.iDb = 0;
  125411. db->mDbFlags = saved_mDbFlags;
  125412. db->flags = saved_flags;
  125413. db->nChange = saved_nChange;
  125414. db->nTotalChange = saved_nTotalChange;
  125415. db->mTrace = saved_mTrace;
  125416. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  125417. /* Currently there is an SQL level transaction open on the vacuum
  125418. ** database. No locks are held on any other files (since the main file
  125419. ** was committed at the btree level). So it safe to end the transaction
  125420. ** by manually setting the autoCommit flag to true and detaching the
  125421. ** vacuum database. The vacuum_db journal file is deleted when the pager
  125422. ** is closed by the DETACH.
  125423. */
  125424. db->autoCommit = 1;
  125425. if( pDb ){
  125426. sqlite3BtreeClose(pDb->pBt);
  125427. pDb->pBt = 0;
  125428. pDb->pSchema = 0;
  125429. }
  125430. /* This both clears the schemas and reduces the size of the db->aDb[]
  125431. ** array. */
  125432. sqlite3ResetAllSchemasOfConnection(db);
  125433. return rc;
  125434. }
  125435. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  125436. /************** End of vacuum.c **********************************************/
  125437. /************** Begin file vtab.c ********************************************/
  125438. /*
  125439. ** 2006 June 10
  125440. **
  125441. ** The author disclaims copyright to this source code. In place of
  125442. ** a legal notice, here is a blessing:
  125443. **
  125444. ** May you do good and not evil.
  125445. ** May you find forgiveness for yourself and forgive others.
  125446. ** May you share freely, never taking more than you give.
  125447. **
  125448. *************************************************************************
  125449. ** This file contains code used to help implement virtual tables.
  125450. */
  125451. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125452. /* #include "sqliteInt.h" */
  125453. /*
  125454. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  125455. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  125456. ** this struct allocated on the stack. It is used by the implementation of
  125457. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  125458. ** are invoked only from within xCreate and xConnect methods.
  125459. */
  125460. struct VtabCtx {
  125461. VTable *pVTable; /* The virtual table being constructed */
  125462. Table *pTab; /* The Table object to which the virtual table belongs */
  125463. VtabCtx *pPrior; /* Parent context (if any) */
  125464. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  125465. };
  125466. /*
  125467. ** Construct and install a Module object for a virtual table. When this
  125468. ** routine is called, it is guaranteed that all appropriate locks are held
  125469. ** and the module is not already part of the connection.
  125470. */
  125471. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  125472. sqlite3 *db, /* Database in which module is registered */
  125473. const char *zName, /* Name assigned to this module */
  125474. const sqlite3_module *pModule, /* The definition of the module */
  125475. void *pAux, /* Context pointer for xCreate/xConnect */
  125476. void (*xDestroy)(void *) /* Module destructor function */
  125477. ){
  125478. Module *pMod;
  125479. int nName = sqlite3Strlen30(zName);
  125480. pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
  125481. if( pMod==0 ){
  125482. sqlite3OomFault(db);
  125483. }else{
  125484. Module *pDel;
  125485. char *zCopy = (char *)(&pMod[1]);
  125486. memcpy(zCopy, zName, nName+1);
  125487. pMod->zName = zCopy;
  125488. pMod->pModule = pModule;
  125489. pMod->pAux = pAux;
  125490. pMod->xDestroy = xDestroy;
  125491. pMod->pEpoTab = 0;
  125492. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  125493. assert( pDel==0 || pDel==pMod );
  125494. if( pDel ){
  125495. sqlite3OomFault(db);
  125496. sqlite3DbFree(db, pDel);
  125497. pMod = 0;
  125498. }
  125499. }
  125500. return pMod;
  125501. }
  125502. /*
  125503. ** The actual function that does the work of creating a new module.
  125504. ** This function implements the sqlite3_create_module() and
  125505. ** sqlite3_create_module_v2() interfaces.
  125506. */
  125507. static int createModule(
  125508. sqlite3 *db, /* Database in which module is registered */
  125509. const char *zName, /* Name assigned to this module */
  125510. const sqlite3_module *pModule, /* The definition of the module */
  125511. void *pAux, /* Context pointer for xCreate/xConnect */
  125512. void (*xDestroy)(void *) /* Module destructor function */
  125513. ){
  125514. int rc = SQLITE_OK;
  125515. sqlite3_mutex_enter(db->mutex);
  125516. if( sqlite3HashFind(&db->aModule, zName) ){
  125517. rc = SQLITE_MISUSE_BKPT;
  125518. }else{
  125519. (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
  125520. }
  125521. rc = sqlite3ApiExit(db, rc);
  125522. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  125523. sqlite3_mutex_leave(db->mutex);
  125524. return rc;
  125525. }
  125526. /*
  125527. ** External API function used to create a new virtual-table module.
  125528. */
  125529. SQLITE_API int sqlite3_create_module(
  125530. sqlite3 *db, /* Database in which module is registered */
  125531. const char *zName, /* Name assigned to this module */
  125532. const sqlite3_module *pModule, /* The definition of the module */
  125533. void *pAux /* Context pointer for xCreate/xConnect */
  125534. ){
  125535. #ifdef SQLITE_ENABLE_API_ARMOR
  125536. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  125537. #endif
  125538. return createModule(db, zName, pModule, pAux, 0);
  125539. }
  125540. /*
  125541. ** External API function used to create a new virtual-table module.
  125542. */
  125543. SQLITE_API int sqlite3_create_module_v2(
  125544. sqlite3 *db, /* Database in which module is registered */
  125545. const char *zName, /* Name assigned to this module */
  125546. const sqlite3_module *pModule, /* The definition of the module */
  125547. void *pAux, /* Context pointer for xCreate/xConnect */
  125548. void (*xDestroy)(void *) /* Module destructor function */
  125549. ){
  125550. #ifdef SQLITE_ENABLE_API_ARMOR
  125551. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  125552. #endif
  125553. return createModule(db, zName, pModule, pAux, xDestroy);
  125554. }
  125555. /*
  125556. ** Lock the virtual table so that it cannot be disconnected.
  125557. ** Locks nest. Every lock should have a corresponding unlock.
  125558. ** If an unlock is omitted, resources leaks will occur.
  125559. **
  125560. ** If a disconnect is attempted while a virtual table is locked,
  125561. ** the disconnect is deferred until all locks have been removed.
  125562. */
  125563. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  125564. pVTab->nRef++;
  125565. }
  125566. /*
  125567. ** pTab is a pointer to a Table structure representing a virtual-table.
  125568. ** Return a pointer to the VTable object used by connection db to access
  125569. ** this virtual-table, if one has been created, or NULL otherwise.
  125570. */
  125571. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  125572. VTable *pVtab;
  125573. assert( IsVirtual(pTab) );
  125574. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  125575. return pVtab;
  125576. }
  125577. /*
  125578. ** Decrement the ref-count on a virtual table object. When the ref-count
  125579. ** reaches zero, call the xDisconnect() method to delete the object.
  125580. */
  125581. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  125582. sqlite3 *db = pVTab->db;
  125583. assert( db );
  125584. assert( pVTab->nRef>0 );
  125585. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  125586. pVTab->nRef--;
  125587. if( pVTab->nRef==0 ){
  125588. sqlite3_vtab *p = pVTab->pVtab;
  125589. if( p ){
  125590. p->pModule->xDisconnect(p);
  125591. }
  125592. sqlite3DbFree(db, pVTab);
  125593. }
  125594. }
  125595. /*
  125596. ** Table p is a virtual table. This function moves all elements in the
  125597. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  125598. ** database connections to be disconnected at the next opportunity.
  125599. ** Except, if argument db is not NULL, then the entry associated with
  125600. ** connection db is left in the p->pVTable list.
  125601. */
  125602. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  125603. VTable *pRet = 0;
  125604. VTable *pVTable = p->pVTable;
  125605. p->pVTable = 0;
  125606. /* Assert that the mutex (if any) associated with the BtShared database
  125607. ** that contains table p is held by the caller. See header comments
  125608. ** above function sqlite3VtabUnlockList() for an explanation of why
  125609. ** this makes it safe to access the sqlite3.pDisconnect list of any
  125610. ** database connection that may have an entry in the p->pVTable list.
  125611. */
  125612. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  125613. while( pVTable ){
  125614. sqlite3 *db2 = pVTable->db;
  125615. VTable *pNext = pVTable->pNext;
  125616. assert( db2 );
  125617. if( db2==db ){
  125618. pRet = pVTable;
  125619. p->pVTable = pRet;
  125620. pRet->pNext = 0;
  125621. }else{
  125622. pVTable->pNext = db2->pDisconnect;
  125623. db2->pDisconnect = pVTable;
  125624. }
  125625. pVTable = pNext;
  125626. }
  125627. assert( !db || pRet );
  125628. return pRet;
  125629. }
  125630. /*
  125631. ** Table *p is a virtual table. This function removes the VTable object
  125632. ** for table *p associated with database connection db from the linked
  125633. ** list in p->pVTab. It also decrements the VTable ref count. This is
  125634. ** used when closing database connection db to free all of its VTable
  125635. ** objects without disturbing the rest of the Schema object (which may
  125636. ** be being used by other shared-cache connections).
  125637. */
  125638. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  125639. VTable **ppVTab;
  125640. assert( IsVirtual(p) );
  125641. assert( sqlite3BtreeHoldsAllMutexes(db) );
  125642. assert( sqlite3_mutex_held(db->mutex) );
  125643. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  125644. if( (*ppVTab)->db==db ){
  125645. VTable *pVTab = *ppVTab;
  125646. *ppVTab = pVTab->pNext;
  125647. sqlite3VtabUnlock(pVTab);
  125648. break;
  125649. }
  125650. }
  125651. }
  125652. /*
  125653. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  125654. **
  125655. ** This function may only be called when the mutexes associated with all
  125656. ** shared b-tree databases opened using connection db are held by the
  125657. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  125658. ** sqlite3.pDisconnect list is accessed only as follows:
  125659. **
  125660. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  125661. ** associated with the database handle itself must be held.
  125662. **
  125663. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  125664. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  125665. ** associated with the database the virtual table is stored in is held
  125666. ** or, if the virtual table is stored in a non-sharable database, then
  125667. ** the database handle mutex is held.
  125668. **
  125669. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  125670. ** by multiple threads. It is thread-safe.
  125671. */
  125672. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  125673. VTable *p = db->pDisconnect;
  125674. db->pDisconnect = 0;
  125675. assert( sqlite3BtreeHoldsAllMutexes(db) );
  125676. assert( sqlite3_mutex_held(db->mutex) );
  125677. if( p ){
  125678. sqlite3ExpirePreparedStatements(db, 0);
  125679. do {
  125680. VTable *pNext = p->pNext;
  125681. sqlite3VtabUnlock(p);
  125682. p = pNext;
  125683. }while( p );
  125684. }
  125685. }
  125686. /*
  125687. ** Clear any and all virtual-table information from the Table record.
  125688. ** This routine is called, for example, just before deleting the Table
  125689. ** record.
  125690. **
  125691. ** Since it is a virtual-table, the Table structure contains a pointer
  125692. ** to the head of a linked list of VTable structures. Each VTable
  125693. ** structure is associated with a single sqlite3* user of the schema.
  125694. ** The reference count of the VTable structure associated with database
  125695. ** connection db is decremented immediately (which may lead to the
  125696. ** structure being xDisconnected and free). Any other VTable structures
  125697. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  125698. ** database connection.
  125699. */
  125700. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  125701. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  125702. if( p->azModuleArg ){
  125703. int i;
  125704. for(i=0; i<p->nModuleArg; i++){
  125705. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  125706. }
  125707. sqlite3DbFree(db, p->azModuleArg);
  125708. }
  125709. }
  125710. /*
  125711. ** Add a new module argument to pTable->azModuleArg[].
  125712. ** The string is not copied - the pointer is stored. The
  125713. ** string will be freed automatically when the table is
  125714. ** deleted.
  125715. */
  125716. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  125717. int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  125718. char **azModuleArg;
  125719. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  125720. if( azModuleArg==0 ){
  125721. sqlite3DbFree(db, zArg);
  125722. }else{
  125723. int i = pTable->nModuleArg++;
  125724. azModuleArg[i] = zArg;
  125725. azModuleArg[i+1] = 0;
  125726. pTable->azModuleArg = azModuleArg;
  125727. }
  125728. }
  125729. /*
  125730. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  125731. ** statement. The module name has been parsed, but the optional list
  125732. ** of parameters that follow the module name are still pending.
  125733. */
  125734. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  125735. Parse *pParse, /* Parsing context */
  125736. Token *pName1, /* Name of new table, or database name */
  125737. Token *pName2, /* Name of new table or NULL */
  125738. Token *pModuleName, /* Name of the module for the virtual table */
  125739. int ifNotExists /* No error if the table already exists */
  125740. ){
  125741. Table *pTable; /* The new virtual table */
  125742. sqlite3 *db; /* Database connection */
  125743. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  125744. pTable = pParse->pNewTable;
  125745. if( pTable==0 ) return;
  125746. assert( 0==pTable->pIndex );
  125747. db = pParse->db;
  125748. assert( pTable->nModuleArg==0 );
  125749. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  125750. addModuleArgument(db, pTable, 0);
  125751. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  125752. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  125753. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  125754. );
  125755. pParse->sNameToken.n = (int)(
  125756. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  125757. );
  125758. #ifndef SQLITE_OMIT_AUTHORIZATION
  125759. /* Creating a virtual table invokes the authorization callback twice.
  125760. ** The first invocation, to obtain permission to INSERT a row into the
  125761. ** sqlite_master table, has already been made by sqlite3StartTable().
  125762. ** The second call, to obtain permission to create the table, is made now.
  125763. */
  125764. if( pTable->azModuleArg ){
  125765. int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  125766. assert( iDb>=0 ); /* The database the table is being created in */
  125767. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  125768. pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
  125769. }
  125770. #endif
  125771. }
  125772. /*
  125773. ** This routine takes the module argument that has been accumulating
  125774. ** in pParse->zArg[] and appends it to the list of arguments on the
  125775. ** virtual table currently under construction in pParse->pTable.
  125776. */
  125777. static void addArgumentToVtab(Parse *pParse){
  125778. if( pParse->sArg.z && pParse->pNewTable ){
  125779. const char *z = (const char*)pParse->sArg.z;
  125780. int n = pParse->sArg.n;
  125781. sqlite3 *db = pParse->db;
  125782. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  125783. }
  125784. }
  125785. /*
  125786. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  125787. ** has been completely parsed.
  125788. */
  125789. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  125790. Table *pTab = pParse->pNewTable; /* The table being constructed */
  125791. sqlite3 *db = pParse->db; /* The database connection */
  125792. if( pTab==0 ) return;
  125793. addArgumentToVtab(pParse);
  125794. pParse->sArg.z = 0;
  125795. if( pTab->nModuleArg<1 ) return;
  125796. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  125797. ** first time (in other words if the virtual table is actually being
  125798. ** created now instead of just being read out of sqlite_master) then
  125799. ** do additional initialization work and store the statement text
  125800. ** in the sqlite_master table.
  125801. */
  125802. if( !db->init.busy ){
  125803. char *zStmt;
  125804. char *zWhere;
  125805. int iDb;
  125806. int iReg;
  125807. Vdbe *v;
  125808. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  125809. if( pEnd ){
  125810. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  125811. }
  125812. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  125813. /* A slot for the record has already been allocated in the
  125814. ** SQLITE_MASTER table. We just need to update that slot with all
  125815. ** the information we've collected.
  125816. **
  125817. ** The VM register number pParse->regRowid holds the rowid of an
  125818. ** entry in the sqlite_master table tht was created for this vtab
  125819. ** by sqlite3StartTable().
  125820. */
  125821. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  125822. sqlite3NestedParse(pParse,
  125823. "UPDATE %Q.%s "
  125824. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  125825. "WHERE rowid=#%d",
  125826. db->aDb[iDb].zDbSName, MASTER_NAME,
  125827. pTab->zName,
  125828. pTab->zName,
  125829. zStmt,
  125830. pParse->regRowid
  125831. );
  125832. sqlite3DbFree(db, zStmt);
  125833. v = sqlite3GetVdbe(pParse);
  125834. sqlite3ChangeCookie(pParse, iDb);
  125835. sqlite3VdbeAddOp0(v, OP_Expire);
  125836. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  125837. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  125838. iReg = ++pParse->nMem;
  125839. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  125840. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  125841. }
  125842. /* If we are rereading the sqlite_master table create the in-memory
  125843. ** record of the table. The xConnect() method is not called until
  125844. ** the first time the virtual table is used in an SQL statement. This
  125845. ** allows a schema that contains virtual tables to be loaded before
  125846. ** the required virtual table implementations are registered. */
  125847. else {
  125848. Table *pOld;
  125849. Schema *pSchema = pTab->pSchema;
  125850. const char *zName = pTab->zName;
  125851. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  125852. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  125853. if( pOld ){
  125854. sqlite3OomFault(db);
  125855. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  125856. return;
  125857. }
  125858. pParse->pNewTable = 0;
  125859. }
  125860. }
  125861. /*
  125862. ** The parser calls this routine when it sees the first token
  125863. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  125864. */
  125865. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  125866. addArgumentToVtab(pParse);
  125867. pParse->sArg.z = 0;
  125868. pParse->sArg.n = 0;
  125869. }
  125870. /*
  125871. ** The parser calls this routine for each token after the first token
  125872. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  125873. */
  125874. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  125875. Token *pArg = &pParse->sArg;
  125876. if( pArg->z==0 ){
  125877. pArg->z = p->z;
  125878. pArg->n = p->n;
  125879. }else{
  125880. assert(pArg->z <= p->z);
  125881. pArg->n = (int)(&p->z[p->n] - pArg->z);
  125882. }
  125883. }
  125884. /*
  125885. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  125886. ** pointer to the function to invoke is passed as the fourth parameter
  125887. ** to this procedure.
  125888. */
  125889. static int vtabCallConstructor(
  125890. sqlite3 *db,
  125891. Table *pTab,
  125892. Module *pMod,
  125893. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  125894. char **pzErr
  125895. ){
  125896. VtabCtx sCtx;
  125897. VTable *pVTable;
  125898. int rc;
  125899. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  125900. int nArg = pTab->nModuleArg;
  125901. char *zErr = 0;
  125902. char *zModuleName;
  125903. int iDb;
  125904. VtabCtx *pCtx;
  125905. /* Check that the virtual-table is not already being initialized */
  125906. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  125907. if( pCtx->pTab==pTab ){
  125908. *pzErr = sqlite3MPrintf(db,
  125909. "vtable constructor called recursively: %s", pTab->zName
  125910. );
  125911. return SQLITE_LOCKED;
  125912. }
  125913. }
  125914. zModuleName = sqlite3DbStrDup(db, pTab->zName);
  125915. if( !zModuleName ){
  125916. return SQLITE_NOMEM_BKPT;
  125917. }
  125918. pVTable = sqlite3MallocZero(sizeof(VTable));
  125919. if( !pVTable ){
  125920. sqlite3OomFault(db);
  125921. sqlite3DbFree(db, zModuleName);
  125922. return SQLITE_NOMEM_BKPT;
  125923. }
  125924. pVTable->db = db;
  125925. pVTable->pMod = pMod;
  125926. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  125927. pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
  125928. /* Invoke the virtual table constructor */
  125929. assert( &db->pVtabCtx );
  125930. assert( xConstruct );
  125931. sCtx.pTab = pTab;
  125932. sCtx.pVTable = pVTable;
  125933. sCtx.pPrior = db->pVtabCtx;
  125934. sCtx.bDeclared = 0;
  125935. db->pVtabCtx = &sCtx;
  125936. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  125937. db->pVtabCtx = sCtx.pPrior;
  125938. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  125939. assert( sCtx.pTab==pTab );
  125940. if( SQLITE_OK!=rc ){
  125941. if( zErr==0 ){
  125942. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  125943. }else {
  125944. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  125945. sqlite3_free(zErr);
  125946. }
  125947. sqlite3DbFree(db, pVTable);
  125948. }else if( ALWAYS(pVTable->pVtab) ){
  125949. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  125950. ** the sqlite3_vtab object if successful. */
  125951. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  125952. pVTable->pVtab->pModule = pMod->pModule;
  125953. pVTable->nRef = 1;
  125954. if( sCtx.bDeclared==0 ){
  125955. const char *zFormat = "vtable constructor did not declare schema: %s";
  125956. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  125957. sqlite3VtabUnlock(pVTable);
  125958. rc = SQLITE_ERROR;
  125959. }else{
  125960. int iCol;
  125961. u8 oooHidden = 0;
  125962. /* If everything went according to plan, link the new VTable structure
  125963. ** into the linked list headed by pTab->pVTable. Then loop through the
  125964. ** columns of the table to see if any of them contain the token "hidden".
  125965. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  125966. ** the type string. */
  125967. pVTable->pNext = pTab->pVTable;
  125968. pTab->pVTable = pVTable;
  125969. for(iCol=0; iCol<pTab->nCol; iCol++){
  125970. char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
  125971. int nType;
  125972. int i = 0;
  125973. nType = sqlite3Strlen30(zType);
  125974. for(i=0; i<nType; i++){
  125975. if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
  125976. && (i==0 || zType[i-1]==' ')
  125977. && (zType[i+6]=='\0' || zType[i+6]==' ')
  125978. ){
  125979. break;
  125980. }
  125981. }
  125982. if( i<nType ){
  125983. int j;
  125984. int nDel = 6 + (zType[i+6] ? 1 : 0);
  125985. for(j=i; (j+nDel)<=nType; j++){
  125986. zType[j] = zType[j+nDel];
  125987. }
  125988. if( zType[i]=='\0' && i>0 ){
  125989. assert(zType[i-1]==' ');
  125990. zType[i-1] = '\0';
  125991. }
  125992. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  125993. oooHidden = TF_OOOHidden;
  125994. }else{
  125995. pTab->tabFlags |= oooHidden;
  125996. }
  125997. }
  125998. }
  125999. }
  126000. sqlite3DbFree(db, zModuleName);
  126001. return rc;
  126002. }
  126003. /*
  126004. ** This function is invoked by the parser to call the xConnect() method
  126005. ** of the virtual table pTab. If an error occurs, an error code is returned
  126006. ** and an error left in pParse.
  126007. **
  126008. ** This call is a no-op if table pTab is not a virtual table.
  126009. */
  126010. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  126011. sqlite3 *db = pParse->db;
  126012. const char *zMod;
  126013. Module *pMod;
  126014. int rc;
  126015. assert( pTab );
  126016. if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
  126017. return SQLITE_OK;
  126018. }
  126019. /* Locate the required virtual table module */
  126020. zMod = pTab->azModuleArg[0];
  126021. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  126022. if( !pMod ){
  126023. const char *zModule = pTab->azModuleArg[0];
  126024. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  126025. rc = SQLITE_ERROR;
  126026. }else{
  126027. char *zErr = 0;
  126028. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  126029. if( rc!=SQLITE_OK ){
  126030. sqlite3ErrorMsg(pParse, "%s", zErr);
  126031. pParse->rc = rc;
  126032. }
  126033. sqlite3DbFree(db, zErr);
  126034. }
  126035. return rc;
  126036. }
  126037. /*
  126038. ** Grow the db->aVTrans[] array so that there is room for at least one
  126039. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  126040. */
  126041. static int growVTrans(sqlite3 *db){
  126042. const int ARRAY_INCR = 5;
  126043. /* Grow the sqlite3.aVTrans array if required */
  126044. if( (db->nVTrans%ARRAY_INCR)==0 ){
  126045. VTable **aVTrans;
  126046. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  126047. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  126048. if( !aVTrans ){
  126049. return SQLITE_NOMEM_BKPT;
  126050. }
  126051. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  126052. db->aVTrans = aVTrans;
  126053. }
  126054. return SQLITE_OK;
  126055. }
  126056. /*
  126057. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  126058. ** have already been reserved using growVTrans().
  126059. */
  126060. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  126061. /* Add pVtab to the end of sqlite3.aVTrans */
  126062. db->aVTrans[db->nVTrans++] = pVTab;
  126063. sqlite3VtabLock(pVTab);
  126064. }
  126065. /*
  126066. ** This function is invoked by the vdbe to call the xCreate method
  126067. ** of the virtual table named zTab in database iDb.
  126068. **
  126069. ** If an error occurs, *pzErr is set to point to an English language
  126070. ** description of the error and an SQLITE_XXX error code is returned.
  126071. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  126072. */
  126073. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  126074. int rc = SQLITE_OK;
  126075. Table *pTab;
  126076. Module *pMod;
  126077. const char *zMod;
  126078. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  126079. assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
  126080. /* Locate the required virtual table module */
  126081. zMod = pTab->azModuleArg[0];
  126082. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  126083. /* If the module has been registered and includes a Create method,
  126084. ** invoke it now. If the module has not been registered, return an
  126085. ** error. Otherwise, do nothing.
  126086. */
  126087. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  126088. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  126089. rc = SQLITE_ERROR;
  126090. }else{
  126091. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  126092. }
  126093. /* Justification of ALWAYS(): The xConstructor method is required to
  126094. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  126095. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  126096. rc = growVTrans(db);
  126097. if( rc==SQLITE_OK ){
  126098. addToVTrans(db, sqlite3GetVTable(db, pTab));
  126099. }
  126100. }
  126101. return rc;
  126102. }
  126103. /*
  126104. ** This function is used to set the schema of a virtual table. It is only
  126105. ** valid to call this function from within the xCreate() or xConnect() of a
  126106. ** virtual table module.
  126107. */
  126108. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  126109. VtabCtx *pCtx;
  126110. int rc = SQLITE_OK;
  126111. Table *pTab;
  126112. char *zErr = 0;
  126113. Parse sParse;
  126114. #ifdef SQLITE_ENABLE_API_ARMOR
  126115. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  126116. return SQLITE_MISUSE_BKPT;
  126117. }
  126118. #endif
  126119. sqlite3_mutex_enter(db->mutex);
  126120. pCtx = db->pVtabCtx;
  126121. if( !pCtx || pCtx->bDeclared ){
  126122. sqlite3Error(db, SQLITE_MISUSE);
  126123. sqlite3_mutex_leave(db->mutex);
  126124. return SQLITE_MISUSE_BKPT;
  126125. }
  126126. pTab = pCtx->pTab;
  126127. assert( IsVirtual(pTab) );
  126128. memset(&sParse, 0, sizeof(sParse));
  126129. sParse.eParseMode = PARSE_MODE_DECLARE_VTAB;
  126130. sParse.db = db;
  126131. sParse.nQueryLoop = 1;
  126132. if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
  126133. && sParse.pNewTable
  126134. && !db->mallocFailed
  126135. && !sParse.pNewTable->pSelect
  126136. && !IsVirtual(sParse.pNewTable)
  126137. ){
  126138. if( !pTab->aCol ){
  126139. Table *pNew = sParse.pNewTable;
  126140. Index *pIdx;
  126141. pTab->aCol = pNew->aCol;
  126142. pTab->nCol = pNew->nCol;
  126143. pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
  126144. pNew->nCol = 0;
  126145. pNew->aCol = 0;
  126146. assert( pTab->pIndex==0 );
  126147. assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
  126148. if( !HasRowid(pNew)
  126149. && pCtx->pVTable->pMod->pModule->xUpdate!=0
  126150. && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
  126151. ){
  126152. /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
  126153. ** or else must have a single-column PRIMARY KEY */
  126154. rc = SQLITE_ERROR;
  126155. }
  126156. pIdx = pNew->pIndex;
  126157. if( pIdx ){
  126158. assert( pIdx->pNext==0 );
  126159. pTab->pIndex = pIdx;
  126160. pNew->pIndex = 0;
  126161. pIdx->pTable = pTab;
  126162. }
  126163. }
  126164. pCtx->bDeclared = 1;
  126165. }else{
  126166. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  126167. sqlite3DbFree(db, zErr);
  126168. rc = SQLITE_ERROR;
  126169. }
  126170. sParse.eParseMode = PARSE_MODE_NORMAL;
  126171. if( sParse.pVdbe ){
  126172. sqlite3VdbeFinalize(sParse.pVdbe);
  126173. }
  126174. sqlite3DeleteTable(db, sParse.pNewTable);
  126175. sqlite3ParserReset(&sParse);
  126176. assert( (rc&0xff)==rc );
  126177. rc = sqlite3ApiExit(db, rc);
  126178. sqlite3_mutex_leave(db->mutex);
  126179. return rc;
  126180. }
  126181. /*
  126182. ** This function is invoked by the vdbe to call the xDestroy method
  126183. ** of the virtual table named zTab in database iDb. This occurs
  126184. ** when a DROP TABLE is mentioned.
  126185. **
  126186. ** This call is a no-op if zTab is not a virtual table.
  126187. */
  126188. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  126189. int rc = SQLITE_OK;
  126190. Table *pTab;
  126191. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  126192. if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
  126193. VTable *p;
  126194. int (*xDestroy)(sqlite3_vtab *);
  126195. for(p=pTab->pVTable; p; p=p->pNext){
  126196. assert( p->pVtab );
  126197. if( p->pVtab->nRef>0 ){
  126198. return SQLITE_LOCKED;
  126199. }
  126200. }
  126201. p = vtabDisconnectAll(db, pTab);
  126202. xDestroy = p->pMod->pModule->xDestroy;
  126203. assert( xDestroy!=0 ); /* Checked before the virtual table is created */
  126204. rc = xDestroy(p->pVtab);
  126205. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  126206. if( rc==SQLITE_OK ){
  126207. assert( pTab->pVTable==p && p->pNext==0 );
  126208. p->pVtab = 0;
  126209. pTab->pVTable = 0;
  126210. sqlite3VtabUnlock(p);
  126211. }
  126212. }
  126213. return rc;
  126214. }
  126215. /*
  126216. ** This function invokes either the xRollback or xCommit method
  126217. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  126218. ** called is identified by the second argument, "offset", which is
  126219. ** the offset of the method to call in the sqlite3_module structure.
  126220. **
  126221. ** The array is cleared after invoking the callbacks.
  126222. */
  126223. static void callFinaliser(sqlite3 *db, int offset){
  126224. int i;
  126225. if( db->aVTrans ){
  126226. VTable **aVTrans = db->aVTrans;
  126227. db->aVTrans = 0;
  126228. for(i=0; i<db->nVTrans; i++){
  126229. VTable *pVTab = aVTrans[i];
  126230. sqlite3_vtab *p = pVTab->pVtab;
  126231. if( p ){
  126232. int (*x)(sqlite3_vtab *);
  126233. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  126234. if( x ) x(p);
  126235. }
  126236. pVTab->iSavepoint = 0;
  126237. sqlite3VtabUnlock(pVTab);
  126238. }
  126239. sqlite3DbFree(db, aVTrans);
  126240. db->nVTrans = 0;
  126241. }
  126242. }
  126243. /*
  126244. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  126245. ** array. Return the error code for the first error that occurs, or
  126246. ** SQLITE_OK if all xSync operations are successful.
  126247. **
  126248. ** If an error message is available, leave it in p->zErrMsg.
  126249. */
  126250. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  126251. int i;
  126252. int rc = SQLITE_OK;
  126253. VTable **aVTrans = db->aVTrans;
  126254. db->aVTrans = 0;
  126255. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  126256. int (*x)(sqlite3_vtab *);
  126257. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  126258. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  126259. rc = x(pVtab);
  126260. sqlite3VtabImportErrmsg(p, pVtab);
  126261. }
  126262. }
  126263. db->aVTrans = aVTrans;
  126264. return rc;
  126265. }
  126266. /*
  126267. ** Invoke the xRollback method of all virtual tables in the
  126268. ** sqlite3.aVTrans array. Then clear the array itself.
  126269. */
  126270. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  126271. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  126272. return SQLITE_OK;
  126273. }
  126274. /*
  126275. ** Invoke the xCommit method of all virtual tables in the
  126276. ** sqlite3.aVTrans array. Then clear the array itself.
  126277. */
  126278. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  126279. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  126280. return SQLITE_OK;
  126281. }
  126282. /*
  126283. ** If the virtual table pVtab supports the transaction interface
  126284. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  126285. ** not currently open, invoke the xBegin method now.
  126286. **
  126287. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  126288. ** in the sqlite3.aVTrans array.
  126289. */
  126290. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  126291. int rc = SQLITE_OK;
  126292. const sqlite3_module *pModule;
  126293. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  126294. ** than zero, then this function is being called from within a
  126295. ** virtual module xSync() callback. It is illegal to write to
  126296. ** virtual module tables in this case, so return SQLITE_LOCKED.
  126297. */
  126298. if( sqlite3VtabInSync(db) ){
  126299. return SQLITE_LOCKED;
  126300. }
  126301. if( !pVTab ){
  126302. return SQLITE_OK;
  126303. }
  126304. pModule = pVTab->pVtab->pModule;
  126305. if( pModule->xBegin ){
  126306. int i;
  126307. /* If pVtab is already in the aVTrans array, return early */
  126308. for(i=0; i<db->nVTrans; i++){
  126309. if( db->aVTrans[i]==pVTab ){
  126310. return SQLITE_OK;
  126311. }
  126312. }
  126313. /* Invoke the xBegin method. If successful, add the vtab to the
  126314. ** sqlite3.aVTrans[] array. */
  126315. rc = growVTrans(db);
  126316. if( rc==SQLITE_OK ){
  126317. rc = pModule->xBegin(pVTab->pVtab);
  126318. if( rc==SQLITE_OK ){
  126319. int iSvpt = db->nStatement + db->nSavepoint;
  126320. addToVTrans(db, pVTab);
  126321. if( iSvpt && pModule->xSavepoint ){
  126322. pVTab->iSavepoint = iSvpt;
  126323. rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
  126324. }
  126325. }
  126326. }
  126327. }
  126328. return rc;
  126329. }
  126330. /*
  126331. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  126332. ** virtual tables that currently have an open transaction. Pass iSavepoint
  126333. ** as the second argument to the virtual table method invoked.
  126334. **
  126335. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  126336. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  126337. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  126338. ** an open transaction is invoked.
  126339. **
  126340. ** If any virtual table method returns an error code other than SQLITE_OK,
  126341. ** processing is abandoned and the error returned to the caller of this
  126342. ** function immediately. If all calls to virtual table methods are successful,
  126343. ** SQLITE_OK is returned.
  126344. */
  126345. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  126346. int rc = SQLITE_OK;
  126347. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  126348. assert( iSavepoint>=-1 );
  126349. if( db->aVTrans ){
  126350. int i;
  126351. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  126352. VTable *pVTab = db->aVTrans[i];
  126353. const sqlite3_module *pMod = pVTab->pMod->pModule;
  126354. if( pVTab->pVtab && pMod->iVersion>=2 ){
  126355. int (*xMethod)(sqlite3_vtab *, int);
  126356. switch( op ){
  126357. case SAVEPOINT_BEGIN:
  126358. xMethod = pMod->xSavepoint;
  126359. pVTab->iSavepoint = iSavepoint+1;
  126360. break;
  126361. case SAVEPOINT_ROLLBACK:
  126362. xMethod = pMod->xRollbackTo;
  126363. break;
  126364. default:
  126365. xMethod = pMod->xRelease;
  126366. break;
  126367. }
  126368. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  126369. rc = xMethod(pVTab->pVtab, iSavepoint);
  126370. }
  126371. }
  126372. }
  126373. }
  126374. return rc;
  126375. }
  126376. /*
  126377. ** The first parameter (pDef) is a function implementation. The
  126378. ** second parameter (pExpr) is the first argument to this function.
  126379. ** If pExpr is a column in a virtual table, then let the virtual
  126380. ** table implementation have an opportunity to overload the function.
  126381. **
  126382. ** This routine is used to allow virtual table implementations to
  126383. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  126384. **
  126385. ** Return either the pDef argument (indicating no change) or a
  126386. ** new FuncDef structure that is marked as ephemeral using the
  126387. ** SQLITE_FUNC_EPHEM flag.
  126388. */
  126389. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  126390. sqlite3 *db, /* Database connection for reporting malloc problems */
  126391. FuncDef *pDef, /* Function to possibly overload */
  126392. int nArg, /* Number of arguments to the function */
  126393. Expr *pExpr /* First argument to the function */
  126394. ){
  126395. Table *pTab;
  126396. sqlite3_vtab *pVtab;
  126397. sqlite3_module *pMod;
  126398. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  126399. void *pArg = 0;
  126400. FuncDef *pNew;
  126401. int rc = 0;
  126402. /* Check to see the left operand is a column in a virtual table */
  126403. if( NEVER(pExpr==0) ) return pDef;
  126404. if( pExpr->op!=TK_COLUMN ) return pDef;
  126405. pTab = pExpr->y.pTab;
  126406. if( pTab==0 ) return pDef;
  126407. if( !IsVirtual(pTab) ) return pDef;
  126408. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  126409. assert( pVtab!=0 );
  126410. assert( pVtab->pModule!=0 );
  126411. pMod = (sqlite3_module *)pVtab->pModule;
  126412. if( pMod->xFindFunction==0 ) return pDef;
  126413. /* Call the xFindFunction method on the virtual table implementation
  126414. ** to see if the implementation wants to overload this function.
  126415. **
  126416. ** Though undocumented, we have historically always invoked xFindFunction
  126417. ** with an all lower-case function name. Continue in this tradition to
  126418. ** avoid any chance of an incompatibility.
  126419. */
  126420. #ifdef SQLITE_DEBUG
  126421. {
  126422. int i;
  126423. for(i=0; pDef->zName[i]; i++){
  126424. unsigned char x = (unsigned char)pDef->zName[i];
  126425. assert( x==sqlite3UpperToLower[x] );
  126426. }
  126427. }
  126428. #endif
  126429. rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);
  126430. if( rc==0 ){
  126431. return pDef;
  126432. }
  126433. /* Create a new ephemeral function definition for the overloaded
  126434. ** function */
  126435. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  126436. + sqlite3Strlen30(pDef->zName) + 1);
  126437. if( pNew==0 ){
  126438. return pDef;
  126439. }
  126440. *pNew = *pDef;
  126441. pNew->zName = (const char*)&pNew[1];
  126442. memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  126443. pNew->xSFunc = xSFunc;
  126444. pNew->pUserData = pArg;
  126445. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  126446. return pNew;
  126447. }
  126448. /*
  126449. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  126450. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  126451. ** array if it is missing. If pTab is already in the array, this routine
  126452. ** is a no-op.
  126453. */
  126454. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  126455. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  126456. int i, n;
  126457. Table **apVtabLock;
  126458. assert( IsVirtual(pTab) );
  126459. for(i=0; i<pToplevel->nVtabLock; i++){
  126460. if( pTab==pToplevel->apVtabLock[i] ) return;
  126461. }
  126462. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  126463. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  126464. if( apVtabLock ){
  126465. pToplevel->apVtabLock = apVtabLock;
  126466. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  126467. }else{
  126468. sqlite3OomFault(pToplevel->db);
  126469. }
  126470. }
  126471. /*
  126472. ** Check to see if virtual table module pMod can be have an eponymous
  126473. ** virtual table instance. If it can, create one if one does not already
  126474. ** exist. Return non-zero if the eponymous virtual table instance exists
  126475. ** when this routine returns, and return zero if it does not exist.
  126476. **
  126477. ** An eponymous virtual table instance is one that is named after its
  126478. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  126479. ** statement in order to come into existance. Eponymous virtual table
  126480. ** instances always exist. They cannot be DROP-ed.
  126481. **
  126482. ** Any virtual table module for which xConnect and xCreate are the same
  126483. ** method can have an eponymous virtual table instance.
  126484. */
  126485. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  126486. const sqlite3_module *pModule = pMod->pModule;
  126487. Table *pTab;
  126488. char *zErr = 0;
  126489. int rc;
  126490. sqlite3 *db = pParse->db;
  126491. if( pMod->pEpoTab ) return 1;
  126492. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  126493. pTab = sqlite3DbMallocZero(db, sizeof(Table));
  126494. if( pTab==0 ) return 0;
  126495. pTab->zName = sqlite3DbStrDup(db, pMod->zName);
  126496. if( pTab->zName==0 ){
  126497. sqlite3DbFree(db, pTab);
  126498. return 0;
  126499. }
  126500. pMod->pEpoTab = pTab;
  126501. pTab->nTabRef = 1;
  126502. pTab->pSchema = db->aDb[0].pSchema;
  126503. assert( pTab->nModuleArg==0 );
  126504. pTab->iPKey = -1;
  126505. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  126506. addModuleArgument(db, pTab, 0);
  126507. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  126508. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  126509. if( rc ){
  126510. sqlite3ErrorMsg(pParse, "%s", zErr);
  126511. sqlite3DbFree(db, zErr);
  126512. sqlite3VtabEponymousTableClear(db, pMod);
  126513. return 0;
  126514. }
  126515. return 1;
  126516. }
  126517. /*
  126518. ** Erase the eponymous virtual table instance associated with
  126519. ** virtual table module pMod, if it exists.
  126520. */
  126521. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  126522. Table *pTab = pMod->pEpoTab;
  126523. if( pTab!=0 ){
  126524. /* Mark the table as Ephemeral prior to deleting it, so that the
  126525. ** sqlite3DeleteTable() routine will know that it is not stored in
  126526. ** the schema. */
  126527. pTab->tabFlags |= TF_Ephemeral;
  126528. sqlite3DeleteTable(db, pTab);
  126529. pMod->pEpoTab = 0;
  126530. }
  126531. }
  126532. /*
  126533. ** Return the ON CONFLICT resolution mode in effect for the virtual
  126534. ** table update operation currently in progress.
  126535. **
  126536. ** The results of this routine are undefined unless it is called from
  126537. ** within an xUpdate method.
  126538. */
  126539. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  126540. static const unsigned char aMap[] = {
  126541. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  126542. };
  126543. #ifdef SQLITE_ENABLE_API_ARMOR
  126544. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  126545. #endif
  126546. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  126547. assert( OE_Ignore==4 && OE_Replace==5 );
  126548. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  126549. return (int)aMap[db->vtabOnConflict-1];
  126550. }
  126551. /*
  126552. ** Call from within the xCreate() or xConnect() methods to provide
  126553. ** the SQLite core with additional information about the behavior
  126554. ** of the virtual table being implemented.
  126555. */
  126556. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  126557. va_list ap;
  126558. int rc = SQLITE_OK;
  126559. #ifdef SQLITE_ENABLE_API_ARMOR
  126560. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  126561. #endif
  126562. sqlite3_mutex_enter(db->mutex);
  126563. va_start(ap, op);
  126564. switch( op ){
  126565. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  126566. VtabCtx *p = db->pVtabCtx;
  126567. if( !p ){
  126568. rc = SQLITE_MISUSE_BKPT;
  126569. }else{
  126570. assert( p->pTab==0 || IsVirtual(p->pTab) );
  126571. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  126572. }
  126573. break;
  126574. }
  126575. default:
  126576. rc = SQLITE_MISUSE_BKPT;
  126577. break;
  126578. }
  126579. va_end(ap);
  126580. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  126581. sqlite3_mutex_leave(db->mutex);
  126582. return rc;
  126583. }
  126584. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  126585. /************** End of vtab.c ************************************************/
  126586. /************** Begin file wherecode.c ***************************************/
  126587. /*
  126588. ** 2015-06-06
  126589. **
  126590. ** The author disclaims copyright to this source code. In place of
  126591. ** a legal notice, here is a blessing:
  126592. **
  126593. ** May you do good and not evil.
  126594. ** May you find forgiveness for yourself and forgive others.
  126595. ** May you share freely, never taking more than you give.
  126596. **
  126597. *************************************************************************
  126598. ** This module contains C code that generates VDBE code used to process
  126599. ** the WHERE clause of SQL statements.
  126600. **
  126601. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  126602. ** size of where.c and make it easier to edit. This file contains the routines
  126603. ** that actually generate the bulk of the WHERE loop code. The original where.c
  126604. ** file retains the code that does query planning and analysis.
  126605. */
  126606. /* #include "sqliteInt.h" */
  126607. /************** Include whereInt.h in the middle of wherecode.c **************/
  126608. /************** Begin file whereInt.h ****************************************/
  126609. /*
  126610. ** 2013-11-12
  126611. **
  126612. ** The author disclaims copyright to this source code. In place of
  126613. ** a legal notice, here is a blessing:
  126614. **
  126615. ** May you do good and not evil.
  126616. ** May you find forgiveness for yourself and forgive others.
  126617. ** May you share freely, never taking more than you give.
  126618. **
  126619. *************************************************************************
  126620. **
  126621. ** This file contains structure and macro definitions for the query
  126622. ** planner logic in "where.c". These definitions are broken out into
  126623. ** a separate source file for easier editing.
  126624. */
  126625. /*
  126626. ** Trace output macros
  126627. */
  126628. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  126629. /***/ extern int sqlite3WhereTrace;
  126630. #endif
  126631. #if defined(SQLITE_DEBUG) \
  126632. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  126633. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  126634. # define WHERETRACE_ENABLED 1
  126635. #else
  126636. # define WHERETRACE(K,X)
  126637. #endif
  126638. /* Forward references
  126639. */
  126640. typedef struct WhereClause WhereClause;
  126641. typedef struct WhereMaskSet WhereMaskSet;
  126642. typedef struct WhereOrInfo WhereOrInfo;
  126643. typedef struct WhereAndInfo WhereAndInfo;
  126644. typedef struct WhereLevel WhereLevel;
  126645. typedef struct WhereLoop WhereLoop;
  126646. typedef struct WherePath WherePath;
  126647. typedef struct WhereTerm WhereTerm;
  126648. typedef struct WhereLoopBuilder WhereLoopBuilder;
  126649. typedef struct WhereScan WhereScan;
  126650. typedef struct WhereOrCost WhereOrCost;
  126651. typedef struct WhereOrSet WhereOrSet;
  126652. /*
  126653. ** This object contains information needed to implement a single nested
  126654. ** loop in WHERE clause.
  126655. **
  126656. ** Contrast this object with WhereLoop. This object describes the
  126657. ** implementation of the loop. WhereLoop describes the algorithm.
  126658. ** This object contains a pointer to the WhereLoop algorithm as one of
  126659. ** its elements.
  126660. **
  126661. ** The WhereInfo object contains a single instance of this object for
  126662. ** each term in the FROM clause (which is to say, for each of the
  126663. ** nested loops as implemented). The order of WhereLevel objects determines
  126664. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  126665. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  126666. */
  126667. struct WhereLevel {
  126668. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  126669. int iTabCur; /* The VDBE cursor used to access the table */
  126670. int iIdxCur; /* The VDBE cursor used to access pIdx */
  126671. int addrBrk; /* Jump here to break out of the loop */
  126672. int addrNxt; /* Jump here to start the next IN combination */
  126673. int addrSkip; /* Jump here for next iteration of skip-scan */
  126674. int addrCont; /* Jump here to continue with the next loop cycle */
  126675. int addrFirst; /* First instruction of interior of the loop */
  126676. int addrBody; /* Beginning of the body of this loop */
  126677. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  126678. u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
  126679. int addrLikeRep; /* LIKE range processing address */
  126680. #endif
  126681. u8 iFrom; /* Which entry in the FROM clause */
  126682. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  126683. int p1, p2; /* Operands of the opcode used to ends the loop */
  126684. union { /* Information that depends on pWLoop->wsFlags */
  126685. struct {
  126686. int nIn; /* Number of entries in aInLoop[] */
  126687. struct InLoop {
  126688. int iCur; /* The VDBE cursor used by this IN operator */
  126689. int addrInTop; /* Top of the IN loop */
  126690. int iBase; /* Base register of multi-key index record */
  126691. int nPrefix; /* Number of prior entires in the key */
  126692. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  126693. } *aInLoop; /* Information about each nested IN operator */
  126694. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  126695. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  126696. } u;
  126697. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  126698. Bitmask notReady; /* FROM entries not usable at this level */
  126699. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  126700. int addrVisit; /* Address at which row is visited */
  126701. #endif
  126702. };
  126703. /*
  126704. ** Each instance of this object represents an algorithm for evaluating one
  126705. ** term of a join. Every term of the FROM clause will have at least
  126706. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  126707. ** prevent a query solution - which is an error) and many terms of the
  126708. ** FROM clause will have multiple WhereLoop objects, each describing a
  126709. ** potential way of implementing that FROM-clause term, together with
  126710. ** dependencies and cost estimates for using the chosen algorithm.
  126711. **
  126712. ** Query planning consists of building up a collection of these WhereLoop
  126713. ** objects, then computing a particular sequence of WhereLoop objects, with
  126714. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  126715. ** and that minimize the overall cost.
  126716. */
  126717. struct WhereLoop {
  126718. Bitmask prereq; /* Bitmask of other loops that must run first */
  126719. Bitmask maskSelf; /* Bitmask identifying table iTab */
  126720. #ifdef SQLITE_DEBUG
  126721. char cId; /* Symbolic ID of this loop for debugging use */
  126722. #endif
  126723. u8 iTab; /* Position in FROM clause of table for this loop */
  126724. u8 iSortIdx; /* Sorting index number. 0==None */
  126725. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  126726. LogEst rRun; /* Cost of running each loop */
  126727. LogEst nOut; /* Estimated number of output rows */
  126728. union {
  126729. struct { /* Information for internal btree tables */
  126730. u16 nEq; /* Number of equality constraints */
  126731. u16 nBtm; /* Size of BTM vector */
  126732. u16 nTop; /* Size of TOP vector */
  126733. u16 nIdxCol; /* Index column used for ORDER BY */
  126734. Index *pIndex; /* Index used, or NULL */
  126735. } btree;
  126736. struct { /* Information for virtual tables */
  126737. int idxNum; /* Index number */
  126738. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  126739. i8 isOrdered; /* True if satisfies ORDER BY */
  126740. u16 omitMask; /* Terms that may be omitted */
  126741. char *idxStr; /* Index identifier string */
  126742. } vtab;
  126743. } u;
  126744. u32 wsFlags; /* WHERE_* flags describing the plan */
  126745. u16 nLTerm; /* Number of entries in aLTerm[] */
  126746. u16 nSkip; /* Number of NULL aLTerm[] entries */
  126747. /**** whereLoopXfer() copies fields above ***********************/
  126748. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  126749. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  126750. WhereTerm **aLTerm; /* WhereTerms used */
  126751. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  126752. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  126753. };
  126754. /* This object holds the prerequisites and the cost of running a
  126755. ** subquery on one operand of an OR operator in the WHERE clause.
  126756. ** See WhereOrSet for additional information
  126757. */
  126758. struct WhereOrCost {
  126759. Bitmask prereq; /* Prerequisites */
  126760. LogEst rRun; /* Cost of running this subquery */
  126761. LogEst nOut; /* Number of outputs for this subquery */
  126762. };
  126763. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  126764. ** correspond to the subquery(s) of OR-clause processing. Only the
  126765. ** best N_OR_COST elements are retained.
  126766. */
  126767. #define N_OR_COST 3
  126768. struct WhereOrSet {
  126769. u16 n; /* Number of valid a[] entries */
  126770. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  126771. };
  126772. /*
  126773. ** Each instance of this object holds a sequence of WhereLoop objects
  126774. ** that implement some or all of a query plan.
  126775. **
  126776. ** Think of each WhereLoop object as a node in a graph with arcs
  126777. ** showing dependencies and costs for travelling between nodes. (That is
  126778. ** not a completely accurate description because WhereLoop costs are a
  126779. ** vector, not a scalar, and because dependencies are many-to-one, not
  126780. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  126781. ** Then a WherePath object is a path through the graph that visits some
  126782. ** or all of the WhereLoop objects once.
  126783. **
  126784. ** The "solver" works by creating the N best WherePath objects of length
  126785. ** 1. Then using those as a basis to compute the N best WherePath objects
  126786. ** of length 2. And so forth until the length of WherePaths equals the
  126787. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  126788. ** at the end is the chosen query plan.
  126789. */
  126790. struct WherePath {
  126791. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  126792. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  126793. LogEst nRow; /* Estimated number of rows generated by this path */
  126794. LogEst rCost; /* Total cost of this path */
  126795. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  126796. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  126797. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  126798. };
  126799. /*
  126800. ** The query generator uses an array of instances of this structure to
  126801. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  126802. ** clause subexpression is separated from the others by AND operators,
  126803. ** usually, or sometimes subexpressions separated by OR.
  126804. **
  126805. ** All WhereTerms are collected into a single WhereClause structure.
  126806. ** The following identity holds:
  126807. **
  126808. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  126809. **
  126810. ** When a term is of the form:
  126811. **
  126812. ** X <op> <expr>
  126813. **
  126814. ** where X is a column name and <op> is one of certain operators,
  126815. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  126816. ** cursor number and column number for X. WhereTerm.eOperator records
  126817. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  126818. ** use of a bitmask encoding for the operator allows us to search
  126819. ** quickly for terms that match any of several different operators.
  126820. **
  126821. ** A WhereTerm might also be two or more subterms connected by OR:
  126822. **
  126823. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  126824. **
  126825. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  126826. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  126827. ** is collected about the OR clause.
  126828. **
  126829. ** If a term in the WHERE clause does not match either of the two previous
  126830. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  126831. ** to the original subexpression content and wtFlags is set up appropriately
  126832. ** but no other fields in the WhereTerm object are meaningful.
  126833. **
  126834. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  126835. ** but they do so indirectly. A single WhereMaskSet structure translates
  126836. ** cursor number into bits and the translated bit is stored in the prereq
  126837. ** fields. The translation is used in order to maximize the number of
  126838. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  126839. ** spread out over the non-negative integers. For example, the cursor
  126840. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  126841. ** translates these sparse cursor numbers into consecutive integers
  126842. ** beginning with 0 in order to make the best possible use of the available
  126843. ** bits in the Bitmask. So, in the example above, the cursor numbers
  126844. ** would be mapped into integers 0 through 7.
  126845. **
  126846. ** The number of terms in a join is limited by the number of bits
  126847. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  126848. ** is only able to process joins with 64 or fewer tables.
  126849. */
  126850. struct WhereTerm {
  126851. Expr *pExpr; /* Pointer to the subexpression that is this term */
  126852. WhereClause *pWC; /* The clause this term is part of */
  126853. LogEst truthProb; /* Probability of truth for this expression */
  126854. u16 wtFlags; /* TERM_xxx bit flags. See below */
  126855. u16 eOperator; /* A WO_xx value describing <op> */
  126856. u8 nChild; /* Number of children that must disable us */
  126857. u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
  126858. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  126859. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  126860. int iField; /* Field in (?,?,?) IN (SELECT...) vector */
  126861. union {
  126862. int leftColumn; /* Column number of X in "X <op> <expr>" */
  126863. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  126864. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  126865. } u;
  126866. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  126867. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  126868. };
  126869. /*
  126870. ** Allowed values of WhereTerm.wtFlags
  126871. */
  126872. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  126873. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  126874. #define TERM_CODED 0x04 /* This term is already coded */
  126875. #define TERM_COPIED 0x08 /* Has a child */
  126876. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  126877. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  126878. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  126879. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  126880. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  126881. #else
  126882. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  126883. #endif
  126884. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  126885. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  126886. #define TERM_LIKE 0x400 /* The original LIKE operator */
  126887. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  126888. #define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */
  126889. /*
  126890. ** An instance of the WhereScan object is used as an iterator for locating
  126891. ** terms in the WHERE clause that are useful to the query planner.
  126892. */
  126893. struct WhereScan {
  126894. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  126895. WhereClause *pWC; /* WhereClause currently being scanned */
  126896. const char *zCollName; /* Required collating sequence, if not NULL */
  126897. Expr *pIdxExpr; /* Search for this index expression */
  126898. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  126899. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  126900. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  126901. u32 opMask; /* Acceptable operators */
  126902. int k; /* Resume scanning at this->pWC->a[this->k] */
  126903. int aiCur[11]; /* Cursors in the equivalence class */
  126904. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  126905. };
  126906. /*
  126907. ** An instance of the following structure holds all information about a
  126908. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  126909. **
  126910. ** Explanation of pOuter: For a WHERE clause of the form
  126911. **
  126912. ** a AND ((b AND c) OR (d AND e)) AND f
  126913. **
  126914. ** There are separate WhereClause objects for the whole clause and for
  126915. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  126916. ** subclauses points to the WhereClause object for the whole clause.
  126917. */
  126918. struct WhereClause {
  126919. WhereInfo *pWInfo; /* WHERE clause processing context */
  126920. WhereClause *pOuter; /* Outer conjunction */
  126921. u8 op; /* Split operator. TK_AND or TK_OR */
  126922. u8 hasOr; /* True if any a[].eOperator is WO_OR */
  126923. int nTerm; /* Number of terms */
  126924. int nSlot; /* Number of entries in a[] */
  126925. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  126926. #if defined(SQLITE_SMALL_STACK)
  126927. WhereTerm aStatic[1]; /* Initial static space for a[] */
  126928. #else
  126929. WhereTerm aStatic[8]; /* Initial static space for a[] */
  126930. #endif
  126931. };
  126932. /*
  126933. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  126934. ** a dynamically allocated instance of the following structure.
  126935. */
  126936. struct WhereOrInfo {
  126937. WhereClause wc; /* Decomposition into subterms */
  126938. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  126939. };
  126940. /*
  126941. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  126942. ** a dynamically allocated instance of the following structure.
  126943. */
  126944. struct WhereAndInfo {
  126945. WhereClause wc; /* The subexpression broken out */
  126946. };
  126947. /*
  126948. ** An instance of the following structure keeps track of a mapping
  126949. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  126950. **
  126951. ** The VDBE cursor numbers are small integers contained in
  126952. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  126953. ** clause, the cursor numbers might not begin with 0 and they might
  126954. ** contain gaps in the numbering sequence. But we want to make maximum
  126955. ** use of the bits in our bitmasks. This structure provides a mapping
  126956. ** from the sparse cursor numbers into consecutive integers beginning
  126957. ** with 0.
  126958. **
  126959. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  126960. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  126961. **
  126962. ** For example, if the WHERE clause expression used these VDBE
  126963. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  126964. ** would map those cursor numbers into bits 0 through 5.
  126965. **
  126966. ** Note that the mapping is not necessarily ordered. In the example
  126967. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  126968. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  126969. ** does not really matter. What is important is that sparse cursor
  126970. ** numbers all get mapped into bit numbers that begin with 0 and contain
  126971. ** no gaps.
  126972. */
  126973. struct WhereMaskSet {
  126974. int bVarSelect; /* Used by sqlite3WhereExprUsage() */
  126975. int n; /* Number of assigned cursor values */
  126976. int ix[BMS]; /* Cursor assigned to each bit */
  126977. };
  126978. /*
  126979. ** Initialize a WhereMaskSet object
  126980. */
  126981. #define initMaskSet(P) (P)->n=0
  126982. /*
  126983. ** This object is a convenience wrapper holding all information needed
  126984. ** to construct WhereLoop objects for a particular query.
  126985. */
  126986. struct WhereLoopBuilder {
  126987. WhereInfo *pWInfo; /* Information about this WHERE */
  126988. WhereClause *pWC; /* WHERE clause terms */
  126989. ExprList *pOrderBy; /* ORDER BY clause */
  126990. WhereLoop *pNew; /* Template WhereLoop */
  126991. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  126992. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  126993. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  126994. int nRecValid; /* Number of valid fields currently in pRec */
  126995. #endif
  126996. unsigned int bldFlags; /* SQLITE_BLDF_* flags */
  126997. unsigned int iPlanLimit; /* Search limiter */
  126998. };
  126999. /* Allowed values for WhereLoopBuider.bldFlags */
  127000. #define SQLITE_BLDF_INDEXED 0x0001 /* An index is used */
  127001. #define SQLITE_BLDF_UNIQUE 0x0002 /* All keys of a UNIQUE index used */
  127002. /* The WhereLoopBuilder.iPlanLimit is used to limit the number of
  127003. ** index+constraint combinations the query planner will consider for a
  127004. ** particular query. If this parameter is unlimited, then certain
  127005. ** pathological queries can spend excess time in the sqlite3WhereBegin()
  127006. ** routine. The limit is high enough that is should not impact real-world
  127007. ** queries.
  127008. **
  127009. ** SQLITE_QUERY_PLANNER_LIMIT is the baseline limit. The limit is
  127010. ** increased by SQLITE_QUERY_PLANNER_LIMIT_INCR before each term of the FROM
  127011. ** clause is processed, so that every table in a join is guaranteed to be
  127012. ** able to propose a some index+constraint combinations even if the initial
  127013. ** baseline limit was exhausted by prior tables of the join.
  127014. */
  127015. #ifndef SQLITE_QUERY_PLANNER_LIMIT
  127016. # define SQLITE_QUERY_PLANNER_LIMIT 20000
  127017. #endif
  127018. #ifndef SQLITE_QUERY_PLANNER_LIMIT_INCR
  127019. # define SQLITE_QUERY_PLANNER_LIMIT_INCR 1000
  127020. #endif
  127021. /*
  127022. ** The WHERE clause processing routine has two halves. The
  127023. ** first part does the start of the WHERE loop and the second
  127024. ** half does the tail of the WHERE loop. An instance of
  127025. ** this structure is returned by the first half and passed
  127026. ** into the second half to give some continuity.
  127027. **
  127028. ** An instance of this object holds the complete state of the query
  127029. ** planner.
  127030. */
  127031. struct WhereInfo {
  127032. Parse *pParse; /* Parsing and code generating context */
  127033. SrcList *pTabList; /* List of tables in the join */
  127034. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  127035. ExprList *pResultSet; /* Result set of the query */
  127036. Expr *pWhere; /* The complete WHERE clause */
  127037. LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
  127038. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  127039. int iContinue; /* Jump here to continue with next record */
  127040. int iBreak; /* Jump here to break out of the loop */
  127041. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  127042. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  127043. u8 nLevel; /* Number of nested loop */
  127044. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  127045. u8 sorted; /* True if really sorted (not just grouped) */
  127046. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  127047. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  127048. u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
  127049. u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */
  127050. int iTop; /* The very beginning of the WHERE loop */
  127051. WhereLoop *pLoops; /* List of all WhereLoop objects */
  127052. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  127053. LogEst nRowOut; /* Estimated number of output rows */
  127054. WhereClause sWC; /* Decomposition of the WHERE clause */
  127055. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  127056. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  127057. };
  127058. /*
  127059. ** Private interfaces - callable only by other where.c routines.
  127060. **
  127061. ** where.c:
  127062. */
  127063. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  127064. #ifdef WHERETRACE_ENABLED
  127065. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
  127066. #endif
  127067. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  127068. WhereClause *pWC, /* The WHERE clause to be searched */
  127069. int iCur, /* Cursor number of LHS */
  127070. int iColumn, /* Column number of LHS */
  127071. Bitmask notReady, /* RHS must not overlap with this mask */
  127072. u32 op, /* Mask of WO_xx values describing operator */
  127073. Index *pIdx /* Must be compatible with this index, if not NULL */
  127074. );
  127075. /* wherecode.c: */
  127076. #ifndef SQLITE_OMIT_EXPLAIN
  127077. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  127078. Parse *pParse, /* Parse context */
  127079. SrcList *pTabList, /* Table list this loop refers to */
  127080. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  127081. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  127082. );
  127083. #else
  127084. # define sqlite3WhereExplainOneScan(u,v,w,x) 0
  127085. #endif /* SQLITE_OMIT_EXPLAIN */
  127086. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  127087. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  127088. Vdbe *v, /* Vdbe to add scanstatus entry to */
  127089. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  127090. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  127091. int addrExplain /* Address of OP_Explain (or 0) */
  127092. );
  127093. #else
  127094. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  127095. #endif
  127096. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  127097. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  127098. int iLevel, /* Which level of pWInfo->a[] should be coded */
  127099. Bitmask notReady /* Which tables are currently available */
  127100. );
  127101. /* whereexpr.c: */
  127102. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  127103. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  127104. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  127105. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  127106. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
  127107. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  127108. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  127109. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  127110. /*
  127111. ** Bitmasks for the operators on WhereTerm objects. These are all
  127112. ** operators that are of interest to the query planner. An
  127113. ** OR-ed combination of these values can be used when searching for
  127114. ** particular WhereTerms within a WhereClause.
  127115. **
  127116. ** Value constraints:
  127117. ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
  127118. ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
  127119. ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
  127120. ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
  127121. ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
  127122. */
  127123. #define WO_IN 0x0001
  127124. #define WO_EQ 0x0002
  127125. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  127126. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  127127. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  127128. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  127129. #define WO_AUX 0x0040 /* Op useful to virtual tables only */
  127130. #define WO_IS 0x0080
  127131. #define WO_ISNULL 0x0100
  127132. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  127133. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  127134. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  127135. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  127136. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  127137. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  127138. /*
  127139. ** These are definitions of bits in the WhereLoop.wsFlags field.
  127140. ** The particular combination of bits in each WhereLoop help to
  127141. ** determine the algorithm that WhereLoop represents.
  127142. */
  127143. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  127144. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  127145. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  127146. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  127147. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  127148. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  127149. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  127150. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  127151. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  127152. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  127153. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  127154. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  127155. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  127156. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  127157. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  127158. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  127159. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  127160. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  127161. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  127162. #define WHERE_IN_EARLYOUT 0x00040000 /* Perhaps quit IN loops early */
  127163. /************** End of whereInt.h ********************************************/
  127164. /************** Continuing where we left off in wherecode.c ******************/
  127165. #ifndef SQLITE_OMIT_EXPLAIN
  127166. /*
  127167. ** Return the name of the i-th column of the pIdx index.
  127168. */
  127169. static const char *explainIndexColumnName(Index *pIdx, int i){
  127170. i = pIdx->aiColumn[i];
  127171. if( i==XN_EXPR ) return "<expr>";
  127172. if( i==XN_ROWID ) return "rowid";
  127173. return pIdx->pTable->aCol[i].zName;
  127174. }
  127175. /*
  127176. ** This routine is a helper for explainIndexRange() below
  127177. **
  127178. ** pStr holds the text of an expression that we are building up one term
  127179. ** at a time. This routine adds a new term to the end of the expression.
  127180. ** Terms are separated by AND so add the "AND" text for second and subsequent
  127181. ** terms only.
  127182. */
  127183. static void explainAppendTerm(
  127184. StrAccum *pStr, /* The text expression being built */
  127185. Index *pIdx, /* Index to read column names from */
  127186. int nTerm, /* Number of terms */
  127187. int iTerm, /* Zero-based index of first term. */
  127188. int bAnd, /* Non-zero to append " AND " */
  127189. const char *zOp /* Name of the operator */
  127190. ){
  127191. int i;
  127192. assert( nTerm>=1 );
  127193. if( bAnd ) sqlite3_str_append(pStr, " AND ", 5);
  127194. if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
  127195. for(i=0; i<nTerm; i++){
  127196. if( i ) sqlite3_str_append(pStr, ",", 1);
  127197. sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i));
  127198. }
  127199. if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
  127200. sqlite3_str_append(pStr, zOp, 1);
  127201. if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
  127202. for(i=0; i<nTerm; i++){
  127203. if( i ) sqlite3_str_append(pStr, ",", 1);
  127204. sqlite3_str_append(pStr, "?", 1);
  127205. }
  127206. if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
  127207. }
  127208. /*
  127209. ** Argument pLevel describes a strategy for scanning table pTab. This
  127210. ** function appends text to pStr that describes the subset of table
  127211. ** rows scanned by the strategy in the form of an SQL expression.
  127212. **
  127213. ** For example, if the query:
  127214. **
  127215. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  127216. **
  127217. ** is run and there is an index on (a, b), then this function returns a
  127218. ** string similar to:
  127219. **
  127220. ** "a=? AND b>?"
  127221. */
  127222. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  127223. Index *pIndex = pLoop->u.btree.pIndex;
  127224. u16 nEq = pLoop->u.btree.nEq;
  127225. u16 nSkip = pLoop->nSkip;
  127226. int i, j;
  127227. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  127228. sqlite3_str_append(pStr, " (", 2);
  127229. for(i=0; i<nEq; i++){
  127230. const char *z = explainIndexColumnName(pIndex, i);
  127231. if( i ) sqlite3_str_append(pStr, " AND ", 5);
  127232. sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  127233. }
  127234. j = i;
  127235. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  127236. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
  127237. i = 1;
  127238. }
  127239. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  127240. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
  127241. }
  127242. sqlite3_str_append(pStr, ")", 1);
  127243. }
  127244. /*
  127245. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  127246. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  127247. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  127248. ** is added to the output to describe the table scan strategy in pLevel.
  127249. **
  127250. ** If an OP_Explain opcode is added to the VM, its address is returned.
  127251. ** Otherwise, if no OP_Explain is coded, zero is returned.
  127252. */
  127253. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  127254. Parse *pParse, /* Parse context */
  127255. SrcList *pTabList, /* Table list this loop refers to */
  127256. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  127257. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  127258. ){
  127259. int ret = 0;
  127260. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  127261. if( sqlite3ParseToplevel(pParse)->explain==2 )
  127262. #endif
  127263. {
  127264. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  127265. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  127266. sqlite3 *db = pParse->db; /* Database handle */
  127267. int isSearch; /* True for a SEARCH. False for SCAN. */
  127268. WhereLoop *pLoop; /* The controlling WhereLoop object */
  127269. u32 flags; /* Flags that describe this loop */
  127270. char *zMsg; /* Text to add to EQP output */
  127271. StrAccum str; /* EQP output string */
  127272. char zBuf[100]; /* Initial space for EQP output string */
  127273. pLoop = pLevel->pWLoop;
  127274. flags = pLoop->wsFlags;
  127275. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
  127276. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  127277. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  127278. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  127279. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  127280. sqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN");
  127281. if( pItem->pSelect ){
  127282. sqlite3_str_appendf(&str, " SUBQUERY %u", pItem->pSelect->selId);
  127283. }else{
  127284. sqlite3_str_appendf(&str, " TABLE %s", pItem->zName);
  127285. }
  127286. if( pItem->zAlias ){
  127287. sqlite3_str_appendf(&str, " AS %s", pItem->zAlias);
  127288. }
  127289. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  127290. const char *zFmt = 0;
  127291. Index *pIdx;
  127292. assert( pLoop->u.btree.pIndex!=0 );
  127293. pIdx = pLoop->u.btree.pIndex;
  127294. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  127295. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  127296. if( isSearch ){
  127297. zFmt = "PRIMARY KEY";
  127298. }
  127299. }else if( flags & WHERE_PARTIALIDX ){
  127300. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  127301. }else if( flags & WHERE_AUTO_INDEX ){
  127302. zFmt = "AUTOMATIC COVERING INDEX";
  127303. }else if( flags & WHERE_IDX_ONLY ){
  127304. zFmt = "COVERING INDEX %s";
  127305. }else{
  127306. zFmt = "INDEX %s";
  127307. }
  127308. if( zFmt ){
  127309. sqlite3_str_append(&str, " USING ", 7);
  127310. sqlite3_str_appendf(&str, zFmt, pIdx->zName);
  127311. explainIndexRange(&str, pLoop);
  127312. }
  127313. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  127314. const char *zRangeOp;
  127315. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  127316. zRangeOp = "=";
  127317. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  127318. zRangeOp = ">? AND rowid<";
  127319. }else if( flags&WHERE_BTM_LIMIT ){
  127320. zRangeOp = ">";
  127321. }else{
  127322. assert( flags&WHERE_TOP_LIMIT);
  127323. zRangeOp = "<";
  127324. }
  127325. sqlite3_str_appendf(&str,
  127326. " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  127327. }
  127328. #ifndef SQLITE_OMIT_VIRTUALTABLE
  127329. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  127330. sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s",
  127331. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  127332. }
  127333. #endif
  127334. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  127335. if( pLoop->nOut>=10 ){
  127336. sqlite3_str_appendf(&str, " (~%llu rows)",
  127337. sqlite3LogEstToInt(pLoop->nOut));
  127338. }else{
  127339. sqlite3_str_append(&str, " (~1 row)", 9);
  127340. }
  127341. #endif
  127342. zMsg = sqlite3StrAccumFinish(&str);
  127343. ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
  127344. pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
  127345. }
  127346. return ret;
  127347. }
  127348. #endif /* SQLITE_OMIT_EXPLAIN */
  127349. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  127350. /*
  127351. ** Configure the VM passed as the first argument with an
  127352. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  127353. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  127354. ** clause that the scan reads data from.
  127355. **
  127356. ** If argument addrExplain is not 0, it must be the address of an
  127357. ** OP_Explain instruction that describes the same loop.
  127358. */
  127359. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  127360. Vdbe *v, /* Vdbe to add scanstatus entry to */
  127361. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  127362. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  127363. int addrExplain /* Address of OP_Explain (or 0) */
  127364. ){
  127365. const char *zObj = 0;
  127366. WhereLoop *pLoop = pLvl->pWLoop;
  127367. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  127368. zObj = pLoop->u.btree.pIndex->zName;
  127369. }else{
  127370. zObj = pSrclist->a[pLvl->iFrom].zName;
  127371. }
  127372. sqlite3VdbeScanStatus(
  127373. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  127374. );
  127375. }
  127376. #endif
  127377. /*
  127378. ** Disable a term in the WHERE clause. Except, do not disable the term
  127379. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  127380. ** or USING clause of that join.
  127381. **
  127382. ** Consider the term t2.z='ok' in the following queries:
  127383. **
  127384. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  127385. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  127386. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  127387. **
  127388. ** The t2.z='ok' is disabled in the in (2) because it originates
  127389. ** in the ON clause. The term is disabled in (3) because it is not part
  127390. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  127391. **
  127392. ** Disabling a term causes that term to not be tested in the inner loop
  127393. ** of the join. Disabling is an optimization. When terms are satisfied
  127394. ** by indices, we disable them to prevent redundant tests in the inner
  127395. ** loop. We would get the correct results if nothing were ever disabled,
  127396. ** but joins might run a little slower. The trick is to disable as much
  127397. ** as we can without disabling too much. If we disabled in (1), we'd get
  127398. ** the wrong answer. See ticket #813.
  127399. **
  127400. ** If all the children of a term are disabled, then that term is also
  127401. ** automatically disabled. In this way, terms get disabled if derived
  127402. ** virtual terms are tested first. For example:
  127403. **
  127404. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  127405. ** \___________/ \______/ \_____/
  127406. ** parent child1 child2
  127407. **
  127408. ** Only the parent term was in the original WHERE clause. The child1
  127409. ** and child2 terms were added by the LIKE optimization. If both of
  127410. ** the virtual child terms are valid, then testing of the parent can be
  127411. ** skipped.
  127412. **
  127413. ** Usually the parent term is marked as TERM_CODED. But if the parent
  127414. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  127415. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  127416. ** a conditional such that is only evaluated on the second pass of a
  127417. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  127418. */
  127419. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  127420. int nLoop = 0;
  127421. assert( pTerm!=0 );
  127422. while( (pTerm->wtFlags & TERM_CODED)==0
  127423. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  127424. && (pLevel->notReady & pTerm->prereqAll)==0
  127425. ){
  127426. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  127427. pTerm->wtFlags |= TERM_LIKECOND;
  127428. }else{
  127429. pTerm->wtFlags |= TERM_CODED;
  127430. }
  127431. if( pTerm->iParent<0 ) break;
  127432. pTerm = &pTerm->pWC->a[pTerm->iParent];
  127433. assert( pTerm!=0 );
  127434. pTerm->nChild--;
  127435. if( pTerm->nChild!=0 ) break;
  127436. nLoop++;
  127437. }
  127438. }
  127439. /*
  127440. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  127441. ** to the n registers starting at base.
  127442. **
  127443. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  127444. ** beginning and end of zAff are ignored. If all entries in zAff are
  127445. ** SQLITE_AFF_BLOB, then no code gets generated.
  127446. **
  127447. ** This routine makes its own copy of zAff so that the caller is free
  127448. ** to modify zAff after this routine returns.
  127449. */
  127450. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  127451. Vdbe *v = pParse->pVdbe;
  127452. if( zAff==0 ){
  127453. assert( pParse->db->mallocFailed );
  127454. return;
  127455. }
  127456. assert( v!=0 );
  127457. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  127458. ** and end of the affinity string.
  127459. */
  127460. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  127461. n--;
  127462. base++;
  127463. zAff++;
  127464. }
  127465. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  127466. n--;
  127467. }
  127468. /* Code the OP_Affinity opcode if there is anything left to do. */
  127469. if( n>0 ){
  127470. sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
  127471. }
  127472. }
  127473. /*
  127474. ** Expression pRight, which is the RHS of a comparison operation, is
  127475. ** either a vector of n elements or, if n==1, a scalar expression.
  127476. ** Before the comparison operation, affinity zAff is to be applied
  127477. ** to the pRight values. This function modifies characters within the
  127478. ** affinity string to SQLITE_AFF_BLOB if either:
  127479. **
  127480. ** * the comparison will be performed with no affinity, or
  127481. ** * the affinity change in zAff is guaranteed not to change the value.
  127482. */
  127483. static void updateRangeAffinityStr(
  127484. Expr *pRight, /* RHS of comparison */
  127485. int n, /* Number of vector elements in comparison */
  127486. char *zAff /* Affinity string to modify */
  127487. ){
  127488. int i;
  127489. for(i=0; i<n; i++){
  127490. Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
  127491. if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
  127492. || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
  127493. ){
  127494. zAff[i] = SQLITE_AFF_BLOB;
  127495. }
  127496. }
  127497. }
  127498. /*
  127499. ** pX is an expression of the form: (vector) IN (SELECT ...)
  127500. ** In other words, it is a vector IN operator with a SELECT clause on the
  127501. ** LHS. But not all terms in the vector are indexable and the terms might
  127502. ** not be in the correct order for indexing.
  127503. **
  127504. ** This routine makes a copy of the input pX expression and then adjusts
  127505. ** the vector on the LHS with corresponding changes to the SELECT so that
  127506. ** the vector contains only index terms and those terms are in the correct
  127507. ** order. The modified IN expression is returned. The caller is responsible
  127508. ** for deleting the returned expression.
  127509. **
  127510. ** Example:
  127511. **
  127512. ** CREATE TABLE t1(a,b,c,d,e,f);
  127513. ** CREATE INDEX t1x1 ON t1(e,c);
  127514. ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
  127515. ** \_______________________________________/
  127516. ** The pX expression
  127517. **
  127518. ** Since only columns e and c can be used with the index, in that order,
  127519. ** the modified IN expression that is returned will be:
  127520. **
  127521. ** (e,c) IN (SELECT z,x FROM t2)
  127522. **
  127523. ** The reduced pX is different from the original (obviously) and thus is
  127524. ** only used for indexing, to improve performance. The original unaltered
  127525. ** IN expression must also be run on each output row for correctness.
  127526. */
  127527. static Expr *removeUnindexableInClauseTerms(
  127528. Parse *pParse, /* The parsing context */
  127529. int iEq, /* Look at loop terms starting here */
  127530. WhereLoop *pLoop, /* The current loop */
  127531. Expr *pX /* The IN expression to be reduced */
  127532. ){
  127533. sqlite3 *db = pParse->db;
  127534. Expr *pNew = sqlite3ExprDup(db, pX, 0);
  127535. if( db->mallocFailed==0 ){
  127536. ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */
  127537. ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */
  127538. ExprList *pRhs = 0; /* New RHS after modifications */
  127539. ExprList *pLhs = 0; /* New LHS after mods */
  127540. int i; /* Loop counter */
  127541. Select *pSelect; /* Pointer to the SELECT on the RHS */
  127542. for(i=iEq; i<pLoop->nLTerm; i++){
  127543. if( pLoop->aLTerm[i]->pExpr==pX ){
  127544. int iField = pLoop->aLTerm[i]->iField - 1;
  127545. if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
  127546. pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
  127547. pOrigRhs->a[iField].pExpr = 0;
  127548. assert( pOrigLhs->a[iField].pExpr!=0 );
  127549. pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
  127550. pOrigLhs->a[iField].pExpr = 0;
  127551. }
  127552. }
  127553. sqlite3ExprListDelete(db, pOrigRhs);
  127554. sqlite3ExprListDelete(db, pOrigLhs);
  127555. pNew->pLeft->x.pList = pLhs;
  127556. pNew->x.pSelect->pEList = pRhs;
  127557. if( pLhs && pLhs->nExpr==1 ){
  127558. /* Take care here not to generate a TK_VECTOR containing only a
  127559. ** single value. Since the parser never creates such a vector, some
  127560. ** of the subroutines do not handle this case. */
  127561. Expr *p = pLhs->a[0].pExpr;
  127562. pLhs->a[0].pExpr = 0;
  127563. sqlite3ExprDelete(db, pNew->pLeft);
  127564. pNew->pLeft = p;
  127565. }
  127566. pSelect = pNew->x.pSelect;
  127567. if( pSelect->pOrderBy ){
  127568. /* If the SELECT statement has an ORDER BY clause, zero the
  127569. ** iOrderByCol variables. These are set to non-zero when an
  127570. ** ORDER BY term exactly matches one of the terms of the
  127571. ** result-set. Since the result-set of the SELECT statement may
  127572. ** have been modified or reordered, these variables are no longer
  127573. ** set correctly. Since setting them is just an optimization,
  127574. ** it's easiest just to zero them here. */
  127575. ExprList *pOrderBy = pSelect->pOrderBy;
  127576. for(i=0; i<pOrderBy->nExpr; i++){
  127577. pOrderBy->a[i].u.x.iOrderByCol = 0;
  127578. }
  127579. }
  127580. #if 0
  127581. printf("For indexing, change the IN expr:\n");
  127582. sqlite3TreeViewExpr(0, pX, 0);
  127583. printf("Into:\n");
  127584. sqlite3TreeViewExpr(0, pNew, 0);
  127585. #endif
  127586. }
  127587. return pNew;
  127588. }
  127589. /*
  127590. ** Generate code for a single equality term of the WHERE clause. An equality
  127591. ** term can be either X=expr or X IN (...). pTerm is the term to be
  127592. ** coded.
  127593. **
  127594. ** The current value for the constraint is left in a register, the index
  127595. ** of which is returned. An attempt is made store the result in iTarget but
  127596. ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
  127597. ** constraint is a TK_EQ or TK_IS, then the current value might be left in
  127598. ** some other register and it is the caller's responsibility to compensate.
  127599. **
  127600. ** For a constraint of the form X=expr, the expression is evaluated in
  127601. ** straight-line code. For constraints of the form X IN (...)
  127602. ** this routine sets up a loop that will iterate over all values of X.
  127603. */
  127604. static int codeEqualityTerm(
  127605. Parse *pParse, /* The parsing context */
  127606. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  127607. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  127608. int iEq, /* Index of the equality term within this level */
  127609. int bRev, /* True for reverse-order IN operations */
  127610. int iTarget /* Attempt to leave results in this register */
  127611. ){
  127612. Expr *pX = pTerm->pExpr;
  127613. Vdbe *v = pParse->pVdbe;
  127614. int iReg; /* Register holding results */
  127615. assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
  127616. assert( iTarget>0 );
  127617. if( pX->op==TK_EQ || pX->op==TK_IS ){
  127618. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  127619. }else if( pX->op==TK_ISNULL ){
  127620. iReg = iTarget;
  127621. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  127622. #ifndef SQLITE_OMIT_SUBQUERY
  127623. }else{
  127624. int eType = IN_INDEX_NOOP;
  127625. int iTab;
  127626. struct InLoop *pIn;
  127627. WhereLoop *pLoop = pLevel->pWLoop;
  127628. int i;
  127629. int nEq = 0;
  127630. int *aiMap = 0;
  127631. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  127632. && pLoop->u.btree.pIndex!=0
  127633. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  127634. ){
  127635. testcase( iEq==0 );
  127636. testcase( bRev );
  127637. bRev = !bRev;
  127638. }
  127639. assert( pX->op==TK_IN );
  127640. iReg = iTarget;
  127641. for(i=0; i<iEq; i++){
  127642. if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
  127643. disableTerm(pLevel, pTerm);
  127644. return iTarget;
  127645. }
  127646. }
  127647. for(i=iEq;i<pLoop->nLTerm; i++){
  127648. assert( pLoop->aLTerm[i]!=0 );
  127649. if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
  127650. }
  127651. if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
  127652. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
  127653. }else{
  127654. sqlite3 *db = pParse->db;
  127655. pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
  127656. if( !db->mallocFailed ){
  127657. aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
  127658. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
  127659. pTerm->pExpr->iTable = pX->iTable;
  127660. }
  127661. sqlite3ExprDelete(db, pX);
  127662. pX = pTerm->pExpr;
  127663. }
  127664. if( eType==IN_INDEX_INDEX_DESC ){
  127665. testcase( bRev );
  127666. bRev = !bRev;
  127667. }
  127668. iTab = pX->iTable;
  127669. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  127670. VdbeCoverageIf(v, bRev);
  127671. VdbeCoverageIf(v, !bRev);
  127672. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  127673. pLoop->wsFlags |= WHERE_IN_ABLE;
  127674. if( pLevel->u.in.nIn==0 ){
  127675. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  127676. }
  127677. i = pLevel->u.in.nIn;
  127678. pLevel->u.in.nIn += nEq;
  127679. pLevel->u.in.aInLoop =
  127680. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  127681. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  127682. pIn = pLevel->u.in.aInLoop;
  127683. if( pIn ){
  127684. int iMap = 0; /* Index in aiMap[] */
  127685. pIn += i;
  127686. for(i=iEq;i<pLoop->nLTerm; i++){
  127687. if( pLoop->aLTerm[i]->pExpr==pX ){
  127688. int iOut = iReg + i - iEq;
  127689. if( eType==IN_INDEX_ROWID ){
  127690. testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */
  127691. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
  127692. }else{
  127693. int iCol = aiMap ? aiMap[iMap++] : 0;
  127694. pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
  127695. }
  127696. sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
  127697. if( i==iEq ){
  127698. pIn->iCur = iTab;
  127699. pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
  127700. if( iEq>0 && (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  127701. pIn->iBase = iReg - i;
  127702. pIn->nPrefix = i;
  127703. pLoop->wsFlags |= WHERE_IN_EARLYOUT;
  127704. }else{
  127705. pIn->nPrefix = 0;
  127706. }
  127707. }else{
  127708. pIn->eEndLoopOp = OP_Noop;
  127709. }
  127710. pIn++;
  127711. }
  127712. }
  127713. }else{
  127714. pLevel->u.in.nIn = 0;
  127715. }
  127716. sqlite3DbFree(pParse->db, aiMap);
  127717. #endif
  127718. }
  127719. disableTerm(pLevel, pTerm);
  127720. return iReg;
  127721. }
  127722. /*
  127723. ** Generate code that will evaluate all == and IN constraints for an
  127724. ** index scan.
  127725. **
  127726. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  127727. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  127728. ** The index has as many as three equality constraints, but in this
  127729. ** example, the third "c" value is an inequality. So only two
  127730. ** constraints are coded. This routine will generate code to evaluate
  127731. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  127732. ** in consecutive registers and the index of the first register is returned.
  127733. **
  127734. ** In the example above nEq==2. But this subroutine works for any value
  127735. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  127736. ** The only thing it does is allocate the pLevel->iMem memory cell and
  127737. ** compute the affinity string.
  127738. **
  127739. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  127740. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  127741. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  127742. ** occurs after the nEq quality constraints.
  127743. **
  127744. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  127745. ** the index of the first memory cell in that range. The code that
  127746. ** calls this routine will use that memory range to store keys for
  127747. ** start and termination conditions of the loop.
  127748. ** key value of the loop. If one or more IN operators appear, then
  127749. ** this routine allocates an additional nEq memory cells for internal
  127750. ** use.
  127751. **
  127752. ** Before returning, *pzAff is set to point to a buffer containing a
  127753. ** copy of the column affinity string of the index allocated using
  127754. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  127755. ** with equality constraints that use BLOB or NONE affinity are set to
  127756. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  127757. **
  127758. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  127759. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  127760. **
  127761. ** In the example above, the index on t1(a) has TEXT affinity. But since
  127762. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  127763. ** no conversion should be attempted before using a t2.b value as part of
  127764. ** a key to search the index. Hence the first byte in the returned affinity
  127765. ** string in this example would be set to SQLITE_AFF_BLOB.
  127766. */
  127767. static int codeAllEqualityTerms(
  127768. Parse *pParse, /* Parsing context */
  127769. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  127770. int bRev, /* Reverse the order of IN operators */
  127771. int nExtraReg, /* Number of extra registers to allocate */
  127772. char **pzAff /* OUT: Set to point to affinity string */
  127773. ){
  127774. u16 nEq; /* The number of == or IN constraints to code */
  127775. u16 nSkip; /* Number of left-most columns to skip */
  127776. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  127777. Index *pIdx; /* The index being used for this loop */
  127778. WhereTerm *pTerm; /* A single constraint term */
  127779. WhereLoop *pLoop; /* The WhereLoop object */
  127780. int j; /* Loop counter */
  127781. int regBase; /* Base register */
  127782. int nReg; /* Number of registers to allocate */
  127783. char *zAff; /* Affinity string to return */
  127784. /* This module is only called on query plans that use an index. */
  127785. pLoop = pLevel->pWLoop;
  127786. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  127787. nEq = pLoop->u.btree.nEq;
  127788. nSkip = pLoop->nSkip;
  127789. pIdx = pLoop->u.btree.pIndex;
  127790. assert( pIdx!=0 );
  127791. /* Figure out how many memory cells we will need then allocate them.
  127792. */
  127793. regBase = pParse->nMem + 1;
  127794. nReg = pLoop->u.btree.nEq + nExtraReg;
  127795. pParse->nMem += nReg;
  127796. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  127797. assert( zAff!=0 || pParse->db->mallocFailed );
  127798. if( nSkip ){
  127799. int iIdxCur = pLevel->iIdxCur;
  127800. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  127801. VdbeCoverageIf(v, bRev==0);
  127802. VdbeCoverageIf(v, bRev!=0);
  127803. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  127804. j = sqlite3VdbeAddOp0(v, OP_Goto);
  127805. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  127806. iIdxCur, 0, regBase, nSkip);
  127807. VdbeCoverageIf(v, bRev==0);
  127808. VdbeCoverageIf(v, bRev!=0);
  127809. sqlite3VdbeJumpHere(v, j);
  127810. for(j=0; j<nSkip; j++){
  127811. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  127812. testcase( pIdx->aiColumn[j]==XN_EXPR );
  127813. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  127814. }
  127815. }
  127816. /* Evaluate the equality constraints
  127817. */
  127818. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  127819. for(j=nSkip; j<nEq; j++){
  127820. int r1;
  127821. pTerm = pLoop->aLTerm[j];
  127822. assert( pTerm!=0 );
  127823. /* The following testcase is true for indices with redundant columns.
  127824. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  127825. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  127826. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  127827. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  127828. if( r1!=regBase+j ){
  127829. if( nReg==1 ){
  127830. sqlite3ReleaseTempReg(pParse, regBase);
  127831. regBase = r1;
  127832. }else{
  127833. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  127834. }
  127835. }
  127836. if( pTerm->eOperator & WO_IN ){
  127837. if( pTerm->pExpr->flags & EP_xIsSelect ){
  127838. /* No affinity ever needs to be (or should be) applied to a value
  127839. ** from the RHS of an "? IN (SELECT ...)" expression. The
  127840. ** sqlite3FindInIndex() routine has already ensured that the
  127841. ** affinity of the comparison has been applied to the value. */
  127842. if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
  127843. }
  127844. }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
  127845. Expr *pRight = pTerm->pExpr->pRight;
  127846. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  127847. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  127848. VdbeCoverage(v);
  127849. }
  127850. if( zAff ){
  127851. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  127852. zAff[j] = SQLITE_AFF_BLOB;
  127853. }
  127854. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  127855. zAff[j] = SQLITE_AFF_BLOB;
  127856. }
  127857. }
  127858. }
  127859. }
  127860. *pzAff = zAff;
  127861. return regBase;
  127862. }
  127863. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  127864. /*
  127865. ** If the most recently coded instruction is a constant range constraint
  127866. ** (a string literal) that originated from the LIKE optimization, then
  127867. ** set P3 and P5 on the OP_String opcode so that the string will be cast
  127868. ** to a BLOB at appropriate times.
  127869. **
  127870. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  127871. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  127872. ** scan loop run twice, once for strings and a second time for BLOBs.
  127873. ** The OP_String opcodes on the second pass convert the upper and lower
  127874. ** bound string constants to blobs. This routine makes the necessary changes
  127875. ** to the OP_String opcodes for that to happen.
  127876. **
  127877. ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
  127878. ** only the one pass through the string space is required, so this routine
  127879. ** becomes a no-op.
  127880. */
  127881. static void whereLikeOptimizationStringFixup(
  127882. Vdbe *v, /* prepared statement under construction */
  127883. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  127884. WhereTerm *pTerm /* The upper or lower bound just coded */
  127885. ){
  127886. if( pTerm->wtFlags & TERM_LIKEOPT ){
  127887. VdbeOp *pOp;
  127888. assert( pLevel->iLikeRepCntr>0 );
  127889. pOp = sqlite3VdbeGetOp(v, -1);
  127890. assert( pOp!=0 );
  127891. assert( pOp->opcode==OP_String8
  127892. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  127893. pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
  127894. pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
  127895. }
  127896. }
  127897. #else
  127898. # define whereLikeOptimizationStringFixup(A,B,C)
  127899. #endif
  127900. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  127901. /*
  127902. ** Information is passed from codeCursorHint() down to individual nodes of
  127903. ** the expression tree (by sqlite3WalkExpr()) using an instance of this
  127904. ** structure.
  127905. */
  127906. struct CCurHint {
  127907. int iTabCur; /* Cursor for the main table */
  127908. int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
  127909. Index *pIdx; /* The index used to access the table */
  127910. };
  127911. /*
  127912. ** This function is called for every node of an expression that is a candidate
  127913. ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
  127914. ** the table CCurHint.iTabCur, verify that the same column can be
  127915. ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
  127916. */
  127917. static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
  127918. struct CCurHint *pHint = pWalker->u.pCCurHint;
  127919. assert( pHint->pIdx!=0 );
  127920. if( pExpr->op==TK_COLUMN
  127921. && pExpr->iTable==pHint->iTabCur
  127922. && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
  127923. ){
  127924. pWalker->eCode = 1;
  127925. }
  127926. return WRC_Continue;
  127927. }
  127928. /*
  127929. ** Test whether or not expression pExpr, which was part of a WHERE clause,
  127930. ** should be included in the cursor-hint for a table that is on the rhs
  127931. ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
  127932. ** expression is not suitable.
  127933. **
  127934. ** An expression is unsuitable if it might evaluate to non NULL even if
  127935. ** a TK_COLUMN node that does affect the value of the expression is set
  127936. ** to NULL. For example:
  127937. **
  127938. ** col IS NULL
  127939. ** col IS NOT NULL
  127940. ** coalesce(col, 1)
  127941. ** CASE WHEN col THEN 0 ELSE 1 END
  127942. */
  127943. static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
  127944. if( pExpr->op==TK_IS
  127945. || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
  127946. || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
  127947. ){
  127948. pWalker->eCode = 1;
  127949. }else if( pExpr->op==TK_FUNCTION ){
  127950. int d1;
  127951. char d2[4];
  127952. if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
  127953. pWalker->eCode = 1;
  127954. }
  127955. }
  127956. return WRC_Continue;
  127957. }
  127958. /*
  127959. ** This function is called on every node of an expression tree used as an
  127960. ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
  127961. ** that accesses any table other than the one identified by
  127962. ** CCurHint.iTabCur, then do the following:
  127963. **
  127964. ** 1) allocate a register and code an OP_Column instruction to read
  127965. ** the specified column into the new register, and
  127966. **
  127967. ** 2) transform the expression node to a TK_REGISTER node that reads
  127968. ** from the newly populated register.
  127969. **
  127970. ** Also, if the node is a TK_COLUMN that does access the table idenified
  127971. ** by pCCurHint.iTabCur, and an index is being used (which we will
  127972. ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
  127973. ** an access of the index rather than the original table.
  127974. */
  127975. static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  127976. int rc = WRC_Continue;
  127977. struct CCurHint *pHint = pWalker->u.pCCurHint;
  127978. if( pExpr->op==TK_COLUMN ){
  127979. if( pExpr->iTable!=pHint->iTabCur ){
  127980. int reg = ++pWalker->pParse->nMem; /* Register for column value */
  127981. sqlite3ExprCode(pWalker->pParse, pExpr, reg);
  127982. pExpr->op = TK_REGISTER;
  127983. pExpr->iTable = reg;
  127984. }else if( pHint->pIdx!=0 ){
  127985. pExpr->iTable = pHint->iIdxCur;
  127986. pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
  127987. assert( pExpr->iColumn>=0 );
  127988. }
  127989. }else if( pExpr->op==TK_AGG_FUNCTION ){
  127990. /* An aggregate function in the WHERE clause of a query means this must
  127991. ** be a correlated sub-query, and expression pExpr is an aggregate from
  127992. ** the parent context. Do not walk the function arguments in this case.
  127993. **
  127994. ** todo: It should be possible to replace this node with a TK_REGISTER
  127995. ** expression, as the result of the expression must be stored in a
  127996. ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
  127997. rc = WRC_Prune;
  127998. }
  127999. return rc;
  128000. }
  128001. /*
  128002. ** Insert an OP_CursorHint instruction if it is appropriate to do so.
  128003. */
  128004. static void codeCursorHint(
  128005. struct SrcList_item *pTabItem, /* FROM clause item */
  128006. WhereInfo *pWInfo, /* The where clause */
  128007. WhereLevel *pLevel, /* Which loop to provide hints for */
  128008. WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
  128009. ){
  128010. Parse *pParse = pWInfo->pParse;
  128011. sqlite3 *db = pParse->db;
  128012. Vdbe *v = pParse->pVdbe;
  128013. Expr *pExpr = 0;
  128014. WhereLoop *pLoop = pLevel->pWLoop;
  128015. int iCur;
  128016. WhereClause *pWC;
  128017. WhereTerm *pTerm;
  128018. int i, j;
  128019. struct CCurHint sHint;
  128020. Walker sWalker;
  128021. if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
  128022. iCur = pLevel->iTabCur;
  128023. assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
  128024. sHint.iTabCur = iCur;
  128025. sHint.iIdxCur = pLevel->iIdxCur;
  128026. sHint.pIdx = pLoop->u.btree.pIndex;
  128027. memset(&sWalker, 0, sizeof(sWalker));
  128028. sWalker.pParse = pParse;
  128029. sWalker.u.pCCurHint = &sHint;
  128030. pWC = &pWInfo->sWC;
  128031. for(i=0; i<pWC->nTerm; i++){
  128032. pTerm = &pWC->a[i];
  128033. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  128034. if( pTerm->prereqAll & pLevel->notReady ) continue;
  128035. /* Any terms specified as part of the ON(...) clause for any LEFT
  128036. ** JOIN for which the current table is not the rhs are omitted
  128037. ** from the cursor-hint.
  128038. **
  128039. ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
  128040. ** that were specified as part of the WHERE clause must be excluded.
  128041. ** This is to address the following:
  128042. **
  128043. ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
  128044. **
  128045. ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
  128046. ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
  128047. ** pushed down to the cursor, this row is filtered out, causing
  128048. ** SQLite to synthesize a row of NULL values. Which does match the
  128049. ** WHERE clause, and so the query returns a row. Which is incorrect.
  128050. **
  128051. ** For the same reason, WHERE terms such as:
  128052. **
  128053. ** WHERE 1 = (t2.c IS NULL)
  128054. **
  128055. ** are also excluded. See codeCursorHintIsOrFunction() for details.
  128056. */
  128057. if( pTabItem->fg.jointype & JT_LEFT ){
  128058. Expr *pExpr = pTerm->pExpr;
  128059. if( !ExprHasProperty(pExpr, EP_FromJoin)
  128060. || pExpr->iRightJoinTable!=pTabItem->iCursor
  128061. ){
  128062. sWalker.eCode = 0;
  128063. sWalker.xExprCallback = codeCursorHintIsOrFunction;
  128064. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  128065. if( sWalker.eCode ) continue;
  128066. }
  128067. }else{
  128068. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
  128069. }
  128070. /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
  128071. ** the cursor. These terms are not needed as hints for a pure range
  128072. ** scan (that has no == terms) so omit them. */
  128073. if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
  128074. for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
  128075. if( j<pLoop->nLTerm ) continue;
  128076. }
  128077. /* No subqueries or non-deterministic functions allowed */
  128078. if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
  128079. /* For an index scan, make sure referenced columns are actually in
  128080. ** the index. */
  128081. if( sHint.pIdx!=0 ){
  128082. sWalker.eCode = 0;
  128083. sWalker.xExprCallback = codeCursorHintCheckExpr;
  128084. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  128085. if( sWalker.eCode ) continue;
  128086. }
  128087. /* If we survive all prior tests, that means this term is worth hinting */
  128088. pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  128089. }
  128090. if( pExpr!=0 ){
  128091. sWalker.xExprCallback = codeCursorHintFixExpr;
  128092. sqlite3WalkExpr(&sWalker, pExpr);
  128093. sqlite3VdbeAddOp4(v, OP_CursorHint,
  128094. (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
  128095. (const char*)pExpr, P4_EXPR);
  128096. }
  128097. }
  128098. #else
  128099. # define codeCursorHint(A,B,C,D) /* No-op */
  128100. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  128101. /*
  128102. ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
  128103. ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
  128104. ** function generates code to do a deferred seek of cursor iCur to the
  128105. ** rowid stored in register iRowid.
  128106. **
  128107. ** Normally, this is just:
  128108. **
  128109. ** OP_DeferredSeek $iCur $iRowid
  128110. **
  128111. ** However, if the scan currently being coded is a branch of an OR-loop and
  128112. ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
  128113. ** is set to iIdxCur and P4 is set to point to an array of integers
  128114. ** containing one entry for each column of the table cursor iCur is open
  128115. ** on. For each table column, if the column is the i'th column of the
  128116. ** index, then the corresponding array entry is set to (i+1). If the column
  128117. ** does not appear in the index at all, the array entry is set to 0.
  128118. */
  128119. static void codeDeferredSeek(
  128120. WhereInfo *pWInfo, /* Where clause context */
  128121. Index *pIdx, /* Index scan is using */
  128122. int iCur, /* Cursor for IPK b-tree */
  128123. int iIdxCur /* Index cursor */
  128124. ){
  128125. Parse *pParse = pWInfo->pParse; /* Parse context */
  128126. Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
  128127. assert( iIdxCur>0 );
  128128. assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
  128129. sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
  128130. if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  128131. && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
  128132. ){
  128133. int i;
  128134. Table *pTab = pIdx->pTable;
  128135. int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
  128136. if( ai ){
  128137. ai[0] = pTab->nCol;
  128138. for(i=0; i<pIdx->nColumn-1; i++){
  128139. assert( pIdx->aiColumn[i]<pTab->nCol );
  128140. if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
  128141. }
  128142. sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
  128143. }
  128144. }
  128145. }
  128146. /*
  128147. ** If the expression passed as the second argument is a vector, generate
  128148. ** code to write the first nReg elements of the vector into an array
  128149. ** of registers starting with iReg.
  128150. **
  128151. ** If the expression is not a vector, then nReg must be passed 1. In
  128152. ** this case, generate code to evaluate the expression and leave the
  128153. ** result in register iReg.
  128154. */
  128155. static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
  128156. assert( nReg>0 );
  128157. if( p && sqlite3ExprIsVector(p) ){
  128158. #ifndef SQLITE_OMIT_SUBQUERY
  128159. if( (p->flags & EP_xIsSelect) ){
  128160. Vdbe *v = pParse->pVdbe;
  128161. int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
  128162. sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
  128163. }else
  128164. #endif
  128165. {
  128166. int i;
  128167. ExprList *pList = p->x.pList;
  128168. assert( nReg<=pList->nExpr );
  128169. for(i=0; i<nReg; i++){
  128170. sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
  128171. }
  128172. }
  128173. }else{
  128174. assert( nReg==1 );
  128175. sqlite3ExprCode(pParse, p, iReg);
  128176. }
  128177. }
  128178. /* An instance of the IdxExprTrans object carries information about a
  128179. ** mapping from an expression on table columns into a column in an index
  128180. ** down through the Walker.
  128181. */
  128182. typedef struct IdxExprTrans {
  128183. Expr *pIdxExpr; /* The index expression */
  128184. int iTabCur; /* The cursor of the corresponding table */
  128185. int iIdxCur; /* The cursor for the index */
  128186. int iIdxCol; /* The column for the index */
  128187. } IdxExprTrans;
  128188. /* The walker node callback used to transform matching expressions into
  128189. ** a reference to an index column for an index on an expression.
  128190. **
  128191. ** If pExpr matches, then transform it into a reference to the index column
  128192. ** that contains the value of pExpr.
  128193. */
  128194. static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
  128195. IdxExprTrans *pX = p->u.pIdxTrans;
  128196. if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
  128197. pExpr->op = TK_COLUMN;
  128198. pExpr->iTable = pX->iIdxCur;
  128199. pExpr->iColumn = pX->iIdxCol;
  128200. pExpr->y.pTab = 0;
  128201. return WRC_Prune;
  128202. }else{
  128203. return WRC_Continue;
  128204. }
  128205. }
  128206. /*
  128207. ** For an indexes on expression X, locate every instance of expression X
  128208. ** in pExpr and change that subexpression into a reference to the appropriate
  128209. ** column of the index.
  128210. */
  128211. static void whereIndexExprTrans(
  128212. Index *pIdx, /* The Index */
  128213. int iTabCur, /* Cursor of the table that is being indexed */
  128214. int iIdxCur, /* Cursor of the index itself */
  128215. WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
  128216. ){
  128217. int iIdxCol; /* Column number of the index */
  128218. ExprList *aColExpr; /* Expressions that are indexed */
  128219. Walker w;
  128220. IdxExprTrans x;
  128221. aColExpr = pIdx->aColExpr;
  128222. if( aColExpr==0 ) return; /* Not an index on expressions */
  128223. memset(&w, 0, sizeof(w));
  128224. w.xExprCallback = whereIndexExprTransNode;
  128225. w.u.pIdxTrans = &x;
  128226. x.iTabCur = iTabCur;
  128227. x.iIdxCur = iIdxCur;
  128228. for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
  128229. if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
  128230. assert( aColExpr->a[iIdxCol].pExpr!=0 );
  128231. x.iIdxCol = iIdxCol;
  128232. x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
  128233. sqlite3WalkExpr(&w, pWInfo->pWhere);
  128234. sqlite3WalkExprList(&w, pWInfo->pOrderBy);
  128235. sqlite3WalkExprList(&w, pWInfo->pResultSet);
  128236. }
  128237. }
  128238. /*
  128239. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  128240. ** implementation described by pWInfo.
  128241. */
  128242. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  128243. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  128244. int iLevel, /* Which level of pWInfo->a[] should be coded */
  128245. Bitmask notReady /* Which tables are currently available */
  128246. ){
  128247. int j, k; /* Loop counters */
  128248. int iCur; /* The VDBE cursor for the table */
  128249. int addrNxt; /* Where to jump to continue with the next IN case */
  128250. int omitTable; /* True if we use the index only */
  128251. int bRev; /* True if we need to scan in reverse order */
  128252. WhereLevel *pLevel; /* The where level to be coded */
  128253. WhereLoop *pLoop; /* The WhereLoop object being coded */
  128254. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  128255. WhereTerm *pTerm; /* A WHERE clause term */
  128256. Parse *pParse; /* Parsing context */
  128257. sqlite3 *db; /* Database connection */
  128258. Vdbe *v; /* The prepared stmt under constructions */
  128259. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  128260. int addrBrk; /* Jump here to break out of the loop */
  128261. int addrHalt; /* addrBrk for the outermost loop */
  128262. int addrCont; /* Jump here to continue with next cycle */
  128263. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  128264. int iReleaseReg = 0; /* Temp register to free before returning */
  128265. Index *pIdx = 0; /* Index used by loop (if any) */
  128266. int iLoop; /* Iteration of constraint generator loop */
  128267. pParse = pWInfo->pParse;
  128268. v = pParse->pVdbe;
  128269. pWC = &pWInfo->sWC;
  128270. db = pParse->db;
  128271. pLevel = &pWInfo->a[iLevel];
  128272. pLoop = pLevel->pWLoop;
  128273. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  128274. iCur = pTabItem->iCursor;
  128275. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  128276. bRev = (pWInfo->revMask>>iLevel)&1;
  128277. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  128278. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
  128279. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  128280. /* Create labels for the "break" and "continue" instructions
  128281. ** for the current loop. Jump to addrBrk to break out of a loop.
  128282. ** Jump to cont to go immediately to the next iteration of the
  128283. ** loop.
  128284. **
  128285. ** When there is an IN operator, we also have a "addrNxt" label that
  128286. ** means to continue with the next IN value combination. When
  128287. ** there are no IN operators in the constraints, the "addrNxt" label
  128288. ** is the same as "addrBrk".
  128289. */
  128290. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  128291. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  128292. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  128293. ** initialize a memory cell that records if this table matches any
  128294. ** row of the left table of the join.
  128295. */
  128296. assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  128297. || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
  128298. );
  128299. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  128300. pLevel->iLeftJoin = ++pParse->nMem;
  128301. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  128302. VdbeComment((v, "init LEFT JOIN no-match flag"));
  128303. }
  128304. /* Compute a safe address to jump to if we discover that the table for
  128305. ** this loop is empty and can never contribute content. */
  128306. for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
  128307. addrHalt = pWInfo->a[j].addrBrk;
  128308. /* Special case of a FROM clause subquery implemented as a co-routine */
  128309. if( pTabItem->fg.viaCoroutine ){
  128310. int regYield = pTabItem->regReturn;
  128311. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  128312. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  128313. VdbeCoverage(v);
  128314. VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
  128315. pLevel->op = OP_Goto;
  128316. }else
  128317. #ifndef SQLITE_OMIT_VIRTUALTABLE
  128318. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  128319. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  128320. ** to access the data.
  128321. */
  128322. int iReg; /* P3 Value for OP_VFilter */
  128323. int addrNotFound;
  128324. int nConstraint = pLoop->nLTerm;
  128325. int iIn; /* Counter for IN constraints */
  128326. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  128327. addrNotFound = pLevel->addrBrk;
  128328. for(j=0; j<nConstraint; j++){
  128329. int iTarget = iReg+j+2;
  128330. pTerm = pLoop->aLTerm[j];
  128331. if( NEVER(pTerm==0) ) continue;
  128332. if( pTerm->eOperator & WO_IN ){
  128333. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  128334. addrNotFound = pLevel->addrNxt;
  128335. }else{
  128336. Expr *pRight = pTerm->pExpr->pRight;
  128337. codeExprOrVector(pParse, pRight, iTarget, 1);
  128338. }
  128339. }
  128340. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  128341. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  128342. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  128343. pLoop->u.vtab.idxStr,
  128344. pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
  128345. VdbeCoverage(v);
  128346. pLoop->u.vtab.needFree = 0;
  128347. pLevel->p1 = iCur;
  128348. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  128349. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  128350. iIn = pLevel->u.in.nIn;
  128351. for(j=nConstraint-1; j>=0; j--){
  128352. pTerm = pLoop->aLTerm[j];
  128353. if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
  128354. disableTerm(pLevel, pTerm);
  128355. }else if( (pTerm->eOperator & WO_IN)!=0 ){
  128356. Expr *pCompare; /* The comparison operator */
  128357. Expr *pRight; /* RHS of the comparison */
  128358. VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
  128359. /* Reload the constraint value into reg[iReg+j+2]. The same value
  128360. ** was loaded into the same register prior to the OP_VFilter, but
  128361. ** the xFilter implementation might have changed the datatype or
  128362. ** encoding of the value in the register, so it *must* be reloaded. */
  128363. assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
  128364. if( !db->mallocFailed ){
  128365. assert( iIn>0 );
  128366. pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
  128367. assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
  128368. assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
  128369. assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
  128370. testcase( pOp->opcode==OP_Rowid );
  128371. sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
  128372. }
  128373. /* Generate code that will continue to the next row if
  128374. ** the IN constraint is not satisfied */
  128375. pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
  128376. assert( pCompare!=0 || db->mallocFailed );
  128377. if( pCompare ){
  128378. pCompare->pLeft = pTerm->pExpr->pLeft;
  128379. pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
  128380. if( pRight ){
  128381. pRight->iTable = iReg+j+2;
  128382. sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
  128383. }
  128384. pCompare->pLeft = 0;
  128385. sqlite3ExprDelete(db, pCompare);
  128386. }
  128387. }
  128388. }
  128389. /* These registers need to be preserved in case there is an IN operator
  128390. ** loop. So we could deallocate the registers here (and potentially
  128391. ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
  128392. ** simpler and safer to simply not reuse the registers.
  128393. **
  128394. ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  128395. */
  128396. }else
  128397. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  128398. if( (pLoop->wsFlags & WHERE_IPK)!=0
  128399. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  128400. ){
  128401. /* Case 2: We can directly reference a single row using an
  128402. ** equality comparison against the ROWID field. Or
  128403. ** we reference multiple rows using a "rowid IN (...)"
  128404. ** construct.
  128405. */
  128406. assert( pLoop->u.btree.nEq==1 );
  128407. pTerm = pLoop->aLTerm[0];
  128408. assert( pTerm!=0 );
  128409. assert( pTerm->pExpr!=0 );
  128410. assert( omitTable==0 );
  128411. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  128412. iReleaseReg = ++pParse->nMem;
  128413. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  128414. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  128415. addrNxt = pLevel->addrNxt;
  128416. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
  128417. VdbeCoverage(v);
  128418. pLevel->op = OP_Noop;
  128419. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  128420. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  128421. ){
  128422. /* Case 3: We have an inequality comparison against the ROWID field.
  128423. */
  128424. int testOp = OP_Noop;
  128425. int start;
  128426. int memEndValue = 0;
  128427. WhereTerm *pStart, *pEnd;
  128428. assert( omitTable==0 );
  128429. j = 0;
  128430. pStart = pEnd = 0;
  128431. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  128432. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  128433. assert( pStart!=0 || pEnd!=0 );
  128434. if( bRev ){
  128435. pTerm = pStart;
  128436. pStart = pEnd;
  128437. pEnd = pTerm;
  128438. }
  128439. codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
  128440. if( pStart ){
  128441. Expr *pX; /* The expression that defines the start bound */
  128442. int r1, rTemp; /* Registers for holding the start boundary */
  128443. int op; /* Cursor seek operation */
  128444. /* The following constant maps TK_xx codes into corresponding
  128445. ** seek opcodes. It depends on a particular ordering of TK_xx
  128446. */
  128447. const u8 aMoveOp[] = {
  128448. /* TK_GT */ OP_SeekGT,
  128449. /* TK_LE */ OP_SeekLE,
  128450. /* TK_LT */ OP_SeekLT,
  128451. /* TK_GE */ OP_SeekGE
  128452. };
  128453. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  128454. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  128455. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  128456. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  128457. testcase( pStart->wtFlags & TERM_VIRTUAL );
  128458. pX = pStart->pExpr;
  128459. assert( pX!=0 );
  128460. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  128461. if( sqlite3ExprIsVector(pX->pRight) ){
  128462. r1 = rTemp = sqlite3GetTempReg(pParse);
  128463. codeExprOrVector(pParse, pX->pRight, r1, 1);
  128464. testcase( pX->op==TK_GT );
  128465. testcase( pX->op==TK_GE );
  128466. testcase( pX->op==TK_LT );
  128467. testcase( pX->op==TK_LE );
  128468. op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
  128469. assert( pX->op!=TK_GT || op==OP_SeekGE );
  128470. assert( pX->op!=TK_GE || op==OP_SeekGE );
  128471. assert( pX->op!=TK_LT || op==OP_SeekLE );
  128472. assert( pX->op!=TK_LE || op==OP_SeekLE );
  128473. }else{
  128474. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  128475. disableTerm(pLevel, pStart);
  128476. op = aMoveOp[(pX->op - TK_GT)];
  128477. }
  128478. sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
  128479. VdbeComment((v, "pk"));
  128480. VdbeCoverageIf(v, pX->op==TK_GT);
  128481. VdbeCoverageIf(v, pX->op==TK_LE);
  128482. VdbeCoverageIf(v, pX->op==TK_LT);
  128483. VdbeCoverageIf(v, pX->op==TK_GE);
  128484. sqlite3ReleaseTempReg(pParse, rTemp);
  128485. }else{
  128486. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
  128487. VdbeCoverageIf(v, bRev==0);
  128488. VdbeCoverageIf(v, bRev!=0);
  128489. }
  128490. if( pEnd ){
  128491. Expr *pX;
  128492. pX = pEnd->pExpr;
  128493. assert( pX!=0 );
  128494. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  128495. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  128496. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  128497. memEndValue = ++pParse->nMem;
  128498. codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
  128499. if( 0==sqlite3ExprIsVector(pX->pRight)
  128500. && (pX->op==TK_LT || pX->op==TK_GT)
  128501. ){
  128502. testOp = bRev ? OP_Le : OP_Ge;
  128503. }else{
  128504. testOp = bRev ? OP_Lt : OP_Gt;
  128505. }
  128506. if( 0==sqlite3ExprIsVector(pX->pRight) ){
  128507. disableTerm(pLevel, pEnd);
  128508. }
  128509. }
  128510. start = sqlite3VdbeCurrentAddr(v);
  128511. pLevel->op = bRev ? OP_Prev : OP_Next;
  128512. pLevel->p1 = iCur;
  128513. pLevel->p2 = start;
  128514. assert( pLevel->p5==0 );
  128515. if( testOp!=OP_Noop ){
  128516. iRowidReg = ++pParse->nMem;
  128517. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  128518. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  128519. VdbeCoverageIf(v, testOp==OP_Le);
  128520. VdbeCoverageIf(v, testOp==OP_Lt);
  128521. VdbeCoverageIf(v, testOp==OP_Ge);
  128522. VdbeCoverageIf(v, testOp==OP_Gt);
  128523. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  128524. }
  128525. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  128526. /* Case 4: A scan using an index.
  128527. **
  128528. ** The WHERE clause may contain zero or more equality
  128529. ** terms ("==" or "IN" operators) that refer to the N
  128530. ** left-most columns of the index. It may also contain
  128531. ** inequality constraints (>, <, >= or <=) on the indexed
  128532. ** column that immediately follows the N equalities. Only
  128533. ** the right-most column can be an inequality - the rest must
  128534. ** use the "==" and "IN" operators. For example, if the
  128535. ** index is on (x,y,z), then the following clauses are all
  128536. ** optimized:
  128537. **
  128538. ** x=5
  128539. ** x=5 AND y=10
  128540. ** x=5 AND y<10
  128541. ** x=5 AND y>5 AND y<10
  128542. ** x=5 AND y=5 AND z<=10
  128543. **
  128544. ** The z<10 term of the following cannot be used, only
  128545. ** the x=5 term:
  128546. **
  128547. ** x=5 AND z<10
  128548. **
  128549. ** N may be zero if there are inequality constraints.
  128550. ** If there are no inequality constraints, then N is at
  128551. ** least one.
  128552. **
  128553. ** This case is also used when there are no WHERE clause
  128554. ** constraints but an index is selected anyway, in order
  128555. ** to force the output order to conform to an ORDER BY.
  128556. */
  128557. static const u8 aStartOp[] = {
  128558. 0,
  128559. 0,
  128560. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  128561. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  128562. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  128563. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  128564. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  128565. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  128566. };
  128567. static const u8 aEndOp[] = {
  128568. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  128569. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  128570. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  128571. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  128572. };
  128573. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  128574. u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
  128575. u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
  128576. int regBase; /* Base register holding constraint values */
  128577. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  128578. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  128579. int startEq; /* True if range start uses ==, >= or <= */
  128580. int endEq; /* True if range end uses ==, >= or <= */
  128581. int start_constraints; /* Start of range is constrained */
  128582. int nConstraint; /* Number of constraint terms */
  128583. int iIdxCur; /* The VDBE cursor for the index */
  128584. int nExtraReg = 0; /* Number of extra registers needed */
  128585. int op; /* Instruction opcode */
  128586. char *zStartAff; /* Affinity for start of range constraint */
  128587. char *zEndAff = 0; /* Affinity for end of range constraint */
  128588. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  128589. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  128590. pIdx = pLoop->u.btree.pIndex;
  128591. iIdxCur = pLevel->iIdxCur;
  128592. assert( nEq>=pLoop->nSkip );
  128593. /* If this loop satisfies a sort order (pOrderBy) request that
  128594. ** was passed to this function to implement a "SELECT min(x) ..."
  128595. ** query, then the caller will only allow the loop to run for
  128596. ** a single iteration. This means that the first row returned
  128597. ** should not have a NULL value stored in 'x'. If column 'x' is
  128598. ** the first one after the nEq equality constraints in the index,
  128599. ** this requires some special handling.
  128600. */
  128601. assert( pWInfo->pOrderBy==0
  128602. || pWInfo->pOrderBy->nExpr==1
  128603. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  128604. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  128605. && pWInfo->nOBSat>0
  128606. && (pIdx->nKeyCol>nEq)
  128607. ){
  128608. assert( pLoop->nSkip==0 );
  128609. bSeekPastNull = 1;
  128610. nExtraReg = 1;
  128611. }
  128612. /* Find any inequality constraint terms for the start and end
  128613. ** of the range.
  128614. */
  128615. j = nEq;
  128616. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  128617. pRangeStart = pLoop->aLTerm[j++];
  128618. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
  128619. /* Like optimization range constraints always occur in pairs */
  128620. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  128621. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  128622. }
  128623. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  128624. pRangeEnd = pLoop->aLTerm[j++];
  128625. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
  128626. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  128627. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  128628. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  128629. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  128630. pLevel->iLikeRepCntr = (u32)++pParse->nMem;
  128631. sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
  128632. VdbeComment((v, "LIKE loop counter"));
  128633. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  128634. /* iLikeRepCntr actually stores 2x the counter register number. The
  128635. ** bottom bit indicates whether the search order is ASC or DESC. */
  128636. testcase( bRev );
  128637. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  128638. assert( (bRev & ~1)==0 );
  128639. pLevel->iLikeRepCntr <<=1;
  128640. pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
  128641. }
  128642. #endif
  128643. if( pRangeStart==0 ){
  128644. j = pIdx->aiColumn[nEq];
  128645. if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
  128646. bSeekPastNull = 1;
  128647. }
  128648. }
  128649. }
  128650. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  128651. /* If we are doing a reverse order scan on an ascending index, or
  128652. ** a forward order scan on a descending index, interchange the
  128653. ** start and end terms (pRangeStart and pRangeEnd).
  128654. */
  128655. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  128656. || (bRev && pIdx->nKeyCol==nEq)
  128657. ){
  128658. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  128659. SWAP(u8, bSeekPastNull, bStopAtNull);
  128660. SWAP(u8, nBtm, nTop);
  128661. }
  128662. /* Generate code to evaluate all constraint terms using == or IN
  128663. ** and store the values of those terms in an array of registers
  128664. ** starting at regBase.
  128665. */
  128666. codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
  128667. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  128668. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  128669. if( zStartAff && nTop ){
  128670. zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
  128671. }
  128672. addrNxt = pLevel->addrNxt;
  128673. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  128674. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  128675. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  128676. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  128677. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  128678. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  128679. start_constraints = pRangeStart || nEq>0;
  128680. /* Seek the index cursor to the start of the range. */
  128681. nConstraint = nEq;
  128682. if( pRangeStart ){
  128683. Expr *pRight = pRangeStart->pExpr->pRight;
  128684. codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
  128685. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  128686. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  128687. && sqlite3ExprCanBeNull(pRight)
  128688. ){
  128689. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  128690. VdbeCoverage(v);
  128691. }
  128692. if( zStartAff ){
  128693. updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
  128694. }
  128695. nConstraint += nBtm;
  128696. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  128697. if( sqlite3ExprIsVector(pRight)==0 ){
  128698. disableTerm(pLevel, pRangeStart);
  128699. }else{
  128700. startEq = 1;
  128701. }
  128702. bSeekPastNull = 0;
  128703. }else if( bSeekPastNull ){
  128704. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  128705. nConstraint++;
  128706. startEq = 0;
  128707. start_constraints = 1;
  128708. }
  128709. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  128710. if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
  128711. /* The skip-scan logic inside the call to codeAllEqualityConstraints()
  128712. ** above has already left the cursor sitting on the correct row,
  128713. ** so no further seeking is needed */
  128714. }else{
  128715. if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
  128716. sqlite3VdbeAddOp1(v, OP_SeekHit, iIdxCur);
  128717. }
  128718. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  128719. assert( op!=0 );
  128720. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  128721. VdbeCoverage(v);
  128722. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  128723. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  128724. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  128725. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  128726. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  128727. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  128728. }
  128729. /* Load the value for the inequality constraint at the end of the
  128730. ** range (if any).
  128731. */
  128732. nConstraint = nEq;
  128733. if( pRangeEnd ){
  128734. Expr *pRight = pRangeEnd->pExpr->pRight;
  128735. codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
  128736. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  128737. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  128738. && sqlite3ExprCanBeNull(pRight)
  128739. ){
  128740. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  128741. VdbeCoverage(v);
  128742. }
  128743. if( zEndAff ){
  128744. updateRangeAffinityStr(pRight, nTop, zEndAff);
  128745. codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
  128746. }else{
  128747. assert( pParse->db->mallocFailed );
  128748. }
  128749. nConstraint += nTop;
  128750. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  128751. if( sqlite3ExprIsVector(pRight)==0 ){
  128752. disableTerm(pLevel, pRangeEnd);
  128753. }else{
  128754. endEq = 1;
  128755. }
  128756. }else if( bStopAtNull ){
  128757. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  128758. endEq = 0;
  128759. nConstraint++;
  128760. }
  128761. sqlite3DbFree(db, zStartAff);
  128762. sqlite3DbFree(db, zEndAff);
  128763. /* Top of the loop body */
  128764. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  128765. /* Check if the index cursor is past the end of the range. */
  128766. if( nConstraint ){
  128767. op = aEndOp[bRev*2 + endEq];
  128768. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  128769. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  128770. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  128771. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  128772. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  128773. }
  128774. if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
  128775. sqlite3VdbeAddOp2(v, OP_SeekHit, iIdxCur, 1);
  128776. }
  128777. /* Seek the table cursor, if required */
  128778. if( omitTable ){
  128779. /* pIdx is a covering index. No need to access the main table. */
  128780. }else if( HasRowid(pIdx->pTable) ){
  128781. if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
  128782. (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
  128783. && (pWInfo->eOnePass==ONEPASS_SINGLE)
  128784. )){
  128785. iRowidReg = ++pParse->nMem;
  128786. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  128787. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  128788. VdbeCoverage(v);
  128789. }else{
  128790. codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
  128791. }
  128792. }else if( iCur!=iIdxCur ){
  128793. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  128794. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  128795. for(j=0; j<pPk->nKeyCol; j++){
  128796. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  128797. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  128798. }
  128799. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  128800. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  128801. }
  128802. /* If pIdx is an index on one or more expressions, then look through
  128803. ** all the expressions in pWInfo and try to transform matching expressions
  128804. ** into reference to index columns.
  128805. **
  128806. ** Do not do this for the RHS of a LEFT JOIN. This is because the
  128807. ** expression may be evaluated after OP_NullRow has been executed on
  128808. ** the cursor. In this case it is important to do the full evaluation,
  128809. ** as the result of the expression may not be NULL, even if all table
  128810. ** column values are. https://www.sqlite.org/src/info/7fa8049685b50b5a
  128811. */
  128812. if( pLevel->iLeftJoin==0 ){
  128813. whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
  128814. }
  128815. /* Record the instruction used to terminate the loop. */
  128816. if( pLoop->wsFlags & WHERE_ONEROW ){
  128817. pLevel->op = OP_Noop;
  128818. }else if( bRev ){
  128819. pLevel->op = OP_Prev;
  128820. }else{
  128821. pLevel->op = OP_Next;
  128822. }
  128823. pLevel->p1 = iIdxCur;
  128824. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  128825. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  128826. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  128827. }else{
  128828. assert( pLevel->p5==0 );
  128829. }
  128830. if( omitTable ) pIdx = 0;
  128831. }else
  128832. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  128833. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  128834. /* Case 5: Two or more separately indexed terms connected by OR
  128835. **
  128836. ** Example:
  128837. **
  128838. ** CREATE TABLE t1(a,b,c,d);
  128839. ** CREATE INDEX i1 ON t1(a);
  128840. ** CREATE INDEX i2 ON t1(b);
  128841. ** CREATE INDEX i3 ON t1(c);
  128842. **
  128843. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  128844. **
  128845. ** In the example, there are three indexed terms connected by OR.
  128846. ** The top of the loop looks like this:
  128847. **
  128848. ** Null 1 # Zero the rowset in reg 1
  128849. **
  128850. ** Then, for each indexed term, the following. The arguments to
  128851. ** RowSetTest are such that the rowid of the current row is inserted
  128852. ** into the RowSet. If it is already present, control skips the
  128853. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  128854. **
  128855. ** sqlite3WhereBegin(<term>)
  128856. ** RowSetTest # Insert rowid into rowset
  128857. ** Gosub 2 A
  128858. ** sqlite3WhereEnd()
  128859. **
  128860. ** Following the above, code to terminate the loop. Label A, the target
  128861. ** of the Gosub above, jumps to the instruction right after the Goto.
  128862. **
  128863. ** Null 1 # Zero the rowset in reg 1
  128864. ** Goto B # The loop is finished.
  128865. **
  128866. ** A: <loop body> # Return data, whatever.
  128867. **
  128868. ** Return 2 # Jump back to the Gosub
  128869. **
  128870. ** B: <after the loop>
  128871. **
  128872. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  128873. ** use an ephemeral index instead of a RowSet to record the primary
  128874. ** keys of the rows we have already seen.
  128875. **
  128876. */
  128877. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  128878. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  128879. Index *pCov = 0; /* Potential covering index (or NULL) */
  128880. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  128881. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  128882. int regRowset = 0; /* Register for RowSet object */
  128883. int regRowid = 0; /* Register holding rowid */
  128884. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  128885. int iRetInit; /* Address of regReturn init */
  128886. int untestedTerms = 0; /* Some terms not completely tested */
  128887. int ii; /* Loop counter */
  128888. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  128889. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  128890. Table *pTab = pTabItem->pTab;
  128891. pTerm = pLoop->aLTerm[0];
  128892. assert( pTerm!=0 );
  128893. assert( pTerm->eOperator & WO_OR );
  128894. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  128895. pOrWc = &pTerm->u.pOrInfo->wc;
  128896. pLevel->op = OP_Return;
  128897. pLevel->p1 = regReturn;
  128898. /* Set up a new SrcList in pOrTab containing the table being scanned
  128899. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  128900. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  128901. */
  128902. if( pWInfo->nLevel>1 ){
  128903. int nNotReady; /* The number of notReady tables */
  128904. struct SrcList_item *origSrc; /* Original list of tables */
  128905. nNotReady = pWInfo->nLevel - iLevel - 1;
  128906. pOrTab = sqlite3StackAllocRaw(db,
  128907. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  128908. if( pOrTab==0 ) return notReady;
  128909. pOrTab->nAlloc = (u8)(nNotReady + 1);
  128910. pOrTab->nSrc = pOrTab->nAlloc;
  128911. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  128912. origSrc = pWInfo->pTabList->a;
  128913. for(k=1; k<=nNotReady; k++){
  128914. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  128915. }
  128916. }else{
  128917. pOrTab = pWInfo->pTabList;
  128918. }
  128919. /* Initialize the rowset register to contain NULL. An SQL NULL is
  128920. ** equivalent to an empty rowset. Or, create an ephemeral index
  128921. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  128922. **
  128923. ** Also initialize regReturn to contain the address of the instruction
  128924. ** immediately following the OP_Return at the bottom of the loop. This
  128925. ** is required in a few obscure LEFT JOIN cases where control jumps
  128926. ** over the top of the loop into the body of it. In this case the
  128927. ** correct response for the end-of-loop code (the OP_Return) is to
  128928. ** fall through to the next instruction, just as an OP_Next does if
  128929. ** called on an uninitialized cursor.
  128930. */
  128931. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  128932. if( HasRowid(pTab) ){
  128933. regRowset = ++pParse->nMem;
  128934. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  128935. }else{
  128936. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  128937. regRowset = pParse->nTab++;
  128938. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  128939. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  128940. }
  128941. regRowid = ++pParse->nMem;
  128942. }
  128943. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  128944. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  128945. ** Then for every term xN, evaluate as the subexpression: xN AND z
  128946. ** That way, terms in y that are factored into the disjunction will
  128947. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  128948. **
  128949. ** Actually, each subexpression is converted to "xN AND w" where w is
  128950. ** the "interesting" terms of z - terms that did not originate in the
  128951. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  128952. ** indices.
  128953. **
  128954. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  128955. ** is not contained in the ON clause of a LEFT JOIN.
  128956. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  128957. */
  128958. if( pWC->nTerm>1 ){
  128959. int iTerm;
  128960. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  128961. Expr *pExpr = pWC->a[iTerm].pExpr;
  128962. if( &pWC->a[iTerm] == pTerm ) continue;
  128963. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  128964. testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
  128965. if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
  128966. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  128967. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  128968. pExpr = sqlite3ExprDup(db, pExpr, 0);
  128969. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  128970. }
  128971. if( pAndExpr ){
  128972. pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
  128973. }
  128974. }
  128975. /* Run a separate WHERE clause for each term of the OR clause. After
  128976. ** eliminating duplicates from other WHERE clauses, the action for each
  128977. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  128978. */
  128979. wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
  128980. ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
  128981. for(ii=0; ii<pOrWc->nTerm; ii++){
  128982. WhereTerm *pOrTerm = &pOrWc->a[ii];
  128983. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  128984. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  128985. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  128986. int jmp1 = 0; /* Address of jump operation */
  128987. assert( (pTabItem[0].fg.jointype & JT_LEFT)==0
  128988. || ExprHasProperty(pOrExpr, EP_FromJoin)
  128989. );
  128990. if( pAndExpr ){
  128991. pAndExpr->pLeft = pOrExpr;
  128992. pOrExpr = pAndExpr;
  128993. }
  128994. /* Loop through table entries that match term pOrTerm. */
  128995. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  128996. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  128997. wctrlFlags, iCovCur);
  128998. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  128999. if( pSubWInfo ){
  129000. WhereLoop *pSubLoop;
  129001. int addrExplain = sqlite3WhereExplainOneScan(
  129002. pParse, pOrTab, &pSubWInfo->a[0], 0
  129003. );
  129004. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  129005. /* This is the sub-WHERE clause body. First skip over
  129006. ** duplicate rows from prior sub-WHERE clauses, and record the
  129007. ** rowid (or PRIMARY KEY) for the current row so that the same
  129008. ** row will be skipped in subsequent sub-WHERE clauses.
  129009. */
  129010. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  129011. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  129012. if( HasRowid(pTab) ){
  129013. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);
  129014. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  129015. regRowid, iSet);
  129016. VdbeCoverage(v);
  129017. }else{
  129018. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  129019. int nPk = pPk->nKeyCol;
  129020. int iPk;
  129021. int r;
  129022. /* Read the PK into an array of temp registers. */
  129023. r = sqlite3GetTempRange(pParse, nPk);
  129024. for(iPk=0; iPk<nPk; iPk++){
  129025. int iCol = pPk->aiColumn[iPk];
  129026. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, r+iPk);
  129027. }
  129028. /* Check if the temp table already contains this key. If so,
  129029. ** the row has already been included in the result set and
  129030. ** can be ignored (by jumping past the Gosub below). Otherwise,
  129031. ** insert the key into the temp table and proceed with processing
  129032. ** the row.
  129033. **
  129034. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  129035. ** is zero, assume that the key cannot already be present in
  129036. ** the temp table. And if iSet is -1, assume that there is no
  129037. ** need to insert the key into the temp table, as it will never
  129038. ** be tested for. */
  129039. if( iSet ){
  129040. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  129041. VdbeCoverage(v);
  129042. }
  129043. if( iSet>=0 ){
  129044. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  129045. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
  129046. r, nPk);
  129047. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  129048. }
  129049. /* Release the array of temp registers */
  129050. sqlite3ReleaseTempRange(pParse, r, nPk);
  129051. }
  129052. }
  129053. /* Invoke the main loop body as a subroutine */
  129054. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  129055. /* Jump here (skipping the main loop body subroutine) if the
  129056. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  129057. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  129058. /* The pSubWInfo->untestedTerms flag means that this OR term
  129059. ** contained one or more AND term from a notReady table. The
  129060. ** terms from the notReady table could not be tested and will
  129061. ** need to be tested later.
  129062. */
  129063. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  129064. /* If all of the OR-connected terms are optimized using the same
  129065. ** index, and the index is opened using the same cursor number
  129066. ** by each call to sqlite3WhereBegin() made by this loop, it may
  129067. ** be possible to use that index as a covering index.
  129068. **
  129069. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  129070. ** uses an index, and this is either the first OR-connected term
  129071. ** processed or the index is the same as that used by all previous
  129072. ** terms, set pCov to the candidate covering index. Otherwise, set
  129073. ** pCov to NULL to indicate that no candidate covering index will
  129074. ** be available.
  129075. */
  129076. pSubLoop = pSubWInfo->a[0].pWLoop;
  129077. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  129078. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  129079. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  129080. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  129081. ){
  129082. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  129083. pCov = pSubLoop->u.btree.pIndex;
  129084. }else{
  129085. pCov = 0;
  129086. }
  129087. /* Finish the loop through table entries that match term pOrTerm. */
  129088. sqlite3WhereEnd(pSubWInfo);
  129089. }
  129090. }
  129091. }
  129092. ExplainQueryPlanPop(pParse);
  129093. pLevel->u.pCovidx = pCov;
  129094. if( pCov ) pLevel->iIdxCur = iCovCur;
  129095. if( pAndExpr ){
  129096. pAndExpr->pLeft = 0;
  129097. sqlite3ExprDelete(db, pAndExpr);
  129098. }
  129099. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  129100. sqlite3VdbeGoto(v, pLevel->addrBrk);
  129101. sqlite3VdbeResolveLabel(v, iLoopBody);
  129102. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  129103. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  129104. }else
  129105. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  129106. {
  129107. /* Case 6: There is no usable index. We must do a complete
  129108. ** scan of the entire table.
  129109. */
  129110. static const u8 aStep[] = { OP_Next, OP_Prev };
  129111. static const u8 aStart[] = { OP_Rewind, OP_Last };
  129112. assert( bRev==0 || bRev==1 );
  129113. if( pTabItem->fg.isRecursive ){
  129114. /* Tables marked isRecursive have only a single row that is stored in
  129115. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  129116. pLevel->op = OP_Noop;
  129117. }else{
  129118. codeCursorHint(pTabItem, pWInfo, pLevel, 0);
  129119. pLevel->op = aStep[bRev];
  129120. pLevel->p1 = iCur;
  129121. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
  129122. VdbeCoverageIf(v, bRev==0);
  129123. VdbeCoverageIf(v, bRev!=0);
  129124. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  129125. }
  129126. }
  129127. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  129128. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  129129. #endif
  129130. /* Insert code to test every subexpression that can be completely
  129131. ** computed using the current set of tables.
  129132. **
  129133. ** This loop may run between one and three times, depending on the
  129134. ** constraints to be generated. The value of stack variable iLoop
  129135. ** determines the constraints coded by each iteration, as follows:
  129136. **
  129137. ** iLoop==1: Code only expressions that are entirely covered by pIdx.
  129138. ** iLoop==2: Code remaining expressions that do not contain correlated
  129139. ** sub-queries.
  129140. ** iLoop==3: Code all remaining expressions.
  129141. **
  129142. ** An effort is made to skip unnecessary iterations of the loop.
  129143. */
  129144. iLoop = (pIdx ? 1 : 2);
  129145. do{
  129146. int iNext = 0; /* Next value for iLoop */
  129147. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  129148. Expr *pE;
  129149. int skipLikeAddr = 0;
  129150. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  129151. testcase( pTerm->wtFlags & TERM_CODED );
  129152. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  129153. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  129154. testcase( pWInfo->untestedTerms==0
  129155. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
  129156. pWInfo->untestedTerms = 1;
  129157. continue;
  129158. }
  129159. pE = pTerm->pExpr;
  129160. assert( pE!=0 );
  129161. if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){
  129162. continue;
  129163. }
  129164. if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
  129165. iNext = 2;
  129166. continue;
  129167. }
  129168. if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
  129169. if( iNext==0 ) iNext = 3;
  129170. continue;
  129171. }
  129172. if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
  129173. /* If the TERM_LIKECOND flag is set, that means that the range search
  129174. ** is sufficient to guarantee that the LIKE operator is true, so we
  129175. ** can skip the call to the like(A,B) function. But this only works
  129176. ** for strings. So do not skip the call to the function on the pass
  129177. ** that compares BLOBs. */
  129178. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  129179. continue;
  129180. #else
  129181. u32 x = pLevel->iLikeRepCntr;
  129182. if( x>0 ){
  129183. skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));
  129184. }
  129185. VdbeCoverage(v);
  129186. #endif
  129187. }
  129188. #ifdef WHERETRACE_ENABLED /* 0xffff */
  129189. if( sqlite3WhereTrace ){
  129190. VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
  129191. pWC->nTerm-j, pTerm, iLoop));
  129192. }
  129193. #endif
  129194. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  129195. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  129196. pTerm->wtFlags |= TERM_CODED;
  129197. }
  129198. iLoop = iNext;
  129199. }while( iLoop>0 );
  129200. /* Insert code to test for implied constraints based on transitivity
  129201. ** of the "==" operator.
  129202. **
  129203. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  129204. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  129205. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  129206. ** the implied "t1.a=123" constraint.
  129207. */
  129208. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  129209. Expr *pE, sEAlt;
  129210. WhereTerm *pAlt;
  129211. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  129212. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  129213. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  129214. if( pTerm->leftCursor!=iCur ) continue;
  129215. if( pLevel->iLeftJoin ) continue;
  129216. pE = pTerm->pExpr;
  129217. assert( !ExprHasProperty(pE, EP_FromJoin) );
  129218. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  129219. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  129220. WO_EQ|WO_IN|WO_IS, 0);
  129221. if( pAlt==0 ) continue;
  129222. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  129223. if( (pAlt->eOperator & WO_IN)
  129224. && (pAlt->pExpr->flags & EP_xIsSelect)
  129225. && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
  129226. ){
  129227. continue;
  129228. }
  129229. testcase( pAlt->eOperator & WO_EQ );
  129230. testcase( pAlt->eOperator & WO_IS );
  129231. testcase( pAlt->eOperator & WO_IN );
  129232. VdbeModuleComment((v, "begin transitive constraint"));
  129233. sEAlt = *pAlt->pExpr;
  129234. sEAlt.pLeft = pE->pLeft;
  129235. sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
  129236. }
  129237. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  129238. ** at least one row of the right table has matched the left table.
  129239. */
  129240. if( pLevel->iLeftJoin ){
  129241. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  129242. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  129243. VdbeComment((v, "record LEFT JOIN hit"));
  129244. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  129245. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  129246. testcase( pTerm->wtFlags & TERM_CODED );
  129247. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  129248. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  129249. assert( pWInfo->untestedTerms );
  129250. continue;
  129251. }
  129252. assert( pTerm->pExpr );
  129253. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  129254. pTerm->wtFlags |= TERM_CODED;
  129255. }
  129256. }
  129257. return pLevel->notReady;
  129258. }
  129259. /************** End of wherecode.c *******************************************/
  129260. /************** Begin file whereexpr.c ***************************************/
  129261. /*
  129262. ** 2015-06-08
  129263. **
  129264. ** The author disclaims copyright to this source code. In place of
  129265. ** a legal notice, here is a blessing:
  129266. **
  129267. ** May you do good and not evil.
  129268. ** May you find forgiveness for yourself and forgive others.
  129269. ** May you share freely, never taking more than you give.
  129270. **
  129271. *************************************************************************
  129272. ** This module contains C code that generates VDBE code used to process
  129273. ** the WHERE clause of SQL statements.
  129274. **
  129275. ** This file was originally part of where.c but was split out to improve
  129276. ** readability and editabiliity. This file contains utility routines for
  129277. ** analyzing Expr objects in the WHERE clause.
  129278. */
  129279. /* #include "sqliteInt.h" */
  129280. /* #include "whereInt.h" */
  129281. /* Forward declarations */
  129282. static void exprAnalyze(SrcList*, WhereClause*, int);
  129283. /*
  129284. ** Deallocate all memory associated with a WhereOrInfo object.
  129285. */
  129286. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  129287. sqlite3WhereClauseClear(&p->wc);
  129288. sqlite3DbFree(db, p);
  129289. }
  129290. /*
  129291. ** Deallocate all memory associated with a WhereAndInfo object.
  129292. */
  129293. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  129294. sqlite3WhereClauseClear(&p->wc);
  129295. sqlite3DbFree(db, p);
  129296. }
  129297. /*
  129298. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  129299. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  129300. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  129301. ** 0 is returned if the new WhereTerm could not be added due to a memory
  129302. ** allocation error. The memory allocation failure will be recorded in
  129303. ** the db->mallocFailed flag so that higher-level functions can detect it.
  129304. **
  129305. ** This routine will increase the size of the pWC->a[] array as necessary.
  129306. **
  129307. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  129308. ** for freeing the expression p is assumed by the WhereClause object pWC.
  129309. ** This is true even if this routine fails to allocate a new WhereTerm.
  129310. **
  129311. ** WARNING: This routine might reallocate the space used to store
  129312. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  129313. ** calling this routine. Such pointers may be reinitialized by referencing
  129314. ** the pWC->a[] array.
  129315. */
  129316. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  129317. WhereTerm *pTerm;
  129318. int idx;
  129319. testcase( wtFlags & TERM_VIRTUAL );
  129320. if( pWC->nTerm>=pWC->nSlot ){
  129321. WhereTerm *pOld = pWC->a;
  129322. sqlite3 *db = pWC->pWInfo->pParse->db;
  129323. pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  129324. if( pWC->a==0 ){
  129325. if( wtFlags & TERM_DYNAMIC ){
  129326. sqlite3ExprDelete(db, p);
  129327. }
  129328. pWC->a = pOld;
  129329. return 0;
  129330. }
  129331. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  129332. if( pOld!=pWC->aStatic ){
  129333. sqlite3DbFree(db, pOld);
  129334. }
  129335. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  129336. }
  129337. pTerm = &pWC->a[idx = pWC->nTerm++];
  129338. if( p && ExprHasProperty(p, EP_Unlikely) ){
  129339. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  129340. }else{
  129341. pTerm->truthProb = 1;
  129342. }
  129343. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  129344. pTerm->wtFlags = wtFlags;
  129345. pTerm->pWC = pWC;
  129346. pTerm->iParent = -1;
  129347. memset(&pTerm->eOperator, 0,
  129348. sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
  129349. return idx;
  129350. }
  129351. /*
  129352. ** Return TRUE if the given operator is one of the operators that is
  129353. ** allowed for an indexable WHERE clause term. The allowed operators are
  129354. ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
  129355. */
  129356. static int allowedOp(int op){
  129357. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  129358. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  129359. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  129360. assert( TK_GE==TK_EQ+4 );
  129361. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  129362. }
  129363. /*
  129364. ** Commute a comparison operator. Expressions of the form "X op Y"
  129365. ** are converted into "Y op X".
  129366. **
  129367. ** If left/right precedence rules come into play when determining the
  129368. ** collating sequence, then COLLATE operators are adjusted to ensure
  129369. ** that the collating sequence does not change. For example:
  129370. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  129371. ** the left hand side of a comparison overrides any collation sequence
  129372. ** attached to the right. For the same reason the EP_Collate flag
  129373. ** is not commuted.
  129374. */
  129375. static void exprCommute(Parse *pParse, Expr *pExpr){
  129376. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  129377. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  129378. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  129379. if( expRight==expLeft ){
  129380. /* Either X and Y both have COLLATE operator or neither do */
  129381. if( expRight ){
  129382. /* Both X and Y have COLLATE operators. Make sure X is always
  129383. ** used by clearing the EP_Collate flag from Y. */
  129384. pExpr->pRight->flags &= ~EP_Collate;
  129385. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  129386. /* Neither X nor Y have COLLATE operators, but X has a non-default
  129387. ** collating sequence. So add the EP_Collate marker on X to cause
  129388. ** it to be searched first. */
  129389. pExpr->pLeft->flags |= EP_Collate;
  129390. }
  129391. }
  129392. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  129393. if( pExpr->op>=TK_GT ){
  129394. assert( TK_LT==TK_GT+2 );
  129395. assert( TK_GE==TK_LE+2 );
  129396. assert( TK_GT>TK_EQ );
  129397. assert( TK_GT<TK_LE );
  129398. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  129399. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  129400. }
  129401. }
  129402. /*
  129403. ** Translate from TK_xx operator to WO_xx bitmask.
  129404. */
  129405. static u16 operatorMask(int op){
  129406. u16 c;
  129407. assert( allowedOp(op) );
  129408. if( op==TK_IN ){
  129409. c = WO_IN;
  129410. }else if( op==TK_ISNULL ){
  129411. c = WO_ISNULL;
  129412. }else if( op==TK_IS ){
  129413. c = WO_IS;
  129414. }else{
  129415. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  129416. c = (u16)(WO_EQ<<(op-TK_EQ));
  129417. }
  129418. assert( op!=TK_ISNULL || c==WO_ISNULL );
  129419. assert( op!=TK_IN || c==WO_IN );
  129420. assert( op!=TK_EQ || c==WO_EQ );
  129421. assert( op!=TK_LT || c==WO_LT );
  129422. assert( op!=TK_LE || c==WO_LE );
  129423. assert( op!=TK_GT || c==WO_GT );
  129424. assert( op!=TK_GE || c==WO_GE );
  129425. assert( op!=TK_IS || c==WO_IS );
  129426. return c;
  129427. }
  129428. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  129429. /*
  129430. ** Check to see if the given expression is a LIKE or GLOB operator that
  129431. ** can be optimized using inequality constraints. Return TRUE if it is
  129432. ** so and false if not.
  129433. **
  129434. ** In order for the operator to be optimizible, the RHS must be a string
  129435. ** literal that does not begin with a wildcard. The LHS must be a column
  129436. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  129437. ** that virtual tables cannot participate in the LIKE optimization.) The
  129438. ** collating sequence for the column on the LHS must be appropriate for
  129439. ** the operator.
  129440. */
  129441. static int isLikeOrGlob(
  129442. Parse *pParse, /* Parsing and code generating context */
  129443. Expr *pExpr, /* Test this expression */
  129444. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  129445. int *pisComplete, /* True if the only wildcard is % in the last character */
  129446. int *pnoCase /* True if uppercase is equivalent to lowercase */
  129447. ){
  129448. const u8 *z = 0; /* String on RHS of LIKE operator */
  129449. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  129450. ExprList *pList; /* List of operands to the LIKE operator */
  129451. u8 c; /* One character in z[] */
  129452. int cnt; /* Number of non-wildcard prefix characters */
  129453. u8 wc[4]; /* Wildcard characters */
  129454. sqlite3 *db = pParse->db; /* Database connection */
  129455. sqlite3_value *pVal = 0;
  129456. int op; /* Opcode of pRight */
  129457. int rc; /* Result code to return */
  129458. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){
  129459. return 0;
  129460. }
  129461. #ifdef SQLITE_EBCDIC
  129462. if( *pnoCase ) return 0;
  129463. #endif
  129464. pList = pExpr->x.pList;
  129465. pLeft = pList->a[1].pExpr;
  129466. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  129467. op = pRight->op;
  129468. if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  129469. Vdbe *pReprepare = pParse->pReprepare;
  129470. int iCol = pRight->iColumn;
  129471. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  129472. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  129473. z = sqlite3_value_text(pVal);
  129474. }
  129475. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  129476. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  129477. }else if( op==TK_STRING ){
  129478. z = (u8*)pRight->u.zToken;
  129479. }
  129480. if( z ){
  129481. /* Count the number of prefix characters prior to the first wildcard */
  129482. cnt = 0;
  129483. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  129484. cnt++;
  129485. if( c==wc[3] && z[cnt]!=0 ) cnt++;
  129486. }
  129487. /* The optimization is possible only if (1) the pattern does not begin
  129488. ** with a wildcard and if (2) the non-wildcard prefix does not end with
  129489. ** an (illegal 0xff) character, or (3) the pattern does not consist of
  129490. ** a single escape character. The second condition is necessary so
  129491. ** that we can increment the prefix key to find an upper bound for the
  129492. ** range search. The third is because the caller assumes that the pattern
  129493. ** consists of at least one character after all escapes have been
  129494. ** removed. */
  129495. if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){
  129496. Expr *pPrefix;
  129497. /* A "complete" match if the pattern ends with "*" or "%" */
  129498. *pisComplete = c==wc[0] && z[cnt+1]==0;
  129499. /* Get the pattern prefix. Remove all escapes from the prefix. */
  129500. pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
  129501. if( pPrefix ){
  129502. int iFrom, iTo;
  129503. char *zNew = pPrefix->u.zToken;
  129504. zNew[cnt] = 0;
  129505. for(iFrom=iTo=0; iFrom<cnt; iFrom++){
  129506. if( zNew[iFrom]==wc[3] ) iFrom++;
  129507. zNew[iTo++] = zNew[iFrom];
  129508. }
  129509. zNew[iTo] = 0;
  129510. /* If the RHS begins with a digit or a minus sign, then the LHS must be
  129511. ** an ordinary column (not a virtual table column) with TEXT affinity.
  129512. ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
  129513. ** even though "lhs LIKE rhs" is true. But if the RHS does not start
  129514. ** with a digit or '-', then "lhs LIKE rhs" will always be false if
  129515. ** the LHS is numeric and so the optimization still works.
  129516. **
  129517. ** 2018-09-10 ticket c94369cae9b561b1f996d0054bfab11389f9d033
  129518. ** The RHS pattern must not be '/%' because the termination condition
  129519. ** will then become "x<'0'" and if the affinity is numeric, will then
  129520. ** be converted into "x<0", which is incorrect.
  129521. */
  129522. if( sqlite3Isdigit(zNew[0])
  129523. || zNew[0]=='-'
  129524. || (zNew[0]+1=='0' && iTo==1)
  129525. ){
  129526. if( pLeft->op!=TK_COLUMN
  129527. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  129528. || IsVirtual(pLeft->y.pTab) /* Value might be numeric */
  129529. ){
  129530. sqlite3ExprDelete(db, pPrefix);
  129531. sqlite3ValueFree(pVal);
  129532. return 0;
  129533. }
  129534. }
  129535. }
  129536. *ppPrefix = pPrefix;
  129537. /* If the RHS pattern is a bound parameter, make arrangements to
  129538. ** reprepare the statement when that parameter is rebound */
  129539. if( op==TK_VARIABLE ){
  129540. Vdbe *v = pParse->pVdbe;
  129541. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  129542. if( *pisComplete && pRight->u.zToken[1] ){
  129543. /* If the rhs of the LIKE expression is a variable, and the current
  129544. ** value of the variable means there is no need to invoke the LIKE
  129545. ** function, then no OP_Variable will be added to the program.
  129546. ** This causes problems for the sqlite3_bind_parameter_name()
  129547. ** API. To work around them, add a dummy OP_Variable here.
  129548. */
  129549. int r1 = sqlite3GetTempReg(pParse);
  129550. sqlite3ExprCodeTarget(pParse, pRight, r1);
  129551. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  129552. sqlite3ReleaseTempReg(pParse, r1);
  129553. }
  129554. }
  129555. }else{
  129556. z = 0;
  129557. }
  129558. }
  129559. rc = (z!=0);
  129560. sqlite3ValueFree(pVal);
  129561. return rc;
  129562. }
  129563. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  129564. #ifndef SQLITE_OMIT_VIRTUALTABLE
  129565. /*
  129566. ** Check to see if the pExpr expression is a form that needs to be passed
  129567. ** to the xBestIndex method of virtual tables. Forms of interest include:
  129568. **
  129569. ** Expression Virtual Table Operator
  129570. ** ----------------------- ---------------------------------
  129571. ** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
  129572. ** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
  129573. ** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
  129574. ** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
  129575. ** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
  129576. ** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
  129577. ** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
  129578. ** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
  129579. ** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
  129580. **
  129581. ** In every case, "column" must be a column of a virtual table. If there
  129582. ** is a match, set *ppLeft to the "column" expression, set *ppRight to the
  129583. ** "expr" expression (even though in forms (6) and (8) the column is on the
  129584. ** right and the expression is on the left). Also set *peOp2 to the
  129585. ** appropriate virtual table operator. The return value is 1 or 2 if there
  129586. ** is a match. The usual return is 1, but if the RHS is also a column
  129587. ** of virtual table in forms (5) or (7) then return 2.
  129588. **
  129589. ** If the expression matches none of the patterns above, return 0.
  129590. */
  129591. static int isAuxiliaryVtabOperator(
  129592. sqlite3 *db, /* Parsing context */
  129593. Expr *pExpr, /* Test this expression */
  129594. unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
  129595. Expr **ppLeft, /* Column expression to left of MATCH/op2 */
  129596. Expr **ppRight /* Expression to left of MATCH/op2 */
  129597. ){
  129598. if( pExpr->op==TK_FUNCTION ){
  129599. static const struct Op2 {
  129600. const char *zOp;
  129601. unsigned char eOp2;
  129602. } aOp[] = {
  129603. { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
  129604. { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
  129605. { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
  129606. { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
  129607. };
  129608. ExprList *pList;
  129609. Expr *pCol; /* Column reference */
  129610. int i;
  129611. pList = pExpr->x.pList;
  129612. if( pList==0 || pList->nExpr!=2 ){
  129613. return 0;
  129614. }
  129615. /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
  129616. ** virtual table on their second argument, which is the same as
  129617. ** the left-hand side operand in their in-fix form.
  129618. **
  129619. ** vtab_column MATCH expression
  129620. ** MATCH(expression,vtab_column)
  129621. */
  129622. pCol = pList->a[1].pExpr;
  129623. if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
  129624. for(i=0; i<ArraySize(aOp); i++){
  129625. if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
  129626. *peOp2 = aOp[i].eOp2;
  129627. *ppRight = pList->a[0].pExpr;
  129628. *ppLeft = pCol;
  129629. return 1;
  129630. }
  129631. }
  129632. }
  129633. /* We can also match against the first column of overloaded
  129634. ** functions where xFindFunction returns a value of at least
  129635. ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
  129636. **
  129637. ** OVERLOADED(vtab_column,expression)
  129638. **
  129639. ** Historically, xFindFunction expected to see lower-case function
  129640. ** names. But for this use case, xFindFunction is expected to deal
  129641. ** with function names in an arbitrary case.
  129642. */
  129643. pCol = pList->a[0].pExpr;
  129644. if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
  129645. sqlite3_vtab *pVtab;
  129646. sqlite3_module *pMod;
  129647. void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
  129648. void *pNotUsed;
  129649. pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
  129650. assert( pVtab!=0 );
  129651. assert( pVtab->pModule!=0 );
  129652. pMod = (sqlite3_module *)pVtab->pModule;
  129653. if( pMod->xFindFunction!=0 ){
  129654. i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
  129655. if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
  129656. *peOp2 = i;
  129657. *ppRight = pList->a[1].pExpr;
  129658. *ppLeft = pCol;
  129659. return 1;
  129660. }
  129661. }
  129662. }
  129663. }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
  129664. int res = 0;
  129665. Expr *pLeft = pExpr->pLeft;
  129666. Expr *pRight = pExpr->pRight;
  129667. if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->y.pTab) ){
  129668. res++;
  129669. }
  129670. if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->y.pTab) ){
  129671. res++;
  129672. SWAP(Expr*, pLeft, pRight);
  129673. }
  129674. *ppLeft = pLeft;
  129675. *ppRight = pRight;
  129676. if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
  129677. if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
  129678. if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
  129679. return res;
  129680. }
  129681. return 0;
  129682. }
  129683. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  129684. /*
  129685. ** If the pBase expression originated in the ON or USING clause of
  129686. ** a join, then transfer the appropriate markings over to derived.
  129687. */
  129688. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  129689. if( pDerived ){
  129690. pDerived->flags |= pBase->flags & EP_FromJoin;
  129691. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  129692. }
  129693. }
  129694. /*
  129695. ** Mark term iChild as being a child of term iParent
  129696. */
  129697. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  129698. pWC->a[iChild].iParent = iParent;
  129699. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  129700. pWC->a[iParent].nChild++;
  129701. }
  129702. /*
  129703. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  129704. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  129705. ** the number of available subterms, return NULL.
  129706. */
  129707. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  129708. if( pTerm->eOperator!=WO_AND ){
  129709. return N==0 ? pTerm : 0;
  129710. }
  129711. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  129712. return &pTerm->u.pAndInfo->wc.a[N];
  129713. }
  129714. return 0;
  129715. }
  129716. /*
  129717. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  129718. ** two subterms are in disjunction - they are OR-ed together.
  129719. **
  129720. ** If these two terms are both of the form: "A op B" with the same
  129721. ** A and B values but different operators and if the operators are
  129722. ** compatible (if one is = and the other is <, for example) then
  129723. ** add a new virtual AND term to pWC that is the combination of the
  129724. ** two.
  129725. **
  129726. ** Some examples:
  129727. **
  129728. ** x<y OR x=y --> x<=y
  129729. ** x=y OR x=y --> x=y
  129730. ** x<=y OR x<y --> x<=y
  129731. **
  129732. ** The following is NOT generated:
  129733. **
  129734. ** x<y OR x>y --> x!=y
  129735. */
  129736. static void whereCombineDisjuncts(
  129737. SrcList *pSrc, /* the FROM clause */
  129738. WhereClause *pWC, /* The complete WHERE clause */
  129739. WhereTerm *pOne, /* First disjunct */
  129740. WhereTerm *pTwo /* Second disjunct */
  129741. ){
  129742. u16 eOp = pOne->eOperator | pTwo->eOperator;
  129743. sqlite3 *db; /* Database connection (for malloc) */
  129744. Expr *pNew; /* New virtual expression */
  129745. int op; /* Operator for the combined expression */
  129746. int idxNew; /* Index in pWC of the next virtual term */
  129747. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  129748. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  129749. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  129750. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  129751. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  129752. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  129753. if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  129754. if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
  129755. /* If we reach this point, it means the two subterms can be combined */
  129756. if( (eOp & (eOp-1))!=0 ){
  129757. if( eOp & (WO_LT|WO_LE) ){
  129758. eOp = WO_LE;
  129759. }else{
  129760. assert( eOp & (WO_GT|WO_GE) );
  129761. eOp = WO_GE;
  129762. }
  129763. }
  129764. db = pWC->pWInfo->pParse->db;
  129765. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  129766. if( pNew==0 ) return;
  129767. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  129768. pNew->op = op;
  129769. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  129770. exprAnalyze(pSrc, pWC, idxNew);
  129771. }
  129772. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  129773. /*
  129774. ** Analyze a term that consists of two or more OR-connected
  129775. ** subterms. So in:
  129776. **
  129777. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  129778. ** ^^^^^^^^^^^^^^^^^^^^
  129779. **
  129780. ** This routine analyzes terms such as the middle term in the above example.
  129781. ** A WhereOrTerm object is computed and attached to the term under
  129782. ** analysis, regardless of the outcome of the analysis. Hence:
  129783. **
  129784. ** WhereTerm.wtFlags |= TERM_ORINFO
  129785. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  129786. **
  129787. ** The term being analyzed must have two or more of OR-connected subterms.
  129788. ** A single subterm might be a set of AND-connected sub-subterms.
  129789. ** Examples of terms under analysis:
  129790. **
  129791. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  129792. ** (B) x=expr1 OR expr2=x OR x=expr3
  129793. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  129794. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  129795. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  129796. ** (F) x>A OR (x=A AND y>=B)
  129797. **
  129798. ** CASE 1:
  129799. **
  129800. ** If all subterms are of the form T.C=expr for some single column of C and
  129801. ** a single table T (as shown in example B above) then create a new virtual
  129802. ** term that is an equivalent IN expression. In other words, if the term
  129803. ** being analyzed is:
  129804. **
  129805. ** x = expr1 OR expr2 = x OR x = expr3
  129806. **
  129807. ** then create a new virtual term like this:
  129808. **
  129809. ** x IN (expr1,expr2,expr3)
  129810. **
  129811. ** CASE 2:
  129812. **
  129813. ** If there are exactly two disjuncts and one side has x>A and the other side
  129814. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  129815. ** WHERE clause of the form "x>=A". Example:
  129816. **
  129817. ** x>A OR (x=A AND y>B) adds: x>=A
  129818. **
  129819. ** The added conjunct can sometimes be helpful in query planning.
  129820. **
  129821. ** CASE 3:
  129822. **
  129823. ** If all subterms are indexable by a single table T, then set
  129824. **
  129825. ** WhereTerm.eOperator = WO_OR
  129826. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  129827. **
  129828. ** A subterm is "indexable" if it is of the form
  129829. ** "T.C <op> <expr>" where C is any column of table T and
  129830. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  129831. ** A subterm is also indexable if it is an AND of two or more
  129832. ** subsubterms at least one of which is indexable. Indexable AND
  129833. ** subterms have their eOperator set to WO_AND and they have
  129834. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  129835. **
  129836. ** From another point of view, "indexable" means that the subterm could
  129837. ** potentially be used with an index if an appropriate index exists.
  129838. ** This analysis does not consider whether or not the index exists; that
  129839. ** is decided elsewhere. This analysis only looks at whether subterms
  129840. ** appropriate for indexing exist.
  129841. **
  129842. ** All examples A through E above satisfy case 3. But if a term
  129843. ** also satisfies case 1 (such as B) we know that the optimizer will
  129844. ** always prefer case 1, so in that case we pretend that case 3 is not
  129845. ** satisfied.
  129846. **
  129847. ** It might be the case that multiple tables are indexable. For example,
  129848. ** (E) above is indexable on tables P, Q, and R.
  129849. **
  129850. ** Terms that satisfy case 3 are candidates for lookup by using
  129851. ** separate indices to find rowids for each subterm and composing
  129852. ** the union of all rowids using a RowSet object. This is similar
  129853. ** to "bitmap indices" in other database engines.
  129854. **
  129855. ** OTHERWISE:
  129856. **
  129857. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  129858. ** zero. This term is not useful for search.
  129859. */
  129860. static void exprAnalyzeOrTerm(
  129861. SrcList *pSrc, /* the FROM clause */
  129862. WhereClause *pWC, /* the complete WHERE clause */
  129863. int idxTerm /* Index of the OR-term to be analyzed */
  129864. ){
  129865. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  129866. Parse *pParse = pWInfo->pParse; /* Parser context */
  129867. sqlite3 *db = pParse->db; /* Database connection */
  129868. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  129869. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  129870. int i; /* Loop counters */
  129871. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  129872. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  129873. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  129874. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  129875. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  129876. /*
  129877. ** Break the OR clause into its separate subterms. The subterms are
  129878. ** stored in a WhereClause structure containing within the WhereOrInfo
  129879. ** object that is attached to the original OR clause term.
  129880. */
  129881. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  129882. assert( pExpr->op==TK_OR );
  129883. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  129884. if( pOrInfo==0 ) return;
  129885. pTerm->wtFlags |= TERM_ORINFO;
  129886. pOrWc = &pOrInfo->wc;
  129887. memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
  129888. sqlite3WhereClauseInit(pOrWc, pWInfo);
  129889. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  129890. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  129891. if( db->mallocFailed ) return;
  129892. assert( pOrWc->nTerm>=2 );
  129893. /*
  129894. ** Compute the set of tables that might satisfy cases 1 or 3.
  129895. */
  129896. indexable = ~(Bitmask)0;
  129897. chngToIN = ~(Bitmask)0;
  129898. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  129899. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  129900. WhereAndInfo *pAndInfo;
  129901. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  129902. chngToIN = 0;
  129903. pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
  129904. if( pAndInfo ){
  129905. WhereClause *pAndWC;
  129906. WhereTerm *pAndTerm;
  129907. int j;
  129908. Bitmask b = 0;
  129909. pOrTerm->u.pAndInfo = pAndInfo;
  129910. pOrTerm->wtFlags |= TERM_ANDINFO;
  129911. pOrTerm->eOperator = WO_AND;
  129912. pAndWC = &pAndInfo->wc;
  129913. memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
  129914. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  129915. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  129916. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  129917. pAndWC->pOuter = pWC;
  129918. if( !db->mallocFailed ){
  129919. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  129920. assert( pAndTerm->pExpr );
  129921. if( allowedOp(pAndTerm->pExpr->op)
  129922. || pAndTerm->eOperator==WO_AUX
  129923. ){
  129924. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  129925. }
  129926. }
  129927. }
  129928. indexable &= b;
  129929. }
  129930. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  129931. /* Skip this term for now. We revisit it when we process the
  129932. ** corresponding TERM_VIRTUAL term */
  129933. }else{
  129934. Bitmask b;
  129935. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  129936. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  129937. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  129938. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  129939. }
  129940. indexable &= b;
  129941. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  129942. chngToIN = 0;
  129943. }else{
  129944. chngToIN &= b;
  129945. }
  129946. }
  129947. }
  129948. /*
  129949. ** Record the set of tables that satisfy case 3. The set might be
  129950. ** empty.
  129951. */
  129952. pOrInfo->indexable = indexable;
  129953. if( indexable ){
  129954. pTerm->eOperator = WO_OR;
  129955. pWC->hasOr = 1;
  129956. }else{
  129957. pTerm->eOperator = WO_OR;
  129958. }
  129959. /* For a two-way OR, attempt to implementation case 2.
  129960. */
  129961. if( indexable && pOrWc->nTerm==2 ){
  129962. int iOne = 0;
  129963. WhereTerm *pOne;
  129964. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  129965. int iTwo = 0;
  129966. WhereTerm *pTwo;
  129967. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  129968. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  129969. }
  129970. }
  129971. }
  129972. /*
  129973. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  129974. ** we have to do some additional checking to see if case 1 really
  129975. ** is satisfied.
  129976. **
  129977. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  129978. ** that there is no possibility of transforming the OR clause into an
  129979. ** IN operator because one or more terms in the OR clause contain
  129980. ** something other than == on a column in the single table. The 1-bit
  129981. ** case means that every term of the OR clause is of the form
  129982. ** "table.column=expr" for some single table. The one bit that is set
  129983. ** will correspond to the common table. We still need to check to make
  129984. ** sure the same column is used on all terms. The 2-bit case is when
  129985. ** the all terms are of the form "table1.column=table2.column". It
  129986. ** might be possible to form an IN operator with either table1.column
  129987. ** or table2.column as the LHS if either is common to every term of
  129988. ** the OR clause.
  129989. **
  129990. ** Note that terms of the form "table.column1=table.column2" (the
  129991. ** same table on both sizes of the ==) cannot be optimized.
  129992. */
  129993. if( chngToIN ){
  129994. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  129995. int iColumn = -1; /* Column index on lhs of IN operator */
  129996. int iCursor = -1; /* Table cursor common to all terms */
  129997. int j = 0; /* Loop counter */
  129998. /* Search for a table and column that appears on one side or the
  129999. ** other of the == operator in every subterm. That table and column
  130000. ** will be recorded in iCursor and iColumn. There might not be any
  130001. ** such table and column. Set okToChngToIN if an appropriate table
  130002. ** and column is found but leave okToChngToIN false if not found.
  130003. */
  130004. for(j=0; j<2 && !okToChngToIN; j++){
  130005. pOrTerm = pOrWc->a;
  130006. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  130007. assert( pOrTerm->eOperator & WO_EQ );
  130008. pOrTerm->wtFlags &= ~TERM_OR_OK;
  130009. if( pOrTerm->leftCursor==iCursor ){
  130010. /* This is the 2-bit case and we are on the second iteration and
  130011. ** current term is from the first iteration. So skip this term. */
  130012. assert( j==1 );
  130013. continue;
  130014. }
  130015. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  130016. pOrTerm->leftCursor))==0 ){
  130017. /* This term must be of the form t1.a==t2.b where t2 is in the
  130018. ** chngToIN set but t1 is not. This term will be either preceded
  130019. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  130020. ** and use its inversion. */
  130021. testcase( pOrTerm->wtFlags & TERM_COPIED );
  130022. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  130023. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  130024. continue;
  130025. }
  130026. iColumn = pOrTerm->u.leftColumn;
  130027. iCursor = pOrTerm->leftCursor;
  130028. break;
  130029. }
  130030. if( i<0 ){
  130031. /* No candidate table+column was found. This can only occur
  130032. ** on the second iteration */
  130033. assert( j==1 );
  130034. assert( IsPowerOfTwo(chngToIN) );
  130035. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  130036. break;
  130037. }
  130038. testcase( j==1 );
  130039. /* We have found a candidate table and column. Check to see if that
  130040. ** table and column is common to every term in the OR clause */
  130041. okToChngToIN = 1;
  130042. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  130043. assert( pOrTerm->eOperator & WO_EQ );
  130044. if( pOrTerm->leftCursor!=iCursor ){
  130045. pOrTerm->wtFlags &= ~TERM_OR_OK;
  130046. }else if( pOrTerm->u.leftColumn!=iColumn ){
  130047. okToChngToIN = 0;
  130048. }else{
  130049. int affLeft, affRight;
  130050. /* If the right-hand side is also a column, then the affinities
  130051. ** of both right and left sides must be such that no type
  130052. ** conversions are required on the right. (Ticket #2249)
  130053. */
  130054. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  130055. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  130056. if( affRight!=0 && affRight!=affLeft ){
  130057. okToChngToIN = 0;
  130058. }else{
  130059. pOrTerm->wtFlags |= TERM_OR_OK;
  130060. }
  130061. }
  130062. }
  130063. }
  130064. /* At this point, okToChngToIN is true if original pTerm satisfies
  130065. ** case 1. In that case, construct a new virtual term that is
  130066. ** pTerm converted into an IN operator.
  130067. */
  130068. if( okToChngToIN ){
  130069. Expr *pDup; /* A transient duplicate expression */
  130070. ExprList *pList = 0; /* The RHS of the IN operator */
  130071. Expr *pLeft = 0; /* The LHS of the IN operator */
  130072. Expr *pNew; /* The complete IN operator */
  130073. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  130074. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  130075. assert( pOrTerm->eOperator & WO_EQ );
  130076. assert( pOrTerm->leftCursor==iCursor );
  130077. assert( pOrTerm->u.leftColumn==iColumn );
  130078. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  130079. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  130080. pLeft = pOrTerm->pExpr->pLeft;
  130081. }
  130082. assert( pLeft!=0 );
  130083. pDup = sqlite3ExprDup(db, pLeft, 0);
  130084. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
  130085. if( pNew ){
  130086. int idxNew;
  130087. transferJoinMarkings(pNew, pExpr);
  130088. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  130089. pNew->x.pList = pList;
  130090. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  130091. testcase( idxNew==0 );
  130092. exprAnalyze(pSrc, pWC, idxNew);
  130093. /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */
  130094. markTermAsChild(pWC, idxNew, idxTerm);
  130095. }else{
  130096. sqlite3ExprListDelete(db, pList);
  130097. }
  130098. }
  130099. }
  130100. }
  130101. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  130102. /*
  130103. ** We already know that pExpr is a binary operator where both operands are
  130104. ** column references. This routine checks to see if pExpr is an equivalence
  130105. ** relation:
  130106. ** 1. The SQLITE_Transitive optimization must be enabled
  130107. ** 2. Must be either an == or an IS operator
  130108. ** 3. Not originating in the ON clause of an OUTER JOIN
  130109. ** 4. The affinities of A and B must be compatible
  130110. ** 5a. Both operands use the same collating sequence OR
  130111. ** 5b. The overall collating sequence is BINARY
  130112. ** If this routine returns TRUE, that means that the RHS can be substituted
  130113. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  130114. ** This is an optimization. No harm comes from returning 0. But if 1 is
  130115. ** returned when it should not be, then incorrect answers might result.
  130116. */
  130117. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  130118. char aff1, aff2;
  130119. CollSeq *pColl;
  130120. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  130121. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  130122. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  130123. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  130124. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  130125. if( aff1!=aff2
  130126. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  130127. ){
  130128. return 0;
  130129. }
  130130. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  130131. if( sqlite3IsBinary(pColl) ) return 1;
  130132. return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
  130133. }
  130134. /*
  130135. ** Recursively walk the expressions of a SELECT statement and generate
  130136. ** a bitmask indicating which tables are used in that expression
  130137. ** tree.
  130138. */
  130139. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  130140. Bitmask mask = 0;
  130141. while( pS ){
  130142. SrcList *pSrc = pS->pSrc;
  130143. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  130144. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  130145. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  130146. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  130147. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  130148. if( ALWAYS(pSrc!=0) ){
  130149. int i;
  130150. for(i=0; i<pSrc->nSrc; i++){
  130151. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  130152. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  130153. if( pSrc->a[i].fg.isTabFunc ){
  130154. mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
  130155. }
  130156. }
  130157. }
  130158. pS = pS->pPrior;
  130159. }
  130160. return mask;
  130161. }
  130162. /*
  130163. ** Expression pExpr is one operand of a comparison operator that might
  130164. ** be useful for indexing. This routine checks to see if pExpr appears
  130165. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  130166. ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
  130167. ** number of the table that is indexed and aiCurCol[1] to the column number
  130168. ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
  130169. ** indexed.
  130170. **
  130171. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  130172. ** true even if that particular column is not indexed, because the column
  130173. ** might be added to an automatic index later.
  130174. */
  130175. static SQLITE_NOINLINE int exprMightBeIndexed2(
  130176. SrcList *pFrom, /* The FROM clause */
  130177. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  130178. int *aiCurCol, /* Write the referenced table cursor and column here */
  130179. Expr *pExpr /* An operand of a comparison operator */
  130180. ){
  130181. Index *pIdx;
  130182. int i;
  130183. int iCur;
  130184. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  130185. iCur = pFrom->a[i].iCursor;
  130186. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  130187. if( pIdx->aColExpr==0 ) continue;
  130188. for(i=0; i<pIdx->nKeyCol; i++){
  130189. if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
  130190. if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  130191. aiCurCol[0] = iCur;
  130192. aiCurCol[1] = XN_EXPR;
  130193. return 1;
  130194. }
  130195. }
  130196. }
  130197. return 0;
  130198. }
  130199. static int exprMightBeIndexed(
  130200. SrcList *pFrom, /* The FROM clause */
  130201. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  130202. int *aiCurCol, /* Write the referenced table cursor & column here */
  130203. Expr *pExpr, /* An operand of a comparison operator */
  130204. int op /* The specific comparison operator */
  130205. ){
  130206. /* If this expression is a vector to the left or right of a
  130207. ** inequality constraint (>, <, >= or <=), perform the processing
  130208. ** on the first element of the vector. */
  130209. assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
  130210. assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
  130211. assert( op<=TK_GE );
  130212. if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
  130213. pExpr = pExpr->x.pList->a[0].pExpr;
  130214. }
  130215. if( pExpr->op==TK_COLUMN ){
  130216. aiCurCol[0] = pExpr->iTable;
  130217. aiCurCol[1] = pExpr->iColumn;
  130218. return 1;
  130219. }
  130220. if( mPrereq==0 ) return 0; /* No table references */
  130221. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  130222. return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
  130223. }
  130224. /*
  130225. ** The input to this routine is an WhereTerm structure with only the
  130226. ** "pExpr" field filled in. The job of this routine is to analyze the
  130227. ** subexpression and populate all the other fields of the WhereTerm
  130228. ** structure.
  130229. **
  130230. ** If the expression is of the form "<expr> <op> X" it gets commuted
  130231. ** to the standard form of "X <op> <expr>".
  130232. **
  130233. ** If the expression is of the form "X <op> Y" where both X and Y are
  130234. ** columns, then the original expression is unchanged and a new virtual
  130235. ** term of the form "Y <op> X" is added to the WHERE clause and
  130236. ** analyzed separately. The original term is marked with TERM_COPIED
  130237. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  130238. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  130239. ** is a commuted copy of a prior term.) The original term has nChild=1
  130240. ** and the copy has idxParent set to the index of the original term.
  130241. */
  130242. static void exprAnalyze(
  130243. SrcList *pSrc, /* the FROM clause */
  130244. WhereClause *pWC, /* the WHERE clause */
  130245. int idxTerm /* Index of the term to be analyzed */
  130246. ){
  130247. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  130248. WhereTerm *pTerm; /* The term to be analyzed */
  130249. WhereMaskSet *pMaskSet; /* Set of table index masks */
  130250. Expr *pExpr; /* The expression to be analyzed */
  130251. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  130252. Bitmask prereqAll; /* Prerequesites of pExpr */
  130253. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  130254. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  130255. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  130256. int noCase = 0; /* uppercase equivalent to lowercase */
  130257. int op; /* Top-level operator. pExpr->op */
  130258. Parse *pParse = pWInfo->pParse; /* Parsing context */
  130259. sqlite3 *db = pParse->db; /* Database connection */
  130260. unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */
  130261. int nLeft; /* Number of elements on left side vector */
  130262. if( db->mallocFailed ){
  130263. return;
  130264. }
  130265. pTerm = &pWC->a[idxTerm];
  130266. pMaskSet = &pWInfo->sMaskSet;
  130267. pExpr = pTerm->pExpr;
  130268. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  130269. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  130270. op = pExpr->op;
  130271. if( op==TK_IN ){
  130272. assert( pExpr->pRight==0 );
  130273. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  130274. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  130275. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  130276. }else{
  130277. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  130278. }
  130279. }else if( op==TK_ISNULL ){
  130280. pTerm->prereqRight = 0;
  130281. }else{
  130282. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  130283. }
  130284. pMaskSet->bVarSelect = 0;
  130285. prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
  130286. if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
  130287. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  130288. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  130289. prereqAll |= x;
  130290. extraRight = x-1; /* ON clause terms may not be used with an index
  130291. ** on left table of a LEFT JOIN. Ticket #3015 */
  130292. if( (prereqAll>>1)>=x ){
  130293. sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
  130294. return;
  130295. }
  130296. }
  130297. pTerm->prereqAll = prereqAll;
  130298. pTerm->leftCursor = -1;
  130299. pTerm->iParent = -1;
  130300. pTerm->eOperator = 0;
  130301. if( allowedOp(op) ){
  130302. int aiCurCol[2];
  130303. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  130304. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  130305. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  130306. if( pTerm->iField>0 ){
  130307. assert( op==TK_IN );
  130308. assert( pLeft->op==TK_VECTOR );
  130309. pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
  130310. }
  130311. if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
  130312. pTerm->leftCursor = aiCurCol[0];
  130313. pTerm->u.leftColumn = aiCurCol[1];
  130314. pTerm->eOperator = operatorMask(op) & opMask;
  130315. }
  130316. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  130317. if( pRight
  130318. && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
  130319. ){
  130320. WhereTerm *pNew;
  130321. Expr *pDup;
  130322. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  130323. assert( pTerm->iField==0 );
  130324. if( pTerm->leftCursor>=0 ){
  130325. int idxNew;
  130326. pDup = sqlite3ExprDup(db, pExpr, 0);
  130327. if( db->mallocFailed ){
  130328. sqlite3ExprDelete(db, pDup);
  130329. return;
  130330. }
  130331. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  130332. if( idxNew==0 ) return;
  130333. pNew = &pWC->a[idxNew];
  130334. markTermAsChild(pWC, idxNew, idxTerm);
  130335. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  130336. pTerm = &pWC->a[idxTerm];
  130337. pTerm->wtFlags |= TERM_COPIED;
  130338. if( termIsEquivalence(pParse, pDup) ){
  130339. pTerm->eOperator |= WO_EQUIV;
  130340. eExtraOp = WO_EQUIV;
  130341. }
  130342. }else{
  130343. pDup = pExpr;
  130344. pNew = pTerm;
  130345. }
  130346. exprCommute(pParse, pDup);
  130347. pNew->leftCursor = aiCurCol[0];
  130348. pNew->u.leftColumn = aiCurCol[1];
  130349. testcase( (prereqLeft | extraRight) != prereqLeft );
  130350. pNew->prereqRight = prereqLeft | extraRight;
  130351. pNew->prereqAll = prereqAll;
  130352. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  130353. }
  130354. }
  130355. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  130356. /* If a term is the BETWEEN operator, create two new virtual terms
  130357. ** that define the range that the BETWEEN implements. For example:
  130358. **
  130359. ** a BETWEEN b AND c
  130360. **
  130361. ** is converted into:
  130362. **
  130363. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  130364. **
  130365. ** The two new terms are added onto the end of the WhereClause object.
  130366. ** The new terms are "dynamic" and are children of the original BETWEEN
  130367. ** term. That means that if the BETWEEN term is coded, the children are
  130368. ** skipped. Or, if the children are satisfied by an index, the original
  130369. ** BETWEEN term is skipped.
  130370. */
  130371. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  130372. ExprList *pList = pExpr->x.pList;
  130373. int i;
  130374. static const u8 ops[] = {TK_GE, TK_LE};
  130375. assert( pList!=0 );
  130376. assert( pList->nExpr==2 );
  130377. for(i=0; i<2; i++){
  130378. Expr *pNewExpr;
  130379. int idxNew;
  130380. pNewExpr = sqlite3PExpr(pParse, ops[i],
  130381. sqlite3ExprDup(db, pExpr->pLeft, 0),
  130382. sqlite3ExprDup(db, pList->a[i].pExpr, 0));
  130383. transferJoinMarkings(pNewExpr, pExpr);
  130384. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  130385. testcase( idxNew==0 );
  130386. exprAnalyze(pSrc, pWC, idxNew);
  130387. pTerm = &pWC->a[idxTerm];
  130388. markTermAsChild(pWC, idxNew, idxTerm);
  130389. }
  130390. }
  130391. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  130392. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  130393. /* Analyze a term that is composed of two or more subterms connected by
  130394. ** an OR operator.
  130395. */
  130396. else if( pExpr->op==TK_OR ){
  130397. assert( pWC->op==TK_AND );
  130398. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  130399. pTerm = &pWC->a[idxTerm];
  130400. }
  130401. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  130402. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  130403. /* Add constraints to reduce the search space on a LIKE or GLOB
  130404. ** operator.
  130405. **
  130406. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  130407. **
  130408. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  130409. **
  130410. ** The last character of the prefix "abc" is incremented to form the
  130411. ** termination condition "abd". If case is not significant (the default
  130412. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  130413. ** bound is made all lowercase so that the bounds also work when comparing
  130414. ** BLOBs.
  130415. */
  130416. if( pWC->op==TK_AND
  130417. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  130418. ){
  130419. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  130420. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  130421. Expr *pNewExpr1;
  130422. Expr *pNewExpr2;
  130423. int idxNew1;
  130424. int idxNew2;
  130425. const char *zCollSeqName; /* Name of collating sequence */
  130426. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  130427. pLeft = pExpr->x.pList->a[1].pExpr;
  130428. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  130429. /* Convert the lower bound to upper-case and the upper bound to
  130430. ** lower-case (upper-case is less than lower-case in ASCII) so that
  130431. ** the range constraints also work for BLOBs
  130432. */
  130433. if( noCase && !pParse->db->mallocFailed ){
  130434. int i;
  130435. char c;
  130436. pTerm->wtFlags |= TERM_LIKE;
  130437. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  130438. pStr1->u.zToken[i] = sqlite3Toupper(c);
  130439. pStr2->u.zToken[i] = sqlite3Tolower(c);
  130440. }
  130441. }
  130442. if( !db->mallocFailed ){
  130443. u8 c, *pC; /* Last character before the first wildcard */
  130444. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  130445. c = *pC;
  130446. if( noCase ){
  130447. /* The point is to increment the last character before the first
  130448. ** wildcard. But if we increment '@', that will push it into the
  130449. ** alphabetic range where case conversions will mess up the
  130450. ** inequality. To avoid this, make sure to also run the full
  130451. ** LIKE on all candidate expressions by clearing the isComplete flag
  130452. */
  130453. if( c=='A'-1 ) isComplete = 0;
  130454. c = sqlite3UpperToLower[c];
  130455. }
  130456. *pC = c + 1;
  130457. }
  130458. zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY;
  130459. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  130460. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  130461. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  130462. pStr1);
  130463. transferJoinMarkings(pNewExpr1, pExpr);
  130464. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  130465. testcase( idxNew1==0 );
  130466. exprAnalyze(pSrc, pWC, idxNew1);
  130467. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  130468. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  130469. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  130470. pStr2);
  130471. transferJoinMarkings(pNewExpr2, pExpr);
  130472. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  130473. testcase( idxNew2==0 );
  130474. exprAnalyze(pSrc, pWC, idxNew2);
  130475. pTerm = &pWC->a[idxTerm];
  130476. if( isComplete ){
  130477. markTermAsChild(pWC, idxNew1, idxTerm);
  130478. markTermAsChild(pWC, idxNew2, idxTerm);
  130479. }
  130480. }
  130481. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  130482. #ifndef SQLITE_OMIT_VIRTUALTABLE
  130483. /* Add a WO_AUX auxiliary term to the constraint set if the
  130484. ** current expression is of the form "column OP expr" where OP
  130485. ** is an operator that gets passed into virtual tables but which is
  130486. ** not normally optimized for ordinary tables. In other words, OP
  130487. ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
  130488. ** This information is used by the xBestIndex methods of
  130489. ** virtual tables. The native query optimizer does not attempt
  130490. ** to do anything with MATCH functions.
  130491. */
  130492. if( pWC->op==TK_AND ){
  130493. Expr *pRight = 0, *pLeft = 0;
  130494. int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
  130495. while( res-- > 0 ){
  130496. int idxNew;
  130497. WhereTerm *pNewTerm;
  130498. Bitmask prereqColumn, prereqExpr;
  130499. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  130500. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  130501. if( (prereqExpr & prereqColumn)==0 ){
  130502. Expr *pNewExpr;
  130503. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  130504. 0, sqlite3ExprDup(db, pRight, 0));
  130505. if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
  130506. ExprSetProperty(pNewExpr, EP_FromJoin);
  130507. }
  130508. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  130509. testcase( idxNew==0 );
  130510. pNewTerm = &pWC->a[idxNew];
  130511. pNewTerm->prereqRight = prereqExpr;
  130512. pNewTerm->leftCursor = pLeft->iTable;
  130513. pNewTerm->u.leftColumn = pLeft->iColumn;
  130514. pNewTerm->eOperator = WO_AUX;
  130515. pNewTerm->eMatchOp = eOp2;
  130516. markTermAsChild(pWC, idxNew, idxTerm);
  130517. pTerm = &pWC->a[idxTerm];
  130518. pTerm->wtFlags |= TERM_COPIED;
  130519. pNewTerm->prereqAll = pTerm->prereqAll;
  130520. }
  130521. SWAP(Expr*, pLeft, pRight);
  130522. }
  130523. }
  130524. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  130525. /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
  130526. ** new terms for each component comparison - "a = ?" and "b = ?". The
  130527. ** new terms completely replace the original vector comparison, which is
  130528. ** no longer used.
  130529. **
  130530. ** This is only required if at least one side of the comparison operation
  130531. ** is not a sub-select. */
  130532. if( pWC->op==TK_AND
  130533. && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
  130534. && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
  130535. && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
  130536. && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
  130537. || (pExpr->pRight->flags & EP_xIsSelect)==0)
  130538. ){
  130539. int i;
  130540. for(i=0; i<nLeft; i++){
  130541. int idxNew;
  130542. Expr *pNew;
  130543. Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
  130544. Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
  130545. pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
  130546. transferJoinMarkings(pNew, pExpr);
  130547. idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
  130548. exprAnalyze(pSrc, pWC, idxNew);
  130549. }
  130550. pTerm = &pWC->a[idxTerm];
  130551. pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
  130552. pTerm->eOperator = 0;
  130553. }
  130554. /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
  130555. ** a virtual term for each vector component. The expression object
  130556. ** used by each such virtual term is pExpr (the full vector IN(...)
  130557. ** expression). The WhereTerm.iField variable identifies the index within
  130558. ** the vector on the LHS that the virtual term represents.
  130559. **
  130560. ** This only works if the RHS is a simple SELECT, not a compound
  130561. */
  130562. if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
  130563. && pExpr->pLeft->op==TK_VECTOR
  130564. && pExpr->x.pSelect->pPrior==0
  130565. ){
  130566. int i;
  130567. for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
  130568. int idxNew;
  130569. idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
  130570. pWC->a[idxNew].iField = i+1;
  130571. exprAnalyze(pSrc, pWC, idxNew);
  130572. markTermAsChild(pWC, idxNew, idxTerm);
  130573. }
  130574. }
  130575. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  130576. /* When sqlite_stat3 histogram data is available an operator of the
  130577. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  130578. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  130579. ** virtual term of that form.
  130580. **
  130581. ** Note that the virtual term must be tagged with TERM_VNULL.
  130582. */
  130583. if( pExpr->op==TK_NOTNULL
  130584. && pExpr->pLeft->op==TK_COLUMN
  130585. && pExpr->pLeft->iColumn>=0
  130586. && !ExprHasProperty(pExpr, EP_FromJoin)
  130587. && OptimizationEnabled(db, SQLITE_Stat34)
  130588. ){
  130589. Expr *pNewExpr;
  130590. Expr *pLeft = pExpr->pLeft;
  130591. int idxNew;
  130592. WhereTerm *pNewTerm;
  130593. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  130594. sqlite3ExprDup(db, pLeft, 0),
  130595. sqlite3ExprAlloc(db, TK_NULL, 0, 0));
  130596. idxNew = whereClauseInsert(pWC, pNewExpr,
  130597. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  130598. if( idxNew ){
  130599. pNewTerm = &pWC->a[idxNew];
  130600. pNewTerm->prereqRight = 0;
  130601. pNewTerm->leftCursor = pLeft->iTable;
  130602. pNewTerm->u.leftColumn = pLeft->iColumn;
  130603. pNewTerm->eOperator = WO_GT;
  130604. markTermAsChild(pWC, idxNew, idxTerm);
  130605. pTerm = &pWC->a[idxTerm];
  130606. pTerm->wtFlags |= TERM_COPIED;
  130607. pNewTerm->prereqAll = pTerm->prereqAll;
  130608. }
  130609. }
  130610. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  130611. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  130612. ** an index for tables to the left of the join.
  130613. */
  130614. testcase( pTerm!=&pWC->a[idxTerm] );
  130615. pTerm = &pWC->a[idxTerm];
  130616. pTerm->prereqRight |= extraRight;
  130617. }
  130618. /***************************************************************************
  130619. ** Routines with file scope above. Interface to the rest of the where.c
  130620. ** subsystem follows.
  130621. ***************************************************************************/
  130622. /*
  130623. ** This routine identifies subexpressions in the WHERE clause where
  130624. ** each subexpression is separated by the AND operator or some other
  130625. ** operator specified in the op parameter. The WhereClause structure
  130626. ** is filled with pointers to subexpressions. For example:
  130627. **
  130628. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  130629. ** \________/ \_______________/ \________________/
  130630. ** slot[0] slot[1] slot[2]
  130631. **
  130632. ** The original WHERE clause in pExpr is unaltered. All this routine
  130633. ** does is make slot[] entries point to substructure within pExpr.
  130634. **
  130635. ** In the previous sentence and in the diagram, "slot[]" refers to
  130636. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  130637. ** all terms of the WHERE clause.
  130638. */
  130639. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  130640. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  130641. pWC->op = op;
  130642. if( pE2==0 ) return;
  130643. if( pE2->op!=op ){
  130644. whereClauseInsert(pWC, pExpr, 0);
  130645. }else{
  130646. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  130647. sqlite3WhereSplit(pWC, pE2->pRight, op);
  130648. }
  130649. }
  130650. /*
  130651. ** Initialize a preallocated WhereClause structure.
  130652. */
  130653. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  130654. WhereClause *pWC, /* The WhereClause to be initialized */
  130655. WhereInfo *pWInfo /* The WHERE processing context */
  130656. ){
  130657. pWC->pWInfo = pWInfo;
  130658. pWC->hasOr = 0;
  130659. pWC->pOuter = 0;
  130660. pWC->nTerm = 0;
  130661. pWC->nSlot = ArraySize(pWC->aStatic);
  130662. pWC->a = pWC->aStatic;
  130663. }
  130664. /*
  130665. ** Deallocate a WhereClause structure. The WhereClause structure
  130666. ** itself is not freed. This routine is the inverse of
  130667. ** sqlite3WhereClauseInit().
  130668. */
  130669. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  130670. int i;
  130671. WhereTerm *a;
  130672. sqlite3 *db = pWC->pWInfo->pParse->db;
  130673. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  130674. if( a->wtFlags & TERM_DYNAMIC ){
  130675. sqlite3ExprDelete(db, a->pExpr);
  130676. }
  130677. if( a->wtFlags & TERM_ORINFO ){
  130678. whereOrInfoDelete(db, a->u.pOrInfo);
  130679. }else if( a->wtFlags & TERM_ANDINFO ){
  130680. whereAndInfoDelete(db, a->u.pAndInfo);
  130681. }
  130682. }
  130683. if( pWC->a!=pWC->aStatic ){
  130684. sqlite3DbFree(db, pWC->a);
  130685. }
  130686. }
  130687. /*
  130688. ** These routines walk (recursively) an expression tree and generate
  130689. ** a bitmask indicating which tables are used in that expression
  130690. ** tree.
  130691. */
  130692. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
  130693. Bitmask mask;
  130694. if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
  130695. return sqlite3WhereGetMask(pMaskSet, p->iTable);
  130696. }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  130697. assert( p->op!=TK_IF_NULL_ROW );
  130698. return 0;
  130699. }
  130700. mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
  130701. if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
  130702. if( p->pRight ){
  130703. mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
  130704. assert( p->x.pList==0 );
  130705. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  130706. if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
  130707. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  130708. }else if( p->x.pList ){
  130709. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  130710. }
  130711. return mask;
  130712. }
  130713. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  130714. return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
  130715. }
  130716. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  130717. int i;
  130718. Bitmask mask = 0;
  130719. if( pList ){
  130720. for(i=0; i<pList->nExpr; i++){
  130721. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  130722. }
  130723. }
  130724. return mask;
  130725. }
  130726. /*
  130727. ** Call exprAnalyze on all terms in a WHERE clause.
  130728. **
  130729. ** Note that exprAnalyze() might add new virtual terms onto the
  130730. ** end of the WHERE clause. We do not want to analyze these new
  130731. ** virtual terms, so start analyzing at the end and work forward
  130732. ** so that the added virtual terms are never processed.
  130733. */
  130734. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  130735. SrcList *pTabList, /* the FROM clause */
  130736. WhereClause *pWC /* the WHERE clause to be analyzed */
  130737. ){
  130738. int i;
  130739. for(i=pWC->nTerm-1; i>=0; i--){
  130740. exprAnalyze(pTabList, pWC, i);
  130741. }
  130742. }
  130743. /*
  130744. ** For table-valued-functions, transform the function arguments into
  130745. ** new WHERE clause terms.
  130746. **
  130747. ** Each function argument translates into an equality constraint against
  130748. ** a HIDDEN column in the table.
  130749. */
  130750. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  130751. Parse *pParse, /* Parsing context */
  130752. struct SrcList_item *pItem, /* The FROM clause term to process */
  130753. WhereClause *pWC /* Xfer function arguments to here */
  130754. ){
  130755. Table *pTab;
  130756. int j, k;
  130757. ExprList *pArgs;
  130758. Expr *pColRef;
  130759. Expr *pTerm;
  130760. if( pItem->fg.isTabFunc==0 ) return;
  130761. pTab = pItem->pTab;
  130762. assert( pTab!=0 );
  130763. pArgs = pItem->u1.pFuncArg;
  130764. if( pArgs==0 ) return;
  130765. for(j=k=0; j<pArgs->nExpr; j++){
  130766. Expr *pRhs;
  130767. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
  130768. if( k>=pTab->nCol ){
  130769. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  130770. pTab->zName, j);
  130771. return;
  130772. }
  130773. pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
  130774. if( pColRef==0 ) return;
  130775. pColRef->iTable = pItem->iCursor;
  130776. pColRef->iColumn = k++;
  130777. pColRef->y.pTab = pTab;
  130778. pRhs = sqlite3PExpr(pParse, TK_UPLUS,
  130779. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
  130780. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
  130781. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  130782. }
  130783. }
  130784. /************** End of whereexpr.c *******************************************/
  130785. /************** Begin file where.c *******************************************/
  130786. /*
  130787. ** 2001 September 15
  130788. **
  130789. ** The author disclaims copyright to this source code. In place of
  130790. ** a legal notice, here is a blessing:
  130791. **
  130792. ** May you do good and not evil.
  130793. ** May you find forgiveness for yourself and forgive others.
  130794. ** May you share freely, never taking more than you give.
  130795. **
  130796. *************************************************************************
  130797. ** This module contains C code that generates VDBE code used to process
  130798. ** the WHERE clause of SQL statements. This module is responsible for
  130799. ** generating the code that loops through a table looking for applicable
  130800. ** rows. Indices are selected and used to speed the search when doing
  130801. ** so is applicable. Because this module is responsible for selecting
  130802. ** indices, you might also think of this module as the "query optimizer".
  130803. */
  130804. /* #include "sqliteInt.h" */
  130805. /* #include "whereInt.h" */
  130806. /*
  130807. ** Extra information appended to the end of sqlite3_index_info but not
  130808. ** visible to the xBestIndex function, at least not directly. The
  130809. ** sqlite3_vtab_collation() interface knows how to reach it, however.
  130810. **
  130811. ** This object is not an API and can be changed from one release to the
  130812. ** next. As long as allocateIndexInfo() and sqlite3_vtab_collation()
  130813. ** agree on the structure, all will be well.
  130814. */
  130815. typedef struct HiddenIndexInfo HiddenIndexInfo;
  130816. struct HiddenIndexInfo {
  130817. WhereClause *pWC; /* The Where clause being analyzed */
  130818. Parse *pParse; /* The parsing context */
  130819. };
  130820. /* Forward declaration of methods */
  130821. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  130822. /* Test variable that can be set to enable WHERE tracing */
  130823. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  130824. /***/ int sqlite3WhereTrace = 0;
  130825. #endif
  130826. /*
  130827. ** Return the estimated number of output rows from a WHERE clause
  130828. */
  130829. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  130830. return pWInfo->nRowOut;
  130831. }
  130832. /*
  130833. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  130834. ** WHERE clause returns outputs for DISTINCT processing.
  130835. */
  130836. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  130837. return pWInfo->eDistinct;
  130838. }
  130839. /*
  130840. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  130841. ** Return FALSE if the output needs to be sorted.
  130842. */
  130843. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  130844. return pWInfo->nOBSat;
  130845. }
  130846. /*
  130847. ** In the ORDER BY LIMIT optimization, if the inner-most loop is known
  130848. ** to emit rows in increasing order, and if the last row emitted by the
  130849. ** inner-most loop did not fit within the sorter, then we can skip all
  130850. ** subsequent rows for the current iteration of the inner loop (because they
  130851. ** will not fit in the sorter either) and continue with the second inner
  130852. ** loop - the loop immediately outside the inner-most.
  130853. **
  130854. ** When a row does not fit in the sorter (because the sorter already
  130855. ** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the
  130856. ** label returned by this function.
  130857. **
  130858. ** If the ORDER BY LIMIT optimization applies, the jump destination should
  130859. ** be the continuation for the second-inner-most loop. If the ORDER BY
  130860. ** LIMIT optimization does not apply, then the jump destination should
  130861. ** be the continuation for the inner-most loop.
  130862. **
  130863. ** It is always safe for this routine to return the continuation of the
  130864. ** inner-most loop, in the sense that a correct answer will result.
  130865. ** Returning the continuation the second inner loop is an optimization
  130866. ** that might make the code run a little faster, but should not change
  130867. ** the final answer.
  130868. */
  130869. SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){
  130870. WhereLevel *pInner;
  130871. if( !pWInfo->bOrderedInnerLoop ){
  130872. /* The ORDER BY LIMIT optimization does not apply. Jump to the
  130873. ** continuation of the inner-most loop. */
  130874. return pWInfo->iContinue;
  130875. }
  130876. pInner = &pWInfo->a[pWInfo->nLevel-1];
  130877. assert( pInner->addrNxt!=0 );
  130878. return pInner->addrNxt;
  130879. }
  130880. /*
  130881. ** Return the VDBE address or label to jump to in order to continue
  130882. ** immediately with the next row of a WHERE clause.
  130883. */
  130884. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  130885. assert( pWInfo->iContinue!=0 );
  130886. return pWInfo->iContinue;
  130887. }
  130888. /*
  130889. ** Return the VDBE address or label to jump to in order to break
  130890. ** out of a WHERE loop.
  130891. */
  130892. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  130893. return pWInfo->iBreak;
  130894. }
  130895. /*
  130896. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  130897. ** operate directly on the rowis returned by a WHERE clause. Return
  130898. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  130899. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  130900. ** optimization can be used on multiple
  130901. **
  130902. ** If the ONEPASS optimization is used (if this routine returns true)
  130903. ** then also write the indices of open cursors used by ONEPASS
  130904. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  130905. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  130906. ** Either value may be -1, indicating that cursor is not used.
  130907. ** Any cursors returned will have been opened for writing.
  130908. **
  130909. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  130910. ** unable to use the ONEPASS optimization.
  130911. */
  130912. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  130913. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  130914. #ifdef WHERETRACE_ENABLED
  130915. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  130916. sqlite3DebugPrintf("%s cursors: %d %d\n",
  130917. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  130918. aiCur[0], aiCur[1]);
  130919. }
  130920. #endif
  130921. return pWInfo->eOnePass;
  130922. }
  130923. /*
  130924. ** Move the content of pSrc into pDest
  130925. */
  130926. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  130927. pDest->n = pSrc->n;
  130928. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  130929. }
  130930. /*
  130931. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  130932. **
  130933. ** The new entry might overwrite an existing entry, or it might be
  130934. ** appended, or it might be discarded. Do whatever is the right thing
  130935. ** so that pSet keeps the N_OR_COST best entries seen so far.
  130936. */
  130937. static int whereOrInsert(
  130938. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  130939. Bitmask prereq, /* Prerequisites of the new entry */
  130940. LogEst rRun, /* Run-cost of the new entry */
  130941. LogEst nOut /* Number of outputs for the new entry */
  130942. ){
  130943. u16 i;
  130944. WhereOrCost *p;
  130945. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  130946. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  130947. goto whereOrInsert_done;
  130948. }
  130949. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  130950. return 0;
  130951. }
  130952. }
  130953. if( pSet->n<N_OR_COST ){
  130954. p = &pSet->a[pSet->n++];
  130955. p->nOut = nOut;
  130956. }else{
  130957. p = pSet->a;
  130958. for(i=1; i<pSet->n; i++){
  130959. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  130960. }
  130961. if( p->rRun<=rRun ) return 0;
  130962. }
  130963. whereOrInsert_done:
  130964. p->prereq = prereq;
  130965. p->rRun = rRun;
  130966. if( p->nOut>nOut ) p->nOut = nOut;
  130967. return 1;
  130968. }
  130969. /*
  130970. ** Return the bitmask for the given cursor number. Return 0 if
  130971. ** iCursor is not in the set.
  130972. */
  130973. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  130974. int i;
  130975. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  130976. for(i=0; i<pMaskSet->n; i++){
  130977. if( pMaskSet->ix[i]==iCursor ){
  130978. return MASKBIT(i);
  130979. }
  130980. }
  130981. return 0;
  130982. }
  130983. /*
  130984. ** Create a new mask for cursor iCursor.
  130985. **
  130986. ** There is one cursor per table in the FROM clause. The number of
  130987. ** tables in the FROM clause is limited by a test early in the
  130988. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  130989. ** array will never overflow.
  130990. */
  130991. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  130992. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  130993. pMaskSet->ix[pMaskSet->n++] = iCursor;
  130994. }
  130995. /*
  130996. ** Advance to the next WhereTerm that matches according to the criteria
  130997. ** established when the pScan object was initialized by whereScanInit().
  130998. ** Return NULL if there are no more matching WhereTerms.
  130999. */
  131000. static WhereTerm *whereScanNext(WhereScan *pScan){
  131001. int iCur; /* The cursor on the LHS of the term */
  131002. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  131003. Expr *pX; /* An expression being tested */
  131004. WhereClause *pWC; /* Shorthand for pScan->pWC */
  131005. WhereTerm *pTerm; /* The term being tested */
  131006. int k = pScan->k; /* Where to start scanning */
  131007. assert( pScan->iEquiv<=pScan->nEquiv );
  131008. pWC = pScan->pWC;
  131009. while(1){
  131010. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  131011. iCur = pScan->aiCur[pScan->iEquiv-1];
  131012. assert( pWC!=0 );
  131013. do{
  131014. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  131015. if( pTerm->leftCursor==iCur
  131016. && pTerm->u.leftColumn==iColumn
  131017. && (iColumn!=XN_EXPR
  131018. || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
  131019. pScan->pIdxExpr,iCur)==0)
  131020. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  131021. ){
  131022. if( (pTerm->eOperator & WO_EQUIV)!=0
  131023. && pScan->nEquiv<ArraySize(pScan->aiCur)
  131024. && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
  131025. ){
  131026. int j;
  131027. for(j=0; j<pScan->nEquiv; j++){
  131028. if( pScan->aiCur[j]==pX->iTable
  131029. && pScan->aiColumn[j]==pX->iColumn ){
  131030. break;
  131031. }
  131032. }
  131033. if( j==pScan->nEquiv ){
  131034. pScan->aiCur[j] = pX->iTable;
  131035. pScan->aiColumn[j] = pX->iColumn;
  131036. pScan->nEquiv++;
  131037. }
  131038. }
  131039. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  131040. /* Verify the affinity and collating sequence match */
  131041. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  131042. CollSeq *pColl;
  131043. Parse *pParse = pWC->pWInfo->pParse;
  131044. pX = pTerm->pExpr;
  131045. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  131046. continue;
  131047. }
  131048. assert(pX->pLeft);
  131049. pColl = sqlite3BinaryCompareCollSeq(pParse,
  131050. pX->pLeft, pX->pRight);
  131051. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  131052. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  131053. continue;
  131054. }
  131055. }
  131056. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  131057. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  131058. && pX->iTable==pScan->aiCur[0]
  131059. && pX->iColumn==pScan->aiColumn[0]
  131060. ){
  131061. testcase( pTerm->eOperator & WO_IS );
  131062. continue;
  131063. }
  131064. pScan->pWC = pWC;
  131065. pScan->k = k+1;
  131066. return pTerm;
  131067. }
  131068. }
  131069. }
  131070. pWC = pWC->pOuter;
  131071. k = 0;
  131072. }while( pWC!=0 );
  131073. if( pScan->iEquiv>=pScan->nEquiv ) break;
  131074. pWC = pScan->pOrigWC;
  131075. k = 0;
  131076. pScan->iEquiv++;
  131077. }
  131078. return 0;
  131079. }
  131080. /*
  131081. ** Initialize a WHERE clause scanner object. Return a pointer to the
  131082. ** first match. Return NULL if there are no matches.
  131083. **
  131084. ** The scanner will be searching the WHERE clause pWC. It will look
  131085. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  131086. ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
  131087. ** must be one of the indexes of table iCur.
  131088. **
  131089. ** The <op> must be one of the operators described by opMask.
  131090. **
  131091. ** If the search is for X and the WHERE clause contains terms of the
  131092. ** form X=Y then this routine might also return terms of the form
  131093. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  131094. ** but is enough to handle most commonly occurring SQL statements.
  131095. **
  131096. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  131097. ** index pIdx.
  131098. */
  131099. static WhereTerm *whereScanInit(
  131100. WhereScan *pScan, /* The WhereScan object being initialized */
  131101. WhereClause *pWC, /* The WHERE clause to be scanned */
  131102. int iCur, /* Cursor to scan for */
  131103. int iColumn, /* Column to scan for */
  131104. u32 opMask, /* Operator(s) to scan for */
  131105. Index *pIdx /* Must be compatible with this index */
  131106. ){
  131107. pScan->pOrigWC = pWC;
  131108. pScan->pWC = pWC;
  131109. pScan->pIdxExpr = 0;
  131110. pScan->idxaff = 0;
  131111. pScan->zCollName = 0;
  131112. if( pIdx ){
  131113. int j = iColumn;
  131114. iColumn = pIdx->aiColumn[j];
  131115. if( iColumn==XN_EXPR ){
  131116. pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  131117. pScan->zCollName = pIdx->azColl[j];
  131118. }else if( iColumn==pIdx->pTable->iPKey ){
  131119. iColumn = XN_ROWID;
  131120. }else if( iColumn>=0 ){
  131121. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  131122. pScan->zCollName = pIdx->azColl[j];
  131123. }
  131124. }else if( iColumn==XN_EXPR ){
  131125. return 0;
  131126. }
  131127. pScan->opMask = opMask;
  131128. pScan->k = 0;
  131129. pScan->aiCur[0] = iCur;
  131130. pScan->aiColumn[0] = iColumn;
  131131. pScan->nEquiv = 1;
  131132. pScan->iEquiv = 1;
  131133. return whereScanNext(pScan);
  131134. }
  131135. /*
  131136. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  131137. ** where X is a reference to the iColumn of table iCur or of index pIdx
  131138. ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
  131139. ** the op parameter. Return a pointer to the term. Return 0 if not found.
  131140. **
  131141. ** If pIdx!=0 then it must be one of the indexes of table iCur.
  131142. ** Search for terms matching the iColumn-th column of pIdx
  131143. ** rather than the iColumn-th column of table iCur.
  131144. **
  131145. ** The term returned might by Y=<expr> if there is another constraint in
  131146. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  131147. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  131148. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  131149. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  131150. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  131151. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  131152. **
  131153. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  131154. ** then try for the one with no dependencies on <expr> - in other words where
  131155. ** <expr> is a constant expression of some kind. Only return entries of
  131156. ** the form "X <op> Y" where Y is a column in another table if no terms of
  131157. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  131158. ** exist, try to return a term that does not use WO_EQUIV.
  131159. */
  131160. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  131161. WhereClause *pWC, /* The WHERE clause to be searched */
  131162. int iCur, /* Cursor number of LHS */
  131163. int iColumn, /* Column number of LHS */
  131164. Bitmask notReady, /* RHS must not overlap with this mask */
  131165. u32 op, /* Mask of WO_xx values describing operator */
  131166. Index *pIdx /* Must be compatible with this index, if not NULL */
  131167. ){
  131168. WhereTerm *pResult = 0;
  131169. WhereTerm *p;
  131170. WhereScan scan;
  131171. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  131172. op &= WO_EQ|WO_IS;
  131173. while( p ){
  131174. if( (p->prereqRight & notReady)==0 ){
  131175. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  131176. testcase( p->eOperator & WO_IS );
  131177. return p;
  131178. }
  131179. if( pResult==0 ) pResult = p;
  131180. }
  131181. p = whereScanNext(&scan);
  131182. }
  131183. return pResult;
  131184. }
  131185. /*
  131186. ** This function searches pList for an entry that matches the iCol-th column
  131187. ** of index pIdx.
  131188. **
  131189. ** If such an expression is found, its index in pList->a[] is returned. If
  131190. ** no expression is found, -1 is returned.
  131191. */
  131192. static int findIndexCol(
  131193. Parse *pParse, /* Parse context */
  131194. ExprList *pList, /* Expression list to search */
  131195. int iBase, /* Cursor for table associated with pIdx */
  131196. Index *pIdx, /* Index to match column of */
  131197. int iCol /* Column of index to match */
  131198. ){
  131199. int i;
  131200. const char *zColl = pIdx->azColl[iCol];
  131201. for(i=0; i<pList->nExpr; i++){
  131202. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  131203. if( p->op==TK_COLUMN
  131204. && p->iColumn==pIdx->aiColumn[iCol]
  131205. && p->iTable==iBase
  131206. ){
  131207. CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
  131208. if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
  131209. return i;
  131210. }
  131211. }
  131212. }
  131213. return -1;
  131214. }
  131215. /*
  131216. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  131217. */
  131218. static int indexColumnNotNull(Index *pIdx, int iCol){
  131219. int j;
  131220. assert( pIdx!=0 );
  131221. assert( iCol>=0 && iCol<pIdx->nColumn );
  131222. j = pIdx->aiColumn[iCol];
  131223. if( j>=0 ){
  131224. return pIdx->pTable->aCol[j].notNull;
  131225. }else if( j==(-1) ){
  131226. return 1;
  131227. }else{
  131228. assert( j==(-2) );
  131229. return 0; /* Assume an indexed expression can always yield a NULL */
  131230. }
  131231. }
  131232. /*
  131233. ** Return true if the DISTINCT expression-list passed as the third argument
  131234. ** is redundant.
  131235. **
  131236. ** A DISTINCT list is redundant if any subset of the columns in the
  131237. ** DISTINCT list are collectively unique and individually non-null.
  131238. */
  131239. static int isDistinctRedundant(
  131240. Parse *pParse, /* Parsing context */
  131241. SrcList *pTabList, /* The FROM clause */
  131242. WhereClause *pWC, /* The WHERE clause */
  131243. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  131244. ){
  131245. Table *pTab;
  131246. Index *pIdx;
  131247. int i;
  131248. int iBase;
  131249. /* If there is more than one table or sub-select in the FROM clause of
  131250. ** this query, then it will not be possible to show that the DISTINCT
  131251. ** clause is redundant. */
  131252. if( pTabList->nSrc!=1 ) return 0;
  131253. iBase = pTabList->a[0].iCursor;
  131254. pTab = pTabList->a[0].pTab;
  131255. /* If any of the expressions is an IPK column on table iBase, then return
  131256. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  131257. ** current SELECT is a correlated sub-query.
  131258. */
  131259. for(i=0; i<pDistinct->nExpr; i++){
  131260. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  131261. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  131262. }
  131263. /* Loop through all indices on the table, checking each to see if it makes
  131264. ** the DISTINCT qualifier redundant. It does so if:
  131265. **
  131266. ** 1. The index is itself UNIQUE, and
  131267. **
  131268. ** 2. All of the columns in the index are either part of the pDistinct
  131269. ** list, or else the WHERE clause contains a term of the form "col=X",
  131270. ** where X is a constant value. The collation sequences of the
  131271. ** comparison and select-list expressions must match those of the index.
  131272. **
  131273. ** 3. All of those index columns for which the WHERE clause does not
  131274. ** contain a "col=X" term are subject to a NOT NULL constraint.
  131275. */
  131276. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  131277. if( !IsUniqueIndex(pIdx) ) continue;
  131278. for(i=0; i<pIdx->nKeyCol; i++){
  131279. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  131280. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  131281. if( indexColumnNotNull(pIdx, i)==0 ) break;
  131282. }
  131283. }
  131284. if( i==pIdx->nKeyCol ){
  131285. /* This index implies that the DISTINCT qualifier is redundant. */
  131286. return 1;
  131287. }
  131288. }
  131289. return 0;
  131290. }
  131291. /*
  131292. ** Estimate the logarithm of the input value to base 2.
  131293. */
  131294. static LogEst estLog(LogEst N){
  131295. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  131296. }
  131297. /*
  131298. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  131299. **
  131300. ** This routine runs over generated VDBE code and translates OP_Column
  131301. ** opcodes into OP_Copy when the table is being accessed via co-routine
  131302. ** instead of via table lookup.
  131303. **
  131304. ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
  131305. ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
  131306. ** then each OP_Rowid is transformed into an instruction to increment the
  131307. ** value stored in its output register.
  131308. */
  131309. static void translateColumnToCopy(
  131310. Parse *pParse, /* Parsing context */
  131311. int iStart, /* Translate from this opcode to the end */
  131312. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  131313. int iRegister, /* The first column is in this register */
  131314. int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
  131315. ){
  131316. Vdbe *v = pParse->pVdbe;
  131317. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  131318. int iEnd = sqlite3VdbeCurrentAddr(v);
  131319. if( pParse->db->mallocFailed ) return;
  131320. for(; iStart<iEnd; iStart++, pOp++){
  131321. if( pOp->p1!=iTabCur ) continue;
  131322. if( pOp->opcode==OP_Column ){
  131323. pOp->opcode = OP_Copy;
  131324. pOp->p1 = pOp->p2 + iRegister;
  131325. pOp->p2 = pOp->p3;
  131326. pOp->p3 = 0;
  131327. }else if( pOp->opcode==OP_Rowid ){
  131328. if( bIncrRowid ){
  131329. /* Increment the value stored in the P2 operand of the OP_Rowid. */
  131330. pOp->opcode = OP_AddImm;
  131331. pOp->p1 = pOp->p2;
  131332. pOp->p2 = 1;
  131333. }else{
  131334. pOp->opcode = OP_Null;
  131335. pOp->p1 = 0;
  131336. pOp->p3 = 0;
  131337. }
  131338. }
  131339. }
  131340. }
  131341. /*
  131342. ** Two routines for printing the content of an sqlite3_index_info
  131343. ** structure. Used for testing and debugging only. If neither
  131344. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  131345. ** are no-ops.
  131346. */
  131347. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  131348. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  131349. int i;
  131350. if( !sqlite3WhereTrace ) return;
  131351. for(i=0; i<p->nConstraint; i++){
  131352. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  131353. i,
  131354. p->aConstraint[i].iColumn,
  131355. p->aConstraint[i].iTermOffset,
  131356. p->aConstraint[i].op,
  131357. p->aConstraint[i].usable);
  131358. }
  131359. for(i=0; i<p->nOrderBy; i++){
  131360. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  131361. i,
  131362. p->aOrderBy[i].iColumn,
  131363. p->aOrderBy[i].desc);
  131364. }
  131365. }
  131366. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  131367. int i;
  131368. if( !sqlite3WhereTrace ) return;
  131369. for(i=0; i<p->nConstraint; i++){
  131370. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  131371. i,
  131372. p->aConstraintUsage[i].argvIndex,
  131373. p->aConstraintUsage[i].omit);
  131374. }
  131375. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  131376. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  131377. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  131378. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  131379. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  131380. }
  131381. #else
  131382. #define TRACE_IDX_INPUTS(A)
  131383. #define TRACE_IDX_OUTPUTS(A)
  131384. #endif
  131385. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  131386. /*
  131387. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  131388. ** could be used with an index to access pSrc, assuming an appropriate
  131389. ** index existed.
  131390. */
  131391. static int termCanDriveIndex(
  131392. WhereTerm *pTerm, /* WHERE clause term to check */
  131393. struct SrcList_item *pSrc, /* Table we are trying to access */
  131394. Bitmask notReady /* Tables in outer loops of the join */
  131395. ){
  131396. char aff;
  131397. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  131398. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  131399. if( (pSrc->fg.jointype & JT_LEFT)
  131400. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  131401. && (pTerm->eOperator & WO_IS)
  131402. ){
  131403. /* Cannot use an IS term from the WHERE clause as an index driver for
  131404. ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
  131405. ** the ON clause. */
  131406. return 0;
  131407. }
  131408. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  131409. if( pTerm->u.leftColumn<0 ) return 0;
  131410. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  131411. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  131412. testcase( pTerm->pExpr->op==TK_IS );
  131413. return 1;
  131414. }
  131415. #endif
  131416. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  131417. /*
  131418. ** Generate code to construct the Index object for an automatic index
  131419. ** and to set up the WhereLevel object pLevel so that the code generator
  131420. ** makes use of the automatic index.
  131421. */
  131422. static void constructAutomaticIndex(
  131423. Parse *pParse, /* The parsing context */
  131424. WhereClause *pWC, /* The WHERE clause */
  131425. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  131426. Bitmask notReady, /* Mask of cursors that are not available */
  131427. WhereLevel *pLevel /* Write new index here */
  131428. ){
  131429. int nKeyCol; /* Number of columns in the constructed index */
  131430. WhereTerm *pTerm; /* A single term of the WHERE clause */
  131431. WhereTerm *pWCEnd; /* End of pWC->a[] */
  131432. Index *pIdx; /* Object describing the transient index */
  131433. Vdbe *v; /* Prepared statement under construction */
  131434. int addrInit; /* Address of the initialization bypass jump */
  131435. Table *pTable; /* The table being indexed */
  131436. int addrTop; /* Top of the index fill loop */
  131437. int regRecord; /* Register holding an index record */
  131438. int n; /* Column counter */
  131439. int i; /* Loop counter */
  131440. int mxBitCol; /* Maximum column in pSrc->colUsed */
  131441. CollSeq *pColl; /* Collating sequence to on a column */
  131442. WhereLoop *pLoop; /* The Loop object */
  131443. char *zNotUsed; /* Extra space on the end of pIdx */
  131444. Bitmask idxCols; /* Bitmap of columns used for indexing */
  131445. Bitmask extraCols; /* Bitmap of additional columns */
  131446. u8 sentWarning = 0; /* True if a warnning has been issued */
  131447. Expr *pPartial = 0; /* Partial Index Expression */
  131448. int iContinue = 0; /* Jump here to skip excluded rows */
  131449. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  131450. int addrCounter = 0; /* Address where integer counter is initialized */
  131451. int regBase; /* Array of registers where record is assembled */
  131452. /* Generate code to skip over the creation and initialization of the
  131453. ** transient index on 2nd and subsequent iterations of the loop. */
  131454. v = pParse->pVdbe;
  131455. assert( v!=0 );
  131456. addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  131457. /* Count the number of columns that will be added to the index
  131458. ** and used to match WHERE clause constraints */
  131459. nKeyCol = 0;
  131460. pTable = pSrc->pTab;
  131461. pWCEnd = &pWC->a[pWC->nTerm];
  131462. pLoop = pLevel->pWLoop;
  131463. idxCols = 0;
  131464. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  131465. Expr *pExpr = pTerm->pExpr;
  131466. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  131467. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  131468. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  131469. if( pLoop->prereq==0
  131470. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  131471. && !ExprHasProperty(pExpr, EP_FromJoin)
  131472. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  131473. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  131474. sqlite3ExprDup(pParse->db, pExpr, 0));
  131475. }
  131476. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  131477. int iCol = pTerm->u.leftColumn;
  131478. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  131479. testcase( iCol==BMS );
  131480. testcase( iCol==BMS-1 );
  131481. if( !sentWarning ){
  131482. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  131483. "automatic index on %s(%s)", pTable->zName,
  131484. pTable->aCol[iCol].zName);
  131485. sentWarning = 1;
  131486. }
  131487. if( (idxCols & cMask)==0 ){
  131488. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  131489. goto end_auto_index_create;
  131490. }
  131491. pLoop->aLTerm[nKeyCol++] = pTerm;
  131492. idxCols |= cMask;
  131493. }
  131494. }
  131495. }
  131496. assert( nKeyCol>0 );
  131497. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  131498. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  131499. | WHERE_AUTO_INDEX;
  131500. /* Count the number of additional columns needed to create a
  131501. ** covering index. A "covering index" is an index that contains all
  131502. ** columns that are needed by the query. With a covering index, the
  131503. ** original table never needs to be accessed. Automatic indices must
  131504. ** be a covering index because the index will not be updated if the
  131505. ** original table changes and the index and table cannot both be used
  131506. ** if they go out of sync.
  131507. */
  131508. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  131509. mxBitCol = MIN(BMS-1,pTable->nCol);
  131510. testcase( pTable->nCol==BMS-1 );
  131511. testcase( pTable->nCol==BMS-2 );
  131512. for(i=0; i<mxBitCol; i++){
  131513. if( extraCols & MASKBIT(i) ) nKeyCol++;
  131514. }
  131515. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  131516. nKeyCol += pTable->nCol - BMS + 1;
  131517. }
  131518. /* Construct the Index object to describe this index */
  131519. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  131520. if( pIdx==0 ) goto end_auto_index_create;
  131521. pLoop->u.btree.pIndex = pIdx;
  131522. pIdx->zName = "auto-index";
  131523. pIdx->pTable = pTable;
  131524. n = 0;
  131525. idxCols = 0;
  131526. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  131527. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  131528. int iCol = pTerm->u.leftColumn;
  131529. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  131530. testcase( iCol==BMS-1 );
  131531. testcase( iCol==BMS );
  131532. if( (idxCols & cMask)==0 ){
  131533. Expr *pX = pTerm->pExpr;
  131534. idxCols |= cMask;
  131535. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  131536. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  131537. pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
  131538. n++;
  131539. }
  131540. }
  131541. }
  131542. assert( (u32)n==pLoop->u.btree.nEq );
  131543. /* Add additional columns needed to make the automatic index into
  131544. ** a covering index */
  131545. for(i=0; i<mxBitCol; i++){
  131546. if( extraCols & MASKBIT(i) ){
  131547. pIdx->aiColumn[n] = i;
  131548. pIdx->azColl[n] = sqlite3StrBINARY;
  131549. n++;
  131550. }
  131551. }
  131552. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  131553. for(i=BMS-1; i<pTable->nCol; i++){
  131554. pIdx->aiColumn[n] = i;
  131555. pIdx->azColl[n] = sqlite3StrBINARY;
  131556. n++;
  131557. }
  131558. }
  131559. assert( n==nKeyCol );
  131560. pIdx->aiColumn[n] = XN_ROWID;
  131561. pIdx->azColl[n] = sqlite3StrBINARY;
  131562. /* Create the automatic index */
  131563. assert( pLevel->iIdxCur>=0 );
  131564. pLevel->iIdxCur = pParse->nTab++;
  131565. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  131566. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  131567. VdbeComment((v, "for %s", pTable->zName));
  131568. /* Fill the automatic index with content */
  131569. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  131570. if( pTabItem->fg.viaCoroutine ){
  131571. int regYield = pTabItem->regReturn;
  131572. addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
  131573. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  131574. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  131575. VdbeCoverage(v);
  131576. VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
  131577. }else{
  131578. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  131579. }
  131580. if( pPartial ){
  131581. iContinue = sqlite3VdbeMakeLabel(v);
  131582. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  131583. pLoop->wsFlags |= WHERE_PARTIALIDX;
  131584. }
  131585. regRecord = sqlite3GetTempReg(pParse);
  131586. regBase = sqlite3GenerateIndexKey(
  131587. pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  131588. );
  131589. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  131590. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  131591. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  131592. if( pTabItem->fg.viaCoroutine ){
  131593. sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
  131594. testcase( pParse->db->mallocFailed );
  131595. translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
  131596. pTabItem->regResult, 1);
  131597. sqlite3VdbeGoto(v, addrTop);
  131598. }else{
  131599. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  131600. }
  131601. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  131602. sqlite3VdbeJumpHere(v, addrTop);
  131603. sqlite3ReleaseTempReg(pParse, regRecord);
  131604. /* Jump here when skipping the initialization */
  131605. sqlite3VdbeJumpHere(v, addrInit);
  131606. end_auto_index_create:
  131607. sqlite3ExprDelete(pParse->db, pPartial);
  131608. }
  131609. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  131610. #ifndef SQLITE_OMIT_VIRTUALTABLE
  131611. /*
  131612. ** Allocate and populate an sqlite3_index_info structure. It is the
  131613. ** responsibility of the caller to eventually release the structure
  131614. ** by passing the pointer returned by this function to sqlite3_free().
  131615. */
  131616. static sqlite3_index_info *allocateIndexInfo(
  131617. Parse *pParse, /* The parsing context */
  131618. WhereClause *pWC, /* The WHERE clause being analyzed */
  131619. Bitmask mUnusable, /* Ignore terms with these prereqs */
  131620. struct SrcList_item *pSrc, /* The FROM clause term that is the vtab */
  131621. ExprList *pOrderBy, /* The ORDER BY clause */
  131622. u16 *pmNoOmit /* Mask of terms not to omit */
  131623. ){
  131624. int i, j;
  131625. int nTerm;
  131626. struct sqlite3_index_constraint *pIdxCons;
  131627. struct sqlite3_index_orderby *pIdxOrderBy;
  131628. struct sqlite3_index_constraint_usage *pUsage;
  131629. struct HiddenIndexInfo *pHidden;
  131630. WhereTerm *pTerm;
  131631. int nOrderBy;
  131632. sqlite3_index_info *pIdxInfo;
  131633. u16 mNoOmit = 0;
  131634. /* Count the number of possible WHERE clause constraints referring
  131635. ** to this virtual table */
  131636. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  131637. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  131638. if( pTerm->prereqRight & mUnusable ) continue;
  131639. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  131640. testcase( pTerm->eOperator & WO_IN );
  131641. testcase( pTerm->eOperator & WO_ISNULL );
  131642. testcase( pTerm->eOperator & WO_IS );
  131643. testcase( pTerm->eOperator & WO_ALL );
  131644. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  131645. if( pTerm->wtFlags & TERM_VNULL ) continue;
  131646. assert( pTerm->u.leftColumn>=(-1) );
  131647. nTerm++;
  131648. }
  131649. /* If the ORDER BY clause contains only columns in the current
  131650. ** virtual table then allocate space for the aOrderBy part of
  131651. ** the sqlite3_index_info structure.
  131652. */
  131653. nOrderBy = 0;
  131654. if( pOrderBy ){
  131655. int n = pOrderBy->nExpr;
  131656. for(i=0; i<n; i++){
  131657. Expr *pExpr = pOrderBy->a[i].pExpr;
  131658. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  131659. }
  131660. if( i==n){
  131661. nOrderBy = n;
  131662. }
  131663. }
  131664. /* Allocate the sqlite3_index_info structure
  131665. */
  131666. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  131667. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  131668. + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) );
  131669. if( pIdxInfo==0 ){
  131670. sqlite3ErrorMsg(pParse, "out of memory");
  131671. return 0;
  131672. }
  131673. /* Initialize the structure. The sqlite3_index_info structure contains
  131674. ** many fields that are declared "const" to prevent xBestIndex from
  131675. ** changing them. We have to do some funky casting in order to
  131676. ** initialize those fields.
  131677. */
  131678. pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
  131679. pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];
  131680. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  131681. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  131682. *(int*)&pIdxInfo->nConstraint = nTerm;
  131683. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  131684. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  131685. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  131686. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  131687. pUsage;
  131688. pHidden->pWC = pWC;
  131689. pHidden->pParse = pParse;
  131690. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  131691. u16 op;
  131692. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  131693. if( pTerm->prereqRight & mUnusable ) continue;
  131694. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  131695. testcase( pTerm->eOperator & WO_IN );
  131696. testcase( pTerm->eOperator & WO_IS );
  131697. testcase( pTerm->eOperator & WO_ISNULL );
  131698. testcase( pTerm->eOperator & WO_ALL );
  131699. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  131700. if( pTerm->wtFlags & TERM_VNULL ) continue;
  131701. if( (pSrc->fg.jointype & JT_LEFT)!=0
  131702. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  131703. && (pTerm->eOperator & (WO_IS|WO_ISNULL))
  131704. ){
  131705. /* An "IS" term in the WHERE clause where the virtual table is the rhs
  131706. ** of a LEFT JOIN. Do not pass this term to the virtual table
  131707. ** implementation, as this can lead to incorrect results from SQL such
  131708. ** as:
  131709. **
  131710. ** "LEFT JOIN vtab WHERE vtab.col IS NULL" */
  131711. testcase( pTerm->eOperator & WO_ISNULL );
  131712. testcase( pTerm->eOperator & WO_IS );
  131713. continue;
  131714. }
  131715. assert( pTerm->u.leftColumn>=(-1) );
  131716. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  131717. pIdxCons[j].iTermOffset = i;
  131718. op = pTerm->eOperator & WO_ALL;
  131719. if( op==WO_IN ) op = WO_EQ;
  131720. if( op==WO_AUX ){
  131721. pIdxCons[j].op = pTerm->eMatchOp;
  131722. }else if( op & (WO_ISNULL|WO_IS) ){
  131723. if( op==WO_ISNULL ){
  131724. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
  131725. }else{
  131726. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
  131727. }
  131728. }else{
  131729. pIdxCons[j].op = (u8)op;
  131730. /* The direct assignment in the previous line is possible only because
  131731. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  131732. ** following asserts verify this fact. */
  131733. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  131734. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  131735. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  131736. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  131737. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  131738. assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
  131739. if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
  131740. && sqlite3ExprIsVector(pTerm->pExpr->pRight)
  131741. ){
  131742. if( i<16 ) mNoOmit |= (1 << i);
  131743. if( op==WO_LT ) pIdxCons[j].op = WO_LE;
  131744. if( op==WO_GT ) pIdxCons[j].op = WO_GE;
  131745. }
  131746. }
  131747. j++;
  131748. }
  131749. for(i=0; i<nOrderBy; i++){
  131750. Expr *pExpr = pOrderBy->a[i].pExpr;
  131751. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  131752. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  131753. }
  131754. *pmNoOmit = mNoOmit;
  131755. return pIdxInfo;
  131756. }
  131757. /*
  131758. ** The table object reference passed as the second argument to this function
  131759. ** must represent a virtual table. This function invokes the xBestIndex()
  131760. ** method of the virtual table with the sqlite3_index_info object that
  131761. ** comes in as the 3rd argument to this function.
  131762. **
  131763. ** If an error occurs, pParse is populated with an error message and an
  131764. ** appropriate error code is returned. A return of SQLITE_CONSTRAINT from
  131765. ** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that
  131766. ** the current configuration of "unusable" flags in sqlite3_index_info can
  131767. ** not result in a valid plan.
  131768. **
  131769. ** Whether or not an error is returned, it is the responsibility of the
  131770. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  131771. ** that this is required.
  131772. */
  131773. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  131774. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  131775. int rc;
  131776. TRACE_IDX_INPUTS(p);
  131777. rc = pVtab->pModule->xBestIndex(pVtab, p);
  131778. TRACE_IDX_OUTPUTS(p);
  131779. if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
  131780. if( rc==SQLITE_NOMEM ){
  131781. sqlite3OomFault(pParse->db);
  131782. }else if( !pVtab->zErrMsg ){
  131783. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  131784. }else{
  131785. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  131786. }
  131787. }
  131788. sqlite3_free(pVtab->zErrMsg);
  131789. pVtab->zErrMsg = 0;
  131790. return rc;
  131791. }
  131792. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  131793. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  131794. /*
  131795. ** Estimate the location of a particular key among all keys in an
  131796. ** index. Store the results in aStat as follows:
  131797. **
  131798. ** aStat[0] Est. number of rows less than pRec
  131799. ** aStat[1] Est. number of rows equal to pRec
  131800. **
  131801. ** Return the index of the sample that is the smallest sample that
  131802. ** is greater than or equal to pRec. Note that this index is not an index
  131803. ** into the aSample[] array - it is an index into a virtual set of samples
  131804. ** based on the contents of aSample[] and the number of fields in record
  131805. ** pRec.
  131806. */
  131807. static int whereKeyStats(
  131808. Parse *pParse, /* Database connection */
  131809. Index *pIdx, /* Index to consider domain of */
  131810. UnpackedRecord *pRec, /* Vector of values to consider */
  131811. int roundUp, /* Round up if true. Round down if false */
  131812. tRowcnt *aStat /* OUT: stats written here */
  131813. ){
  131814. IndexSample *aSample = pIdx->aSample;
  131815. int iCol; /* Index of required stats in anEq[] etc. */
  131816. int i; /* Index of first sample >= pRec */
  131817. int iSample; /* Smallest sample larger than or equal to pRec */
  131818. int iMin = 0; /* Smallest sample not yet tested */
  131819. int iTest; /* Next sample to test */
  131820. int res; /* Result of comparison operation */
  131821. int nField; /* Number of fields in pRec */
  131822. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  131823. #ifndef SQLITE_DEBUG
  131824. UNUSED_PARAMETER( pParse );
  131825. #endif
  131826. assert( pRec!=0 );
  131827. assert( pIdx->nSample>0 );
  131828. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  131829. /* Do a binary search to find the first sample greater than or equal
  131830. ** to pRec. If pRec contains a single field, the set of samples to search
  131831. ** is simply the aSample[] array. If the samples in aSample[] contain more
  131832. ** than one fields, all fields following the first are ignored.
  131833. **
  131834. ** If pRec contains N fields, where N is more than one, then as well as the
  131835. ** samples in aSample[] (truncated to N fields), the search also has to
  131836. ** consider prefixes of those samples. For example, if the set of samples
  131837. ** in aSample is:
  131838. **
  131839. ** aSample[0] = (a, 5)
  131840. ** aSample[1] = (a, 10)
  131841. ** aSample[2] = (b, 5)
  131842. ** aSample[3] = (c, 100)
  131843. ** aSample[4] = (c, 105)
  131844. **
  131845. ** Then the search space should ideally be the samples above and the
  131846. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  131847. ** the code actually searches this set:
  131848. **
  131849. ** 0: (a)
  131850. ** 1: (a, 5)
  131851. ** 2: (a, 10)
  131852. ** 3: (a, 10)
  131853. ** 4: (b)
  131854. ** 5: (b, 5)
  131855. ** 6: (c)
  131856. ** 7: (c, 100)
  131857. ** 8: (c, 105)
  131858. ** 9: (c, 105)
  131859. **
  131860. ** For each sample in the aSample[] array, N samples are present in the
  131861. ** effective sample array. In the above, samples 0 and 1 are based on
  131862. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  131863. **
  131864. ** Often, sample i of each block of N effective samples has (i+1) fields.
  131865. ** Except, each sample may be extended to ensure that it is greater than or
  131866. ** equal to the previous sample in the array. For example, in the above,
  131867. ** sample 2 is the first sample of a block of N samples, so at first it
  131868. ** appears that it should be 1 field in size. However, that would make it
  131869. ** smaller than sample 1, so the binary search would not work. As a result,
  131870. ** it is extended to two fields. The duplicates that this creates do not
  131871. ** cause any problems.
  131872. */
  131873. nField = pRec->nField;
  131874. iCol = 0;
  131875. iSample = pIdx->nSample * nField;
  131876. do{
  131877. int iSamp; /* Index in aSample[] of test sample */
  131878. int n; /* Number of fields in test sample */
  131879. iTest = (iMin+iSample)/2;
  131880. iSamp = iTest / nField;
  131881. if( iSamp>0 ){
  131882. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  131883. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  131884. ** fields that is greater than the previous effective sample. */
  131885. for(n=(iTest % nField) + 1; n<nField; n++){
  131886. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  131887. }
  131888. }else{
  131889. n = iTest + 1;
  131890. }
  131891. pRec->nField = n;
  131892. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  131893. if( res<0 ){
  131894. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  131895. iMin = iTest+1;
  131896. }else if( res==0 && n<nField ){
  131897. iLower = aSample[iSamp].anLt[n-1];
  131898. iMin = iTest+1;
  131899. res = -1;
  131900. }else{
  131901. iSample = iTest;
  131902. iCol = n-1;
  131903. }
  131904. }while( res && iMin<iSample );
  131905. i = iSample / nField;
  131906. #ifdef SQLITE_DEBUG
  131907. /* The following assert statements check that the binary search code
  131908. ** above found the right answer. This block serves no purpose other
  131909. ** than to invoke the asserts. */
  131910. if( pParse->db->mallocFailed==0 ){
  131911. if( res==0 ){
  131912. /* If (res==0) is true, then pRec must be equal to sample i. */
  131913. assert( i<pIdx->nSample );
  131914. assert( iCol==nField-1 );
  131915. pRec->nField = nField;
  131916. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  131917. || pParse->db->mallocFailed
  131918. );
  131919. }else{
  131920. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  131921. ** all samples in the aSample[] array, pRec must be smaller than the
  131922. ** (iCol+1) field prefix of sample i. */
  131923. assert( i<=pIdx->nSample && i>=0 );
  131924. pRec->nField = iCol+1;
  131925. assert( i==pIdx->nSample
  131926. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  131927. || pParse->db->mallocFailed );
  131928. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  131929. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  131930. ** be greater than or equal to the (iCol) field prefix of sample i.
  131931. ** If (i>0), then pRec must also be greater than sample (i-1). */
  131932. if( iCol>0 ){
  131933. pRec->nField = iCol;
  131934. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  131935. || pParse->db->mallocFailed );
  131936. }
  131937. if( i>0 ){
  131938. pRec->nField = nField;
  131939. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  131940. || pParse->db->mallocFailed );
  131941. }
  131942. }
  131943. }
  131944. #endif /* ifdef SQLITE_DEBUG */
  131945. if( res==0 ){
  131946. /* Record pRec is equal to sample i */
  131947. assert( iCol==nField-1 );
  131948. aStat[0] = aSample[i].anLt[iCol];
  131949. aStat[1] = aSample[i].anEq[iCol];
  131950. }else{
  131951. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  131952. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  131953. ** is larger than all samples in the array. */
  131954. tRowcnt iUpper, iGap;
  131955. if( i>=pIdx->nSample ){
  131956. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  131957. }else{
  131958. iUpper = aSample[i].anLt[iCol];
  131959. }
  131960. if( iLower>=iUpper ){
  131961. iGap = 0;
  131962. }else{
  131963. iGap = iUpper - iLower;
  131964. }
  131965. if( roundUp ){
  131966. iGap = (iGap*2)/3;
  131967. }else{
  131968. iGap = iGap/3;
  131969. }
  131970. aStat[0] = iLower + iGap;
  131971. aStat[1] = pIdx->aAvgEq[nField-1];
  131972. }
  131973. /* Restore the pRec->nField value before returning. */
  131974. pRec->nField = nField;
  131975. return i;
  131976. }
  131977. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  131978. /*
  131979. ** If it is not NULL, pTerm is a term that provides an upper or lower
  131980. ** bound on a range scan. Without considering pTerm, it is estimated
  131981. ** that the scan will visit nNew rows. This function returns the number
  131982. ** estimated to be visited after taking pTerm into account.
  131983. **
  131984. ** If the user explicitly specified a likelihood() value for this term,
  131985. ** then the return value is the likelihood multiplied by the number of
  131986. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  131987. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  131988. */
  131989. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  131990. LogEst nRet = nNew;
  131991. if( pTerm ){
  131992. if( pTerm->truthProb<=0 ){
  131993. nRet += pTerm->truthProb;
  131994. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  131995. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  131996. }
  131997. }
  131998. return nRet;
  131999. }
  132000. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  132001. /*
  132002. ** Return the affinity for a single column of an index.
  132003. */
  132004. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  132005. assert( iCol>=0 && iCol<pIdx->nColumn );
  132006. if( !pIdx->zColAff ){
  132007. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  132008. }
  132009. return pIdx->zColAff[iCol];
  132010. }
  132011. #endif
  132012. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  132013. /*
  132014. ** This function is called to estimate the number of rows visited by a
  132015. ** range-scan on a skip-scan index. For example:
  132016. **
  132017. ** CREATE INDEX i1 ON t1(a, b, c);
  132018. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  132019. **
  132020. ** Value pLoop->nOut is currently set to the estimated number of rows
  132021. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  132022. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  132023. ** on the stat4 data for the index. this scan will be peformed multiple
  132024. ** times (once for each (a,b) combination that matches a=?) is dealt with
  132025. ** by the caller.
  132026. **
  132027. ** It does this by scanning through all stat4 samples, comparing values
  132028. ** extracted from pLower and pUpper with the corresponding column in each
  132029. ** sample. If L and U are the number of samples found to be less than or
  132030. ** equal to the values extracted from pLower and pUpper respectively, and
  132031. ** N is the total number of samples, the pLoop->nOut value is adjusted
  132032. ** as follows:
  132033. **
  132034. ** nOut = nOut * ( min(U - L, 1) / N )
  132035. **
  132036. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  132037. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  132038. ** U is set to N.
  132039. **
  132040. ** Normally, this function sets *pbDone to 1 before returning. However,
  132041. ** if no value can be extracted from either pLower or pUpper (and so the
  132042. ** estimate of the number of rows delivered remains unchanged), *pbDone
  132043. ** is left as is.
  132044. **
  132045. ** If an error occurs, an SQLite error code is returned. Otherwise,
  132046. ** SQLITE_OK.
  132047. */
  132048. static int whereRangeSkipScanEst(
  132049. Parse *pParse, /* Parsing & code generating context */
  132050. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  132051. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  132052. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  132053. int *pbDone /* Set to true if at least one expr. value extracted */
  132054. ){
  132055. Index *p = pLoop->u.btree.pIndex;
  132056. int nEq = pLoop->u.btree.nEq;
  132057. sqlite3 *db = pParse->db;
  132058. int nLower = -1;
  132059. int nUpper = p->nSample+1;
  132060. int rc = SQLITE_OK;
  132061. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  132062. CollSeq *pColl;
  132063. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  132064. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  132065. sqlite3_value *pVal = 0; /* Value extracted from record */
  132066. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  132067. if( pLower ){
  132068. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  132069. nLower = 0;
  132070. }
  132071. if( pUpper && rc==SQLITE_OK ){
  132072. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  132073. nUpper = p2 ? 0 : p->nSample;
  132074. }
  132075. if( p1 || p2 ){
  132076. int i;
  132077. int nDiff;
  132078. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  132079. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  132080. if( rc==SQLITE_OK && p1 ){
  132081. int res = sqlite3MemCompare(p1, pVal, pColl);
  132082. if( res>=0 ) nLower++;
  132083. }
  132084. if( rc==SQLITE_OK && p2 ){
  132085. int res = sqlite3MemCompare(p2, pVal, pColl);
  132086. if( res>=0 ) nUpper++;
  132087. }
  132088. }
  132089. nDiff = (nUpper - nLower);
  132090. if( nDiff<=0 ) nDiff = 1;
  132091. /* If there is both an upper and lower bound specified, and the
  132092. ** comparisons indicate that they are close together, use the fallback
  132093. ** method (assume that the scan visits 1/64 of the rows) for estimating
  132094. ** the number of rows visited. Otherwise, estimate the number of rows
  132095. ** using the method described in the header comment for this function. */
  132096. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  132097. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  132098. pLoop->nOut -= nAdjust;
  132099. *pbDone = 1;
  132100. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  132101. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  132102. }
  132103. }else{
  132104. assert( *pbDone==0 );
  132105. }
  132106. sqlite3ValueFree(p1);
  132107. sqlite3ValueFree(p2);
  132108. sqlite3ValueFree(pVal);
  132109. return rc;
  132110. }
  132111. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  132112. /*
  132113. ** This function is used to estimate the number of rows that will be visited
  132114. ** by scanning an index for a range of values. The range may have an upper
  132115. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  132116. ** and lower bounds are represented by pLower and pUpper respectively. For
  132117. ** example, assuming that index p is on t1(a):
  132118. **
  132119. ** ... FROM t1 WHERE a > ? AND a < ? ...
  132120. ** |_____| |_____|
  132121. ** | |
  132122. ** pLower pUpper
  132123. **
  132124. ** If either of the upper or lower bound is not present, then NULL is passed in
  132125. ** place of the corresponding WhereTerm.
  132126. **
  132127. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  132128. ** column subject to the range constraint. Or, equivalently, the number of
  132129. ** equality constraints optimized by the proposed index scan. For example,
  132130. ** assuming index p is on t1(a, b), and the SQL query is:
  132131. **
  132132. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  132133. **
  132134. ** then nEq is set to 1 (as the range restricted column, b, is the second
  132135. ** left-most column of the index). Or, if the query is:
  132136. **
  132137. ** ... FROM t1 WHERE a > ? AND a < ? ...
  132138. **
  132139. ** then nEq is set to 0.
  132140. **
  132141. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  132142. ** number of rows that the index scan is expected to visit without
  132143. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  132144. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  132145. ** to account for the range constraints pLower and pUpper.
  132146. **
  132147. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  132148. ** used, a single range inequality reduces the search space by a factor of 4.
  132149. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  132150. ** rows visited by a factor of 64.
  132151. */
  132152. static int whereRangeScanEst(
  132153. Parse *pParse, /* Parsing & code generating context */
  132154. WhereLoopBuilder *pBuilder,
  132155. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  132156. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  132157. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  132158. ){
  132159. int rc = SQLITE_OK;
  132160. int nOut = pLoop->nOut;
  132161. LogEst nNew;
  132162. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  132163. Index *p = pLoop->u.btree.pIndex;
  132164. int nEq = pLoop->u.btree.nEq;
  132165. if( p->nSample>0 && nEq<p->nSampleCol
  132166. && OptimizationEnabled(pParse->db, SQLITE_Stat34)
  132167. ){
  132168. if( nEq==pBuilder->nRecValid ){
  132169. UnpackedRecord *pRec = pBuilder->pRec;
  132170. tRowcnt a[2];
  132171. int nBtm = pLoop->u.btree.nBtm;
  132172. int nTop = pLoop->u.btree.nTop;
  132173. /* Variable iLower will be set to the estimate of the number of rows in
  132174. ** the index that are less than the lower bound of the range query. The
  132175. ** lower bound being the concatenation of $P and $L, where $P is the
  132176. ** key-prefix formed by the nEq values matched against the nEq left-most
  132177. ** columns of the index, and $L is the value in pLower.
  132178. **
  132179. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  132180. ** is not a simple variable or literal value), the lower bound of the
  132181. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  132182. ** if $L is available, whereKeyStats() is called for both ($P) and
  132183. ** ($P:$L) and the larger of the two returned values is used.
  132184. **
  132185. ** Similarly, iUpper is to be set to the estimate of the number of rows
  132186. ** less than the upper bound of the range query. Where the upper bound
  132187. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  132188. ** of iUpper are requested of whereKeyStats() and the smaller used.
  132189. **
  132190. ** The number of rows between the two bounds is then just iUpper-iLower.
  132191. */
  132192. tRowcnt iLower; /* Rows less than the lower bound */
  132193. tRowcnt iUpper; /* Rows less than the upper bound */
  132194. int iLwrIdx = -2; /* aSample[] for the lower bound */
  132195. int iUprIdx = -1; /* aSample[] for the upper bound */
  132196. if( pRec ){
  132197. testcase( pRec->nField!=pBuilder->nRecValid );
  132198. pRec->nField = pBuilder->nRecValid;
  132199. }
  132200. /* Determine iLower and iUpper using ($P) only. */
  132201. if( nEq==0 ){
  132202. iLower = 0;
  132203. iUpper = p->nRowEst0;
  132204. }else{
  132205. /* Note: this call could be optimized away - since the same values must
  132206. ** have been requested when testing key $P in whereEqualScanEst(). */
  132207. whereKeyStats(pParse, p, pRec, 0, a);
  132208. iLower = a[0];
  132209. iUpper = a[0] + a[1];
  132210. }
  132211. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  132212. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  132213. assert( p->aSortOrder!=0 );
  132214. if( p->aSortOrder[nEq] ){
  132215. /* The roles of pLower and pUpper are swapped for a DESC index */
  132216. SWAP(WhereTerm*, pLower, pUpper);
  132217. SWAP(int, nBtm, nTop);
  132218. }
  132219. /* If possible, improve on the iLower estimate using ($P:$L). */
  132220. if( pLower ){
  132221. int n; /* Values extracted from pExpr */
  132222. Expr *pExpr = pLower->pExpr->pRight;
  132223. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
  132224. if( rc==SQLITE_OK && n ){
  132225. tRowcnt iNew;
  132226. u16 mask = WO_GT|WO_LE;
  132227. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  132228. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  132229. iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
  132230. if( iNew>iLower ) iLower = iNew;
  132231. nOut--;
  132232. pLower = 0;
  132233. }
  132234. }
  132235. /* If possible, improve on the iUpper estimate using ($P:$U). */
  132236. if( pUpper ){
  132237. int n; /* Values extracted from pExpr */
  132238. Expr *pExpr = pUpper->pExpr->pRight;
  132239. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
  132240. if( rc==SQLITE_OK && n ){
  132241. tRowcnt iNew;
  132242. u16 mask = WO_GT|WO_LE;
  132243. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  132244. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  132245. iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
  132246. if( iNew<iUpper ) iUpper = iNew;
  132247. nOut--;
  132248. pUpper = 0;
  132249. }
  132250. }
  132251. pBuilder->pRec = pRec;
  132252. if( rc==SQLITE_OK ){
  132253. if( iUpper>iLower ){
  132254. nNew = sqlite3LogEst(iUpper - iLower);
  132255. /* TUNING: If both iUpper and iLower are derived from the same
  132256. ** sample, then assume they are 4x more selective. This brings
  132257. ** the estimated selectivity more in line with what it would be
  132258. ** if estimated without the use of STAT3/4 tables. */
  132259. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  132260. }else{
  132261. nNew = 10; assert( 10==sqlite3LogEst(2) );
  132262. }
  132263. if( nNew<nOut ){
  132264. nOut = nNew;
  132265. }
  132266. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  132267. (u32)iLower, (u32)iUpper, nOut));
  132268. }
  132269. }else{
  132270. int bDone = 0;
  132271. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  132272. if( bDone ) return rc;
  132273. }
  132274. }
  132275. #else
  132276. UNUSED_PARAMETER(pParse);
  132277. UNUSED_PARAMETER(pBuilder);
  132278. assert( pLower || pUpper );
  132279. #endif
  132280. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  132281. nNew = whereRangeAdjust(pLower, nOut);
  132282. nNew = whereRangeAdjust(pUpper, nNew);
  132283. /* TUNING: If there is both an upper and lower limit and neither limit
  132284. ** has an application-defined likelihood(), assume the range is
  132285. ** reduced by an additional 75%. This means that, by default, an open-ended
  132286. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  132287. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  132288. ** match 1/64 of the index. */
  132289. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  132290. nNew -= 20;
  132291. }
  132292. nOut -= (pLower!=0) + (pUpper!=0);
  132293. if( nNew<10 ) nNew = 10;
  132294. if( nNew<nOut ) nOut = nNew;
  132295. #if defined(WHERETRACE_ENABLED)
  132296. if( pLoop->nOut>nOut ){
  132297. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  132298. pLoop->nOut, nOut));
  132299. }
  132300. #endif
  132301. pLoop->nOut = (LogEst)nOut;
  132302. return rc;
  132303. }
  132304. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  132305. /*
  132306. ** Estimate the number of rows that will be returned based on
  132307. ** an equality constraint x=VALUE and where that VALUE occurs in
  132308. ** the histogram data. This only works when x is the left-most
  132309. ** column of an index and sqlite_stat3 histogram data is available
  132310. ** for that index. When pExpr==NULL that means the constraint is
  132311. ** "x IS NULL" instead of "x=VALUE".
  132312. **
  132313. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  132314. ** If unable to make an estimate, leave *pnRow unchanged and return
  132315. ** non-zero.
  132316. **
  132317. ** This routine can fail if it is unable to load a collating sequence
  132318. ** required for string comparison, or if unable to allocate memory
  132319. ** for a UTF conversion required for comparison. The error is stored
  132320. ** in the pParse structure.
  132321. */
  132322. static int whereEqualScanEst(
  132323. Parse *pParse, /* Parsing & code generating context */
  132324. WhereLoopBuilder *pBuilder,
  132325. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  132326. tRowcnt *pnRow /* Write the revised row estimate here */
  132327. ){
  132328. Index *p = pBuilder->pNew->u.btree.pIndex;
  132329. int nEq = pBuilder->pNew->u.btree.nEq;
  132330. UnpackedRecord *pRec = pBuilder->pRec;
  132331. int rc; /* Subfunction return code */
  132332. tRowcnt a[2]; /* Statistics */
  132333. int bOk;
  132334. assert( nEq>=1 );
  132335. assert( nEq<=p->nColumn );
  132336. assert( p->aSample!=0 );
  132337. assert( p->nSample>0 );
  132338. assert( pBuilder->nRecValid<nEq );
  132339. /* If values are not available for all fields of the index to the left
  132340. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  132341. if( pBuilder->nRecValid<(nEq-1) ){
  132342. return SQLITE_NOTFOUND;
  132343. }
  132344. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  132345. ** below would return the same value. */
  132346. if( nEq>=p->nColumn ){
  132347. *pnRow = 1;
  132348. return SQLITE_OK;
  132349. }
  132350. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
  132351. pBuilder->pRec = pRec;
  132352. if( rc!=SQLITE_OK ) return rc;
  132353. if( bOk==0 ) return SQLITE_NOTFOUND;
  132354. pBuilder->nRecValid = nEq;
  132355. whereKeyStats(pParse, p, pRec, 0, a);
  132356. WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
  132357. p->zName, nEq-1, (int)a[1]));
  132358. *pnRow = a[1];
  132359. return rc;
  132360. }
  132361. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  132362. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  132363. /*
  132364. ** Estimate the number of rows that will be returned based on
  132365. ** an IN constraint where the right-hand side of the IN operator
  132366. ** is a list of values. Example:
  132367. **
  132368. ** WHERE x IN (1,2,3,4)
  132369. **
  132370. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  132371. ** If unable to make an estimate, leave *pnRow unchanged and return
  132372. ** non-zero.
  132373. **
  132374. ** This routine can fail if it is unable to load a collating sequence
  132375. ** required for string comparison, or if unable to allocate memory
  132376. ** for a UTF conversion required for comparison. The error is stored
  132377. ** in the pParse structure.
  132378. */
  132379. static int whereInScanEst(
  132380. Parse *pParse, /* Parsing & code generating context */
  132381. WhereLoopBuilder *pBuilder,
  132382. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  132383. tRowcnt *pnRow /* Write the revised row estimate here */
  132384. ){
  132385. Index *p = pBuilder->pNew->u.btree.pIndex;
  132386. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  132387. int nRecValid = pBuilder->nRecValid;
  132388. int rc = SQLITE_OK; /* Subfunction return code */
  132389. tRowcnt nEst; /* Number of rows for a single term */
  132390. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  132391. int i; /* Loop counter */
  132392. assert( p->aSample!=0 );
  132393. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  132394. nEst = nRow0;
  132395. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  132396. nRowEst += nEst;
  132397. pBuilder->nRecValid = nRecValid;
  132398. }
  132399. if( rc==SQLITE_OK ){
  132400. if( nRowEst > nRow0 ) nRowEst = nRow0;
  132401. *pnRow = nRowEst;
  132402. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  132403. }
  132404. assert( pBuilder->nRecValid==nRecValid );
  132405. return rc;
  132406. }
  132407. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  132408. #ifdef WHERETRACE_ENABLED
  132409. /*
  132410. ** Print the content of a WhereTerm object
  132411. */
  132412. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  132413. if( pTerm==0 ){
  132414. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  132415. }else{
  132416. char zType[4];
  132417. char zLeft[50];
  132418. memcpy(zType, "...", 4);
  132419. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  132420. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  132421. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  132422. if( pTerm->eOperator & WO_SINGLE ){
  132423. sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
  132424. pTerm->leftCursor, pTerm->u.leftColumn);
  132425. }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
  132426. sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
  132427. pTerm->u.pOrInfo->indexable);
  132428. }else{
  132429. sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
  132430. }
  132431. sqlite3DebugPrintf(
  132432. "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
  132433. iTerm, pTerm, zType, zLeft, pTerm->truthProb,
  132434. pTerm->eOperator, pTerm->wtFlags);
  132435. if( pTerm->iField ){
  132436. sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
  132437. }else{
  132438. sqlite3DebugPrintf("\n");
  132439. }
  132440. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  132441. }
  132442. }
  132443. #endif
  132444. #ifdef WHERETRACE_ENABLED
  132445. /*
  132446. ** Show the complete content of a WhereClause
  132447. */
  132448. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
  132449. int i;
  132450. for(i=0; i<pWC->nTerm; i++){
  132451. whereTermPrint(&pWC->a[i], i);
  132452. }
  132453. }
  132454. #endif
  132455. #ifdef WHERETRACE_ENABLED
  132456. /*
  132457. ** Print a WhereLoop object for debugging purposes
  132458. */
  132459. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  132460. WhereInfo *pWInfo = pWC->pWInfo;
  132461. int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
  132462. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  132463. Table *pTab = pItem->pTab;
  132464. Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
  132465. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  132466. p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
  132467. sqlite3DebugPrintf(" %12s",
  132468. pItem->zAlias ? pItem->zAlias : pTab->zName);
  132469. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  132470. const char *zName;
  132471. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  132472. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  132473. int i = sqlite3Strlen30(zName) - 1;
  132474. while( zName[i]!='_' ) i--;
  132475. zName += i;
  132476. }
  132477. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  132478. }else{
  132479. sqlite3DebugPrintf("%20s","");
  132480. }
  132481. }else{
  132482. char *z;
  132483. if( p->u.vtab.idxStr ){
  132484. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  132485. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  132486. }else{
  132487. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  132488. }
  132489. sqlite3DebugPrintf(" %-19s", z);
  132490. sqlite3_free(z);
  132491. }
  132492. if( p->wsFlags & WHERE_SKIPSCAN ){
  132493. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  132494. }else{
  132495. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  132496. }
  132497. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  132498. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  132499. int i;
  132500. for(i=0; i<p->nLTerm; i++){
  132501. whereTermPrint(p->aLTerm[i], i);
  132502. }
  132503. }
  132504. }
  132505. #endif
  132506. /*
  132507. ** Convert bulk memory into a valid WhereLoop that can be passed
  132508. ** to whereLoopClear harmlessly.
  132509. */
  132510. static void whereLoopInit(WhereLoop *p){
  132511. p->aLTerm = p->aLTermSpace;
  132512. p->nLTerm = 0;
  132513. p->nLSlot = ArraySize(p->aLTermSpace);
  132514. p->wsFlags = 0;
  132515. }
  132516. /*
  132517. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  132518. */
  132519. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  132520. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  132521. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  132522. sqlite3_free(p->u.vtab.idxStr);
  132523. p->u.vtab.needFree = 0;
  132524. p->u.vtab.idxStr = 0;
  132525. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  132526. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  132527. sqlite3DbFreeNN(db, p->u.btree.pIndex);
  132528. p->u.btree.pIndex = 0;
  132529. }
  132530. }
  132531. }
  132532. /*
  132533. ** Deallocate internal memory used by a WhereLoop object
  132534. */
  132535. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  132536. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  132537. whereLoopClearUnion(db, p);
  132538. whereLoopInit(p);
  132539. }
  132540. /*
  132541. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  132542. */
  132543. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  132544. WhereTerm **paNew;
  132545. if( p->nLSlot>=n ) return SQLITE_OK;
  132546. n = (n+7)&~7;
  132547. paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
  132548. if( paNew==0 ) return SQLITE_NOMEM_BKPT;
  132549. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  132550. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  132551. p->aLTerm = paNew;
  132552. p->nLSlot = n;
  132553. return SQLITE_OK;
  132554. }
  132555. /*
  132556. ** Transfer content from the second pLoop into the first.
  132557. */
  132558. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  132559. whereLoopClearUnion(db, pTo);
  132560. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  132561. memset(&pTo->u, 0, sizeof(pTo->u));
  132562. return SQLITE_NOMEM_BKPT;
  132563. }
  132564. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  132565. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  132566. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  132567. pFrom->u.vtab.needFree = 0;
  132568. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  132569. pFrom->u.btree.pIndex = 0;
  132570. }
  132571. return SQLITE_OK;
  132572. }
  132573. /*
  132574. ** Delete a WhereLoop object
  132575. */
  132576. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  132577. whereLoopClear(db, p);
  132578. sqlite3DbFreeNN(db, p);
  132579. }
  132580. /*
  132581. ** Free a WhereInfo structure
  132582. */
  132583. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  132584. int i;
  132585. assert( pWInfo!=0 );
  132586. for(i=0; i<pWInfo->nLevel; i++){
  132587. WhereLevel *pLevel = &pWInfo->a[i];
  132588. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  132589. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  132590. }
  132591. }
  132592. sqlite3WhereClauseClear(&pWInfo->sWC);
  132593. while( pWInfo->pLoops ){
  132594. WhereLoop *p = pWInfo->pLoops;
  132595. pWInfo->pLoops = p->pNextLoop;
  132596. whereLoopDelete(db, p);
  132597. }
  132598. sqlite3DbFreeNN(db, pWInfo);
  132599. }
  132600. /*
  132601. ** Return TRUE if all of the following are true:
  132602. **
  132603. ** (1) X has the same or lower cost that Y
  132604. ** (2) X uses fewer WHERE clause terms than Y
  132605. ** (3) Every WHERE clause term used by X is also used by Y
  132606. ** (4) X skips at least as many columns as Y
  132607. ** (5) If X is a covering index, than Y is too
  132608. **
  132609. ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
  132610. ** If X is a proper subset of Y then Y is a better choice and ought
  132611. ** to have a lower cost. This routine returns TRUE when that cost
  132612. ** relationship is inverted and needs to be adjusted. Constraint (4)
  132613. ** was added because if X uses skip-scan less than Y it still might
  132614. ** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
  132615. ** was added because a covering index probably deserves to have a lower cost
  132616. ** than a non-covering index even if it is a proper subset.
  132617. */
  132618. static int whereLoopCheaperProperSubset(
  132619. const WhereLoop *pX, /* First WhereLoop to compare */
  132620. const WhereLoop *pY /* Compare against this WhereLoop */
  132621. ){
  132622. int i, j;
  132623. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  132624. return 0; /* X is not a subset of Y */
  132625. }
  132626. if( pY->nSkip > pX->nSkip ) return 0;
  132627. if( pX->rRun >= pY->rRun ){
  132628. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  132629. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  132630. }
  132631. for(i=pX->nLTerm-1; i>=0; i--){
  132632. if( pX->aLTerm[i]==0 ) continue;
  132633. for(j=pY->nLTerm-1; j>=0; j--){
  132634. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  132635. }
  132636. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  132637. }
  132638. if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
  132639. && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
  132640. return 0; /* Constraint (5) */
  132641. }
  132642. return 1; /* All conditions meet */
  132643. }
  132644. /*
  132645. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  132646. ** that:
  132647. **
  132648. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  132649. ** subset of pTemplate
  132650. **
  132651. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  132652. ** is a proper subset.
  132653. **
  132654. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  132655. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  132656. ** also used by Y.
  132657. */
  132658. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  132659. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  132660. for(; p; p=p->pNextLoop){
  132661. if( p->iTab!=pTemplate->iTab ) continue;
  132662. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  132663. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  132664. /* Adjust pTemplate cost downward so that it is cheaper than its
  132665. ** subset p. */
  132666. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  132667. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  132668. pTemplate->rRun = p->rRun;
  132669. pTemplate->nOut = p->nOut - 1;
  132670. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  132671. /* Adjust pTemplate cost upward so that it is costlier than p since
  132672. ** pTemplate is a proper subset of p */
  132673. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  132674. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  132675. pTemplate->rRun = p->rRun;
  132676. pTemplate->nOut = p->nOut + 1;
  132677. }
  132678. }
  132679. }
  132680. /*
  132681. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  132682. ** replaced by pTemplate.
  132683. **
  132684. ** Return NULL if pTemplate does not belong on the WhereLoop list.
  132685. ** In other words if pTemplate ought to be dropped from further consideration.
  132686. **
  132687. ** If pX is a WhereLoop that pTemplate can replace, then return the
  132688. ** link that points to pX.
  132689. **
  132690. ** If pTemplate cannot replace any existing element of the list but needs
  132691. ** to be added to the list as a new entry, then return a pointer to the
  132692. ** tail of the list.
  132693. */
  132694. static WhereLoop **whereLoopFindLesser(
  132695. WhereLoop **ppPrev,
  132696. const WhereLoop *pTemplate
  132697. ){
  132698. WhereLoop *p;
  132699. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  132700. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  132701. /* If either the iTab or iSortIdx values for two WhereLoop are different
  132702. ** then those WhereLoops need to be considered separately. Neither is
  132703. ** a candidate to replace the other. */
  132704. continue;
  132705. }
  132706. /* In the current implementation, the rSetup value is either zero
  132707. ** or the cost of building an automatic index (NlogN) and the NlogN
  132708. ** is the same for compatible WhereLoops. */
  132709. assert( p->rSetup==0 || pTemplate->rSetup==0
  132710. || p->rSetup==pTemplate->rSetup );
  132711. /* whereLoopAddBtree() always generates and inserts the automatic index
  132712. ** case first. Hence compatible candidate WhereLoops never have a larger
  132713. ** rSetup. Call this SETUP-INVARIANT */
  132714. assert( p->rSetup>=pTemplate->rSetup );
  132715. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  132716. ** UNIQUE constraint) with one or more == constraints is better
  132717. ** than an automatic index. Unless it is a skip-scan. */
  132718. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  132719. && (pTemplate->nSkip)==0
  132720. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  132721. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  132722. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  132723. ){
  132724. break;
  132725. }
  132726. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  132727. ** discarded. WhereLoop p is better if:
  132728. ** (1) p has no more dependencies than pTemplate, and
  132729. ** (2) p has an equal or lower cost than pTemplate
  132730. */
  132731. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  132732. && p->rSetup<=pTemplate->rSetup /* (2a) */
  132733. && p->rRun<=pTemplate->rRun /* (2b) */
  132734. && p->nOut<=pTemplate->nOut /* (2c) */
  132735. ){
  132736. return 0; /* Discard pTemplate */
  132737. }
  132738. /* If pTemplate is always better than p, then cause p to be overwritten
  132739. ** with pTemplate. pTemplate is better than p if:
  132740. ** (1) pTemplate has no more dependences than p, and
  132741. ** (2) pTemplate has an equal or lower cost than p.
  132742. */
  132743. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  132744. && p->rRun>=pTemplate->rRun /* (2a) */
  132745. && p->nOut>=pTemplate->nOut /* (2b) */
  132746. ){
  132747. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  132748. break; /* Cause p to be overwritten by pTemplate */
  132749. }
  132750. }
  132751. return ppPrev;
  132752. }
  132753. /*
  132754. ** Insert or replace a WhereLoop entry using the template supplied.
  132755. **
  132756. ** An existing WhereLoop entry might be overwritten if the new template
  132757. ** is better and has fewer dependencies. Or the template will be ignored
  132758. ** and no insert will occur if an existing WhereLoop is faster and has
  132759. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  132760. ** added based on the template.
  132761. **
  132762. ** If pBuilder->pOrSet is not NULL then we care about only the
  132763. ** prerequisites and rRun and nOut costs of the N best loops. That
  132764. ** information is gathered in the pBuilder->pOrSet object. This special
  132765. ** processing mode is used only for OR clause processing.
  132766. **
  132767. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  132768. ** still might overwrite similar loops with the new template if the
  132769. ** new template is better. Loops may be overwritten if the following
  132770. ** conditions are met:
  132771. **
  132772. ** (1) They have the same iTab.
  132773. ** (2) They have the same iSortIdx.
  132774. ** (3) The template has same or fewer dependencies than the current loop
  132775. ** (4) The template has the same or lower cost than the current loop
  132776. */
  132777. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  132778. WhereLoop **ppPrev, *p;
  132779. WhereInfo *pWInfo = pBuilder->pWInfo;
  132780. sqlite3 *db = pWInfo->pParse->db;
  132781. int rc;
  132782. /* Stop the search once we hit the query planner search limit */
  132783. if( pBuilder->iPlanLimit==0 ){
  132784. WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
  132785. if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
  132786. return SQLITE_DONE;
  132787. }
  132788. pBuilder->iPlanLimit--;
  132789. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  132790. ** and prereqs.
  132791. */
  132792. if( pBuilder->pOrSet!=0 ){
  132793. if( pTemplate->nLTerm ){
  132794. #if WHERETRACE_ENABLED
  132795. u16 n = pBuilder->pOrSet->n;
  132796. int x =
  132797. #endif
  132798. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  132799. pTemplate->nOut);
  132800. #if WHERETRACE_ENABLED /* 0x8 */
  132801. if( sqlite3WhereTrace & 0x8 ){
  132802. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  132803. whereLoopPrint(pTemplate, pBuilder->pWC);
  132804. }
  132805. #endif
  132806. }
  132807. return SQLITE_OK;
  132808. }
  132809. /* Look for an existing WhereLoop to replace with pTemplate
  132810. */
  132811. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  132812. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  132813. if( ppPrev==0 ){
  132814. /* There already exists a WhereLoop on the list that is better
  132815. ** than pTemplate, so just ignore pTemplate */
  132816. #if WHERETRACE_ENABLED /* 0x8 */
  132817. if( sqlite3WhereTrace & 0x8 ){
  132818. sqlite3DebugPrintf(" skip: ");
  132819. whereLoopPrint(pTemplate, pBuilder->pWC);
  132820. }
  132821. #endif
  132822. return SQLITE_OK;
  132823. }else{
  132824. p = *ppPrev;
  132825. }
  132826. /* If we reach this point it means that either p[] should be overwritten
  132827. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  132828. ** WhereLoop and insert it.
  132829. */
  132830. #if WHERETRACE_ENABLED /* 0x8 */
  132831. if( sqlite3WhereTrace & 0x8 ){
  132832. if( p!=0 ){
  132833. sqlite3DebugPrintf("replace: ");
  132834. whereLoopPrint(p, pBuilder->pWC);
  132835. sqlite3DebugPrintf(" with: ");
  132836. }else{
  132837. sqlite3DebugPrintf(" add: ");
  132838. }
  132839. whereLoopPrint(pTemplate, pBuilder->pWC);
  132840. }
  132841. #endif
  132842. if( p==0 ){
  132843. /* Allocate a new WhereLoop to add to the end of the list */
  132844. *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
  132845. if( p==0 ) return SQLITE_NOMEM_BKPT;
  132846. whereLoopInit(p);
  132847. p->pNextLoop = 0;
  132848. }else{
  132849. /* We will be overwriting WhereLoop p[]. But before we do, first
  132850. ** go through the rest of the list and delete any other entries besides
  132851. ** p[] that are also supplated by pTemplate */
  132852. WhereLoop **ppTail = &p->pNextLoop;
  132853. WhereLoop *pToDel;
  132854. while( *ppTail ){
  132855. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  132856. if( ppTail==0 ) break;
  132857. pToDel = *ppTail;
  132858. if( pToDel==0 ) break;
  132859. *ppTail = pToDel->pNextLoop;
  132860. #if WHERETRACE_ENABLED /* 0x8 */
  132861. if( sqlite3WhereTrace & 0x8 ){
  132862. sqlite3DebugPrintf(" delete: ");
  132863. whereLoopPrint(pToDel, pBuilder->pWC);
  132864. }
  132865. #endif
  132866. whereLoopDelete(db, pToDel);
  132867. }
  132868. }
  132869. rc = whereLoopXfer(db, p, pTemplate);
  132870. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  132871. Index *pIndex = p->u.btree.pIndex;
  132872. if( pIndex && pIndex->tnum==0 ){
  132873. p->u.btree.pIndex = 0;
  132874. }
  132875. }
  132876. return rc;
  132877. }
  132878. /*
  132879. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  132880. ** WHERE clause that reference the loop but which are not used by an
  132881. ** index.
  132882. *
  132883. ** For every WHERE clause term that is not used by the index
  132884. ** and which has a truth probability assigned by one of the likelihood(),
  132885. ** likely(), or unlikely() SQL functions, reduce the estimated number
  132886. ** of output rows by the probability specified.
  132887. **
  132888. ** TUNING: For every WHERE clause term that is not used by the index
  132889. ** and which does not have an assigned truth probability, heuristics
  132890. ** described below are used to try to estimate the truth probability.
  132891. ** TODO --> Perhaps this is something that could be improved by better
  132892. ** table statistics.
  132893. **
  132894. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  132895. ** value corresponds to -1 in LogEst notation, so this means decrement
  132896. ** the WhereLoop.nOut field for every such WHERE clause term.
  132897. **
  132898. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  132899. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  132900. ** final output row estimate is no greater than 1/4 of the total number
  132901. ** of rows in the table. In other words, assume that x==EXPR will filter
  132902. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  132903. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  132904. ** on the "x" column and so in that case only cap the output row estimate
  132905. ** at 1/2 instead of 1/4.
  132906. */
  132907. static void whereLoopOutputAdjust(
  132908. WhereClause *pWC, /* The WHERE clause */
  132909. WhereLoop *pLoop, /* The loop to adjust downward */
  132910. LogEst nRow /* Number of rows in the entire table */
  132911. ){
  132912. WhereTerm *pTerm, *pX;
  132913. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  132914. int i, j, k;
  132915. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  132916. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  132917. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  132918. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  132919. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  132920. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  132921. for(j=pLoop->nLTerm-1; j>=0; j--){
  132922. pX = pLoop->aLTerm[j];
  132923. if( pX==0 ) continue;
  132924. if( pX==pTerm ) break;
  132925. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  132926. }
  132927. if( j<0 ){
  132928. if( pTerm->truthProb<=0 ){
  132929. /* If a truth probability is specified using the likelihood() hints,
  132930. ** then use the probability provided by the application. */
  132931. pLoop->nOut += pTerm->truthProb;
  132932. }else{
  132933. /* In the absence of explicit truth probabilities, use heuristics to
  132934. ** guess a reasonable truth probability. */
  132935. pLoop->nOut--;
  132936. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  132937. Expr *pRight = pTerm->pExpr->pRight;
  132938. testcase( pTerm->pExpr->op==TK_IS );
  132939. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  132940. k = 10;
  132941. }else{
  132942. k = 20;
  132943. }
  132944. if( iReduce<k ) iReduce = k;
  132945. }
  132946. }
  132947. }
  132948. }
  132949. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  132950. }
  132951. /*
  132952. ** Term pTerm is a vector range comparison operation. The first comparison
  132953. ** in the vector can be optimized using column nEq of the index. This
  132954. ** function returns the total number of vector elements that can be used
  132955. ** as part of the range comparison.
  132956. **
  132957. ** For example, if the query is:
  132958. **
  132959. ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
  132960. **
  132961. ** and the index:
  132962. **
  132963. ** CREATE INDEX ... ON (a, b, c, d, e)
  132964. **
  132965. ** then this function would be invoked with nEq=1. The value returned in
  132966. ** this case is 3.
  132967. */
  132968. static int whereRangeVectorLen(
  132969. Parse *pParse, /* Parsing context */
  132970. int iCur, /* Cursor open on pIdx */
  132971. Index *pIdx, /* The index to be used for a inequality constraint */
  132972. int nEq, /* Number of prior equality constraints on same index */
  132973. WhereTerm *pTerm /* The vector inequality constraint */
  132974. ){
  132975. int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
  132976. int i;
  132977. nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
  132978. for(i=1; i<nCmp; i++){
  132979. /* Test if comparison i of pTerm is compatible with column (i+nEq)
  132980. ** of the index. If not, exit the loop. */
  132981. char aff; /* Comparison affinity */
  132982. char idxaff = 0; /* Indexed columns affinity */
  132983. CollSeq *pColl; /* Comparison collation sequence */
  132984. Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
  132985. Expr *pRhs = pTerm->pExpr->pRight;
  132986. if( pRhs->flags & EP_xIsSelect ){
  132987. pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
  132988. }else{
  132989. pRhs = pRhs->x.pList->a[i].pExpr;
  132990. }
  132991. /* Check that the LHS of the comparison is a column reference to
  132992. ** the right column of the right source table. And that the sort
  132993. ** order of the index column is the same as the sort order of the
  132994. ** leftmost index column. */
  132995. if( pLhs->op!=TK_COLUMN
  132996. || pLhs->iTable!=iCur
  132997. || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
  132998. || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
  132999. ){
  133000. break;
  133001. }
  133002. testcase( pLhs->iColumn==XN_ROWID );
  133003. aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
  133004. idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
  133005. if( aff!=idxaff ) break;
  133006. pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  133007. if( pColl==0 ) break;
  133008. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
  133009. }
  133010. return i;
  133011. }
  133012. /*
  133013. ** Adjust the cost C by the costMult facter T. This only occurs if
  133014. ** compiled with -DSQLITE_ENABLE_COSTMULT
  133015. */
  133016. #ifdef SQLITE_ENABLE_COSTMULT
  133017. # define ApplyCostMultiplier(C,T) C += T
  133018. #else
  133019. # define ApplyCostMultiplier(C,T)
  133020. #endif
  133021. /*
  133022. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  133023. ** index pIndex. Try to match one more.
  133024. **
  133025. ** When this function is called, pBuilder->pNew->nOut contains the
  133026. ** number of rows expected to be visited by filtering using the nEq
  133027. ** terms only. If it is modified, this value is restored before this
  133028. ** function returns.
  133029. **
  133030. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  133031. ** INTEGER PRIMARY KEY.
  133032. */
  133033. static int whereLoopAddBtreeIndex(
  133034. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  133035. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  133036. Index *pProbe, /* An index on pSrc */
  133037. LogEst nInMul /* log(Number of iterations due to IN) */
  133038. ){
  133039. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  133040. Parse *pParse = pWInfo->pParse; /* Parsing context */
  133041. sqlite3 *db = pParse->db; /* Database connection malloc context */
  133042. WhereLoop *pNew; /* Template WhereLoop under construction */
  133043. WhereTerm *pTerm; /* A WhereTerm under consideration */
  133044. int opMask; /* Valid operators for constraints */
  133045. WhereScan scan; /* Iterator for WHERE terms */
  133046. Bitmask saved_prereq; /* Original value of pNew->prereq */
  133047. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  133048. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  133049. u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
  133050. u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
  133051. u16 saved_nSkip; /* Original value of pNew->nSkip */
  133052. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  133053. LogEst saved_nOut; /* Original value of pNew->nOut */
  133054. int rc = SQLITE_OK; /* Return code */
  133055. LogEst rSize; /* Number of rows in the table */
  133056. LogEst rLogSize; /* Logarithm of table size */
  133057. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  133058. pNew = pBuilder->pNew;
  133059. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  133060. WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d\n",
  133061. pProbe->pTable->zName,pProbe->zName, pNew->u.btree.nEq));
  133062. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  133063. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  133064. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  133065. opMask = WO_LT|WO_LE;
  133066. }else{
  133067. assert( pNew->u.btree.nBtm==0 );
  133068. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  133069. }
  133070. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  133071. assert( pNew->u.btree.nEq<pProbe->nColumn );
  133072. saved_nEq = pNew->u.btree.nEq;
  133073. saved_nBtm = pNew->u.btree.nBtm;
  133074. saved_nTop = pNew->u.btree.nTop;
  133075. saved_nSkip = pNew->nSkip;
  133076. saved_nLTerm = pNew->nLTerm;
  133077. saved_wsFlags = pNew->wsFlags;
  133078. saved_prereq = pNew->prereq;
  133079. saved_nOut = pNew->nOut;
  133080. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  133081. opMask, pProbe);
  133082. pNew->rSetup = 0;
  133083. rSize = pProbe->aiRowLogEst[0];
  133084. rLogSize = estLog(rSize);
  133085. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  133086. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  133087. LogEst rCostIdx;
  133088. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  133089. int nIn = 0;
  133090. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133091. int nRecValid = pBuilder->nRecValid;
  133092. #endif
  133093. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  133094. && indexColumnNotNull(pProbe, saved_nEq)
  133095. ){
  133096. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  133097. }
  133098. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  133099. /* Do not allow the upper bound of a LIKE optimization range constraint
  133100. ** to mix with a lower range bound from some other source */
  133101. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  133102. /* Do not allow constraints from the WHERE clause to be used by the
  133103. ** right table of a LEFT JOIN. Only constraints in the ON clause are
  133104. ** allowed */
  133105. if( (pSrc->fg.jointype & JT_LEFT)!=0
  133106. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  133107. ){
  133108. continue;
  133109. }
  133110. if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
  133111. pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
  133112. }else{
  133113. pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
  133114. }
  133115. pNew->wsFlags = saved_wsFlags;
  133116. pNew->u.btree.nEq = saved_nEq;
  133117. pNew->u.btree.nBtm = saved_nBtm;
  133118. pNew->u.btree.nTop = saved_nTop;
  133119. pNew->nLTerm = saved_nLTerm;
  133120. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  133121. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  133122. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  133123. assert( nInMul==0
  133124. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  133125. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  133126. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  133127. );
  133128. if( eOp & WO_IN ){
  133129. Expr *pExpr = pTerm->pExpr;
  133130. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  133131. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  133132. int i;
  133133. nIn = 46; assert( 46==sqlite3LogEst(25) );
  133134. /* The expression may actually be of the form (x, y) IN (SELECT...).
  133135. ** In this case there is a separate term for each of (x) and (y).
  133136. ** However, the nIn multiplier should only be applied once, not once
  133137. ** for each such term. The following loop checks that pTerm is the
  133138. ** first such term in use, and sets nIn back to 0 if it is not. */
  133139. for(i=0; i<pNew->nLTerm-1; i++){
  133140. if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
  133141. }
  133142. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  133143. /* "x IN (value, value, ...)" */
  133144. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  133145. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  133146. ** changes "x IN (?)" into "x=?". */
  133147. }
  133148. if( pProbe->hasStat1 ){
  133149. LogEst M, logK, safetyMargin;
  133150. /* Let:
  133151. ** N = the total number of rows in the table
  133152. ** K = the number of entries on the RHS of the IN operator
  133153. ** M = the number of rows in the table that match terms to the
  133154. ** to the left in the same index. If the IN operator is on
  133155. ** the left-most index column, M==N.
  133156. **
  133157. ** Given the definitions above, it is better to omit the IN operator
  133158. ** from the index lookup and instead do a scan of the M elements,
  133159. ** testing each scanned row against the IN operator separately, if:
  133160. **
  133161. ** M*log(K) < K*log(N)
  133162. **
  133163. ** Our estimates for M, K, and N might be inaccurate, so we build in
  133164. ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
  133165. ** with the index, as using an index has better worst-case behavior.
  133166. ** If we do not have real sqlite_stat1 data, always prefer to use
  133167. ** the index.
  133168. */
  133169. M = pProbe->aiRowLogEst[saved_nEq];
  133170. logK = estLog(nIn);
  133171. safetyMargin = 10; /* TUNING: extra weight for indexed IN */
  133172. if( M + logK + safetyMargin < nIn + rLogSize ){
  133173. WHERETRACE(0x40,
  133174. ("Scan preferred over IN operator on column %d of \"%s\" (%d<%d)\n",
  133175. saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
  133176. continue;
  133177. }else{
  133178. WHERETRACE(0x40,
  133179. ("IN operator preferred on column %d of \"%s\" (%d>=%d)\n",
  133180. saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
  133181. }
  133182. }
  133183. pNew->wsFlags |= WHERE_COLUMN_IN;
  133184. }else if( eOp & (WO_EQ|WO_IS) ){
  133185. int iCol = pProbe->aiColumn[saved_nEq];
  133186. pNew->wsFlags |= WHERE_COLUMN_EQ;
  133187. assert( saved_nEq==pNew->u.btree.nEq );
  133188. if( iCol==XN_ROWID
  133189. || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  133190. ){
  133191. if( iCol==XN_ROWID || pProbe->uniqNotNull
  133192. || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
  133193. ){
  133194. pNew->wsFlags |= WHERE_ONEROW;
  133195. }else{
  133196. pNew->wsFlags |= WHERE_UNQ_WANTED;
  133197. }
  133198. }
  133199. }else if( eOp & WO_ISNULL ){
  133200. pNew->wsFlags |= WHERE_COLUMN_NULL;
  133201. }else if( eOp & (WO_GT|WO_GE) ){
  133202. testcase( eOp & WO_GT );
  133203. testcase( eOp & WO_GE );
  133204. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  133205. pNew->u.btree.nBtm = whereRangeVectorLen(
  133206. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  133207. );
  133208. pBtm = pTerm;
  133209. pTop = 0;
  133210. if( pTerm->wtFlags & TERM_LIKEOPT ){
  133211. /* Range contraints that come from the LIKE optimization are
  133212. ** always used in pairs. */
  133213. pTop = &pTerm[1];
  133214. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  133215. assert( pTop->wtFlags & TERM_LIKEOPT );
  133216. assert( pTop->eOperator==WO_LT );
  133217. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  133218. pNew->aLTerm[pNew->nLTerm++] = pTop;
  133219. pNew->wsFlags |= WHERE_TOP_LIMIT;
  133220. pNew->u.btree.nTop = 1;
  133221. }
  133222. }else{
  133223. assert( eOp & (WO_LT|WO_LE) );
  133224. testcase( eOp & WO_LT );
  133225. testcase( eOp & WO_LE );
  133226. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  133227. pNew->u.btree.nTop = whereRangeVectorLen(
  133228. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  133229. );
  133230. pTop = pTerm;
  133231. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  133232. pNew->aLTerm[pNew->nLTerm-2] : 0;
  133233. }
  133234. /* At this point pNew->nOut is set to the number of rows expected to
  133235. ** be visited by the index scan before considering term pTerm, or the
  133236. ** values of nIn and nInMul. In other words, assuming that all
  133237. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  133238. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  133239. assert( pNew->nOut==saved_nOut );
  133240. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  133241. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  133242. ** data, using some other estimate. */
  133243. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  133244. }else{
  133245. int nEq = ++pNew->u.btree.nEq;
  133246. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  133247. assert( pNew->nOut==saved_nOut );
  133248. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  133249. assert( (eOp & WO_IN) || nIn==0 );
  133250. testcase( eOp & WO_IN );
  133251. pNew->nOut += pTerm->truthProb;
  133252. pNew->nOut -= nIn;
  133253. }else{
  133254. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133255. tRowcnt nOut = 0;
  133256. if( nInMul==0
  133257. && pProbe->nSample
  133258. && pNew->u.btree.nEq<=pProbe->nSampleCol
  133259. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  133260. && OptimizationEnabled(db, SQLITE_Stat34)
  133261. ){
  133262. Expr *pExpr = pTerm->pExpr;
  133263. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  133264. testcase( eOp & WO_EQ );
  133265. testcase( eOp & WO_IS );
  133266. testcase( eOp & WO_ISNULL );
  133267. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  133268. }else{
  133269. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  133270. }
  133271. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  133272. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  133273. if( nOut ){
  133274. pNew->nOut = sqlite3LogEst(nOut);
  133275. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  133276. pNew->nOut -= nIn;
  133277. }
  133278. }
  133279. if( nOut==0 )
  133280. #endif
  133281. {
  133282. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  133283. if( eOp & WO_ISNULL ){
  133284. /* TUNING: If there is no likelihood() value, assume that a
  133285. ** "col IS NULL" expression matches twice as many rows
  133286. ** as (col=?). */
  133287. pNew->nOut += 10;
  133288. }
  133289. }
  133290. }
  133291. }
  133292. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  133293. ** it to pNew->rRun, which is currently set to the cost of the index
  133294. ** seek only. Then, if this is a non-covering index, add the cost of
  133295. ** visiting the rows in the main table. */
  133296. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  133297. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  133298. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  133299. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  133300. }
  133301. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  133302. nOutUnadjusted = pNew->nOut;
  133303. pNew->rRun += nInMul + nIn;
  133304. pNew->nOut += nInMul + nIn;
  133305. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  133306. rc = whereLoopInsert(pBuilder, pNew);
  133307. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  133308. pNew->nOut = saved_nOut;
  133309. }else{
  133310. pNew->nOut = nOutUnadjusted;
  133311. }
  133312. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  133313. && pNew->u.btree.nEq<pProbe->nColumn
  133314. ){
  133315. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  133316. }
  133317. pNew->nOut = saved_nOut;
  133318. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133319. pBuilder->nRecValid = nRecValid;
  133320. #endif
  133321. }
  133322. pNew->prereq = saved_prereq;
  133323. pNew->u.btree.nEq = saved_nEq;
  133324. pNew->u.btree.nBtm = saved_nBtm;
  133325. pNew->u.btree.nTop = saved_nTop;
  133326. pNew->nSkip = saved_nSkip;
  133327. pNew->wsFlags = saved_wsFlags;
  133328. pNew->nOut = saved_nOut;
  133329. pNew->nLTerm = saved_nLTerm;
  133330. /* Consider using a skip-scan if there are no WHERE clause constraints
  133331. ** available for the left-most terms of the index, and if the average
  133332. ** number of repeats in the left-most terms is at least 18.
  133333. **
  133334. ** The magic number 18 is selected on the basis that scanning 17 rows
  133335. ** is almost always quicker than an index seek (even though if the index
  133336. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  133337. ** the code). And, even if it is not, it should not be too much slower.
  133338. ** On the other hand, the extra seeks could end up being significantly
  133339. ** more expensive. */
  133340. assert( 42==sqlite3LogEst(18) );
  133341. if( saved_nEq==saved_nSkip
  133342. && saved_nEq+1<pProbe->nKeyCol
  133343. && pProbe->noSkipScan==0
  133344. && OptimizationEnabled(db, SQLITE_SkipScan)
  133345. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  133346. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  133347. ){
  133348. LogEst nIter;
  133349. pNew->u.btree.nEq++;
  133350. pNew->nSkip++;
  133351. pNew->aLTerm[pNew->nLTerm++] = 0;
  133352. pNew->wsFlags |= WHERE_SKIPSCAN;
  133353. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  133354. pNew->nOut -= nIter;
  133355. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  133356. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  133357. nIter += 5;
  133358. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  133359. pNew->nOut = saved_nOut;
  133360. pNew->u.btree.nEq = saved_nEq;
  133361. pNew->nSkip = saved_nSkip;
  133362. pNew->wsFlags = saved_wsFlags;
  133363. }
  133364. WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
  133365. pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
  133366. return rc;
  133367. }
  133368. /*
  133369. ** Return True if it is possible that pIndex might be useful in
  133370. ** implementing the ORDER BY clause in pBuilder.
  133371. **
  133372. ** Return False if pBuilder does not contain an ORDER BY clause or
  133373. ** if there is no way for pIndex to be useful in implementing that
  133374. ** ORDER BY clause.
  133375. */
  133376. static int indexMightHelpWithOrderBy(
  133377. WhereLoopBuilder *pBuilder,
  133378. Index *pIndex,
  133379. int iCursor
  133380. ){
  133381. ExprList *pOB;
  133382. ExprList *aColExpr;
  133383. int ii, jj;
  133384. if( pIndex->bUnordered ) return 0;
  133385. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  133386. for(ii=0; ii<pOB->nExpr; ii++){
  133387. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  133388. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  133389. if( pExpr->iColumn<0 ) return 1;
  133390. for(jj=0; jj<pIndex->nKeyCol; jj++){
  133391. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  133392. }
  133393. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  133394. for(jj=0; jj<pIndex->nKeyCol; jj++){
  133395. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  133396. if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  133397. return 1;
  133398. }
  133399. }
  133400. }
  133401. }
  133402. return 0;
  133403. }
  133404. /* Check to see if a partial index with pPartIndexWhere can be used
  133405. ** in the current query. Return true if it can be and false if not.
  133406. */
  133407. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  133408. int i;
  133409. WhereTerm *pTerm;
  133410. Parse *pParse = pWC->pWInfo->pParse;
  133411. while( pWhere->op==TK_AND ){
  133412. if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
  133413. pWhere = pWhere->pRight;
  133414. }
  133415. if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
  133416. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  133417. Expr *pExpr = pTerm->pExpr;
  133418. if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  133419. && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
  133420. ){
  133421. return 1;
  133422. }
  133423. }
  133424. return 0;
  133425. }
  133426. /*
  133427. ** Add all WhereLoop objects for a single table of the join where the table
  133428. ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
  133429. ** a b-tree table, not a virtual table.
  133430. **
  133431. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  133432. ** are calculated as follows:
  133433. **
  133434. ** For a full scan, assuming the table (or index) contains nRow rows:
  133435. **
  133436. ** cost = nRow * 3.0 // full-table scan
  133437. ** cost = nRow * K // scan of covering index
  133438. ** cost = nRow * (K+3.0) // scan of non-covering index
  133439. **
  133440. ** where K is a value between 1.1 and 3.0 set based on the relative
  133441. ** estimated average size of the index and table records.
  133442. **
  133443. ** For an index scan, where nVisit is the number of index rows visited
  133444. ** by the scan, and nSeek is the number of seek operations required on
  133445. ** the index b-tree:
  133446. **
  133447. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  133448. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  133449. **
  133450. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  133451. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  133452. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  133453. **
  133454. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  133455. ** of uncertainty. For this reason, scoring is designed to pick plans that
  133456. ** "do the least harm" if the estimates are inaccurate. For example, a
  133457. ** log(nRow) factor is omitted from a non-covering index scan in order to
  133458. ** bias the scoring in favor of using an index, since the worst-case
  133459. ** performance of using an index is far better than the worst-case performance
  133460. ** of a full table scan.
  133461. */
  133462. static int whereLoopAddBtree(
  133463. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  133464. Bitmask mPrereq /* Extra prerequesites for using this table */
  133465. ){
  133466. WhereInfo *pWInfo; /* WHERE analysis context */
  133467. Index *pProbe; /* An index we are evaluating */
  133468. Index sPk; /* A fake index object for the primary key */
  133469. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  133470. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  133471. SrcList *pTabList; /* The FROM clause */
  133472. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  133473. WhereLoop *pNew; /* Template WhereLoop object */
  133474. int rc = SQLITE_OK; /* Return code */
  133475. int iSortIdx = 1; /* Index number */
  133476. int b; /* A boolean value */
  133477. LogEst rSize; /* number of rows in the table */
  133478. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  133479. WhereClause *pWC; /* The parsed WHERE clause */
  133480. Table *pTab; /* Table being queried */
  133481. pNew = pBuilder->pNew;
  133482. pWInfo = pBuilder->pWInfo;
  133483. pTabList = pWInfo->pTabList;
  133484. pSrc = pTabList->a + pNew->iTab;
  133485. pTab = pSrc->pTab;
  133486. pWC = pBuilder->pWC;
  133487. assert( !IsVirtual(pSrc->pTab) );
  133488. if( pSrc->pIBIndex ){
  133489. /* An INDEXED BY clause specifies a particular index to use */
  133490. pProbe = pSrc->pIBIndex;
  133491. }else if( !HasRowid(pTab) ){
  133492. pProbe = pTab->pIndex;
  133493. }else{
  133494. /* There is no INDEXED BY clause. Create a fake Index object in local
  133495. ** variable sPk to represent the rowid primary key index. Make this
  133496. ** fake index the first in a chain of Index objects with all of the real
  133497. ** indices to follow */
  133498. Index *pFirst; /* First of real indices on the table */
  133499. memset(&sPk, 0, sizeof(Index));
  133500. sPk.nKeyCol = 1;
  133501. sPk.nColumn = 1;
  133502. sPk.aiColumn = &aiColumnPk;
  133503. sPk.aiRowLogEst = aiRowEstPk;
  133504. sPk.onError = OE_Replace;
  133505. sPk.pTable = pTab;
  133506. sPk.szIdxRow = pTab->szTabRow;
  133507. aiRowEstPk[0] = pTab->nRowLogEst;
  133508. aiRowEstPk[1] = 0;
  133509. pFirst = pSrc->pTab->pIndex;
  133510. if( pSrc->fg.notIndexed==0 ){
  133511. /* The real indices of the table are only considered if the
  133512. ** NOT INDEXED qualifier is omitted from the FROM clause */
  133513. sPk.pNext = pFirst;
  133514. }
  133515. pProbe = &sPk;
  133516. }
  133517. rSize = pTab->nRowLogEst;
  133518. rLogSize = estLog(rSize);
  133519. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  133520. /* Automatic indexes */
  133521. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  133522. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  133523. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  133524. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  133525. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  133526. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  133527. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  133528. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  133529. ){
  133530. /* Generate auto-index WhereLoops */
  133531. WhereTerm *pTerm;
  133532. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  133533. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  133534. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  133535. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  133536. pNew->u.btree.nEq = 1;
  133537. pNew->nSkip = 0;
  133538. pNew->u.btree.pIndex = 0;
  133539. pNew->nLTerm = 1;
  133540. pNew->aLTerm[0] = pTerm;
  133541. /* TUNING: One-time cost for computing the automatic index is
  133542. ** estimated to be X*N*log2(N) where N is the number of rows in
  133543. ** the table being indexed and where X is 7 (LogEst=28) for normal
  133544. ** tables or 0.5 (LogEst=-10) for views and subqueries. The value
  133545. ** of X is smaller for views and subqueries so that the query planner
  133546. ** will be more aggressive about generating automatic indexes for
  133547. ** those objects, since there is no opportunity to add schema
  133548. ** indexes on subqueries and views. */
  133549. pNew->rSetup = rLogSize + rSize;
  133550. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  133551. pNew->rSetup += 28;
  133552. }else{
  133553. pNew->rSetup -= 10;
  133554. }
  133555. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  133556. if( pNew->rSetup<0 ) pNew->rSetup = 0;
  133557. /* TUNING: Each index lookup yields 20 rows in the table. This
  133558. ** is more than the usual guess of 10 rows, since we have no way
  133559. ** of knowing how selective the index will ultimately be. It would
  133560. ** not be unreasonable to make this value much larger. */
  133561. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  133562. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  133563. pNew->wsFlags = WHERE_AUTO_INDEX;
  133564. pNew->prereq = mPrereq | pTerm->prereqRight;
  133565. rc = whereLoopInsert(pBuilder, pNew);
  133566. }
  133567. }
  133568. }
  133569. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  133570. /* Loop over all indices. If there was an INDEXED BY clause, then only
  133571. ** consider index pProbe. */
  133572. for(; rc==SQLITE_OK && pProbe;
  133573. pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++
  133574. ){
  133575. if( pProbe->pPartIdxWhere!=0
  133576. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  133577. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  133578. continue; /* Partial index inappropriate for this query */
  133579. }
  133580. if( pProbe->bNoQuery ) continue;
  133581. rSize = pProbe->aiRowLogEst[0];
  133582. pNew->u.btree.nEq = 0;
  133583. pNew->u.btree.nBtm = 0;
  133584. pNew->u.btree.nTop = 0;
  133585. pNew->nSkip = 0;
  133586. pNew->nLTerm = 0;
  133587. pNew->iSortIdx = 0;
  133588. pNew->rSetup = 0;
  133589. pNew->prereq = mPrereq;
  133590. pNew->nOut = rSize;
  133591. pNew->u.btree.pIndex = pProbe;
  133592. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  133593. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  133594. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  133595. if( pProbe->tnum<=0 ){
  133596. /* Integer primary key index */
  133597. pNew->wsFlags = WHERE_IPK;
  133598. /* Full table scan */
  133599. pNew->iSortIdx = b ? iSortIdx : 0;
  133600. /* TUNING: Cost of full table scan is (N*3.0). */
  133601. pNew->rRun = rSize + 16;
  133602. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  133603. whereLoopOutputAdjust(pWC, pNew, rSize);
  133604. rc = whereLoopInsert(pBuilder, pNew);
  133605. pNew->nOut = rSize;
  133606. if( rc ) break;
  133607. }else{
  133608. Bitmask m;
  133609. if( pProbe->isCovering ){
  133610. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  133611. m = 0;
  133612. }else{
  133613. m = pSrc->colUsed & pProbe->colNotIdxed;
  133614. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  133615. }
  133616. /* Full scan via index */
  133617. if( b
  133618. || !HasRowid(pTab)
  133619. || pProbe->pPartIdxWhere!=0
  133620. || ( m==0
  133621. && pProbe->bUnordered==0
  133622. && (pProbe->szIdxRow<pTab->szTabRow)
  133623. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  133624. && sqlite3GlobalConfig.bUseCis
  133625. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  133626. )
  133627. ){
  133628. pNew->iSortIdx = b ? iSortIdx : 0;
  133629. /* The cost of visiting the index rows is N*K, where K is
  133630. ** between 1.1 and 3.0, depending on the relative sizes of the
  133631. ** index and table rows. */
  133632. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  133633. if( m!=0 ){
  133634. /* If this is a non-covering index scan, add in the cost of
  133635. ** doing table lookups. The cost will be 3x the number of
  133636. ** lookups. Take into account WHERE clause terms that can be
  133637. ** satisfied using just the index, and that do not require a
  133638. ** table lookup. */
  133639. LogEst nLookup = rSize + 16; /* Base cost: N*3 */
  133640. int ii;
  133641. int iCur = pSrc->iCursor;
  133642. WhereClause *pWC2 = &pWInfo->sWC;
  133643. for(ii=0; ii<pWC2->nTerm; ii++){
  133644. WhereTerm *pTerm = &pWC2->a[ii];
  133645. if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
  133646. break;
  133647. }
  133648. /* pTerm can be evaluated using just the index. So reduce
  133649. ** the expected number of table lookups accordingly */
  133650. if( pTerm->truthProb<=0 ){
  133651. nLookup += pTerm->truthProb;
  133652. }else{
  133653. nLookup--;
  133654. if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
  133655. }
  133656. }
  133657. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
  133658. }
  133659. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  133660. whereLoopOutputAdjust(pWC, pNew, rSize);
  133661. rc = whereLoopInsert(pBuilder, pNew);
  133662. pNew->nOut = rSize;
  133663. if( rc ) break;
  133664. }
  133665. }
  133666. pBuilder->bldFlags = 0;
  133667. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  133668. if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
  133669. /* If a non-unique index is used, or if a prefix of the key for
  133670. ** unique index is used (making the index functionally non-unique)
  133671. ** then the sqlite_stat1 data becomes important for scoring the
  133672. ** plan */
  133673. pTab->tabFlags |= TF_StatsUsed;
  133674. }
  133675. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133676. sqlite3Stat4ProbeFree(pBuilder->pRec);
  133677. pBuilder->nRecValid = 0;
  133678. pBuilder->pRec = 0;
  133679. #endif
  133680. }
  133681. return rc;
  133682. }
  133683. #ifndef SQLITE_OMIT_VIRTUALTABLE
  133684. /*
  133685. ** Argument pIdxInfo is already populated with all constraints that may
  133686. ** be used by the virtual table identified by pBuilder->pNew->iTab. This
  133687. ** function marks a subset of those constraints usable, invokes the
  133688. ** xBestIndex method and adds the returned plan to pBuilder.
  133689. **
  133690. ** A constraint is marked usable if:
  133691. **
  133692. ** * Argument mUsable indicates that its prerequisites are available, and
  133693. **
  133694. ** * It is not one of the operators specified in the mExclude mask passed
  133695. ** as the fourth argument (which in practice is either WO_IN or 0).
  133696. **
  133697. ** Argument mPrereq is a mask of tables that must be scanned before the
  133698. ** virtual table in question. These are added to the plans prerequisites
  133699. ** before it is added to pBuilder.
  133700. **
  133701. ** Output parameter *pbIn is set to true if the plan added to pBuilder
  133702. ** uses one or more WO_IN terms, or false otherwise.
  133703. */
  133704. static int whereLoopAddVirtualOne(
  133705. WhereLoopBuilder *pBuilder,
  133706. Bitmask mPrereq, /* Mask of tables that must be used. */
  133707. Bitmask mUsable, /* Mask of usable tables */
  133708. u16 mExclude, /* Exclude terms using these operators */
  133709. sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
  133710. u16 mNoOmit, /* Do not omit these constraints */
  133711. int *pbIn /* OUT: True if plan uses an IN(...) op */
  133712. ){
  133713. WhereClause *pWC = pBuilder->pWC;
  133714. struct sqlite3_index_constraint *pIdxCons;
  133715. struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
  133716. int i;
  133717. int mxTerm;
  133718. int rc = SQLITE_OK;
  133719. WhereLoop *pNew = pBuilder->pNew;
  133720. Parse *pParse = pBuilder->pWInfo->pParse;
  133721. struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
  133722. int nConstraint = pIdxInfo->nConstraint;
  133723. assert( (mUsable & mPrereq)==mPrereq );
  133724. *pbIn = 0;
  133725. pNew->prereq = mPrereq;
  133726. /* Set the usable flag on the subset of constraints identified by
  133727. ** arguments mUsable and mExclude. */
  133728. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  133729. for(i=0; i<nConstraint; i++, pIdxCons++){
  133730. WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
  133731. pIdxCons->usable = 0;
  133732. if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
  133733. && (pTerm->eOperator & mExclude)==0
  133734. ){
  133735. pIdxCons->usable = 1;
  133736. }
  133737. }
  133738. /* Initialize the output fields of the sqlite3_index_info structure */
  133739. memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
  133740. assert( pIdxInfo->needToFreeIdxStr==0 );
  133741. pIdxInfo->idxStr = 0;
  133742. pIdxInfo->idxNum = 0;
  133743. pIdxInfo->orderByConsumed = 0;
  133744. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  133745. pIdxInfo->estimatedRows = 25;
  133746. pIdxInfo->idxFlags = 0;
  133747. pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
  133748. /* Invoke the virtual table xBestIndex() method */
  133749. rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
  133750. if( rc ){
  133751. if( rc==SQLITE_CONSTRAINT ){
  133752. /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
  133753. ** that the particular combination of parameters provided is unusable.
  133754. ** Make no entries in the loop table.
  133755. */
  133756. WHERETRACE(0xffff, (" ^^^^--- non-viable plan rejected!\n"));
  133757. return SQLITE_OK;
  133758. }
  133759. return rc;
  133760. }
  133761. mxTerm = -1;
  133762. assert( pNew->nLSlot>=nConstraint );
  133763. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  133764. pNew->u.vtab.omitMask = 0;
  133765. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  133766. for(i=0; i<nConstraint; i++, pIdxCons++){
  133767. int iTerm;
  133768. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  133769. WhereTerm *pTerm;
  133770. int j = pIdxCons->iTermOffset;
  133771. if( iTerm>=nConstraint
  133772. || j<0
  133773. || j>=pWC->nTerm
  133774. || pNew->aLTerm[iTerm]!=0
  133775. || pIdxCons->usable==0
  133776. ){
  133777. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  133778. testcase( pIdxInfo->needToFreeIdxStr );
  133779. return SQLITE_ERROR;
  133780. }
  133781. testcase( iTerm==nConstraint-1 );
  133782. testcase( j==0 );
  133783. testcase( j==pWC->nTerm-1 );
  133784. pTerm = &pWC->a[j];
  133785. pNew->prereq |= pTerm->prereqRight;
  133786. assert( iTerm<pNew->nLSlot );
  133787. pNew->aLTerm[iTerm] = pTerm;
  133788. if( iTerm>mxTerm ) mxTerm = iTerm;
  133789. testcase( iTerm==15 );
  133790. testcase( iTerm==16 );
  133791. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  133792. if( (pTerm->eOperator & WO_IN)!=0 ){
  133793. /* A virtual table that is constrained by an IN clause may not
  133794. ** consume the ORDER BY clause because (1) the order of IN terms
  133795. ** is not necessarily related to the order of output terms and
  133796. ** (2) Multiple outputs from a single IN value will not merge
  133797. ** together. */
  133798. pIdxInfo->orderByConsumed = 0;
  133799. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  133800. *pbIn = 1; assert( (mExclude & WO_IN)==0 );
  133801. }
  133802. }
  133803. }
  133804. pNew->u.vtab.omitMask &= ~mNoOmit;
  133805. pNew->nLTerm = mxTerm+1;
  133806. for(i=0; i<=mxTerm; i++){
  133807. if( pNew->aLTerm[i]==0 ){
  133808. /* The non-zero argvIdx values must be contiguous. Raise an
  133809. ** error if they are not */
  133810. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  133811. testcase( pIdxInfo->needToFreeIdxStr );
  133812. return SQLITE_ERROR;
  133813. }
  133814. }
  133815. assert( pNew->nLTerm<=pNew->nLSlot );
  133816. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  133817. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  133818. pIdxInfo->needToFreeIdxStr = 0;
  133819. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  133820. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  133821. pIdxInfo->nOrderBy : 0);
  133822. pNew->rSetup = 0;
  133823. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  133824. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  133825. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  133826. ** that the scan will visit at most one row. Clear it otherwise. */
  133827. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  133828. pNew->wsFlags |= WHERE_ONEROW;
  133829. }else{
  133830. pNew->wsFlags &= ~WHERE_ONEROW;
  133831. }
  133832. rc = whereLoopInsert(pBuilder, pNew);
  133833. if( pNew->u.vtab.needFree ){
  133834. sqlite3_free(pNew->u.vtab.idxStr);
  133835. pNew->u.vtab.needFree = 0;
  133836. }
  133837. WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
  133838. *pbIn, (sqlite3_uint64)mPrereq,
  133839. (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
  133840. return rc;
  133841. }
  133842. /*
  133843. ** If this function is invoked from within an xBestIndex() callback, it
  133844. ** returns a pointer to a buffer containing the name of the collation
  133845. ** sequence associated with element iCons of the sqlite3_index_info.aConstraint
  133846. ** array. Or, if iCons is out of range or there is no active xBestIndex
  133847. ** call, return NULL.
  133848. */
  133849. SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
  133850. HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  133851. const char *zRet = 0;
  133852. if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
  133853. CollSeq *pC = 0;
  133854. int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
  133855. Expr *pX = pHidden->pWC->a[iTerm].pExpr;
  133856. if( pX->pLeft ){
  133857. pC = sqlite3BinaryCompareCollSeq(pHidden->pParse, pX->pLeft, pX->pRight);
  133858. }
  133859. zRet = (pC ? pC->zName : sqlite3StrBINARY);
  133860. }
  133861. return zRet;
  133862. }
  133863. /*
  133864. ** Add all WhereLoop objects for a table of the join identified by
  133865. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  133866. **
  133867. ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
  133868. ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
  133869. ** entries that occur before the virtual table in the FROM clause and are
  133870. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  133871. ** mUnusable mask contains all FROM clause entries that occur after the
  133872. ** virtual table and are separated from it by at least one LEFT or
  133873. ** CROSS JOIN.
  133874. **
  133875. ** For example, if the query were:
  133876. **
  133877. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  133878. **
  133879. ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
  133880. **
  133881. ** All the tables in mPrereq must be scanned before the current virtual
  133882. ** table. So any terms for which all prerequisites are satisfied by
  133883. ** mPrereq may be specified as "usable" in all calls to xBestIndex.
  133884. ** Conversely, all tables in mUnusable must be scanned after the current
  133885. ** virtual table, so any terms for which the prerequisites overlap with
  133886. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  133887. */
  133888. static int whereLoopAddVirtual(
  133889. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  133890. Bitmask mPrereq, /* Tables that must be scanned before this one */
  133891. Bitmask mUnusable /* Tables that must be scanned after this one */
  133892. ){
  133893. int rc = SQLITE_OK; /* Return code */
  133894. WhereInfo *pWInfo; /* WHERE analysis context */
  133895. Parse *pParse; /* The parsing context */
  133896. WhereClause *pWC; /* The WHERE clause */
  133897. struct SrcList_item *pSrc; /* The FROM clause term to search */
  133898. sqlite3_index_info *p; /* Object to pass to xBestIndex() */
  133899. int nConstraint; /* Number of constraints in p */
  133900. int bIn; /* True if plan uses IN(...) operator */
  133901. WhereLoop *pNew;
  133902. Bitmask mBest; /* Tables used by best possible plan */
  133903. u16 mNoOmit;
  133904. assert( (mPrereq & mUnusable)==0 );
  133905. pWInfo = pBuilder->pWInfo;
  133906. pParse = pWInfo->pParse;
  133907. pWC = pBuilder->pWC;
  133908. pNew = pBuilder->pNew;
  133909. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  133910. assert( IsVirtual(pSrc->pTab) );
  133911. p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
  133912. &mNoOmit);
  133913. if( p==0 ) return SQLITE_NOMEM_BKPT;
  133914. pNew->rSetup = 0;
  133915. pNew->wsFlags = WHERE_VIRTUALTABLE;
  133916. pNew->nLTerm = 0;
  133917. pNew->u.vtab.needFree = 0;
  133918. nConstraint = p->nConstraint;
  133919. if( whereLoopResize(pParse->db, pNew, nConstraint) ){
  133920. sqlite3DbFree(pParse->db, p);
  133921. return SQLITE_NOMEM_BKPT;
  133922. }
  133923. /* First call xBestIndex() with all constraints usable. */
  133924. WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
  133925. WHERETRACE(0x40, (" VirtualOne: all usable\n"));
  133926. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
  133927. /* If the call to xBestIndex() with all terms enabled produced a plan
  133928. ** that does not require any source tables (IOW: a plan with mBest==0),
  133929. ** then there is no point in making any further calls to xBestIndex()
  133930. ** since they will all return the same result (if the xBestIndex()
  133931. ** implementation is sane). */
  133932. if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
  133933. int seenZero = 0; /* True if a plan with no prereqs seen */
  133934. int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
  133935. Bitmask mPrev = 0;
  133936. Bitmask mBestNoIn = 0;
  133937. /* If the plan produced by the earlier call uses an IN(...) term, call
  133938. ** xBestIndex again, this time with IN(...) terms disabled. */
  133939. if( bIn ){
  133940. WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
  133941. rc = whereLoopAddVirtualOne(
  133942. pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
  133943. assert( bIn==0 );
  133944. mBestNoIn = pNew->prereq & ~mPrereq;
  133945. if( mBestNoIn==0 ){
  133946. seenZero = 1;
  133947. seenZeroNoIN = 1;
  133948. }
  133949. }
  133950. /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
  133951. ** in the set of terms that apply to the current virtual table. */
  133952. while( rc==SQLITE_OK ){
  133953. int i;
  133954. Bitmask mNext = ALLBITS;
  133955. assert( mNext>0 );
  133956. for(i=0; i<nConstraint; i++){
  133957. Bitmask mThis = (
  133958. pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
  133959. );
  133960. if( mThis>mPrev && mThis<mNext ) mNext = mThis;
  133961. }
  133962. mPrev = mNext;
  133963. if( mNext==ALLBITS ) break;
  133964. if( mNext==mBest || mNext==mBestNoIn ) continue;
  133965. WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
  133966. (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
  133967. rc = whereLoopAddVirtualOne(
  133968. pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
  133969. if( pNew->prereq==mPrereq ){
  133970. seenZero = 1;
  133971. if( bIn==0 ) seenZeroNoIN = 1;
  133972. }
  133973. }
  133974. /* If the calls to xBestIndex() in the above loop did not find a plan
  133975. ** that requires no source tables at all (i.e. one guaranteed to be
  133976. ** usable), make a call here with all source tables disabled */
  133977. if( rc==SQLITE_OK && seenZero==0 ){
  133978. WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
  133979. rc = whereLoopAddVirtualOne(
  133980. pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
  133981. if( bIn==0 ) seenZeroNoIN = 1;
  133982. }
  133983. /* If the calls to xBestIndex() have so far failed to find a plan
  133984. ** that requires no source tables at all and does not use an IN(...)
  133985. ** operator, make a final call to obtain one here. */
  133986. if( rc==SQLITE_OK && seenZeroNoIN==0 ){
  133987. WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
  133988. rc = whereLoopAddVirtualOne(
  133989. pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
  133990. }
  133991. }
  133992. if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
  133993. sqlite3DbFreeNN(pParse->db, p);
  133994. WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
  133995. return rc;
  133996. }
  133997. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  133998. /*
  133999. ** Add WhereLoop entries to handle OR terms. This works for either
  134000. ** btrees or virtual tables.
  134001. */
  134002. static int whereLoopAddOr(
  134003. WhereLoopBuilder *pBuilder,
  134004. Bitmask mPrereq,
  134005. Bitmask mUnusable
  134006. ){
  134007. WhereInfo *pWInfo = pBuilder->pWInfo;
  134008. WhereClause *pWC;
  134009. WhereLoop *pNew;
  134010. WhereTerm *pTerm, *pWCEnd;
  134011. int rc = SQLITE_OK;
  134012. int iCur;
  134013. WhereClause tempWC;
  134014. WhereLoopBuilder sSubBuild;
  134015. WhereOrSet sSum, sCur;
  134016. struct SrcList_item *pItem;
  134017. pWC = pBuilder->pWC;
  134018. pWCEnd = pWC->a + pWC->nTerm;
  134019. pNew = pBuilder->pNew;
  134020. memset(&sSum, 0, sizeof(sSum));
  134021. pItem = pWInfo->pTabList->a + pNew->iTab;
  134022. iCur = pItem->iCursor;
  134023. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  134024. if( (pTerm->eOperator & WO_OR)!=0
  134025. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  134026. ){
  134027. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  134028. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  134029. WhereTerm *pOrTerm;
  134030. int once = 1;
  134031. int i, j;
  134032. sSubBuild = *pBuilder;
  134033. sSubBuild.pOrderBy = 0;
  134034. sSubBuild.pOrSet = &sCur;
  134035. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  134036. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  134037. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  134038. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  134039. }else if( pOrTerm->leftCursor==iCur ){
  134040. tempWC.pWInfo = pWC->pWInfo;
  134041. tempWC.pOuter = pWC;
  134042. tempWC.op = TK_AND;
  134043. tempWC.nTerm = 1;
  134044. tempWC.a = pOrTerm;
  134045. sSubBuild.pWC = &tempWC;
  134046. }else{
  134047. continue;
  134048. }
  134049. sCur.n = 0;
  134050. #ifdef WHERETRACE_ENABLED
  134051. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  134052. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  134053. if( sqlite3WhereTrace & 0x400 ){
  134054. sqlite3WhereClausePrint(sSubBuild.pWC);
  134055. }
  134056. #endif
  134057. #ifndef SQLITE_OMIT_VIRTUALTABLE
  134058. if( IsVirtual(pItem->pTab) ){
  134059. rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
  134060. }else
  134061. #endif
  134062. {
  134063. rc = whereLoopAddBtree(&sSubBuild, mPrereq);
  134064. }
  134065. if( rc==SQLITE_OK ){
  134066. rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
  134067. }
  134068. assert( rc==SQLITE_OK || sCur.n==0 );
  134069. if( sCur.n==0 ){
  134070. sSum.n = 0;
  134071. break;
  134072. }else if( once ){
  134073. whereOrMove(&sSum, &sCur);
  134074. once = 0;
  134075. }else{
  134076. WhereOrSet sPrev;
  134077. whereOrMove(&sPrev, &sSum);
  134078. sSum.n = 0;
  134079. for(i=0; i<sPrev.n; i++){
  134080. for(j=0; j<sCur.n; j++){
  134081. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  134082. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  134083. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  134084. }
  134085. }
  134086. }
  134087. }
  134088. pNew->nLTerm = 1;
  134089. pNew->aLTerm[0] = pTerm;
  134090. pNew->wsFlags = WHERE_MULTI_OR;
  134091. pNew->rSetup = 0;
  134092. pNew->iSortIdx = 0;
  134093. memset(&pNew->u, 0, sizeof(pNew->u));
  134094. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  134095. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  134096. ** of all sub-scans required by the OR-scan. However, due to rounding
  134097. ** errors, it may be that the cost of the OR-scan is equal to its
  134098. ** most expensive sub-scan. Add the smallest possible penalty
  134099. ** (equivalent to multiplying the cost by 1.07) to ensure that
  134100. ** this does not happen. Otherwise, for WHERE clauses such as the
  134101. ** following where there is an index on "y":
  134102. **
  134103. ** WHERE likelihood(x=?, 0.99) OR y=?
  134104. **
  134105. ** the planner may elect to "OR" together a full-table scan and an
  134106. ** index lookup. And other similarly odd results. */
  134107. pNew->rRun = sSum.a[i].rRun + 1;
  134108. pNew->nOut = sSum.a[i].nOut;
  134109. pNew->prereq = sSum.a[i].prereq;
  134110. rc = whereLoopInsert(pBuilder, pNew);
  134111. }
  134112. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  134113. }
  134114. }
  134115. return rc;
  134116. }
  134117. /*
  134118. ** Add all WhereLoop objects for all tables
  134119. */
  134120. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  134121. WhereInfo *pWInfo = pBuilder->pWInfo;
  134122. Bitmask mPrereq = 0;
  134123. Bitmask mPrior = 0;
  134124. int iTab;
  134125. SrcList *pTabList = pWInfo->pTabList;
  134126. struct SrcList_item *pItem;
  134127. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  134128. sqlite3 *db = pWInfo->pParse->db;
  134129. int rc = SQLITE_OK;
  134130. WhereLoop *pNew;
  134131. u8 priorJointype = 0;
  134132. /* Loop over the tables in the join, from left to right */
  134133. pNew = pBuilder->pNew;
  134134. whereLoopInit(pNew);
  134135. pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
  134136. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  134137. Bitmask mUnusable = 0;
  134138. pNew->iTab = iTab;
  134139. pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
  134140. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  134141. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  134142. /* This condition is true when pItem is the FROM clause term on the
  134143. ** right-hand-side of a LEFT or CROSS JOIN. */
  134144. mPrereq = mPrior;
  134145. }
  134146. priorJointype = pItem->fg.jointype;
  134147. #ifndef SQLITE_OMIT_VIRTUALTABLE
  134148. if( IsVirtual(pItem->pTab) ){
  134149. struct SrcList_item *p;
  134150. for(p=&pItem[1]; p<pEnd; p++){
  134151. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  134152. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  134153. }
  134154. }
  134155. rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
  134156. }else
  134157. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  134158. {
  134159. rc = whereLoopAddBtree(pBuilder, mPrereq);
  134160. }
  134161. if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
  134162. rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
  134163. }
  134164. mPrior |= pNew->maskSelf;
  134165. if( rc || db->mallocFailed ){
  134166. if( rc==SQLITE_DONE ){
  134167. /* We hit the query planner search limit set by iPlanLimit */
  134168. sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
  134169. rc = SQLITE_OK;
  134170. }else{
  134171. break;
  134172. }
  134173. }
  134174. }
  134175. whereLoopClear(db, pNew);
  134176. return rc;
  134177. }
  134178. /*
  134179. ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
  134180. ** parameters) to see if it outputs rows in the requested ORDER BY
  134181. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  134182. **
  134183. ** N>0: N terms of the ORDER BY clause are satisfied
  134184. ** N==0: No terms of the ORDER BY clause are satisfied
  134185. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  134186. **
  134187. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  134188. ** strict. With GROUP BY and DISTINCT the only requirement is that
  134189. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  134190. ** and DISTINCT do not require rows to appear in any particular order as long
  134191. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  134192. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  134193. ** pOrderBy terms must be matched in strict left-to-right order.
  134194. */
  134195. static i8 wherePathSatisfiesOrderBy(
  134196. WhereInfo *pWInfo, /* The WHERE clause */
  134197. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  134198. WherePath *pPath, /* The WherePath to check */
  134199. u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
  134200. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  134201. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  134202. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  134203. ){
  134204. u8 revSet; /* True if rev is known */
  134205. u8 rev; /* Composite sort order */
  134206. u8 revIdx; /* Index sort order */
  134207. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  134208. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  134209. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  134210. u16 eqOpMask; /* Allowed equality operators */
  134211. u16 nKeyCol; /* Number of key columns in pIndex */
  134212. u16 nColumn; /* Total number of ordered columns in the index */
  134213. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  134214. int iLoop; /* Index of WhereLoop in pPath being processed */
  134215. int i, j; /* Loop counters */
  134216. int iCur; /* Cursor number for current WhereLoop */
  134217. int iColumn; /* A column number within table iCur */
  134218. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  134219. WhereTerm *pTerm; /* A single term of the WHERE clause */
  134220. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  134221. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  134222. Index *pIndex; /* The index associated with pLoop */
  134223. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  134224. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  134225. Bitmask obDone; /* Mask of all ORDER BY terms */
  134226. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  134227. Bitmask ready; /* Mask of inner loops */
  134228. /*
  134229. ** We say the WhereLoop is "one-row" if it generates no more than one
  134230. ** row of output. A WhereLoop is one-row if all of the following are true:
  134231. ** (a) All index columns match with WHERE_COLUMN_EQ.
  134232. ** (b) The index is unique
  134233. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  134234. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  134235. **
  134236. ** We say the WhereLoop is "order-distinct" if the set of columns from
  134237. ** that WhereLoop that are in the ORDER BY clause are different for every
  134238. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  134239. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  134240. ** is not order-distinct. To be order-distinct is not quite the same as being
  134241. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  134242. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  134243. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  134244. **
  134245. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  134246. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  134247. ** automatically order-distinct.
  134248. */
  134249. assert( pOrderBy!=0 );
  134250. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  134251. nOrderBy = pOrderBy->nExpr;
  134252. testcase( nOrderBy==BMS-1 );
  134253. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  134254. isOrderDistinct = 1;
  134255. obDone = MASKBIT(nOrderBy)-1;
  134256. orderDistinctMask = 0;
  134257. ready = 0;
  134258. eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
  134259. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
  134260. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  134261. if( iLoop>0 ) ready |= pLoop->maskSelf;
  134262. if( iLoop<nLoop ){
  134263. pLoop = pPath->aLoop[iLoop];
  134264. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
  134265. }else{
  134266. pLoop = pLast;
  134267. }
  134268. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  134269. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  134270. break;
  134271. }else{
  134272. pLoop->u.btree.nIdxCol = 0;
  134273. }
  134274. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  134275. /* Mark off any ORDER BY term X that is a column in the table of
  134276. ** the current loop for which there is term in the WHERE
  134277. ** clause of the form X IS NULL or X=? that reference only outer
  134278. ** loops.
  134279. */
  134280. for(i=0; i<nOrderBy; i++){
  134281. if( MASKBIT(i) & obSat ) continue;
  134282. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  134283. if( pOBExpr->op!=TK_COLUMN ) continue;
  134284. if( pOBExpr->iTable!=iCur ) continue;
  134285. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  134286. ~ready, eqOpMask, 0);
  134287. if( pTerm==0 ) continue;
  134288. if( pTerm->eOperator==WO_IN ){
  134289. /* IN terms are only valid for sorting in the ORDER BY LIMIT
  134290. ** optimization, and then only if they are actually used
  134291. ** by the query plan */
  134292. assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
  134293. for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
  134294. if( j>=pLoop->nLTerm ) continue;
  134295. }
  134296. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  134297. if( sqlite3ExprCollSeqMatch(pWInfo->pParse,
  134298. pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){
  134299. continue;
  134300. }
  134301. testcase( pTerm->pExpr->op==TK_IS );
  134302. }
  134303. obSat |= MASKBIT(i);
  134304. }
  134305. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  134306. if( pLoop->wsFlags & WHERE_IPK ){
  134307. pIndex = 0;
  134308. nKeyCol = 0;
  134309. nColumn = 1;
  134310. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  134311. return 0;
  134312. }else{
  134313. nKeyCol = pIndex->nKeyCol;
  134314. nColumn = pIndex->nColumn;
  134315. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  134316. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  134317. || !HasRowid(pIndex->pTable));
  134318. isOrderDistinct = IsUniqueIndex(pIndex);
  134319. }
  134320. /* Loop through all columns of the index and deal with the ones
  134321. ** that are not constrained by == or IN.
  134322. */
  134323. rev = revSet = 0;
  134324. distinctColumns = 0;
  134325. for(j=0; j<nColumn; j++){
  134326. u8 bOnce = 1; /* True to run the ORDER BY search loop */
  134327. assert( j>=pLoop->u.btree.nEq
  134328. || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
  134329. );
  134330. if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
  134331. u16 eOp = pLoop->aLTerm[j]->eOperator;
  134332. /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
  134333. ** doing WHERE_ORDERBY_LIMIT processing).
  134334. **
  134335. ** If the current term is a column of an ((?,?) IN (SELECT...))
  134336. ** expression for which the SELECT returns more than one column,
  134337. ** check that it is the only column used by this loop. Otherwise,
  134338. ** if it is one of two or more, none of the columns can be
  134339. ** considered to match an ORDER BY term. */
  134340. if( (eOp & eqOpMask)!=0 ){
  134341. if( eOp & WO_ISNULL ){
  134342. testcase( isOrderDistinct );
  134343. isOrderDistinct = 0;
  134344. }
  134345. continue;
  134346. }else if( ALWAYS(eOp & WO_IN) ){
  134347. /* ALWAYS() justification: eOp is an equality operator due to the
  134348. ** j<pLoop->u.btree.nEq constraint above. Any equality other
  134349. ** than WO_IN is captured by the previous "if". So this one
  134350. ** always has to be WO_IN. */
  134351. Expr *pX = pLoop->aLTerm[j]->pExpr;
  134352. for(i=j+1; i<pLoop->u.btree.nEq; i++){
  134353. if( pLoop->aLTerm[i]->pExpr==pX ){
  134354. assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
  134355. bOnce = 0;
  134356. break;
  134357. }
  134358. }
  134359. }
  134360. }
  134361. /* Get the column number in the table (iColumn) and sort order
  134362. ** (revIdx) for the j-th column of the index.
  134363. */
  134364. if( pIndex ){
  134365. iColumn = pIndex->aiColumn[j];
  134366. revIdx = pIndex->aSortOrder[j];
  134367. if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
  134368. }else{
  134369. iColumn = XN_ROWID;
  134370. revIdx = 0;
  134371. }
  134372. /* An unconstrained column that might be NULL means that this
  134373. ** WhereLoop is not well-ordered
  134374. */
  134375. if( isOrderDistinct
  134376. && iColumn>=0
  134377. && j>=pLoop->u.btree.nEq
  134378. && pIndex->pTable->aCol[iColumn].notNull==0
  134379. ){
  134380. isOrderDistinct = 0;
  134381. }
  134382. /* Find the ORDER BY term that corresponds to the j-th column
  134383. ** of the index and mark that ORDER BY term off
  134384. */
  134385. isMatch = 0;
  134386. for(i=0; bOnce && i<nOrderBy; i++){
  134387. if( MASKBIT(i) & obSat ) continue;
  134388. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  134389. testcase( wctrlFlags & WHERE_GROUPBY );
  134390. testcase( wctrlFlags & WHERE_DISTINCTBY );
  134391. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  134392. if( iColumn>=XN_ROWID ){
  134393. if( pOBExpr->op!=TK_COLUMN ) continue;
  134394. if( pOBExpr->iTable!=iCur ) continue;
  134395. if( pOBExpr->iColumn!=iColumn ) continue;
  134396. }else{
  134397. Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
  134398. if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
  134399. continue;
  134400. }
  134401. }
  134402. if( iColumn!=XN_ROWID ){
  134403. pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  134404. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  134405. }
  134406. pLoop->u.btree.nIdxCol = j+1;
  134407. isMatch = 1;
  134408. break;
  134409. }
  134410. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  134411. /* Make sure the sort order is compatible in an ORDER BY clause.
  134412. ** Sort order is irrelevant for a GROUP BY clause. */
  134413. if( revSet ){
  134414. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  134415. }else{
  134416. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  134417. if( rev ) *pRevMask |= MASKBIT(iLoop);
  134418. revSet = 1;
  134419. }
  134420. }
  134421. if( isMatch ){
  134422. if( iColumn==XN_ROWID ){
  134423. testcase( distinctColumns==0 );
  134424. distinctColumns = 1;
  134425. }
  134426. obSat |= MASKBIT(i);
  134427. }else{
  134428. /* No match found */
  134429. if( j==0 || j<nKeyCol ){
  134430. testcase( isOrderDistinct!=0 );
  134431. isOrderDistinct = 0;
  134432. }
  134433. break;
  134434. }
  134435. } /* end Loop over all index columns */
  134436. if( distinctColumns ){
  134437. testcase( isOrderDistinct==0 );
  134438. isOrderDistinct = 1;
  134439. }
  134440. } /* end-if not one-row */
  134441. /* Mark off any other ORDER BY terms that reference pLoop */
  134442. if( isOrderDistinct ){
  134443. orderDistinctMask |= pLoop->maskSelf;
  134444. for(i=0; i<nOrderBy; i++){
  134445. Expr *p;
  134446. Bitmask mTerm;
  134447. if( MASKBIT(i) & obSat ) continue;
  134448. p = pOrderBy->a[i].pExpr;
  134449. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  134450. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  134451. if( (mTerm&~orderDistinctMask)==0 ){
  134452. obSat |= MASKBIT(i);
  134453. }
  134454. }
  134455. }
  134456. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  134457. if( obSat==obDone ) return (i8)nOrderBy;
  134458. if( !isOrderDistinct ){
  134459. for(i=nOrderBy-1; i>0; i--){
  134460. Bitmask m = MASKBIT(i) - 1;
  134461. if( (obSat&m)==m ) return i;
  134462. }
  134463. return 0;
  134464. }
  134465. return -1;
  134466. }
  134467. /*
  134468. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  134469. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  134470. ** BY clause - and so any order that groups rows as required satisfies the
  134471. ** request.
  134472. **
  134473. ** Normally, in this case it is not possible for the caller to determine
  134474. ** whether or not the rows are really being delivered in sorted order, or
  134475. ** just in some other order that provides the required grouping. However,
  134476. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  134477. ** this function may be called on the returned WhereInfo object. It returns
  134478. ** true if the rows really will be sorted in the specified order, or false
  134479. ** otherwise.
  134480. **
  134481. ** For example, assuming:
  134482. **
  134483. ** CREATE INDEX i1 ON t1(x, Y);
  134484. **
  134485. ** then
  134486. **
  134487. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  134488. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  134489. */
  134490. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  134491. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  134492. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  134493. return pWInfo->sorted;
  134494. }
  134495. #ifdef WHERETRACE_ENABLED
  134496. /* For debugging use only: */
  134497. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  134498. static char zName[65];
  134499. int i;
  134500. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  134501. if( pLast ) zName[i++] = pLast->cId;
  134502. zName[i] = 0;
  134503. return zName;
  134504. }
  134505. #endif
  134506. /*
  134507. ** Return the cost of sorting nRow rows, assuming that the keys have
  134508. ** nOrderby columns and that the first nSorted columns are already in
  134509. ** order.
  134510. */
  134511. static LogEst whereSortingCost(
  134512. WhereInfo *pWInfo,
  134513. LogEst nRow,
  134514. int nOrderBy,
  134515. int nSorted
  134516. ){
  134517. /* TUNING: Estimated cost of a full external sort, where N is
  134518. ** the number of rows to sort is:
  134519. **
  134520. ** cost = (3.0 * N * log(N)).
  134521. **
  134522. ** Or, if the order-by clause has X terms but only the last Y
  134523. ** terms are out of order, then block-sorting will reduce the
  134524. ** sorting cost to:
  134525. **
  134526. ** cost = (3.0 * N * log(N)) * (Y/X)
  134527. **
  134528. ** The (Y/X) term is implemented using stack variable rScale
  134529. ** below. */
  134530. LogEst rScale, rSortCost;
  134531. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  134532. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  134533. rSortCost = nRow + rScale + 16;
  134534. /* Multiple by log(M) where M is the number of output rows.
  134535. ** Use the LIMIT for M if it is smaller */
  134536. if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
  134537. nRow = pWInfo->iLimit;
  134538. }
  134539. rSortCost += estLog(nRow);
  134540. return rSortCost;
  134541. }
  134542. /*
  134543. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  134544. ** attempts to find the lowest cost path that visits each WhereLoop
  134545. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  134546. **
  134547. ** Assume that the total number of output rows that will need to be sorted
  134548. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  134549. ** costs if nRowEst==0.
  134550. **
  134551. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  134552. ** error occurs.
  134553. */
  134554. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  134555. int mxChoice; /* Maximum number of simultaneous paths tracked */
  134556. int nLoop; /* Number of terms in the join */
  134557. Parse *pParse; /* Parsing context */
  134558. sqlite3 *db; /* The database connection */
  134559. int iLoop; /* Loop counter over the terms of the join */
  134560. int ii, jj; /* Loop counters */
  134561. int mxI = 0; /* Index of next entry to replace */
  134562. int nOrderBy; /* Number of ORDER BY clause terms */
  134563. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  134564. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  134565. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  134566. WherePath *aFrom; /* All nFrom paths at the previous level */
  134567. WherePath *aTo; /* The nTo best paths at the current level */
  134568. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  134569. WherePath *pTo; /* An element of aTo[] that we are working on */
  134570. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  134571. WhereLoop **pX; /* Used to divy up the pSpace memory */
  134572. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  134573. char *pSpace; /* Temporary memory used by this routine */
  134574. int nSpace; /* Bytes of space allocated at pSpace */
  134575. pParse = pWInfo->pParse;
  134576. db = pParse->db;
  134577. nLoop = pWInfo->nLevel;
  134578. /* TUNING: For simple queries, only the best path is tracked.
  134579. ** For 2-way joins, the 5 best paths are followed.
  134580. ** For joins of 3 or more tables, track the 10 best paths */
  134581. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  134582. assert( nLoop<=pWInfo->pTabList->nSrc );
  134583. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  134584. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  134585. ** case the purpose of this call is to estimate the number of rows returned
  134586. ** by the overall query. Once this estimate has been obtained, the caller
  134587. ** will invoke this function a second time, passing the estimate as the
  134588. ** nRowEst parameter. */
  134589. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  134590. nOrderBy = 0;
  134591. }else{
  134592. nOrderBy = pWInfo->pOrderBy->nExpr;
  134593. }
  134594. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  134595. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  134596. nSpace += sizeof(LogEst) * nOrderBy;
  134597. pSpace = sqlite3DbMallocRawNN(db, nSpace);
  134598. if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
  134599. aTo = (WherePath*)pSpace;
  134600. aFrom = aTo+mxChoice;
  134601. memset(aFrom, 0, sizeof(aFrom[0]));
  134602. pX = (WhereLoop**)(aFrom+mxChoice);
  134603. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  134604. pFrom->aLoop = pX;
  134605. }
  134606. if( nOrderBy ){
  134607. /* If there is an ORDER BY clause and it is not being ignored, set up
  134608. ** space for the aSortCost[] array. Each element of the aSortCost array
  134609. ** is either zero - meaning it has not yet been initialized - or the
  134610. ** cost of sorting nRowEst rows of data where the first X terms of
  134611. ** the ORDER BY clause are already in order, where X is the array
  134612. ** index. */
  134613. aSortCost = (LogEst*)pX;
  134614. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  134615. }
  134616. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  134617. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  134618. /* Seed the search with a single WherePath containing zero WhereLoops.
  134619. **
  134620. ** TUNING: Do not let the number of iterations go above 28. If the cost
  134621. ** of computing an automatic index is not paid back within the first 28
  134622. ** rows, then do not use the automatic index. */
  134623. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  134624. nFrom = 1;
  134625. assert( aFrom[0].isOrdered==0 );
  134626. if( nOrderBy ){
  134627. /* If nLoop is zero, then there are no FROM terms in the query. Since
  134628. ** in this case the query may return a maximum of one row, the results
  134629. ** are already in the requested order. Set isOrdered to nOrderBy to
  134630. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  134631. ** -1, indicating that the result set may or may not be ordered,
  134632. ** depending on the loops added to the current plan. */
  134633. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  134634. }
  134635. /* Compute successively longer WherePaths using the previous generation
  134636. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  134637. ** best paths at each generation */
  134638. for(iLoop=0; iLoop<nLoop; iLoop++){
  134639. nTo = 0;
  134640. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  134641. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  134642. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  134643. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  134644. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  134645. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  134646. Bitmask maskNew; /* Mask of src visited by (..) */
  134647. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  134648. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  134649. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  134650. if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
  134651. /* Do not use an automatic index if the this loop is expected
  134652. ** to run less than 1.25 times. It is tempting to also exclude
  134653. ** automatic index usage on an outer loop, but sometimes an automatic
  134654. ** index is useful in the outer loop of a correlated subquery. */
  134655. assert( 10==sqlite3LogEst(2) );
  134656. continue;
  134657. }
  134658. /* At this point, pWLoop is a candidate to be the next loop.
  134659. ** Compute its cost */
  134660. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  134661. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  134662. nOut = pFrom->nRow + pWLoop->nOut;
  134663. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  134664. if( isOrdered<0 ){
  134665. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  134666. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  134667. iLoop, pWLoop, &revMask);
  134668. }else{
  134669. revMask = pFrom->revLoop;
  134670. }
  134671. if( isOrdered>=0 && isOrdered<nOrderBy ){
  134672. if( aSortCost[isOrdered]==0 ){
  134673. aSortCost[isOrdered] = whereSortingCost(
  134674. pWInfo, nRowEst, nOrderBy, isOrdered
  134675. );
  134676. }
  134677. /* TUNING: Add a small extra penalty (5) to sorting as an
  134678. ** extra encouragment to the query planner to select a plan
  134679. ** where the rows emerge in the correct order without any sorting
  134680. ** required. */
  134681. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 5;
  134682. WHERETRACE(0x002,
  134683. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  134684. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  134685. rUnsorted, rCost));
  134686. }else{
  134687. rCost = rUnsorted;
  134688. rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
  134689. }
  134690. /* Check to see if pWLoop should be added to the set of
  134691. ** mxChoice best-so-far paths.
  134692. **
  134693. ** First look for an existing path among best-so-far paths
  134694. ** that covers the same set of loops and has the same isOrdered
  134695. ** setting as the current path candidate.
  134696. **
  134697. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  134698. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  134699. ** of legal values for isOrdered, -1..64.
  134700. */
  134701. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  134702. if( pTo->maskLoop==maskNew
  134703. && ((pTo->isOrdered^isOrdered)&0x80)==0
  134704. ){
  134705. testcase( jj==nTo-1 );
  134706. break;
  134707. }
  134708. }
  134709. if( jj>=nTo ){
  134710. /* None of the existing best-so-far paths match the candidate. */
  134711. if( nTo>=mxChoice
  134712. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  134713. ){
  134714. /* The current candidate is no better than any of the mxChoice
  134715. ** paths currently in the best-so-far buffer. So discard
  134716. ** this candidate as not viable. */
  134717. #ifdef WHERETRACE_ENABLED /* 0x4 */
  134718. if( sqlite3WhereTrace&0x4 ){
  134719. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
  134720. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  134721. isOrdered>=0 ? isOrdered+'0' : '?');
  134722. }
  134723. #endif
  134724. continue;
  134725. }
  134726. /* If we reach this points it means that the new candidate path
  134727. ** needs to be added to the set of best-so-far paths. */
  134728. if( nTo<mxChoice ){
  134729. /* Increase the size of the aTo set by one */
  134730. jj = nTo++;
  134731. }else{
  134732. /* New path replaces the prior worst to keep count below mxChoice */
  134733. jj = mxI;
  134734. }
  134735. pTo = &aTo[jj];
  134736. #ifdef WHERETRACE_ENABLED /* 0x4 */
  134737. if( sqlite3WhereTrace&0x4 ){
  134738. sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
  134739. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  134740. isOrdered>=0 ? isOrdered+'0' : '?');
  134741. }
  134742. #endif
  134743. }else{
  134744. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  134745. ** same set of loops and has the same isOrdered setting as the
  134746. ** candidate path. Check to see if the candidate should replace
  134747. ** pTo or if the candidate should be skipped.
  134748. **
  134749. ** The conditional is an expanded vector comparison equivalent to:
  134750. ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
  134751. */
  134752. if( pTo->rCost<rCost
  134753. || (pTo->rCost==rCost
  134754. && (pTo->nRow<nOut
  134755. || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
  134756. )
  134757. )
  134758. ){
  134759. #ifdef WHERETRACE_ENABLED /* 0x4 */
  134760. if( sqlite3WhereTrace&0x4 ){
  134761. sqlite3DebugPrintf(
  134762. "Skip %s cost=%-3d,%3d,%3d order=%c",
  134763. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  134764. isOrdered>=0 ? isOrdered+'0' : '?');
  134765. sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
  134766. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  134767. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  134768. }
  134769. #endif
  134770. /* Discard the candidate path from further consideration */
  134771. testcase( pTo->rCost==rCost );
  134772. continue;
  134773. }
  134774. testcase( pTo->rCost==rCost+1 );
  134775. /* Control reaches here if the candidate path is better than the
  134776. ** pTo path. Replace pTo with the candidate. */
  134777. #ifdef WHERETRACE_ENABLED /* 0x4 */
  134778. if( sqlite3WhereTrace&0x4 ){
  134779. sqlite3DebugPrintf(
  134780. "Update %s cost=%-3d,%3d,%3d order=%c",
  134781. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  134782. isOrdered>=0 ? isOrdered+'0' : '?');
  134783. sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
  134784. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  134785. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  134786. }
  134787. #endif
  134788. }
  134789. /* pWLoop is a winner. Add it to the set of best so far */
  134790. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  134791. pTo->revLoop = revMask;
  134792. pTo->nRow = nOut;
  134793. pTo->rCost = rCost;
  134794. pTo->rUnsorted = rUnsorted;
  134795. pTo->isOrdered = isOrdered;
  134796. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  134797. pTo->aLoop[iLoop] = pWLoop;
  134798. if( nTo>=mxChoice ){
  134799. mxI = 0;
  134800. mxCost = aTo[0].rCost;
  134801. mxUnsorted = aTo[0].nRow;
  134802. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  134803. if( pTo->rCost>mxCost
  134804. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  134805. ){
  134806. mxCost = pTo->rCost;
  134807. mxUnsorted = pTo->rUnsorted;
  134808. mxI = jj;
  134809. }
  134810. }
  134811. }
  134812. }
  134813. }
  134814. #ifdef WHERETRACE_ENABLED /* >=2 */
  134815. if( sqlite3WhereTrace & 0x02 ){
  134816. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  134817. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  134818. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  134819. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  134820. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  134821. if( pTo->isOrdered>0 ){
  134822. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  134823. }else{
  134824. sqlite3DebugPrintf("\n");
  134825. }
  134826. }
  134827. }
  134828. #endif
  134829. /* Swap the roles of aFrom and aTo for the next generation */
  134830. pFrom = aTo;
  134831. aTo = aFrom;
  134832. aFrom = pFrom;
  134833. nFrom = nTo;
  134834. }
  134835. if( nFrom==0 ){
  134836. sqlite3ErrorMsg(pParse, "no query solution");
  134837. sqlite3DbFreeNN(db, pSpace);
  134838. return SQLITE_ERROR;
  134839. }
  134840. /* Find the lowest cost path. pFrom will be left pointing to that path */
  134841. pFrom = aFrom;
  134842. for(ii=1; ii<nFrom; ii++){
  134843. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  134844. }
  134845. assert( pWInfo->nLevel==nLoop );
  134846. /* Load the lowest cost path into pWInfo */
  134847. for(iLoop=0; iLoop<nLoop; iLoop++){
  134848. WhereLevel *pLevel = pWInfo->a + iLoop;
  134849. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  134850. pLevel->iFrom = pWLoop->iTab;
  134851. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  134852. }
  134853. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  134854. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  134855. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  134856. && nRowEst
  134857. ){
  134858. Bitmask notUsed;
  134859. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  134860. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  134861. if( rc==pWInfo->pResultSet->nExpr ){
  134862. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  134863. }
  134864. }
  134865. pWInfo->bOrderedInnerLoop = 0;
  134866. if( pWInfo->pOrderBy ){
  134867. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  134868. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  134869. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  134870. }
  134871. }else{
  134872. pWInfo->nOBSat = pFrom->isOrdered;
  134873. pWInfo->revMask = pFrom->revLoop;
  134874. if( pWInfo->nOBSat<=0 ){
  134875. pWInfo->nOBSat = 0;
  134876. if( nLoop>0 ){
  134877. u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
  134878. if( (wsFlags & WHERE_ONEROW)==0
  134879. && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
  134880. ){
  134881. Bitmask m = 0;
  134882. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
  134883. WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
  134884. testcase( wsFlags & WHERE_IPK );
  134885. testcase( wsFlags & WHERE_COLUMN_IN );
  134886. if( rc==pWInfo->pOrderBy->nExpr ){
  134887. pWInfo->bOrderedInnerLoop = 1;
  134888. pWInfo->revMask = m;
  134889. }
  134890. }
  134891. }
  134892. }
  134893. }
  134894. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  134895. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  134896. ){
  134897. Bitmask revMask = 0;
  134898. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  134899. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  134900. );
  134901. assert( pWInfo->sorted==0 );
  134902. if( nOrder==pWInfo->pOrderBy->nExpr ){
  134903. pWInfo->sorted = 1;
  134904. pWInfo->revMask = revMask;
  134905. }
  134906. }
  134907. }
  134908. pWInfo->nRowOut = pFrom->nRow;
  134909. /* Free temporary memory and return success */
  134910. sqlite3DbFreeNN(db, pSpace);
  134911. return SQLITE_OK;
  134912. }
  134913. /*
  134914. ** Most queries use only a single table (they are not joins) and have
  134915. ** simple == constraints against indexed fields. This routine attempts
  134916. ** to plan those simple cases using much less ceremony than the
  134917. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  134918. ** times for the common case.
  134919. **
  134920. ** Return non-zero on success, if this query can be handled by this
  134921. ** no-frills query planner. Return zero if this query needs the
  134922. ** general-purpose query planner.
  134923. */
  134924. static int whereShortCut(WhereLoopBuilder *pBuilder){
  134925. WhereInfo *pWInfo;
  134926. struct SrcList_item *pItem;
  134927. WhereClause *pWC;
  134928. WhereTerm *pTerm;
  134929. WhereLoop *pLoop;
  134930. int iCur;
  134931. int j;
  134932. Table *pTab;
  134933. Index *pIdx;
  134934. pWInfo = pBuilder->pWInfo;
  134935. if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
  134936. assert( pWInfo->pTabList->nSrc>=1 );
  134937. pItem = pWInfo->pTabList->a;
  134938. pTab = pItem->pTab;
  134939. if( IsVirtual(pTab) ) return 0;
  134940. if( pItem->fg.isIndexedBy ) return 0;
  134941. iCur = pItem->iCursor;
  134942. pWC = &pWInfo->sWC;
  134943. pLoop = pBuilder->pNew;
  134944. pLoop->wsFlags = 0;
  134945. pLoop->nSkip = 0;
  134946. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  134947. if( pTerm ){
  134948. testcase( pTerm->eOperator & WO_IS );
  134949. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  134950. pLoop->aLTerm[0] = pTerm;
  134951. pLoop->nLTerm = 1;
  134952. pLoop->u.btree.nEq = 1;
  134953. /* TUNING: Cost of a rowid lookup is 10 */
  134954. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  134955. }else{
  134956. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  134957. int opMask;
  134958. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  134959. if( !IsUniqueIndex(pIdx)
  134960. || pIdx->pPartIdxWhere!=0
  134961. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  134962. ) continue;
  134963. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  134964. for(j=0; j<pIdx->nKeyCol; j++){
  134965. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  134966. if( pTerm==0 ) break;
  134967. testcase( pTerm->eOperator & WO_IS );
  134968. pLoop->aLTerm[j] = pTerm;
  134969. }
  134970. if( j!=pIdx->nKeyCol ) continue;
  134971. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  134972. if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
  134973. pLoop->wsFlags |= WHERE_IDX_ONLY;
  134974. }
  134975. pLoop->nLTerm = j;
  134976. pLoop->u.btree.nEq = j;
  134977. pLoop->u.btree.pIndex = pIdx;
  134978. /* TUNING: Cost of a unique index lookup is 15 */
  134979. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  134980. break;
  134981. }
  134982. }
  134983. if( pLoop->wsFlags ){
  134984. pLoop->nOut = (LogEst)1;
  134985. pWInfo->a[0].pWLoop = pLoop;
  134986. assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
  134987. pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
  134988. pWInfo->a[0].iTabCur = iCur;
  134989. pWInfo->nRowOut = 1;
  134990. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  134991. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  134992. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  134993. }
  134994. #ifdef SQLITE_DEBUG
  134995. pLoop->cId = '0';
  134996. #endif
  134997. return 1;
  134998. }
  134999. return 0;
  135000. }
  135001. /*
  135002. ** Helper function for exprIsDeterministic().
  135003. */
  135004. static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
  135005. if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
  135006. pWalker->eCode = 0;
  135007. return WRC_Abort;
  135008. }
  135009. return WRC_Continue;
  135010. }
  135011. /*
  135012. ** Return true if the expression contains no non-deterministic SQL
  135013. ** functions. Do not consider non-deterministic SQL functions that are
  135014. ** part of sub-select statements.
  135015. */
  135016. static int exprIsDeterministic(Expr *p){
  135017. Walker w;
  135018. memset(&w, 0, sizeof(w));
  135019. w.eCode = 1;
  135020. w.xExprCallback = exprNodeIsDeterministic;
  135021. w.xSelectCallback = sqlite3SelectWalkFail;
  135022. sqlite3WalkExpr(&w, p);
  135023. return w.eCode;
  135024. }
  135025. /*
  135026. ** Generate the beginning of the loop used for WHERE clause processing.
  135027. ** The return value is a pointer to an opaque structure that contains
  135028. ** information needed to terminate the loop. Later, the calling routine
  135029. ** should invoke sqlite3WhereEnd() with the return value of this function
  135030. ** in order to complete the WHERE clause processing.
  135031. **
  135032. ** If an error occurs, this routine returns NULL.
  135033. **
  135034. ** The basic idea is to do a nested loop, one loop for each table in
  135035. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  135036. ** same as a SELECT with only a single table in the FROM clause.) For
  135037. ** example, if the SQL is this:
  135038. **
  135039. ** SELECT * FROM t1, t2, t3 WHERE ...;
  135040. **
  135041. ** Then the code generated is conceptually like the following:
  135042. **
  135043. ** foreach row1 in t1 do \ Code generated
  135044. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  135045. ** foreach row3 in t3 do /
  135046. ** ...
  135047. ** end \ Code generated
  135048. ** end |-- by sqlite3WhereEnd()
  135049. ** end /
  135050. **
  135051. ** Note that the loops might not be nested in the order in which they
  135052. ** appear in the FROM clause if a different order is better able to make
  135053. ** use of indices. Note also that when the IN operator appears in
  135054. ** the WHERE clause, it might result in additional nested loops for
  135055. ** scanning through all values on the right-hand side of the IN.
  135056. **
  135057. ** There are Btree cursors associated with each table. t1 uses cursor
  135058. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  135059. ** And so forth. This routine generates code to open those VDBE cursors
  135060. ** and sqlite3WhereEnd() generates the code to close them.
  135061. **
  135062. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  135063. ** in pTabList pointing at their appropriate entries. The [...] code
  135064. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  135065. ** data from the various tables of the loop.
  135066. **
  135067. ** If the WHERE clause is empty, the foreach loops must each scan their
  135068. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  135069. ** the tables have indices and there are terms in the WHERE clause that
  135070. ** refer to those indices, a complete table scan can be avoided and the
  135071. ** code will run much faster. Most of the work of this routine is checking
  135072. ** to see if there are indices that can be used to speed up the loop.
  135073. **
  135074. ** Terms of the WHERE clause are also used to limit which rows actually
  135075. ** make it to the "..." in the middle of the loop. After each "foreach",
  135076. ** terms of the WHERE clause that use only terms in that loop and outer
  135077. ** loops are evaluated and if false a jump is made around all subsequent
  135078. ** inner loops (or around the "..." if the test occurs within the inner-
  135079. ** most loop)
  135080. **
  135081. ** OUTER JOINS
  135082. **
  135083. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  135084. **
  135085. ** foreach row1 in t1 do
  135086. ** flag = 0
  135087. ** foreach row2 in t2 do
  135088. ** start:
  135089. ** ...
  135090. ** flag = 1
  135091. ** end
  135092. ** if flag==0 then
  135093. ** move the row2 cursor to a null row
  135094. ** goto start
  135095. ** fi
  135096. ** end
  135097. **
  135098. ** ORDER BY CLAUSE PROCESSING
  135099. **
  135100. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  135101. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  135102. ** if there is one. If there is no ORDER BY clause or if this routine
  135103. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  135104. **
  135105. ** The iIdxCur parameter is the cursor number of an index. If
  135106. ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
  135107. ** to use for OR clause processing. The WHERE clause should use this
  135108. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  135109. ** the first cursor in an array of cursors for all indices. iIdxCur should
  135110. ** be used to compute the appropriate cursor depending on which index is
  135111. ** used.
  135112. */
  135113. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  135114. Parse *pParse, /* The parser context */
  135115. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  135116. Expr *pWhere, /* The WHERE clause */
  135117. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  135118. ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
  135119. u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
  135120. int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
  135121. ** If WHERE_USE_LIMIT, then the limit amount */
  135122. ){
  135123. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  135124. int nTabList; /* Number of elements in pTabList */
  135125. WhereInfo *pWInfo; /* Will become the return value of this function */
  135126. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  135127. Bitmask notReady; /* Cursors that are not yet positioned */
  135128. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  135129. WhereMaskSet *pMaskSet; /* The expression mask set */
  135130. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  135131. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  135132. int ii; /* Loop counter */
  135133. sqlite3 *db; /* Database connection */
  135134. int rc; /* Return code */
  135135. u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
  135136. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  135137. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  135138. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  135139. ));
  135140. /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
  135141. assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  135142. || (wctrlFlags & WHERE_USE_LIMIT)==0 );
  135143. /* Variable initialization */
  135144. db = pParse->db;
  135145. memset(&sWLB, 0, sizeof(sWLB));
  135146. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  135147. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  135148. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  135149. sWLB.pOrderBy = pOrderBy;
  135150. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  135151. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  135152. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  135153. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  135154. }
  135155. /* The number of tables in the FROM clause is limited by the number of
  135156. ** bits in a Bitmask
  135157. */
  135158. testcase( pTabList->nSrc==BMS );
  135159. if( pTabList->nSrc>BMS ){
  135160. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  135161. return 0;
  135162. }
  135163. /* This function normally generates a nested loop for all tables in
  135164. ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
  135165. ** only generate code for the first table in pTabList and assume that
  135166. ** any cursors associated with subsequent tables are uninitialized.
  135167. */
  135168. nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
  135169. /* Allocate and initialize the WhereInfo structure that will become the
  135170. ** return value. A single allocation is used to store the WhereInfo
  135171. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  135172. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  135173. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  135174. ** some architectures. Hence the ROUND8() below.
  135175. */
  135176. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  135177. pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
  135178. if( db->mallocFailed ){
  135179. sqlite3DbFree(db, pWInfo);
  135180. pWInfo = 0;
  135181. goto whereBeginError;
  135182. }
  135183. pWInfo->pParse = pParse;
  135184. pWInfo->pTabList = pTabList;
  135185. pWInfo->pOrderBy = pOrderBy;
  135186. pWInfo->pWhere = pWhere;
  135187. pWInfo->pResultSet = pResultSet;
  135188. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  135189. pWInfo->nLevel = nTabList;
  135190. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  135191. pWInfo->wctrlFlags = wctrlFlags;
  135192. pWInfo->iLimit = iAuxArg;
  135193. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  135194. memset(&pWInfo->nOBSat, 0,
  135195. offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
  135196. memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
  135197. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  135198. pMaskSet = &pWInfo->sMaskSet;
  135199. sWLB.pWInfo = pWInfo;
  135200. sWLB.pWC = &pWInfo->sWC;
  135201. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  135202. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  135203. whereLoopInit(sWLB.pNew);
  135204. #ifdef SQLITE_DEBUG
  135205. sWLB.pNew->cId = '*';
  135206. #endif
  135207. /* Split the WHERE clause into separate subexpressions where each
  135208. ** subexpression is separated by an AND operator.
  135209. */
  135210. initMaskSet(pMaskSet);
  135211. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  135212. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  135213. /* Special case: No FROM clause
  135214. */
  135215. if( nTabList==0 ){
  135216. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  135217. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  135218. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  135219. }
  135220. ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
  135221. }else{
  135222. /* Assign a bit from the bitmask to every term in the FROM clause.
  135223. **
  135224. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  135225. **
  135226. ** The rule of the previous sentence ensures thta if X is the bitmask for
  135227. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  135228. ** Knowing the bitmask for all tables to the left of a left join is
  135229. ** important. Ticket #3015.
  135230. **
  135231. ** Note that bitmasks are created for all pTabList->nSrc tables in
  135232. ** pTabList, not just the first nTabList tables. nTabList is normally
  135233. ** equal to pTabList->nSrc but might be shortened to 1 if the
  135234. ** WHERE_OR_SUBCLAUSE flag is set.
  135235. */
  135236. ii = 0;
  135237. do{
  135238. createMask(pMaskSet, pTabList->a[ii].iCursor);
  135239. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  135240. }while( (++ii)<pTabList->nSrc );
  135241. #ifdef SQLITE_DEBUG
  135242. {
  135243. Bitmask mx = 0;
  135244. for(ii=0; ii<pTabList->nSrc; ii++){
  135245. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  135246. assert( m>=mx );
  135247. mx = m;
  135248. }
  135249. }
  135250. #endif
  135251. }
  135252. /* Analyze all of the subexpressions. */
  135253. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  135254. if( db->mallocFailed ) goto whereBeginError;
  135255. /* Special case: WHERE terms that do not refer to any tables in the join
  135256. ** (constant expressions). Evaluate each such term, and jump over all the
  135257. ** generated code if the result is not true.
  135258. **
  135259. ** Do not do this if the expression contains non-deterministic functions
  135260. ** that are not within a sub-select. This is not strictly required, but
  135261. ** preserves SQLite's legacy behaviour in the following two cases:
  135262. **
  135263. ** FROM ... WHERE random()>0; -- eval random() once per row
  135264. ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall
  135265. */
  135266. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  135267. WhereTerm *pT = &sWLB.pWC->a[ii];
  135268. if( pT->wtFlags & TERM_VIRTUAL ) continue;
  135269. if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
  135270. sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  135271. pT->wtFlags |= TERM_CODED;
  135272. }
  135273. }
  135274. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  135275. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  135276. /* The DISTINCT marking is pointless. Ignore it. */
  135277. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  135278. }else if( pOrderBy==0 ){
  135279. /* Try to ORDER BY the result set to make distinct processing easier */
  135280. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  135281. pWInfo->pOrderBy = pResultSet;
  135282. }
  135283. }
  135284. /* Construct the WhereLoop objects */
  135285. #if defined(WHERETRACE_ENABLED)
  135286. if( sqlite3WhereTrace & 0xffff ){
  135287. sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
  135288. if( wctrlFlags & WHERE_USE_LIMIT ){
  135289. sqlite3DebugPrintf(", limit: %d", iAuxArg);
  135290. }
  135291. sqlite3DebugPrintf(")\n");
  135292. }
  135293. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  135294. sqlite3WhereClausePrint(sWLB.pWC);
  135295. }
  135296. #endif
  135297. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  135298. rc = whereLoopAddAll(&sWLB);
  135299. if( rc ) goto whereBeginError;
  135300. #ifdef WHERETRACE_ENABLED
  135301. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  135302. WhereLoop *p;
  135303. int i;
  135304. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  135305. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  135306. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  135307. p->cId = zLabel[i%(sizeof(zLabel)-1)];
  135308. whereLoopPrint(p, sWLB.pWC);
  135309. }
  135310. }
  135311. #endif
  135312. wherePathSolver(pWInfo, 0);
  135313. if( db->mallocFailed ) goto whereBeginError;
  135314. if( pWInfo->pOrderBy ){
  135315. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  135316. if( db->mallocFailed ) goto whereBeginError;
  135317. }
  135318. }
  135319. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  135320. pWInfo->revMask = ALLBITS;
  135321. }
  135322. if( pParse->nErr || NEVER(db->mallocFailed) ){
  135323. goto whereBeginError;
  135324. }
  135325. #ifdef WHERETRACE_ENABLED
  135326. if( sqlite3WhereTrace ){
  135327. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  135328. if( pWInfo->nOBSat>0 ){
  135329. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  135330. }
  135331. switch( pWInfo->eDistinct ){
  135332. case WHERE_DISTINCT_UNIQUE: {
  135333. sqlite3DebugPrintf(" DISTINCT=unique");
  135334. break;
  135335. }
  135336. case WHERE_DISTINCT_ORDERED: {
  135337. sqlite3DebugPrintf(" DISTINCT=ordered");
  135338. break;
  135339. }
  135340. case WHERE_DISTINCT_UNORDERED: {
  135341. sqlite3DebugPrintf(" DISTINCT=unordered");
  135342. break;
  135343. }
  135344. }
  135345. sqlite3DebugPrintf("\n");
  135346. for(ii=0; ii<pWInfo->nLevel; ii++){
  135347. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  135348. }
  135349. }
  135350. #endif
  135351. /* Attempt to omit tables from the join that do not affect the result.
  135352. ** For a table to not affect the result, the following must be true:
  135353. **
  135354. ** 1) The query must not be an aggregate.
  135355. ** 2) The table must be the RHS of a LEFT JOIN.
  135356. ** 3) Either the query must be DISTINCT, or else the ON or USING clause
  135357. ** must contain a constraint that limits the scan of the table to
  135358. ** at most a single row.
  135359. ** 4) The table must not be referenced by any part of the query apart
  135360. ** from its own USING or ON clause.
  135361. **
  135362. ** For example, given:
  135363. **
  135364. ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
  135365. ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
  135366. ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
  135367. **
  135368. ** then table t2 can be omitted from the following:
  135369. **
  135370. ** SELECT v1, v3 FROM t1
  135371. ** LEFT JOIN t2 USING (t1.ipk=t2.ipk)
  135372. ** LEFT JOIN t3 USING (t1.ipk=t3.ipk)
  135373. **
  135374. ** or from:
  135375. **
  135376. ** SELECT DISTINCT v1, v3 FROM t1
  135377. ** LEFT JOIN t2
  135378. ** LEFT JOIN t3 USING (t1.ipk=t3.ipk)
  135379. */
  135380. notReady = ~(Bitmask)0;
  135381. if( pWInfo->nLevel>=2
  135382. && pResultSet!=0 /* guarantees condition (1) above */
  135383. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  135384. ){
  135385. int i;
  135386. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  135387. if( sWLB.pOrderBy ){
  135388. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  135389. }
  135390. for(i=pWInfo->nLevel-1; i>=1; i--){
  135391. WhereTerm *pTerm, *pEnd;
  135392. struct SrcList_item *pItem;
  135393. pLoop = pWInfo->a[i].pWLoop;
  135394. pItem = &pWInfo->pTabList->a[pLoop->iTab];
  135395. if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
  135396. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  135397. && (pLoop->wsFlags & WHERE_ONEROW)==0
  135398. ){
  135399. continue;
  135400. }
  135401. if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
  135402. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  135403. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  135404. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  135405. if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  135406. || pTerm->pExpr->iRightJoinTable!=pItem->iCursor
  135407. ){
  135408. break;
  135409. }
  135410. }
  135411. }
  135412. if( pTerm<pEnd ) continue;
  135413. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  135414. notReady &= ~pLoop->maskSelf;
  135415. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  135416. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  135417. pTerm->wtFlags |= TERM_CODED;
  135418. }
  135419. }
  135420. if( i!=pWInfo->nLevel-1 ){
  135421. int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
  135422. memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
  135423. }
  135424. pWInfo->nLevel--;
  135425. nTabList--;
  135426. }
  135427. }
  135428. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  135429. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  135430. /* If the caller is an UPDATE or DELETE statement that is requesting
  135431. ** to use a one-pass algorithm, determine if this is appropriate.
  135432. **
  135433. ** A one-pass approach can be used if the caller has requested one
  135434. ** and either (a) the scan visits at most one row or (b) each
  135435. ** of the following are true:
  135436. **
  135437. ** * the caller has indicated that a one-pass approach can be used
  135438. ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
  135439. ** * the table is not a virtual table, and
  135440. ** * either the scan does not use the OR optimization or the caller
  135441. ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
  135442. ** for DELETE).
  135443. **
  135444. ** The last qualification is because an UPDATE statement uses
  135445. ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
  135446. ** use a one-pass approach, and this is not set accurately for scans
  135447. ** that use the OR optimization.
  135448. */
  135449. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  135450. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  135451. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  135452. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  135453. if( bOnerow || (
  135454. 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
  135455. && 0==(wsFlags & WHERE_VIRTUALTABLE)
  135456. && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
  135457. )){
  135458. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  135459. if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
  135460. if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
  135461. bFordelete = OPFLAG_FORDELETE;
  135462. }
  135463. pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
  135464. }
  135465. }
  135466. }
  135467. /* Open all tables in the pTabList and any indices selected for
  135468. ** searching those tables.
  135469. */
  135470. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  135471. Table *pTab; /* Table to open */
  135472. int iDb; /* Index of database containing table/index */
  135473. struct SrcList_item *pTabItem;
  135474. pTabItem = &pTabList->a[pLevel->iFrom];
  135475. pTab = pTabItem->pTab;
  135476. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  135477. pLoop = pLevel->pWLoop;
  135478. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  135479. /* Do nothing */
  135480. }else
  135481. #ifndef SQLITE_OMIT_VIRTUALTABLE
  135482. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  135483. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  135484. int iCur = pTabItem->iCursor;
  135485. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  135486. }else if( IsVirtual(pTab) ){
  135487. /* noop */
  135488. }else
  135489. #endif
  135490. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  135491. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  135492. int op = OP_OpenRead;
  135493. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  135494. op = OP_OpenWrite;
  135495. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  135496. };
  135497. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  135498. assert( pTabItem->iCursor==pLevel->iTabCur );
  135499. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  135500. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  135501. if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
  135502. Bitmask b = pTabItem->colUsed;
  135503. int n = 0;
  135504. for(; b; b=b>>1, n++){}
  135505. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
  135506. assert( n<=pTab->nCol );
  135507. }
  135508. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  135509. if( pLoop->u.btree.pIndex!=0 ){
  135510. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
  135511. }else
  135512. #endif
  135513. {
  135514. sqlite3VdbeChangeP5(v, bFordelete);
  135515. }
  135516. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  135517. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  135518. (const u8*)&pTabItem->colUsed, P4_INT64);
  135519. #endif
  135520. }else{
  135521. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  135522. }
  135523. if( pLoop->wsFlags & WHERE_INDEXED ){
  135524. Index *pIx = pLoop->u.btree.pIndex;
  135525. int iIndexCur;
  135526. int op = OP_OpenRead;
  135527. /* iAuxArg is always set to a positive value if ONEPASS is possible */
  135528. assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  135529. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  135530. && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
  135531. ){
  135532. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  135533. ** WITHOUT ROWID table. No need for a separate index */
  135534. iIndexCur = pLevel->iTabCur;
  135535. op = 0;
  135536. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  135537. Index *pJ = pTabItem->pTab->pIndex;
  135538. iIndexCur = iAuxArg;
  135539. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  135540. while( ALWAYS(pJ) && pJ!=pIx ){
  135541. iIndexCur++;
  135542. pJ = pJ->pNext;
  135543. }
  135544. op = OP_OpenWrite;
  135545. pWInfo->aiCurOnePass[1] = iIndexCur;
  135546. }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
  135547. iIndexCur = iAuxArg;
  135548. op = OP_ReopenIdx;
  135549. }else{
  135550. iIndexCur = pParse->nTab++;
  135551. }
  135552. pLevel->iIdxCur = iIndexCur;
  135553. assert( pIx->pSchema==pTab->pSchema );
  135554. assert( iIndexCur>=0 );
  135555. if( op ){
  135556. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  135557. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  135558. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  135559. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  135560. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  135561. && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
  135562. ){
  135563. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  135564. }
  135565. VdbeComment((v, "%s", pIx->zName));
  135566. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  135567. {
  135568. u64 colUsed = 0;
  135569. int ii, jj;
  135570. for(ii=0; ii<pIx->nColumn; ii++){
  135571. jj = pIx->aiColumn[ii];
  135572. if( jj<0 ) continue;
  135573. if( jj>63 ) jj = 63;
  135574. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  135575. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  135576. }
  135577. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  135578. (u8*)&colUsed, P4_INT64);
  135579. }
  135580. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  135581. }
  135582. }
  135583. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  135584. }
  135585. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  135586. if( db->mallocFailed ) goto whereBeginError;
  135587. /* Generate the code to do the search. Each iteration of the for
  135588. ** loop below generates code for a single nested loop of the VM
  135589. ** program.
  135590. */
  135591. for(ii=0; ii<nTabList; ii++){
  135592. int addrExplain;
  135593. int wsFlags;
  135594. pLevel = &pWInfo->a[ii];
  135595. wsFlags = pLevel->pWLoop->wsFlags;
  135596. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  135597. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  135598. constructAutomaticIndex(pParse, &pWInfo->sWC,
  135599. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  135600. if( db->mallocFailed ) goto whereBeginError;
  135601. }
  135602. #endif
  135603. addrExplain = sqlite3WhereExplainOneScan(
  135604. pParse, pTabList, pLevel, wctrlFlags
  135605. );
  135606. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  135607. notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
  135608. pWInfo->iContinue = pLevel->addrCont;
  135609. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
  135610. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  135611. }
  135612. }
  135613. /* Done. */
  135614. VdbeModuleComment((v, "Begin WHERE-core"));
  135615. return pWInfo;
  135616. /* Jump here if malloc fails */
  135617. whereBeginError:
  135618. if( pWInfo ){
  135619. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  135620. whereInfoFree(db, pWInfo);
  135621. }
  135622. return 0;
  135623. }
  135624. /*
  135625. ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
  135626. ** index rather than the main table. In SQLITE_DEBUG mode, we want
  135627. ** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine
  135628. ** does that.
  135629. */
  135630. #ifndef SQLITE_DEBUG
  135631. # define OpcodeRewriteTrace(D,K,P) /* no-op */
  135632. #else
  135633. # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
  135634. static void sqlite3WhereOpcodeRewriteTrace(
  135635. sqlite3 *db,
  135636. int pc,
  135637. VdbeOp *pOp
  135638. ){
  135639. if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
  135640. sqlite3VdbePrintOp(0, pc, pOp);
  135641. }
  135642. #endif
  135643. /*
  135644. ** Generate the end of the WHERE loop. See comments on
  135645. ** sqlite3WhereBegin() for additional information.
  135646. */
  135647. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  135648. Parse *pParse = pWInfo->pParse;
  135649. Vdbe *v = pParse->pVdbe;
  135650. int i;
  135651. WhereLevel *pLevel;
  135652. WhereLoop *pLoop;
  135653. SrcList *pTabList = pWInfo->pTabList;
  135654. sqlite3 *db = pParse->db;
  135655. /* Generate loop termination code.
  135656. */
  135657. VdbeModuleComment((v, "End WHERE-core"));
  135658. for(i=pWInfo->nLevel-1; i>=0; i--){
  135659. int addr;
  135660. pLevel = &pWInfo->a[i];
  135661. pLoop = pLevel->pWLoop;
  135662. if( pLevel->op!=OP_Noop ){
  135663. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  135664. int addrSeek = 0;
  135665. Index *pIdx;
  135666. int n;
  135667. if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
  135668. && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
  135669. && (pLoop->wsFlags & WHERE_INDEXED)!=0
  135670. && (pIdx = pLoop->u.btree.pIndex)->hasStat1
  135671. && (n = pLoop->u.btree.nIdxCol)>0
  135672. && pIdx->aiRowLogEst[n]>=36
  135673. ){
  135674. int r1 = pParse->nMem+1;
  135675. int j, op;
  135676. for(j=0; j<n; j++){
  135677. sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
  135678. }
  135679. pParse->nMem += n+1;
  135680. op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
  135681. addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
  135682. VdbeCoverageIf(v, op==OP_SeekLT);
  135683. VdbeCoverageIf(v, op==OP_SeekGT);
  135684. sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
  135685. }
  135686. #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
  135687. /* The common case: Advance to the next row */
  135688. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  135689. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  135690. sqlite3VdbeChangeP5(v, pLevel->p5);
  135691. VdbeCoverage(v);
  135692. VdbeCoverageIf(v, pLevel->op==OP_Next);
  135693. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  135694. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  135695. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  135696. if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
  135697. #endif
  135698. }else{
  135699. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  135700. }
  135701. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  135702. struct InLoop *pIn;
  135703. int j;
  135704. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  135705. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  135706. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  135707. if( pIn->eEndLoopOp!=OP_Noop ){
  135708. if( pIn->nPrefix ){
  135709. assert( pLoop->wsFlags & WHERE_IN_EARLYOUT );
  135710. sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
  135711. sqlite3VdbeCurrentAddr(v)+2,
  135712. pIn->iBase, pIn->nPrefix);
  135713. VdbeCoverage(v);
  135714. }
  135715. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  135716. VdbeCoverage(v);
  135717. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
  135718. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
  135719. }
  135720. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  135721. }
  135722. }
  135723. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  135724. if( pLevel->addrSkip ){
  135725. sqlite3VdbeGoto(v, pLevel->addrSkip);
  135726. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  135727. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  135728. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  135729. }
  135730. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  135731. if( pLevel->addrLikeRep ){
  135732. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
  135733. pLevel->addrLikeRep);
  135734. VdbeCoverage(v);
  135735. }
  135736. #endif
  135737. if( pLevel->iLeftJoin ){
  135738. int ws = pLoop->wsFlags;
  135739. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  135740. assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
  135741. if( (ws & WHERE_IDX_ONLY)==0 ){
  135742. assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
  135743. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
  135744. }
  135745. if( (ws & WHERE_INDEXED)
  135746. || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
  135747. ){
  135748. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  135749. }
  135750. if( pLevel->op==OP_Return ){
  135751. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  135752. }else{
  135753. sqlite3VdbeGoto(v, pLevel->addrFirst);
  135754. }
  135755. sqlite3VdbeJumpHere(v, addr);
  135756. }
  135757. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  135758. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  135759. }
  135760. /* The "break" point is here, just past the end of the outer loop.
  135761. ** Set it.
  135762. */
  135763. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  135764. assert( pWInfo->nLevel<=pTabList->nSrc );
  135765. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  135766. int k, last;
  135767. VdbeOp *pOp;
  135768. Index *pIdx = 0;
  135769. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  135770. Table *pTab = pTabItem->pTab;
  135771. assert( pTab!=0 );
  135772. pLoop = pLevel->pWLoop;
  135773. /* For a co-routine, change all OP_Column references to the table of
  135774. ** the co-routine into OP_Copy of result contained in a register.
  135775. ** OP_Rowid becomes OP_Null.
  135776. */
  135777. if( pTabItem->fg.viaCoroutine ){
  135778. testcase( pParse->db->mallocFailed );
  135779. translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
  135780. pTabItem->regResult, 0);
  135781. continue;
  135782. }
  135783. /* If this scan uses an index, make VDBE code substitutions to read data
  135784. ** from the index instead of from the table where possible. In some cases
  135785. ** this optimization prevents the table from ever being read, which can
  135786. ** yield a significant performance boost.
  135787. **
  135788. ** Calls to the code generator in between sqlite3WhereBegin and
  135789. ** sqlite3WhereEnd will have created code that references the table
  135790. ** directly. This loop scans all that code looking for opcodes
  135791. ** that reference the table and converts them into opcodes that
  135792. ** reference the index.
  135793. */
  135794. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  135795. pIdx = pLoop->u.btree.pIndex;
  135796. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  135797. pIdx = pLevel->u.pCovidx;
  135798. }
  135799. if( pIdx
  135800. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  135801. && !db->mallocFailed
  135802. ){
  135803. last = sqlite3VdbeCurrentAddr(v);
  135804. k = pLevel->addrBody;
  135805. #ifdef SQLITE_DEBUG
  135806. if( db->flags & SQLITE_VdbeAddopTrace ){
  135807. printf("TRANSLATE opcodes in range %d..%d\n", k, last-1);
  135808. }
  135809. #endif
  135810. pOp = sqlite3VdbeGetOp(v, k);
  135811. for(; k<last; k++, pOp++){
  135812. if( pOp->p1!=pLevel->iTabCur ) continue;
  135813. if( pOp->opcode==OP_Column
  135814. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  135815. || pOp->opcode==OP_Offset
  135816. #endif
  135817. ){
  135818. int x = pOp->p2;
  135819. assert( pIdx->pTable==pTab );
  135820. if( !HasRowid(pTab) ){
  135821. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  135822. x = pPk->aiColumn[x];
  135823. assert( x>=0 );
  135824. }
  135825. x = sqlite3ColumnOfIndex(pIdx, x);
  135826. if( x>=0 ){
  135827. pOp->p2 = x;
  135828. pOp->p1 = pLevel->iIdxCur;
  135829. OpcodeRewriteTrace(db, k, pOp);
  135830. }
  135831. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
  135832. || pWInfo->eOnePass );
  135833. }else if( pOp->opcode==OP_Rowid ){
  135834. pOp->p1 = pLevel->iIdxCur;
  135835. pOp->opcode = OP_IdxRowid;
  135836. OpcodeRewriteTrace(db, k, pOp);
  135837. }else if( pOp->opcode==OP_IfNullRow ){
  135838. pOp->p1 = pLevel->iIdxCur;
  135839. OpcodeRewriteTrace(db, k, pOp);
  135840. }
  135841. }
  135842. #ifdef SQLITE_DEBUG
  135843. if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
  135844. #endif
  135845. }
  135846. }
  135847. /* Final cleanup
  135848. */
  135849. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  135850. whereInfoFree(db, pWInfo);
  135851. return;
  135852. }
  135853. /************** End of where.c ***********************************************/
  135854. /************** Begin file window.c ******************************************/
  135855. /*
  135856. ** 2018 May 08
  135857. **
  135858. ** The author disclaims copyright to this source code. In place of
  135859. ** a legal notice, here is a blessing:
  135860. **
  135861. ** May you do good and not evil.
  135862. ** May you find forgiveness for yourself and forgive others.
  135863. ** May you share freely, never taking more than you give.
  135864. **
  135865. *************************************************************************
  135866. */
  135867. /* #include "sqliteInt.h" */
  135868. #ifndef SQLITE_OMIT_WINDOWFUNC
  135869. /*
  135870. ** SELECT REWRITING
  135871. **
  135872. ** Any SELECT statement that contains one or more window functions in
  135873. ** either the select list or ORDER BY clause (the only two places window
  135874. ** functions may be used) is transformed by function sqlite3WindowRewrite()
  135875. ** in order to support window function processing. For example, with the
  135876. ** schema:
  135877. **
  135878. ** CREATE TABLE t1(a, b, c, d, e, f, g);
  135879. **
  135880. ** the statement:
  135881. **
  135882. ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
  135883. **
  135884. ** is transformed to:
  135885. **
  135886. ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (
  135887. ** SELECT a, e, c, d, b FROM t1 ORDER BY c, d
  135888. ** ) ORDER BY e;
  135889. **
  135890. ** The flattening optimization is disabled when processing this transformed
  135891. ** SELECT statement. This allows the implementation of the window function
  135892. ** (in this case max()) to process rows sorted in order of (c, d), which
  135893. ** makes things easier for obvious reasons. More generally:
  135894. **
  135895. ** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
  135896. ** the sub-query.
  135897. **
  135898. ** * ORDER BY, LIMIT and OFFSET remain part of the parent query.
  135899. **
  135900. ** * Terminals from each of the expression trees that make up the
  135901. ** select-list and ORDER BY expressions in the parent query are
  135902. ** selected by the sub-query. For the purposes of the transformation,
  135903. ** terminals are column references and aggregate functions.
  135904. **
  135905. ** If there is more than one window function in the SELECT that uses
  135906. ** the same window declaration (the OVER bit), then a single scan may
  135907. ** be used to process more than one window function. For example:
  135908. **
  135909. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
  135910. ** min(e) OVER (PARTITION BY c ORDER BY d)
  135911. ** FROM t1;
  135912. **
  135913. ** is transformed in the same way as the example above. However:
  135914. **
  135915. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
  135916. ** min(e) OVER (PARTITION BY a ORDER BY b)
  135917. ** FROM t1;
  135918. **
  135919. ** Must be transformed to:
  135920. **
  135921. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (
  135922. ** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM
  135923. ** SELECT a, e, c, d, b FROM t1 ORDER BY a, b
  135924. ** ) ORDER BY c, d
  135925. ** ) ORDER BY e;
  135926. **
  135927. ** so that both min() and max() may process rows in the order defined by
  135928. ** their respective window declarations.
  135929. **
  135930. ** INTERFACE WITH SELECT.C
  135931. **
  135932. ** When processing the rewritten SELECT statement, code in select.c calls
  135933. ** sqlite3WhereBegin() to begin iterating through the results of the
  135934. ** sub-query, which is always implemented as a co-routine. It then calls
  135935. ** sqlite3WindowCodeStep() to process rows and finish the scan by calling
  135936. ** sqlite3WhereEnd().
  135937. **
  135938. ** sqlite3WindowCodeStep() generates VM code so that, for each row returned
  135939. ** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
  135940. ** When the sub-routine is invoked:
  135941. **
  135942. ** * The results of all window-functions for the row are stored
  135943. ** in the associated Window.regResult registers.
  135944. **
  135945. ** * The required terminal values are stored in the current row of
  135946. ** temp table Window.iEphCsr.
  135947. **
  135948. ** In some cases, depending on the window frame and the specific window
  135949. ** functions invoked, sqlite3WindowCodeStep() caches each entire partition
  135950. ** in a temp table before returning any rows. In other cases it does not.
  135951. ** This detail is encapsulated within this file, the code generated by
  135952. ** select.c is the same in either case.
  135953. **
  135954. ** BUILT-IN WINDOW FUNCTIONS
  135955. **
  135956. ** This implementation features the following built-in window functions:
  135957. **
  135958. ** row_number()
  135959. ** rank()
  135960. ** dense_rank()
  135961. ** percent_rank()
  135962. ** cume_dist()
  135963. ** ntile(N)
  135964. ** lead(expr [, offset [, default]])
  135965. ** lag(expr [, offset [, default]])
  135966. ** first_value(expr)
  135967. ** last_value(expr)
  135968. ** nth_value(expr, N)
  135969. **
  135970. ** These are the same built-in window functions supported by Postgres.
  135971. ** Although the behaviour of aggregate window functions (functions that
  135972. ** can be used as either aggregates or window funtions) allows them to
  135973. ** be implemented using an API, built-in window functions are much more
  135974. ** esoteric. Additionally, some window functions (e.g. nth_value())
  135975. ** may only be implemented by caching the entire partition in memory.
  135976. ** As such, some built-in window functions use the same API as aggregate
  135977. ** window functions and some are implemented directly using VDBE
  135978. ** instructions. Additionally, for those functions that use the API, the
  135979. ** window frame is sometimes modified before the SELECT statement is
  135980. ** rewritten. For example, regardless of the specified window frame, the
  135981. ** row_number() function always uses:
  135982. **
  135983. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  135984. **
  135985. ** See sqlite3WindowUpdate() for details.
  135986. **
  135987. ** As well as some of the built-in window functions, aggregate window
  135988. ** functions min() and max() are implemented using VDBE instructions if
  135989. ** the start of the window frame is declared as anything other than
  135990. ** UNBOUNDED PRECEDING.
  135991. */
  135992. /*
  135993. ** Implementation of built-in window function row_number(). Assumes that the
  135994. ** window frame has been coerced to:
  135995. **
  135996. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  135997. */
  135998. static void row_numberStepFunc(
  135999. sqlite3_context *pCtx,
  136000. int nArg,
  136001. sqlite3_value **apArg
  136002. ){
  136003. i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136004. if( p ) (*p)++;
  136005. UNUSED_PARAMETER(nArg);
  136006. UNUSED_PARAMETER(apArg);
  136007. }
  136008. static void row_numberValueFunc(sqlite3_context *pCtx){
  136009. i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136010. sqlite3_result_int64(pCtx, (p ? *p : 0));
  136011. }
  136012. /*
  136013. ** Context object type used by rank(), dense_rank(), percent_rank() and
  136014. ** cume_dist().
  136015. */
  136016. struct CallCount {
  136017. i64 nValue;
  136018. i64 nStep;
  136019. i64 nTotal;
  136020. };
  136021. /*
  136022. ** Implementation of built-in window function dense_rank(). Assumes that
  136023. ** the window frame has been set to:
  136024. **
  136025. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  136026. */
  136027. static void dense_rankStepFunc(
  136028. sqlite3_context *pCtx,
  136029. int nArg,
  136030. sqlite3_value **apArg
  136031. ){
  136032. struct CallCount *p;
  136033. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136034. if( p ) p->nStep = 1;
  136035. UNUSED_PARAMETER(nArg);
  136036. UNUSED_PARAMETER(apArg);
  136037. }
  136038. static void dense_rankValueFunc(sqlite3_context *pCtx){
  136039. struct CallCount *p;
  136040. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136041. if( p ){
  136042. if( p->nStep ){
  136043. p->nValue++;
  136044. p->nStep = 0;
  136045. }
  136046. sqlite3_result_int64(pCtx, p->nValue);
  136047. }
  136048. }
  136049. /*
  136050. ** Implementation of built-in window function rank(). Assumes that
  136051. ** the window frame has been set to:
  136052. **
  136053. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  136054. */
  136055. static void rankStepFunc(
  136056. sqlite3_context *pCtx,
  136057. int nArg,
  136058. sqlite3_value **apArg
  136059. ){
  136060. struct CallCount *p;
  136061. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136062. if( p ){
  136063. p->nStep++;
  136064. if( p->nValue==0 ){
  136065. p->nValue = p->nStep;
  136066. }
  136067. }
  136068. UNUSED_PARAMETER(nArg);
  136069. UNUSED_PARAMETER(apArg);
  136070. }
  136071. static void rankValueFunc(sqlite3_context *pCtx){
  136072. struct CallCount *p;
  136073. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136074. if( p ){
  136075. sqlite3_result_int64(pCtx, p->nValue);
  136076. p->nValue = 0;
  136077. }
  136078. }
  136079. /*
  136080. ** Implementation of built-in window function percent_rank(). Assumes that
  136081. ** the window frame has been set to:
  136082. **
  136083. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  136084. */
  136085. static void percent_rankStepFunc(
  136086. sqlite3_context *pCtx,
  136087. int nArg,
  136088. sqlite3_value **apArg
  136089. ){
  136090. struct CallCount *p;
  136091. UNUSED_PARAMETER(nArg); assert( nArg==1 );
  136092. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136093. if( p ){
  136094. if( p->nTotal==0 ){
  136095. p->nTotal = sqlite3_value_int64(apArg[0]);
  136096. }
  136097. p->nStep++;
  136098. if( p->nValue==0 ){
  136099. p->nValue = p->nStep;
  136100. }
  136101. }
  136102. }
  136103. static void percent_rankValueFunc(sqlite3_context *pCtx){
  136104. struct CallCount *p;
  136105. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136106. if( p ){
  136107. if( p->nTotal>1 ){
  136108. double r = (double)(p->nValue-1) / (double)(p->nTotal-1);
  136109. sqlite3_result_double(pCtx, r);
  136110. }else{
  136111. sqlite3_result_double(pCtx, 0.0);
  136112. }
  136113. p->nValue = 0;
  136114. }
  136115. }
  136116. /*
  136117. ** Implementation of built-in window function cume_dist(). Assumes that
  136118. ** the window frame has been set to:
  136119. **
  136120. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  136121. */
  136122. static void cume_distStepFunc(
  136123. sqlite3_context *pCtx,
  136124. int nArg,
  136125. sqlite3_value **apArg
  136126. ){
  136127. struct CallCount *p;
  136128. assert( nArg==1 ); UNUSED_PARAMETER(nArg);
  136129. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136130. if( p ){
  136131. if( p->nTotal==0 ){
  136132. p->nTotal = sqlite3_value_int64(apArg[0]);
  136133. }
  136134. p->nStep++;
  136135. }
  136136. }
  136137. static void cume_distValueFunc(sqlite3_context *pCtx){
  136138. struct CallCount *p;
  136139. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136140. if( p && p->nTotal ){
  136141. double r = (double)(p->nStep) / (double)(p->nTotal);
  136142. sqlite3_result_double(pCtx, r);
  136143. }
  136144. }
  136145. /*
  136146. ** Context object for ntile() window function.
  136147. */
  136148. struct NtileCtx {
  136149. i64 nTotal; /* Total rows in partition */
  136150. i64 nParam; /* Parameter passed to ntile(N) */
  136151. i64 iRow; /* Current row */
  136152. };
  136153. /*
  136154. ** Implementation of ntile(). This assumes that the window frame has
  136155. ** been coerced to:
  136156. **
  136157. ** ROWS UNBOUNDED PRECEDING AND CURRENT ROW
  136158. */
  136159. static void ntileStepFunc(
  136160. sqlite3_context *pCtx,
  136161. int nArg,
  136162. sqlite3_value **apArg
  136163. ){
  136164. struct NtileCtx *p;
  136165. assert( nArg==2 ); UNUSED_PARAMETER(nArg);
  136166. p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136167. if( p ){
  136168. if( p->nTotal==0 ){
  136169. p->nParam = sqlite3_value_int64(apArg[0]);
  136170. p->nTotal = sqlite3_value_int64(apArg[1]);
  136171. if( p->nParam<=0 ){
  136172. sqlite3_result_error(
  136173. pCtx, "argument of ntile must be a positive integer", -1
  136174. );
  136175. }
  136176. }
  136177. p->iRow++;
  136178. }
  136179. }
  136180. static void ntileValueFunc(sqlite3_context *pCtx){
  136181. struct NtileCtx *p;
  136182. p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136183. if( p && p->nParam>0 ){
  136184. int nSize = (p->nTotal / p->nParam);
  136185. if( nSize==0 ){
  136186. sqlite3_result_int64(pCtx, p->iRow);
  136187. }else{
  136188. i64 nLarge = p->nTotal - p->nParam*nSize;
  136189. i64 iSmall = nLarge*(nSize+1);
  136190. i64 iRow = p->iRow-1;
  136191. assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
  136192. if( iRow<iSmall ){
  136193. sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
  136194. }else{
  136195. sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
  136196. }
  136197. }
  136198. }
  136199. }
  136200. /*
  136201. ** Context object for last_value() window function.
  136202. */
  136203. struct LastValueCtx {
  136204. sqlite3_value *pVal;
  136205. int nVal;
  136206. };
  136207. /*
  136208. ** Implementation of last_value().
  136209. */
  136210. static void last_valueStepFunc(
  136211. sqlite3_context *pCtx,
  136212. int nArg,
  136213. sqlite3_value **apArg
  136214. ){
  136215. struct LastValueCtx *p;
  136216. UNUSED_PARAMETER(nArg);
  136217. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136218. if( p ){
  136219. sqlite3_value_free(p->pVal);
  136220. p->pVal = sqlite3_value_dup(apArg[0]);
  136221. if( p->pVal==0 ){
  136222. sqlite3_result_error_nomem(pCtx);
  136223. }else{
  136224. p->nVal++;
  136225. }
  136226. }
  136227. }
  136228. static void last_valueInvFunc(
  136229. sqlite3_context *pCtx,
  136230. int nArg,
  136231. sqlite3_value **apArg
  136232. ){
  136233. struct LastValueCtx *p;
  136234. UNUSED_PARAMETER(nArg);
  136235. UNUSED_PARAMETER(apArg);
  136236. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136237. if( ALWAYS(p) ){
  136238. p->nVal--;
  136239. if( p->nVal==0 ){
  136240. sqlite3_value_free(p->pVal);
  136241. p->pVal = 0;
  136242. }
  136243. }
  136244. }
  136245. static void last_valueValueFunc(sqlite3_context *pCtx){
  136246. struct LastValueCtx *p;
  136247. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136248. if( p && p->pVal ){
  136249. sqlite3_result_value(pCtx, p->pVal);
  136250. }
  136251. }
  136252. static void last_valueFinalizeFunc(sqlite3_context *pCtx){
  136253. struct LastValueCtx *p;
  136254. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136255. if( p && p->pVal ){
  136256. sqlite3_result_value(pCtx, p->pVal);
  136257. sqlite3_value_free(p->pVal);
  136258. p->pVal = 0;
  136259. }
  136260. }
  136261. /*
  136262. ** Static names for the built-in window function names. These static
  136263. ** names are used, rather than string literals, so that FuncDef objects
  136264. ** can be associated with a particular window function by direct
  136265. ** comparison of the zName pointer. Example:
  136266. **
  136267. ** if( pFuncDef->zName==row_valueName ){ ... }
  136268. */
  136269. static const char row_numberName[] = "row_number";
  136270. static const char dense_rankName[] = "dense_rank";
  136271. static const char rankName[] = "rank";
  136272. static const char percent_rankName[] = "percent_rank";
  136273. static const char cume_distName[] = "cume_dist";
  136274. static const char ntileName[] = "ntile";
  136275. static const char last_valueName[] = "last_value";
  136276. static const char nth_valueName[] = "nth_value";
  136277. static const char first_valueName[] = "first_value";
  136278. static const char leadName[] = "lead";
  136279. static const char lagName[] = "lag";
  136280. /*
  136281. ** No-op implementations of xStep() and xFinalize(). Used as place-holders
  136282. ** for built-in window functions that never call those interfaces.
  136283. **
  136284. ** The noopValueFunc() is called but is expected to do nothing. The
  136285. ** noopStepFunc() is never called, and so it is marked with NO_TEST to
  136286. ** let the test coverage routine know not to expect this function to be
  136287. ** invoked.
  136288. */
  136289. static void noopStepFunc( /*NO_TEST*/
  136290. sqlite3_context *p, /*NO_TEST*/
  136291. int n, /*NO_TEST*/
  136292. sqlite3_value **a /*NO_TEST*/
  136293. ){ /*NO_TEST*/
  136294. UNUSED_PARAMETER(p); /*NO_TEST*/
  136295. UNUSED_PARAMETER(n); /*NO_TEST*/
  136296. UNUSED_PARAMETER(a); /*NO_TEST*/
  136297. assert(0); /*NO_TEST*/
  136298. } /*NO_TEST*/
  136299. static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
  136300. /* Window functions that use all window interfaces: xStep, xFinal,
  136301. ** xValue, and xInverse */
  136302. #define WINDOWFUNCALL(name,nArg,extra) { \
  136303. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  136304. name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
  136305. name ## InvFunc, name ## Name, {0} \
  136306. }
  136307. /* Window functions that are implemented using bytecode and thus have
  136308. ** no-op routines for their methods */
  136309. #define WINDOWFUNCNOOP(name,nArg,extra) { \
  136310. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  136311. noopStepFunc, noopValueFunc, noopValueFunc, \
  136312. noopStepFunc, name ## Name, {0} \
  136313. }
  136314. /* Window functions that use all window interfaces: xStep, the
  136315. ** same routine for xFinalize and xValue and which never call
  136316. ** xInverse. */
  136317. #define WINDOWFUNCX(name,nArg,extra) { \
  136318. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  136319. name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
  136320. noopStepFunc, name ## Name, {0} \
  136321. }
  136322. /*
  136323. ** Register those built-in window functions that are not also aggregates.
  136324. */
  136325. SQLITE_PRIVATE void sqlite3WindowFunctions(void){
  136326. static FuncDef aWindowFuncs[] = {
  136327. WINDOWFUNCX(row_number, 0, 0),
  136328. WINDOWFUNCX(dense_rank, 0, 0),
  136329. WINDOWFUNCX(rank, 0, 0),
  136330. WINDOWFUNCX(percent_rank, 0, SQLITE_FUNC_WINDOW_SIZE),
  136331. WINDOWFUNCX(cume_dist, 0, SQLITE_FUNC_WINDOW_SIZE),
  136332. WINDOWFUNCX(ntile, 1, SQLITE_FUNC_WINDOW_SIZE),
  136333. WINDOWFUNCALL(last_value, 1, 0),
  136334. WINDOWFUNCNOOP(nth_value, 2, 0),
  136335. WINDOWFUNCNOOP(first_value, 1, 0),
  136336. WINDOWFUNCNOOP(lead, 1, 0),
  136337. WINDOWFUNCNOOP(lead, 2, 0),
  136338. WINDOWFUNCNOOP(lead, 3, 0),
  136339. WINDOWFUNCNOOP(lag, 1, 0),
  136340. WINDOWFUNCNOOP(lag, 2, 0),
  136341. WINDOWFUNCNOOP(lag, 3, 0),
  136342. };
  136343. sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
  136344. }
  136345. /*
  136346. ** This function is called immediately after resolving the function name
  136347. ** for a window function within a SELECT statement. Argument pList is a
  136348. ** linked list of WINDOW definitions for the current SELECT statement.
  136349. ** Argument pFunc is the function definition just resolved and pWin
  136350. ** is the Window object representing the associated OVER clause. This
  136351. ** function updates the contents of pWin as follows:
  136352. **
  136353. ** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
  136354. ** search list pList for a matching WINDOW definition, and update pWin
  136355. ** accordingly. If no such WINDOW clause can be found, leave an error
  136356. ** in pParse.
  136357. **
  136358. ** * If the function is a built-in window function that requires the
  136359. ** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
  136360. ** of this file), pWin is updated here.
  136361. */
  136362. SQLITE_PRIVATE void sqlite3WindowUpdate(
  136363. Parse *pParse,
  136364. Window *pList, /* List of named windows for this SELECT */
  136365. Window *pWin, /* Window frame to update */
  136366. FuncDef *pFunc /* Window function definition */
  136367. ){
  136368. if( pWin->zName && pWin->eType==0 ){
  136369. Window *p;
  136370. for(p=pList; p; p=p->pNextWin){
  136371. if( sqlite3StrICmp(p->zName, pWin->zName)==0 ) break;
  136372. }
  136373. if( p==0 ){
  136374. sqlite3ErrorMsg(pParse, "no such window: %s", pWin->zName);
  136375. return;
  136376. }
  136377. pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
  136378. pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
  136379. pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
  136380. pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
  136381. pWin->eStart = p->eStart;
  136382. pWin->eEnd = p->eEnd;
  136383. pWin->eType = p->eType;
  136384. }
  136385. if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
  136386. sqlite3 *db = pParse->db;
  136387. if( pWin->pFilter ){
  136388. sqlite3ErrorMsg(pParse,
  136389. "FILTER clause may only be used with aggregate window functions"
  136390. );
  136391. }else
  136392. if( pFunc->zName==row_numberName || pFunc->zName==ntileName ){
  136393. sqlite3ExprDelete(db, pWin->pStart);
  136394. sqlite3ExprDelete(db, pWin->pEnd);
  136395. pWin->pStart = pWin->pEnd = 0;
  136396. pWin->eType = TK_ROWS;
  136397. pWin->eStart = TK_UNBOUNDED;
  136398. pWin->eEnd = TK_CURRENT;
  136399. }else
  136400. if( pFunc->zName==dense_rankName || pFunc->zName==rankName
  136401. || pFunc->zName==percent_rankName || pFunc->zName==cume_distName
  136402. ){
  136403. sqlite3ExprDelete(db, pWin->pStart);
  136404. sqlite3ExprDelete(db, pWin->pEnd);
  136405. pWin->pStart = pWin->pEnd = 0;
  136406. pWin->eType = TK_RANGE;
  136407. pWin->eStart = TK_UNBOUNDED;
  136408. pWin->eEnd = TK_CURRENT;
  136409. }
  136410. }
  136411. pWin->pFunc = pFunc;
  136412. }
  136413. /*
  136414. ** Context object passed through sqlite3WalkExprList() to
  136415. ** selectWindowRewriteExprCb() by selectWindowRewriteEList().
  136416. */
  136417. typedef struct WindowRewrite WindowRewrite;
  136418. struct WindowRewrite {
  136419. Window *pWin;
  136420. SrcList *pSrc;
  136421. ExprList *pSub;
  136422. Select *pSubSelect; /* Current sub-select, if any */
  136423. };
  136424. /*
  136425. ** Callback function used by selectWindowRewriteEList(). If necessary,
  136426. ** this function appends to the output expression-list and updates
  136427. ** expression (*ppExpr) in place.
  136428. */
  136429. static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
  136430. struct WindowRewrite *p = pWalker->u.pRewrite;
  136431. Parse *pParse = pWalker->pParse;
  136432. /* If this function is being called from within a scalar sub-select
  136433. ** that used by the SELECT statement being processed, only process
  136434. ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
  136435. ** not process aggregates or window functions at all, as they belong
  136436. ** to the scalar sub-select. */
  136437. if( p->pSubSelect ){
  136438. if( pExpr->op!=TK_COLUMN ){
  136439. return WRC_Continue;
  136440. }else{
  136441. int nSrc = p->pSrc->nSrc;
  136442. int i;
  136443. for(i=0; i<nSrc; i++){
  136444. if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
  136445. }
  136446. if( i==nSrc ) return WRC_Continue;
  136447. }
  136448. }
  136449. switch( pExpr->op ){
  136450. case TK_FUNCTION:
  136451. if( !ExprHasProperty(pExpr, EP_WinFunc) ){
  136452. break;
  136453. }else{
  136454. Window *pWin;
  136455. for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
  136456. if( pExpr->y.pWin==pWin ){
  136457. assert( pWin->pOwner==pExpr );
  136458. return WRC_Prune;
  136459. }
  136460. }
  136461. }
  136462. /* Fall through. */
  136463. case TK_AGG_FUNCTION:
  136464. case TK_COLUMN: {
  136465. Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
  136466. p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
  136467. if( p->pSub ){
  136468. assert( ExprHasProperty(pExpr, EP_Static)==0 );
  136469. ExprSetProperty(pExpr, EP_Static);
  136470. sqlite3ExprDelete(pParse->db, pExpr);
  136471. ExprClearProperty(pExpr, EP_Static);
  136472. memset(pExpr, 0, sizeof(Expr));
  136473. pExpr->op = TK_COLUMN;
  136474. pExpr->iColumn = p->pSub->nExpr-1;
  136475. pExpr->iTable = p->pWin->iEphCsr;
  136476. }
  136477. break;
  136478. }
  136479. default: /* no-op */
  136480. break;
  136481. }
  136482. return WRC_Continue;
  136483. }
  136484. static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
  136485. struct WindowRewrite *p = pWalker->u.pRewrite;
  136486. Select *pSave = p->pSubSelect;
  136487. if( pSave==pSelect ){
  136488. return WRC_Continue;
  136489. }else{
  136490. p->pSubSelect = pSelect;
  136491. sqlite3WalkSelect(pWalker, pSelect);
  136492. p->pSubSelect = pSave;
  136493. }
  136494. return WRC_Prune;
  136495. }
  136496. /*
  136497. ** Iterate through each expression in expression-list pEList. For each:
  136498. **
  136499. ** * TK_COLUMN,
  136500. ** * aggregate function, or
  136501. ** * window function with a Window object that is not a member of the
  136502. ** Window list passed as the second argument (pWin).
  136503. **
  136504. ** Append the node to output expression-list (*ppSub). And replace it
  136505. ** with a TK_COLUMN that reads the (N-1)th element of table
  136506. ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
  136507. ** appending the new one.
  136508. */
  136509. static void selectWindowRewriteEList(
  136510. Parse *pParse,
  136511. Window *pWin,
  136512. SrcList *pSrc,
  136513. ExprList *pEList, /* Rewrite expressions in this list */
  136514. ExprList **ppSub /* IN/OUT: Sub-select expression-list */
  136515. ){
  136516. Walker sWalker;
  136517. WindowRewrite sRewrite;
  136518. memset(&sWalker, 0, sizeof(Walker));
  136519. memset(&sRewrite, 0, sizeof(WindowRewrite));
  136520. sRewrite.pSub = *ppSub;
  136521. sRewrite.pWin = pWin;
  136522. sRewrite.pSrc = pSrc;
  136523. sWalker.pParse = pParse;
  136524. sWalker.xExprCallback = selectWindowRewriteExprCb;
  136525. sWalker.xSelectCallback = selectWindowRewriteSelectCb;
  136526. sWalker.u.pRewrite = &sRewrite;
  136527. (void)sqlite3WalkExprList(&sWalker, pEList);
  136528. *ppSub = sRewrite.pSub;
  136529. }
  136530. /*
  136531. ** Append a copy of each expression in expression-list pAppend to
  136532. ** expression list pList. Return a pointer to the result list.
  136533. */
  136534. static ExprList *exprListAppendList(
  136535. Parse *pParse, /* Parsing context */
  136536. ExprList *pList, /* List to which to append. Might be NULL */
  136537. ExprList *pAppend /* List of values to append. Might be NULL */
  136538. ){
  136539. if( pAppend ){
  136540. int i;
  136541. int nInit = pList ? pList->nExpr : 0;
  136542. for(i=0; i<pAppend->nExpr; i++){
  136543. Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
  136544. pList = sqlite3ExprListAppend(pParse, pList, pDup);
  136545. if( pList ) pList->a[nInit+i].sortOrder = pAppend->a[i].sortOrder;
  136546. }
  136547. }
  136548. return pList;
  136549. }
  136550. /*
  136551. ** If the SELECT statement passed as the second argument does not invoke
  136552. ** any SQL window functions, this function is a no-op. Otherwise, it
  136553. ** rewrites the SELECT statement so that window function xStep functions
  136554. ** are invoked in the correct order as described under "SELECT REWRITING"
  136555. ** at the top of this file.
  136556. */
  136557. SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
  136558. int rc = SQLITE_OK;
  136559. if( p->pWin && p->pPrior==0 ){
  136560. Vdbe *v = sqlite3GetVdbe(pParse);
  136561. sqlite3 *db = pParse->db;
  136562. Select *pSub = 0; /* The subquery */
  136563. SrcList *pSrc = p->pSrc;
  136564. Expr *pWhere = p->pWhere;
  136565. ExprList *pGroupBy = p->pGroupBy;
  136566. Expr *pHaving = p->pHaving;
  136567. ExprList *pSort = 0;
  136568. ExprList *pSublist = 0; /* Expression list for sub-query */
  136569. Window *pMWin = p->pWin; /* Master window object */
  136570. Window *pWin; /* Window object iterator */
  136571. p->pSrc = 0;
  136572. p->pWhere = 0;
  136573. p->pGroupBy = 0;
  136574. p->pHaving = 0;
  136575. /* Create the ORDER BY clause for the sub-select. This is the concatenation
  136576. ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
  136577. ** redundant, remove the ORDER BY from the parent SELECT. */
  136578. pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
  136579. pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy);
  136580. if( pSort && p->pOrderBy ){
  136581. if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
  136582. sqlite3ExprListDelete(db, p->pOrderBy);
  136583. p->pOrderBy = 0;
  136584. }
  136585. }
  136586. /* Assign a cursor number for the ephemeral table used to buffer rows.
  136587. ** The OpenEphemeral instruction is coded later, after it is known how
  136588. ** many columns the table will have. */
  136589. pMWin->iEphCsr = pParse->nTab++;
  136590. selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, &pSublist);
  136591. selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, &pSublist);
  136592. pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
  136593. /* Append the PARTITION BY and ORDER BY expressions to the to the
  136594. ** sub-select expression list. They are required to figure out where
  136595. ** boundaries for partitions and sets of peer rows lie. */
  136596. pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition);
  136597. pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy);
  136598. /* Append the arguments passed to each window function to the
  136599. ** sub-select expression list. Also allocate two registers for each
  136600. ** window function - one for the accumulator, another for interim
  136601. ** results. */
  136602. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  136603. pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
  136604. pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList);
  136605. if( pWin->pFilter ){
  136606. Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
  136607. pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
  136608. }
  136609. pWin->regAccum = ++pParse->nMem;
  136610. pWin->regResult = ++pParse->nMem;
  136611. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  136612. }
  136613. /* If there is no ORDER BY or PARTITION BY clause, and the window
  136614. ** function accepts zero arguments, and there are no other columns
  136615. ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
  136616. ** that pSublist is still NULL here. Add a constant expression here to
  136617. ** keep everything legal in this case.
  136618. */
  136619. if( pSublist==0 ){
  136620. pSublist = sqlite3ExprListAppend(pParse, 0,
  136621. sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
  136622. );
  136623. }
  136624. pSub = sqlite3SelectNew(
  136625. pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
  136626. );
  136627. p->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  136628. assert( p->pSrc || db->mallocFailed );
  136629. if( p->pSrc ){
  136630. p->pSrc->a[0].pSelect = pSub;
  136631. sqlite3SrcListAssignCursors(pParse, p->pSrc);
  136632. if( sqlite3ExpandSubquery(pParse, &p->pSrc->a[0]) ){
  136633. rc = SQLITE_NOMEM;
  136634. }else{
  136635. pSub->selFlags |= SF_Expanded;
  136636. p->selFlags &= ~SF_Aggregate;
  136637. sqlite3SelectPrep(pParse, pSub, 0);
  136638. }
  136639. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
  136640. }else{
  136641. sqlite3SelectDelete(db, pSub);
  136642. }
  136643. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  136644. }
  136645. return rc;
  136646. }
  136647. /*
  136648. ** Free the Window object passed as the second argument.
  136649. */
  136650. SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3 *db, Window *p){
  136651. if( p ){
  136652. sqlite3ExprDelete(db, p->pFilter);
  136653. sqlite3ExprListDelete(db, p->pPartition);
  136654. sqlite3ExprListDelete(db, p->pOrderBy);
  136655. sqlite3ExprDelete(db, p->pEnd);
  136656. sqlite3ExprDelete(db, p->pStart);
  136657. sqlite3DbFree(db, p->zName);
  136658. sqlite3DbFree(db, p);
  136659. }
  136660. }
  136661. /*
  136662. ** Free the linked list of Window objects starting at the second argument.
  136663. */
  136664. SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p){
  136665. while( p ){
  136666. Window *pNext = p->pNextWin;
  136667. sqlite3WindowDelete(db, p);
  136668. p = pNext;
  136669. }
  136670. }
  136671. /*
  136672. ** The argument expression is an PRECEDING or FOLLOWING offset. The
  136673. ** value should be a non-negative integer. If the value is not a
  136674. ** constant, change it to NULL. The fact that it is then a non-negative
  136675. ** integer will be caught later. But it is important not to leave
  136676. ** variable values in the expression tree.
  136677. */
  136678. static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
  136679. if( 0==sqlite3ExprIsConstant(pExpr) ){
  136680. sqlite3ExprDelete(pParse->db, pExpr);
  136681. pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
  136682. }
  136683. return pExpr;
  136684. }
  136685. /*
  136686. ** Allocate and return a new Window object describing a Window Definition.
  136687. */
  136688. SQLITE_PRIVATE Window *sqlite3WindowAlloc(
  136689. Parse *pParse, /* Parsing context */
  136690. int eType, /* Frame type. TK_RANGE or TK_ROWS */
  136691. int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
  136692. Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
  136693. int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
  136694. Expr *pEnd /* End window size if TK_FOLLOWING or PRECEDING */
  136695. ){
  136696. Window *pWin = 0;
  136697. /* Parser assures the following: */
  136698. assert( eType==TK_RANGE || eType==TK_ROWS );
  136699. assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
  136700. || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
  136701. assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
  136702. || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
  136703. assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
  136704. assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
  136705. /* If a frame is declared "RANGE" (not "ROWS"), then it may not use
  136706. ** either "<expr> PRECEDING" or "<expr> FOLLOWING".
  136707. */
  136708. if( eType==TK_RANGE && (pStart!=0 || pEnd!=0) ){
  136709. sqlite3ErrorMsg(pParse, "RANGE must use only UNBOUNDED or CURRENT ROW");
  136710. goto windowAllocErr;
  136711. }
  136712. /* Additionally, the
  136713. ** starting boundary type may not occur earlier in the following list than
  136714. ** the ending boundary type:
  136715. **
  136716. ** UNBOUNDED PRECEDING
  136717. ** <expr> PRECEDING
  136718. ** CURRENT ROW
  136719. ** <expr> FOLLOWING
  136720. ** UNBOUNDED FOLLOWING
  136721. **
  136722. ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
  136723. ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
  136724. ** frame boundary.
  136725. */
  136726. if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
  136727. || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
  136728. ){
  136729. sqlite3ErrorMsg(pParse, "unsupported frame delimiter for ROWS");
  136730. goto windowAllocErr;
  136731. }
  136732. pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  136733. if( pWin==0 ) goto windowAllocErr;
  136734. pWin->eType = eType;
  136735. pWin->eStart = eStart;
  136736. pWin->eEnd = eEnd;
  136737. pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
  136738. pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
  136739. return pWin;
  136740. windowAllocErr:
  136741. sqlite3ExprDelete(pParse->db, pEnd);
  136742. sqlite3ExprDelete(pParse->db, pStart);
  136743. return 0;
  136744. }
  136745. /*
  136746. ** Attach window object pWin to expression p.
  136747. */
  136748. SQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
  136749. if( p ){
  136750. assert( p->op==TK_FUNCTION );
  136751. /* This routine is only called for the parser. If pWin was not
  136752. ** allocated due to an OOM, then the parser would fail before ever
  136753. ** invoking this routine */
  136754. if( ALWAYS(pWin) ){
  136755. p->y.pWin = pWin;
  136756. ExprSetProperty(p, EP_WinFunc);
  136757. pWin->pOwner = p;
  136758. if( p->flags & EP_Distinct ){
  136759. sqlite3ErrorMsg(pParse,
  136760. "DISTINCT is not supported for window functions");
  136761. }
  136762. }
  136763. }else{
  136764. sqlite3WindowDelete(pParse->db, pWin);
  136765. }
  136766. }
  136767. /*
  136768. ** Return 0 if the two window objects are identical, or non-zero otherwise.
  136769. ** Identical window objects can be processed in a single scan.
  136770. */
  136771. SQLITE_PRIVATE int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2){
  136772. if( p1->eType!=p2->eType ) return 1;
  136773. if( p1->eStart!=p2->eStart ) return 1;
  136774. if( p1->eEnd!=p2->eEnd ) return 1;
  136775. if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
  136776. if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
  136777. if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
  136778. if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
  136779. return 0;
  136780. }
  136781. /*
  136782. ** This is called by code in select.c before it calls sqlite3WhereBegin()
  136783. ** to begin iterating through the sub-query results. It is used to allocate
  136784. ** and initialize registers and cursors used by sqlite3WindowCodeStep().
  136785. */
  136786. SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
  136787. Window *pWin;
  136788. Vdbe *v = sqlite3GetVdbe(pParse);
  136789. int nPart = (pMWin->pPartition ? pMWin->pPartition->nExpr : 0);
  136790. nPart += (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
  136791. if( nPart ){
  136792. pMWin->regPart = pParse->nMem+1;
  136793. pParse->nMem += nPart;
  136794. sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nPart-1);
  136795. }
  136796. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  136797. FuncDef *p = pWin->pFunc;
  136798. if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
  136799. /* The inline versions of min() and max() require a single ephemeral
  136800. ** table and 3 registers. The registers are used as follows:
  136801. **
  136802. ** regApp+0: slot to copy min()/max() argument to for MakeRecord
  136803. ** regApp+1: integer value used to ensure keys are unique
  136804. ** regApp+2: output of MakeRecord
  136805. */
  136806. ExprList *pList = pWin->pOwner->x.pList;
  136807. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
  136808. pWin->csrApp = pParse->nTab++;
  136809. pWin->regApp = pParse->nMem+1;
  136810. pParse->nMem += 3;
  136811. if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
  136812. assert( pKeyInfo->aSortOrder[0]==0 );
  136813. pKeyInfo->aSortOrder[0] = 1;
  136814. }
  136815. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
  136816. sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  136817. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  136818. }
  136819. else if( p->zName==nth_valueName || p->zName==first_valueName ){
  136820. /* Allocate two registers at pWin->regApp. These will be used to
  136821. ** store the start and end index of the current frame. */
  136822. assert( pMWin->iEphCsr );
  136823. pWin->regApp = pParse->nMem+1;
  136824. pWin->csrApp = pParse->nTab++;
  136825. pParse->nMem += 2;
  136826. sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
  136827. }
  136828. else if( p->zName==leadName || p->zName==lagName ){
  136829. assert( pMWin->iEphCsr );
  136830. pWin->csrApp = pParse->nTab++;
  136831. sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
  136832. }
  136833. }
  136834. }
  136835. /*
  136836. ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
  136837. ** value of the second argument to nth_value() (eCond==2) has just been
  136838. ** evaluated and the result left in register reg. This function generates VM
  136839. ** code to check that the value is a non-negative integer and throws an
  136840. ** exception if it is not.
  136841. */
  136842. static void windowCheckIntValue(Parse *pParse, int reg, int eCond){
  136843. static const char *azErr[] = {
  136844. "frame starting offset must be a non-negative integer",
  136845. "frame ending offset must be a non-negative integer",
  136846. "second argument to nth_value must be a positive integer"
  136847. };
  136848. static int aOp[] = { OP_Ge, OP_Ge, OP_Gt };
  136849. Vdbe *v = sqlite3GetVdbe(pParse);
  136850. int regZero = sqlite3GetTempReg(pParse);
  136851. assert( eCond==0 || eCond==1 || eCond==2 );
  136852. sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
  136853. sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
  136854. VdbeCoverageIf(v, eCond==0);
  136855. VdbeCoverageIf(v, eCond==1);
  136856. VdbeCoverageIf(v, eCond==2);
  136857. sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
  136858. VdbeCoverageNeverNullIf(v, eCond==0);
  136859. VdbeCoverageNeverNullIf(v, eCond==1);
  136860. VdbeCoverageNeverNullIf(v, eCond==2);
  136861. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
  136862. sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
  136863. sqlite3ReleaseTempReg(pParse, regZero);
  136864. }
  136865. /*
  136866. ** Return the number of arguments passed to the window-function associated
  136867. ** with the object passed as the only argument to this function.
  136868. */
  136869. static int windowArgCount(Window *pWin){
  136870. ExprList *pList = pWin->pOwner->x.pList;
  136871. return (pList ? pList->nExpr : 0);
  136872. }
  136873. /*
  136874. ** Generate VM code to invoke either xStep() (if bInverse is 0) or
  136875. ** xInverse (if bInverse is non-zero) for each window function in the
  136876. ** linked list starting at pMWin. Or, for built-in window functions
  136877. ** that do not use the standard function API, generate the required
  136878. ** inline VM code.
  136879. **
  136880. ** If argument csr is greater than or equal to 0, then argument reg is
  136881. ** the first register in an array of registers guaranteed to be large
  136882. ** enough to hold the array of arguments for each function. In this case
  136883. ** the arguments are extracted from the current row of csr into the
  136884. ** array of registers before invoking OP_AggStep or OP_AggInverse
  136885. **
  136886. ** Or, if csr is less than zero, then the array of registers at reg is
  136887. ** already populated with all columns from the current row of the sub-query.
  136888. **
  136889. ** If argument regPartSize is non-zero, then it is a register containing the
  136890. ** number of rows in the current partition.
  136891. */
  136892. static void windowAggStep(
  136893. Parse *pParse,
  136894. Window *pMWin, /* Linked list of window functions */
  136895. int csr, /* Read arguments from this cursor */
  136896. int bInverse, /* True to invoke xInverse instead of xStep */
  136897. int reg, /* Array of registers */
  136898. int regPartSize /* Register containing size of partition */
  136899. ){
  136900. Vdbe *v = sqlite3GetVdbe(pParse);
  136901. Window *pWin;
  136902. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  136903. int flags = pWin->pFunc->funcFlags;
  136904. int regArg;
  136905. int nArg = windowArgCount(pWin);
  136906. if( csr>=0 ){
  136907. int i;
  136908. for(i=0; i<nArg; i++){
  136909. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
  136910. }
  136911. regArg = reg;
  136912. if( flags & SQLITE_FUNC_WINDOW_SIZE ){
  136913. if( nArg==0 ){
  136914. regArg = regPartSize;
  136915. }else{
  136916. sqlite3VdbeAddOp2(v, OP_SCopy, regPartSize, reg+nArg);
  136917. }
  136918. nArg++;
  136919. }
  136920. }else{
  136921. assert( !(flags & SQLITE_FUNC_WINDOW_SIZE) );
  136922. regArg = reg + pWin->iArgCol;
  136923. }
  136924. if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
  136925. && pWin->eStart!=TK_UNBOUNDED
  136926. ){
  136927. int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
  136928. VdbeCoverage(v);
  136929. if( bInverse==0 ){
  136930. sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
  136931. sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
  136932. sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
  136933. sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
  136934. }else{
  136935. sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
  136936. VdbeCoverageNeverTaken(v);
  136937. sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
  136938. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  136939. }
  136940. sqlite3VdbeJumpHere(v, addrIsNull);
  136941. }else if( pWin->regApp ){
  136942. assert( pWin->pFunc->zName==nth_valueName
  136943. || pWin->pFunc->zName==first_valueName
  136944. );
  136945. assert( bInverse==0 || bInverse==1 );
  136946. sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
  136947. }else if( pWin->pFunc->zName==leadName
  136948. || pWin->pFunc->zName==lagName
  136949. ){
  136950. /* no-op */
  136951. }else{
  136952. int addrIf = 0;
  136953. if( pWin->pFilter ){
  136954. int regTmp;
  136955. assert( nArg==0 || nArg==pWin->pOwner->x.pList->nExpr );
  136956. assert( nArg || pWin->pOwner->x.pList==0 );
  136957. if( csr>0 ){
  136958. regTmp = sqlite3GetTempReg(pParse);
  136959. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
  136960. }else{
  136961. regTmp = regArg + nArg;
  136962. }
  136963. addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
  136964. VdbeCoverage(v);
  136965. if( csr>0 ){
  136966. sqlite3ReleaseTempReg(pParse, regTmp);
  136967. }
  136968. }
  136969. if( pWin->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  136970. CollSeq *pColl;
  136971. assert( nArg>0 );
  136972. pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
  136973. sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
  136974. }
  136975. sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
  136976. bInverse, regArg, pWin->regAccum);
  136977. sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
  136978. sqlite3VdbeChangeP5(v, (u8)nArg);
  136979. if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
  136980. }
  136981. }
  136982. }
  136983. /*
  136984. ** Generate VM code to invoke either xValue() (bFinal==0) or xFinalize()
  136985. ** (bFinal==1) for each window function in the linked list starting at
  136986. ** pMWin. Or, for built-in window-functions that do not use the standard
  136987. ** API, generate the equivalent VM code.
  136988. */
  136989. static void windowAggFinal(Parse *pParse, Window *pMWin, int bFinal){
  136990. Vdbe *v = sqlite3GetVdbe(pParse);
  136991. Window *pWin;
  136992. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  136993. if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
  136994. && pWin->eStart!=TK_UNBOUNDED
  136995. ){
  136996. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  136997. sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
  136998. VdbeCoverage(v);
  136999. sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
  137000. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  137001. if( bFinal ){
  137002. sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
  137003. }
  137004. }else if( pWin->regApp ){
  137005. }else{
  137006. if( bFinal ){
  137007. sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, windowArgCount(pWin));
  137008. sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
  137009. sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
  137010. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  137011. }else{
  137012. sqlite3VdbeAddOp3(v, OP_AggValue, pWin->regAccum, windowArgCount(pWin),
  137013. pWin->regResult);
  137014. sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
  137015. }
  137016. }
  137017. }
  137018. }
  137019. /*
  137020. ** This function generates VM code to invoke the sub-routine at address
  137021. ** lblFlushPart once for each partition with the entire partition cached in
  137022. ** the Window.iEphCsr temp table.
  137023. */
  137024. static void windowPartitionCache(
  137025. Parse *pParse,
  137026. Select *p, /* The rewritten SELECT statement */
  137027. WhereInfo *pWInfo, /* WhereInfo to call WhereEnd() on */
  137028. int regFlushPart, /* Register to use with Gosub lblFlushPart */
  137029. int lblFlushPart, /* Subroutine to Gosub to */
  137030. int *pRegSize /* OUT: Register containing partition size */
  137031. ){
  137032. Window *pMWin = p->pWin;
  137033. Vdbe *v = sqlite3GetVdbe(pParse);
  137034. int iSubCsr = p->pSrc->a[0].iCursor;
  137035. int nSub = p->pSrc->a[0].pTab->nCol;
  137036. int k;
  137037. int reg = pParse->nMem+1;
  137038. int regRecord = reg+nSub;
  137039. int regRowid = regRecord+1;
  137040. *pRegSize = regRowid;
  137041. pParse->nMem += nSub + 2;
  137042. /* Load the column values for the row returned by the sub-select
  137043. ** into an array of registers starting at reg. */
  137044. for(k=0; k<nSub; k++){
  137045. sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k);
  137046. }
  137047. sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, nSub, regRecord);
  137048. /* Check if this is the start of a new partition. If so, call the
  137049. ** flush_partition sub-routine. */
  137050. if( pMWin->pPartition ){
  137051. int addr;
  137052. ExprList *pPart = pMWin->pPartition;
  137053. int nPart = pPart->nExpr;
  137054. int regNewPart = reg + pMWin->nBufferCol;
  137055. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
  137056. addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart);
  137057. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  137058. sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
  137059. VdbeCoverageEqNe(v);
  137060. sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
  137061. sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart);
  137062. VdbeComment((v, "call flush_partition"));
  137063. }
  137064. /* Buffer the current row in the ephemeral table. */
  137065. sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid);
  137066. sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid);
  137067. /* End of the input loop */
  137068. sqlite3WhereEnd(pWInfo);
  137069. /* Invoke "flush_partition" to deal with the final (or only) partition */
  137070. sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart);
  137071. VdbeComment((v, "call flush_partition"));
  137072. }
  137073. /*
  137074. ** Invoke the sub-routine at regGosub (generated by code in select.c) to
  137075. ** return the current row of Window.iEphCsr. If all window functions are
  137076. ** aggregate window functions that use the standard API, a single
  137077. ** OP_Gosub instruction is all that this routine generates. Extra VM code
  137078. ** for per-row processing is only generated for the following built-in window
  137079. ** functions:
  137080. **
  137081. ** nth_value()
  137082. ** first_value()
  137083. ** lag()
  137084. ** lead()
  137085. */
  137086. static void windowReturnOneRow(
  137087. Parse *pParse,
  137088. Window *pMWin,
  137089. int regGosub,
  137090. int addrGosub
  137091. ){
  137092. Vdbe *v = sqlite3GetVdbe(pParse);
  137093. Window *pWin;
  137094. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  137095. FuncDef *pFunc = pWin->pFunc;
  137096. if( pFunc->zName==nth_valueName
  137097. || pFunc->zName==first_valueName
  137098. ){
  137099. int csr = pWin->csrApp;
  137100. int lbl = sqlite3VdbeMakeLabel(v);
  137101. int tmpReg = sqlite3GetTempReg(pParse);
  137102. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  137103. if( pFunc->zName==nth_valueName ){
  137104. sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+1,tmpReg);
  137105. windowCheckIntValue(pParse, tmpReg, 2);
  137106. }else{
  137107. sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
  137108. }
  137109. sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
  137110. sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
  137111. VdbeCoverageNeverNull(v);
  137112. sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
  137113. VdbeCoverageNeverTaken(v);
  137114. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
  137115. sqlite3VdbeResolveLabel(v, lbl);
  137116. sqlite3ReleaseTempReg(pParse, tmpReg);
  137117. }
  137118. else if( pFunc->zName==leadName || pFunc->zName==lagName ){
  137119. int nArg = pWin->pOwner->x.pList->nExpr;
  137120. int iEph = pMWin->iEphCsr;
  137121. int csr = pWin->csrApp;
  137122. int lbl = sqlite3VdbeMakeLabel(v);
  137123. int tmpReg = sqlite3GetTempReg(pParse);
  137124. if( nArg<3 ){
  137125. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  137126. }else{
  137127. sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+2, pWin->regResult);
  137128. }
  137129. sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
  137130. if( nArg<2 ){
  137131. int val = (pFunc->zName==leadName ? 1 : -1);
  137132. sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
  137133. }else{
  137134. int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
  137135. int tmpReg2 = sqlite3GetTempReg(pParse);
  137136. sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
  137137. sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
  137138. sqlite3ReleaseTempReg(pParse, tmpReg2);
  137139. }
  137140. sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
  137141. VdbeCoverage(v);
  137142. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
  137143. sqlite3VdbeResolveLabel(v, lbl);
  137144. sqlite3ReleaseTempReg(pParse, tmpReg);
  137145. }
  137146. }
  137147. sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
  137148. }
  137149. /*
  137150. ** Invoke the code generated by windowReturnOneRow() and, optionally, the
  137151. ** xInverse() function for each window function, for one or more rows
  137152. ** from the Window.iEphCsr temp table. This routine generates VM code
  137153. ** similar to:
  137154. **
  137155. ** while( regCtr>0 ){
  137156. ** regCtr--;
  137157. ** windowReturnOneRow()
  137158. ** if( bInverse ){
  137159. ** AggInverse
  137160. ** }
  137161. ** Next (Window.iEphCsr)
  137162. ** }
  137163. */
  137164. static void windowReturnRows(
  137165. Parse *pParse,
  137166. Window *pMWin, /* List of window functions */
  137167. int regCtr, /* Register containing number of rows */
  137168. int regGosub, /* Register for Gosub addrGosub */
  137169. int addrGosub, /* Address of sub-routine for ReturnOneRow */
  137170. int regInvArg, /* Array of registers for xInverse args */
  137171. int regInvSize /* Register containing size of partition */
  137172. ){
  137173. int addr;
  137174. Vdbe *v = sqlite3GetVdbe(pParse);
  137175. windowAggFinal(pParse, pMWin, 0);
  137176. addr = sqlite3VdbeAddOp3(v, OP_IfPos, regCtr, sqlite3VdbeCurrentAddr(v)+2 ,1);
  137177. VdbeCoverage(v);
  137178. sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  137179. windowReturnOneRow(pParse, pMWin, regGosub, addrGosub);
  137180. if( regInvArg ){
  137181. windowAggStep(pParse, pMWin, pMWin->iEphCsr, 1, regInvArg, regInvSize);
  137182. }
  137183. sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, addr);
  137184. VdbeCoverage(v);
  137185. sqlite3VdbeJumpHere(v, addr+1); /* The OP_Goto */
  137186. }
  137187. /*
  137188. ** Generate code to set the accumulator register for each window function
  137189. ** in the linked list passed as the second argument to NULL. And perform
  137190. ** any equivalent initialization required by any built-in window functions
  137191. ** in the list.
  137192. */
  137193. static int windowInitAccum(Parse *pParse, Window *pMWin){
  137194. Vdbe *v = sqlite3GetVdbe(pParse);
  137195. int regArg;
  137196. int nArg = 0;
  137197. Window *pWin;
  137198. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  137199. FuncDef *pFunc = pWin->pFunc;
  137200. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  137201. nArg = MAX(nArg, windowArgCount(pWin));
  137202. if( pFunc->zName==nth_valueName
  137203. || pFunc->zName==first_valueName
  137204. ){
  137205. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
  137206. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  137207. }
  137208. if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
  137209. assert( pWin->eStart!=TK_UNBOUNDED );
  137210. sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
  137211. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  137212. }
  137213. }
  137214. regArg = pParse->nMem+1;
  137215. pParse->nMem += nArg;
  137216. return regArg;
  137217. }
  137218. /*
  137219. ** This function does the work of sqlite3WindowCodeStep() for all "ROWS"
  137220. ** window frame types except for "BETWEEN UNBOUNDED PRECEDING AND CURRENT
  137221. ** ROW". Pseudo-code for each follows.
  137222. **
  137223. ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
  137224. **
  137225. ** ...
  137226. ** if( new partition ){
  137227. ** Gosub flush_partition
  137228. ** }
  137229. ** Insert (record in eph-table)
  137230. ** sqlite3WhereEnd()
  137231. ** Gosub flush_partition
  137232. **
  137233. ** flush_partition:
  137234. ** Once {
  137235. ** OpenDup (iEphCsr -> csrStart)
  137236. ** OpenDup (iEphCsr -> csrEnd)
  137237. ** }
  137238. ** regStart = <expr1> // PRECEDING expression
  137239. ** regEnd = <expr2> // FOLLOWING expression
  137240. ** if( regStart<0 || regEnd<0 ){ error! }
  137241. ** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
  137242. ** Next(csrEnd) // if EOF skip Aggstep
  137243. ** Aggstep (csrEnd)
  137244. ** if( (regEnd--)<=0 ){
  137245. ** AggFinal (xValue)
  137246. ** Gosub addrGosub
  137247. ** Next(csr) // if EOF goto flush_partition_done
  137248. ** if( (regStart--)<=0 ){
  137249. ** AggInverse (csrStart)
  137250. ** Next(csrStart)
  137251. ** }
  137252. ** }
  137253. ** flush_partition_done:
  137254. ** ResetSorter (csr)
  137255. ** Return
  137256. **
  137257. ** ROWS BETWEEN <expr> PRECEDING AND CURRENT ROW
  137258. ** ROWS BETWEEN CURRENT ROW AND <expr> FOLLOWING
  137259. ** ROWS BETWEEN UNBOUNDED PRECEDING AND <expr> FOLLOWING
  137260. **
  137261. ** These are similar to the above. For "CURRENT ROW", intialize the
  137262. ** register to 0. For "UNBOUNDED PRECEDING" to infinity.
  137263. **
  137264. ** ROWS BETWEEN <expr> PRECEDING AND UNBOUNDED FOLLOWING
  137265. ** ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
  137266. **
  137267. ** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
  137268. ** while( 1 ){
  137269. ** Next(csrEnd) // Exit while(1) at EOF
  137270. ** Aggstep (csrEnd)
  137271. ** }
  137272. ** while( 1 ){
  137273. ** AggFinal (xValue)
  137274. ** Gosub addrGosub
  137275. ** Next(csr) // if EOF goto flush_partition_done
  137276. ** if( (regStart--)<=0 ){
  137277. ** AggInverse (csrStart)
  137278. ** Next(csrStart)
  137279. ** }
  137280. ** }
  137281. **
  137282. ** For the "CURRENT ROW AND UNBOUNDED FOLLOWING" case, the final if()
  137283. ** condition is always true (as if regStart were initialized to 0).
  137284. **
  137285. ** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
  137286. **
  137287. ** This is the only RANGE case handled by this routine. It modifies the
  137288. ** second while( 1 ) loop in "ROWS BETWEEN CURRENT ... UNBOUNDED..." to
  137289. ** be:
  137290. **
  137291. ** while( 1 ){
  137292. ** AggFinal (xValue)
  137293. ** while( 1 ){
  137294. ** regPeer++
  137295. ** Gosub addrGosub
  137296. ** Next(csr) // if EOF goto flush_partition_done
  137297. ** if( new peer ) break;
  137298. ** }
  137299. ** while( (regPeer--)>0 ){
  137300. ** AggInverse (csrStart)
  137301. ** Next(csrStart)
  137302. ** }
  137303. ** }
  137304. **
  137305. ** ROWS BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING
  137306. **
  137307. ** regEnd = regEnd - regStart
  137308. ** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
  137309. ** Aggstep (csrEnd)
  137310. ** Next(csrEnd) // if EOF fall-through
  137311. ** if( (regEnd--)<=0 ){
  137312. ** if( (regStart--)<=0 ){
  137313. ** AggFinal (xValue)
  137314. ** Gosub addrGosub
  137315. ** Next(csr) // if EOF goto flush_partition_done
  137316. ** }
  137317. ** AggInverse (csrStart)
  137318. ** Next (csrStart)
  137319. ** }
  137320. **
  137321. ** ROWS BETWEEN <expr> PRECEDING AND <expr> PRECEDING
  137322. **
  137323. ** Replace the bit after "Rewind" in the above with:
  137324. **
  137325. ** if( (regEnd--)<=0 ){
  137326. ** AggStep (csrEnd)
  137327. ** Next (csrEnd)
  137328. ** }
  137329. ** AggFinal (xValue)
  137330. ** Gosub addrGosub
  137331. ** Next(csr) // if EOF goto flush_partition_done
  137332. ** if( (regStart--)<=0 ){
  137333. ** AggInverse (csr2)
  137334. ** Next (csr2)
  137335. ** }
  137336. **
  137337. */
  137338. static void windowCodeRowExprStep(
  137339. Parse *pParse,
  137340. Select *p,
  137341. WhereInfo *pWInfo,
  137342. int regGosub,
  137343. int addrGosub
  137344. ){
  137345. Window *pMWin = p->pWin;
  137346. Vdbe *v = sqlite3GetVdbe(pParse);
  137347. int regFlushPart; /* Register for "Gosub flush_partition" */
  137348. int lblFlushPart; /* Label for "Gosub flush_partition" */
  137349. int lblFlushDone; /* Label for "Gosub flush_partition_done" */
  137350. int regArg;
  137351. int addr;
  137352. int csrStart = pParse->nTab++;
  137353. int csrEnd = pParse->nTab++;
  137354. int regStart; /* Value of <expr> PRECEDING */
  137355. int regEnd; /* Value of <expr> FOLLOWING */
  137356. int addrGoto;
  137357. int addrTop;
  137358. int addrIfPos1 = 0;
  137359. int addrIfPos2 = 0;
  137360. int regSize = 0;
  137361. assert( pMWin->eStart==TK_PRECEDING
  137362. || pMWin->eStart==TK_CURRENT
  137363. || pMWin->eStart==TK_FOLLOWING
  137364. || pMWin->eStart==TK_UNBOUNDED
  137365. );
  137366. assert( pMWin->eEnd==TK_FOLLOWING
  137367. || pMWin->eEnd==TK_CURRENT
  137368. || pMWin->eEnd==TK_UNBOUNDED
  137369. || pMWin->eEnd==TK_PRECEDING
  137370. );
  137371. /* Allocate register and label for the "flush_partition" sub-routine. */
  137372. regFlushPart = ++pParse->nMem;
  137373. lblFlushPart = sqlite3VdbeMakeLabel(v);
  137374. lblFlushDone = sqlite3VdbeMakeLabel(v);
  137375. regStart = ++pParse->nMem;
  137376. regEnd = ++pParse->nMem;
  137377. windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, &regSize);
  137378. addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
  137379. /* Start of "flush_partition" */
  137380. sqlite3VdbeResolveLabel(v, lblFlushPart);
  137381. sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+3);
  137382. VdbeCoverage(v);
  137383. VdbeComment((v, "Flush_partition subroutine"));
  137384. sqlite3VdbeAddOp2(v, OP_OpenDup, csrStart, pMWin->iEphCsr);
  137385. sqlite3VdbeAddOp2(v, OP_OpenDup, csrEnd, pMWin->iEphCsr);
  137386. /* If either regStart or regEnd are not non-negative integers, throw
  137387. ** an exception. */
  137388. if( pMWin->pStart ){
  137389. sqlite3ExprCode(pParse, pMWin->pStart, regStart);
  137390. windowCheckIntValue(pParse, regStart, 0);
  137391. }
  137392. if( pMWin->pEnd ){
  137393. sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
  137394. windowCheckIntValue(pParse, regEnd, 1);
  137395. }
  137396. /* If this is "ROWS <expr1> FOLLOWING AND ROWS <expr2> FOLLOWING", do:
  137397. **
  137398. ** if( regEnd<regStart ){
  137399. ** // The frame always consists of 0 rows
  137400. ** regStart = regSize;
  137401. ** }
  137402. ** regEnd = regEnd - regStart;
  137403. */
  137404. if( pMWin->pEnd && pMWin->eStart==TK_FOLLOWING ){
  137405. assert( pMWin->pStart!=0 );
  137406. assert( pMWin->eEnd==TK_FOLLOWING );
  137407. sqlite3VdbeAddOp3(v, OP_Ge, regStart, sqlite3VdbeCurrentAddr(v)+2, regEnd);
  137408. VdbeCoverageNeverNull(v);
  137409. sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart);
  137410. sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regEnd);
  137411. }
  137412. if( pMWin->pStart && pMWin->eEnd==TK_PRECEDING ){
  137413. assert( pMWin->pEnd!=0 );
  137414. assert( pMWin->eStart==TK_PRECEDING );
  137415. sqlite3VdbeAddOp3(v, OP_Le, regStart, sqlite3VdbeCurrentAddr(v)+3, regEnd);
  137416. VdbeCoverageNeverNull(v);
  137417. sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart);
  137418. sqlite3VdbeAddOp2(v, OP_Copy, regSize, regEnd);
  137419. }
  137420. /* Initialize the accumulator register for each window function to NULL */
  137421. regArg = windowInitAccum(pParse, pMWin);
  137422. sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblFlushDone);
  137423. VdbeCoverage(v);
  137424. sqlite3VdbeAddOp2(v, OP_Rewind, csrStart, lblFlushDone);
  137425. VdbeCoverageNeverTaken(v);
  137426. sqlite3VdbeChangeP5(v, 1);
  137427. sqlite3VdbeAddOp2(v, OP_Rewind, csrEnd, lblFlushDone);
  137428. VdbeCoverageNeverTaken(v);
  137429. sqlite3VdbeChangeP5(v, 1);
  137430. /* Invoke AggStep function for each window function using the row that
  137431. ** csrEnd currently points to. Or, if csrEnd is already at EOF,
  137432. ** do nothing. */
  137433. addrTop = sqlite3VdbeCurrentAddr(v);
  137434. if( pMWin->eEnd==TK_PRECEDING ){
  137435. addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1);
  137436. VdbeCoverage(v);
  137437. }
  137438. sqlite3VdbeAddOp2(v, OP_Next, csrEnd, sqlite3VdbeCurrentAddr(v)+2);
  137439. VdbeCoverage(v);
  137440. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  137441. windowAggStep(pParse, pMWin, csrEnd, 0, regArg, regSize);
  137442. if( pMWin->eEnd==TK_UNBOUNDED ){
  137443. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  137444. sqlite3VdbeJumpHere(v, addr);
  137445. addrTop = sqlite3VdbeCurrentAddr(v);
  137446. }else{
  137447. sqlite3VdbeJumpHere(v, addr);
  137448. if( pMWin->eEnd==TK_PRECEDING ){
  137449. sqlite3VdbeJumpHere(v, addrIfPos1);
  137450. }
  137451. }
  137452. if( pMWin->eEnd==TK_FOLLOWING ){
  137453. addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1);
  137454. VdbeCoverage(v);
  137455. }
  137456. if( pMWin->eStart==TK_FOLLOWING ){
  137457. addrIfPos2 = sqlite3VdbeAddOp3(v, OP_IfPos, regStart, 0 , 1);
  137458. VdbeCoverage(v);
  137459. }
  137460. windowAggFinal(pParse, pMWin, 0);
  137461. windowReturnOneRow(pParse, pMWin, regGosub, addrGosub);
  137462. sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)+2);
  137463. VdbeCoverage(v);
  137464. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblFlushDone);
  137465. if( pMWin->eStart==TK_FOLLOWING ){
  137466. sqlite3VdbeJumpHere(v, addrIfPos2);
  137467. }
  137468. if( pMWin->eStart==TK_CURRENT
  137469. || pMWin->eStart==TK_PRECEDING
  137470. || pMWin->eStart==TK_FOLLOWING
  137471. ){
  137472. int lblSkipInverse = sqlite3VdbeMakeLabel(v);;
  137473. if( pMWin->eStart==TK_PRECEDING ){
  137474. sqlite3VdbeAddOp3(v, OP_IfPos, regStart, lblSkipInverse, 1);
  137475. VdbeCoverage(v);
  137476. }
  137477. if( pMWin->eStart==TK_FOLLOWING ){
  137478. sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+2);
  137479. VdbeCoverage(v);
  137480. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblSkipInverse);
  137481. }else{
  137482. sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+1);
  137483. VdbeCoverageAlwaysTaken(v);
  137484. }
  137485. windowAggStep(pParse, pMWin, csrStart, 1, regArg, regSize);
  137486. sqlite3VdbeResolveLabel(v, lblSkipInverse);
  137487. }
  137488. if( pMWin->eEnd==TK_FOLLOWING ){
  137489. sqlite3VdbeJumpHere(v, addrIfPos1);
  137490. }
  137491. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  137492. /* flush_partition_done: */
  137493. sqlite3VdbeResolveLabel(v, lblFlushDone);
  137494. sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
  137495. sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
  137496. VdbeComment((v, "end flush_partition subroutine"));
  137497. /* Jump to here to skip over flush_partition */
  137498. sqlite3VdbeJumpHere(v, addrGoto);
  137499. }
  137500. /*
  137501. ** This function does the work of sqlite3WindowCodeStep() for cases that
  137502. ** would normally be handled by windowCodeDefaultStep() when there are
  137503. ** one or more built-in window-functions that require the entire partition
  137504. ** to be cached in a temp table before any rows can be returned. Additionally.
  137505. ** "RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING" is always handled by
  137506. ** this function.
  137507. **
  137508. ** Pseudo-code corresponding to the VM code generated by this function
  137509. ** for each type of window follows.
  137510. **
  137511. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  137512. **
  137513. ** flush_partition:
  137514. ** Once {
  137515. ** OpenDup (iEphCsr -> csrLead)
  137516. ** }
  137517. ** Integer ctr 0
  137518. ** foreach row (csrLead){
  137519. ** if( new peer ){
  137520. ** AggFinal (xValue)
  137521. ** for(i=0; i<ctr; i++){
  137522. ** Gosub addrGosub
  137523. ** Next iEphCsr
  137524. ** }
  137525. ** Integer ctr 0
  137526. ** }
  137527. ** AggStep (csrLead)
  137528. ** Incr ctr
  137529. ** }
  137530. **
  137531. ** AggFinal (xFinalize)
  137532. ** for(i=0; i<ctr; i++){
  137533. ** Gosub addrGosub
  137534. ** Next iEphCsr
  137535. ** }
  137536. **
  137537. ** ResetSorter (csr)
  137538. ** Return
  137539. **
  137540. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  137541. **
  137542. ** As above, except that the "if( new peer )" branch is always taken.
  137543. **
  137544. ** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
  137545. **
  137546. ** As above, except that each of the for() loops becomes:
  137547. **
  137548. ** for(i=0; i<ctr; i++){
  137549. ** Gosub addrGosub
  137550. ** AggInverse (iEphCsr)
  137551. ** Next iEphCsr
  137552. ** }
  137553. **
  137554. ** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  137555. **
  137556. ** flush_partition:
  137557. ** Once {
  137558. ** OpenDup (iEphCsr -> csrLead)
  137559. ** }
  137560. ** foreach row (csrLead) {
  137561. ** AggStep (csrLead)
  137562. ** }
  137563. ** foreach row (iEphCsr) {
  137564. ** Gosub addrGosub
  137565. ** }
  137566. **
  137567. ** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
  137568. **
  137569. ** flush_partition:
  137570. ** Once {
  137571. ** OpenDup (iEphCsr -> csrLead)
  137572. ** }
  137573. ** foreach row (csrLead){
  137574. ** AggStep (csrLead)
  137575. ** }
  137576. ** Rewind (csrLead)
  137577. ** Integer ctr 0
  137578. ** foreach row (csrLead){
  137579. ** if( new peer ){
  137580. ** AggFinal (xValue)
  137581. ** for(i=0; i<ctr; i++){
  137582. ** Gosub addrGosub
  137583. ** AggInverse (iEphCsr)
  137584. ** Next iEphCsr
  137585. ** }
  137586. ** Integer ctr 0
  137587. ** }
  137588. ** Incr ctr
  137589. ** }
  137590. **
  137591. ** AggFinal (xFinalize)
  137592. ** for(i=0; i<ctr; i++){
  137593. ** Gosub addrGosub
  137594. ** Next iEphCsr
  137595. ** }
  137596. **
  137597. ** ResetSorter (csr)
  137598. ** Return
  137599. */
  137600. static void windowCodeCacheStep(
  137601. Parse *pParse,
  137602. Select *p,
  137603. WhereInfo *pWInfo,
  137604. int regGosub,
  137605. int addrGosub
  137606. ){
  137607. Window *pMWin = p->pWin;
  137608. Vdbe *v = sqlite3GetVdbe(pParse);
  137609. int k;
  137610. int addr;
  137611. ExprList *pPart = pMWin->pPartition;
  137612. ExprList *pOrderBy = pMWin->pOrderBy;
  137613. int nPeer = pOrderBy ? pOrderBy->nExpr : 0;
  137614. int regNewPeer;
  137615. int addrGoto; /* Address of Goto used to jump flush_par.. */
  137616. int addrNext; /* Jump here for next iteration of loop */
  137617. int regFlushPart;
  137618. int lblFlushPart;
  137619. int csrLead;
  137620. int regCtr;
  137621. int regArg; /* Register array to martial function args */
  137622. int regSize;
  137623. int lblEmpty;
  137624. int bReverse = pMWin->pOrderBy && pMWin->eStart==TK_CURRENT
  137625. && pMWin->eEnd==TK_UNBOUNDED;
  137626. assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
  137627. || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED)
  137628. || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT)
  137629. || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED)
  137630. );
  137631. lblEmpty = sqlite3VdbeMakeLabel(v);
  137632. regNewPeer = pParse->nMem+1;
  137633. pParse->nMem += nPeer;
  137634. /* Allocate register and label for the "flush_partition" sub-routine. */
  137635. regFlushPart = ++pParse->nMem;
  137636. lblFlushPart = sqlite3VdbeMakeLabel(v);
  137637. csrLead = pParse->nTab++;
  137638. regCtr = ++pParse->nMem;
  137639. windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, &regSize);
  137640. addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
  137641. /* Start of "flush_partition" */
  137642. sqlite3VdbeResolveLabel(v, lblFlushPart);
  137643. sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+2);
  137644. VdbeCoverage(v);
  137645. sqlite3VdbeAddOp2(v, OP_OpenDup, csrLead, pMWin->iEphCsr);
  137646. /* Initialize the accumulator register for each window function to NULL */
  137647. regArg = windowInitAccum(pParse, pMWin);
  137648. sqlite3VdbeAddOp2(v, OP_Integer, 0, regCtr);
  137649. sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty);
  137650. VdbeCoverage(v);
  137651. sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblEmpty);
  137652. VdbeCoverageNeverTaken(v);
  137653. if( bReverse ){
  137654. int addr2 = sqlite3VdbeCurrentAddr(v);
  137655. windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize);
  137656. sqlite3VdbeAddOp2(v, OP_Next, csrLead, addr2);
  137657. VdbeCoverage(v);
  137658. sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty);
  137659. VdbeCoverageNeverTaken(v);
  137660. }
  137661. addrNext = sqlite3VdbeCurrentAddr(v);
  137662. if( pOrderBy && (pMWin->eEnd==TK_CURRENT || pMWin->eStart==TK_CURRENT) ){
  137663. int bCurrent = (pMWin->eStart==TK_CURRENT);
  137664. int addrJump = 0; /* Address of OP_Jump below */
  137665. if( pMWin->eType==TK_RANGE ){
  137666. int iOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
  137667. int regPeer = pMWin->regPart + (pPart ? pPart->nExpr : 0);
  137668. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
  137669. for(k=0; k<nPeer; k++){
  137670. sqlite3VdbeAddOp3(v, OP_Column, csrLead, iOff+k, regNewPeer+k);
  137671. }
  137672. addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer);
  137673. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  137674. addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
  137675. VdbeCoverage(v);
  137676. sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, nPeer-1);
  137677. }
  137678. windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub,
  137679. (bCurrent ? regArg : 0), (bCurrent ? regSize : 0)
  137680. );
  137681. if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
  137682. }
  137683. if( bReverse==0 ){
  137684. windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize);
  137685. }
  137686. sqlite3VdbeAddOp2(v, OP_AddImm, regCtr, 1);
  137687. sqlite3VdbeAddOp2(v, OP_Next, csrLead, addrNext);
  137688. VdbeCoverage(v);
  137689. windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub, 0, 0);
  137690. sqlite3VdbeResolveLabel(v, lblEmpty);
  137691. sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
  137692. sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
  137693. /* Jump to here to skip over flush_partition */
  137694. sqlite3VdbeJumpHere(v, addrGoto);
  137695. }
  137696. /*
  137697. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  137698. **
  137699. ** ...
  137700. ** if( new partition ){
  137701. ** AggFinal (xFinalize)
  137702. ** Gosub addrGosub
  137703. ** ResetSorter eph-table
  137704. ** }
  137705. ** else if( new peer ){
  137706. ** AggFinal (xValue)
  137707. ** Gosub addrGosub
  137708. ** ResetSorter eph-table
  137709. ** }
  137710. ** AggStep
  137711. ** Insert (record into eph-table)
  137712. ** sqlite3WhereEnd()
  137713. ** AggFinal (xFinalize)
  137714. ** Gosub addrGosub
  137715. **
  137716. ** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  137717. **
  137718. ** As above, except take no action for a "new peer". Invoke
  137719. ** the sub-routine once only for each partition.
  137720. **
  137721. ** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
  137722. **
  137723. ** As above, except that the "new peer" condition is handled in the
  137724. ** same way as "new partition" (so there is no "else if" block).
  137725. **
  137726. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  137727. **
  137728. ** As above, except assume every row is a "new peer".
  137729. */
  137730. static void windowCodeDefaultStep(
  137731. Parse *pParse,
  137732. Select *p,
  137733. WhereInfo *pWInfo,
  137734. int regGosub,
  137735. int addrGosub
  137736. ){
  137737. Window *pMWin = p->pWin;
  137738. Vdbe *v = sqlite3GetVdbe(pParse);
  137739. int k;
  137740. int iSubCsr = p->pSrc->a[0].iCursor;
  137741. int nSub = p->pSrc->a[0].pTab->nCol;
  137742. int reg = pParse->nMem+1;
  137743. int regRecord = reg+nSub;
  137744. int regRowid = regRecord+1;
  137745. int addr;
  137746. ExprList *pPart = pMWin->pPartition;
  137747. ExprList *pOrderBy = pMWin->pOrderBy;
  137748. assert( pMWin->eType==TK_RANGE
  137749. || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
  137750. );
  137751. assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
  137752. || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED)
  137753. || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT)
  137754. || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED && !pOrderBy)
  137755. );
  137756. if( pMWin->eEnd==TK_UNBOUNDED ){
  137757. pOrderBy = 0;
  137758. }
  137759. pParse->nMem += nSub + 2;
  137760. /* Load the individual column values of the row returned by
  137761. ** the sub-select into an array of registers. */
  137762. for(k=0; k<nSub; k++){
  137763. sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k);
  137764. }
  137765. /* Check if this is the start of a new partition or peer group. */
  137766. if( pPart || pOrderBy ){
  137767. int nPart = (pPart ? pPart->nExpr : 0);
  137768. int addrGoto = 0;
  137769. int addrJump = 0;
  137770. int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
  137771. if( pPart ){
  137772. int regNewPart = reg + pMWin->nBufferCol;
  137773. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
  137774. addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart);
  137775. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  137776. addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
  137777. VdbeCoverageEqNe(v);
  137778. windowAggFinal(pParse, pMWin, 1);
  137779. if( pOrderBy ){
  137780. addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
  137781. }
  137782. }
  137783. if( pOrderBy ){
  137784. int regNewPeer = reg + pMWin->nBufferCol + nPart;
  137785. int regPeer = pMWin->regPart + nPart;
  137786. if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
  137787. if( pMWin->eType==TK_RANGE ){
  137788. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
  137789. addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer);
  137790. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  137791. addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
  137792. VdbeCoverage(v);
  137793. }else{
  137794. addrJump = 0;
  137795. }
  137796. windowAggFinal(pParse, pMWin, pMWin->eStart==TK_CURRENT);
  137797. if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
  137798. }
  137799. sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3);
  137800. VdbeCoverage(v);
  137801. sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
  137802. sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1);
  137803. VdbeCoverage(v);
  137804. sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
  137805. sqlite3VdbeAddOp3(
  137806. v, OP_Copy, reg+pMWin->nBufferCol, pMWin->regPart, nPart+nPeer-1
  137807. );
  137808. if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
  137809. }
  137810. /* Invoke step function for window functions */
  137811. windowAggStep(pParse, pMWin, -1, 0, reg, 0);
  137812. /* Buffer the current row in the ephemeral table. */
  137813. if( pMWin->nBufferCol>0 ){
  137814. sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, pMWin->nBufferCol, regRecord);
  137815. }else{
  137816. sqlite3VdbeAddOp2(v, OP_Blob, 0, regRecord);
  137817. sqlite3VdbeAppendP4(v, (void*)"", 0);
  137818. }
  137819. sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid);
  137820. sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid);
  137821. /* End the database scan loop. */
  137822. sqlite3WhereEnd(pWInfo);
  137823. windowAggFinal(pParse, pMWin, 1);
  137824. sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3);
  137825. VdbeCoverage(v);
  137826. sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
  137827. sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1);
  137828. VdbeCoverage(v);
  137829. }
  137830. /*
  137831. ** Allocate and return a duplicate of the Window object indicated by the
  137832. ** third argument. Set the Window.pOwner field of the new object to
  137833. ** pOwner.
  137834. */
  137835. SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
  137836. Window *pNew = 0;
  137837. if( ALWAYS(p) ){
  137838. pNew = sqlite3DbMallocZero(db, sizeof(Window));
  137839. if( pNew ){
  137840. pNew->zName = sqlite3DbStrDup(db, p->zName);
  137841. pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
  137842. pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
  137843. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
  137844. pNew->eType = p->eType;
  137845. pNew->eEnd = p->eEnd;
  137846. pNew->eStart = p->eStart;
  137847. pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
  137848. pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
  137849. pNew->pOwner = pOwner;
  137850. }
  137851. }
  137852. return pNew;
  137853. }
  137854. /*
  137855. ** Return a copy of the linked list of Window objects passed as the
  137856. ** second argument.
  137857. */
  137858. SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
  137859. Window *pWin;
  137860. Window *pRet = 0;
  137861. Window **pp = &pRet;
  137862. for(pWin=p; pWin; pWin=pWin->pNextWin){
  137863. *pp = sqlite3WindowDup(db, 0, pWin);
  137864. if( *pp==0 ) break;
  137865. pp = &((*pp)->pNextWin);
  137866. }
  137867. return pRet;
  137868. }
  137869. /*
  137870. ** sqlite3WhereBegin() has already been called for the SELECT statement
  137871. ** passed as the second argument when this function is invoked. It generates
  137872. ** code to populate the Window.regResult register for each window function and
  137873. ** invoke the sub-routine at instruction addrGosub once for each row.
  137874. ** This function calls sqlite3WhereEnd() before returning.
  137875. */
  137876. SQLITE_PRIVATE void sqlite3WindowCodeStep(
  137877. Parse *pParse, /* Parse context */
  137878. Select *p, /* Rewritten SELECT statement */
  137879. WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
  137880. int regGosub, /* Register for OP_Gosub */
  137881. int addrGosub /* OP_Gosub here to return each row */
  137882. ){
  137883. Window *pMWin = p->pWin;
  137884. /* There are three different functions that may be used to do the work
  137885. ** of this one, depending on the window frame and the specific built-in
  137886. ** window functions used (if any).
  137887. **
  137888. ** windowCodeRowExprStep() handles all "ROWS" window frames, except for:
  137889. **
  137890. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  137891. **
  137892. ** The exception is because windowCodeRowExprStep() implements all window
  137893. ** frame types by caching the entire partition in a temp table, and
  137894. ** "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" is easy enough to
  137895. ** implement without such a cache.
  137896. **
  137897. ** windowCodeCacheStep() is used for:
  137898. **
  137899. ** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
  137900. **
  137901. ** It is also used for anything not handled by windowCodeRowExprStep()
  137902. ** that invokes a built-in window function that requires the entire
  137903. ** partition to be cached in a temp table before any rows are returned
  137904. ** (e.g. nth_value() or percent_rank()).
  137905. **
  137906. ** Finally, assuming there is no built-in window function that requires
  137907. ** the partition to be cached, windowCodeDefaultStep() is used for:
  137908. **
  137909. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  137910. ** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  137911. ** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
  137912. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  137913. **
  137914. ** windowCodeDefaultStep() is the only one of the three functions that
  137915. ** does not cache each partition in a temp table before beginning to
  137916. ** return rows.
  137917. */
  137918. if( pMWin->eType==TK_ROWS
  137919. && (pMWin->eStart!=TK_UNBOUNDED||pMWin->eEnd!=TK_CURRENT||!pMWin->pOrderBy)
  137920. ){
  137921. VdbeModuleComment((pParse->pVdbe, "Begin RowExprStep()"));
  137922. windowCodeRowExprStep(pParse, p, pWInfo, regGosub, addrGosub);
  137923. }else{
  137924. Window *pWin;
  137925. int bCache = 0; /* True to use CacheStep() */
  137926. if( pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED ){
  137927. bCache = 1;
  137928. }else{
  137929. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  137930. FuncDef *pFunc = pWin->pFunc;
  137931. if( (pFunc->funcFlags & SQLITE_FUNC_WINDOW_SIZE)
  137932. || (pFunc->zName==nth_valueName)
  137933. || (pFunc->zName==first_valueName)
  137934. || (pFunc->zName==leadName)
  137935. || (pFunc->zName==lagName)
  137936. ){
  137937. bCache = 1;
  137938. break;
  137939. }
  137940. }
  137941. }
  137942. /* Otherwise, call windowCodeDefaultStep(). */
  137943. if( bCache ){
  137944. VdbeModuleComment((pParse->pVdbe, "Begin CacheStep()"));
  137945. windowCodeCacheStep(pParse, p, pWInfo, regGosub, addrGosub);
  137946. }else{
  137947. VdbeModuleComment((pParse->pVdbe, "Begin DefaultStep()"));
  137948. windowCodeDefaultStep(pParse, p, pWInfo, regGosub, addrGosub);
  137949. }
  137950. }
  137951. }
  137952. #endif /* SQLITE_OMIT_WINDOWFUNC */
  137953. /************** End of window.c **********************************************/
  137954. /************** Begin file parse.c *******************************************/
  137955. /*
  137956. ** 2000-05-29
  137957. **
  137958. ** The author disclaims copyright to this source code. In place of
  137959. ** a legal notice, here is a blessing:
  137960. **
  137961. ** May you do good and not evil.
  137962. ** May you find forgiveness for yourself and forgive others.
  137963. ** May you share freely, never taking more than you give.
  137964. **
  137965. *************************************************************************
  137966. ** Driver template for the LEMON parser generator.
  137967. **
  137968. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  137969. ** this template to construct a parser. The "lemon" program inserts text
  137970. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  137971. ** interstitial "-" characters) contained in this template is changed into
  137972. ** the value of the %name directive from the grammar. Otherwise, the content
  137973. ** of this template is copied straight through into the generate parser
  137974. ** source file.
  137975. **
  137976. ** The following is the concatenation of all %include directives from the
  137977. ** input grammar file:
  137978. */
  137979. /* #include <stdio.h> */
  137980. /* #include <assert.h> */
  137981. /************ Begin %include sections from the grammar ************************/
  137982. /* #include "sqliteInt.h" */
  137983. /*
  137984. ** Disable all error recovery processing in the parser push-down
  137985. ** automaton.
  137986. */
  137987. #define YYNOERRORRECOVERY 1
  137988. /*
  137989. ** Make yytestcase() the same as testcase()
  137990. */
  137991. #define yytestcase(X) testcase(X)
  137992. /*
  137993. ** Indicate that sqlite3ParserFree() will never be called with a null
  137994. ** pointer.
  137995. */
  137996. #define YYPARSEFREENEVERNULL 1
  137997. /*
  137998. ** In the amalgamation, the parse.c file generated by lemon and the
  137999. ** tokenize.c file are concatenated. In that case, sqlite3RunParser()
  138000. ** has access to the the size of the yyParser object and so the parser
  138001. ** engine can be allocated from stack. In that case, only the
  138002. ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
  138003. ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
  138004. ** omitted.
  138005. */
  138006. #ifdef SQLITE_AMALGAMATION
  138007. # define sqlite3Parser_ENGINEALWAYSONSTACK 1
  138008. #endif
  138009. /*
  138010. ** Alternative datatype for the argument to the malloc() routine passed
  138011. ** into sqlite3ParserAlloc(). The default is size_t.
  138012. */
  138013. #define YYMALLOCARGTYPE u64
  138014. /*
  138015. ** An instance of the following structure describes the event of a
  138016. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  138017. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  138018. **
  138019. ** UPDATE ON (a,b,c)
  138020. **
  138021. ** Then the "b" IdList records the list "a,b,c".
  138022. */
  138023. struct TrigEvent { int a; IdList * b; };
  138024. struct FrameBound { int eType; Expr *pExpr; };
  138025. /*
  138026. ** Disable lookaside memory allocation for objects that might be
  138027. ** shared across database connections.
  138028. */
  138029. static void disableLookaside(Parse *pParse){
  138030. pParse->disableLookaside++;
  138031. pParse->db->lookaside.bDisable++;
  138032. }
  138033. /*
  138034. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  138035. ** all elements in the list. And make sure list length does not exceed
  138036. ** SQLITE_LIMIT_COMPOUND_SELECT.
  138037. */
  138038. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  138039. if( p->pPrior ){
  138040. Select *pNext = 0, *pLoop;
  138041. int mxSelect, cnt = 0;
  138042. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  138043. pLoop->pNext = pNext;
  138044. pLoop->selFlags |= SF_Compound;
  138045. }
  138046. if( (p->selFlags & SF_MultiValue)==0 &&
  138047. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  138048. cnt>mxSelect
  138049. ){
  138050. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  138051. }
  138052. }
  138053. }
  138054. /* Construct a new Expr object from a single identifier. Use the
  138055. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  138056. ** that created the expression.
  138057. */
  138058. static Expr *tokenExpr(Parse *pParse, int op, Token t){
  138059. Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
  138060. if( p ){
  138061. /* memset(p, 0, sizeof(Expr)); */
  138062. p->op = (u8)op;
  138063. p->affinity = 0;
  138064. p->flags = EP_Leaf;
  138065. p->iAgg = -1;
  138066. p->pLeft = p->pRight = 0;
  138067. p->x.pList = 0;
  138068. p->pAggInfo = 0;
  138069. p->y.pTab = 0;
  138070. p->op2 = 0;
  138071. p->iTable = 0;
  138072. p->iColumn = 0;
  138073. p->u.zToken = (char*)&p[1];
  138074. memcpy(p->u.zToken, t.z, t.n);
  138075. p->u.zToken[t.n] = 0;
  138076. if( sqlite3Isquote(p->u.zToken[0]) ){
  138077. if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
  138078. sqlite3Dequote(p->u.zToken);
  138079. }
  138080. #if SQLITE_MAX_EXPR_DEPTH>0
  138081. p->nHeight = 1;
  138082. #endif
  138083. if( IN_RENAME_OBJECT ){
  138084. return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);
  138085. }
  138086. }
  138087. return p;
  138088. }
  138089. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  138090. ** unary TK_ISNULL or TK_NOTNULL expression. */
  138091. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  138092. sqlite3 *db = pParse->db;
  138093. if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){
  138094. pA->op = (u8)op;
  138095. sqlite3ExprDelete(db, pA->pRight);
  138096. pA->pRight = 0;
  138097. }
  138098. }
  138099. /* Add a single new term to an ExprList that is used to store a
  138100. ** list of identifiers. Report an error if the ID list contains
  138101. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  138102. ** error while parsing a legacy schema.
  138103. */
  138104. static ExprList *parserAddExprIdListTerm(
  138105. Parse *pParse,
  138106. ExprList *pPrior,
  138107. Token *pIdToken,
  138108. int hasCollate,
  138109. int sortOrder
  138110. ){
  138111. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  138112. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  138113. && pParse->db->init.busy==0
  138114. ){
  138115. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  138116. pIdToken->n, pIdToken->z);
  138117. }
  138118. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  138119. return p;
  138120. }
  138121. /**************** End of %include directives **********************************/
  138122. /* These constants specify the various numeric values for terminal symbols
  138123. ** in a format understandable to "makeheaders". This section is blank unless
  138124. ** "lemon" is run with the "-m" command-line option.
  138125. ***************** Begin makeheaders token definitions *************************/
  138126. /**************** End makeheaders token definitions ***************************/
  138127. /* The next sections is a series of control #defines.
  138128. ** various aspects of the generated parser.
  138129. ** YYCODETYPE is the data type used to store the integer codes
  138130. ** that represent terminal and non-terminal symbols.
  138131. ** "unsigned char" is used if there are fewer than
  138132. ** 256 symbols. Larger types otherwise.
  138133. ** YYNOCODE is a number of type YYCODETYPE that is not used for
  138134. ** any terminal or nonterminal symbol.
  138135. ** YYFALLBACK If defined, this indicates that one or more tokens
  138136. ** (also known as: "terminal symbols") have fall-back
  138137. ** values which should be used if the original symbol
  138138. ** would not parse. This permits keywords to sometimes
  138139. ** be used as identifiers, for example.
  138140. ** YYACTIONTYPE is the data type used for "action codes" - numbers
  138141. ** that indicate what to do in response to the next
  138142. ** token.
  138143. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
  138144. ** symbols. Background: A "minor type" is a semantic
  138145. ** value associated with a terminal or non-terminal
  138146. ** symbols. For example, for an "ID" terminal symbol,
  138147. ** the minor type might be the name of the identifier.
  138148. ** Each non-terminal can have a different minor type.
  138149. ** Terminal symbols all have the same minor type, though.
  138150. ** This macros defines the minor type for terminal
  138151. ** symbols.
  138152. ** YYMINORTYPE is the data type used for all minor types.
  138153. ** This is typically a union of many types, one of
  138154. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  138155. ** for terminal symbols is called "yy0".
  138156. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  138157. ** zero the stack is dynamically sized using realloc()
  138158. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  138159. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  138160. ** sqlite3ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
  138161. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  138162. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  138163. ** sqlite3ParserCTX_* As sqlite3ParserARG_ except for %extra_context
  138164. ** YYERRORSYMBOL is the code number of the error symbol. If not
  138165. ** defined, then do no error processing.
  138166. ** YYNSTATE the combined number of states.
  138167. ** YYNRULE the number of rules in the grammar
  138168. ** YYNTOKEN Number of terminal symbols
  138169. ** YY_MAX_SHIFT Maximum value for shift actions
  138170. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  138171. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  138172. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  138173. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  138174. ** YY_NO_ACTION The yy_action[] code for no-op
  138175. ** YY_MIN_REDUCE Minimum value for reduce actions
  138176. ** YY_MAX_REDUCE Maximum value for reduce actions
  138177. */
  138178. #ifndef INTERFACE
  138179. # define INTERFACE 1
  138180. #endif
  138181. /************* Begin control #defines *****************************************/
  138182. #define YYCODETYPE unsigned short int
  138183. #define YYNOCODE 277
  138184. #define YYACTIONTYPE unsigned short int
  138185. #define YYWILDCARD 91
  138186. #define sqlite3ParserTOKENTYPE Token
  138187. typedef union {
  138188. int yyinit;
  138189. sqlite3ParserTOKENTYPE yy0;
  138190. Expr* yy18;
  138191. struct TrigEvent yy34;
  138192. IdList* yy48;
  138193. int yy70;
  138194. struct {int value; int mask;} yy111;
  138195. struct FrameBound yy119;
  138196. SrcList* yy135;
  138197. TriggerStep* yy207;
  138198. Window* yy327;
  138199. Upsert* yy340;
  138200. const char* yy392;
  138201. ExprList* yy420;
  138202. With* yy449;
  138203. Select* yy489;
  138204. } YYMINORTYPE;
  138205. #ifndef YYSTACKDEPTH
  138206. #define YYSTACKDEPTH 100
  138207. #endif
  138208. #define sqlite3ParserARG_SDECL
  138209. #define sqlite3ParserARG_PDECL
  138210. #define sqlite3ParserARG_PARAM
  138211. #define sqlite3ParserARG_FETCH
  138212. #define sqlite3ParserARG_STORE
  138213. #define sqlite3ParserCTX_SDECL Parse *pParse;
  138214. #define sqlite3ParserCTX_PDECL ,Parse *pParse
  138215. #define sqlite3ParserCTX_PARAM ,pParse
  138216. #define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
  138217. #define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
  138218. #define YYFALLBACK 1
  138219. #define YYNSTATE 521
  138220. #define YYNRULE 367
  138221. #define YYNTOKEN 155
  138222. #define YY_MAX_SHIFT 520
  138223. #define YY_MIN_SHIFTREDUCE 756
  138224. #define YY_MAX_SHIFTREDUCE 1122
  138225. #define YY_ERROR_ACTION 1123
  138226. #define YY_ACCEPT_ACTION 1124
  138227. #define YY_NO_ACTION 1125
  138228. #define YY_MIN_REDUCE 1126
  138229. #define YY_MAX_REDUCE 1492
  138230. /************* End control #defines *******************************************/
  138231. #define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))
  138232. /* Define the yytestcase() macro to be a no-op if is not already defined
  138233. ** otherwise.
  138234. **
  138235. ** Applications can choose to define yytestcase() in the %include section
  138236. ** to a macro that can assist in verifying code coverage. For production
  138237. ** code the yytestcase() macro should be turned off. But it is useful
  138238. ** for testing.
  138239. */
  138240. #ifndef yytestcase
  138241. # define yytestcase(X)
  138242. #endif
  138243. /* Next are the tables used to determine what action to take based on the
  138244. ** current state and lookahead token. These tables are used to implement
  138245. ** functions that take a state number and lookahead value and return an
  138246. ** action integer.
  138247. **
  138248. ** Suppose the action integer is N. Then the action is determined as
  138249. ** follows
  138250. **
  138251. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  138252. ** token onto the stack and goto state N.
  138253. **
  138254. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  138255. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  138256. **
  138257. ** N == YY_ERROR_ACTION A syntax error has occurred.
  138258. **
  138259. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  138260. **
  138261. ** N == YY_NO_ACTION No such action. Denotes unused
  138262. ** slots in the yy_action[] table.
  138263. **
  138264. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  138265. ** and YY_MAX_REDUCE
  138266. **
  138267. ** The action table is constructed as a single large table named yy_action[].
  138268. ** Given state S and lookahead X, the action is computed as either:
  138269. **
  138270. ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
  138271. ** (B) N = yy_default[S]
  138272. **
  138273. ** The (A) formula is preferred. The B formula is used instead if
  138274. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X.
  138275. **
  138276. ** The formulas above are for computing the action when the lookahead is
  138277. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  138278. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  138279. ** the yy_shift_ofst[] array.
  138280. **
  138281. ** The following are the tables generated in this section:
  138282. **
  138283. ** yy_action[] A single table containing all actions.
  138284. ** yy_lookahead[] A table containing the lookahead for each entry in
  138285. ** yy_action. Used to detect hash collisions.
  138286. ** yy_shift_ofst[] For each state, the offset into yy_action for
  138287. ** shifting terminals.
  138288. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  138289. ** shifting non-terminals after a reduce.
  138290. ** yy_default[] Default action for each state.
  138291. **
  138292. *********** Begin parsing tables **********************************************/
  138293. #define YY_ACTTAB_COUNT (2009)
  138294. static const YYACTIONTYPE yy_action[] = {
  138295. /* 0 */ 368, 105, 102, 197, 105, 102, 197, 515, 1124, 1,
  138296. /* 10 */ 1, 520, 2, 1128, 515, 1192, 1171, 1456, 275, 370,
  138297. /* 20 */ 127, 1389, 1197, 1197, 1192, 1166, 178, 1205, 64, 64,
  138298. /* 30 */ 477, 887, 322, 428, 348, 37, 37, 808, 362, 888,
  138299. /* 40 */ 509, 509, 509, 112, 113, 103, 1100, 1100, 953, 956,
  138300. /* 50 */ 946, 946, 110, 110, 111, 111, 111, 111, 365, 252,
  138301. /* 60 */ 252, 515, 252, 252, 497, 515, 309, 515, 459, 515,
  138302. /* 70 */ 1079, 491, 512, 478, 6, 512, 809, 134, 498, 228,
  138303. /* 80 */ 194, 428, 37, 37, 515, 208, 64, 64, 64, 64,
  138304. /* 90 */ 13, 13, 109, 109, 109, 109, 108, 108, 107, 107,
  138305. /* 100 */ 107, 106, 401, 258, 381, 13, 13, 398, 397, 428,
  138306. /* 110 */ 252, 252, 370, 476, 405, 1104, 1079, 1080, 1081, 386,
  138307. /* 120 */ 1106, 390, 497, 512, 497, 1423, 1419, 304, 1105, 307,
  138308. /* 130 */ 1256, 496, 370, 499, 16, 16, 112, 113, 103, 1100,
  138309. /* 140 */ 1100, 953, 956, 946, 946, 110, 110, 111, 111, 111,
  138310. /* 150 */ 111, 262, 1107, 495, 1107, 401, 112, 113, 103, 1100,
  138311. /* 160 */ 1100, 953, 956, 946, 946, 110, 110, 111, 111, 111,
  138312. /* 170 */ 111, 129, 1425, 343, 1420, 339, 1059, 492, 1057, 263,
  138313. /* 180 */ 73, 105, 102, 197, 994, 109, 109, 109, 109, 108,
  138314. /* 190 */ 108, 107, 107, 107, 106, 401, 370, 111, 111, 111,
  138315. /* 200 */ 111, 104, 492, 89, 1432, 109, 109, 109, 109, 108,
  138316. /* 210 */ 108, 107, 107, 107, 106, 401, 111, 111, 111, 111,
  138317. /* 220 */ 112, 113, 103, 1100, 1100, 953, 956, 946, 946, 110,
  138318. /* 230 */ 110, 111, 111, 111, 111, 109, 109, 109, 109, 108,
  138319. /* 240 */ 108, 107, 107, 107, 106, 401, 114, 108, 108, 107,
  138320. /* 250 */ 107, 107, 106, 401, 109, 109, 109, 109, 108, 108,
  138321. /* 260 */ 107, 107, 107, 106, 401, 152, 399, 399, 399, 109,
  138322. /* 270 */ 109, 109, 109, 108, 108, 107, 107, 107, 106, 401,
  138323. /* 280 */ 178, 493, 1412, 434, 1037, 1486, 1079, 515, 1486, 370,
  138324. /* 290 */ 421, 297, 357, 412, 74, 1079, 109, 109, 109, 109,
  138325. /* 300 */ 108, 108, 107, 107, 107, 106, 401, 1413, 37, 37,
  138326. /* 310 */ 1431, 274, 506, 112, 113, 103, 1100, 1100, 953, 956,
  138327. /* 320 */ 946, 946, 110, 110, 111, 111, 111, 111, 1436, 520,
  138328. /* 330 */ 2, 1128, 1079, 1080, 1081, 430, 275, 1079, 127, 366,
  138329. /* 340 */ 933, 1079, 1080, 1081, 220, 1205, 913, 458, 455, 454,
  138330. /* 350 */ 392, 167, 515, 1035, 152, 445, 924, 453, 152, 874,
  138331. /* 360 */ 923, 289, 109, 109, 109, 109, 108, 108, 107, 107,
  138332. /* 370 */ 107, 106, 401, 13, 13, 261, 853, 252, 252, 227,
  138333. /* 380 */ 106, 401, 370, 1079, 1080, 1081, 311, 388, 1079, 296,
  138334. /* 390 */ 512, 923, 923, 925, 231, 323, 1255, 1388, 1423, 490,
  138335. /* 400 */ 274, 506, 12, 208, 274, 506, 112, 113, 103, 1100,
  138336. /* 410 */ 1100, 953, 956, 946, 946, 110, 110, 111, 111, 111,
  138337. /* 420 */ 111, 1440, 286, 1128, 288, 1079, 1097, 247, 275, 1098,
  138338. /* 430 */ 127, 387, 405, 389, 1079, 1080, 1081, 1205, 159, 238,
  138339. /* 440 */ 255, 321, 461, 316, 460, 225, 790, 105, 102, 197,
  138340. /* 450 */ 513, 314, 842, 842, 445, 109, 109, 109, 109, 108,
  138341. /* 460 */ 108, 107, 107, 107, 106, 401, 515, 514, 515, 252,
  138342. /* 470 */ 252, 1079, 1080, 1081, 435, 370, 1098, 933, 1460, 794,
  138343. /* 480 */ 274, 506, 512, 105, 102, 197, 336, 63, 63, 64,
  138344. /* 490 */ 64, 27, 790, 924, 287, 208, 1354, 923, 515, 112,
  138345. /* 500 */ 113, 103, 1100, 1100, 953, 956, 946, 946, 110, 110,
  138346. /* 510 */ 111, 111, 111, 111, 107, 107, 107, 106, 401, 49,
  138347. /* 520 */ 49, 515, 28, 1079, 405, 497, 421, 297, 923, 923,
  138348. /* 530 */ 925, 186, 468, 1079, 467, 999, 999, 442, 515, 1079,
  138349. /* 540 */ 334, 515, 45, 45, 1083, 342, 173, 168, 109, 109,
  138350. /* 550 */ 109, 109, 108, 108, 107, 107, 107, 106, 401, 13,
  138351. /* 560 */ 13, 205, 13, 13, 252, 252, 1195, 1195, 370, 1079,
  138352. /* 570 */ 1080, 1081, 787, 265, 5, 359, 494, 512, 469, 1079,
  138353. /* 580 */ 1080, 1081, 398, 397, 1079, 1079, 1080, 1081, 3, 282,
  138354. /* 590 */ 1079, 1083, 112, 113, 103, 1100, 1100, 953, 956, 946,
  138355. /* 600 */ 946, 110, 110, 111, 111, 111, 111, 252, 252, 1015,
  138356. /* 610 */ 220, 1079, 873, 458, 455, 454, 943, 943, 954, 957,
  138357. /* 620 */ 512, 252, 252, 453, 1016, 1079, 445, 1107, 1209, 1107,
  138358. /* 630 */ 1079, 1080, 1081, 515, 512, 426, 1079, 1080, 1081, 1017,
  138359. /* 640 */ 512, 109, 109, 109, 109, 108, 108, 107, 107, 107,
  138360. /* 650 */ 106, 401, 1052, 515, 50, 50, 515, 1079, 1080, 1081,
  138361. /* 660 */ 828, 370, 1051, 379, 411, 1064, 1358, 207, 408, 773,
  138362. /* 670 */ 829, 1079, 1080, 1081, 64, 64, 322, 64, 64, 1302,
  138363. /* 680 */ 947, 411, 410, 1358, 1360, 112, 113, 103, 1100, 1100,
  138364. /* 690 */ 953, 956, 946, 946, 110, 110, 111, 111, 111, 111,
  138365. /* 700 */ 294, 482, 515, 1037, 1487, 515, 434, 1487, 354, 1120,
  138366. /* 710 */ 483, 996, 913, 485, 466, 996, 132, 178, 33, 450,
  138367. /* 720 */ 1203, 136, 406, 64, 64, 479, 64, 64, 419, 369,
  138368. /* 730 */ 283, 1146, 252, 252, 109, 109, 109, 109, 108, 108,
  138369. /* 740 */ 107, 107, 107, 106, 401, 512, 224, 440, 411, 266,
  138370. /* 750 */ 1358, 266, 252, 252, 370, 296, 416, 284, 934, 396,
  138371. /* 760 */ 976, 470, 400, 252, 252, 512, 9, 473, 231, 500,
  138372. /* 770 */ 354, 1036, 1035, 1488, 355, 374, 512, 1121, 112, 113,
  138373. /* 780 */ 103, 1100, 1100, 953, 956, 946, 946, 110, 110, 111,
  138374. /* 790 */ 111, 111, 111, 252, 252, 1015, 515, 1347, 295, 252,
  138375. /* 800 */ 252, 252, 252, 1098, 375, 249, 512, 445, 872, 322,
  138376. /* 810 */ 1016, 480, 512, 195, 512, 434, 273, 15, 15, 515,
  138377. /* 820 */ 314, 515, 95, 515, 93, 1017, 367, 109, 109, 109,
  138378. /* 830 */ 109, 108, 108, 107, 107, 107, 106, 401, 515, 1121,
  138379. /* 840 */ 39, 39, 51, 51, 52, 52, 503, 370, 515, 1204,
  138380. /* 850 */ 1098, 918, 439, 341, 133, 436, 223, 222, 221, 53,
  138381. /* 860 */ 53, 322, 1400, 761, 762, 763, 515, 370, 88, 54,
  138382. /* 870 */ 54, 112, 113, 103, 1100, 1100, 953, 956, 946, 946,
  138383. /* 880 */ 110, 110, 111, 111, 111, 111, 407, 55, 55, 196,
  138384. /* 890 */ 515, 112, 113, 103, 1100, 1100, 953, 956, 946, 946,
  138385. /* 900 */ 110, 110, 111, 111, 111, 111, 135, 264, 1149, 376,
  138386. /* 910 */ 515, 40, 40, 515, 872, 515, 993, 515, 993, 116,
  138387. /* 920 */ 109, 109, 109, 109, 108, 108, 107, 107, 107, 106,
  138388. /* 930 */ 401, 41, 41, 515, 43, 43, 44, 44, 56, 56,
  138389. /* 940 */ 109, 109, 109, 109, 108, 108, 107, 107, 107, 106,
  138390. /* 950 */ 401, 515, 379, 515, 57, 57, 515, 799, 515, 379,
  138391. /* 960 */ 515, 445, 200, 515, 323, 515, 1397, 515, 1459, 515,
  138392. /* 970 */ 1287, 817, 58, 58, 14, 14, 515, 59, 59, 118,
  138393. /* 980 */ 118, 60, 60, 515, 46, 46, 61, 61, 62, 62,
  138394. /* 990 */ 47, 47, 515, 190, 189, 91, 515, 140, 140, 515,
  138395. /* 1000 */ 394, 515, 277, 1200, 141, 141, 515, 1115, 515, 992,
  138396. /* 1010 */ 515, 992, 515, 69, 69, 370, 278, 48, 48, 259,
  138397. /* 1020 */ 65, 65, 119, 119, 246, 246, 260, 66, 66, 120,
  138398. /* 1030 */ 120, 121, 121, 117, 117, 370, 515, 512, 383, 112,
  138399. /* 1040 */ 113, 103, 1100, 1100, 953, 956, 946, 946, 110, 110,
  138400. /* 1050 */ 111, 111, 111, 111, 515, 872, 515, 139, 139, 112,
  138401. /* 1060 */ 113, 103, 1100, 1100, 953, 956, 946, 946, 110, 110,
  138402. /* 1070 */ 111, 111, 111, 111, 1287, 138, 138, 125, 125, 515,
  138403. /* 1080 */ 12, 515, 281, 1287, 515, 445, 131, 1287, 109, 109,
  138404. /* 1090 */ 109, 109, 108, 108, 107, 107, 107, 106, 401, 515,
  138405. /* 1100 */ 124, 124, 122, 122, 515, 123, 123, 515, 109, 109,
  138406. /* 1110 */ 109, 109, 108, 108, 107, 107, 107, 106, 401, 515,
  138407. /* 1120 */ 68, 68, 463, 783, 515, 70, 70, 302, 67, 67,
  138408. /* 1130 */ 1032, 253, 253, 356, 1287, 191, 196, 1433, 465, 1301,
  138409. /* 1140 */ 38, 38, 384, 94, 512, 42, 42, 177, 848, 274,
  138410. /* 1150 */ 506, 385, 420, 847, 1356, 441, 508, 376, 377, 153,
  138411. /* 1160 */ 423, 872, 432, 370, 224, 251, 194, 887, 182, 293,
  138412. /* 1170 */ 783, 848, 88, 254, 466, 888, 847, 915, 807, 806,
  138413. /* 1180 */ 230, 1241, 910, 370, 17, 413, 797, 112, 113, 103,
  138414. /* 1190 */ 1100, 1100, 953, 956, 946, 946, 110, 110, 111, 111,
  138415. /* 1200 */ 111, 111, 395, 814, 815, 1175, 983, 112, 101, 103,
  138416. /* 1210 */ 1100, 1100, 953, 956, 946, 946, 110, 110, 111, 111,
  138417. /* 1220 */ 111, 111, 375, 422, 427, 429, 298, 230, 230, 88,
  138418. /* 1230 */ 1240, 451, 312, 797, 226, 88, 109, 109, 109, 109,
  138419. /* 1240 */ 108, 108, 107, 107, 107, 106, 401, 86, 433, 979,
  138420. /* 1250 */ 927, 881, 226, 983, 230, 415, 109, 109, 109, 109,
  138421. /* 1260 */ 108, 108, 107, 107, 107, 106, 401, 320, 845, 781,
  138422. /* 1270 */ 846, 100, 130, 100, 1403, 290, 370, 319, 1377, 1376,
  138423. /* 1280 */ 437, 1449, 299, 1237, 303, 306, 308, 310, 1188, 1174,
  138424. /* 1290 */ 1173, 1172, 315, 324, 325, 1228, 370, 927, 1249, 271,
  138425. /* 1300 */ 1286, 113, 103, 1100, 1100, 953, 956, 946, 946, 110,
  138426. /* 1310 */ 110, 111, 111, 111, 111, 1224, 1235, 502, 501, 1292,
  138427. /* 1320 */ 1221, 1155, 103, 1100, 1100, 953, 956, 946, 946, 110,
  138428. /* 1330 */ 110, 111, 111, 111, 111, 1148, 1137, 1136, 1138, 1443,
  138429. /* 1340 */ 446, 244, 184, 98, 507, 188, 4, 353, 327, 109,
  138430. /* 1350 */ 109, 109, 109, 108, 108, 107, 107, 107, 106, 401,
  138431. /* 1360 */ 510, 329, 331, 199, 414, 456, 292, 285, 318, 109,
  138432. /* 1370 */ 109, 109, 109, 108, 108, 107, 107, 107, 106, 401,
  138433. /* 1380 */ 11, 1271, 1279, 402, 361, 192, 1171, 1351, 431, 505,
  138434. /* 1390 */ 346, 1350, 333, 98, 507, 504, 4, 187, 1446, 1115,
  138435. /* 1400 */ 233, 1396, 155, 1394, 1112, 152, 72, 75, 378, 425,
  138436. /* 1410 */ 510, 165, 149, 157, 933, 1276, 86, 30, 1268, 417,
  138437. /* 1420 */ 96, 96, 8, 160, 161, 162, 163, 97, 418, 402,
  138438. /* 1430 */ 517, 516, 449, 402, 923, 210, 358, 424, 1282, 438,
  138439. /* 1440 */ 169, 214, 360, 1345, 80, 504, 31, 444, 1365, 301,
  138440. /* 1450 */ 245, 274, 506, 216, 174, 305, 488, 447, 217, 462,
  138441. /* 1460 */ 1139, 487, 218, 363, 933, 923, 923, 925, 926, 24,
  138442. /* 1470 */ 96, 96, 1191, 1190, 1189, 391, 1182, 97, 1163, 402,
  138443. /* 1480 */ 517, 516, 799, 364, 923, 1162, 317, 1161, 98, 507,
  138444. /* 1490 */ 1181, 4, 1458, 472, 393, 269, 270, 475, 481, 1232,
  138445. /* 1500 */ 85, 1233, 326, 328, 232, 510, 495, 1231, 330, 98,
  138446. /* 1510 */ 507, 1230, 4, 486, 335, 923, 923, 925, 926, 24,
  138447. /* 1520 */ 1435, 1068, 404, 181, 336, 256, 510, 115, 402, 332,
  138448. /* 1530 */ 352, 352, 351, 241, 349, 1214, 1414, 770, 338, 10,
  138449. /* 1540 */ 504, 340, 272, 92, 1331, 1213, 87, 183, 484, 402,
  138450. /* 1550 */ 201, 488, 280, 239, 344, 345, 489, 1145, 29, 933,
  138451. /* 1560 */ 279, 504, 1074, 518, 240, 96, 96, 242, 243, 519,
  138452. /* 1570 */ 1134, 1129, 97, 154, 402, 517, 516, 372, 373, 923,
  138453. /* 1580 */ 933, 142, 143, 128, 1381, 267, 96, 96, 852, 757,
  138454. /* 1590 */ 203, 144, 403, 97, 1382, 402, 517, 516, 204, 1380,
  138455. /* 1600 */ 923, 146, 1379, 1159, 1158, 71, 1156, 276, 202, 185,
  138456. /* 1610 */ 923, 923, 925, 926, 24, 198, 257, 126, 991, 989,
  138457. /* 1620 */ 907, 98, 507, 156, 4, 145, 158, 206, 831, 209,
  138458. /* 1630 */ 291, 923, 923, 925, 926, 24, 1005, 911, 510, 164,
  138459. /* 1640 */ 147, 380, 371, 382, 166, 76, 77, 274, 506, 148,
  138460. /* 1650 */ 78, 79, 1008, 211, 212, 1004, 137, 213, 18, 300,
  138461. /* 1660 */ 230, 402, 997, 1109, 443, 215, 32, 170, 171, 772,
  138462. /* 1670 */ 409, 448, 319, 504, 219, 172, 452, 81, 19, 457,
  138463. /* 1680 */ 313, 20, 82, 268, 488, 150, 810, 179, 83, 487,
  138464. /* 1690 */ 464, 151, 933, 180, 959, 84, 1040, 34, 96, 96,
  138465. /* 1700 */ 471, 1041, 35, 474, 193, 97, 248, 402, 517, 516,
  138466. /* 1710 */ 1068, 404, 923, 250, 256, 880, 229, 175, 875, 352,
  138467. /* 1720 */ 352, 351, 241, 349, 100, 21, 770, 22, 1054, 1056,
  138468. /* 1730 */ 7, 98, 507, 1045, 4, 337, 1058, 23, 974, 201,
  138469. /* 1740 */ 176, 280, 88, 923, 923, 925, 926, 24, 510, 279,
  138470. /* 1750 */ 960, 958, 962, 1014, 963, 1013, 235, 234, 25, 36,
  138471. /* 1760 */ 99, 90, 507, 928, 4, 511, 350, 782, 26, 841,
  138472. /* 1770 */ 236, 402, 347, 1069, 237, 1125, 1125, 1451, 510, 203,
  138473. /* 1780 */ 1450, 1125, 1125, 504, 1125, 1125, 1125, 204, 1125, 1125,
  138474. /* 1790 */ 146, 1125, 1125, 1125, 1125, 1125, 1125, 202, 1125, 1125,
  138475. /* 1800 */ 1125, 402, 933, 1125, 1125, 1125, 1125, 1125, 96, 96,
  138476. /* 1810 */ 1125, 1125, 1125, 504, 1125, 97, 1125, 402, 517, 516,
  138477. /* 1820 */ 1125, 1125, 923, 1125, 1125, 1125, 1125, 1125, 1125, 1125,
  138478. /* 1830 */ 1125, 371, 933, 1125, 1125, 1125, 274, 506, 96, 96,
  138479. /* 1840 */ 1125, 1125, 1125, 1125, 1125, 97, 1125, 402, 517, 516,
  138480. /* 1850 */ 1125, 1125, 923, 923, 923, 925, 926, 24, 1125, 409,
  138481. /* 1860 */ 1125, 1125, 1125, 256, 1125, 1125, 1125, 1125, 352, 352,
  138482. /* 1870 */ 351, 241, 349, 1125, 1125, 770, 1125, 1125, 1125, 1125,
  138483. /* 1880 */ 1125, 1125, 1125, 923, 923, 925, 926, 24, 201, 1125,
  138484. /* 1890 */ 280, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 279, 1125,
  138485. /* 1900 */ 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125,
  138486. /* 1910 */ 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125,
  138487. /* 1920 */ 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 203, 1125,
  138488. /* 1930 */ 1125, 1125, 1125, 1125, 1125, 1125, 204, 1125, 1125, 146,
  138489. /* 1940 */ 1125, 1125, 1125, 1125, 1125, 1125, 202, 1125, 1125, 1125,
  138490. /* 1950 */ 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125,
  138491. /* 1960 */ 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125,
  138492. /* 1970 */ 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125,
  138493. /* 1980 */ 371, 1125, 1125, 1125, 1125, 274, 506, 1125, 1125, 1125,
  138494. /* 1990 */ 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125,
  138495. /* 2000 */ 1125, 1125, 1125, 1125, 1125, 1125, 1125, 1125, 409,
  138496. };
  138497. static const YYCODETYPE yy_lookahead[] = {
  138498. /* 0 */ 184, 238, 239, 240, 238, 239, 240, 163, 155, 156,
  138499. /* 10 */ 157, 158, 159, 160, 163, 191, 192, 183, 165, 19,
  138500. /* 20 */ 167, 258, 202, 203, 200, 191, 163, 174, 184, 185,
  138501. /* 30 */ 174, 31, 163, 163, 171, 184, 185, 35, 175, 39,
  138502. /* 40 */ 179, 180, 181, 43, 44, 45, 46, 47, 48, 49,
  138503. /* 50 */ 50, 51, 52, 53, 54, 55, 56, 57, 184, 206,
  138504. /* 60 */ 207, 163, 206, 207, 220, 163, 16, 163, 66, 163,
  138505. /* 70 */ 59, 270, 219, 229, 273, 219, 74, 208, 174, 223,
  138506. /* 80 */ 224, 163, 184, 185, 163, 232, 184, 185, 184, 185,
  138507. /* 90 */ 184, 185, 92, 93, 94, 95, 96, 97, 98, 99,
  138508. /* 100 */ 100, 101, 102, 233, 198, 184, 185, 96, 97, 163,
  138509. /* 110 */ 206, 207, 19, 163, 261, 104, 105, 106, 107, 198,
  138510. /* 120 */ 109, 119, 220, 219, 220, 274, 275, 77, 117, 79,
  138511. /* 130 */ 187, 229, 19, 229, 184, 185, 43, 44, 45, 46,
  138512. /* 140 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  138513. /* 150 */ 57, 233, 141, 134, 143, 102, 43, 44, 45, 46,
  138514. /* 160 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  138515. /* 170 */ 57, 152, 274, 216, 276, 218, 83, 163, 85, 233,
  138516. /* 180 */ 67, 238, 239, 240, 11, 92, 93, 94, 95, 96,
  138517. /* 190 */ 97, 98, 99, 100, 101, 102, 19, 54, 55, 56,
  138518. /* 200 */ 57, 58, 163, 26, 163, 92, 93, 94, 95, 96,
  138519. /* 210 */ 97, 98, 99, 100, 101, 102, 54, 55, 56, 57,
  138520. /* 220 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  138521. /* 230 */ 53, 54, 55, 56, 57, 92, 93, 94, 95, 96,
  138522. /* 240 */ 97, 98, 99, 100, 101, 102, 69, 96, 97, 98,
  138523. /* 250 */ 99, 100, 101, 102, 92, 93, 94, 95, 96, 97,
  138524. /* 260 */ 98, 99, 100, 101, 102, 81, 179, 180, 181, 92,
  138525. /* 270 */ 93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
  138526. /* 280 */ 163, 267, 268, 163, 22, 23, 59, 163, 26, 19,
  138527. /* 290 */ 117, 118, 175, 109, 24, 59, 92, 93, 94, 95,
  138528. /* 300 */ 96, 97, 98, 99, 100, 101, 102, 268, 184, 185,
  138529. /* 310 */ 269, 127, 128, 43, 44, 45, 46, 47, 48, 49,
  138530. /* 320 */ 50, 51, 52, 53, 54, 55, 56, 57, 157, 158,
  138531. /* 330 */ 159, 160, 105, 106, 107, 163, 165, 59, 167, 184,
  138532. /* 340 */ 90, 105, 106, 107, 108, 174, 73, 111, 112, 113,
  138533. /* 350 */ 19, 22, 163, 91, 81, 163, 106, 121, 81, 132,
  138534. /* 360 */ 110, 16, 92, 93, 94, 95, 96, 97, 98, 99,
  138535. /* 370 */ 100, 101, 102, 184, 185, 255, 98, 206, 207, 26,
  138536. /* 380 */ 101, 102, 19, 105, 106, 107, 23, 198, 59, 116,
  138537. /* 390 */ 219, 141, 142, 143, 24, 163, 187, 205, 274, 275,
  138538. /* 400 */ 127, 128, 182, 232, 127, 128, 43, 44, 45, 46,
  138539. /* 410 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  138540. /* 420 */ 57, 158, 77, 160, 79, 59, 26, 182, 165, 59,
  138541. /* 430 */ 167, 199, 261, 102, 105, 106, 107, 174, 72, 108,
  138542. /* 440 */ 109, 110, 111, 112, 113, 114, 59, 238, 239, 240,
  138543. /* 450 */ 123, 120, 125, 126, 163, 92, 93, 94, 95, 96,
  138544. /* 460 */ 97, 98, 99, 100, 101, 102, 163, 163, 163, 206,
  138545. /* 470 */ 207, 105, 106, 107, 254, 19, 106, 90, 197, 23,
  138546. /* 480 */ 127, 128, 219, 238, 239, 240, 22, 184, 185, 184,
  138547. /* 490 */ 185, 22, 105, 106, 149, 232, 205, 110, 163, 43,
  138548. /* 500 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  138549. /* 510 */ 54, 55, 56, 57, 98, 99, 100, 101, 102, 184,
  138550. /* 520 */ 185, 163, 53, 59, 261, 220, 117, 118, 141, 142,
  138551. /* 530 */ 143, 131, 174, 59, 229, 116, 117, 118, 163, 59,
  138552. /* 540 */ 163, 163, 184, 185, 59, 242, 72, 22, 92, 93,
  138553. /* 550 */ 94, 95, 96, 97, 98, 99, 100, 101, 102, 184,
  138554. /* 560 */ 185, 24, 184, 185, 206, 207, 202, 203, 19, 105,
  138555. /* 570 */ 106, 107, 23, 198, 22, 174, 198, 219, 220, 105,
  138556. /* 580 */ 106, 107, 96, 97, 59, 105, 106, 107, 22, 174,
  138557. /* 590 */ 59, 106, 43, 44, 45, 46, 47, 48, 49, 50,
  138558. /* 600 */ 51, 52, 53, 54, 55, 56, 57, 206, 207, 12,
  138559. /* 610 */ 108, 59, 132, 111, 112, 113, 46, 47, 48, 49,
  138560. /* 620 */ 219, 206, 207, 121, 27, 59, 163, 141, 207, 143,
  138561. /* 630 */ 105, 106, 107, 163, 219, 234, 105, 106, 107, 42,
  138562. /* 640 */ 219, 92, 93, 94, 95, 96, 97, 98, 99, 100,
  138563. /* 650 */ 101, 102, 76, 163, 184, 185, 163, 105, 106, 107,
  138564. /* 660 */ 63, 19, 86, 163, 163, 23, 163, 130, 205, 21,
  138565. /* 670 */ 73, 105, 106, 107, 184, 185, 163, 184, 185, 237,
  138566. /* 680 */ 110, 180, 181, 180, 181, 43, 44, 45, 46, 47,
  138567. /* 690 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  138568. /* 700 */ 174, 163, 163, 22, 23, 163, 163, 26, 22, 23,
  138569. /* 710 */ 220, 29, 73, 220, 272, 33, 22, 163, 24, 19,
  138570. /* 720 */ 174, 208, 259, 184, 185, 19, 184, 185, 80, 175,
  138571. /* 730 */ 230, 174, 206, 207, 92, 93, 94, 95, 96, 97,
  138572. /* 740 */ 98, 99, 100, 101, 102, 219, 46, 65, 247, 195,
  138573. /* 750 */ 247, 197, 206, 207, 19, 116, 117, 118, 23, 220,
  138574. /* 760 */ 112, 174, 220, 206, 207, 219, 22, 174, 24, 174,
  138575. /* 770 */ 22, 23, 91, 264, 265, 168, 219, 91, 43, 44,
  138576. /* 780 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
  138577. /* 790 */ 55, 56, 57, 206, 207, 12, 163, 149, 255, 206,
  138578. /* 800 */ 207, 206, 207, 59, 104, 23, 219, 163, 26, 163,
  138579. /* 810 */ 27, 105, 219, 163, 219, 163, 211, 184, 185, 163,
  138580. /* 820 */ 120, 163, 146, 163, 148, 42, 221, 92, 93, 94,
  138581. /* 830 */ 95, 96, 97, 98, 99, 100, 101, 102, 163, 91,
  138582. /* 840 */ 184, 185, 184, 185, 184, 185, 63, 19, 163, 205,
  138583. /* 850 */ 106, 23, 245, 163, 208, 248, 116, 117, 118, 184,
  138584. /* 860 */ 185, 163, 163, 7, 8, 9, 163, 19, 26, 184,
  138585. /* 870 */ 185, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  138586. /* 880 */ 52, 53, 54, 55, 56, 57, 163, 184, 185, 107,
  138587. /* 890 */ 163, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  138588. /* 900 */ 52, 53, 54, 55, 56, 57, 208, 255, 177, 178,
  138589. /* 910 */ 163, 184, 185, 163, 132, 163, 141, 163, 143, 22,
  138590. /* 920 */ 92, 93, 94, 95, 96, 97, 98, 99, 100, 101,
  138591. /* 930 */ 102, 184, 185, 163, 184, 185, 184, 185, 184, 185,
  138592. /* 940 */ 92, 93, 94, 95, 96, 97, 98, 99, 100, 101,
  138593. /* 950 */ 102, 163, 163, 163, 184, 185, 163, 115, 163, 163,
  138594. /* 960 */ 163, 163, 15, 163, 163, 163, 163, 163, 23, 163,
  138595. /* 970 */ 163, 26, 184, 185, 184, 185, 163, 184, 185, 184,
  138596. /* 980 */ 185, 184, 185, 163, 184, 185, 184, 185, 184, 185,
  138597. /* 990 */ 184, 185, 163, 96, 97, 147, 163, 184, 185, 163,
  138598. /* 1000 */ 199, 163, 163, 205, 184, 185, 163, 60, 163, 141,
  138599. /* 1010 */ 163, 143, 163, 184, 185, 19, 163, 184, 185, 230,
  138600. /* 1020 */ 184, 185, 184, 185, 206, 207, 230, 184, 185, 184,
  138601. /* 1030 */ 185, 184, 185, 184, 185, 19, 163, 219, 231, 43,
  138602. /* 1040 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  138603. /* 1050 */ 54, 55, 56, 57, 163, 26, 163, 184, 185, 43,
  138604. /* 1060 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  138605. /* 1070 */ 54, 55, 56, 57, 163, 184, 185, 184, 185, 163,
  138606. /* 1080 */ 182, 163, 163, 163, 163, 163, 22, 163, 92, 93,
  138607. /* 1090 */ 94, 95, 96, 97, 98, 99, 100, 101, 102, 163,
  138608. /* 1100 */ 184, 185, 184, 185, 163, 184, 185, 163, 92, 93,
  138609. /* 1110 */ 94, 95, 96, 97, 98, 99, 100, 101, 102, 163,
  138610. /* 1120 */ 184, 185, 98, 59, 163, 184, 185, 205, 184, 185,
  138611. /* 1130 */ 23, 206, 207, 26, 163, 26, 107, 153, 154, 237,
  138612. /* 1140 */ 184, 185, 231, 147, 219, 184, 185, 249, 124, 127,
  138613. /* 1150 */ 128, 231, 254, 129, 163, 231, 177, 178, 262, 263,
  138614. /* 1160 */ 118, 132, 19, 19, 46, 223, 224, 31, 24, 23,
  138615. /* 1170 */ 106, 124, 26, 22, 272, 39, 129, 23, 109, 110,
  138616. /* 1180 */ 26, 163, 140, 19, 22, 234, 59, 43, 44, 45,
  138617. /* 1190 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  138618. /* 1200 */ 56, 57, 231, 7, 8, 193, 59, 43, 44, 45,
  138619. /* 1210 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  138620. /* 1220 */ 56, 57, 104, 61, 23, 23, 23, 26, 26, 26,
  138621. /* 1230 */ 163, 23, 23, 106, 26, 26, 92, 93, 94, 95,
  138622. /* 1240 */ 96, 97, 98, 99, 100, 101, 102, 138, 105, 23,
  138623. /* 1250 */ 59, 23, 26, 106, 26, 163, 92, 93, 94, 95,
  138624. /* 1260 */ 96, 97, 98, 99, 100, 101, 102, 110, 23, 23,
  138625. /* 1270 */ 23, 26, 26, 26, 163, 163, 19, 120, 163, 163,
  138626. /* 1280 */ 163, 130, 163, 163, 163, 163, 163, 163, 163, 193,
  138627. /* 1290 */ 193, 163, 163, 163, 163, 225, 19, 106, 163, 222,
  138628. /* 1300 */ 163, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  138629. /* 1310 */ 53, 54, 55, 56, 57, 163, 163, 203, 163, 163,
  138630. /* 1320 */ 222, 163, 45, 46, 47, 48, 49, 50, 51, 52,
  138631. /* 1330 */ 53, 54, 55, 56, 57, 163, 163, 163, 163, 163,
  138632. /* 1340 */ 251, 250, 209, 19, 20, 182, 22, 161, 222, 92,
  138633. /* 1350 */ 93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
  138634. /* 1360 */ 36, 222, 222, 260, 226, 188, 256, 226, 187, 92,
  138635. /* 1370 */ 93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
  138636. /* 1380 */ 210, 213, 213, 59, 213, 196, 192, 187, 256, 244,
  138637. /* 1390 */ 212, 187, 226, 19, 20, 71, 22, 210, 166, 60,
  138638. /* 1400 */ 130, 170, 260, 170, 38, 81, 257, 257, 170, 104,
  138639. /* 1410 */ 36, 22, 43, 201, 90, 236, 138, 235, 213, 18,
  138640. /* 1420 */ 96, 97, 48, 204, 204, 204, 204, 103, 170, 105,
  138641. /* 1430 */ 106, 107, 18, 59, 110, 169, 213, 213, 201, 170,
  138642. /* 1440 */ 201, 169, 236, 213, 146, 71, 235, 62, 253, 252,
  138643. /* 1450 */ 170, 127, 128, 169, 22, 170, 82, 189, 169, 104,
  138644. /* 1460 */ 170, 87, 169, 189, 90, 141, 142, 143, 144, 145,
  138645. /* 1470 */ 96, 97, 186, 186, 186, 64, 194, 103, 186, 105,
  138646. /* 1480 */ 106, 107, 115, 189, 110, 188, 186, 186, 19, 20,
  138647. /* 1490 */ 194, 22, 186, 189, 102, 246, 246, 189, 133, 228,
  138648. /* 1500 */ 104, 228, 227, 227, 170, 36, 134, 228, 227, 19,
  138649. /* 1510 */ 20, 228, 22, 84, 271, 141, 142, 143, 144, 145,
  138650. /* 1520 */ 0, 1, 2, 216, 22, 5, 36, 137, 59, 227,
  138651. /* 1530 */ 10, 11, 12, 13, 14, 217, 269, 17, 216, 22,
  138652. /* 1540 */ 71, 170, 243, 146, 241, 217, 136, 215, 135, 59,
  138653. /* 1550 */ 30, 82, 32, 25, 214, 213, 87, 173, 26, 90,
  138654. /* 1560 */ 40, 71, 13, 172, 164, 96, 97, 164, 6, 162,
  138655. /* 1570 */ 162, 162, 103, 263, 105, 106, 107, 266, 266, 110,
  138656. /* 1580 */ 90, 176, 176, 190, 182, 190, 96, 97, 98, 4,
  138657. /* 1590 */ 70, 176, 3, 103, 182, 105, 106, 107, 78, 182,
  138658. /* 1600 */ 110, 81, 182, 182, 182, 182, 182, 151, 88, 22,
  138659. /* 1610 */ 141, 142, 143, 144, 145, 15, 89, 16, 23, 23,
  138660. /* 1620 */ 128, 19, 20, 139, 22, 119, 131, 24, 20, 133,
  138661. /* 1630 */ 16, 141, 142, 143, 144, 145, 1, 140, 36, 131,
  138662. /* 1640 */ 119, 61, 122, 37, 139, 53, 53, 127, 128, 119,
  138663. /* 1650 */ 53, 53, 105, 34, 130, 1, 5, 104, 22, 149,
  138664. /* 1660 */ 26, 59, 68, 75, 41, 130, 24, 68, 104, 20,
  138665. /* 1670 */ 150, 19, 120, 71, 114, 22, 67, 22, 22, 67,
  138666. /* 1680 */ 23, 22, 22, 67, 82, 37, 28, 23, 138, 87,
  138667. /* 1690 */ 22, 153, 90, 23, 23, 26, 23, 22, 96, 97,
  138668. /* 1700 */ 24, 23, 22, 24, 130, 103, 23, 105, 106, 107,
  138669. /* 1710 */ 1, 2, 110, 23, 5, 105, 34, 22, 132, 10,
  138670. /* 1720 */ 11, 12, 13, 14, 26, 34, 17, 34, 85, 83,
  138671. /* 1730 */ 44, 19, 20, 23, 22, 24, 75, 34, 23, 30,
  138672. /* 1740 */ 26, 32, 26, 141, 142, 143, 144, 145, 36, 40,
  138673. /* 1750 */ 23, 23, 23, 23, 11, 23, 22, 26, 22, 22,
  138674. /* 1760 */ 22, 19, 20, 23, 22, 26, 15, 23, 22, 124,
  138675. /* 1770 */ 130, 59, 23, 1, 130, 277, 277, 130, 36, 70,
  138676. /* 1780 */ 130, 277, 277, 71, 277, 277, 277, 78, 277, 277,
  138677. /* 1790 */ 81, 277, 277, 277, 277, 277, 277, 88, 277, 277,
  138678. /* 1800 */ 277, 59, 90, 277, 277, 277, 277, 277, 96, 97,
  138679. /* 1810 */ 277, 277, 277, 71, 277, 103, 277, 105, 106, 107,
  138680. /* 1820 */ 277, 277, 110, 277, 277, 277, 277, 277, 277, 277,
  138681. /* 1830 */ 277, 122, 90, 277, 277, 277, 127, 128, 96, 97,
  138682. /* 1840 */ 277, 277, 277, 277, 277, 103, 277, 105, 106, 107,
  138683. /* 1850 */ 277, 277, 110, 141, 142, 143, 144, 145, 277, 150,
  138684. /* 1860 */ 277, 277, 277, 5, 277, 277, 277, 277, 10, 11,
  138685. /* 1870 */ 12, 13, 14, 277, 277, 17, 277, 277, 277, 277,
  138686. /* 1880 */ 277, 277, 277, 141, 142, 143, 144, 145, 30, 277,
  138687. /* 1890 */ 32, 277, 277, 277, 277, 277, 277, 277, 40, 277,
  138688. /* 1900 */ 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
  138689. /* 1910 */ 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
  138690. /* 1920 */ 277, 277, 277, 277, 277, 277, 277, 277, 70, 277,
  138691. /* 1930 */ 277, 277, 277, 277, 277, 277, 78, 277, 277, 81,
  138692. /* 1940 */ 277, 277, 277, 277, 277, 277, 88, 277, 277, 277,
  138693. /* 1950 */ 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
  138694. /* 1960 */ 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
  138695. /* 1970 */ 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
  138696. /* 1980 */ 122, 277, 277, 277, 277, 127, 128, 277, 277, 277,
  138697. /* 1990 */ 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
  138698. /* 2000 */ 277, 277, 277, 277, 277, 277, 277, 277, 150, 277,
  138699. /* 2010 */ 277, 277, 277, 277, 277, 277, 277, 277, 277,
  138700. };
  138701. #define YY_SHIFT_COUNT (520)
  138702. #define YY_SHIFT_MIN (0)
  138703. #define YY_SHIFT_MAX (1858)
  138704. static const unsigned short int yy_shift_ofst[] = {
  138705. /* 0 */ 1709, 1520, 1858, 1324, 1324, 277, 1374, 1469, 1602, 1712,
  138706. /* 10 */ 1712, 1712, 273, 0, 0, 113, 1016, 1712, 1712, 1712,
  138707. /* 20 */ 1712, 1712, 1712, 1712, 1712, 1712, 1712, 11, 11, 236,
  138708. /* 30 */ 184, 277, 277, 277, 277, 277, 277, 93, 177, 270,
  138709. /* 40 */ 363, 456, 549, 642, 735, 828, 848, 996, 1144, 1016,
  138710. /* 50 */ 1016, 1016, 1016, 1016, 1016, 1016, 1016, 1016, 1016, 1016,
  138711. /* 60 */ 1016, 1016, 1016, 1016, 1016, 1016, 1164, 1016, 1257, 1277,
  138712. /* 70 */ 1277, 1490, 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712,
  138713. /* 80 */ 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712,
  138714. /* 90 */ 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712,
  138715. /* 100 */ 1712, 1712, 1712, 1742, 1712, 1712, 1712, 1712, 1712, 1712,
  138716. /* 110 */ 1712, 1712, 1712, 1712, 1712, 1712, 1712, 143, 162, 162,
  138717. /* 120 */ 162, 162, 162, 204, 151, 416, 531, 648, 700, 531,
  138718. /* 130 */ 486, 486, 531, 353, 353, 353, 353, 409, 279, 53,
  138719. /* 140 */ 2009, 2009, 331, 331, 331, 329, 366, 329, 329, 597,
  138720. /* 150 */ 597, 464, 474, 262, 681, 531, 531, 531, 531, 531,
  138721. /* 160 */ 531, 531, 531, 531, 531, 531, 531, 531, 531, 531,
  138722. /* 170 */ 531, 531, 531, 531, 531, 531, 531, 173, 485, 984,
  138723. /* 180 */ 984, 576, 485, 19, 1022, 2009, 2009, 2009, 387, 250,
  138724. /* 190 */ 250, 525, 502, 278, 552, 227, 480, 566, 531, 531,
  138725. /* 200 */ 531, 531, 531, 531, 531, 531, 531, 531, 639, 531,
  138726. /* 210 */ 531, 531, 531, 531, 531, 531, 531, 531, 531, 531,
  138727. /* 220 */ 531, 2, 2, 2, 531, 531, 531, 531, 782, 531,
  138728. /* 230 */ 531, 531, 744, 531, 531, 783, 531, 531, 531, 531,
  138729. /* 240 */ 531, 531, 531, 531, 419, 682, 327, 370, 370, 370,
  138730. /* 250 */ 370, 1029, 327, 327, 1024, 897, 856, 947, 1109, 706,
  138731. /* 260 */ 706, 1143, 1109, 1109, 1143, 842, 945, 1118, 1136, 1136,
  138732. /* 270 */ 1136, 706, 676, 400, 1047, 694, 1339, 1270, 1270, 1366,
  138733. /* 280 */ 1366, 1270, 1305, 1389, 1369, 1278, 1401, 1401, 1401, 1401,
  138734. /* 290 */ 1270, 1414, 1278, 1278, 1305, 1389, 1369, 1369, 1278, 1270,
  138735. /* 300 */ 1414, 1298, 1385, 1270, 1414, 1432, 1270, 1414, 1270, 1414,
  138736. /* 310 */ 1432, 1355, 1355, 1355, 1411, 1432, 1355, 1367, 1355, 1411,
  138737. /* 320 */ 1355, 1355, 1432, 1392, 1392, 1432, 1365, 1396, 1365, 1396,
  138738. /* 330 */ 1365, 1396, 1365, 1396, 1270, 1372, 1429, 1502, 1390, 1372,
  138739. /* 340 */ 1517, 1270, 1397, 1390, 1410, 1413, 1278, 1528, 1532, 1549,
  138740. /* 350 */ 1549, 1562, 1562, 1562, 2009, 2009, 2009, 2009, 2009, 2009,
  138741. /* 360 */ 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009,
  138742. /* 370 */ 570, 345, 686, 748, 50, 740, 1064, 1107, 469, 537,
  138743. /* 380 */ 1042, 1146, 1162, 1154, 1201, 1202, 1203, 1208, 1209, 1127,
  138744. /* 390 */ 1069, 1196, 1157, 1147, 1226, 1228, 1245, 775, 868, 1246,
  138745. /* 400 */ 1247, 1191, 1151, 1585, 1589, 1587, 1456, 1600, 1527, 1601,
  138746. /* 410 */ 1595, 1596, 1492, 1484, 1506, 1603, 1495, 1608, 1496, 1614,
  138747. /* 420 */ 1635, 1508, 1497, 1521, 1580, 1606, 1505, 1592, 1593, 1597,
  138748. /* 430 */ 1598, 1530, 1547, 1619, 1524, 1654, 1651, 1636, 1553, 1510,
  138749. /* 440 */ 1594, 1634, 1599, 1588, 1623, 1535, 1564, 1642, 1649, 1652,
  138750. /* 450 */ 1552, 1560, 1653, 1609, 1655, 1656, 1657, 1659, 1612, 1658,
  138751. /* 460 */ 1660, 1616, 1648, 1664, 1550, 1668, 1538, 1670, 1671, 1669,
  138752. /* 470 */ 1673, 1675, 1676, 1678, 1680, 1679, 1574, 1683, 1690, 1610,
  138753. /* 480 */ 1682, 1695, 1586, 1698, 1691, 1698, 1693, 1643, 1661, 1646,
  138754. /* 490 */ 1686, 1710, 1711, 1714, 1716, 1703, 1715, 1698, 1727, 1728,
  138755. /* 500 */ 1729, 1730, 1731, 1732, 1734, 1743, 1736, 1737, 1740, 1744,
  138756. /* 510 */ 1738, 1746, 1739, 1645, 1640, 1644, 1647, 1650, 1749, 1751,
  138757. /* 520 */ 1772,
  138758. };
  138759. #define YY_REDUCE_COUNT (369)
  138760. #define YY_REDUCE_MIN (-237)
  138761. #define YY_REDUCE_MAX (1424)
  138762. static const short yy_reduce_ofst[] = {
  138763. /* 0 */ -147, 171, 263, -96, 358, -144, -149, -102, 124, -156,
  138764. /* 10 */ -98, 305, 401, -57, 209, -237, 245, -94, -79, 189,
  138765. /* 20 */ 375, 490, 493, 378, 303, 539, 542, 501, 503, 554,
  138766. /* 30 */ 415, 526, 546, 557, 587, 593, 595, -234, -234, -234,
  138767. /* 40 */ -234, -234, -234, -234, -234, -234, -234, -234, -234, -234,
  138768. /* 50 */ -234, -234, -234, -234, -234, -234, -234, -234, -234, -234,
  138769. /* 60 */ -234, -234, -234, -234, -234, -234, -234, -234, -234, -234,
  138770. /* 70 */ -234, -50, 335, 470, 633, 656, 658, 660, 675, 685,
  138771. /* 80 */ 703, 727, 747, 750, 752, 754, 770, 788, 790, 793,
  138772. /* 90 */ 795, 797, 800, 802, 804, 806, 813, 820, 829, 833,
  138773. /* 100 */ 836, 838, 843, 845, 847, 849, 873, 891, 893, 916,
  138774. /* 110 */ 918, 921, 936, 941, 944, 956, 961, -234, -234, -234,
  138775. /* 120 */ -234, -234, -234, -234, -234, -234, 463, 607, -176, 14,
  138776. /* 130 */ -139, 87, -137, 818, 925, 818, 925, 898, -234, -234,
  138777. /* 140 */ -234, -234, -166, -166, -166, -130, -131, -82, -54, -180,
  138778. /* 150 */ 364, 41, 513, 509, 509, 117, 500, 789, 796, 646,
  138779. /* 160 */ 192, 291, 644, 798, 120, 807, 543, 911, 920, 652,
  138780. /* 170 */ 924, 922, 232, 698, 801, 971, 39, 220, 731, 442,
  138781. /* 180 */ 902, -199, 979, -43, 421, 896, 942, 605, -184, -126,
  138782. /* 190 */ 155, 172, 281, 304, 377, 538, 650, 690, 699, 723,
  138783. /* 200 */ 803, 839, 853, 919, 991, 1018, 1067, 1092, 951, 1111,
  138784. /* 210 */ 1112, 1115, 1116, 1117, 1119, 1120, 1121, 1122, 1123, 1124,
  138785. /* 220 */ 1125, 1012, 1096, 1097, 1128, 1129, 1130, 1131, 1070, 1135,
  138786. /* 230 */ 1137, 1152, 1077, 1153, 1155, 1114, 1156, 304, 1158, 1172,
  138787. /* 240 */ 1173, 1174, 1175, 1176, 1089, 1091, 1133, 1098, 1126, 1139,
  138788. /* 250 */ 1140, 1070, 1133, 1133, 1170, 1163, 1186, 1103, 1168, 1138,
  138789. /* 260 */ 1141, 1110, 1169, 1171, 1132, 1177, 1189, 1194, 1181, 1200,
  138790. /* 270 */ 1204, 1166, 1145, 1178, 1187, 1232, 1142, 1231, 1233, 1149,
  138791. /* 280 */ 1150, 1238, 1179, 1182, 1212, 1205, 1219, 1220, 1221, 1222,
  138792. /* 290 */ 1258, 1266, 1223, 1224, 1206, 1211, 1237, 1239, 1230, 1269,
  138793. /* 300 */ 1272, 1195, 1197, 1280, 1284, 1268, 1285, 1289, 1290, 1293,
  138794. /* 310 */ 1274, 1286, 1287, 1288, 1282, 1294, 1292, 1297, 1300, 1296,
  138795. /* 320 */ 1301, 1306, 1304, 1249, 1250, 1308, 1271, 1275, 1273, 1276,
  138796. /* 330 */ 1279, 1281, 1283, 1302, 1334, 1307, 1243, 1267, 1318, 1322,
  138797. /* 340 */ 1303, 1371, 1299, 1328, 1332, 1340, 1342, 1384, 1391, 1400,
  138798. /* 350 */ 1403, 1407, 1408, 1409, 1311, 1312, 1310, 1405, 1402, 1412,
  138799. /* 360 */ 1417, 1420, 1406, 1393, 1395, 1421, 1422, 1423, 1424, 1415,
  138800. };
  138801. static const YYACTIONTYPE yy_default[] = {
  138802. /* 0 */ 1492, 1492, 1492, 1340, 1123, 1229, 1123, 1123, 1123, 1340,
  138803. /* 10 */ 1340, 1340, 1123, 1259, 1259, 1391, 1154, 1123, 1123, 1123,
  138804. /* 20 */ 1123, 1123, 1123, 1123, 1339, 1123, 1123, 1123, 1123, 1123,
  138805. /* 30 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1265, 1123,
  138806. /* 40 */ 1123, 1123, 1123, 1123, 1341, 1342, 1123, 1123, 1123, 1390,
  138807. /* 50 */ 1392, 1275, 1274, 1273, 1272, 1373, 1246, 1270, 1263, 1267,
  138808. /* 60 */ 1335, 1336, 1334, 1338, 1342, 1341, 1123, 1266, 1306, 1320,
  138809. /* 70 */ 1305, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138810. /* 80 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138811. /* 90 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138812. /* 100 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138813. /* 110 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1314, 1319, 1325,
  138814. /* 120 */ 1318, 1315, 1308, 1307, 1309, 1310, 1123, 1144, 1193, 1123,
  138815. /* 130 */ 1123, 1123, 1123, 1409, 1408, 1123, 1123, 1154, 1311, 1312,
  138816. /* 140 */ 1322, 1321, 1398, 1448, 1447, 1123, 1123, 1123, 1123, 1123,
  138817. /* 150 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138818. /* 160 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138819. /* 170 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1154, 1150, 1300,
  138820. /* 180 */ 1299, 1418, 1150, 1253, 1123, 1404, 1229, 1220, 1123, 1123,
  138821. /* 190 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138822. /* 200 */ 1123, 1395, 1393, 1123, 1355, 1123, 1123, 1123, 1123, 1123,
  138823. /* 210 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138824. /* 220 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138825. /* 230 */ 1123, 1123, 1225, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138826. /* 240 */ 1123, 1123, 1123, 1442, 1123, 1368, 1207, 1225, 1225, 1225,
  138827. /* 250 */ 1225, 1227, 1208, 1206, 1219, 1154, 1130, 1484, 1269, 1248,
  138828. /* 260 */ 1248, 1481, 1269, 1269, 1481, 1168, 1462, 1165, 1259, 1259,
  138829. /* 270 */ 1259, 1248, 1337, 1226, 1219, 1123, 1484, 1234, 1234, 1483,
  138830. /* 280 */ 1483, 1234, 1278, 1284, 1196, 1269, 1202, 1202, 1202, 1202,
  138831. /* 290 */ 1234, 1141, 1269, 1269, 1278, 1284, 1196, 1196, 1269, 1234,
  138832. /* 300 */ 1141, 1372, 1478, 1234, 1141, 1348, 1234, 1141, 1234, 1141,
  138833. /* 310 */ 1348, 1194, 1194, 1194, 1183, 1348, 1194, 1168, 1194, 1183,
  138834. /* 320 */ 1194, 1194, 1348, 1352, 1352, 1348, 1252, 1247, 1252, 1247,
  138835. /* 330 */ 1252, 1247, 1252, 1247, 1234, 1253, 1417, 1123, 1264, 1253,
  138836. /* 340 */ 1343, 1234, 1123, 1264, 1262, 1260, 1269, 1147, 1186, 1445,
  138837. /* 350 */ 1445, 1441, 1441, 1441, 1489, 1489, 1404, 1457, 1154, 1154,
  138838. /* 360 */ 1154, 1154, 1457, 1170, 1170, 1154, 1154, 1154, 1154, 1457,
  138839. /* 370 */ 1123, 1123, 1123, 1123, 1123, 1123, 1452, 1123, 1357, 1238,
  138840. /* 380 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138841. /* 390 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138842. /* 400 */ 1123, 1123, 1289, 1123, 1126, 1401, 1123, 1123, 1399, 1123,
  138843. /* 410 */ 1123, 1123, 1123, 1123, 1123, 1239, 1123, 1123, 1123, 1123,
  138844. /* 420 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138845. /* 430 */ 1123, 1123, 1123, 1123, 1480, 1123, 1123, 1123, 1123, 1123,
  138846. /* 440 */ 1123, 1371, 1370, 1123, 1123, 1236, 1123, 1123, 1123, 1123,
  138847. /* 450 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138848. /* 460 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138849. /* 470 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138850. /* 480 */ 1123, 1123, 1123, 1261, 1123, 1416, 1123, 1123, 1123, 1123,
  138851. /* 490 */ 1123, 1123, 1123, 1430, 1254, 1123, 1123, 1471, 1123, 1123,
  138852. /* 500 */ 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123, 1123,
  138853. /* 510 */ 1123, 1123, 1466, 1210, 1291, 1123, 1290, 1294, 1123, 1135,
  138854. /* 520 */ 1123,
  138855. };
  138856. /********** End of lemon-generated parsing tables *****************************/
  138857. /* The next table maps tokens (terminal symbols) into fallback tokens.
  138858. ** If a construct like the following:
  138859. **
  138860. ** %fallback ID X Y Z.
  138861. **
  138862. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  138863. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  138864. ** but it does not parse, the type of the token is changed to ID and
  138865. ** the parse is retried before an error is thrown.
  138866. **
  138867. ** This feature can be used, for example, to cause some keywords in a language
  138868. ** to revert to identifiers if they keyword does not apply in the context where
  138869. ** it appears.
  138870. */
  138871. #ifdef YYFALLBACK
  138872. static const YYCODETYPE yyFallback[] = {
  138873. 0, /* $ => nothing */
  138874. 0, /* SEMI => nothing */
  138875. 59, /* EXPLAIN => ID */
  138876. 59, /* QUERY => ID */
  138877. 59, /* PLAN => ID */
  138878. 59, /* BEGIN => ID */
  138879. 0, /* TRANSACTION => nothing */
  138880. 59, /* DEFERRED => ID */
  138881. 59, /* IMMEDIATE => ID */
  138882. 59, /* EXCLUSIVE => ID */
  138883. 0, /* COMMIT => nothing */
  138884. 59, /* END => ID */
  138885. 59, /* ROLLBACK => ID */
  138886. 59, /* SAVEPOINT => ID */
  138887. 59, /* RELEASE => ID */
  138888. 0, /* TO => nothing */
  138889. 0, /* TABLE => nothing */
  138890. 0, /* CREATE => nothing */
  138891. 59, /* IF => ID */
  138892. 0, /* NOT => nothing */
  138893. 0, /* EXISTS => nothing */
  138894. 59, /* TEMP => ID */
  138895. 0, /* LP => nothing */
  138896. 0, /* RP => nothing */
  138897. 0, /* AS => nothing */
  138898. 59, /* WITHOUT => ID */
  138899. 0, /* COMMA => nothing */
  138900. 59, /* ABORT => ID */
  138901. 59, /* ACTION => ID */
  138902. 59, /* AFTER => ID */
  138903. 59, /* ANALYZE => ID */
  138904. 59, /* ASC => ID */
  138905. 59, /* ATTACH => ID */
  138906. 59, /* BEFORE => ID */
  138907. 59, /* BY => ID */
  138908. 59, /* CASCADE => ID */
  138909. 59, /* CAST => ID */
  138910. 59, /* CONFLICT => ID */
  138911. 59, /* DATABASE => ID */
  138912. 59, /* DESC => ID */
  138913. 59, /* DETACH => ID */
  138914. 59, /* EACH => ID */
  138915. 59, /* FAIL => ID */
  138916. 0, /* OR => nothing */
  138917. 0, /* AND => nothing */
  138918. 0, /* IS => nothing */
  138919. 59, /* MATCH => ID */
  138920. 59, /* LIKE_KW => ID */
  138921. 0, /* BETWEEN => nothing */
  138922. 0, /* IN => nothing */
  138923. 0, /* ISNULL => nothing */
  138924. 0, /* NOTNULL => nothing */
  138925. 0, /* NE => nothing */
  138926. 0, /* EQ => nothing */
  138927. 0, /* GT => nothing */
  138928. 0, /* LE => nothing */
  138929. 0, /* LT => nothing */
  138930. 0, /* GE => nothing */
  138931. 0, /* ESCAPE => nothing */
  138932. 0, /* ID => nothing */
  138933. 59, /* COLUMNKW => ID */
  138934. 59, /* DO => ID */
  138935. 59, /* FOR => ID */
  138936. 59, /* IGNORE => ID */
  138937. 59, /* INITIALLY => ID */
  138938. 59, /* INSTEAD => ID */
  138939. 59, /* NO => ID */
  138940. 59, /* KEY => ID */
  138941. 59, /* OF => ID */
  138942. 59, /* OFFSET => ID */
  138943. 59, /* PRAGMA => ID */
  138944. 59, /* RAISE => ID */
  138945. 59, /* RECURSIVE => ID */
  138946. 59, /* REPLACE => ID */
  138947. 59, /* RESTRICT => ID */
  138948. 59, /* ROW => ID */
  138949. 59, /* ROWS => ID */
  138950. 59, /* TRIGGER => ID */
  138951. 59, /* VACUUM => ID */
  138952. 59, /* VIEW => ID */
  138953. 59, /* VIRTUAL => ID */
  138954. 59, /* WITH => ID */
  138955. 59, /* CURRENT => ID */
  138956. 59, /* FOLLOWING => ID */
  138957. 59, /* PARTITION => ID */
  138958. 59, /* PRECEDING => ID */
  138959. 59, /* RANGE => ID */
  138960. 59, /* UNBOUNDED => ID */
  138961. 59, /* REINDEX => ID */
  138962. 59, /* RENAME => ID */
  138963. 59, /* CTIME_KW => ID */
  138964. };
  138965. #endif /* YYFALLBACK */
  138966. /* The following structure represents a single element of the
  138967. ** parser's stack. Information stored includes:
  138968. **
  138969. ** + The state number for the parser at this level of the stack.
  138970. **
  138971. ** + The value of the token stored at this level of the stack.
  138972. ** (In other words, the "major" token.)
  138973. **
  138974. ** + The semantic value stored at this level of the stack. This is
  138975. ** the information used by the action routines in the grammar.
  138976. ** It is sometimes called the "minor" token.
  138977. **
  138978. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  138979. ** actually contains the reduce action for the second half of the
  138980. ** SHIFTREDUCE.
  138981. */
  138982. struct yyStackEntry {
  138983. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  138984. YYCODETYPE major; /* The major token value. This is the code
  138985. ** number for the token at this stack level */
  138986. YYMINORTYPE minor; /* The user-supplied minor token value. This
  138987. ** is the value of the token */
  138988. };
  138989. typedef struct yyStackEntry yyStackEntry;
  138990. /* The state of the parser is completely contained in an instance of
  138991. ** the following structure */
  138992. struct yyParser {
  138993. yyStackEntry *yytos; /* Pointer to top element of the stack */
  138994. #ifdef YYTRACKMAXSTACKDEPTH
  138995. int yyhwm; /* High-water mark of the stack */
  138996. #endif
  138997. #ifndef YYNOERRORRECOVERY
  138998. int yyerrcnt; /* Shifts left before out of the error */
  138999. #endif
  139000. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  139001. sqlite3ParserCTX_SDECL /* A place to hold %extra_context */
  139002. #if YYSTACKDEPTH<=0
  139003. int yystksz; /* Current side of the stack */
  139004. yyStackEntry *yystack; /* The parser's stack */
  139005. yyStackEntry yystk0; /* First stack entry */
  139006. #else
  139007. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  139008. yyStackEntry *yystackEnd; /* Last entry in the stack */
  139009. #endif
  139010. };
  139011. typedef struct yyParser yyParser;
  139012. #ifndef NDEBUG
  139013. /* #include <stdio.h> */
  139014. static FILE *yyTraceFILE = 0;
  139015. static char *yyTracePrompt = 0;
  139016. #endif /* NDEBUG */
  139017. #ifndef NDEBUG
  139018. /*
  139019. ** Turn parser tracing on by giving a stream to which to write the trace
  139020. ** and a prompt to preface each trace message. Tracing is turned off
  139021. ** by making either argument NULL
  139022. **
  139023. ** Inputs:
  139024. ** <ul>
  139025. ** <li> A FILE* to which trace output should be written.
  139026. ** If NULL, then tracing is turned off.
  139027. ** <li> A prefix string written at the beginning of every
  139028. ** line of trace output. If NULL, then tracing is
  139029. ** turned off.
  139030. ** </ul>
  139031. **
  139032. ** Outputs:
  139033. ** None.
  139034. */
  139035. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  139036. yyTraceFILE = TraceFILE;
  139037. yyTracePrompt = zTracePrompt;
  139038. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  139039. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  139040. }
  139041. #endif /* NDEBUG */
  139042. #if defined(YYCOVERAGE) || !defined(NDEBUG)
  139043. /* For tracing shifts, the names of all terminals and nonterminals
  139044. ** are required. The following table supplies these names */
  139045. static const char *const yyTokenName[] = {
  139046. /* 0 */ "$",
  139047. /* 1 */ "SEMI",
  139048. /* 2 */ "EXPLAIN",
  139049. /* 3 */ "QUERY",
  139050. /* 4 */ "PLAN",
  139051. /* 5 */ "BEGIN",
  139052. /* 6 */ "TRANSACTION",
  139053. /* 7 */ "DEFERRED",
  139054. /* 8 */ "IMMEDIATE",
  139055. /* 9 */ "EXCLUSIVE",
  139056. /* 10 */ "COMMIT",
  139057. /* 11 */ "END",
  139058. /* 12 */ "ROLLBACK",
  139059. /* 13 */ "SAVEPOINT",
  139060. /* 14 */ "RELEASE",
  139061. /* 15 */ "TO",
  139062. /* 16 */ "TABLE",
  139063. /* 17 */ "CREATE",
  139064. /* 18 */ "IF",
  139065. /* 19 */ "NOT",
  139066. /* 20 */ "EXISTS",
  139067. /* 21 */ "TEMP",
  139068. /* 22 */ "LP",
  139069. /* 23 */ "RP",
  139070. /* 24 */ "AS",
  139071. /* 25 */ "WITHOUT",
  139072. /* 26 */ "COMMA",
  139073. /* 27 */ "ABORT",
  139074. /* 28 */ "ACTION",
  139075. /* 29 */ "AFTER",
  139076. /* 30 */ "ANALYZE",
  139077. /* 31 */ "ASC",
  139078. /* 32 */ "ATTACH",
  139079. /* 33 */ "BEFORE",
  139080. /* 34 */ "BY",
  139081. /* 35 */ "CASCADE",
  139082. /* 36 */ "CAST",
  139083. /* 37 */ "CONFLICT",
  139084. /* 38 */ "DATABASE",
  139085. /* 39 */ "DESC",
  139086. /* 40 */ "DETACH",
  139087. /* 41 */ "EACH",
  139088. /* 42 */ "FAIL",
  139089. /* 43 */ "OR",
  139090. /* 44 */ "AND",
  139091. /* 45 */ "IS",
  139092. /* 46 */ "MATCH",
  139093. /* 47 */ "LIKE_KW",
  139094. /* 48 */ "BETWEEN",
  139095. /* 49 */ "IN",
  139096. /* 50 */ "ISNULL",
  139097. /* 51 */ "NOTNULL",
  139098. /* 52 */ "NE",
  139099. /* 53 */ "EQ",
  139100. /* 54 */ "GT",
  139101. /* 55 */ "LE",
  139102. /* 56 */ "LT",
  139103. /* 57 */ "GE",
  139104. /* 58 */ "ESCAPE",
  139105. /* 59 */ "ID",
  139106. /* 60 */ "COLUMNKW",
  139107. /* 61 */ "DO",
  139108. /* 62 */ "FOR",
  139109. /* 63 */ "IGNORE",
  139110. /* 64 */ "INITIALLY",
  139111. /* 65 */ "INSTEAD",
  139112. /* 66 */ "NO",
  139113. /* 67 */ "KEY",
  139114. /* 68 */ "OF",
  139115. /* 69 */ "OFFSET",
  139116. /* 70 */ "PRAGMA",
  139117. /* 71 */ "RAISE",
  139118. /* 72 */ "RECURSIVE",
  139119. /* 73 */ "REPLACE",
  139120. /* 74 */ "RESTRICT",
  139121. /* 75 */ "ROW",
  139122. /* 76 */ "ROWS",
  139123. /* 77 */ "TRIGGER",
  139124. /* 78 */ "VACUUM",
  139125. /* 79 */ "VIEW",
  139126. /* 80 */ "VIRTUAL",
  139127. /* 81 */ "WITH",
  139128. /* 82 */ "CURRENT",
  139129. /* 83 */ "FOLLOWING",
  139130. /* 84 */ "PARTITION",
  139131. /* 85 */ "PRECEDING",
  139132. /* 86 */ "RANGE",
  139133. /* 87 */ "UNBOUNDED",
  139134. /* 88 */ "REINDEX",
  139135. /* 89 */ "RENAME",
  139136. /* 90 */ "CTIME_KW",
  139137. /* 91 */ "ANY",
  139138. /* 92 */ "BITAND",
  139139. /* 93 */ "BITOR",
  139140. /* 94 */ "LSHIFT",
  139141. /* 95 */ "RSHIFT",
  139142. /* 96 */ "PLUS",
  139143. /* 97 */ "MINUS",
  139144. /* 98 */ "STAR",
  139145. /* 99 */ "SLASH",
  139146. /* 100 */ "REM",
  139147. /* 101 */ "CONCAT",
  139148. /* 102 */ "COLLATE",
  139149. /* 103 */ "BITNOT",
  139150. /* 104 */ "ON",
  139151. /* 105 */ "INDEXED",
  139152. /* 106 */ "STRING",
  139153. /* 107 */ "JOIN_KW",
  139154. /* 108 */ "CONSTRAINT",
  139155. /* 109 */ "DEFAULT",
  139156. /* 110 */ "NULL",
  139157. /* 111 */ "PRIMARY",
  139158. /* 112 */ "UNIQUE",
  139159. /* 113 */ "CHECK",
  139160. /* 114 */ "REFERENCES",
  139161. /* 115 */ "AUTOINCR",
  139162. /* 116 */ "INSERT",
  139163. /* 117 */ "DELETE",
  139164. /* 118 */ "UPDATE",
  139165. /* 119 */ "SET",
  139166. /* 120 */ "DEFERRABLE",
  139167. /* 121 */ "FOREIGN",
  139168. /* 122 */ "DROP",
  139169. /* 123 */ "UNION",
  139170. /* 124 */ "ALL",
  139171. /* 125 */ "EXCEPT",
  139172. /* 126 */ "INTERSECT",
  139173. /* 127 */ "SELECT",
  139174. /* 128 */ "VALUES",
  139175. /* 129 */ "DISTINCT",
  139176. /* 130 */ "DOT",
  139177. /* 131 */ "FROM",
  139178. /* 132 */ "JOIN",
  139179. /* 133 */ "USING",
  139180. /* 134 */ "ORDER",
  139181. /* 135 */ "GROUP",
  139182. /* 136 */ "HAVING",
  139183. /* 137 */ "LIMIT",
  139184. /* 138 */ "WHERE",
  139185. /* 139 */ "INTO",
  139186. /* 140 */ "NOTHING",
  139187. /* 141 */ "FLOAT",
  139188. /* 142 */ "BLOB",
  139189. /* 143 */ "INTEGER",
  139190. /* 144 */ "VARIABLE",
  139191. /* 145 */ "CASE",
  139192. /* 146 */ "WHEN",
  139193. /* 147 */ "THEN",
  139194. /* 148 */ "ELSE",
  139195. /* 149 */ "INDEX",
  139196. /* 150 */ "ALTER",
  139197. /* 151 */ "ADD",
  139198. /* 152 */ "WINDOW",
  139199. /* 153 */ "OVER",
  139200. /* 154 */ "FILTER",
  139201. /* 155 */ "input",
  139202. /* 156 */ "cmdlist",
  139203. /* 157 */ "ecmd",
  139204. /* 158 */ "cmdx",
  139205. /* 159 */ "explain",
  139206. /* 160 */ "cmd",
  139207. /* 161 */ "transtype",
  139208. /* 162 */ "trans_opt",
  139209. /* 163 */ "nm",
  139210. /* 164 */ "savepoint_opt",
  139211. /* 165 */ "create_table",
  139212. /* 166 */ "create_table_args",
  139213. /* 167 */ "createkw",
  139214. /* 168 */ "temp",
  139215. /* 169 */ "ifnotexists",
  139216. /* 170 */ "dbnm",
  139217. /* 171 */ "columnlist",
  139218. /* 172 */ "conslist_opt",
  139219. /* 173 */ "table_options",
  139220. /* 174 */ "select",
  139221. /* 175 */ "columnname",
  139222. /* 176 */ "carglist",
  139223. /* 177 */ "typetoken",
  139224. /* 178 */ "typename",
  139225. /* 179 */ "signed",
  139226. /* 180 */ "plus_num",
  139227. /* 181 */ "minus_num",
  139228. /* 182 */ "scanpt",
  139229. /* 183 */ "ccons",
  139230. /* 184 */ "term",
  139231. /* 185 */ "expr",
  139232. /* 186 */ "onconf",
  139233. /* 187 */ "sortorder",
  139234. /* 188 */ "autoinc",
  139235. /* 189 */ "eidlist_opt",
  139236. /* 190 */ "refargs",
  139237. /* 191 */ "defer_subclause",
  139238. /* 192 */ "refarg",
  139239. /* 193 */ "refact",
  139240. /* 194 */ "init_deferred_pred_opt",
  139241. /* 195 */ "conslist",
  139242. /* 196 */ "tconscomma",
  139243. /* 197 */ "tcons",
  139244. /* 198 */ "sortlist",
  139245. /* 199 */ "eidlist",
  139246. /* 200 */ "defer_subclause_opt",
  139247. /* 201 */ "orconf",
  139248. /* 202 */ "resolvetype",
  139249. /* 203 */ "raisetype",
  139250. /* 204 */ "ifexists",
  139251. /* 205 */ "fullname",
  139252. /* 206 */ "selectnowith",
  139253. /* 207 */ "oneselect",
  139254. /* 208 */ "wqlist",
  139255. /* 209 */ "multiselect_op",
  139256. /* 210 */ "distinct",
  139257. /* 211 */ "selcollist",
  139258. /* 212 */ "from",
  139259. /* 213 */ "where_opt",
  139260. /* 214 */ "groupby_opt",
  139261. /* 215 */ "having_opt",
  139262. /* 216 */ "orderby_opt",
  139263. /* 217 */ "limit_opt",
  139264. /* 218 */ "window_clause",
  139265. /* 219 */ "values",
  139266. /* 220 */ "nexprlist",
  139267. /* 221 */ "sclp",
  139268. /* 222 */ "as",
  139269. /* 223 */ "seltablist",
  139270. /* 224 */ "stl_prefix",
  139271. /* 225 */ "joinop",
  139272. /* 226 */ "indexed_opt",
  139273. /* 227 */ "on_opt",
  139274. /* 228 */ "using_opt",
  139275. /* 229 */ "exprlist",
  139276. /* 230 */ "xfullname",
  139277. /* 231 */ "idlist",
  139278. /* 232 */ "with",
  139279. /* 233 */ "setlist",
  139280. /* 234 */ "insert_cmd",
  139281. /* 235 */ "idlist_opt",
  139282. /* 236 */ "upsert",
  139283. /* 237 */ "over_clause",
  139284. /* 238 */ "likeop",
  139285. /* 239 */ "between_op",
  139286. /* 240 */ "in_op",
  139287. /* 241 */ "paren_exprlist",
  139288. /* 242 */ "case_operand",
  139289. /* 243 */ "case_exprlist",
  139290. /* 244 */ "case_else",
  139291. /* 245 */ "uniqueflag",
  139292. /* 246 */ "collate",
  139293. /* 247 */ "nmnum",
  139294. /* 248 */ "trigger_decl",
  139295. /* 249 */ "trigger_cmd_list",
  139296. /* 250 */ "trigger_time",
  139297. /* 251 */ "trigger_event",
  139298. /* 252 */ "foreach_clause",
  139299. /* 253 */ "when_clause",
  139300. /* 254 */ "trigger_cmd",
  139301. /* 255 */ "trnm",
  139302. /* 256 */ "tridxby",
  139303. /* 257 */ "database_kw_opt",
  139304. /* 258 */ "key_opt",
  139305. /* 259 */ "add_column_fullname",
  139306. /* 260 */ "kwcolumn_opt",
  139307. /* 261 */ "create_vtab",
  139308. /* 262 */ "vtabarglist",
  139309. /* 263 */ "vtabarg",
  139310. /* 264 */ "vtabargtoken",
  139311. /* 265 */ "lp",
  139312. /* 266 */ "anylist",
  139313. /* 267 */ "windowdefn_list",
  139314. /* 268 */ "windowdefn",
  139315. /* 269 */ "window",
  139316. /* 270 */ "frame_opt",
  139317. /* 271 */ "part_opt",
  139318. /* 272 */ "filter_opt",
  139319. /* 273 */ "range_or_rows",
  139320. /* 274 */ "frame_bound",
  139321. /* 275 */ "frame_bound_s",
  139322. /* 276 */ "frame_bound_e",
  139323. };
  139324. #endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
  139325. #ifndef NDEBUG
  139326. /* For tracing reduce actions, the names of all rules are required.
  139327. */
  139328. static const char *const yyRuleName[] = {
  139329. /* 0 */ "explain ::= EXPLAIN",
  139330. /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
  139331. /* 2 */ "cmdx ::= cmd",
  139332. /* 3 */ "cmd ::= BEGIN transtype trans_opt",
  139333. /* 4 */ "transtype ::=",
  139334. /* 5 */ "transtype ::= DEFERRED",
  139335. /* 6 */ "transtype ::= IMMEDIATE",
  139336. /* 7 */ "transtype ::= EXCLUSIVE",
  139337. /* 8 */ "cmd ::= COMMIT|END trans_opt",
  139338. /* 9 */ "cmd ::= ROLLBACK trans_opt",
  139339. /* 10 */ "cmd ::= SAVEPOINT nm",
  139340. /* 11 */ "cmd ::= RELEASE savepoint_opt nm",
  139341. /* 12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  139342. /* 13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  139343. /* 14 */ "createkw ::= CREATE",
  139344. /* 15 */ "ifnotexists ::=",
  139345. /* 16 */ "ifnotexists ::= IF NOT EXISTS",
  139346. /* 17 */ "temp ::= TEMP",
  139347. /* 18 */ "temp ::=",
  139348. /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  139349. /* 20 */ "create_table_args ::= AS select",
  139350. /* 21 */ "table_options ::=",
  139351. /* 22 */ "table_options ::= WITHOUT nm",
  139352. /* 23 */ "columnname ::= nm typetoken",
  139353. /* 24 */ "typetoken ::=",
  139354. /* 25 */ "typetoken ::= typename LP signed RP",
  139355. /* 26 */ "typetoken ::= typename LP signed COMMA signed RP",
  139356. /* 27 */ "typename ::= typename ID|STRING",
  139357. /* 28 */ "scanpt ::=",
  139358. /* 29 */ "ccons ::= CONSTRAINT nm",
  139359. /* 30 */ "ccons ::= DEFAULT scanpt term scanpt",
  139360. /* 31 */ "ccons ::= DEFAULT LP expr RP",
  139361. /* 32 */ "ccons ::= DEFAULT PLUS term scanpt",
  139362. /* 33 */ "ccons ::= DEFAULT MINUS term scanpt",
  139363. /* 34 */ "ccons ::= DEFAULT scanpt ID|INDEXED",
  139364. /* 35 */ "ccons ::= NOT NULL onconf",
  139365. /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  139366. /* 37 */ "ccons ::= UNIQUE onconf",
  139367. /* 38 */ "ccons ::= CHECK LP expr RP",
  139368. /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  139369. /* 40 */ "ccons ::= defer_subclause",
  139370. /* 41 */ "ccons ::= COLLATE ID|STRING",
  139371. /* 42 */ "autoinc ::=",
  139372. /* 43 */ "autoinc ::= AUTOINCR",
  139373. /* 44 */ "refargs ::=",
  139374. /* 45 */ "refargs ::= refargs refarg",
  139375. /* 46 */ "refarg ::= MATCH nm",
  139376. /* 47 */ "refarg ::= ON INSERT refact",
  139377. /* 48 */ "refarg ::= ON DELETE refact",
  139378. /* 49 */ "refarg ::= ON UPDATE refact",
  139379. /* 50 */ "refact ::= SET NULL",
  139380. /* 51 */ "refact ::= SET DEFAULT",
  139381. /* 52 */ "refact ::= CASCADE",
  139382. /* 53 */ "refact ::= RESTRICT",
  139383. /* 54 */ "refact ::= NO ACTION",
  139384. /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  139385. /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  139386. /* 57 */ "init_deferred_pred_opt ::=",
  139387. /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  139388. /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  139389. /* 60 */ "conslist_opt ::=",
  139390. /* 61 */ "tconscomma ::= COMMA",
  139391. /* 62 */ "tcons ::= CONSTRAINT nm",
  139392. /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  139393. /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  139394. /* 65 */ "tcons ::= CHECK LP expr RP onconf",
  139395. /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  139396. /* 67 */ "defer_subclause_opt ::=",
  139397. /* 68 */ "onconf ::=",
  139398. /* 69 */ "onconf ::= ON CONFLICT resolvetype",
  139399. /* 70 */ "orconf ::=",
  139400. /* 71 */ "orconf ::= OR resolvetype",
  139401. /* 72 */ "resolvetype ::= IGNORE",
  139402. /* 73 */ "resolvetype ::= REPLACE",
  139403. /* 74 */ "cmd ::= DROP TABLE ifexists fullname",
  139404. /* 75 */ "ifexists ::= IF EXISTS",
  139405. /* 76 */ "ifexists ::=",
  139406. /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  139407. /* 78 */ "cmd ::= DROP VIEW ifexists fullname",
  139408. /* 79 */ "cmd ::= select",
  139409. /* 80 */ "select ::= WITH wqlist selectnowith",
  139410. /* 81 */ "select ::= WITH RECURSIVE wqlist selectnowith",
  139411. /* 82 */ "select ::= selectnowith",
  139412. /* 83 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  139413. /* 84 */ "multiselect_op ::= UNION",
  139414. /* 85 */ "multiselect_op ::= UNION ALL",
  139415. /* 86 */ "multiselect_op ::= EXCEPT|INTERSECT",
  139416. /* 87 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  139417. /* 88 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt",
  139418. /* 89 */ "values ::= VALUES LP nexprlist RP",
  139419. /* 90 */ "values ::= values COMMA LP nexprlist RP",
  139420. /* 91 */ "distinct ::= DISTINCT",
  139421. /* 92 */ "distinct ::= ALL",
  139422. /* 93 */ "distinct ::=",
  139423. /* 94 */ "sclp ::=",
  139424. /* 95 */ "selcollist ::= sclp scanpt expr scanpt as",
  139425. /* 96 */ "selcollist ::= sclp scanpt STAR",
  139426. /* 97 */ "selcollist ::= sclp scanpt nm DOT STAR",
  139427. /* 98 */ "as ::= AS nm",
  139428. /* 99 */ "as ::=",
  139429. /* 100 */ "from ::=",
  139430. /* 101 */ "from ::= FROM seltablist",
  139431. /* 102 */ "stl_prefix ::= seltablist joinop",
  139432. /* 103 */ "stl_prefix ::=",
  139433. /* 104 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  139434. /* 105 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  139435. /* 106 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  139436. /* 107 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  139437. /* 108 */ "dbnm ::=",
  139438. /* 109 */ "dbnm ::= DOT nm",
  139439. /* 110 */ "fullname ::= nm",
  139440. /* 111 */ "fullname ::= nm DOT nm",
  139441. /* 112 */ "xfullname ::= nm",
  139442. /* 113 */ "xfullname ::= nm DOT nm",
  139443. /* 114 */ "xfullname ::= nm DOT nm AS nm",
  139444. /* 115 */ "xfullname ::= nm AS nm",
  139445. /* 116 */ "joinop ::= COMMA|JOIN",
  139446. /* 117 */ "joinop ::= JOIN_KW JOIN",
  139447. /* 118 */ "joinop ::= JOIN_KW nm JOIN",
  139448. /* 119 */ "joinop ::= JOIN_KW nm nm JOIN",
  139449. /* 120 */ "on_opt ::= ON expr",
  139450. /* 121 */ "on_opt ::=",
  139451. /* 122 */ "indexed_opt ::=",
  139452. /* 123 */ "indexed_opt ::= INDEXED BY nm",
  139453. /* 124 */ "indexed_opt ::= NOT INDEXED",
  139454. /* 125 */ "using_opt ::= USING LP idlist RP",
  139455. /* 126 */ "using_opt ::=",
  139456. /* 127 */ "orderby_opt ::=",
  139457. /* 128 */ "orderby_opt ::= ORDER BY sortlist",
  139458. /* 129 */ "sortlist ::= sortlist COMMA expr sortorder",
  139459. /* 130 */ "sortlist ::= expr sortorder",
  139460. /* 131 */ "sortorder ::= ASC",
  139461. /* 132 */ "sortorder ::= DESC",
  139462. /* 133 */ "sortorder ::=",
  139463. /* 134 */ "groupby_opt ::=",
  139464. /* 135 */ "groupby_opt ::= GROUP BY nexprlist",
  139465. /* 136 */ "having_opt ::=",
  139466. /* 137 */ "having_opt ::= HAVING expr",
  139467. /* 138 */ "limit_opt ::=",
  139468. /* 139 */ "limit_opt ::= LIMIT expr",
  139469. /* 140 */ "limit_opt ::= LIMIT expr OFFSET expr",
  139470. /* 141 */ "limit_opt ::= LIMIT expr COMMA expr",
  139471. /* 142 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt",
  139472. /* 143 */ "where_opt ::=",
  139473. /* 144 */ "where_opt ::= WHERE expr",
  139474. /* 145 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt",
  139475. /* 146 */ "setlist ::= setlist COMMA nm EQ expr",
  139476. /* 147 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
  139477. /* 148 */ "setlist ::= nm EQ expr",
  139478. /* 149 */ "setlist ::= LP idlist RP EQ expr",
  139479. /* 150 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
  139480. /* 151 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES",
  139481. /* 152 */ "upsert ::=",
  139482. /* 153 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt",
  139483. /* 154 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING",
  139484. /* 155 */ "upsert ::= ON CONFLICT DO NOTHING",
  139485. /* 156 */ "insert_cmd ::= INSERT orconf",
  139486. /* 157 */ "insert_cmd ::= REPLACE",
  139487. /* 158 */ "idlist_opt ::=",
  139488. /* 159 */ "idlist_opt ::= LP idlist RP",
  139489. /* 160 */ "idlist ::= idlist COMMA nm",
  139490. /* 161 */ "idlist ::= nm",
  139491. /* 162 */ "expr ::= LP expr RP",
  139492. /* 163 */ "expr ::= ID|INDEXED",
  139493. /* 164 */ "expr ::= JOIN_KW",
  139494. /* 165 */ "expr ::= nm DOT nm",
  139495. /* 166 */ "expr ::= nm DOT nm DOT nm",
  139496. /* 167 */ "term ::= NULL|FLOAT|BLOB",
  139497. /* 168 */ "term ::= STRING",
  139498. /* 169 */ "term ::= INTEGER",
  139499. /* 170 */ "expr ::= VARIABLE",
  139500. /* 171 */ "expr ::= expr COLLATE ID|STRING",
  139501. /* 172 */ "expr ::= CAST LP expr AS typetoken RP",
  139502. /* 173 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  139503. /* 174 */ "expr ::= ID|INDEXED LP STAR RP",
  139504. /* 175 */ "expr ::= ID|INDEXED LP distinct exprlist RP over_clause",
  139505. /* 176 */ "expr ::= ID|INDEXED LP STAR RP over_clause",
  139506. /* 177 */ "term ::= CTIME_KW",
  139507. /* 178 */ "expr ::= LP nexprlist COMMA expr RP",
  139508. /* 179 */ "expr ::= expr AND expr",
  139509. /* 180 */ "expr ::= expr OR expr",
  139510. /* 181 */ "expr ::= expr LT|GT|GE|LE expr",
  139511. /* 182 */ "expr ::= expr EQ|NE expr",
  139512. /* 183 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  139513. /* 184 */ "expr ::= expr PLUS|MINUS expr",
  139514. /* 185 */ "expr ::= expr STAR|SLASH|REM expr",
  139515. /* 186 */ "expr ::= expr CONCAT expr",
  139516. /* 187 */ "likeop ::= NOT LIKE_KW|MATCH",
  139517. /* 188 */ "expr ::= expr likeop expr",
  139518. /* 189 */ "expr ::= expr likeop expr ESCAPE expr",
  139519. /* 190 */ "expr ::= expr ISNULL|NOTNULL",
  139520. /* 191 */ "expr ::= expr NOT NULL",
  139521. /* 192 */ "expr ::= expr IS expr",
  139522. /* 193 */ "expr ::= expr IS NOT expr",
  139523. /* 194 */ "expr ::= NOT expr",
  139524. /* 195 */ "expr ::= BITNOT expr",
  139525. /* 196 */ "expr ::= PLUS|MINUS expr",
  139526. /* 197 */ "between_op ::= BETWEEN",
  139527. /* 198 */ "between_op ::= NOT BETWEEN",
  139528. /* 199 */ "expr ::= expr between_op expr AND expr",
  139529. /* 200 */ "in_op ::= IN",
  139530. /* 201 */ "in_op ::= NOT IN",
  139531. /* 202 */ "expr ::= expr in_op LP exprlist RP",
  139532. /* 203 */ "expr ::= LP select RP",
  139533. /* 204 */ "expr ::= expr in_op LP select RP",
  139534. /* 205 */ "expr ::= expr in_op nm dbnm paren_exprlist",
  139535. /* 206 */ "expr ::= EXISTS LP select RP",
  139536. /* 207 */ "expr ::= CASE case_operand case_exprlist case_else END",
  139537. /* 208 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  139538. /* 209 */ "case_exprlist ::= WHEN expr THEN expr",
  139539. /* 210 */ "case_else ::= ELSE expr",
  139540. /* 211 */ "case_else ::=",
  139541. /* 212 */ "case_operand ::= expr",
  139542. /* 213 */ "case_operand ::=",
  139543. /* 214 */ "exprlist ::=",
  139544. /* 215 */ "nexprlist ::= nexprlist COMMA expr",
  139545. /* 216 */ "nexprlist ::= expr",
  139546. /* 217 */ "paren_exprlist ::=",
  139547. /* 218 */ "paren_exprlist ::= LP exprlist RP",
  139548. /* 219 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  139549. /* 220 */ "uniqueflag ::= UNIQUE",
  139550. /* 221 */ "uniqueflag ::=",
  139551. /* 222 */ "eidlist_opt ::=",
  139552. /* 223 */ "eidlist_opt ::= LP eidlist RP",
  139553. /* 224 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  139554. /* 225 */ "eidlist ::= nm collate sortorder",
  139555. /* 226 */ "collate ::=",
  139556. /* 227 */ "collate ::= COLLATE ID|STRING",
  139557. /* 228 */ "cmd ::= DROP INDEX ifexists fullname",
  139558. /* 229 */ "cmd ::= VACUUM",
  139559. /* 230 */ "cmd ::= VACUUM nm",
  139560. /* 231 */ "cmd ::= PRAGMA nm dbnm",
  139561. /* 232 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  139562. /* 233 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  139563. /* 234 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  139564. /* 235 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  139565. /* 236 */ "plus_num ::= PLUS INTEGER|FLOAT",
  139566. /* 237 */ "minus_num ::= MINUS INTEGER|FLOAT",
  139567. /* 238 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  139568. /* 239 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  139569. /* 240 */ "trigger_time ::= BEFORE|AFTER",
  139570. /* 241 */ "trigger_time ::= INSTEAD OF",
  139571. /* 242 */ "trigger_time ::=",
  139572. /* 243 */ "trigger_event ::= DELETE|INSERT",
  139573. /* 244 */ "trigger_event ::= UPDATE",
  139574. /* 245 */ "trigger_event ::= UPDATE OF idlist",
  139575. /* 246 */ "when_clause ::=",
  139576. /* 247 */ "when_clause ::= WHEN expr",
  139577. /* 248 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  139578. /* 249 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  139579. /* 250 */ "trnm ::= nm DOT nm",
  139580. /* 251 */ "tridxby ::= INDEXED BY nm",
  139581. /* 252 */ "tridxby ::= NOT INDEXED",
  139582. /* 253 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt",
  139583. /* 254 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
  139584. /* 255 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
  139585. /* 256 */ "trigger_cmd ::= scanpt select scanpt",
  139586. /* 257 */ "expr ::= RAISE LP IGNORE RP",
  139587. /* 258 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  139588. /* 259 */ "raisetype ::= ROLLBACK",
  139589. /* 260 */ "raisetype ::= ABORT",
  139590. /* 261 */ "raisetype ::= FAIL",
  139591. /* 262 */ "cmd ::= DROP TRIGGER ifexists fullname",
  139592. /* 263 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  139593. /* 264 */ "cmd ::= DETACH database_kw_opt expr",
  139594. /* 265 */ "key_opt ::=",
  139595. /* 266 */ "key_opt ::= KEY expr",
  139596. /* 267 */ "cmd ::= REINDEX",
  139597. /* 268 */ "cmd ::= REINDEX nm dbnm",
  139598. /* 269 */ "cmd ::= ANALYZE",
  139599. /* 270 */ "cmd ::= ANALYZE nm dbnm",
  139600. /* 271 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  139601. /* 272 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
  139602. /* 273 */ "add_column_fullname ::= fullname",
  139603. /* 274 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
  139604. /* 275 */ "cmd ::= create_vtab",
  139605. /* 276 */ "cmd ::= create_vtab LP vtabarglist RP",
  139606. /* 277 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  139607. /* 278 */ "vtabarg ::=",
  139608. /* 279 */ "vtabargtoken ::= ANY",
  139609. /* 280 */ "vtabargtoken ::= lp anylist RP",
  139610. /* 281 */ "lp ::= LP",
  139611. /* 282 */ "with ::= WITH wqlist",
  139612. /* 283 */ "with ::= WITH RECURSIVE wqlist",
  139613. /* 284 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  139614. /* 285 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  139615. /* 286 */ "windowdefn_list ::= windowdefn",
  139616. /* 287 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
  139617. /* 288 */ "windowdefn ::= nm AS window",
  139618. /* 289 */ "window ::= LP part_opt orderby_opt frame_opt RP",
  139619. /* 290 */ "part_opt ::= PARTITION BY nexprlist",
  139620. /* 291 */ "part_opt ::=",
  139621. /* 292 */ "frame_opt ::=",
  139622. /* 293 */ "frame_opt ::= range_or_rows frame_bound_s",
  139623. /* 294 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e",
  139624. /* 295 */ "range_or_rows ::= RANGE",
  139625. /* 296 */ "range_or_rows ::= ROWS",
  139626. /* 297 */ "frame_bound_s ::= frame_bound",
  139627. /* 298 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
  139628. /* 299 */ "frame_bound_e ::= frame_bound",
  139629. /* 300 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
  139630. /* 301 */ "frame_bound ::= expr PRECEDING",
  139631. /* 302 */ "frame_bound ::= CURRENT ROW",
  139632. /* 303 */ "frame_bound ::= expr FOLLOWING",
  139633. /* 304 */ "window_clause ::= WINDOW windowdefn_list",
  139634. /* 305 */ "over_clause ::= filter_opt OVER window",
  139635. /* 306 */ "over_clause ::= filter_opt OVER nm",
  139636. /* 307 */ "filter_opt ::=",
  139637. /* 308 */ "filter_opt ::= FILTER LP WHERE expr RP",
  139638. /* 309 */ "input ::= cmdlist",
  139639. /* 310 */ "cmdlist ::= cmdlist ecmd",
  139640. /* 311 */ "cmdlist ::= ecmd",
  139641. /* 312 */ "ecmd ::= SEMI",
  139642. /* 313 */ "ecmd ::= cmdx SEMI",
  139643. /* 314 */ "ecmd ::= explain cmdx",
  139644. /* 315 */ "trans_opt ::=",
  139645. /* 316 */ "trans_opt ::= TRANSACTION",
  139646. /* 317 */ "trans_opt ::= TRANSACTION nm",
  139647. /* 318 */ "savepoint_opt ::= SAVEPOINT",
  139648. /* 319 */ "savepoint_opt ::=",
  139649. /* 320 */ "cmd ::= create_table create_table_args",
  139650. /* 321 */ "columnlist ::= columnlist COMMA columnname carglist",
  139651. /* 322 */ "columnlist ::= columnname carglist",
  139652. /* 323 */ "nm ::= ID|INDEXED",
  139653. /* 324 */ "nm ::= STRING",
  139654. /* 325 */ "nm ::= JOIN_KW",
  139655. /* 326 */ "typetoken ::= typename",
  139656. /* 327 */ "typename ::= ID|STRING",
  139657. /* 328 */ "signed ::= plus_num",
  139658. /* 329 */ "signed ::= minus_num",
  139659. /* 330 */ "carglist ::= carglist ccons",
  139660. /* 331 */ "carglist ::=",
  139661. /* 332 */ "ccons ::= NULL onconf",
  139662. /* 333 */ "conslist_opt ::= COMMA conslist",
  139663. /* 334 */ "conslist ::= conslist tconscomma tcons",
  139664. /* 335 */ "conslist ::= tcons",
  139665. /* 336 */ "tconscomma ::=",
  139666. /* 337 */ "defer_subclause_opt ::= defer_subclause",
  139667. /* 338 */ "resolvetype ::= raisetype",
  139668. /* 339 */ "selectnowith ::= oneselect",
  139669. /* 340 */ "oneselect ::= values",
  139670. /* 341 */ "sclp ::= selcollist COMMA",
  139671. /* 342 */ "as ::= ID|STRING",
  139672. /* 343 */ "expr ::= term",
  139673. /* 344 */ "likeop ::= LIKE_KW|MATCH",
  139674. /* 345 */ "exprlist ::= nexprlist",
  139675. /* 346 */ "nmnum ::= plus_num",
  139676. /* 347 */ "nmnum ::= nm",
  139677. /* 348 */ "nmnum ::= ON",
  139678. /* 349 */ "nmnum ::= DELETE",
  139679. /* 350 */ "nmnum ::= DEFAULT",
  139680. /* 351 */ "plus_num ::= INTEGER|FLOAT",
  139681. /* 352 */ "foreach_clause ::=",
  139682. /* 353 */ "foreach_clause ::= FOR EACH ROW",
  139683. /* 354 */ "trnm ::= nm",
  139684. /* 355 */ "tridxby ::=",
  139685. /* 356 */ "database_kw_opt ::= DATABASE",
  139686. /* 357 */ "database_kw_opt ::=",
  139687. /* 358 */ "kwcolumn_opt ::=",
  139688. /* 359 */ "kwcolumn_opt ::= COLUMNKW",
  139689. /* 360 */ "vtabarglist ::= vtabarg",
  139690. /* 361 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  139691. /* 362 */ "vtabarg ::= vtabarg vtabargtoken",
  139692. /* 363 */ "anylist ::=",
  139693. /* 364 */ "anylist ::= anylist LP anylist RP",
  139694. /* 365 */ "anylist ::= anylist ANY",
  139695. /* 366 */ "with ::=",
  139696. };
  139697. #endif /* NDEBUG */
  139698. #if YYSTACKDEPTH<=0
  139699. /*
  139700. ** Try to increase the size of the parser stack. Return the number
  139701. ** of errors. Return 0 on success.
  139702. */
  139703. static int yyGrowStack(yyParser *p){
  139704. int newSize;
  139705. int idx;
  139706. yyStackEntry *pNew;
  139707. newSize = p->yystksz*2 + 100;
  139708. idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
  139709. if( p->yystack==&p->yystk0 ){
  139710. pNew = malloc(newSize*sizeof(pNew[0]));
  139711. if( pNew ) pNew[0] = p->yystk0;
  139712. }else{
  139713. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  139714. }
  139715. if( pNew ){
  139716. p->yystack = pNew;
  139717. p->yytos = &p->yystack[idx];
  139718. #ifndef NDEBUG
  139719. if( yyTraceFILE ){
  139720. fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  139721. yyTracePrompt, p->yystksz, newSize);
  139722. }
  139723. #endif
  139724. p->yystksz = newSize;
  139725. }
  139726. return pNew==0;
  139727. }
  139728. #endif
  139729. /* Datatype of the argument to the memory allocated passed as the
  139730. ** second argument to sqlite3ParserAlloc() below. This can be changed by
  139731. ** putting an appropriate #define in the %include section of the input
  139732. ** grammar.
  139733. */
  139734. #ifndef YYMALLOCARGTYPE
  139735. # define YYMALLOCARGTYPE size_t
  139736. #endif
  139737. /* Initialize a new parser that has already been allocated.
  139738. */
  139739. SQLITE_PRIVATE void sqlite3ParserInit(void *yypRawParser sqlite3ParserCTX_PDECL){
  139740. yyParser *yypParser = (yyParser*)yypRawParser;
  139741. sqlite3ParserCTX_STORE
  139742. #ifdef YYTRACKMAXSTACKDEPTH
  139743. yypParser->yyhwm = 0;
  139744. #endif
  139745. #if YYSTACKDEPTH<=0
  139746. yypParser->yytos = NULL;
  139747. yypParser->yystack = NULL;
  139748. yypParser->yystksz = 0;
  139749. if( yyGrowStack(yypParser) ){
  139750. yypParser->yystack = &yypParser->yystk0;
  139751. yypParser->yystksz = 1;
  139752. }
  139753. #endif
  139754. #ifndef YYNOERRORRECOVERY
  139755. yypParser->yyerrcnt = -1;
  139756. #endif
  139757. yypParser->yytos = yypParser->yystack;
  139758. yypParser->yystack[0].stateno = 0;
  139759. yypParser->yystack[0].major = 0;
  139760. #if YYSTACKDEPTH>0
  139761. yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1];
  139762. #endif
  139763. }
  139764. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  139765. /*
  139766. ** This function allocates a new parser.
  139767. ** The only argument is a pointer to a function which works like
  139768. ** malloc.
  139769. **
  139770. ** Inputs:
  139771. ** A pointer to the function used to allocate memory.
  139772. **
  139773. ** Outputs:
  139774. ** A pointer to a parser. This pointer is used in subsequent calls
  139775. ** to sqlite3Parser and sqlite3ParserFree.
  139776. */
  139777. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) sqlite3ParserCTX_PDECL){
  139778. yyParser *yypParser;
  139779. yypParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
  139780. if( yypParser ){
  139781. sqlite3ParserCTX_STORE
  139782. sqlite3ParserInit(yypParser sqlite3ParserCTX_PARAM);
  139783. }
  139784. return (void*)yypParser;
  139785. }
  139786. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  139787. /* The following function deletes the "minor type" or semantic value
  139788. ** associated with a symbol. The symbol can be either a terminal
  139789. ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
  139790. ** a pointer to the value to be deleted. The code used to do the
  139791. ** deletions is derived from the %destructor and/or %token_destructor
  139792. ** directives of the input grammar.
  139793. */
  139794. static void yy_destructor(
  139795. yyParser *yypParser, /* The parser */
  139796. YYCODETYPE yymajor, /* Type code for object to destroy */
  139797. YYMINORTYPE *yypminor /* The object to be destroyed */
  139798. ){
  139799. sqlite3ParserARG_FETCH
  139800. sqlite3ParserCTX_FETCH
  139801. switch( yymajor ){
  139802. /* Here is inserted the actions which take place when a
  139803. ** terminal or non-terminal is destroyed. This can happen
  139804. ** when the symbol is popped from the stack during a
  139805. ** reduce or during error processing or when a parser is
  139806. ** being destroyed before it is finished parsing.
  139807. **
  139808. ** Note: during a reduce, the only symbols destroyed are those
  139809. ** which appear on the RHS of the rule, but which are *not* used
  139810. ** inside the C code.
  139811. */
  139812. /********* Begin destructor definitions ***************************************/
  139813. case 174: /* select */
  139814. case 206: /* selectnowith */
  139815. case 207: /* oneselect */
  139816. case 219: /* values */
  139817. {
  139818. sqlite3SelectDelete(pParse->db, (yypminor->yy489));
  139819. }
  139820. break;
  139821. case 184: /* term */
  139822. case 185: /* expr */
  139823. case 213: /* where_opt */
  139824. case 215: /* having_opt */
  139825. case 227: /* on_opt */
  139826. case 242: /* case_operand */
  139827. case 244: /* case_else */
  139828. case 253: /* when_clause */
  139829. case 258: /* key_opt */
  139830. case 272: /* filter_opt */
  139831. {
  139832. sqlite3ExprDelete(pParse->db, (yypminor->yy18));
  139833. }
  139834. break;
  139835. case 189: /* eidlist_opt */
  139836. case 198: /* sortlist */
  139837. case 199: /* eidlist */
  139838. case 211: /* selcollist */
  139839. case 214: /* groupby_opt */
  139840. case 216: /* orderby_opt */
  139841. case 220: /* nexprlist */
  139842. case 221: /* sclp */
  139843. case 229: /* exprlist */
  139844. case 233: /* setlist */
  139845. case 241: /* paren_exprlist */
  139846. case 243: /* case_exprlist */
  139847. case 271: /* part_opt */
  139848. {
  139849. sqlite3ExprListDelete(pParse->db, (yypminor->yy420));
  139850. }
  139851. break;
  139852. case 205: /* fullname */
  139853. case 212: /* from */
  139854. case 223: /* seltablist */
  139855. case 224: /* stl_prefix */
  139856. case 230: /* xfullname */
  139857. {
  139858. sqlite3SrcListDelete(pParse->db, (yypminor->yy135));
  139859. }
  139860. break;
  139861. case 208: /* wqlist */
  139862. {
  139863. sqlite3WithDelete(pParse->db, (yypminor->yy449));
  139864. }
  139865. break;
  139866. case 218: /* window_clause */
  139867. case 267: /* windowdefn_list */
  139868. {
  139869. sqlite3WindowListDelete(pParse->db, (yypminor->yy327));
  139870. }
  139871. break;
  139872. case 228: /* using_opt */
  139873. case 231: /* idlist */
  139874. case 235: /* idlist_opt */
  139875. {
  139876. sqlite3IdListDelete(pParse->db, (yypminor->yy48));
  139877. }
  139878. break;
  139879. case 237: /* over_clause */
  139880. case 268: /* windowdefn */
  139881. case 269: /* window */
  139882. case 270: /* frame_opt */
  139883. {
  139884. sqlite3WindowDelete(pParse->db, (yypminor->yy327));
  139885. }
  139886. break;
  139887. case 249: /* trigger_cmd_list */
  139888. case 254: /* trigger_cmd */
  139889. {
  139890. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy207));
  139891. }
  139892. break;
  139893. case 251: /* trigger_event */
  139894. {
  139895. sqlite3IdListDelete(pParse->db, (yypminor->yy34).b);
  139896. }
  139897. break;
  139898. case 274: /* frame_bound */
  139899. case 275: /* frame_bound_s */
  139900. case 276: /* frame_bound_e */
  139901. {
  139902. sqlite3ExprDelete(pParse->db, (yypminor->yy119).pExpr);
  139903. }
  139904. break;
  139905. /********* End destructor definitions *****************************************/
  139906. default: break; /* If no destructor action specified: do nothing */
  139907. }
  139908. }
  139909. /*
  139910. ** Pop the parser's stack once.
  139911. **
  139912. ** If there is a destructor routine associated with the token which
  139913. ** is popped from the stack, then call it.
  139914. */
  139915. static void yy_pop_parser_stack(yyParser *pParser){
  139916. yyStackEntry *yytos;
  139917. assert( pParser->yytos!=0 );
  139918. assert( pParser->yytos > pParser->yystack );
  139919. yytos = pParser->yytos--;
  139920. #ifndef NDEBUG
  139921. if( yyTraceFILE ){
  139922. fprintf(yyTraceFILE,"%sPopping %s\n",
  139923. yyTracePrompt,
  139924. yyTokenName[yytos->major]);
  139925. }
  139926. #endif
  139927. yy_destructor(pParser, yytos->major, &yytos->minor);
  139928. }
  139929. /*
  139930. ** Clear all secondary memory allocations from the parser
  139931. */
  139932. SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
  139933. yyParser *pParser = (yyParser*)p;
  139934. while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
  139935. #if YYSTACKDEPTH<=0
  139936. if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
  139937. #endif
  139938. }
  139939. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  139940. /*
  139941. ** Deallocate and destroy a parser. Destructors are called for
  139942. ** all stack elements before shutting the parser down.
  139943. **
  139944. ** If the YYPARSEFREENEVERNULL macro exists (for example because it
  139945. ** is defined in a %include section of the input grammar) then it is
  139946. ** assumed that the input pointer is never NULL.
  139947. */
  139948. SQLITE_PRIVATE void sqlite3ParserFree(
  139949. void *p, /* The parser to be deleted */
  139950. void (*freeProc)(void*) /* Function used to reclaim memory */
  139951. ){
  139952. #ifndef YYPARSEFREENEVERNULL
  139953. if( p==0 ) return;
  139954. #endif
  139955. sqlite3ParserFinalize(p);
  139956. (*freeProc)(p);
  139957. }
  139958. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  139959. /*
  139960. ** Return the peak depth of the stack for a parser.
  139961. */
  139962. #ifdef YYTRACKMAXSTACKDEPTH
  139963. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  139964. yyParser *pParser = (yyParser*)p;
  139965. return pParser->yyhwm;
  139966. }
  139967. #endif
  139968. /* This array of booleans keeps track of the parser statement
  139969. ** coverage. The element yycoverage[X][Y] is set when the parser
  139970. ** is in state X and has a lookahead token Y. In a well-tested
  139971. ** systems, every element of this matrix should end up being set.
  139972. */
  139973. #if defined(YYCOVERAGE)
  139974. static unsigned char yycoverage[YYNSTATE][YYNTOKEN];
  139975. #endif
  139976. /*
  139977. ** Write into out a description of every state/lookahead combination that
  139978. **
  139979. ** (1) has not been used by the parser, and
  139980. ** (2) is not a syntax error.
  139981. **
  139982. ** Return the number of missed state/lookahead combinations.
  139983. */
  139984. #if defined(YYCOVERAGE)
  139985. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){
  139986. int stateno, iLookAhead, i;
  139987. int nMissed = 0;
  139988. for(stateno=0; stateno<YYNSTATE; stateno++){
  139989. i = yy_shift_ofst[stateno];
  139990. for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){
  139991. if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  139992. if( yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  139993. if( out ){
  139994. fprintf(out,"State %d lookahead %s %s\n", stateno,
  139995. yyTokenName[iLookAhead],
  139996. yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  139997. }
  139998. }
  139999. }
  140000. return nMissed;
  140001. }
  140002. #endif
  140003. /*
  140004. ** Find the appropriate action for a parser given the terminal
  140005. ** look-ahead token iLookAhead.
  140006. */
  140007. static YYACTIONTYPE yy_find_shift_action(
  140008. YYCODETYPE iLookAhead, /* The look-ahead token */
  140009. YYACTIONTYPE stateno /* Current state number */
  140010. ){
  140011. int i;
  140012. if( stateno>YY_MAX_SHIFT ) return stateno;
  140013. assert( stateno <= YY_SHIFT_COUNT );
  140014. #if defined(YYCOVERAGE)
  140015. yycoverage[stateno][iLookAhead] = 1;
  140016. #endif
  140017. do{
  140018. i = yy_shift_ofst[stateno];
  140019. assert( i>=0 );
  140020. /* assert( i+YYNTOKEN<=(int)YY_NLOOKAHEAD ); */
  140021. assert( iLookAhead!=YYNOCODE );
  140022. assert( iLookAhead < YYNTOKEN );
  140023. i += iLookAhead;
  140024. if( i>=YY_NLOOKAHEAD || yy_lookahead[i]!=iLookAhead ){
  140025. #ifdef YYFALLBACK
  140026. YYCODETYPE iFallback; /* Fallback token */
  140027. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  140028. && (iFallback = yyFallback[iLookAhead])!=0 ){
  140029. #ifndef NDEBUG
  140030. if( yyTraceFILE ){
  140031. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  140032. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  140033. }
  140034. #endif
  140035. assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  140036. iLookAhead = iFallback;
  140037. continue;
  140038. }
  140039. #endif
  140040. #ifdef YYWILDCARD
  140041. {
  140042. int j = i - iLookAhead + YYWILDCARD;
  140043. if(
  140044. #if YY_SHIFT_MIN+YYWILDCARD<0
  140045. j>=0 &&
  140046. #endif
  140047. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  140048. j<YY_ACTTAB_COUNT &&
  140049. #endif
  140050. j<(int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])) &&
  140051. yy_lookahead[j]==YYWILDCARD && iLookAhead>0
  140052. ){
  140053. #ifndef NDEBUG
  140054. if( yyTraceFILE ){
  140055. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  140056. yyTracePrompt, yyTokenName[iLookAhead],
  140057. yyTokenName[YYWILDCARD]);
  140058. }
  140059. #endif /* NDEBUG */
  140060. return yy_action[j];
  140061. }
  140062. }
  140063. #endif /* YYWILDCARD */
  140064. return yy_default[stateno];
  140065. }else{
  140066. return yy_action[i];
  140067. }
  140068. }while(1);
  140069. }
  140070. /*
  140071. ** Find the appropriate action for a parser given the non-terminal
  140072. ** look-ahead token iLookAhead.
  140073. */
  140074. static YYACTIONTYPE yy_find_reduce_action(
  140075. YYACTIONTYPE stateno, /* Current state number */
  140076. YYCODETYPE iLookAhead /* The look-ahead token */
  140077. ){
  140078. int i;
  140079. #ifdef YYERRORSYMBOL
  140080. if( stateno>YY_REDUCE_COUNT ){
  140081. return yy_default[stateno];
  140082. }
  140083. #else
  140084. assert( stateno<=YY_REDUCE_COUNT );
  140085. #endif
  140086. i = yy_reduce_ofst[stateno];
  140087. assert( iLookAhead!=YYNOCODE );
  140088. i += iLookAhead;
  140089. #ifdef YYERRORSYMBOL
  140090. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  140091. return yy_default[stateno];
  140092. }
  140093. #else
  140094. assert( i>=0 && i<YY_ACTTAB_COUNT );
  140095. assert( yy_lookahead[i]==iLookAhead );
  140096. #endif
  140097. return yy_action[i];
  140098. }
  140099. /*
  140100. ** The following routine is called if the stack overflows.
  140101. */
  140102. static void yyStackOverflow(yyParser *yypParser){
  140103. sqlite3ParserARG_FETCH
  140104. sqlite3ParserCTX_FETCH
  140105. #ifndef NDEBUG
  140106. if( yyTraceFILE ){
  140107. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  140108. }
  140109. #endif
  140110. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  140111. /* Here code is inserted which will execute if the parser
  140112. ** stack every overflows */
  140113. /******** Begin %stack_overflow code ******************************************/
  140114. sqlite3ErrorMsg(pParse, "parser stack overflow");
  140115. /******** End %stack_overflow code ********************************************/
  140116. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */
  140117. sqlite3ParserCTX_STORE
  140118. }
  140119. /*
  140120. ** Print tracing information for a SHIFT action
  140121. */
  140122. #ifndef NDEBUG
  140123. static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){
  140124. if( yyTraceFILE ){
  140125. if( yyNewState<YYNSTATE ){
  140126. fprintf(yyTraceFILE,"%s%s '%s', go to state %d\n",
  140127. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  140128. yyNewState);
  140129. }else{
  140130. fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  140131. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  140132. yyNewState - YY_MIN_REDUCE);
  140133. }
  140134. }
  140135. }
  140136. #else
  140137. # define yyTraceShift(X,Y,Z)
  140138. #endif
  140139. /*
  140140. ** Perform a shift action.
  140141. */
  140142. static void yy_shift(
  140143. yyParser *yypParser, /* The parser to be shifted */
  140144. YYACTIONTYPE yyNewState, /* The new state to shift in */
  140145. YYCODETYPE yyMajor, /* The major token to shift in */
  140146. sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
  140147. ){
  140148. yyStackEntry *yytos;
  140149. yypParser->yytos++;
  140150. #ifdef YYTRACKMAXSTACKDEPTH
  140151. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  140152. yypParser->yyhwm++;
  140153. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
  140154. }
  140155. #endif
  140156. #if YYSTACKDEPTH>0
  140157. if( yypParser->yytos>yypParser->yystackEnd ){
  140158. yypParser->yytos--;
  140159. yyStackOverflow(yypParser);
  140160. return;
  140161. }
  140162. #else
  140163. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
  140164. if( yyGrowStack(yypParser) ){
  140165. yypParser->yytos--;
  140166. yyStackOverflow(yypParser);
  140167. return;
  140168. }
  140169. }
  140170. #endif
  140171. if( yyNewState > YY_MAX_SHIFT ){
  140172. yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  140173. }
  140174. yytos = yypParser->yytos;
  140175. yytos->stateno = yyNewState;
  140176. yytos->major = yyMajor;
  140177. yytos->minor.yy0 = yyMinor;
  140178. yyTraceShift(yypParser, yyNewState, "Shift");
  140179. }
  140180. /* The following table contains information about every rule that
  140181. ** is used during the reduce.
  140182. */
  140183. static const struct {
  140184. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  140185. signed char nrhs; /* Negative of the number of RHS symbols in the rule */
  140186. } yyRuleInfo[] = {
  140187. { 159, -1 }, /* (0) explain ::= EXPLAIN */
  140188. { 159, -3 }, /* (1) explain ::= EXPLAIN QUERY PLAN */
  140189. { 158, -1 }, /* (2) cmdx ::= cmd */
  140190. { 160, -3 }, /* (3) cmd ::= BEGIN transtype trans_opt */
  140191. { 161, 0 }, /* (4) transtype ::= */
  140192. { 161, -1 }, /* (5) transtype ::= DEFERRED */
  140193. { 161, -1 }, /* (6) transtype ::= IMMEDIATE */
  140194. { 161, -1 }, /* (7) transtype ::= EXCLUSIVE */
  140195. { 160, -2 }, /* (8) cmd ::= COMMIT|END trans_opt */
  140196. { 160, -2 }, /* (9) cmd ::= ROLLBACK trans_opt */
  140197. { 160, -2 }, /* (10) cmd ::= SAVEPOINT nm */
  140198. { 160, -3 }, /* (11) cmd ::= RELEASE savepoint_opt nm */
  140199. { 160, -5 }, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  140200. { 165, -6 }, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  140201. { 167, -1 }, /* (14) createkw ::= CREATE */
  140202. { 169, 0 }, /* (15) ifnotexists ::= */
  140203. { 169, -3 }, /* (16) ifnotexists ::= IF NOT EXISTS */
  140204. { 168, -1 }, /* (17) temp ::= TEMP */
  140205. { 168, 0 }, /* (18) temp ::= */
  140206. { 166, -5 }, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
  140207. { 166, -2 }, /* (20) create_table_args ::= AS select */
  140208. { 173, 0 }, /* (21) table_options ::= */
  140209. { 173, -2 }, /* (22) table_options ::= WITHOUT nm */
  140210. { 175, -2 }, /* (23) columnname ::= nm typetoken */
  140211. { 177, 0 }, /* (24) typetoken ::= */
  140212. { 177, -4 }, /* (25) typetoken ::= typename LP signed RP */
  140213. { 177, -6 }, /* (26) typetoken ::= typename LP signed COMMA signed RP */
  140214. { 178, -2 }, /* (27) typename ::= typename ID|STRING */
  140215. { 182, 0 }, /* (28) scanpt ::= */
  140216. { 183, -2 }, /* (29) ccons ::= CONSTRAINT nm */
  140217. { 183, -4 }, /* (30) ccons ::= DEFAULT scanpt term scanpt */
  140218. { 183, -4 }, /* (31) ccons ::= DEFAULT LP expr RP */
  140219. { 183, -4 }, /* (32) ccons ::= DEFAULT PLUS term scanpt */
  140220. { 183, -4 }, /* (33) ccons ::= DEFAULT MINUS term scanpt */
  140221. { 183, -3 }, /* (34) ccons ::= DEFAULT scanpt ID|INDEXED */
  140222. { 183, -3 }, /* (35) ccons ::= NOT NULL onconf */
  140223. { 183, -5 }, /* (36) ccons ::= PRIMARY KEY sortorder onconf autoinc */
  140224. { 183, -2 }, /* (37) ccons ::= UNIQUE onconf */
  140225. { 183, -4 }, /* (38) ccons ::= CHECK LP expr RP */
  140226. { 183, -4 }, /* (39) ccons ::= REFERENCES nm eidlist_opt refargs */
  140227. { 183, -1 }, /* (40) ccons ::= defer_subclause */
  140228. { 183, -2 }, /* (41) ccons ::= COLLATE ID|STRING */
  140229. { 188, 0 }, /* (42) autoinc ::= */
  140230. { 188, -1 }, /* (43) autoinc ::= AUTOINCR */
  140231. { 190, 0 }, /* (44) refargs ::= */
  140232. { 190, -2 }, /* (45) refargs ::= refargs refarg */
  140233. { 192, -2 }, /* (46) refarg ::= MATCH nm */
  140234. { 192, -3 }, /* (47) refarg ::= ON INSERT refact */
  140235. { 192, -3 }, /* (48) refarg ::= ON DELETE refact */
  140236. { 192, -3 }, /* (49) refarg ::= ON UPDATE refact */
  140237. { 193, -2 }, /* (50) refact ::= SET NULL */
  140238. { 193, -2 }, /* (51) refact ::= SET DEFAULT */
  140239. { 193, -1 }, /* (52) refact ::= CASCADE */
  140240. { 193, -1 }, /* (53) refact ::= RESTRICT */
  140241. { 193, -2 }, /* (54) refact ::= NO ACTION */
  140242. { 191, -3 }, /* (55) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  140243. { 191, -2 }, /* (56) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  140244. { 194, 0 }, /* (57) init_deferred_pred_opt ::= */
  140245. { 194, -2 }, /* (58) init_deferred_pred_opt ::= INITIALLY DEFERRED */
  140246. { 194, -2 }, /* (59) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  140247. { 172, 0 }, /* (60) conslist_opt ::= */
  140248. { 196, -1 }, /* (61) tconscomma ::= COMMA */
  140249. { 197, -2 }, /* (62) tcons ::= CONSTRAINT nm */
  140250. { 197, -7 }, /* (63) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  140251. { 197, -5 }, /* (64) tcons ::= UNIQUE LP sortlist RP onconf */
  140252. { 197, -5 }, /* (65) tcons ::= CHECK LP expr RP onconf */
  140253. { 197, -10 }, /* (66) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  140254. { 200, 0 }, /* (67) defer_subclause_opt ::= */
  140255. { 186, 0 }, /* (68) onconf ::= */
  140256. { 186, -3 }, /* (69) onconf ::= ON CONFLICT resolvetype */
  140257. { 201, 0 }, /* (70) orconf ::= */
  140258. { 201, -2 }, /* (71) orconf ::= OR resolvetype */
  140259. { 202, -1 }, /* (72) resolvetype ::= IGNORE */
  140260. { 202, -1 }, /* (73) resolvetype ::= REPLACE */
  140261. { 160, -4 }, /* (74) cmd ::= DROP TABLE ifexists fullname */
  140262. { 204, -2 }, /* (75) ifexists ::= IF EXISTS */
  140263. { 204, 0 }, /* (76) ifexists ::= */
  140264. { 160, -9 }, /* (77) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  140265. { 160, -4 }, /* (78) cmd ::= DROP VIEW ifexists fullname */
  140266. { 160, -1 }, /* (79) cmd ::= select */
  140267. { 174, -3 }, /* (80) select ::= WITH wqlist selectnowith */
  140268. { 174, -4 }, /* (81) select ::= WITH RECURSIVE wqlist selectnowith */
  140269. { 174, -1 }, /* (82) select ::= selectnowith */
  140270. { 206, -3 }, /* (83) selectnowith ::= selectnowith multiselect_op oneselect */
  140271. { 209, -1 }, /* (84) multiselect_op ::= UNION */
  140272. { 209, -2 }, /* (85) multiselect_op ::= UNION ALL */
  140273. { 209, -1 }, /* (86) multiselect_op ::= EXCEPT|INTERSECT */
  140274. { 207, -9 }, /* (87) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  140275. { 207, -10 }, /* (88) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
  140276. { 219, -4 }, /* (89) values ::= VALUES LP nexprlist RP */
  140277. { 219, -5 }, /* (90) values ::= values COMMA LP nexprlist RP */
  140278. { 210, -1 }, /* (91) distinct ::= DISTINCT */
  140279. { 210, -1 }, /* (92) distinct ::= ALL */
  140280. { 210, 0 }, /* (93) distinct ::= */
  140281. { 221, 0 }, /* (94) sclp ::= */
  140282. { 211, -5 }, /* (95) selcollist ::= sclp scanpt expr scanpt as */
  140283. { 211, -3 }, /* (96) selcollist ::= sclp scanpt STAR */
  140284. { 211, -5 }, /* (97) selcollist ::= sclp scanpt nm DOT STAR */
  140285. { 222, -2 }, /* (98) as ::= AS nm */
  140286. { 222, 0 }, /* (99) as ::= */
  140287. { 212, 0 }, /* (100) from ::= */
  140288. { 212, -2 }, /* (101) from ::= FROM seltablist */
  140289. { 224, -2 }, /* (102) stl_prefix ::= seltablist joinop */
  140290. { 224, 0 }, /* (103) stl_prefix ::= */
  140291. { 223, -7 }, /* (104) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  140292. { 223, -9 }, /* (105) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  140293. { 223, -7 }, /* (106) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  140294. { 223, -7 }, /* (107) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  140295. { 170, 0 }, /* (108) dbnm ::= */
  140296. { 170, -2 }, /* (109) dbnm ::= DOT nm */
  140297. { 205, -1 }, /* (110) fullname ::= nm */
  140298. { 205, -3 }, /* (111) fullname ::= nm DOT nm */
  140299. { 230, -1 }, /* (112) xfullname ::= nm */
  140300. { 230, -3 }, /* (113) xfullname ::= nm DOT nm */
  140301. { 230, -5 }, /* (114) xfullname ::= nm DOT nm AS nm */
  140302. { 230, -3 }, /* (115) xfullname ::= nm AS nm */
  140303. { 225, -1 }, /* (116) joinop ::= COMMA|JOIN */
  140304. { 225, -2 }, /* (117) joinop ::= JOIN_KW JOIN */
  140305. { 225, -3 }, /* (118) joinop ::= JOIN_KW nm JOIN */
  140306. { 225, -4 }, /* (119) joinop ::= JOIN_KW nm nm JOIN */
  140307. { 227, -2 }, /* (120) on_opt ::= ON expr */
  140308. { 227, 0 }, /* (121) on_opt ::= */
  140309. { 226, 0 }, /* (122) indexed_opt ::= */
  140310. { 226, -3 }, /* (123) indexed_opt ::= INDEXED BY nm */
  140311. { 226, -2 }, /* (124) indexed_opt ::= NOT INDEXED */
  140312. { 228, -4 }, /* (125) using_opt ::= USING LP idlist RP */
  140313. { 228, 0 }, /* (126) using_opt ::= */
  140314. { 216, 0 }, /* (127) orderby_opt ::= */
  140315. { 216, -3 }, /* (128) orderby_opt ::= ORDER BY sortlist */
  140316. { 198, -4 }, /* (129) sortlist ::= sortlist COMMA expr sortorder */
  140317. { 198, -2 }, /* (130) sortlist ::= expr sortorder */
  140318. { 187, -1 }, /* (131) sortorder ::= ASC */
  140319. { 187, -1 }, /* (132) sortorder ::= DESC */
  140320. { 187, 0 }, /* (133) sortorder ::= */
  140321. { 214, 0 }, /* (134) groupby_opt ::= */
  140322. { 214, -3 }, /* (135) groupby_opt ::= GROUP BY nexprlist */
  140323. { 215, 0 }, /* (136) having_opt ::= */
  140324. { 215, -2 }, /* (137) having_opt ::= HAVING expr */
  140325. { 217, 0 }, /* (138) limit_opt ::= */
  140326. { 217, -2 }, /* (139) limit_opt ::= LIMIT expr */
  140327. { 217, -4 }, /* (140) limit_opt ::= LIMIT expr OFFSET expr */
  140328. { 217, -4 }, /* (141) limit_opt ::= LIMIT expr COMMA expr */
  140329. { 160, -6 }, /* (142) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  140330. { 213, 0 }, /* (143) where_opt ::= */
  140331. { 213, -2 }, /* (144) where_opt ::= WHERE expr */
  140332. { 160, -8 }, /* (145) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  140333. { 233, -5 }, /* (146) setlist ::= setlist COMMA nm EQ expr */
  140334. { 233, -7 }, /* (147) setlist ::= setlist COMMA LP idlist RP EQ expr */
  140335. { 233, -3 }, /* (148) setlist ::= nm EQ expr */
  140336. { 233, -5 }, /* (149) setlist ::= LP idlist RP EQ expr */
  140337. { 160, -7 }, /* (150) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  140338. { 160, -7 }, /* (151) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  140339. { 236, 0 }, /* (152) upsert ::= */
  140340. { 236, -11 }, /* (153) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  140341. { 236, -8 }, /* (154) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  140342. { 236, -4 }, /* (155) upsert ::= ON CONFLICT DO NOTHING */
  140343. { 234, -2 }, /* (156) insert_cmd ::= INSERT orconf */
  140344. { 234, -1 }, /* (157) insert_cmd ::= REPLACE */
  140345. { 235, 0 }, /* (158) idlist_opt ::= */
  140346. { 235, -3 }, /* (159) idlist_opt ::= LP idlist RP */
  140347. { 231, -3 }, /* (160) idlist ::= idlist COMMA nm */
  140348. { 231, -1 }, /* (161) idlist ::= nm */
  140349. { 185, -3 }, /* (162) expr ::= LP expr RP */
  140350. { 185, -1 }, /* (163) expr ::= ID|INDEXED */
  140351. { 185, -1 }, /* (164) expr ::= JOIN_KW */
  140352. { 185, -3 }, /* (165) expr ::= nm DOT nm */
  140353. { 185, -5 }, /* (166) expr ::= nm DOT nm DOT nm */
  140354. { 184, -1 }, /* (167) term ::= NULL|FLOAT|BLOB */
  140355. { 184, -1 }, /* (168) term ::= STRING */
  140356. { 184, -1 }, /* (169) term ::= INTEGER */
  140357. { 185, -1 }, /* (170) expr ::= VARIABLE */
  140358. { 185, -3 }, /* (171) expr ::= expr COLLATE ID|STRING */
  140359. { 185, -6 }, /* (172) expr ::= CAST LP expr AS typetoken RP */
  140360. { 185, -5 }, /* (173) expr ::= ID|INDEXED LP distinct exprlist RP */
  140361. { 185, -4 }, /* (174) expr ::= ID|INDEXED LP STAR RP */
  140362. { 185, -6 }, /* (175) expr ::= ID|INDEXED LP distinct exprlist RP over_clause */
  140363. { 185, -5 }, /* (176) expr ::= ID|INDEXED LP STAR RP over_clause */
  140364. { 184, -1 }, /* (177) term ::= CTIME_KW */
  140365. { 185, -5 }, /* (178) expr ::= LP nexprlist COMMA expr RP */
  140366. { 185, -3 }, /* (179) expr ::= expr AND expr */
  140367. { 185, -3 }, /* (180) expr ::= expr OR expr */
  140368. { 185, -3 }, /* (181) expr ::= expr LT|GT|GE|LE expr */
  140369. { 185, -3 }, /* (182) expr ::= expr EQ|NE expr */
  140370. { 185, -3 }, /* (183) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
  140371. { 185, -3 }, /* (184) expr ::= expr PLUS|MINUS expr */
  140372. { 185, -3 }, /* (185) expr ::= expr STAR|SLASH|REM expr */
  140373. { 185, -3 }, /* (186) expr ::= expr CONCAT expr */
  140374. { 238, -2 }, /* (187) likeop ::= NOT LIKE_KW|MATCH */
  140375. { 185, -3 }, /* (188) expr ::= expr likeop expr */
  140376. { 185, -5 }, /* (189) expr ::= expr likeop expr ESCAPE expr */
  140377. { 185, -2 }, /* (190) expr ::= expr ISNULL|NOTNULL */
  140378. { 185, -3 }, /* (191) expr ::= expr NOT NULL */
  140379. { 185, -3 }, /* (192) expr ::= expr IS expr */
  140380. { 185, -4 }, /* (193) expr ::= expr IS NOT expr */
  140381. { 185, -2 }, /* (194) expr ::= NOT expr */
  140382. { 185, -2 }, /* (195) expr ::= BITNOT expr */
  140383. { 185, -2 }, /* (196) expr ::= PLUS|MINUS expr */
  140384. { 239, -1 }, /* (197) between_op ::= BETWEEN */
  140385. { 239, -2 }, /* (198) between_op ::= NOT BETWEEN */
  140386. { 185, -5 }, /* (199) expr ::= expr between_op expr AND expr */
  140387. { 240, -1 }, /* (200) in_op ::= IN */
  140388. { 240, -2 }, /* (201) in_op ::= NOT IN */
  140389. { 185, -5 }, /* (202) expr ::= expr in_op LP exprlist RP */
  140390. { 185, -3 }, /* (203) expr ::= LP select RP */
  140391. { 185, -5 }, /* (204) expr ::= expr in_op LP select RP */
  140392. { 185, -5 }, /* (205) expr ::= expr in_op nm dbnm paren_exprlist */
  140393. { 185, -4 }, /* (206) expr ::= EXISTS LP select RP */
  140394. { 185, -5 }, /* (207) expr ::= CASE case_operand case_exprlist case_else END */
  140395. { 243, -5 }, /* (208) case_exprlist ::= case_exprlist WHEN expr THEN expr */
  140396. { 243, -4 }, /* (209) case_exprlist ::= WHEN expr THEN expr */
  140397. { 244, -2 }, /* (210) case_else ::= ELSE expr */
  140398. { 244, 0 }, /* (211) case_else ::= */
  140399. { 242, -1 }, /* (212) case_operand ::= expr */
  140400. { 242, 0 }, /* (213) case_operand ::= */
  140401. { 229, 0 }, /* (214) exprlist ::= */
  140402. { 220, -3 }, /* (215) nexprlist ::= nexprlist COMMA expr */
  140403. { 220, -1 }, /* (216) nexprlist ::= expr */
  140404. { 241, 0 }, /* (217) paren_exprlist ::= */
  140405. { 241, -3 }, /* (218) paren_exprlist ::= LP exprlist RP */
  140406. { 160, -12 }, /* (219) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  140407. { 245, -1 }, /* (220) uniqueflag ::= UNIQUE */
  140408. { 245, 0 }, /* (221) uniqueflag ::= */
  140409. { 189, 0 }, /* (222) eidlist_opt ::= */
  140410. { 189, -3 }, /* (223) eidlist_opt ::= LP eidlist RP */
  140411. { 199, -5 }, /* (224) eidlist ::= eidlist COMMA nm collate sortorder */
  140412. { 199, -3 }, /* (225) eidlist ::= nm collate sortorder */
  140413. { 246, 0 }, /* (226) collate ::= */
  140414. { 246, -2 }, /* (227) collate ::= COLLATE ID|STRING */
  140415. { 160, -4 }, /* (228) cmd ::= DROP INDEX ifexists fullname */
  140416. { 160, -1 }, /* (229) cmd ::= VACUUM */
  140417. { 160, -2 }, /* (230) cmd ::= VACUUM nm */
  140418. { 160, -3 }, /* (231) cmd ::= PRAGMA nm dbnm */
  140419. { 160, -5 }, /* (232) cmd ::= PRAGMA nm dbnm EQ nmnum */
  140420. { 160, -6 }, /* (233) cmd ::= PRAGMA nm dbnm LP nmnum RP */
  140421. { 160, -5 }, /* (234) cmd ::= PRAGMA nm dbnm EQ minus_num */
  140422. { 160, -6 }, /* (235) cmd ::= PRAGMA nm dbnm LP minus_num RP */
  140423. { 180, -2 }, /* (236) plus_num ::= PLUS INTEGER|FLOAT */
  140424. { 181, -2 }, /* (237) minus_num ::= MINUS INTEGER|FLOAT */
  140425. { 160, -5 }, /* (238) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  140426. { 248, -11 }, /* (239) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  140427. { 250, -1 }, /* (240) trigger_time ::= BEFORE|AFTER */
  140428. { 250, -2 }, /* (241) trigger_time ::= INSTEAD OF */
  140429. { 250, 0 }, /* (242) trigger_time ::= */
  140430. { 251, -1 }, /* (243) trigger_event ::= DELETE|INSERT */
  140431. { 251, -1 }, /* (244) trigger_event ::= UPDATE */
  140432. { 251, -3 }, /* (245) trigger_event ::= UPDATE OF idlist */
  140433. { 253, 0 }, /* (246) when_clause ::= */
  140434. { 253, -2 }, /* (247) when_clause ::= WHEN expr */
  140435. { 249, -3 }, /* (248) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  140436. { 249, -2 }, /* (249) trigger_cmd_list ::= trigger_cmd SEMI */
  140437. { 255, -3 }, /* (250) trnm ::= nm DOT nm */
  140438. { 256, -3 }, /* (251) tridxby ::= INDEXED BY nm */
  140439. { 256, -2 }, /* (252) tridxby ::= NOT INDEXED */
  140440. { 254, -8 }, /* (253) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  140441. { 254, -8 }, /* (254) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  140442. { 254, -6 }, /* (255) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  140443. { 254, -3 }, /* (256) trigger_cmd ::= scanpt select scanpt */
  140444. { 185, -4 }, /* (257) expr ::= RAISE LP IGNORE RP */
  140445. { 185, -6 }, /* (258) expr ::= RAISE LP raisetype COMMA nm RP */
  140446. { 203, -1 }, /* (259) raisetype ::= ROLLBACK */
  140447. { 203, -1 }, /* (260) raisetype ::= ABORT */
  140448. { 203, -1 }, /* (261) raisetype ::= FAIL */
  140449. { 160, -4 }, /* (262) cmd ::= DROP TRIGGER ifexists fullname */
  140450. { 160, -6 }, /* (263) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  140451. { 160, -3 }, /* (264) cmd ::= DETACH database_kw_opt expr */
  140452. { 258, 0 }, /* (265) key_opt ::= */
  140453. { 258, -2 }, /* (266) key_opt ::= KEY expr */
  140454. { 160, -1 }, /* (267) cmd ::= REINDEX */
  140455. { 160, -3 }, /* (268) cmd ::= REINDEX nm dbnm */
  140456. { 160, -1 }, /* (269) cmd ::= ANALYZE */
  140457. { 160, -3 }, /* (270) cmd ::= ANALYZE nm dbnm */
  140458. { 160, -6 }, /* (271) cmd ::= ALTER TABLE fullname RENAME TO nm */
  140459. { 160, -7 }, /* (272) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  140460. { 259, -1 }, /* (273) add_column_fullname ::= fullname */
  140461. { 160, -8 }, /* (274) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
  140462. { 160, -1 }, /* (275) cmd ::= create_vtab */
  140463. { 160, -4 }, /* (276) cmd ::= create_vtab LP vtabarglist RP */
  140464. { 261, -8 }, /* (277) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  140465. { 263, 0 }, /* (278) vtabarg ::= */
  140466. { 264, -1 }, /* (279) vtabargtoken ::= ANY */
  140467. { 264, -3 }, /* (280) vtabargtoken ::= lp anylist RP */
  140468. { 265, -1 }, /* (281) lp ::= LP */
  140469. { 232, -2 }, /* (282) with ::= WITH wqlist */
  140470. { 232, -3 }, /* (283) with ::= WITH RECURSIVE wqlist */
  140471. { 208, -6 }, /* (284) wqlist ::= nm eidlist_opt AS LP select RP */
  140472. { 208, -8 }, /* (285) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  140473. { 267, -1 }, /* (286) windowdefn_list ::= windowdefn */
  140474. { 267, -3 }, /* (287) windowdefn_list ::= windowdefn_list COMMA windowdefn */
  140475. { 268, -3 }, /* (288) windowdefn ::= nm AS window */
  140476. { 269, -5 }, /* (289) window ::= LP part_opt orderby_opt frame_opt RP */
  140477. { 271, -3 }, /* (290) part_opt ::= PARTITION BY nexprlist */
  140478. { 271, 0 }, /* (291) part_opt ::= */
  140479. { 270, 0 }, /* (292) frame_opt ::= */
  140480. { 270, -2 }, /* (293) frame_opt ::= range_or_rows frame_bound_s */
  140481. { 270, -5 }, /* (294) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e */
  140482. { 273, -1 }, /* (295) range_or_rows ::= RANGE */
  140483. { 273, -1 }, /* (296) range_or_rows ::= ROWS */
  140484. { 275, -1 }, /* (297) frame_bound_s ::= frame_bound */
  140485. { 275, -2 }, /* (298) frame_bound_s ::= UNBOUNDED PRECEDING */
  140486. { 276, -1 }, /* (299) frame_bound_e ::= frame_bound */
  140487. { 276, -2 }, /* (300) frame_bound_e ::= UNBOUNDED FOLLOWING */
  140488. { 274, -2 }, /* (301) frame_bound ::= expr PRECEDING */
  140489. { 274, -2 }, /* (302) frame_bound ::= CURRENT ROW */
  140490. { 274, -2 }, /* (303) frame_bound ::= expr FOLLOWING */
  140491. { 218, -2 }, /* (304) window_clause ::= WINDOW windowdefn_list */
  140492. { 237, -3 }, /* (305) over_clause ::= filter_opt OVER window */
  140493. { 237, -3 }, /* (306) over_clause ::= filter_opt OVER nm */
  140494. { 272, 0 }, /* (307) filter_opt ::= */
  140495. { 272, -5 }, /* (308) filter_opt ::= FILTER LP WHERE expr RP */
  140496. { 155, -1 }, /* (309) input ::= cmdlist */
  140497. { 156, -2 }, /* (310) cmdlist ::= cmdlist ecmd */
  140498. { 156, -1 }, /* (311) cmdlist ::= ecmd */
  140499. { 157, -1 }, /* (312) ecmd ::= SEMI */
  140500. { 157, -2 }, /* (313) ecmd ::= cmdx SEMI */
  140501. { 157, -2 }, /* (314) ecmd ::= explain cmdx */
  140502. { 162, 0 }, /* (315) trans_opt ::= */
  140503. { 162, -1 }, /* (316) trans_opt ::= TRANSACTION */
  140504. { 162, -2 }, /* (317) trans_opt ::= TRANSACTION nm */
  140505. { 164, -1 }, /* (318) savepoint_opt ::= SAVEPOINT */
  140506. { 164, 0 }, /* (319) savepoint_opt ::= */
  140507. { 160, -2 }, /* (320) cmd ::= create_table create_table_args */
  140508. { 171, -4 }, /* (321) columnlist ::= columnlist COMMA columnname carglist */
  140509. { 171, -2 }, /* (322) columnlist ::= columnname carglist */
  140510. { 163, -1 }, /* (323) nm ::= ID|INDEXED */
  140511. { 163, -1 }, /* (324) nm ::= STRING */
  140512. { 163, -1 }, /* (325) nm ::= JOIN_KW */
  140513. { 177, -1 }, /* (326) typetoken ::= typename */
  140514. { 178, -1 }, /* (327) typename ::= ID|STRING */
  140515. { 179, -1 }, /* (328) signed ::= plus_num */
  140516. { 179, -1 }, /* (329) signed ::= minus_num */
  140517. { 176, -2 }, /* (330) carglist ::= carglist ccons */
  140518. { 176, 0 }, /* (331) carglist ::= */
  140519. { 183, -2 }, /* (332) ccons ::= NULL onconf */
  140520. { 172, -2 }, /* (333) conslist_opt ::= COMMA conslist */
  140521. { 195, -3 }, /* (334) conslist ::= conslist tconscomma tcons */
  140522. { 195, -1 }, /* (335) conslist ::= tcons */
  140523. { 196, 0 }, /* (336) tconscomma ::= */
  140524. { 200, -1 }, /* (337) defer_subclause_opt ::= defer_subclause */
  140525. { 202, -1 }, /* (338) resolvetype ::= raisetype */
  140526. { 206, -1 }, /* (339) selectnowith ::= oneselect */
  140527. { 207, -1 }, /* (340) oneselect ::= values */
  140528. { 221, -2 }, /* (341) sclp ::= selcollist COMMA */
  140529. { 222, -1 }, /* (342) as ::= ID|STRING */
  140530. { 185, -1 }, /* (343) expr ::= term */
  140531. { 238, -1 }, /* (344) likeop ::= LIKE_KW|MATCH */
  140532. { 229, -1 }, /* (345) exprlist ::= nexprlist */
  140533. { 247, -1 }, /* (346) nmnum ::= plus_num */
  140534. { 247, -1 }, /* (347) nmnum ::= nm */
  140535. { 247, -1 }, /* (348) nmnum ::= ON */
  140536. { 247, -1 }, /* (349) nmnum ::= DELETE */
  140537. { 247, -1 }, /* (350) nmnum ::= DEFAULT */
  140538. { 180, -1 }, /* (351) plus_num ::= INTEGER|FLOAT */
  140539. { 252, 0 }, /* (352) foreach_clause ::= */
  140540. { 252, -3 }, /* (353) foreach_clause ::= FOR EACH ROW */
  140541. { 255, -1 }, /* (354) trnm ::= nm */
  140542. { 256, 0 }, /* (355) tridxby ::= */
  140543. { 257, -1 }, /* (356) database_kw_opt ::= DATABASE */
  140544. { 257, 0 }, /* (357) database_kw_opt ::= */
  140545. { 260, 0 }, /* (358) kwcolumn_opt ::= */
  140546. { 260, -1 }, /* (359) kwcolumn_opt ::= COLUMNKW */
  140547. { 262, -1 }, /* (360) vtabarglist ::= vtabarg */
  140548. { 262, -3 }, /* (361) vtabarglist ::= vtabarglist COMMA vtabarg */
  140549. { 263, -2 }, /* (362) vtabarg ::= vtabarg vtabargtoken */
  140550. { 266, 0 }, /* (363) anylist ::= */
  140551. { 266, -4 }, /* (364) anylist ::= anylist LP anylist RP */
  140552. { 266, -2 }, /* (365) anylist ::= anylist ANY */
  140553. { 232, 0 }, /* (366) with ::= */
  140554. };
  140555. static void yy_accept(yyParser*); /* Forward Declaration */
  140556. /*
  140557. ** Perform a reduce action and the shift that must immediately
  140558. ** follow the reduce.
  140559. **
  140560. ** The yyLookahead and yyLookaheadToken parameters provide reduce actions
  140561. ** access to the lookahead token (if any). The yyLookahead will be YYNOCODE
  140562. ** if the lookahead token has already been consumed. As this procedure is
  140563. ** only called from one place, optimizing compilers will in-line it, which
  140564. ** means that the extra parameters have no performance impact.
  140565. */
  140566. static YYACTIONTYPE yy_reduce(
  140567. yyParser *yypParser, /* The parser */
  140568. unsigned int yyruleno, /* Number of the rule by which to reduce */
  140569. int yyLookahead, /* Lookahead token, or YYNOCODE if none */
  140570. sqlite3ParserTOKENTYPE yyLookaheadToken /* Value of the lookahead token */
  140571. sqlite3ParserCTX_PDECL /* %extra_context */
  140572. ){
  140573. int yygoto; /* The next state */
  140574. YYACTIONTYPE yyact; /* The next action */
  140575. yyStackEntry *yymsp; /* The top of the parser's stack */
  140576. int yysize; /* Amount to pop the stack */
  140577. sqlite3ParserARG_FETCH
  140578. (void)yyLookahead;
  140579. (void)yyLookaheadToken;
  140580. yymsp = yypParser->yytos;
  140581. #ifndef NDEBUG
  140582. if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  140583. yysize = yyRuleInfo[yyruleno].nrhs;
  140584. if( yysize ){
  140585. fprintf(yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
  140586. yyTracePrompt,
  140587. yyruleno, yyRuleName[yyruleno], yymsp[yysize].stateno);
  140588. }else{
  140589. fprintf(yyTraceFILE, "%sReduce %d [%s].\n",
  140590. yyTracePrompt, yyruleno, yyRuleName[yyruleno]);
  140591. }
  140592. }
  140593. #endif /* NDEBUG */
  140594. /* Check that the stack is large enough to grow by a single entry
  140595. ** if the RHS of the rule is empty. This ensures that there is room
  140596. ** enough on the stack to push the LHS value */
  140597. if( yyRuleInfo[yyruleno].nrhs==0 ){
  140598. #ifdef YYTRACKMAXSTACKDEPTH
  140599. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  140600. yypParser->yyhwm++;
  140601. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
  140602. }
  140603. #endif
  140604. #if YYSTACKDEPTH>0
  140605. if( yypParser->yytos>=yypParser->yystackEnd ){
  140606. yyStackOverflow(yypParser);
  140607. /* The call to yyStackOverflow() above pops the stack until it is
  140608. ** empty, causing the main parser loop to exit. So the return value
  140609. ** is never used and does not matter. */
  140610. return 0;
  140611. }
  140612. #else
  140613. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
  140614. if( yyGrowStack(yypParser) ){
  140615. yyStackOverflow(yypParser);
  140616. /* The call to yyStackOverflow() above pops the stack until it is
  140617. ** empty, causing the main parser loop to exit. So the return value
  140618. ** is never used and does not matter. */
  140619. return 0;
  140620. }
  140621. yymsp = yypParser->yytos;
  140622. }
  140623. #endif
  140624. }
  140625. switch( yyruleno ){
  140626. /* Beginning here are the reduction cases. A typical example
  140627. ** follows:
  140628. ** case 0:
  140629. ** #line <lineno> <grammarfile>
  140630. ** { ... } // User supplied code
  140631. ** #line <lineno> <thisfile>
  140632. ** break;
  140633. */
  140634. /********** Begin reduce actions **********************************************/
  140635. YYMINORTYPE yylhsminor;
  140636. case 0: /* explain ::= EXPLAIN */
  140637. { pParse->explain = 1; }
  140638. break;
  140639. case 1: /* explain ::= EXPLAIN QUERY PLAN */
  140640. { pParse->explain = 2; }
  140641. break;
  140642. case 2: /* cmdx ::= cmd */
  140643. { sqlite3FinishCoding(pParse); }
  140644. break;
  140645. case 3: /* cmd ::= BEGIN transtype trans_opt */
  140646. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy70);}
  140647. break;
  140648. case 4: /* transtype ::= */
  140649. {yymsp[1].minor.yy70 = TK_DEFERRED;}
  140650. break;
  140651. case 5: /* transtype ::= DEFERRED */
  140652. case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
  140653. case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
  140654. {yymsp[0].minor.yy70 = yymsp[0].major; /*A-overwrites-X*/}
  140655. break;
  140656. case 8: /* cmd ::= COMMIT|END trans_opt */
  140657. case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
  140658. {sqlite3EndTransaction(pParse,yymsp[-1].major);}
  140659. break;
  140660. case 10: /* cmd ::= SAVEPOINT nm */
  140661. {
  140662. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  140663. }
  140664. break;
  140665. case 11: /* cmd ::= RELEASE savepoint_opt nm */
  140666. {
  140667. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  140668. }
  140669. break;
  140670. case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  140671. {
  140672. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  140673. }
  140674. break;
  140675. case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  140676. {
  140677. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy70,0,0,yymsp[-2].minor.yy70);
  140678. }
  140679. break;
  140680. case 14: /* createkw ::= CREATE */
  140681. {disableLookaside(pParse);}
  140682. break;
  140683. case 15: /* ifnotexists ::= */
  140684. case 18: /* temp ::= */ yytestcase(yyruleno==18);
  140685. case 21: /* table_options ::= */ yytestcase(yyruleno==21);
  140686. case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
  140687. case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
  140688. case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
  140689. case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
  140690. case 93: /* distinct ::= */ yytestcase(yyruleno==93);
  140691. case 226: /* collate ::= */ yytestcase(yyruleno==226);
  140692. {yymsp[1].minor.yy70 = 0;}
  140693. break;
  140694. case 16: /* ifnotexists ::= IF NOT EXISTS */
  140695. {yymsp[-2].minor.yy70 = 1;}
  140696. break;
  140697. case 17: /* temp ::= TEMP */
  140698. case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
  140699. {yymsp[0].minor.yy70 = 1;}
  140700. break;
  140701. case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  140702. {
  140703. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy70,0);
  140704. }
  140705. break;
  140706. case 20: /* create_table_args ::= AS select */
  140707. {
  140708. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy489);
  140709. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy489);
  140710. }
  140711. break;
  140712. case 22: /* table_options ::= WITHOUT nm */
  140713. {
  140714. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  140715. yymsp[-1].minor.yy70 = TF_WithoutRowid | TF_NoVisibleRowid;
  140716. }else{
  140717. yymsp[-1].minor.yy70 = 0;
  140718. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  140719. }
  140720. }
  140721. break;
  140722. case 23: /* columnname ::= nm typetoken */
  140723. {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  140724. break;
  140725. case 24: /* typetoken ::= */
  140726. case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
  140727. case 99: /* as ::= */ yytestcase(yyruleno==99);
  140728. {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
  140729. break;
  140730. case 25: /* typetoken ::= typename LP signed RP */
  140731. {
  140732. yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  140733. }
  140734. break;
  140735. case 26: /* typetoken ::= typename LP signed COMMA signed RP */
  140736. {
  140737. yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  140738. }
  140739. break;
  140740. case 27: /* typename ::= typename ID|STRING */
  140741. {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  140742. break;
  140743. case 28: /* scanpt ::= */
  140744. {
  140745. assert( yyLookahead!=YYNOCODE );
  140746. yymsp[1].minor.yy392 = yyLookaheadToken.z;
  140747. }
  140748. break;
  140749. case 29: /* ccons ::= CONSTRAINT nm */
  140750. case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
  140751. {pParse->constraintName = yymsp[0].minor.yy0;}
  140752. break;
  140753. case 30: /* ccons ::= DEFAULT scanpt term scanpt */
  140754. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy18,yymsp[-2].minor.yy392,yymsp[0].minor.yy392);}
  140755. break;
  140756. case 31: /* ccons ::= DEFAULT LP expr RP */
  140757. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy18,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
  140758. break;
  140759. case 32: /* ccons ::= DEFAULT PLUS term scanpt */
  140760. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy18,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy392);}
  140761. break;
  140762. case 33: /* ccons ::= DEFAULT MINUS term scanpt */
  140763. {
  140764. Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[-1].minor.yy18, 0);
  140765. sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy392);
  140766. }
  140767. break;
  140768. case 34: /* ccons ::= DEFAULT scanpt ID|INDEXED */
  140769. {
  140770. Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);
  140771. if( p ){
  140772. sqlite3ExprIdToTrueFalse(p);
  140773. testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
  140774. }
  140775. sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);
  140776. }
  140777. break;
  140778. case 35: /* ccons ::= NOT NULL onconf */
  140779. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy70);}
  140780. break;
  140781. case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  140782. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy70,yymsp[0].minor.yy70,yymsp[-2].minor.yy70);}
  140783. break;
  140784. case 37: /* ccons ::= UNIQUE onconf */
  140785. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy70,0,0,0,0,
  140786. SQLITE_IDXTYPE_UNIQUE);}
  140787. break;
  140788. case 38: /* ccons ::= CHECK LP expr RP */
  140789. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy18);}
  140790. break;
  140791. case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  140792. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy420,yymsp[0].minor.yy70);}
  140793. break;
  140794. case 40: /* ccons ::= defer_subclause */
  140795. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy70);}
  140796. break;
  140797. case 41: /* ccons ::= COLLATE ID|STRING */
  140798. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  140799. break;
  140800. case 44: /* refargs ::= */
  140801. { yymsp[1].minor.yy70 = OE_None*0x0101; /* EV: R-19803-45884 */}
  140802. break;
  140803. case 45: /* refargs ::= refargs refarg */
  140804. { yymsp[-1].minor.yy70 = (yymsp[-1].minor.yy70 & ~yymsp[0].minor.yy111.mask) | yymsp[0].minor.yy111.value; }
  140805. break;
  140806. case 46: /* refarg ::= MATCH nm */
  140807. { yymsp[-1].minor.yy111.value = 0; yymsp[-1].minor.yy111.mask = 0x000000; }
  140808. break;
  140809. case 47: /* refarg ::= ON INSERT refact */
  140810. { yymsp[-2].minor.yy111.value = 0; yymsp[-2].minor.yy111.mask = 0x000000; }
  140811. break;
  140812. case 48: /* refarg ::= ON DELETE refact */
  140813. { yymsp[-2].minor.yy111.value = yymsp[0].minor.yy70; yymsp[-2].minor.yy111.mask = 0x0000ff; }
  140814. break;
  140815. case 49: /* refarg ::= ON UPDATE refact */
  140816. { yymsp[-2].minor.yy111.value = yymsp[0].minor.yy70<<8; yymsp[-2].minor.yy111.mask = 0x00ff00; }
  140817. break;
  140818. case 50: /* refact ::= SET NULL */
  140819. { yymsp[-1].minor.yy70 = OE_SetNull; /* EV: R-33326-45252 */}
  140820. break;
  140821. case 51: /* refact ::= SET DEFAULT */
  140822. { yymsp[-1].minor.yy70 = OE_SetDflt; /* EV: R-33326-45252 */}
  140823. break;
  140824. case 52: /* refact ::= CASCADE */
  140825. { yymsp[0].minor.yy70 = OE_Cascade; /* EV: R-33326-45252 */}
  140826. break;
  140827. case 53: /* refact ::= RESTRICT */
  140828. { yymsp[0].minor.yy70 = OE_Restrict; /* EV: R-33326-45252 */}
  140829. break;
  140830. case 54: /* refact ::= NO ACTION */
  140831. { yymsp[-1].minor.yy70 = OE_None; /* EV: R-33326-45252 */}
  140832. break;
  140833. case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  140834. {yymsp[-2].minor.yy70 = 0;}
  140835. break;
  140836. case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  140837. case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
  140838. case 156: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==156);
  140839. {yymsp[-1].minor.yy70 = yymsp[0].minor.yy70;}
  140840. break;
  140841. case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  140842. case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
  140843. case 198: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==198);
  140844. case 201: /* in_op ::= NOT IN */ yytestcase(yyruleno==201);
  140845. case 227: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==227);
  140846. {yymsp[-1].minor.yy70 = 1;}
  140847. break;
  140848. case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  140849. {yymsp[-1].minor.yy70 = 0;}
  140850. break;
  140851. case 61: /* tconscomma ::= COMMA */
  140852. {pParse->constraintName.n = 0;}
  140853. break;
  140854. case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  140855. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy420,yymsp[0].minor.yy70,yymsp[-2].minor.yy70,0);}
  140856. break;
  140857. case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
  140858. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy420,yymsp[0].minor.yy70,0,0,0,0,
  140859. SQLITE_IDXTYPE_UNIQUE);}
  140860. break;
  140861. case 65: /* tcons ::= CHECK LP expr RP onconf */
  140862. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy18);}
  140863. break;
  140864. case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  140865. {
  140866. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy420, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy420, yymsp[-1].minor.yy70);
  140867. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy70);
  140868. }
  140869. break;
  140870. case 68: /* onconf ::= */
  140871. case 70: /* orconf ::= */ yytestcase(yyruleno==70);
  140872. {yymsp[1].minor.yy70 = OE_Default;}
  140873. break;
  140874. case 69: /* onconf ::= ON CONFLICT resolvetype */
  140875. {yymsp[-2].minor.yy70 = yymsp[0].minor.yy70;}
  140876. break;
  140877. case 72: /* resolvetype ::= IGNORE */
  140878. {yymsp[0].minor.yy70 = OE_Ignore;}
  140879. break;
  140880. case 73: /* resolvetype ::= REPLACE */
  140881. case 157: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==157);
  140882. {yymsp[0].minor.yy70 = OE_Replace;}
  140883. break;
  140884. case 74: /* cmd ::= DROP TABLE ifexists fullname */
  140885. {
  140886. sqlite3DropTable(pParse, yymsp[0].minor.yy135, 0, yymsp[-1].minor.yy70);
  140887. }
  140888. break;
  140889. case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  140890. {
  140891. sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy420, yymsp[0].minor.yy489, yymsp[-7].minor.yy70, yymsp[-5].minor.yy70);
  140892. }
  140893. break;
  140894. case 78: /* cmd ::= DROP VIEW ifexists fullname */
  140895. {
  140896. sqlite3DropTable(pParse, yymsp[0].minor.yy135, 1, yymsp[-1].minor.yy70);
  140897. }
  140898. break;
  140899. case 79: /* cmd ::= select */
  140900. {
  140901. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  140902. sqlite3Select(pParse, yymsp[0].minor.yy489, &dest);
  140903. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy489);
  140904. }
  140905. break;
  140906. case 80: /* select ::= WITH wqlist selectnowith */
  140907. {
  140908. Select *p = yymsp[0].minor.yy489;
  140909. if( p ){
  140910. p->pWith = yymsp[-1].minor.yy449;
  140911. parserDoubleLinkSelect(pParse, p);
  140912. }else{
  140913. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy449);
  140914. }
  140915. yymsp[-2].minor.yy489 = p;
  140916. }
  140917. break;
  140918. case 81: /* select ::= WITH RECURSIVE wqlist selectnowith */
  140919. {
  140920. Select *p = yymsp[0].minor.yy489;
  140921. if( p ){
  140922. p->pWith = yymsp[-1].minor.yy449;
  140923. parserDoubleLinkSelect(pParse, p);
  140924. }else{
  140925. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy449);
  140926. }
  140927. yymsp[-3].minor.yy489 = p;
  140928. }
  140929. break;
  140930. case 82: /* select ::= selectnowith */
  140931. {
  140932. Select *p = yymsp[0].minor.yy489;
  140933. if( p ){
  140934. parserDoubleLinkSelect(pParse, p);
  140935. }
  140936. yymsp[0].minor.yy489 = p; /*A-overwrites-X*/
  140937. }
  140938. break;
  140939. case 83: /* selectnowith ::= selectnowith multiselect_op oneselect */
  140940. {
  140941. Select *pRhs = yymsp[0].minor.yy489;
  140942. Select *pLhs = yymsp[-2].minor.yy489;
  140943. if( pRhs && pRhs->pPrior ){
  140944. SrcList *pFrom;
  140945. Token x;
  140946. x.n = 0;
  140947. parserDoubleLinkSelect(pParse, pRhs);
  140948. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  140949. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
  140950. }
  140951. if( pRhs ){
  140952. pRhs->op = (u8)yymsp[-1].minor.yy70;
  140953. pRhs->pPrior = pLhs;
  140954. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  140955. pRhs->selFlags &= ~SF_MultiValue;
  140956. if( yymsp[-1].minor.yy70!=TK_ALL ) pParse->hasCompound = 1;
  140957. }else{
  140958. sqlite3SelectDelete(pParse->db, pLhs);
  140959. }
  140960. yymsp[-2].minor.yy489 = pRhs;
  140961. }
  140962. break;
  140963. case 84: /* multiselect_op ::= UNION */
  140964. case 86: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==86);
  140965. {yymsp[0].minor.yy70 = yymsp[0].major; /*A-overwrites-OP*/}
  140966. break;
  140967. case 85: /* multiselect_op ::= UNION ALL */
  140968. {yymsp[-1].minor.yy70 = TK_ALL;}
  140969. break;
  140970. case 87: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  140971. {
  140972. yymsp[-8].minor.yy489 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy420,yymsp[-5].minor.yy135,yymsp[-4].minor.yy18,yymsp[-3].minor.yy420,yymsp[-2].minor.yy18,yymsp[-1].minor.yy420,yymsp[-7].minor.yy70,yymsp[0].minor.yy18);
  140973. }
  140974. break;
  140975. case 88: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
  140976. {
  140977. yymsp[-9].minor.yy489 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy420,yymsp[-6].minor.yy135,yymsp[-5].minor.yy18,yymsp[-4].minor.yy420,yymsp[-3].minor.yy18,yymsp[-1].minor.yy420,yymsp[-8].minor.yy70,yymsp[0].minor.yy18);
  140978. if( yymsp[-9].minor.yy489 ){
  140979. yymsp[-9].minor.yy489->pWinDefn = yymsp[-2].minor.yy327;
  140980. }else{
  140981. sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy327);
  140982. }
  140983. }
  140984. break;
  140985. case 89: /* values ::= VALUES LP nexprlist RP */
  140986. {
  140987. yymsp[-3].minor.yy489 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy420,0,0,0,0,0,SF_Values,0);
  140988. }
  140989. break;
  140990. case 90: /* values ::= values COMMA LP nexprlist RP */
  140991. {
  140992. Select *pRight, *pLeft = yymsp[-4].minor.yy489;
  140993. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy420,0,0,0,0,0,SF_Values|SF_MultiValue,0);
  140994. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  140995. if( pRight ){
  140996. pRight->op = TK_ALL;
  140997. pRight->pPrior = pLeft;
  140998. yymsp[-4].minor.yy489 = pRight;
  140999. }else{
  141000. yymsp[-4].minor.yy489 = pLeft;
  141001. }
  141002. }
  141003. break;
  141004. case 91: /* distinct ::= DISTINCT */
  141005. {yymsp[0].minor.yy70 = SF_Distinct;}
  141006. break;
  141007. case 92: /* distinct ::= ALL */
  141008. {yymsp[0].minor.yy70 = SF_All;}
  141009. break;
  141010. case 94: /* sclp ::= */
  141011. case 127: /* orderby_opt ::= */ yytestcase(yyruleno==127);
  141012. case 134: /* groupby_opt ::= */ yytestcase(yyruleno==134);
  141013. case 214: /* exprlist ::= */ yytestcase(yyruleno==214);
  141014. case 217: /* paren_exprlist ::= */ yytestcase(yyruleno==217);
  141015. case 222: /* eidlist_opt ::= */ yytestcase(yyruleno==222);
  141016. {yymsp[1].minor.yy420 = 0;}
  141017. break;
  141018. case 95: /* selcollist ::= sclp scanpt expr scanpt as */
  141019. {
  141020. yymsp[-4].minor.yy420 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy420, yymsp[-2].minor.yy18);
  141021. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy420, &yymsp[0].minor.yy0, 1);
  141022. sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy420,yymsp[-3].minor.yy392,yymsp[-1].minor.yy392);
  141023. }
  141024. break;
  141025. case 96: /* selcollist ::= sclp scanpt STAR */
  141026. {
  141027. Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
  141028. yymsp[-2].minor.yy420 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy420, p);
  141029. }
  141030. break;
  141031. case 97: /* selcollist ::= sclp scanpt nm DOT STAR */
  141032. {
  141033. Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
  141034. Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  141035. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  141036. yymsp[-4].minor.yy420 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy420, pDot);
  141037. }
  141038. break;
  141039. case 98: /* as ::= AS nm */
  141040. case 109: /* dbnm ::= DOT nm */ yytestcase(yyruleno==109);
  141041. case 236: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==236);
  141042. case 237: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==237);
  141043. {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
  141044. break;
  141045. case 100: /* from ::= */
  141046. {yymsp[1].minor.yy135 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy135));}
  141047. break;
  141048. case 101: /* from ::= FROM seltablist */
  141049. {
  141050. yymsp[-1].minor.yy135 = yymsp[0].minor.yy135;
  141051. sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy135);
  141052. }
  141053. break;
  141054. case 102: /* stl_prefix ::= seltablist joinop */
  141055. {
  141056. if( ALWAYS(yymsp[-1].minor.yy135 && yymsp[-1].minor.yy135->nSrc>0) ) yymsp[-1].minor.yy135->a[yymsp[-1].minor.yy135->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy70;
  141057. }
  141058. break;
  141059. case 103: /* stl_prefix ::= */
  141060. {yymsp[1].minor.yy135 = 0;}
  141061. break;
  141062. case 104: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  141063. {
  141064. yymsp[-6].minor.yy135 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy135,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy18,yymsp[0].minor.yy48);
  141065. sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy135, &yymsp[-2].minor.yy0);
  141066. }
  141067. break;
  141068. case 105: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  141069. {
  141070. yymsp[-8].minor.yy135 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy135,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy18,yymsp[0].minor.yy48);
  141071. sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy135, yymsp[-4].minor.yy420);
  141072. }
  141073. break;
  141074. case 106: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  141075. {
  141076. yymsp[-6].minor.yy135 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy135,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy489,yymsp[-1].minor.yy18,yymsp[0].minor.yy48);
  141077. }
  141078. break;
  141079. case 107: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  141080. {
  141081. if( yymsp[-6].minor.yy135==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy18==0 && yymsp[0].minor.yy48==0 ){
  141082. yymsp[-6].minor.yy135 = yymsp[-4].minor.yy135;
  141083. }else if( yymsp[-4].minor.yy135->nSrc==1 ){
  141084. yymsp[-6].minor.yy135 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy135,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy18,yymsp[0].minor.yy48);
  141085. if( yymsp[-6].minor.yy135 ){
  141086. struct SrcList_item *pNew = &yymsp[-6].minor.yy135->a[yymsp[-6].minor.yy135->nSrc-1];
  141087. struct SrcList_item *pOld = yymsp[-4].minor.yy135->a;
  141088. pNew->zName = pOld->zName;
  141089. pNew->zDatabase = pOld->zDatabase;
  141090. pNew->pSelect = pOld->pSelect;
  141091. pOld->zName = pOld->zDatabase = 0;
  141092. pOld->pSelect = 0;
  141093. }
  141094. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy135);
  141095. }else{
  141096. Select *pSubquery;
  141097. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy135);
  141098. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy135,0,0,0,0,SF_NestedFrom,0);
  141099. yymsp[-6].minor.yy135 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy135,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy18,yymsp[0].minor.yy48);
  141100. }
  141101. }
  141102. break;
  141103. case 108: /* dbnm ::= */
  141104. case 122: /* indexed_opt ::= */ yytestcase(yyruleno==122);
  141105. {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
  141106. break;
  141107. case 110: /* fullname ::= nm */
  141108. {
  141109. yylhsminor.yy135 = sqlite3SrcListAppend(pParse->db,0,&yymsp[0].minor.yy0,0);
  141110. if( IN_RENAME_OBJECT && yylhsminor.yy135 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy135->a[0].zName, &yymsp[0].minor.yy0);
  141111. }
  141112. yymsp[0].minor.yy135 = yylhsminor.yy135;
  141113. break;
  141114. case 111: /* fullname ::= nm DOT nm */
  141115. {
  141116. yylhsminor.yy135 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  141117. if( IN_RENAME_OBJECT && yylhsminor.yy135 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy135->a[0].zName, &yymsp[0].minor.yy0);
  141118. }
  141119. yymsp[-2].minor.yy135 = yylhsminor.yy135;
  141120. break;
  141121. case 112: /* xfullname ::= nm */
  141122. {yymsp[0].minor.yy135 = sqlite3SrcListAppend(pParse->db,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
  141123. break;
  141124. case 113: /* xfullname ::= nm DOT nm */
  141125. {yymsp[-2].minor.yy135 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
  141126. break;
  141127. case 114: /* xfullname ::= nm DOT nm AS nm */
  141128. {
  141129. yymsp[-4].minor.yy135 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
  141130. if( yymsp[-4].minor.yy135 ) yymsp[-4].minor.yy135->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
  141131. }
  141132. break;
  141133. case 115: /* xfullname ::= nm AS nm */
  141134. {
  141135. yymsp[-2].minor.yy135 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
  141136. if( yymsp[-2].minor.yy135 ) yymsp[-2].minor.yy135->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
  141137. }
  141138. break;
  141139. case 116: /* joinop ::= COMMA|JOIN */
  141140. { yymsp[0].minor.yy70 = JT_INNER; }
  141141. break;
  141142. case 117: /* joinop ::= JOIN_KW JOIN */
  141143. {yymsp[-1].minor.yy70 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
  141144. break;
  141145. case 118: /* joinop ::= JOIN_KW nm JOIN */
  141146. {yymsp[-2].minor.yy70 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
  141147. break;
  141148. case 119: /* joinop ::= JOIN_KW nm nm JOIN */
  141149. {yymsp[-3].minor.yy70 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
  141150. break;
  141151. case 120: /* on_opt ::= ON expr */
  141152. case 137: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==137);
  141153. case 144: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==144);
  141154. case 210: /* case_else ::= ELSE expr */ yytestcase(yyruleno==210);
  141155. {yymsp[-1].minor.yy18 = yymsp[0].minor.yy18;}
  141156. break;
  141157. case 121: /* on_opt ::= */
  141158. case 136: /* having_opt ::= */ yytestcase(yyruleno==136);
  141159. case 138: /* limit_opt ::= */ yytestcase(yyruleno==138);
  141160. case 143: /* where_opt ::= */ yytestcase(yyruleno==143);
  141161. case 211: /* case_else ::= */ yytestcase(yyruleno==211);
  141162. case 213: /* case_operand ::= */ yytestcase(yyruleno==213);
  141163. {yymsp[1].minor.yy18 = 0;}
  141164. break;
  141165. case 123: /* indexed_opt ::= INDEXED BY nm */
  141166. {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
  141167. break;
  141168. case 124: /* indexed_opt ::= NOT INDEXED */
  141169. {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
  141170. break;
  141171. case 125: /* using_opt ::= USING LP idlist RP */
  141172. {yymsp[-3].minor.yy48 = yymsp[-1].minor.yy48;}
  141173. break;
  141174. case 126: /* using_opt ::= */
  141175. case 158: /* idlist_opt ::= */ yytestcase(yyruleno==158);
  141176. {yymsp[1].minor.yy48 = 0;}
  141177. break;
  141178. case 128: /* orderby_opt ::= ORDER BY sortlist */
  141179. case 135: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==135);
  141180. {yymsp[-2].minor.yy420 = yymsp[0].minor.yy420;}
  141181. break;
  141182. case 129: /* sortlist ::= sortlist COMMA expr sortorder */
  141183. {
  141184. yymsp[-3].minor.yy420 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy420,yymsp[-1].minor.yy18);
  141185. sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy420,yymsp[0].minor.yy70);
  141186. }
  141187. break;
  141188. case 130: /* sortlist ::= expr sortorder */
  141189. {
  141190. yymsp[-1].minor.yy420 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy18); /*A-overwrites-Y*/
  141191. sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy420,yymsp[0].minor.yy70);
  141192. }
  141193. break;
  141194. case 131: /* sortorder ::= ASC */
  141195. {yymsp[0].minor.yy70 = SQLITE_SO_ASC;}
  141196. break;
  141197. case 132: /* sortorder ::= DESC */
  141198. {yymsp[0].minor.yy70 = SQLITE_SO_DESC;}
  141199. break;
  141200. case 133: /* sortorder ::= */
  141201. {yymsp[1].minor.yy70 = SQLITE_SO_UNDEFINED;}
  141202. break;
  141203. case 139: /* limit_opt ::= LIMIT expr */
  141204. {yymsp[-1].minor.yy18 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy18,0);}
  141205. break;
  141206. case 140: /* limit_opt ::= LIMIT expr OFFSET expr */
  141207. {yymsp[-3].minor.yy18 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy18,yymsp[0].minor.yy18);}
  141208. break;
  141209. case 141: /* limit_opt ::= LIMIT expr COMMA expr */
  141210. {yymsp[-3].minor.yy18 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy18,yymsp[-2].minor.yy18);}
  141211. break;
  141212. case 142: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  141213. {
  141214. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy135, &yymsp[-1].minor.yy0);
  141215. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy135,yymsp[0].minor.yy18,0,0);
  141216. }
  141217. break;
  141218. case 145: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  141219. {
  141220. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy135, &yymsp[-3].minor.yy0);
  141221. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy420,"set list");
  141222. sqlite3Update(pParse,yymsp[-4].minor.yy135,yymsp[-1].minor.yy420,yymsp[0].minor.yy18,yymsp[-5].minor.yy70,0,0,0);
  141223. }
  141224. break;
  141225. case 146: /* setlist ::= setlist COMMA nm EQ expr */
  141226. {
  141227. yymsp[-4].minor.yy420 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy420, yymsp[0].minor.yy18);
  141228. sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy420, &yymsp[-2].minor.yy0, 1);
  141229. }
  141230. break;
  141231. case 147: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
  141232. {
  141233. yymsp[-6].minor.yy420 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy420, yymsp[-3].minor.yy48, yymsp[0].minor.yy18);
  141234. }
  141235. break;
  141236. case 148: /* setlist ::= nm EQ expr */
  141237. {
  141238. yylhsminor.yy420 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy18);
  141239. sqlite3ExprListSetName(pParse, yylhsminor.yy420, &yymsp[-2].minor.yy0, 1);
  141240. }
  141241. yymsp[-2].minor.yy420 = yylhsminor.yy420;
  141242. break;
  141243. case 149: /* setlist ::= LP idlist RP EQ expr */
  141244. {
  141245. yymsp[-4].minor.yy420 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy48, yymsp[0].minor.yy18);
  141246. }
  141247. break;
  141248. case 150: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  141249. {
  141250. sqlite3Insert(pParse, yymsp[-3].minor.yy135, yymsp[-1].minor.yy489, yymsp[-2].minor.yy48, yymsp[-5].minor.yy70, yymsp[0].minor.yy340);
  141251. }
  141252. break;
  141253. case 151: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  141254. {
  141255. sqlite3Insert(pParse, yymsp[-3].minor.yy135, 0, yymsp[-2].minor.yy48, yymsp[-5].minor.yy70, 0);
  141256. }
  141257. break;
  141258. case 152: /* upsert ::= */
  141259. { yymsp[1].minor.yy340 = 0; }
  141260. break;
  141261. case 153: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  141262. { yymsp[-10].minor.yy340 = sqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy420,yymsp[-5].minor.yy18,yymsp[-1].minor.yy420,yymsp[0].minor.yy18);}
  141263. break;
  141264. case 154: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  141265. { yymsp[-7].minor.yy340 = sqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy420,yymsp[-2].minor.yy18,0,0); }
  141266. break;
  141267. case 155: /* upsert ::= ON CONFLICT DO NOTHING */
  141268. { yymsp[-3].minor.yy340 = sqlite3UpsertNew(pParse->db,0,0,0,0); }
  141269. break;
  141270. case 159: /* idlist_opt ::= LP idlist RP */
  141271. {yymsp[-2].minor.yy48 = yymsp[-1].minor.yy48;}
  141272. break;
  141273. case 160: /* idlist ::= idlist COMMA nm */
  141274. {yymsp[-2].minor.yy48 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy48,&yymsp[0].minor.yy0);}
  141275. break;
  141276. case 161: /* idlist ::= nm */
  141277. {yymsp[0].minor.yy48 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
  141278. break;
  141279. case 162: /* expr ::= LP expr RP */
  141280. {yymsp[-2].minor.yy18 = yymsp[-1].minor.yy18;}
  141281. break;
  141282. case 163: /* expr ::= ID|INDEXED */
  141283. case 164: /* expr ::= JOIN_KW */ yytestcase(yyruleno==164);
  141284. {yymsp[0].minor.yy18=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  141285. break;
  141286. case 165: /* expr ::= nm DOT nm */
  141287. {
  141288. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  141289. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  141290. if( IN_RENAME_OBJECT ){
  141291. sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[0].minor.yy0);
  141292. sqlite3RenameTokenMap(pParse, (void*)temp1, &yymsp[-2].minor.yy0);
  141293. }
  141294. yylhsminor.yy18 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
  141295. }
  141296. yymsp[-2].minor.yy18 = yylhsminor.yy18;
  141297. break;
  141298. case 166: /* expr ::= nm DOT nm DOT nm */
  141299. {
  141300. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
  141301. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  141302. Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  141303. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
  141304. if( IN_RENAME_OBJECT ){
  141305. sqlite3RenameTokenMap(pParse, (void*)temp3, &yymsp[0].minor.yy0);
  141306. sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[-2].minor.yy0);
  141307. }
  141308. yylhsminor.yy18 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
  141309. }
  141310. yymsp[-4].minor.yy18 = yylhsminor.yy18;
  141311. break;
  141312. case 167: /* term ::= NULL|FLOAT|BLOB */
  141313. case 168: /* term ::= STRING */ yytestcase(yyruleno==168);
  141314. {yymsp[0].minor.yy18=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  141315. break;
  141316. case 169: /* term ::= INTEGER */
  141317. {
  141318. yylhsminor.yy18 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
  141319. }
  141320. yymsp[0].minor.yy18 = yylhsminor.yy18;
  141321. break;
  141322. case 170: /* expr ::= VARIABLE */
  141323. {
  141324. if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
  141325. u32 n = yymsp[0].minor.yy0.n;
  141326. yymsp[0].minor.yy18 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
  141327. sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy18, n);
  141328. }else{
  141329. /* When doing a nested parse, one can include terms in an expression
  141330. ** that look like this: #1 #2 ... These terms refer to registers
  141331. ** in the virtual machine. #N is the N-th register. */
  141332. Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
  141333. assert( t.n>=2 );
  141334. if( pParse->nested==0 ){
  141335. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
  141336. yymsp[0].minor.yy18 = 0;
  141337. }else{
  141338. yymsp[0].minor.yy18 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
  141339. if( yymsp[0].minor.yy18 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy18->iTable);
  141340. }
  141341. }
  141342. }
  141343. break;
  141344. case 171: /* expr ::= expr COLLATE ID|STRING */
  141345. {
  141346. yymsp[-2].minor.yy18 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy18, &yymsp[0].minor.yy0, 1);
  141347. }
  141348. break;
  141349. case 172: /* expr ::= CAST LP expr AS typetoken RP */
  141350. {
  141351. yymsp[-5].minor.yy18 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
  141352. sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy18, yymsp[-3].minor.yy18, 0);
  141353. }
  141354. break;
  141355. case 173: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  141356. {
  141357. yylhsminor.yy18 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy420, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy70);
  141358. }
  141359. yymsp[-4].minor.yy18 = yylhsminor.yy18;
  141360. break;
  141361. case 174: /* expr ::= ID|INDEXED LP STAR RP */
  141362. {
  141363. yylhsminor.yy18 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
  141364. }
  141365. yymsp[-3].minor.yy18 = yylhsminor.yy18;
  141366. break;
  141367. case 175: /* expr ::= ID|INDEXED LP distinct exprlist RP over_clause */
  141368. {
  141369. yylhsminor.yy18 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy420, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy70);
  141370. sqlite3WindowAttach(pParse, yylhsminor.yy18, yymsp[0].minor.yy327);
  141371. }
  141372. yymsp[-5].minor.yy18 = yylhsminor.yy18;
  141373. break;
  141374. case 176: /* expr ::= ID|INDEXED LP STAR RP over_clause */
  141375. {
  141376. yylhsminor.yy18 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
  141377. sqlite3WindowAttach(pParse, yylhsminor.yy18, yymsp[0].minor.yy327);
  141378. }
  141379. yymsp[-4].minor.yy18 = yylhsminor.yy18;
  141380. break;
  141381. case 177: /* term ::= CTIME_KW */
  141382. {
  141383. yylhsminor.yy18 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
  141384. }
  141385. yymsp[0].minor.yy18 = yylhsminor.yy18;
  141386. break;
  141387. case 178: /* expr ::= LP nexprlist COMMA expr RP */
  141388. {
  141389. ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy420, yymsp[-1].minor.yy18);
  141390. yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  141391. if( yymsp[-4].minor.yy18 ){
  141392. yymsp[-4].minor.yy18->x.pList = pList;
  141393. }else{
  141394. sqlite3ExprListDelete(pParse->db, pList);
  141395. }
  141396. }
  141397. break;
  141398. case 179: /* expr ::= expr AND expr */
  141399. case 180: /* expr ::= expr OR expr */ yytestcase(yyruleno==180);
  141400. case 181: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==181);
  141401. case 182: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==182);
  141402. case 183: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==183);
  141403. case 184: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==184);
  141404. case 185: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==185);
  141405. case 186: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==186);
  141406. {yymsp[-2].minor.yy18=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy18,yymsp[0].minor.yy18);}
  141407. break;
  141408. case 187: /* likeop ::= NOT LIKE_KW|MATCH */
  141409. {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
  141410. break;
  141411. case 188: /* expr ::= expr likeop expr */
  141412. {
  141413. ExprList *pList;
  141414. int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
  141415. yymsp[-1].minor.yy0.n &= 0x7fffffff;
  141416. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy18);
  141417. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy18);
  141418. yymsp[-2].minor.yy18 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
  141419. if( bNot ) yymsp[-2].minor.yy18 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy18, 0);
  141420. if( yymsp[-2].minor.yy18 ) yymsp[-2].minor.yy18->flags |= EP_InfixFunc;
  141421. }
  141422. break;
  141423. case 189: /* expr ::= expr likeop expr ESCAPE expr */
  141424. {
  141425. ExprList *pList;
  141426. int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
  141427. yymsp[-3].minor.yy0.n &= 0x7fffffff;
  141428. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy18);
  141429. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy18);
  141430. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy18);
  141431. yymsp[-4].minor.yy18 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
  141432. if( bNot ) yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy18, 0);
  141433. if( yymsp[-4].minor.yy18 ) yymsp[-4].minor.yy18->flags |= EP_InfixFunc;
  141434. }
  141435. break;
  141436. case 190: /* expr ::= expr ISNULL|NOTNULL */
  141437. {yymsp[-1].minor.yy18 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy18,0);}
  141438. break;
  141439. case 191: /* expr ::= expr NOT NULL */
  141440. {yymsp[-2].minor.yy18 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy18,0);}
  141441. break;
  141442. case 192: /* expr ::= expr IS expr */
  141443. {
  141444. yymsp[-2].minor.yy18 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy18,yymsp[0].minor.yy18);
  141445. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy18, yymsp[-2].minor.yy18, TK_ISNULL);
  141446. }
  141447. break;
  141448. case 193: /* expr ::= expr IS NOT expr */
  141449. {
  141450. yymsp[-3].minor.yy18 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy18,yymsp[0].minor.yy18);
  141451. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy18, yymsp[-3].minor.yy18, TK_NOTNULL);
  141452. }
  141453. break;
  141454. case 194: /* expr ::= NOT expr */
  141455. case 195: /* expr ::= BITNOT expr */ yytestcase(yyruleno==195);
  141456. {yymsp[-1].minor.yy18 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy18, 0);/*A-overwrites-B*/}
  141457. break;
  141458. case 196: /* expr ::= PLUS|MINUS expr */
  141459. {
  141460. yymsp[-1].minor.yy18 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy18, 0);
  141461. /*A-overwrites-B*/
  141462. }
  141463. break;
  141464. case 197: /* between_op ::= BETWEEN */
  141465. case 200: /* in_op ::= IN */ yytestcase(yyruleno==200);
  141466. {yymsp[0].minor.yy70 = 0;}
  141467. break;
  141468. case 199: /* expr ::= expr between_op expr AND expr */
  141469. {
  141470. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy18);
  141471. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy18);
  141472. yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy18, 0);
  141473. if( yymsp[-4].minor.yy18 ){
  141474. yymsp[-4].minor.yy18->x.pList = pList;
  141475. }else{
  141476. sqlite3ExprListDelete(pParse->db, pList);
  141477. }
  141478. if( yymsp[-3].minor.yy70 ) yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy18, 0);
  141479. }
  141480. break;
  141481. case 202: /* expr ::= expr in_op LP exprlist RP */
  141482. {
  141483. if( yymsp[-1].minor.yy420==0 ){
  141484. /* Expressions of the form
  141485. **
  141486. ** expr1 IN ()
  141487. ** expr1 NOT IN ()
  141488. **
  141489. ** simplify to constants 0 (false) and 1 (true), respectively,
  141490. ** regardless of the value of expr1.
  141491. */
  141492. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy18);
  141493. yymsp[-4].minor.yy18 = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy70],1);
  141494. }else if( yymsp[-1].minor.yy420->nExpr==1 ){
  141495. /* Expressions of the form:
  141496. **
  141497. ** expr1 IN (?1)
  141498. ** expr1 NOT IN (?2)
  141499. **
  141500. ** with exactly one value on the RHS can be simplified to something
  141501. ** like this:
  141502. **
  141503. ** expr1 == ?1
  141504. ** expr1 <> ?2
  141505. **
  141506. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  141507. ** so that it may not contribute to the computation of comparison
  141508. ** affinity or the collating sequence to use for comparison. Otherwise,
  141509. ** the semantics would be subtly different from IN or NOT IN.
  141510. */
  141511. Expr *pRHS = yymsp[-1].minor.yy420->a[0].pExpr;
  141512. yymsp[-1].minor.yy420->a[0].pExpr = 0;
  141513. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy420);
  141514. /* pRHS cannot be NULL because a malloc error would have been detected
  141515. ** before now and control would have never reached this point */
  141516. if( ALWAYS(pRHS) ){
  141517. pRHS->flags &= ~EP_Collate;
  141518. pRHS->flags |= EP_Generic;
  141519. }
  141520. yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, yymsp[-3].minor.yy70 ? TK_NE : TK_EQ, yymsp[-4].minor.yy18, pRHS);
  141521. }else{
  141522. yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy18, 0);
  141523. if( yymsp[-4].minor.yy18 ){
  141524. yymsp[-4].minor.yy18->x.pList = yymsp[-1].minor.yy420;
  141525. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy18);
  141526. }else{
  141527. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy420);
  141528. }
  141529. if( yymsp[-3].minor.yy70 ) yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy18, 0);
  141530. }
  141531. }
  141532. break;
  141533. case 203: /* expr ::= LP select RP */
  141534. {
  141535. yymsp[-2].minor.yy18 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  141536. sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy18, yymsp[-1].minor.yy489);
  141537. }
  141538. break;
  141539. case 204: /* expr ::= expr in_op LP select RP */
  141540. {
  141541. yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy18, 0);
  141542. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy18, yymsp[-1].minor.yy489);
  141543. if( yymsp[-3].minor.yy70 ) yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy18, 0);
  141544. }
  141545. break;
  141546. case 205: /* expr ::= expr in_op nm dbnm paren_exprlist */
  141547. {
  141548. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
  141549. Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
  141550. if( yymsp[0].minor.yy420 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy420);
  141551. yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy18, 0);
  141552. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy18, pSelect);
  141553. if( yymsp[-3].minor.yy70 ) yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy18, 0);
  141554. }
  141555. break;
  141556. case 206: /* expr ::= EXISTS LP select RP */
  141557. {
  141558. Expr *p;
  141559. p = yymsp[-3].minor.yy18 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
  141560. sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy489);
  141561. }
  141562. break;
  141563. case 207: /* expr ::= CASE case_operand case_exprlist case_else END */
  141564. {
  141565. yymsp[-4].minor.yy18 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy18, 0);
  141566. if( yymsp[-4].minor.yy18 ){
  141567. yymsp[-4].minor.yy18->x.pList = yymsp[-1].minor.yy18 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy420,yymsp[-1].minor.yy18) : yymsp[-2].minor.yy420;
  141568. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy18);
  141569. }else{
  141570. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy420);
  141571. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy18);
  141572. }
  141573. }
  141574. break;
  141575. case 208: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  141576. {
  141577. yymsp[-4].minor.yy420 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy420, yymsp[-2].minor.yy18);
  141578. yymsp[-4].minor.yy420 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy420, yymsp[0].minor.yy18);
  141579. }
  141580. break;
  141581. case 209: /* case_exprlist ::= WHEN expr THEN expr */
  141582. {
  141583. yymsp[-3].minor.yy420 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy18);
  141584. yymsp[-3].minor.yy420 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy420, yymsp[0].minor.yy18);
  141585. }
  141586. break;
  141587. case 212: /* case_operand ::= expr */
  141588. {yymsp[0].minor.yy18 = yymsp[0].minor.yy18; /*A-overwrites-X*/}
  141589. break;
  141590. case 215: /* nexprlist ::= nexprlist COMMA expr */
  141591. {yymsp[-2].minor.yy420 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy420,yymsp[0].minor.yy18);}
  141592. break;
  141593. case 216: /* nexprlist ::= expr */
  141594. {yymsp[0].minor.yy420 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy18); /*A-overwrites-Y*/}
  141595. break;
  141596. case 218: /* paren_exprlist ::= LP exprlist RP */
  141597. case 223: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==223);
  141598. {yymsp[-2].minor.yy420 = yymsp[-1].minor.yy420;}
  141599. break;
  141600. case 219: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  141601. {
  141602. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  141603. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy420, yymsp[-10].minor.yy70,
  141604. &yymsp[-11].minor.yy0, yymsp[0].minor.yy18, SQLITE_SO_ASC, yymsp[-8].minor.yy70, SQLITE_IDXTYPE_APPDEF);
  141605. if( IN_RENAME_OBJECT && pParse->pNewIndex ){
  141606. sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
  141607. }
  141608. }
  141609. break;
  141610. case 220: /* uniqueflag ::= UNIQUE */
  141611. case 260: /* raisetype ::= ABORT */ yytestcase(yyruleno==260);
  141612. {yymsp[0].minor.yy70 = OE_Abort;}
  141613. break;
  141614. case 221: /* uniqueflag ::= */
  141615. {yymsp[1].minor.yy70 = OE_None;}
  141616. break;
  141617. case 224: /* eidlist ::= eidlist COMMA nm collate sortorder */
  141618. {
  141619. yymsp[-4].minor.yy420 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy420, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy70, yymsp[0].minor.yy70);
  141620. }
  141621. break;
  141622. case 225: /* eidlist ::= nm collate sortorder */
  141623. {
  141624. yymsp[-2].minor.yy420 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy70, yymsp[0].minor.yy70); /*A-overwrites-Y*/
  141625. }
  141626. break;
  141627. case 228: /* cmd ::= DROP INDEX ifexists fullname */
  141628. {sqlite3DropIndex(pParse, yymsp[0].minor.yy135, yymsp[-1].minor.yy70);}
  141629. break;
  141630. case 229: /* cmd ::= VACUUM */
  141631. {sqlite3Vacuum(pParse,0);}
  141632. break;
  141633. case 230: /* cmd ::= VACUUM nm */
  141634. {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
  141635. break;
  141636. case 231: /* cmd ::= PRAGMA nm dbnm */
  141637. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  141638. break;
  141639. case 232: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  141640. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  141641. break;
  141642. case 233: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  141643. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  141644. break;
  141645. case 234: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  141646. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  141647. break;
  141648. case 235: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  141649. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  141650. break;
  141651. case 238: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  141652. {
  141653. Token all;
  141654. all.z = yymsp[-3].minor.yy0.z;
  141655. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  141656. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy207, &all);
  141657. }
  141658. break;
  141659. case 239: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  141660. {
  141661. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy70, yymsp[-4].minor.yy34.a, yymsp[-4].minor.yy34.b, yymsp[-2].minor.yy135, yymsp[0].minor.yy18, yymsp[-10].minor.yy70, yymsp[-8].minor.yy70);
  141662. yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
  141663. }
  141664. break;
  141665. case 240: /* trigger_time ::= BEFORE|AFTER */
  141666. { yymsp[0].minor.yy70 = yymsp[0].major; /*A-overwrites-X*/ }
  141667. break;
  141668. case 241: /* trigger_time ::= INSTEAD OF */
  141669. { yymsp[-1].minor.yy70 = TK_INSTEAD;}
  141670. break;
  141671. case 242: /* trigger_time ::= */
  141672. { yymsp[1].minor.yy70 = TK_BEFORE; }
  141673. break;
  141674. case 243: /* trigger_event ::= DELETE|INSERT */
  141675. case 244: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==244);
  141676. {yymsp[0].minor.yy34.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy34.b = 0;}
  141677. break;
  141678. case 245: /* trigger_event ::= UPDATE OF idlist */
  141679. {yymsp[-2].minor.yy34.a = TK_UPDATE; yymsp[-2].minor.yy34.b = yymsp[0].minor.yy48;}
  141680. break;
  141681. case 246: /* when_clause ::= */
  141682. case 265: /* key_opt ::= */ yytestcase(yyruleno==265);
  141683. case 307: /* filter_opt ::= */ yytestcase(yyruleno==307);
  141684. { yymsp[1].minor.yy18 = 0; }
  141685. break;
  141686. case 247: /* when_clause ::= WHEN expr */
  141687. case 266: /* key_opt ::= KEY expr */ yytestcase(yyruleno==266);
  141688. { yymsp[-1].minor.yy18 = yymsp[0].minor.yy18; }
  141689. break;
  141690. case 248: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  141691. {
  141692. assert( yymsp[-2].minor.yy207!=0 );
  141693. yymsp[-2].minor.yy207->pLast->pNext = yymsp[-1].minor.yy207;
  141694. yymsp[-2].minor.yy207->pLast = yymsp[-1].minor.yy207;
  141695. }
  141696. break;
  141697. case 249: /* trigger_cmd_list ::= trigger_cmd SEMI */
  141698. {
  141699. assert( yymsp[-1].minor.yy207!=0 );
  141700. yymsp[-1].minor.yy207->pLast = yymsp[-1].minor.yy207;
  141701. }
  141702. break;
  141703. case 250: /* trnm ::= nm DOT nm */
  141704. {
  141705. yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  141706. sqlite3ErrorMsg(pParse,
  141707. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  141708. "statements within triggers");
  141709. }
  141710. break;
  141711. case 251: /* tridxby ::= INDEXED BY nm */
  141712. {
  141713. sqlite3ErrorMsg(pParse,
  141714. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  141715. "within triggers");
  141716. }
  141717. break;
  141718. case 252: /* tridxby ::= NOT INDEXED */
  141719. {
  141720. sqlite3ErrorMsg(pParse,
  141721. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  141722. "within triggers");
  141723. }
  141724. break;
  141725. case 253: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  141726. {yylhsminor.yy207 = sqlite3TriggerUpdateStep(pParse, &yymsp[-5].minor.yy0, yymsp[-2].minor.yy420, yymsp[-1].minor.yy18, yymsp[-6].minor.yy70, yymsp[-7].minor.yy0.z, yymsp[0].minor.yy392);}
  141727. yymsp[-7].minor.yy207 = yylhsminor.yy207;
  141728. break;
  141729. case 254: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  141730. {
  141731. yylhsminor.yy207 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy48,yymsp[-2].minor.yy489,yymsp[-6].minor.yy70,yymsp[-1].minor.yy340,yymsp[-7].minor.yy392,yymsp[0].minor.yy392);/*yylhsminor.yy207-overwrites-yymsp[-6].minor.yy70*/
  141732. }
  141733. yymsp[-7].minor.yy207 = yylhsminor.yy207;
  141734. break;
  141735. case 255: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  141736. {yylhsminor.yy207 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy18, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy392);}
  141737. yymsp[-5].minor.yy207 = yylhsminor.yy207;
  141738. break;
  141739. case 256: /* trigger_cmd ::= scanpt select scanpt */
  141740. {yylhsminor.yy207 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy489, yymsp[-2].minor.yy392, yymsp[0].minor.yy392); /*yylhsminor.yy207-overwrites-yymsp[-1].minor.yy489*/}
  141741. yymsp[-2].minor.yy207 = yylhsminor.yy207;
  141742. break;
  141743. case 257: /* expr ::= RAISE LP IGNORE RP */
  141744. {
  141745. yymsp[-3].minor.yy18 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  141746. if( yymsp[-3].minor.yy18 ){
  141747. yymsp[-3].minor.yy18->affinity = OE_Ignore;
  141748. }
  141749. }
  141750. break;
  141751. case 258: /* expr ::= RAISE LP raisetype COMMA nm RP */
  141752. {
  141753. yymsp[-5].minor.yy18 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  141754. if( yymsp[-5].minor.yy18 ) {
  141755. yymsp[-5].minor.yy18->affinity = (char)yymsp[-3].minor.yy70;
  141756. }
  141757. }
  141758. break;
  141759. case 259: /* raisetype ::= ROLLBACK */
  141760. {yymsp[0].minor.yy70 = OE_Rollback;}
  141761. break;
  141762. case 261: /* raisetype ::= FAIL */
  141763. {yymsp[0].minor.yy70 = OE_Fail;}
  141764. break;
  141765. case 262: /* cmd ::= DROP TRIGGER ifexists fullname */
  141766. {
  141767. sqlite3DropTrigger(pParse,yymsp[0].minor.yy135,yymsp[-1].minor.yy70);
  141768. }
  141769. break;
  141770. case 263: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  141771. {
  141772. sqlite3Attach(pParse, yymsp[-3].minor.yy18, yymsp[-1].minor.yy18, yymsp[0].minor.yy18);
  141773. }
  141774. break;
  141775. case 264: /* cmd ::= DETACH database_kw_opt expr */
  141776. {
  141777. sqlite3Detach(pParse, yymsp[0].minor.yy18);
  141778. }
  141779. break;
  141780. case 267: /* cmd ::= REINDEX */
  141781. {sqlite3Reindex(pParse, 0, 0);}
  141782. break;
  141783. case 268: /* cmd ::= REINDEX nm dbnm */
  141784. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  141785. break;
  141786. case 269: /* cmd ::= ANALYZE */
  141787. {sqlite3Analyze(pParse, 0, 0);}
  141788. break;
  141789. case 270: /* cmd ::= ANALYZE nm dbnm */
  141790. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  141791. break;
  141792. case 271: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  141793. {
  141794. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy135,&yymsp[0].minor.yy0);
  141795. }
  141796. break;
  141797. case 272: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  141798. {
  141799. yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  141800. sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
  141801. }
  141802. break;
  141803. case 273: /* add_column_fullname ::= fullname */
  141804. {
  141805. disableLookaside(pParse);
  141806. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy135);
  141807. }
  141808. break;
  141809. case 274: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
  141810. {
  141811. sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy135, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
  141812. }
  141813. break;
  141814. case 275: /* cmd ::= create_vtab */
  141815. {sqlite3VtabFinishParse(pParse,0);}
  141816. break;
  141817. case 276: /* cmd ::= create_vtab LP vtabarglist RP */
  141818. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  141819. break;
  141820. case 277: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  141821. {
  141822. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy70);
  141823. }
  141824. break;
  141825. case 278: /* vtabarg ::= */
  141826. {sqlite3VtabArgInit(pParse);}
  141827. break;
  141828. case 279: /* vtabargtoken ::= ANY */
  141829. case 280: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==280);
  141830. case 281: /* lp ::= LP */ yytestcase(yyruleno==281);
  141831. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  141832. break;
  141833. case 282: /* with ::= WITH wqlist */
  141834. case 283: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==283);
  141835. { sqlite3WithPush(pParse, yymsp[0].minor.yy449, 1); }
  141836. break;
  141837. case 284: /* wqlist ::= nm eidlist_opt AS LP select RP */
  141838. {
  141839. yymsp[-5].minor.yy449 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy420, yymsp[-1].minor.yy489); /*A-overwrites-X*/
  141840. }
  141841. break;
  141842. case 285: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  141843. {
  141844. yymsp[-7].minor.yy449 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy449, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy420, yymsp[-1].minor.yy489);
  141845. }
  141846. break;
  141847. case 286: /* windowdefn_list ::= windowdefn */
  141848. { yylhsminor.yy327 = yymsp[0].minor.yy327; }
  141849. yymsp[0].minor.yy327 = yylhsminor.yy327;
  141850. break;
  141851. case 287: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
  141852. {
  141853. assert( yymsp[0].minor.yy327!=0 );
  141854. yymsp[0].minor.yy327->pNextWin = yymsp[-2].minor.yy327;
  141855. yylhsminor.yy327 = yymsp[0].minor.yy327;
  141856. }
  141857. yymsp[-2].minor.yy327 = yylhsminor.yy327;
  141858. break;
  141859. case 288: /* windowdefn ::= nm AS window */
  141860. {
  141861. if( ALWAYS(yymsp[0].minor.yy327) ){
  141862. yymsp[0].minor.yy327->zName = sqlite3DbStrNDup(pParse->db, yymsp[-2].minor.yy0.z, yymsp[-2].minor.yy0.n);
  141863. }
  141864. yylhsminor.yy327 = yymsp[0].minor.yy327;
  141865. }
  141866. yymsp[-2].minor.yy327 = yylhsminor.yy327;
  141867. break;
  141868. case 289: /* window ::= LP part_opt orderby_opt frame_opt RP */
  141869. {
  141870. yymsp[-4].minor.yy327 = yymsp[-1].minor.yy327;
  141871. if( ALWAYS(yymsp[-4].minor.yy327) ){
  141872. yymsp[-4].minor.yy327->pPartition = yymsp[-3].minor.yy420;
  141873. yymsp[-4].minor.yy327->pOrderBy = yymsp[-2].minor.yy420;
  141874. }
  141875. }
  141876. break;
  141877. case 290: /* part_opt ::= PARTITION BY nexprlist */
  141878. { yymsp[-2].minor.yy420 = yymsp[0].minor.yy420; }
  141879. break;
  141880. case 291: /* part_opt ::= */
  141881. { yymsp[1].minor.yy420 = 0; }
  141882. break;
  141883. case 292: /* frame_opt ::= */
  141884. {
  141885. yymsp[1].minor.yy327 = sqlite3WindowAlloc(pParse, TK_RANGE, TK_UNBOUNDED, 0, TK_CURRENT, 0);
  141886. }
  141887. break;
  141888. case 293: /* frame_opt ::= range_or_rows frame_bound_s */
  141889. {
  141890. yylhsminor.yy327 = sqlite3WindowAlloc(pParse, yymsp[-1].minor.yy70, yymsp[0].minor.yy119.eType, yymsp[0].minor.yy119.pExpr, TK_CURRENT, 0);
  141891. }
  141892. yymsp[-1].minor.yy327 = yylhsminor.yy327;
  141893. break;
  141894. case 294: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e */
  141895. {
  141896. yylhsminor.yy327 = sqlite3WindowAlloc(pParse, yymsp[-4].minor.yy70, yymsp[-2].minor.yy119.eType, yymsp[-2].minor.yy119.pExpr, yymsp[0].minor.yy119.eType, yymsp[0].minor.yy119.pExpr);
  141897. }
  141898. yymsp[-4].minor.yy327 = yylhsminor.yy327;
  141899. break;
  141900. case 295: /* range_or_rows ::= RANGE */
  141901. { yymsp[0].minor.yy70 = TK_RANGE; }
  141902. break;
  141903. case 296: /* range_or_rows ::= ROWS */
  141904. { yymsp[0].minor.yy70 = TK_ROWS; }
  141905. break;
  141906. case 297: /* frame_bound_s ::= frame_bound */
  141907. case 299: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==299);
  141908. { yylhsminor.yy119 = yymsp[0].minor.yy119; }
  141909. yymsp[0].minor.yy119 = yylhsminor.yy119;
  141910. break;
  141911. case 298: /* frame_bound_s ::= UNBOUNDED PRECEDING */
  141912. case 300: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==300);
  141913. {yymsp[-1].minor.yy119.eType = TK_UNBOUNDED; yymsp[-1].minor.yy119.pExpr = 0;}
  141914. break;
  141915. case 301: /* frame_bound ::= expr PRECEDING */
  141916. { yylhsminor.yy119.eType = TK_PRECEDING; yylhsminor.yy119.pExpr = yymsp[-1].minor.yy18; }
  141917. yymsp[-1].minor.yy119 = yylhsminor.yy119;
  141918. break;
  141919. case 302: /* frame_bound ::= CURRENT ROW */
  141920. { yymsp[-1].minor.yy119.eType = TK_CURRENT ; yymsp[-1].minor.yy119.pExpr = 0; }
  141921. break;
  141922. case 303: /* frame_bound ::= expr FOLLOWING */
  141923. { yylhsminor.yy119.eType = TK_FOLLOWING; yylhsminor.yy119.pExpr = yymsp[-1].minor.yy18; }
  141924. yymsp[-1].minor.yy119 = yylhsminor.yy119;
  141925. break;
  141926. case 304: /* window_clause ::= WINDOW windowdefn_list */
  141927. { yymsp[-1].minor.yy327 = yymsp[0].minor.yy327; }
  141928. break;
  141929. case 305: /* over_clause ::= filter_opt OVER window */
  141930. {
  141931. yylhsminor.yy327 = yymsp[0].minor.yy327;
  141932. assert( yylhsminor.yy327!=0 );
  141933. yylhsminor.yy327->pFilter = yymsp[-2].minor.yy18;
  141934. }
  141935. yymsp[-2].minor.yy327 = yylhsminor.yy327;
  141936. break;
  141937. case 306: /* over_clause ::= filter_opt OVER nm */
  141938. {
  141939. yylhsminor.yy327 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  141940. if( yylhsminor.yy327 ){
  141941. yylhsminor.yy327->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
  141942. yylhsminor.yy327->pFilter = yymsp[-2].minor.yy18;
  141943. }else{
  141944. sqlite3ExprDelete(pParse->db, yymsp[-2].minor.yy18);
  141945. }
  141946. }
  141947. yymsp[-2].minor.yy327 = yylhsminor.yy327;
  141948. break;
  141949. case 308: /* filter_opt ::= FILTER LP WHERE expr RP */
  141950. { yymsp[-4].minor.yy18 = yymsp[-1].minor.yy18; }
  141951. break;
  141952. default:
  141953. /* (309) input ::= cmdlist */ yytestcase(yyruleno==309);
  141954. /* (310) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==310);
  141955. /* (311) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=311);
  141956. /* (312) ecmd ::= SEMI */ yytestcase(yyruleno==312);
  141957. /* (313) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==313);
  141958. /* (314) ecmd ::= explain cmdx */ yytestcase(yyruleno==314);
  141959. /* (315) trans_opt ::= */ yytestcase(yyruleno==315);
  141960. /* (316) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==316);
  141961. /* (317) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==317);
  141962. /* (318) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==318);
  141963. /* (319) savepoint_opt ::= */ yytestcase(yyruleno==319);
  141964. /* (320) cmd ::= create_table create_table_args */ yytestcase(yyruleno==320);
  141965. /* (321) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==321);
  141966. /* (322) columnlist ::= columnname carglist */ yytestcase(yyruleno==322);
  141967. /* (323) nm ::= ID|INDEXED */ yytestcase(yyruleno==323);
  141968. /* (324) nm ::= STRING */ yytestcase(yyruleno==324);
  141969. /* (325) nm ::= JOIN_KW */ yytestcase(yyruleno==325);
  141970. /* (326) typetoken ::= typename */ yytestcase(yyruleno==326);
  141971. /* (327) typename ::= ID|STRING */ yytestcase(yyruleno==327);
  141972. /* (328) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=328);
  141973. /* (329) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=329);
  141974. /* (330) carglist ::= carglist ccons */ yytestcase(yyruleno==330);
  141975. /* (331) carglist ::= */ yytestcase(yyruleno==331);
  141976. /* (332) ccons ::= NULL onconf */ yytestcase(yyruleno==332);
  141977. /* (333) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==333);
  141978. /* (334) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==334);
  141979. /* (335) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=335);
  141980. /* (336) tconscomma ::= */ yytestcase(yyruleno==336);
  141981. /* (337) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=337);
  141982. /* (338) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=338);
  141983. /* (339) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=339);
  141984. /* (340) oneselect ::= values */ yytestcase(yyruleno==340);
  141985. /* (341) sclp ::= selcollist COMMA */ yytestcase(yyruleno==341);
  141986. /* (342) as ::= ID|STRING */ yytestcase(yyruleno==342);
  141987. /* (343) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=343);
  141988. /* (344) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==344);
  141989. /* (345) exprlist ::= nexprlist */ yytestcase(yyruleno==345);
  141990. /* (346) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=346);
  141991. /* (347) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=347);
  141992. /* (348) nmnum ::= ON */ yytestcase(yyruleno==348);
  141993. /* (349) nmnum ::= DELETE */ yytestcase(yyruleno==349);
  141994. /* (350) nmnum ::= DEFAULT */ yytestcase(yyruleno==350);
  141995. /* (351) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==351);
  141996. /* (352) foreach_clause ::= */ yytestcase(yyruleno==352);
  141997. /* (353) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==353);
  141998. /* (354) trnm ::= nm */ yytestcase(yyruleno==354);
  141999. /* (355) tridxby ::= */ yytestcase(yyruleno==355);
  142000. /* (356) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==356);
  142001. /* (357) database_kw_opt ::= */ yytestcase(yyruleno==357);
  142002. /* (358) kwcolumn_opt ::= */ yytestcase(yyruleno==358);
  142003. /* (359) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==359);
  142004. /* (360) vtabarglist ::= vtabarg */ yytestcase(yyruleno==360);
  142005. /* (361) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==361);
  142006. /* (362) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==362);
  142007. /* (363) anylist ::= */ yytestcase(yyruleno==363);
  142008. /* (364) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==364);
  142009. /* (365) anylist ::= anylist ANY */ yytestcase(yyruleno==365);
  142010. /* (366) with ::= */ yytestcase(yyruleno==366);
  142011. break;
  142012. /********** End reduce actions ************************************************/
  142013. };
  142014. assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  142015. yygoto = yyRuleInfo[yyruleno].lhs;
  142016. yysize = yyRuleInfo[yyruleno].nrhs;
  142017. yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
  142018. /* There are no SHIFTREDUCE actions on nonterminals because the table
  142019. ** generator has simplified them to pure REDUCE actions. */
  142020. assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
  142021. /* It is not possible for a REDUCE to be followed by an error */
  142022. assert( yyact!=YY_ERROR_ACTION );
  142023. yymsp += yysize+1;
  142024. yypParser->yytos = yymsp;
  142025. yymsp->stateno = (YYACTIONTYPE)yyact;
  142026. yymsp->major = (YYCODETYPE)yygoto;
  142027. yyTraceShift(yypParser, yyact, "... then shift");
  142028. return yyact;
  142029. }
  142030. /*
  142031. ** The following code executes when the parse fails
  142032. */
  142033. #ifndef YYNOERRORRECOVERY
  142034. static void yy_parse_failed(
  142035. yyParser *yypParser /* The parser */
  142036. ){
  142037. sqlite3ParserARG_FETCH
  142038. sqlite3ParserCTX_FETCH
  142039. #ifndef NDEBUG
  142040. if( yyTraceFILE ){
  142041. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  142042. }
  142043. #endif
  142044. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  142045. /* Here code is inserted which will be executed whenever the
  142046. ** parser fails */
  142047. /************ Begin %parse_failure code ***************************************/
  142048. /************ End %parse_failure code *****************************************/
  142049. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  142050. sqlite3ParserCTX_STORE
  142051. }
  142052. #endif /* YYNOERRORRECOVERY */
  142053. /*
  142054. ** The following code executes when a syntax error first occurs.
  142055. */
  142056. static void yy_syntax_error(
  142057. yyParser *yypParser, /* The parser */
  142058. int yymajor, /* The major type of the error token */
  142059. sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
  142060. ){
  142061. sqlite3ParserARG_FETCH
  142062. sqlite3ParserCTX_FETCH
  142063. #define TOKEN yyminor
  142064. /************ Begin %syntax_error code ****************************************/
  142065. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  142066. if( TOKEN.z[0] ){
  142067. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  142068. }else{
  142069. sqlite3ErrorMsg(pParse, "incomplete input");
  142070. }
  142071. /************ End %syntax_error code ******************************************/
  142072. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  142073. sqlite3ParserCTX_STORE
  142074. }
  142075. /*
  142076. ** The following is executed when the parser accepts
  142077. */
  142078. static void yy_accept(
  142079. yyParser *yypParser /* The parser */
  142080. ){
  142081. sqlite3ParserARG_FETCH
  142082. sqlite3ParserCTX_FETCH
  142083. #ifndef NDEBUG
  142084. if( yyTraceFILE ){
  142085. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  142086. }
  142087. #endif
  142088. #ifndef YYNOERRORRECOVERY
  142089. yypParser->yyerrcnt = -1;
  142090. #endif
  142091. assert( yypParser->yytos==yypParser->yystack );
  142092. /* Here code is inserted which will be executed whenever the
  142093. ** parser accepts */
  142094. /*********** Begin %parse_accept code *****************************************/
  142095. /*********** End %parse_accept code *******************************************/
  142096. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  142097. sqlite3ParserCTX_STORE
  142098. }
  142099. /* The main parser program.
  142100. ** The first argument is a pointer to a structure obtained from
  142101. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  142102. ** The second argument is the major token number. The third is
  142103. ** the minor token. The fourth optional argument is whatever the
  142104. ** user wants (and specified in the grammar) and is available for
  142105. ** use by the action routines.
  142106. **
  142107. ** Inputs:
  142108. ** <ul>
  142109. ** <li> A pointer to the parser (an opaque structure.)
  142110. ** <li> The major token number.
  142111. ** <li> The minor token number.
  142112. ** <li> An option argument of a grammar-specified type.
  142113. ** </ul>
  142114. **
  142115. ** Outputs:
  142116. ** None.
  142117. */
  142118. SQLITE_PRIVATE void sqlite3Parser(
  142119. void *yyp, /* The parser */
  142120. int yymajor, /* The major token code number */
  142121. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  142122. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  142123. ){
  142124. YYMINORTYPE yyminorunion;
  142125. YYACTIONTYPE yyact; /* The parser action. */
  142126. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  142127. int yyendofinput; /* True if we are at the end of input */
  142128. #endif
  142129. #ifdef YYERRORSYMBOL
  142130. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  142131. #endif
  142132. yyParser *yypParser = (yyParser*)yyp; /* The parser */
  142133. sqlite3ParserCTX_FETCH
  142134. sqlite3ParserARG_STORE
  142135. assert( yypParser->yytos!=0 );
  142136. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  142137. yyendofinput = (yymajor==0);
  142138. #endif
  142139. yyact = yypParser->yytos->stateno;
  142140. #ifndef NDEBUG
  142141. if( yyTraceFILE ){
  142142. if( yyact < YY_MIN_REDUCE ){
  142143. fprintf(yyTraceFILE,"%sInput '%s' in state %d\n",
  142144. yyTracePrompt,yyTokenName[yymajor],yyact);
  142145. }else{
  142146. fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  142147. yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE);
  142148. }
  142149. }
  142150. #endif
  142151. do{
  142152. assert( yyact==yypParser->yytos->stateno );
  142153. yyact = yy_find_shift_action((YYCODETYPE)yymajor,yyact);
  142154. if( yyact >= YY_MIN_REDUCE ){
  142155. yyact = yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor,
  142156. yyminor sqlite3ParserCTX_PARAM);
  142157. }else if( yyact <= YY_MAX_SHIFTREDUCE ){
  142158. yy_shift(yypParser,yyact,(YYCODETYPE)yymajor,yyminor);
  142159. #ifndef YYNOERRORRECOVERY
  142160. yypParser->yyerrcnt--;
  142161. #endif
  142162. break;
  142163. }else if( yyact==YY_ACCEPT_ACTION ){
  142164. yypParser->yytos--;
  142165. yy_accept(yypParser);
  142166. return;
  142167. }else{
  142168. assert( yyact == YY_ERROR_ACTION );
  142169. yyminorunion.yy0 = yyminor;
  142170. #ifdef YYERRORSYMBOL
  142171. int yymx;
  142172. #endif
  142173. #ifndef NDEBUG
  142174. if( yyTraceFILE ){
  142175. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  142176. }
  142177. #endif
  142178. #ifdef YYERRORSYMBOL
  142179. /* A syntax error has occurred.
  142180. ** The response to an error depends upon whether or not the
  142181. ** grammar defines an error token "ERROR".
  142182. **
  142183. ** This is what we do if the grammar does define ERROR:
  142184. **
  142185. ** * Call the %syntax_error function.
  142186. **
  142187. ** * Begin popping the stack until we enter a state where
  142188. ** it is legal to shift the error symbol, then shift
  142189. ** the error symbol.
  142190. **
  142191. ** * Set the error count to three.
  142192. **
  142193. ** * Begin accepting and shifting new tokens. No new error
  142194. ** processing will occur until three tokens have been
  142195. ** shifted successfully.
  142196. **
  142197. */
  142198. if( yypParser->yyerrcnt<0 ){
  142199. yy_syntax_error(yypParser,yymajor,yyminor);
  142200. }
  142201. yymx = yypParser->yytos->major;
  142202. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  142203. #ifndef NDEBUG
  142204. if( yyTraceFILE ){
  142205. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  142206. yyTracePrompt,yyTokenName[yymajor]);
  142207. }
  142208. #endif
  142209. yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
  142210. yymajor = YYNOCODE;
  142211. }else{
  142212. while( yypParser->yytos >= yypParser->yystack
  142213. && (yyact = yy_find_reduce_action(
  142214. yypParser->yytos->stateno,
  142215. YYERRORSYMBOL)) > YY_MAX_SHIFTREDUCE
  142216. ){
  142217. yy_pop_parser_stack(yypParser);
  142218. }
  142219. if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
  142220. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  142221. yy_parse_failed(yypParser);
  142222. #ifndef YYNOERRORRECOVERY
  142223. yypParser->yyerrcnt = -1;
  142224. #endif
  142225. yymajor = YYNOCODE;
  142226. }else if( yymx!=YYERRORSYMBOL ){
  142227. yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
  142228. }
  142229. }
  142230. yypParser->yyerrcnt = 3;
  142231. yyerrorhit = 1;
  142232. if( yymajor==YYNOCODE ) break;
  142233. yyact = yypParser->yytos->stateno;
  142234. #elif defined(YYNOERRORRECOVERY)
  142235. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  142236. ** do any kind of error recovery. Instead, simply invoke the syntax
  142237. ** error routine and continue going as if nothing had happened.
  142238. **
  142239. ** Applications can set this macro (for example inside %include) if
  142240. ** they intend to abandon the parse upon the first syntax error seen.
  142241. */
  142242. yy_syntax_error(yypParser,yymajor, yyminor);
  142243. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  142244. break;
  142245. #else /* YYERRORSYMBOL is not defined */
  142246. /* This is what we do if the grammar does not define ERROR:
  142247. **
  142248. ** * Report an error message, and throw away the input token.
  142249. **
  142250. ** * If the input token is $, then fail the parse.
  142251. **
  142252. ** As before, subsequent error messages are suppressed until
  142253. ** three input tokens have been successfully shifted.
  142254. */
  142255. if( yypParser->yyerrcnt<=0 ){
  142256. yy_syntax_error(yypParser,yymajor, yyminor);
  142257. }
  142258. yypParser->yyerrcnt = 3;
  142259. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  142260. if( yyendofinput ){
  142261. yy_parse_failed(yypParser);
  142262. #ifndef YYNOERRORRECOVERY
  142263. yypParser->yyerrcnt = -1;
  142264. #endif
  142265. }
  142266. break;
  142267. #endif
  142268. }
  142269. }while( yypParser->yytos>yypParser->yystack );
  142270. #ifndef NDEBUG
  142271. if( yyTraceFILE ){
  142272. yyStackEntry *i;
  142273. char cDiv = '[';
  142274. fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
  142275. for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
  142276. fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
  142277. cDiv = ' ';
  142278. }
  142279. fprintf(yyTraceFILE,"]\n");
  142280. }
  142281. #endif
  142282. return;
  142283. }
  142284. /*
  142285. ** Return the fallback token corresponding to canonical token iToken, or
  142286. ** 0 if iToken has no fallback.
  142287. */
  142288. SQLITE_PRIVATE int sqlite3ParserFallback(int iToken){
  142289. #ifdef YYFALLBACK
  142290. if( iToken<(int)(sizeof(yyFallback)/sizeof(yyFallback[0])) ){
  142291. return yyFallback[iToken];
  142292. }
  142293. #else
  142294. (void)iToken;
  142295. #endif
  142296. return 0;
  142297. }
  142298. /************** End of parse.c ***********************************************/
  142299. /************** Begin file tokenize.c ****************************************/
  142300. /*
  142301. ** 2001 September 15
  142302. **
  142303. ** The author disclaims copyright to this source code. In place of
  142304. ** a legal notice, here is a blessing:
  142305. **
  142306. ** May you do good and not evil.
  142307. ** May you find forgiveness for yourself and forgive others.
  142308. ** May you share freely, never taking more than you give.
  142309. **
  142310. *************************************************************************
  142311. ** An tokenizer for SQL
  142312. **
  142313. ** This file contains C code that splits an SQL input string up into
  142314. ** individual tokens and sends those tokens one-by-one over to the
  142315. ** parser for analysis.
  142316. */
  142317. /* #include "sqliteInt.h" */
  142318. /* #include <stdlib.h> */
  142319. /* Character classes for tokenizing
  142320. **
  142321. ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
  142322. ** using a lookup table, whereas a switch() directly on c uses a binary search.
  142323. ** The lookup table is much faster. To maximize speed, and to ensure that
  142324. ** a lookup table is used, all of the classes need to be small integers and
  142325. ** all of them need to be used within the switch.
  142326. */
  142327. #define CC_X 0 /* The letter 'x', or start of BLOB literal */
  142328. #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
  142329. #define CC_ID 2 /* unicode characters usable in IDs */
  142330. #define CC_DIGIT 3 /* Digits */
  142331. #define CC_DOLLAR 4 /* '$' */
  142332. #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
  142333. #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
  142334. #define CC_SPACE 7 /* Space characters */
  142335. #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
  142336. #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
  142337. #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
  142338. #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
  142339. #define CC_LT 12 /* '<'. Part of < or <= or <> */
  142340. #define CC_GT 13 /* '>'. Part of > or >= */
  142341. #define CC_EQ 14 /* '='. Part of = or == */
  142342. #define CC_BANG 15 /* '!'. Part of != */
  142343. #define CC_SLASH 16 /* '/'. / or c-style comment */
  142344. #define CC_LP 17 /* '(' */
  142345. #define CC_RP 18 /* ')' */
  142346. #define CC_SEMI 19 /* ';' */
  142347. #define CC_PLUS 20 /* '+' */
  142348. #define CC_STAR 21 /* '*' */
  142349. #define CC_PERCENT 22 /* '%' */
  142350. #define CC_COMMA 23 /* ',' */
  142351. #define CC_AND 24 /* '&' */
  142352. #define CC_TILDA 25 /* '~' */
  142353. #define CC_DOT 26 /* '.' */
  142354. #define CC_ILLEGAL 27 /* Illegal character */
  142355. #define CC_NUL 28 /* 0x00 */
  142356. static const unsigned char aiClass[] = {
  142357. #ifdef SQLITE_ASCII
  142358. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  142359. /* 0x */ 28, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
  142360. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  142361. /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
  142362. /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
  142363. /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  142364. /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
  142365. /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  142366. /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
  142367. /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  142368. /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  142369. /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  142370. /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  142371. /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  142372. /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  142373. /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  142374. /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
  142375. #endif
  142376. #ifdef SQLITE_EBCDIC
  142377. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  142378. /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
  142379. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  142380. /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  142381. /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  142382. /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
  142383. /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
  142384. /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6,
  142385. /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
  142386. /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  142387. /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  142388. /* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  142389. /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
  142390. /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  142391. /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  142392. /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  142393. /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
  142394. #endif
  142395. };
  142396. /*
  142397. ** The charMap() macro maps alphabetic characters (only) into their
  142398. ** lower-case ASCII equivalent. On ASCII machines, this is just
  142399. ** an upper-to-lower case map. On EBCDIC machines we also need
  142400. ** to adjust the encoding. The mapping is only valid for alphabetics
  142401. ** which are the only characters for which this feature is used.
  142402. **
  142403. ** Used by keywordhash.h
  142404. */
  142405. #ifdef SQLITE_ASCII
  142406. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  142407. #endif
  142408. #ifdef SQLITE_EBCDIC
  142409. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  142410. const unsigned char ebcdicToAscii[] = {
  142411. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  142412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  142413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  142414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  142415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  142416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  142417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  142418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  142419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  142420. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  142421. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  142422. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  142423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  142424. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  142425. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  142426. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  142427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  142428. };
  142429. #endif
  142430. /*
  142431. ** The sqlite3KeywordCode function looks up an identifier to determine if
  142432. ** it is a keyword. If it is a keyword, the token code of that keyword is
  142433. ** returned. If the input is not a keyword, TK_ID is returned.
  142434. **
  142435. ** The implementation of this routine was generated by a program,
  142436. ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
  142437. ** The output of the mkkeywordhash.c program is written into a file
  142438. ** named keywordhash.h and then included into this source file by
  142439. ** the #include below.
  142440. */
  142441. /************** Include keywordhash.h in the middle of tokenize.c ************/
  142442. /************** Begin file keywordhash.h *************************************/
  142443. /***** This file contains automatically generated code ******
  142444. **
  142445. ** The code in this file has been automatically generated by
  142446. **
  142447. ** sqlite/tool/mkkeywordhash.c
  142448. **
  142449. ** The code in this file implements a function that determines whether
  142450. ** or not a given identifier is really an SQL keyword. The same thing
  142451. ** might be implemented more directly using a hand-written hash table.
  142452. ** But by using this automatically generated code, the size of the code
  142453. ** is substantially reduced. This is important for embedded applications
  142454. ** on platforms with limited memory.
  142455. */
  142456. /* Hash score: 208 */
  142457. /* zKWText[] encodes 923 bytes of keyword text in 614 bytes */
  142458. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  142459. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  142460. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  142461. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERANGEBETWEEN */
  142462. /* OTHINGLOBYCASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  142463. /* IMMEDIATEJOINSERTLIKEMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMIT */
  142464. /* WHENOTNULLWHERECURSIVEAFTERENAMEANDEFAULTAUTOINCREMENTCAST */
  142465. /* COLUMNCOMMITCONFLICTCROSSCURRENT_TIMESTAMPARTITIONDEFERRED */
  142466. /* ISTINCTDROPRECEDINGFAILFILTEREPLACEFOLLOWINGFROMFULLIFISNULL */
  142467. /* ORDERESTRICTOVERIGHTROLLBACKROWSUNBOUNDEDUNIONUSINGVACUUMVIEW */
  142468. /* INDOWINITIALLYPRIMARY */
  142469. static const char zKWText[613] = {
  142470. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  142471. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  142472. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  142473. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  142474. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  142475. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  142476. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  142477. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  142478. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  142479. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  142480. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  142481. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  142482. 'T','E','B','E','G','I','N','N','E','R','A','N','G','E','B','E','T','W',
  142483. 'E','E','N','O','T','H','I','N','G','L','O','B','Y','C','A','S','C','A',
  142484. 'D','E','L','E','T','E','C','A','S','E','C','O','L','L','A','T','E','C',
  142485. 'R','E','A','T','E','C','U','R','R','E','N','T','_','D','A','T','E','D',
  142486. 'E','T','A','C','H','I','M','M','E','D','I','A','T','E','J','O','I','N',
  142487. 'S','E','R','T','L','I','K','E','M','A','T','C','H','P','L','A','N','A',
  142488. 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
  142489. 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','O',
  142490. 'T','N','U','L','L','W','H','E','R','E','C','U','R','S','I','V','E','A',
  142491. 'F','T','E','R','E','N','A','M','E','A','N','D','E','F','A','U','L','T',
  142492. 'A','U','T','O','I','N','C','R','E','M','E','N','T','C','A','S','T','C',
  142493. 'O','L','U','M','N','C','O','M','M','I','T','C','O','N','F','L','I','C',
  142494. 'T','C','R','O','S','S','C','U','R','R','E','N','T','_','T','I','M','E',
  142495. 'S','T','A','M','P','A','R','T','I','T','I','O','N','D','E','F','E','R',
  142496. 'R','E','D','I','S','T','I','N','C','T','D','R','O','P','R','E','C','E',
  142497. 'D','I','N','G','F','A','I','L','F','I','L','T','E','R','E','P','L','A',
  142498. 'C','E','F','O','L','L','O','W','I','N','G','F','R','O','M','F','U','L',
  142499. 'L','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T','R',
  142500. 'I','C','T','O','V','E','R','I','G','H','T','R','O','L','L','B','A','C',
  142501. 'K','R','O','W','S','U','N','B','O','U','N','D','E','D','U','N','I','O',
  142502. 'N','U','S','I','N','G','V','A','C','U','U','M','V','I','E','W','I','N',
  142503. 'D','O','W','I','N','I','T','I','A','L','L','Y','P','R','I','M','A','R',
  142504. 'Y',
  142505. };
  142506. /* aKWHash[i] is the hash value for the i-th keyword */
  142507. static const unsigned char aKWHash[127] = {
  142508. 74, 109, 124, 72, 106, 45, 0, 0, 81, 0, 76, 61, 0,
  142509. 42, 12, 77, 15, 0, 123, 84, 54, 118, 125, 19, 0, 0,
  142510. 130, 0, 128, 121, 0, 22, 96, 0, 9, 0, 0, 115, 69,
  142511. 0, 67, 6, 0, 48, 93, 136, 0, 126, 104, 0, 0, 44,
  142512. 0, 107, 24, 0, 17, 0, 131, 53, 23, 0, 5, 62, 132,
  142513. 99, 0, 0, 135, 110, 60, 134, 57, 113, 55, 0, 94, 0,
  142514. 103, 26, 0, 102, 0, 0, 0, 98, 95, 100, 105, 117, 14,
  142515. 39, 116, 0, 80, 0, 133, 114, 92, 59, 0, 129, 79, 119,
  142516. 86, 46, 83, 0, 0, 97, 40, 122, 120, 0, 127, 0, 0,
  142517. 29, 0, 89, 87, 88, 0, 20, 85, 111, 56,
  142518. };
  142519. /* aKWNext[] forms the hash collision chain. If aKWHash[i]==0
  142520. ** then the i-th keyword has no more hash collisions. Otherwise,
  142521. ** the next keyword with the same hash is aKWHash[i]-1. */
  142522. static const unsigned char aKWNext[136] = {
  142523. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  142524. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  142525. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142526. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  142527. 0, 43, 3, 47, 0, 0, 32, 0, 0, 0, 0, 0, 0,
  142528. 0, 1, 64, 0, 0, 65, 0, 41, 0, 38, 0, 0, 0,
  142529. 0, 0, 49, 75, 0, 0, 30, 0, 58, 0, 0, 0, 31,
  142530. 63, 16, 34, 10, 0, 0, 0, 0, 0, 0, 0, 11, 70,
  142531. 91, 0, 0, 8, 0, 108, 0, 101, 28, 52, 68, 0, 112,
  142532. 0, 73, 51, 0, 90, 27, 37, 0, 71, 36, 82, 0, 35,
  142533. 66, 25, 18, 0, 0, 78,
  142534. };
  142535. /* aKWLen[i] is the length (in bytes) of the i-th keyword */
  142536. static const unsigned char aKWLen[136] = {
  142537. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  142538. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  142539. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  142540. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  142541. 6, 6, 5, 6, 5, 5, 5, 7, 7, 4, 2, 7, 3,
  142542. 6, 4, 7, 6, 12, 6, 9, 4, 6, 4, 5, 4, 7,
  142543. 6, 5, 6, 7, 5, 4, 7, 3, 2, 4, 5, 9, 5,
  142544. 6, 3, 7, 13, 2, 2, 4, 6, 6, 8, 5, 17, 12,
  142545. 7, 9, 8, 8, 2, 4, 9, 4, 6, 7, 9, 4, 4,
  142546. 2, 6, 5, 8, 4, 5, 8, 4, 3, 9, 5, 5, 6,
  142547. 4, 6, 2, 9, 3, 7,
  142548. };
  142549. /* aKWOffset[i] is the index into zKWText[] of the start of
  142550. ** the text for the i-th keyword. */
  142551. static const unsigned short int aKWOffset[136] = {
  142552. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  142553. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  142554. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  142555. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  142556. 199, 204, 209, 212, 218, 221, 225, 230, 236, 242, 245, 247, 248,
  142557. 252, 258, 262, 269, 275, 287, 293, 302, 304, 310, 314, 319, 321,
  142558. 328, 333, 338, 344, 350, 355, 358, 358, 358, 361, 365, 368, 377,
  142559. 381, 387, 389, 396, 398, 400, 409, 413, 419, 425, 433, 438, 438,
  142560. 438, 454, 463, 470, 471, 478, 481, 490, 494, 499, 506, 515, 519,
  142561. 523, 525, 531, 535, 543, 546, 551, 559, 559, 563, 572, 577, 582,
  142562. 588, 591, 594, 597, 602, 606,
  142563. };
  142564. /* aKWCode[i] is the parser symbol code for the i-th keyword */
  142565. static const unsigned char aKWCode[136] = {
  142566. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  142567. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  142568. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  142569. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  142570. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  142571. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  142572. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  142573. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  142574. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  142575. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  142576. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  142577. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RANGE, TK_BETWEEN,
  142578. TK_NOTHING, TK_LIKE_KW, TK_BY, TK_CASCADE, TK_ASC,
  142579. TK_DELETE, TK_CASE, TK_COLLATE, TK_CREATE, TK_CTIME_KW,
  142580. TK_DETACH, TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_LIKE_KW,
  142581. TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT,
  142582. TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, TK_NOTNULL,
  142583. TK_NOT, TK_NO, TK_NULL, TK_WHERE, TK_RECURSIVE,
  142584. TK_AFTER, TK_RENAME, TK_AND, TK_DEFAULT, TK_AUTOINCR,
  142585. TK_TO, TK_IN, TK_CAST, TK_COLUMNKW, TK_COMMIT,
  142586. TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW, TK_CURRENT,
  142587. TK_PARTITION, TK_DEFERRED, TK_DISTINCT, TK_IS, TK_DROP,
  142588. TK_PRECEDING, TK_FAIL, TK_FILTER, TK_REPLACE, TK_FOLLOWING,
  142589. TK_FROM, TK_JOIN_KW, TK_IF, TK_ISNULL, TK_ORDER,
  142590. TK_RESTRICT, TK_OVER, TK_JOIN_KW, TK_ROLLBACK, TK_ROWS,
  142591. TK_ROW, TK_UNBOUNDED, TK_UNION, TK_USING, TK_VACUUM,
  142592. TK_VIEW, TK_WINDOW, TK_DO, TK_INITIALLY, TK_ALL,
  142593. TK_PRIMARY,
  142594. };
  142595. /* Check to see if z[0..n-1] is a keyword. If it is, write the
  142596. ** parser symbol code for that keyword into *pType. Always
  142597. ** return the integer n (the length of the token). */
  142598. static int keywordCode(const char *z, int n, int *pType){
  142599. int i, j;
  142600. const char *zKW;
  142601. if( n>=2 ){
  142602. i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
  142603. for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
  142604. if( aKWLen[i]!=n ) continue;
  142605. j = 0;
  142606. zKW = &zKWText[aKWOffset[i]];
  142607. #ifdef SQLITE_ASCII
  142608. while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
  142609. #endif
  142610. #ifdef SQLITE_EBCDIC
  142611. while( j<n && toupper(z[j])==zKW[j] ){ j++; }
  142612. #endif
  142613. if( j<n ) continue;
  142614. testcase( i==0 ); /* REINDEX */
  142615. testcase( i==1 ); /* INDEXED */
  142616. testcase( i==2 ); /* INDEX */
  142617. testcase( i==3 ); /* DESC */
  142618. testcase( i==4 ); /* ESCAPE */
  142619. testcase( i==5 ); /* EACH */
  142620. testcase( i==6 ); /* CHECK */
  142621. testcase( i==7 ); /* KEY */
  142622. testcase( i==8 ); /* BEFORE */
  142623. testcase( i==9 ); /* FOREIGN */
  142624. testcase( i==10 ); /* FOR */
  142625. testcase( i==11 ); /* IGNORE */
  142626. testcase( i==12 ); /* REGEXP */
  142627. testcase( i==13 ); /* EXPLAIN */
  142628. testcase( i==14 ); /* INSTEAD */
  142629. testcase( i==15 ); /* ADD */
  142630. testcase( i==16 ); /* DATABASE */
  142631. testcase( i==17 ); /* AS */
  142632. testcase( i==18 ); /* SELECT */
  142633. testcase( i==19 ); /* TABLE */
  142634. testcase( i==20 ); /* LEFT */
  142635. testcase( i==21 ); /* THEN */
  142636. testcase( i==22 ); /* END */
  142637. testcase( i==23 ); /* DEFERRABLE */
  142638. testcase( i==24 ); /* ELSE */
  142639. testcase( i==25 ); /* EXCEPT */
  142640. testcase( i==26 ); /* TRANSACTION */
  142641. testcase( i==27 ); /* ACTION */
  142642. testcase( i==28 ); /* ON */
  142643. testcase( i==29 ); /* NATURAL */
  142644. testcase( i==30 ); /* ALTER */
  142645. testcase( i==31 ); /* RAISE */
  142646. testcase( i==32 ); /* EXCLUSIVE */
  142647. testcase( i==33 ); /* EXISTS */
  142648. testcase( i==34 ); /* SAVEPOINT */
  142649. testcase( i==35 ); /* INTERSECT */
  142650. testcase( i==36 ); /* TRIGGER */
  142651. testcase( i==37 ); /* REFERENCES */
  142652. testcase( i==38 ); /* CONSTRAINT */
  142653. testcase( i==39 ); /* INTO */
  142654. testcase( i==40 ); /* OFFSET */
  142655. testcase( i==41 ); /* OF */
  142656. testcase( i==42 ); /* SET */
  142657. testcase( i==43 ); /* TEMPORARY */
  142658. testcase( i==44 ); /* TEMP */
  142659. testcase( i==45 ); /* OR */
  142660. testcase( i==46 ); /* UNIQUE */
  142661. testcase( i==47 ); /* QUERY */
  142662. testcase( i==48 ); /* WITHOUT */
  142663. testcase( i==49 ); /* WITH */
  142664. testcase( i==50 ); /* OUTER */
  142665. testcase( i==51 ); /* RELEASE */
  142666. testcase( i==52 ); /* ATTACH */
  142667. testcase( i==53 ); /* HAVING */
  142668. testcase( i==54 ); /* GROUP */
  142669. testcase( i==55 ); /* UPDATE */
  142670. testcase( i==56 ); /* BEGIN */
  142671. testcase( i==57 ); /* INNER */
  142672. testcase( i==58 ); /* RANGE */
  142673. testcase( i==59 ); /* BETWEEN */
  142674. testcase( i==60 ); /* NOTHING */
  142675. testcase( i==61 ); /* GLOB */
  142676. testcase( i==62 ); /* BY */
  142677. testcase( i==63 ); /* CASCADE */
  142678. testcase( i==64 ); /* ASC */
  142679. testcase( i==65 ); /* DELETE */
  142680. testcase( i==66 ); /* CASE */
  142681. testcase( i==67 ); /* COLLATE */
  142682. testcase( i==68 ); /* CREATE */
  142683. testcase( i==69 ); /* CURRENT_DATE */
  142684. testcase( i==70 ); /* DETACH */
  142685. testcase( i==71 ); /* IMMEDIATE */
  142686. testcase( i==72 ); /* JOIN */
  142687. testcase( i==73 ); /* INSERT */
  142688. testcase( i==74 ); /* LIKE */
  142689. testcase( i==75 ); /* MATCH */
  142690. testcase( i==76 ); /* PLAN */
  142691. testcase( i==77 ); /* ANALYZE */
  142692. testcase( i==78 ); /* PRAGMA */
  142693. testcase( i==79 ); /* ABORT */
  142694. testcase( i==80 ); /* VALUES */
  142695. testcase( i==81 ); /* VIRTUAL */
  142696. testcase( i==82 ); /* LIMIT */
  142697. testcase( i==83 ); /* WHEN */
  142698. testcase( i==84 ); /* NOTNULL */
  142699. testcase( i==85 ); /* NOT */
  142700. testcase( i==86 ); /* NO */
  142701. testcase( i==87 ); /* NULL */
  142702. testcase( i==88 ); /* WHERE */
  142703. testcase( i==89 ); /* RECURSIVE */
  142704. testcase( i==90 ); /* AFTER */
  142705. testcase( i==91 ); /* RENAME */
  142706. testcase( i==92 ); /* AND */
  142707. testcase( i==93 ); /* DEFAULT */
  142708. testcase( i==94 ); /* AUTOINCREMENT */
  142709. testcase( i==95 ); /* TO */
  142710. testcase( i==96 ); /* IN */
  142711. testcase( i==97 ); /* CAST */
  142712. testcase( i==98 ); /* COLUMN */
  142713. testcase( i==99 ); /* COMMIT */
  142714. testcase( i==100 ); /* CONFLICT */
  142715. testcase( i==101 ); /* CROSS */
  142716. testcase( i==102 ); /* CURRENT_TIMESTAMP */
  142717. testcase( i==103 ); /* CURRENT_TIME */
  142718. testcase( i==104 ); /* CURRENT */
  142719. testcase( i==105 ); /* PARTITION */
  142720. testcase( i==106 ); /* DEFERRED */
  142721. testcase( i==107 ); /* DISTINCT */
  142722. testcase( i==108 ); /* IS */
  142723. testcase( i==109 ); /* DROP */
  142724. testcase( i==110 ); /* PRECEDING */
  142725. testcase( i==111 ); /* FAIL */
  142726. testcase( i==112 ); /* FILTER */
  142727. testcase( i==113 ); /* REPLACE */
  142728. testcase( i==114 ); /* FOLLOWING */
  142729. testcase( i==115 ); /* FROM */
  142730. testcase( i==116 ); /* FULL */
  142731. testcase( i==117 ); /* IF */
  142732. testcase( i==118 ); /* ISNULL */
  142733. testcase( i==119 ); /* ORDER */
  142734. testcase( i==120 ); /* RESTRICT */
  142735. testcase( i==121 ); /* OVER */
  142736. testcase( i==122 ); /* RIGHT */
  142737. testcase( i==123 ); /* ROLLBACK */
  142738. testcase( i==124 ); /* ROWS */
  142739. testcase( i==125 ); /* ROW */
  142740. testcase( i==126 ); /* UNBOUNDED */
  142741. testcase( i==127 ); /* UNION */
  142742. testcase( i==128 ); /* USING */
  142743. testcase( i==129 ); /* VACUUM */
  142744. testcase( i==130 ); /* VIEW */
  142745. testcase( i==131 ); /* WINDOW */
  142746. testcase( i==132 ); /* DO */
  142747. testcase( i==133 ); /* INITIALLY */
  142748. testcase( i==134 ); /* ALL */
  142749. testcase( i==135 ); /* PRIMARY */
  142750. *pType = aKWCode[i];
  142751. break;
  142752. }
  142753. }
  142754. return n;
  142755. }
  142756. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  142757. int id = TK_ID;
  142758. keywordCode((char*)z, n, &id);
  142759. return id;
  142760. }
  142761. #define SQLITE_N_KEYWORD 136
  142762. SQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){
  142763. if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;
  142764. *pzName = zKWText + aKWOffset[i];
  142765. *pnName = aKWLen[i];
  142766. return SQLITE_OK;
  142767. }
  142768. SQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; }
  142769. SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){
  142770. return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName);
  142771. }
  142772. /************** End of keywordhash.h *****************************************/
  142773. /************** Continuing where we left off in tokenize.c *******************/
  142774. /*
  142775. ** If X is a character that can be used in an identifier then
  142776. ** IdChar(X) will be true. Otherwise it is false.
  142777. **
  142778. ** For ASCII, any character with the high-order bit set is
  142779. ** allowed in an identifier. For 7-bit characters,
  142780. ** sqlite3IsIdChar[X] must be 1.
  142781. **
  142782. ** For EBCDIC, the rules are more complex but have the same
  142783. ** end result.
  142784. **
  142785. ** Ticket #1066. the SQL standard does not allow '$' in the
  142786. ** middle of identifiers. But many SQL implementations do.
  142787. ** SQLite will allow '$' in identifiers for compatibility.
  142788. ** But the feature is undocumented.
  142789. */
  142790. #ifdef SQLITE_ASCII
  142791. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  142792. #endif
  142793. #ifdef SQLITE_EBCDIC
  142794. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  142795. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  142796. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  142797. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  142798. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  142799. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  142800. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  142801. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  142802. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  142803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  142804. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  142805. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  142806. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  142807. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  142808. };
  142809. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  142810. #endif
  142811. /* Make the IdChar function accessible from ctime.c and alter.c */
  142812. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  142813. #ifndef SQLITE_OMIT_WINDOWFUNC
  142814. /*
  142815. ** Return the id of the next token in string (*pz). Before returning, set
  142816. ** (*pz) to point to the byte following the parsed token.
  142817. */
  142818. static int getToken(const unsigned char **pz){
  142819. const unsigned char *z = *pz;
  142820. int t; /* Token type to return */
  142821. do {
  142822. z += sqlite3GetToken(z, &t);
  142823. }while( t==TK_SPACE );
  142824. if( t==TK_ID
  142825. || t==TK_STRING
  142826. || t==TK_JOIN_KW
  142827. || t==TK_WINDOW
  142828. || t==TK_OVER
  142829. || sqlite3ParserFallback(t)==TK_ID
  142830. ){
  142831. t = TK_ID;
  142832. }
  142833. *pz = z;
  142834. return t;
  142835. }
  142836. /*
  142837. ** The following three functions are called immediately after the tokenizer
  142838. ** reads the keywords WINDOW, OVER and FILTER, respectively, to determine
  142839. ** whether the token should be treated as a keyword or an SQL identifier.
  142840. ** This cannot be handled by the usual lemon %fallback method, due to
  142841. ** the ambiguity in some constructions. e.g.
  142842. **
  142843. ** SELECT sum(x) OVER ...
  142844. **
  142845. ** In the above, "OVER" might be a keyword, or it might be an alias for the
  142846. ** sum(x) expression. If a "%fallback ID OVER" directive were added to
  142847. ** grammar, then SQLite would always treat "OVER" as an alias, making it
  142848. ** impossible to call a window-function without a FILTER clause.
  142849. **
  142850. ** WINDOW is treated as a keyword if:
  142851. **
  142852. ** * the following token is an identifier, or a keyword that can fallback
  142853. ** to being an identifier, and
  142854. ** * the token after than one is TK_AS.
  142855. **
  142856. ** OVER is a keyword if:
  142857. **
  142858. ** * the previous token was TK_RP, and
  142859. ** * the next token is either TK_LP or an identifier.
  142860. **
  142861. ** FILTER is a keyword if:
  142862. **
  142863. ** * the previous token was TK_RP, and
  142864. ** * the next token is TK_LP.
  142865. */
  142866. static int analyzeWindowKeyword(const unsigned char *z){
  142867. int t;
  142868. t = getToken(&z);
  142869. if( t!=TK_ID ) return TK_ID;
  142870. t = getToken(&z);
  142871. if( t!=TK_AS ) return TK_ID;
  142872. return TK_WINDOW;
  142873. }
  142874. static int analyzeOverKeyword(const unsigned char *z, int lastToken){
  142875. if( lastToken==TK_RP ){
  142876. int t = getToken(&z);
  142877. if( t==TK_LP || t==TK_ID ) return TK_OVER;
  142878. }
  142879. return TK_ID;
  142880. }
  142881. static int analyzeFilterKeyword(const unsigned char *z, int lastToken){
  142882. if( lastToken==TK_RP && getToken(&z)==TK_LP ){
  142883. return TK_FILTER;
  142884. }
  142885. return TK_ID;
  142886. }
  142887. #endif /* SQLITE_OMIT_WINDOWFUNC */
  142888. /*
  142889. ** Return the length (in bytes) of the token that begins at z[0].
  142890. ** Store the token type in *tokenType before returning.
  142891. */
  142892. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  142893. int i, c;
  142894. switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
  142895. ** of the token. See the comment on the CC_ defines
  142896. ** above. */
  142897. case CC_SPACE: {
  142898. testcase( z[0]==' ' );
  142899. testcase( z[0]=='\t' );
  142900. testcase( z[0]=='\n' );
  142901. testcase( z[0]=='\f' );
  142902. testcase( z[0]=='\r' );
  142903. for(i=1; sqlite3Isspace(z[i]); i++){}
  142904. *tokenType = TK_SPACE;
  142905. return i;
  142906. }
  142907. case CC_MINUS: {
  142908. if( z[1]=='-' ){
  142909. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  142910. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  142911. return i;
  142912. }
  142913. *tokenType = TK_MINUS;
  142914. return 1;
  142915. }
  142916. case CC_LP: {
  142917. *tokenType = TK_LP;
  142918. return 1;
  142919. }
  142920. case CC_RP: {
  142921. *tokenType = TK_RP;
  142922. return 1;
  142923. }
  142924. case CC_SEMI: {
  142925. *tokenType = TK_SEMI;
  142926. return 1;
  142927. }
  142928. case CC_PLUS: {
  142929. *tokenType = TK_PLUS;
  142930. return 1;
  142931. }
  142932. case CC_STAR: {
  142933. *tokenType = TK_STAR;
  142934. return 1;
  142935. }
  142936. case CC_SLASH: {
  142937. if( z[1]!='*' || z[2]==0 ){
  142938. *tokenType = TK_SLASH;
  142939. return 1;
  142940. }
  142941. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  142942. if( c ) i++;
  142943. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  142944. return i;
  142945. }
  142946. case CC_PERCENT: {
  142947. *tokenType = TK_REM;
  142948. return 1;
  142949. }
  142950. case CC_EQ: {
  142951. *tokenType = TK_EQ;
  142952. return 1 + (z[1]=='=');
  142953. }
  142954. case CC_LT: {
  142955. if( (c=z[1])=='=' ){
  142956. *tokenType = TK_LE;
  142957. return 2;
  142958. }else if( c=='>' ){
  142959. *tokenType = TK_NE;
  142960. return 2;
  142961. }else if( c=='<' ){
  142962. *tokenType = TK_LSHIFT;
  142963. return 2;
  142964. }else{
  142965. *tokenType = TK_LT;
  142966. return 1;
  142967. }
  142968. }
  142969. case CC_GT: {
  142970. if( (c=z[1])=='=' ){
  142971. *tokenType = TK_GE;
  142972. return 2;
  142973. }else if( c=='>' ){
  142974. *tokenType = TK_RSHIFT;
  142975. return 2;
  142976. }else{
  142977. *tokenType = TK_GT;
  142978. return 1;
  142979. }
  142980. }
  142981. case CC_BANG: {
  142982. if( z[1]!='=' ){
  142983. *tokenType = TK_ILLEGAL;
  142984. return 1;
  142985. }else{
  142986. *tokenType = TK_NE;
  142987. return 2;
  142988. }
  142989. }
  142990. case CC_PIPE: {
  142991. if( z[1]!='|' ){
  142992. *tokenType = TK_BITOR;
  142993. return 1;
  142994. }else{
  142995. *tokenType = TK_CONCAT;
  142996. return 2;
  142997. }
  142998. }
  142999. case CC_COMMA: {
  143000. *tokenType = TK_COMMA;
  143001. return 1;
  143002. }
  143003. case CC_AND: {
  143004. *tokenType = TK_BITAND;
  143005. return 1;
  143006. }
  143007. case CC_TILDA: {
  143008. *tokenType = TK_BITNOT;
  143009. return 1;
  143010. }
  143011. case CC_QUOTE: {
  143012. int delim = z[0];
  143013. testcase( delim=='`' );
  143014. testcase( delim=='\'' );
  143015. testcase( delim=='"' );
  143016. for(i=1; (c=z[i])!=0; i++){
  143017. if( c==delim ){
  143018. if( z[i+1]==delim ){
  143019. i++;
  143020. }else{
  143021. break;
  143022. }
  143023. }
  143024. }
  143025. if( c=='\'' ){
  143026. *tokenType = TK_STRING;
  143027. return i+1;
  143028. }else if( c!=0 ){
  143029. *tokenType = TK_ID;
  143030. return i+1;
  143031. }else{
  143032. *tokenType = TK_ILLEGAL;
  143033. return i;
  143034. }
  143035. }
  143036. case CC_DOT: {
  143037. #ifndef SQLITE_OMIT_FLOATING_POINT
  143038. if( !sqlite3Isdigit(z[1]) )
  143039. #endif
  143040. {
  143041. *tokenType = TK_DOT;
  143042. return 1;
  143043. }
  143044. /* If the next character is a digit, this is a floating point
  143045. ** number that begins with ".". Fall thru into the next case */
  143046. }
  143047. case CC_DIGIT: {
  143048. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  143049. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  143050. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  143051. testcase( z[0]=='9' );
  143052. *tokenType = TK_INTEGER;
  143053. #ifndef SQLITE_OMIT_HEX_INTEGER
  143054. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  143055. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  143056. return i;
  143057. }
  143058. #endif
  143059. for(i=0; sqlite3Isdigit(z[i]); i++){}
  143060. #ifndef SQLITE_OMIT_FLOATING_POINT
  143061. if( z[i]=='.' ){
  143062. i++;
  143063. while( sqlite3Isdigit(z[i]) ){ i++; }
  143064. *tokenType = TK_FLOAT;
  143065. }
  143066. if( (z[i]=='e' || z[i]=='E') &&
  143067. ( sqlite3Isdigit(z[i+1])
  143068. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  143069. )
  143070. ){
  143071. i += 2;
  143072. while( sqlite3Isdigit(z[i]) ){ i++; }
  143073. *tokenType = TK_FLOAT;
  143074. }
  143075. #endif
  143076. while( IdChar(z[i]) ){
  143077. *tokenType = TK_ILLEGAL;
  143078. i++;
  143079. }
  143080. return i;
  143081. }
  143082. case CC_QUOTE2: {
  143083. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  143084. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  143085. return i;
  143086. }
  143087. case CC_VARNUM: {
  143088. *tokenType = TK_VARIABLE;
  143089. for(i=1; sqlite3Isdigit(z[i]); i++){}
  143090. return i;
  143091. }
  143092. case CC_DOLLAR:
  143093. case CC_VARALPHA: {
  143094. int n = 0;
  143095. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  143096. testcase( z[0]==':' ); testcase( z[0]=='#' );
  143097. *tokenType = TK_VARIABLE;
  143098. for(i=1; (c=z[i])!=0; i++){
  143099. if( IdChar(c) ){
  143100. n++;
  143101. #ifndef SQLITE_OMIT_TCL_VARIABLE
  143102. }else if( c=='(' && n>0 ){
  143103. do{
  143104. i++;
  143105. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  143106. if( c==')' ){
  143107. i++;
  143108. }else{
  143109. *tokenType = TK_ILLEGAL;
  143110. }
  143111. break;
  143112. }else if( c==':' && z[i+1]==':' ){
  143113. i++;
  143114. #endif
  143115. }else{
  143116. break;
  143117. }
  143118. }
  143119. if( n==0 ) *tokenType = TK_ILLEGAL;
  143120. return i;
  143121. }
  143122. case CC_KYWD: {
  143123. for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
  143124. if( IdChar(z[i]) ){
  143125. /* This token started out using characters that can appear in keywords,
  143126. ** but z[i] is a character not allowed within keywords, so this must
  143127. ** be an identifier instead */
  143128. i++;
  143129. break;
  143130. }
  143131. *tokenType = TK_ID;
  143132. return keywordCode((char*)z, i, tokenType);
  143133. }
  143134. case CC_X: {
  143135. #ifndef SQLITE_OMIT_BLOB_LITERAL
  143136. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  143137. if( z[1]=='\'' ){
  143138. *tokenType = TK_BLOB;
  143139. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  143140. if( z[i]!='\'' || i%2 ){
  143141. *tokenType = TK_ILLEGAL;
  143142. while( z[i] && z[i]!='\'' ){ i++; }
  143143. }
  143144. if( z[i] ) i++;
  143145. return i;
  143146. }
  143147. #endif
  143148. /* If it is not a BLOB literal, then it must be an ID, since no
  143149. ** SQL keywords start with the letter 'x'. Fall through */
  143150. }
  143151. case CC_ID: {
  143152. i = 1;
  143153. break;
  143154. }
  143155. case CC_NUL: {
  143156. *tokenType = TK_ILLEGAL;
  143157. return 0;
  143158. }
  143159. default: {
  143160. *tokenType = TK_ILLEGAL;
  143161. return 1;
  143162. }
  143163. }
  143164. while( IdChar(z[i]) ){ i++; }
  143165. *tokenType = TK_ID;
  143166. return i;
  143167. }
  143168. #ifdef SQLITE_ENABLE_NORMALIZE
  143169. /*
  143170. ** Return the length (in bytes) of the token that begins at z[0].
  143171. ** Store the token type in *tokenType before returning. If flags has
  143172. ** SQLITE_TOKEN_NORMALIZE flag enabled, use the identifier token type
  143173. ** for keywords. Add SQLITE_TOKEN_QUOTED to flags if the token was
  143174. ** actually a quoted identifier. Add SQLITE_TOKEN_KEYWORD to flags
  143175. ** if the token was recognized as a keyword; this is useful when the
  143176. ** SQLITE_TOKEN_NORMALIZE flag is used, because it enables the caller
  143177. ** to differentiate between a keyword being treated as an identifier
  143178. ** (for normalization purposes) and an actual identifier.
  143179. */
  143180. SQLITE_PRIVATE int sqlite3GetTokenNormalized(
  143181. const unsigned char *z,
  143182. int *tokenType,
  143183. int *flags
  143184. ){
  143185. int n;
  143186. unsigned char iClass = aiClass[*z];
  143187. if( iClass==CC_KYWD ){
  143188. int i;
  143189. for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
  143190. if( IdChar(z[i]) ){
  143191. /* This token started out using characters that can appear in keywords,
  143192. ** but z[i] is a character not allowed within keywords, so this must
  143193. ** be an identifier instead */
  143194. i++;
  143195. while( IdChar(z[i]) ){ i++; }
  143196. *tokenType = TK_ID;
  143197. return i;
  143198. }
  143199. *tokenType = TK_ID;
  143200. n = keywordCode((char*)z, i, tokenType);
  143201. /* If the token is no longer considered to be an identifier, then it is a
  143202. ** keyword of some kind. Make the token back into an identifier and then
  143203. ** set the SQLITE_TOKEN_KEYWORD flag. Several non-identifier tokens are
  143204. ** used verbatim, including IN, IS, NOT, and NULL. */
  143205. switch( *tokenType ){
  143206. case TK_ID: {
  143207. /* do nothing, handled by caller */
  143208. break;
  143209. }
  143210. case TK_IN:
  143211. case TK_IS:
  143212. case TK_NOT:
  143213. case TK_NULL: {
  143214. *flags |= SQLITE_TOKEN_KEYWORD;
  143215. break;
  143216. }
  143217. default: {
  143218. *tokenType = TK_ID;
  143219. *flags |= SQLITE_TOKEN_KEYWORD;
  143220. break;
  143221. }
  143222. }
  143223. }else{
  143224. n = sqlite3GetToken(z, tokenType);
  143225. /* If the token is considered to be an identifier and the character class
  143226. ** of the first character is a quote, set the SQLITE_TOKEN_QUOTED flag. */
  143227. if( *tokenType==TK_ID && (iClass==CC_QUOTE || iClass==CC_QUOTE2) ){
  143228. *flags |= SQLITE_TOKEN_QUOTED;
  143229. }
  143230. }
  143231. return n;
  143232. }
  143233. #endif /* SQLITE_ENABLE_NORMALIZE */
  143234. /*
  143235. ** Run the parser on the given SQL string. The parser structure is
  143236. ** passed in. An SQLITE_ status code is returned. If an error occurs
  143237. ** then an and attempt is made to write an error message into
  143238. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  143239. ** error message.
  143240. */
  143241. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  143242. int nErr = 0; /* Number of errors encountered */
  143243. void *pEngine; /* The LEMON-generated LALR(1) parser */
  143244. int n = 0; /* Length of the next token token */
  143245. int tokenType; /* type of the next token */
  143246. int lastTokenParsed = -1; /* type of the previous token */
  143247. sqlite3 *db = pParse->db; /* The database connection */
  143248. int mxSqlLen; /* Max length of an SQL string */
  143249. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  143250. yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
  143251. #endif
  143252. assert( zSql!=0 );
  143253. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  143254. if( db->nVdbeActive==0 ){
  143255. db->u1.isInterrupted = 0;
  143256. }
  143257. pParse->rc = SQLITE_OK;
  143258. pParse->zTail = zSql;
  143259. assert( pzErrMsg!=0 );
  143260. /* sqlite3ParserTrace(stdout, "parser: "); */
  143261. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  143262. pEngine = &sEngine;
  143263. sqlite3ParserInit(pEngine, pParse);
  143264. #else
  143265. pEngine = sqlite3ParserAlloc(sqlite3Malloc, pParse);
  143266. if( pEngine==0 ){
  143267. sqlite3OomFault(db);
  143268. return SQLITE_NOMEM_BKPT;
  143269. }
  143270. #endif
  143271. assert( pParse->pNewTable==0 );
  143272. assert( pParse->pNewTrigger==0 );
  143273. assert( pParse->nVar==0 );
  143274. assert( pParse->pVList==0 );
  143275. while( 1 ){
  143276. n = sqlite3GetToken((u8*)zSql, &tokenType);
  143277. mxSqlLen -= n;
  143278. if( mxSqlLen<0 ){
  143279. pParse->rc = SQLITE_TOOBIG;
  143280. break;
  143281. }
  143282. #ifndef SQLITE_OMIT_WINDOWFUNC
  143283. if( tokenType>=TK_WINDOW ){
  143284. assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER
  143285. || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW
  143286. );
  143287. #else
  143288. if( tokenType>=TK_SPACE ){
  143289. assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
  143290. #endif /* SQLITE_OMIT_WINDOWFUNC */
  143291. if( db->u1.isInterrupted ){
  143292. pParse->rc = SQLITE_INTERRUPT;
  143293. break;
  143294. }
  143295. if( tokenType==TK_SPACE ){
  143296. zSql += n;
  143297. continue;
  143298. }
  143299. if( zSql[0]==0 ){
  143300. /* Upon reaching the end of input, call the parser two more times
  143301. ** with tokens TK_SEMI and 0, in that order. */
  143302. if( lastTokenParsed==TK_SEMI ){
  143303. tokenType = 0;
  143304. }else if( lastTokenParsed==0 ){
  143305. break;
  143306. }else{
  143307. tokenType = TK_SEMI;
  143308. }
  143309. n = 0;
  143310. #ifndef SQLITE_OMIT_WINDOWFUNC
  143311. }else if( tokenType==TK_WINDOW ){
  143312. assert( n==6 );
  143313. tokenType = analyzeWindowKeyword((const u8*)&zSql[6]);
  143314. }else if( tokenType==TK_OVER ){
  143315. assert( n==4 );
  143316. tokenType = analyzeOverKeyword((const u8*)&zSql[4], lastTokenParsed);
  143317. }else if( tokenType==TK_FILTER ){
  143318. assert( n==6 );
  143319. tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed);
  143320. #endif /* SQLITE_OMIT_WINDOWFUNC */
  143321. }else{
  143322. sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
  143323. break;
  143324. }
  143325. }
  143326. pParse->sLastToken.z = zSql;
  143327. pParse->sLastToken.n = n;
  143328. sqlite3Parser(pEngine, tokenType, pParse->sLastToken);
  143329. lastTokenParsed = tokenType;
  143330. zSql += n;
  143331. if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
  143332. }
  143333. assert( nErr==0 );
  143334. #ifdef YYTRACKMAXSTACKDEPTH
  143335. sqlite3_mutex_enter(sqlite3MallocMutex());
  143336. sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
  143337. sqlite3ParserStackPeak(pEngine)
  143338. );
  143339. sqlite3_mutex_leave(sqlite3MallocMutex());
  143340. #endif /* YYDEBUG */
  143341. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  143342. sqlite3ParserFinalize(pEngine);
  143343. #else
  143344. sqlite3ParserFree(pEngine, sqlite3_free);
  143345. #endif
  143346. if( db->mallocFailed ){
  143347. pParse->rc = SQLITE_NOMEM_BKPT;
  143348. }
  143349. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  143350. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  143351. }
  143352. assert( pzErrMsg!=0 );
  143353. if( pParse->zErrMsg ){
  143354. *pzErrMsg = pParse->zErrMsg;
  143355. sqlite3_log(pParse->rc, "%s in \"%s\"",
  143356. *pzErrMsg, pParse->zTail);
  143357. pParse->zErrMsg = 0;
  143358. nErr++;
  143359. }
  143360. pParse->zTail = zSql;
  143361. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  143362. sqlite3VdbeDelete(pParse->pVdbe);
  143363. pParse->pVdbe = 0;
  143364. }
  143365. #ifndef SQLITE_OMIT_SHARED_CACHE
  143366. if( pParse->nested==0 ){
  143367. sqlite3DbFree(db, pParse->aTableLock);
  143368. pParse->aTableLock = 0;
  143369. pParse->nTableLock = 0;
  143370. }
  143371. #endif
  143372. #ifndef SQLITE_OMIT_VIRTUALTABLE
  143373. sqlite3_free(pParse->apVtabLock);
  143374. #endif
  143375. if( !IN_SPECIAL_PARSE ){
  143376. /* If the pParse->declareVtab flag is set, do not delete any table
  143377. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  143378. ** will take responsibility for freeing the Table structure.
  143379. */
  143380. sqlite3DeleteTable(db, pParse->pNewTable);
  143381. }
  143382. if( !IN_RENAME_OBJECT ){
  143383. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  143384. }
  143385. if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
  143386. sqlite3DbFree(db, pParse->pVList);
  143387. while( pParse->pAinc ){
  143388. AutoincInfo *p = pParse->pAinc;
  143389. pParse->pAinc = p->pNext;
  143390. sqlite3DbFreeNN(db, p);
  143391. }
  143392. while( pParse->pZombieTab ){
  143393. Table *p = pParse->pZombieTab;
  143394. pParse->pZombieTab = p->pNextZombie;
  143395. sqlite3DeleteTable(db, p);
  143396. }
  143397. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  143398. return nErr;
  143399. }
  143400. /************** End of tokenize.c ********************************************/
  143401. /************** Begin file complete.c ****************************************/
  143402. /*
  143403. ** 2001 September 15
  143404. **
  143405. ** The author disclaims copyright to this source code. In place of
  143406. ** a legal notice, here is a blessing:
  143407. **
  143408. ** May you do good and not evil.
  143409. ** May you find forgiveness for yourself and forgive others.
  143410. ** May you share freely, never taking more than you give.
  143411. **
  143412. *************************************************************************
  143413. ** An tokenizer for SQL
  143414. **
  143415. ** This file contains C code that implements the sqlite3_complete() API.
  143416. ** This code used to be part of the tokenizer.c source file. But by
  143417. ** separating it out, the code will be automatically omitted from
  143418. ** static links that do not use it.
  143419. */
  143420. /* #include "sqliteInt.h" */
  143421. #ifndef SQLITE_OMIT_COMPLETE
  143422. /*
  143423. ** This is defined in tokenize.c. We just have to import the definition.
  143424. */
  143425. #ifndef SQLITE_AMALGAMATION
  143426. #ifdef SQLITE_ASCII
  143427. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  143428. #endif
  143429. #ifdef SQLITE_EBCDIC
  143430. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  143431. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  143432. #endif
  143433. #endif /* SQLITE_AMALGAMATION */
  143434. /*
  143435. ** Token types used by the sqlite3_complete() routine. See the header
  143436. ** comments on that procedure for additional information.
  143437. */
  143438. #define tkSEMI 0
  143439. #define tkWS 1
  143440. #define tkOTHER 2
  143441. #ifndef SQLITE_OMIT_TRIGGER
  143442. #define tkEXPLAIN 3
  143443. #define tkCREATE 4
  143444. #define tkTEMP 5
  143445. #define tkTRIGGER 6
  143446. #define tkEND 7
  143447. #endif
  143448. /*
  143449. ** Return TRUE if the given SQL string ends in a semicolon.
  143450. **
  143451. ** Special handling is require for CREATE TRIGGER statements.
  143452. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  143453. ** must end with ";END;".
  143454. **
  143455. ** This implementation uses a state machine with 8 states:
  143456. **
  143457. ** (0) INVALID We have not yet seen a non-whitespace character.
  143458. **
  143459. ** (1) START At the beginning or end of an SQL statement. This routine
  143460. ** returns 1 if it ends in the START state and 0 if it ends
  143461. ** in any other state.
  143462. **
  143463. ** (2) NORMAL We are in the middle of statement which ends with a single
  143464. ** semicolon.
  143465. **
  143466. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  143467. ** a statement.
  143468. **
  143469. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  143470. ** statement, possibly preceded by EXPLAIN and/or followed by
  143471. ** TEMP or TEMPORARY
  143472. **
  143473. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  143474. ** ended by a semicolon, the keyword END, and another semicolon.
  143475. **
  143476. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  143477. ** the end of a trigger definition.
  143478. **
  143479. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  143480. ** of a trigger definition.
  143481. **
  143482. ** Transitions between states above are determined by tokens extracted
  143483. ** from the input. The following tokens are significant:
  143484. **
  143485. ** (0) tkSEMI A semicolon.
  143486. ** (1) tkWS Whitespace.
  143487. ** (2) tkOTHER Any other SQL token.
  143488. ** (3) tkEXPLAIN The "explain" keyword.
  143489. ** (4) tkCREATE The "create" keyword.
  143490. ** (5) tkTEMP The "temp" or "temporary" keyword.
  143491. ** (6) tkTRIGGER The "trigger" keyword.
  143492. ** (7) tkEND The "end" keyword.
  143493. **
  143494. ** Whitespace never causes a state transition and is always ignored.
  143495. ** This means that a SQL string of all whitespace is invalid.
  143496. **
  143497. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  143498. ** to recognize the end of a trigger can be omitted. All we have to do
  143499. ** is look for a semicolon that is not part of an string or comment.
  143500. */
  143501. SQLITE_API int sqlite3_complete(const char *zSql){
  143502. u8 state = 0; /* Current state, using numbers defined in header comment */
  143503. u8 token; /* Value of the next token */
  143504. #ifndef SQLITE_OMIT_TRIGGER
  143505. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  143506. ** statement. This is the normal case.
  143507. */
  143508. static const u8 trans[8][8] = {
  143509. /* Token: */
  143510. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  143511. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  143512. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  143513. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  143514. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  143515. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  143516. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  143517. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  143518. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  143519. };
  143520. #else
  143521. /* If triggers are not supported by this compile then the statement machine
  143522. ** used to detect the end of a statement is much simpler
  143523. */
  143524. static const u8 trans[3][3] = {
  143525. /* Token: */
  143526. /* State: ** SEMI WS OTHER */
  143527. /* 0 INVALID: */ { 1, 0, 2, },
  143528. /* 1 START: */ { 1, 1, 2, },
  143529. /* 2 NORMAL: */ { 1, 2, 2, },
  143530. };
  143531. #endif /* SQLITE_OMIT_TRIGGER */
  143532. #ifdef SQLITE_ENABLE_API_ARMOR
  143533. if( zSql==0 ){
  143534. (void)SQLITE_MISUSE_BKPT;
  143535. return 0;
  143536. }
  143537. #endif
  143538. while( *zSql ){
  143539. switch( *zSql ){
  143540. case ';': { /* A semicolon */
  143541. token = tkSEMI;
  143542. break;
  143543. }
  143544. case ' ':
  143545. case '\r':
  143546. case '\t':
  143547. case '\n':
  143548. case '\f': { /* White space is ignored */
  143549. token = tkWS;
  143550. break;
  143551. }
  143552. case '/': { /* C-style comments */
  143553. if( zSql[1]!='*' ){
  143554. token = tkOTHER;
  143555. break;
  143556. }
  143557. zSql += 2;
  143558. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  143559. if( zSql[0]==0 ) return 0;
  143560. zSql++;
  143561. token = tkWS;
  143562. break;
  143563. }
  143564. case '-': { /* SQL-style comments from "--" to end of line */
  143565. if( zSql[1]!='-' ){
  143566. token = tkOTHER;
  143567. break;
  143568. }
  143569. while( *zSql && *zSql!='\n' ){ zSql++; }
  143570. if( *zSql==0 ) return state==1;
  143571. token = tkWS;
  143572. break;
  143573. }
  143574. case '[': { /* Microsoft-style identifiers in [...] */
  143575. zSql++;
  143576. while( *zSql && *zSql!=']' ){ zSql++; }
  143577. if( *zSql==0 ) return 0;
  143578. token = tkOTHER;
  143579. break;
  143580. }
  143581. case '`': /* Grave-accent quoted symbols used by MySQL */
  143582. case '"': /* single- and double-quoted strings */
  143583. case '\'': {
  143584. int c = *zSql;
  143585. zSql++;
  143586. while( *zSql && *zSql!=c ){ zSql++; }
  143587. if( *zSql==0 ) return 0;
  143588. token = tkOTHER;
  143589. break;
  143590. }
  143591. default: {
  143592. #ifdef SQLITE_EBCDIC
  143593. unsigned char c;
  143594. #endif
  143595. if( IdChar((u8)*zSql) ){
  143596. /* Keywords and unquoted identifiers */
  143597. int nId;
  143598. for(nId=1; IdChar(zSql[nId]); nId++){}
  143599. #ifdef SQLITE_OMIT_TRIGGER
  143600. token = tkOTHER;
  143601. #else
  143602. switch( *zSql ){
  143603. case 'c': case 'C': {
  143604. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  143605. token = tkCREATE;
  143606. }else{
  143607. token = tkOTHER;
  143608. }
  143609. break;
  143610. }
  143611. case 't': case 'T': {
  143612. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  143613. token = tkTRIGGER;
  143614. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  143615. token = tkTEMP;
  143616. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  143617. token = tkTEMP;
  143618. }else{
  143619. token = tkOTHER;
  143620. }
  143621. break;
  143622. }
  143623. case 'e': case 'E': {
  143624. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  143625. token = tkEND;
  143626. }else
  143627. #ifndef SQLITE_OMIT_EXPLAIN
  143628. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  143629. token = tkEXPLAIN;
  143630. }else
  143631. #endif
  143632. {
  143633. token = tkOTHER;
  143634. }
  143635. break;
  143636. }
  143637. default: {
  143638. token = tkOTHER;
  143639. break;
  143640. }
  143641. }
  143642. #endif /* SQLITE_OMIT_TRIGGER */
  143643. zSql += nId-1;
  143644. }else{
  143645. /* Operators and special symbols */
  143646. token = tkOTHER;
  143647. }
  143648. break;
  143649. }
  143650. }
  143651. state = trans[state][token];
  143652. zSql++;
  143653. }
  143654. return state==1;
  143655. }
  143656. #ifndef SQLITE_OMIT_UTF16
  143657. /*
  143658. ** This routine is the same as the sqlite3_complete() routine described
  143659. ** above, except that the parameter is required to be UTF-16 encoded, not
  143660. ** UTF-8.
  143661. */
  143662. SQLITE_API int sqlite3_complete16(const void *zSql){
  143663. sqlite3_value *pVal;
  143664. char const *zSql8;
  143665. int rc;
  143666. #ifndef SQLITE_OMIT_AUTOINIT
  143667. rc = sqlite3_initialize();
  143668. if( rc ) return rc;
  143669. #endif
  143670. pVal = sqlite3ValueNew(0);
  143671. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  143672. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  143673. if( zSql8 ){
  143674. rc = sqlite3_complete(zSql8);
  143675. }else{
  143676. rc = SQLITE_NOMEM_BKPT;
  143677. }
  143678. sqlite3ValueFree(pVal);
  143679. return rc & 0xff;
  143680. }
  143681. #endif /* SQLITE_OMIT_UTF16 */
  143682. #endif /* SQLITE_OMIT_COMPLETE */
  143683. /************** End of complete.c ********************************************/
  143684. /************** Begin file main.c ********************************************/
  143685. /*
  143686. ** 2001 September 15
  143687. **
  143688. ** The author disclaims copyright to this source code. In place of
  143689. ** a legal notice, here is a blessing:
  143690. **
  143691. ** May you do good and not evil.
  143692. ** May you find forgiveness for yourself and forgive others.
  143693. ** May you share freely, never taking more than you give.
  143694. **
  143695. *************************************************************************
  143696. ** Main file for the SQLite library. The routines in this file
  143697. ** implement the programmer interface to the library. Routines in
  143698. ** other files are for internal use by SQLite and should not be
  143699. ** accessed by users of the library.
  143700. */
  143701. /* #include "sqliteInt.h" */
  143702. #ifdef SQLITE_ENABLE_FTS3
  143703. /************** Include fts3.h in the middle of main.c ***********************/
  143704. /************** Begin file fts3.h ********************************************/
  143705. /*
  143706. ** 2006 Oct 10
  143707. **
  143708. ** The author disclaims copyright to this source code. In place of
  143709. ** a legal notice, here is a blessing:
  143710. **
  143711. ** May you do good and not evil.
  143712. ** May you find forgiveness for yourself and forgive others.
  143713. ** May you share freely, never taking more than you give.
  143714. **
  143715. ******************************************************************************
  143716. **
  143717. ** This header file is used by programs that want to link against the
  143718. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  143719. */
  143720. /* #include "sqlite3.h" */
  143721. #if 0
  143722. extern "C" {
  143723. #endif /* __cplusplus */
  143724. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  143725. #if 0
  143726. } /* extern "C" */
  143727. #endif /* __cplusplus */
  143728. /************** End of fts3.h ************************************************/
  143729. /************** Continuing where we left off in main.c ***********************/
  143730. #endif
  143731. #ifdef SQLITE_ENABLE_RTREE
  143732. /************** Include rtree.h in the middle of main.c **********************/
  143733. /************** Begin file rtree.h *******************************************/
  143734. /*
  143735. ** 2008 May 26
  143736. **
  143737. ** The author disclaims copyright to this source code. In place of
  143738. ** a legal notice, here is a blessing:
  143739. **
  143740. ** May you do good and not evil.
  143741. ** May you find forgiveness for yourself and forgive others.
  143742. ** May you share freely, never taking more than you give.
  143743. **
  143744. ******************************************************************************
  143745. **
  143746. ** This header file is used by programs that want to link against the
  143747. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  143748. */
  143749. /* #include "sqlite3.h" */
  143750. #ifdef SQLITE_OMIT_VIRTUALTABLE
  143751. # undef SQLITE_ENABLE_RTREE
  143752. #endif
  143753. #if 0
  143754. extern "C" {
  143755. #endif /* __cplusplus */
  143756. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  143757. #if 0
  143758. } /* extern "C" */
  143759. #endif /* __cplusplus */
  143760. /************** End of rtree.h ***********************************************/
  143761. /************** Continuing where we left off in main.c ***********************/
  143762. #endif
  143763. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  143764. /************** Include sqliteicu.h in the middle of main.c ******************/
  143765. /************** Begin file sqliteicu.h ***************************************/
  143766. /*
  143767. ** 2008 May 26
  143768. **
  143769. ** The author disclaims copyright to this source code. In place of
  143770. ** a legal notice, here is a blessing:
  143771. **
  143772. ** May you do good and not evil.
  143773. ** May you find forgiveness for yourself and forgive others.
  143774. ** May you share freely, never taking more than you give.
  143775. **
  143776. ******************************************************************************
  143777. **
  143778. ** This header file is used by programs that want to link against the
  143779. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  143780. */
  143781. /* #include "sqlite3.h" */
  143782. #if 0
  143783. extern "C" {
  143784. #endif /* __cplusplus */
  143785. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  143786. #if 0
  143787. } /* extern "C" */
  143788. #endif /* __cplusplus */
  143789. /************** End of sqliteicu.h *******************************************/
  143790. /************** Continuing where we left off in main.c ***********************/
  143791. #endif
  143792. #ifdef SQLITE_ENABLE_JSON1
  143793. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  143794. #endif
  143795. #ifdef SQLITE_ENABLE_STMTVTAB
  143796. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
  143797. #endif
  143798. #ifdef SQLITE_ENABLE_FTS5
  143799. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  143800. #endif
  143801. #ifndef SQLITE_AMALGAMATION
  143802. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  143803. ** contains the text of SQLITE_VERSION macro.
  143804. */
  143805. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  143806. #endif
  143807. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  143808. ** a pointer to the to the sqlite3_version[] string constant.
  143809. */
  143810. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  143811. /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
  143812. ** pointer to a string constant whose value is the same as the
  143813. ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
  143814. ** an edited copy of the amalgamation, then the last four characters of
  143815. ** the hash might be different from SQLITE_SOURCE_ID.
  143816. */
  143817. /* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
  143818. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  143819. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  143820. */
  143821. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  143822. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  143823. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  143824. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  143825. */
  143826. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  143827. /*
  143828. ** When compiling the test fixture or with debugging enabled (on Win32),
  143829. ** this variable being set to non-zero will cause OSTRACE macros to emit
  143830. ** extra diagnostic information.
  143831. */
  143832. #ifdef SQLITE_HAVE_OS_TRACE
  143833. # ifndef SQLITE_DEBUG_OS_TRACE
  143834. # define SQLITE_DEBUG_OS_TRACE 0
  143835. # endif
  143836. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  143837. #endif
  143838. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  143839. /*
  143840. ** If the following function pointer is not NULL and if
  143841. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  143842. ** I/O active are written using this function. These messages
  143843. ** are intended for debugging activity only.
  143844. */
  143845. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  143846. #endif
  143847. /*
  143848. ** If the following global variable points to a string which is the
  143849. ** name of a directory, then that directory will be used to store
  143850. ** temporary files.
  143851. **
  143852. ** See also the "PRAGMA temp_store_directory" SQL command.
  143853. */
  143854. SQLITE_API char *sqlite3_temp_directory = 0;
  143855. /*
  143856. ** If the following global variable points to a string which is the
  143857. ** name of a directory, then that directory will be used to store
  143858. ** all database files specified with a relative pathname.
  143859. **
  143860. ** See also the "PRAGMA data_store_directory" SQL command.
  143861. */
  143862. SQLITE_API char *sqlite3_data_directory = 0;
  143863. /*
  143864. ** Initialize SQLite.
  143865. **
  143866. ** This routine must be called to initialize the memory allocation,
  143867. ** VFS, and mutex subsystems prior to doing any serious work with
  143868. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  143869. ** this routine will be called automatically by key routines such as
  143870. ** sqlite3_open().
  143871. **
  143872. ** This routine is a no-op except on its very first call for the process,
  143873. ** or for the first call after a call to sqlite3_shutdown.
  143874. **
  143875. ** The first thread to call this routine runs the initialization to
  143876. ** completion. If subsequent threads call this routine before the first
  143877. ** thread has finished the initialization process, then the subsequent
  143878. ** threads must block until the first thread finishes with the initialization.
  143879. **
  143880. ** The first thread might call this routine recursively. Recursive
  143881. ** calls to this routine should not block, of course. Otherwise the
  143882. ** initialization process would never complete.
  143883. **
  143884. ** Let X be the first thread to enter this routine. Let Y be some other
  143885. ** thread. Then while the initial invocation of this routine by X is
  143886. ** incomplete, it is required that:
  143887. **
  143888. ** * Calls to this routine from Y must block until the outer-most
  143889. ** call by X completes.
  143890. **
  143891. ** * Recursive calls to this routine from thread X return immediately
  143892. ** without blocking.
  143893. */
  143894. SQLITE_API int sqlite3_initialize(void){
  143895. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  143896. int rc; /* Result code */
  143897. #ifdef SQLITE_EXTRA_INIT
  143898. int bRunExtraInit = 0; /* Extra initialization needed */
  143899. #endif
  143900. #ifdef SQLITE_OMIT_WSD
  143901. rc = sqlite3_wsd_init(4096, 24);
  143902. if( rc!=SQLITE_OK ){
  143903. return rc;
  143904. }
  143905. #endif
  143906. /* If the following assert() fails on some obscure processor/compiler
  143907. ** combination, the work-around is to set the correct pointer
  143908. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  143909. assert( SQLITE_PTRSIZE==sizeof(char*) );
  143910. /* If SQLite is already completely initialized, then this call
  143911. ** to sqlite3_initialize() should be a no-op. But the initialization
  143912. ** must be complete. So isInit must not be set until the very end
  143913. ** of this routine.
  143914. */
  143915. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  143916. /* Make sure the mutex subsystem is initialized. If unable to
  143917. ** initialize the mutex subsystem, return early with the error.
  143918. ** If the system is so sick that we are unable to allocate a mutex,
  143919. ** there is not much SQLite is going to be able to do.
  143920. **
  143921. ** The mutex subsystem must take care of serializing its own
  143922. ** initialization.
  143923. */
  143924. rc = sqlite3MutexInit();
  143925. if( rc ) return rc;
  143926. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  143927. ** This operation is protected by the STATIC_MASTER mutex. Note that
  143928. ** MutexAlloc() is called for a static mutex prior to initializing the
  143929. ** malloc subsystem - this implies that the allocation of a static
  143930. ** mutex must not require support from the malloc subsystem.
  143931. */
  143932. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  143933. sqlite3_mutex_enter(pMaster);
  143934. sqlite3GlobalConfig.isMutexInit = 1;
  143935. if( !sqlite3GlobalConfig.isMallocInit ){
  143936. rc = sqlite3MallocInit();
  143937. }
  143938. if( rc==SQLITE_OK ){
  143939. sqlite3GlobalConfig.isMallocInit = 1;
  143940. if( !sqlite3GlobalConfig.pInitMutex ){
  143941. sqlite3GlobalConfig.pInitMutex =
  143942. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  143943. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  143944. rc = SQLITE_NOMEM_BKPT;
  143945. }
  143946. }
  143947. }
  143948. if( rc==SQLITE_OK ){
  143949. sqlite3GlobalConfig.nRefInitMutex++;
  143950. }
  143951. sqlite3_mutex_leave(pMaster);
  143952. /* If rc is not SQLITE_OK at this point, then either the malloc
  143953. ** subsystem could not be initialized or the system failed to allocate
  143954. ** the pInitMutex mutex. Return an error in either case. */
  143955. if( rc!=SQLITE_OK ){
  143956. return rc;
  143957. }
  143958. /* Do the rest of the initialization under the recursive mutex so
  143959. ** that we will be able to handle recursive calls into
  143960. ** sqlite3_initialize(). The recursive calls normally come through
  143961. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  143962. ** recursive calls might also be possible.
  143963. **
  143964. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  143965. ** to the xInit method, so the xInit method need not be threadsafe.
  143966. **
  143967. ** The following mutex is what serializes access to the appdef pcache xInit
  143968. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  143969. ** call to sqlite3PcacheInitialize().
  143970. */
  143971. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  143972. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  143973. sqlite3GlobalConfig.inProgress = 1;
  143974. #ifdef SQLITE_ENABLE_SQLLOG
  143975. {
  143976. extern void sqlite3_init_sqllog(void);
  143977. sqlite3_init_sqllog();
  143978. }
  143979. #endif
  143980. memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
  143981. sqlite3RegisterBuiltinFunctions();
  143982. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  143983. rc = sqlite3PcacheInitialize();
  143984. }
  143985. if( rc==SQLITE_OK ){
  143986. sqlite3GlobalConfig.isPCacheInit = 1;
  143987. rc = sqlite3OsInit();
  143988. }
  143989. #ifdef SQLITE_ENABLE_DESERIALIZE
  143990. if( rc==SQLITE_OK ){
  143991. rc = sqlite3MemdbInit();
  143992. }
  143993. #endif
  143994. if( rc==SQLITE_OK ){
  143995. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  143996. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  143997. sqlite3GlobalConfig.isInit = 1;
  143998. #ifdef SQLITE_EXTRA_INIT
  143999. bRunExtraInit = 1;
  144000. #endif
  144001. }
  144002. sqlite3GlobalConfig.inProgress = 0;
  144003. }
  144004. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  144005. /* Go back under the static mutex and clean up the recursive
  144006. ** mutex to prevent a resource leak.
  144007. */
  144008. sqlite3_mutex_enter(pMaster);
  144009. sqlite3GlobalConfig.nRefInitMutex--;
  144010. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  144011. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  144012. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  144013. sqlite3GlobalConfig.pInitMutex = 0;
  144014. }
  144015. sqlite3_mutex_leave(pMaster);
  144016. /* The following is just a sanity check to make sure SQLite has
  144017. ** been compiled correctly. It is important to run this code, but
  144018. ** we don't want to run it too often and soak up CPU cycles for no
  144019. ** reason. So we run it once during initialization.
  144020. */
  144021. #ifndef NDEBUG
  144022. #ifndef SQLITE_OMIT_FLOATING_POINT
  144023. /* This section of code's only "output" is via assert() statements. */
  144024. if( rc==SQLITE_OK ){
  144025. u64 x = (((u64)1)<<63)-1;
  144026. double y;
  144027. assert(sizeof(x)==8);
  144028. assert(sizeof(x)==sizeof(y));
  144029. memcpy(&y, &x, 8);
  144030. assert( sqlite3IsNaN(y) );
  144031. }
  144032. #endif
  144033. #endif
  144034. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  144035. ** compile-time option.
  144036. */
  144037. #ifdef SQLITE_EXTRA_INIT
  144038. if( bRunExtraInit ){
  144039. int SQLITE_EXTRA_INIT(const char*);
  144040. rc = SQLITE_EXTRA_INIT(0);
  144041. }
  144042. #endif
  144043. return rc;
  144044. }
  144045. /*
  144046. ** Undo the effects of sqlite3_initialize(). Must not be called while
  144047. ** there are outstanding database connections or memory allocations or
  144048. ** while any part of SQLite is otherwise in use in any thread. This
  144049. ** routine is not threadsafe. But it is safe to invoke this routine
  144050. ** on when SQLite is already shut down. If SQLite is already shut down
  144051. ** when this routine is invoked, then this routine is a harmless no-op.
  144052. */
  144053. SQLITE_API int sqlite3_shutdown(void){
  144054. #ifdef SQLITE_OMIT_WSD
  144055. int rc = sqlite3_wsd_init(4096, 24);
  144056. if( rc!=SQLITE_OK ){
  144057. return rc;
  144058. }
  144059. #endif
  144060. if( sqlite3GlobalConfig.isInit ){
  144061. #ifdef SQLITE_EXTRA_SHUTDOWN
  144062. void SQLITE_EXTRA_SHUTDOWN(void);
  144063. SQLITE_EXTRA_SHUTDOWN();
  144064. #endif
  144065. sqlite3_os_end();
  144066. sqlite3_reset_auto_extension();
  144067. sqlite3GlobalConfig.isInit = 0;
  144068. }
  144069. if( sqlite3GlobalConfig.isPCacheInit ){
  144070. sqlite3PcacheShutdown();
  144071. sqlite3GlobalConfig.isPCacheInit = 0;
  144072. }
  144073. if( sqlite3GlobalConfig.isMallocInit ){
  144074. sqlite3MallocEnd();
  144075. sqlite3GlobalConfig.isMallocInit = 0;
  144076. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  144077. /* The heap subsystem has now been shutdown and these values are supposed
  144078. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  144079. ** which would rely on that heap subsystem; therefore, make sure these
  144080. ** values cannot refer to heap memory that was just invalidated when the
  144081. ** heap subsystem was shutdown. This is only done if the current call to
  144082. ** this function resulted in the heap subsystem actually being shutdown.
  144083. */
  144084. sqlite3_data_directory = 0;
  144085. sqlite3_temp_directory = 0;
  144086. #endif
  144087. }
  144088. if( sqlite3GlobalConfig.isMutexInit ){
  144089. sqlite3MutexEnd();
  144090. sqlite3GlobalConfig.isMutexInit = 0;
  144091. }
  144092. return SQLITE_OK;
  144093. }
  144094. /*
  144095. ** This API allows applications to modify the global configuration of
  144096. ** the SQLite library at run-time.
  144097. **
  144098. ** This routine should only be called when there are no outstanding
  144099. ** database connections or memory allocations. This routine is not
  144100. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  144101. ** behavior.
  144102. */
  144103. SQLITE_API int sqlite3_config(int op, ...){
  144104. va_list ap;
  144105. int rc = SQLITE_OK;
  144106. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  144107. ** the SQLite library is in use. */
  144108. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  144109. va_start(ap, op);
  144110. switch( op ){
  144111. /* Mutex configuration options are only available in a threadsafe
  144112. ** compile.
  144113. */
  144114. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  144115. case SQLITE_CONFIG_SINGLETHREAD: {
  144116. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  144117. ** Single-thread. */
  144118. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  144119. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  144120. break;
  144121. }
  144122. #endif
  144123. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  144124. case SQLITE_CONFIG_MULTITHREAD: {
  144125. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  144126. ** Multi-thread. */
  144127. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  144128. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  144129. break;
  144130. }
  144131. #endif
  144132. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  144133. case SQLITE_CONFIG_SERIALIZED: {
  144134. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  144135. ** Serialized. */
  144136. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  144137. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  144138. break;
  144139. }
  144140. #endif
  144141. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  144142. case SQLITE_CONFIG_MUTEX: {
  144143. /* Specify an alternative mutex implementation */
  144144. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  144145. break;
  144146. }
  144147. #endif
  144148. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  144149. case SQLITE_CONFIG_GETMUTEX: {
  144150. /* Retrieve the current mutex implementation */
  144151. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  144152. break;
  144153. }
  144154. #endif
  144155. case SQLITE_CONFIG_MALLOC: {
  144156. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  144157. ** single argument which is a pointer to an instance of the
  144158. ** sqlite3_mem_methods structure. The argument specifies alternative
  144159. ** low-level memory allocation routines to be used in place of the memory
  144160. ** allocation routines built into SQLite. */
  144161. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  144162. break;
  144163. }
  144164. case SQLITE_CONFIG_GETMALLOC: {
  144165. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  144166. ** single argument which is a pointer to an instance of the
  144167. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  144168. ** filled with the currently defined memory allocation routines. */
  144169. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  144170. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  144171. break;
  144172. }
  144173. case SQLITE_CONFIG_MEMSTATUS: {
  144174. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  144175. ** single argument of type int, interpreted as a boolean, which enables
  144176. ** or disables the collection of memory allocation statistics. */
  144177. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  144178. break;
  144179. }
  144180. case SQLITE_CONFIG_SMALL_MALLOC: {
  144181. sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
  144182. break;
  144183. }
  144184. case SQLITE_CONFIG_PAGECACHE: {
  144185. /* EVIDENCE-OF: R-18761-36601 There are three arguments to
  144186. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
  144187. ** the size of each page cache line (sz), and the number of cache lines
  144188. ** (N). */
  144189. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  144190. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  144191. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  144192. break;
  144193. }
  144194. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  144195. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  144196. ** a single parameter which is a pointer to an integer and writes into
  144197. ** that integer the number of extra bytes per page required for each page
  144198. ** in SQLITE_CONFIG_PAGECACHE. */
  144199. *va_arg(ap, int*) =
  144200. sqlite3HeaderSizeBtree() +
  144201. sqlite3HeaderSizePcache() +
  144202. sqlite3HeaderSizePcache1();
  144203. break;
  144204. }
  144205. case SQLITE_CONFIG_PCACHE: {
  144206. /* no-op */
  144207. break;
  144208. }
  144209. case SQLITE_CONFIG_GETPCACHE: {
  144210. /* now an error */
  144211. rc = SQLITE_ERROR;
  144212. break;
  144213. }
  144214. case SQLITE_CONFIG_PCACHE2: {
  144215. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  144216. ** single argument which is a pointer to an sqlite3_pcache_methods2
  144217. ** object. This object specifies the interface to a custom page cache
  144218. ** implementation. */
  144219. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  144220. break;
  144221. }
  144222. case SQLITE_CONFIG_GETPCACHE2: {
  144223. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  144224. ** single argument which is a pointer to an sqlite3_pcache_methods2
  144225. ** object. SQLite copies of the current page cache implementation into
  144226. ** that object. */
  144227. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  144228. sqlite3PCacheSetDefault();
  144229. }
  144230. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  144231. break;
  144232. }
  144233. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  144234. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  144235. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  144236. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  144237. case SQLITE_CONFIG_HEAP: {
  144238. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  144239. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  144240. ** number of bytes in the memory buffer, and the minimum allocation size.
  144241. */
  144242. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  144243. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  144244. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  144245. if( sqlite3GlobalConfig.mnReq<1 ){
  144246. sqlite3GlobalConfig.mnReq = 1;
  144247. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  144248. /* cap min request size at 2^12 */
  144249. sqlite3GlobalConfig.mnReq = (1<<12);
  144250. }
  144251. if( sqlite3GlobalConfig.pHeap==0 ){
  144252. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  144253. ** is NULL, then SQLite reverts to using its default memory allocator
  144254. ** (the system malloc() implementation), undoing any prior invocation of
  144255. ** SQLITE_CONFIG_MALLOC.
  144256. **
  144257. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  144258. ** revert to its default implementation when sqlite3_initialize() is run
  144259. */
  144260. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  144261. }else{
  144262. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  144263. ** alternative memory allocator is engaged to handle all of SQLites
  144264. ** memory allocation needs. */
  144265. #ifdef SQLITE_ENABLE_MEMSYS3
  144266. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  144267. #endif
  144268. #ifdef SQLITE_ENABLE_MEMSYS5
  144269. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  144270. #endif
  144271. }
  144272. break;
  144273. }
  144274. #endif
  144275. case SQLITE_CONFIG_LOOKASIDE: {
  144276. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  144277. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  144278. break;
  144279. }
  144280. /* Record a pointer to the logger function and its first argument.
  144281. ** The default is NULL. Logging is disabled if the function pointer is
  144282. ** NULL.
  144283. */
  144284. case SQLITE_CONFIG_LOG: {
  144285. /* MSVC is picky about pulling func ptrs from va lists.
  144286. ** http://support.microsoft.com/kb/47961
  144287. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  144288. */
  144289. typedef void(*LOGFUNC_t)(void*,int,const char*);
  144290. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  144291. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  144292. break;
  144293. }
  144294. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  144295. ** can be changed at start-time using the
  144296. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  144297. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  144298. */
  144299. case SQLITE_CONFIG_URI: {
  144300. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  144301. ** argument of type int. If non-zero, then URI handling is globally
  144302. ** enabled. If the parameter is zero, then URI handling is globally
  144303. ** disabled. */
  144304. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  144305. break;
  144306. }
  144307. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  144308. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  144309. ** option takes a single integer argument which is interpreted as a
  144310. ** boolean in order to enable or disable the use of covering indices for
  144311. ** full table scans in the query optimizer. */
  144312. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  144313. break;
  144314. }
  144315. #ifdef SQLITE_ENABLE_SQLLOG
  144316. case SQLITE_CONFIG_SQLLOG: {
  144317. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  144318. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  144319. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  144320. break;
  144321. }
  144322. #endif
  144323. case SQLITE_CONFIG_MMAP_SIZE: {
  144324. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  144325. ** integer (sqlite3_int64) values that are the default mmap size limit
  144326. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  144327. ** mmap size limit. */
  144328. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  144329. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  144330. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  144331. ** negative, then that argument is changed to its compile-time default.
  144332. **
  144333. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  144334. ** silently truncated if necessary so that it does not exceed the
  144335. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  144336. ** compile-time option.
  144337. */
  144338. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  144339. mxMmap = SQLITE_MAX_MMAP_SIZE;
  144340. }
  144341. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  144342. if( szMmap>mxMmap) szMmap = mxMmap;
  144343. sqlite3GlobalConfig.mxMmap = mxMmap;
  144344. sqlite3GlobalConfig.szMmap = szMmap;
  144345. break;
  144346. }
  144347. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  144348. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  144349. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  144350. ** unsigned integer value that specifies the maximum size of the created
  144351. ** heap. */
  144352. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  144353. break;
  144354. }
  144355. #endif
  144356. case SQLITE_CONFIG_PMASZ: {
  144357. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  144358. break;
  144359. }
  144360. case SQLITE_CONFIG_STMTJRNL_SPILL: {
  144361. sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
  144362. break;
  144363. }
  144364. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  144365. case SQLITE_CONFIG_SORTERREF_SIZE: {
  144366. int iVal = va_arg(ap, int);
  144367. if( iVal<0 ){
  144368. iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
  144369. }
  144370. sqlite3GlobalConfig.szSorterRef = (u32)iVal;
  144371. break;
  144372. }
  144373. #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
  144374. default: {
  144375. rc = SQLITE_ERROR;
  144376. break;
  144377. }
  144378. }
  144379. va_end(ap);
  144380. return rc;
  144381. }
  144382. /*
  144383. ** Set up the lookaside buffers for a database connection.
  144384. ** Return SQLITE_OK on success.
  144385. ** If lookaside is already active, return SQLITE_BUSY.
  144386. **
  144387. ** The sz parameter is the number of bytes in each lookaside slot.
  144388. ** The cnt parameter is the number of slots. If pStart is NULL the
  144389. ** space for the lookaside memory is obtained from sqlite3_malloc().
  144390. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  144391. ** the lookaside memory.
  144392. */
  144393. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  144394. #ifndef SQLITE_OMIT_LOOKASIDE
  144395. void *pStart;
  144396. if( sqlite3LookasideUsed(db,0)>0 ){
  144397. return SQLITE_BUSY;
  144398. }
  144399. /* Free any existing lookaside buffer for this handle before
  144400. ** allocating a new one so we don't have to have space for
  144401. ** both at the same time.
  144402. */
  144403. if( db->lookaside.bMalloced ){
  144404. sqlite3_free(db->lookaside.pStart);
  144405. }
  144406. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  144407. ** than a pointer to be useful.
  144408. */
  144409. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  144410. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  144411. if( cnt<0 ) cnt = 0;
  144412. if( sz==0 || cnt==0 ){
  144413. sz = 0;
  144414. pStart = 0;
  144415. }else if( pBuf==0 ){
  144416. sqlite3BeginBenignMalloc();
  144417. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  144418. sqlite3EndBenignMalloc();
  144419. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  144420. }else{
  144421. pStart = pBuf;
  144422. }
  144423. db->lookaside.pStart = pStart;
  144424. db->lookaside.pInit = 0;
  144425. db->lookaside.pFree = 0;
  144426. db->lookaside.sz = (u16)sz;
  144427. if( pStart ){
  144428. int i;
  144429. LookasideSlot *p;
  144430. assert( sz > (int)sizeof(LookasideSlot*) );
  144431. db->lookaside.nSlot = cnt;
  144432. p = (LookasideSlot*)pStart;
  144433. for(i=cnt-1; i>=0; i--){
  144434. p->pNext = db->lookaside.pInit;
  144435. db->lookaside.pInit = p;
  144436. p = (LookasideSlot*)&((u8*)p)[sz];
  144437. }
  144438. db->lookaside.pEnd = p;
  144439. db->lookaside.bDisable = 0;
  144440. db->lookaside.bMalloced = pBuf==0 ?1:0;
  144441. }else{
  144442. db->lookaside.pStart = db;
  144443. db->lookaside.pEnd = db;
  144444. db->lookaside.bDisable = 1;
  144445. db->lookaside.bMalloced = 0;
  144446. db->lookaside.nSlot = 0;
  144447. }
  144448. #endif /* SQLITE_OMIT_LOOKASIDE */
  144449. return SQLITE_OK;
  144450. }
  144451. /*
  144452. ** Return the mutex associated with a database connection.
  144453. */
  144454. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  144455. #ifdef SQLITE_ENABLE_API_ARMOR
  144456. if( !sqlite3SafetyCheckOk(db) ){
  144457. (void)SQLITE_MISUSE_BKPT;
  144458. return 0;
  144459. }
  144460. #endif
  144461. return db->mutex;
  144462. }
  144463. /*
  144464. ** Free up as much memory as we can from the given database
  144465. ** connection.
  144466. */
  144467. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  144468. int i;
  144469. #ifdef SQLITE_ENABLE_API_ARMOR
  144470. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  144471. #endif
  144472. sqlite3_mutex_enter(db->mutex);
  144473. sqlite3BtreeEnterAll(db);
  144474. for(i=0; i<db->nDb; i++){
  144475. Btree *pBt = db->aDb[i].pBt;
  144476. if( pBt ){
  144477. Pager *pPager = sqlite3BtreePager(pBt);
  144478. sqlite3PagerShrink(pPager);
  144479. }
  144480. }
  144481. sqlite3BtreeLeaveAll(db);
  144482. sqlite3_mutex_leave(db->mutex);
  144483. return SQLITE_OK;
  144484. }
  144485. /*
  144486. ** Flush any dirty pages in the pager-cache for any attached database
  144487. ** to disk.
  144488. */
  144489. SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
  144490. int i;
  144491. int rc = SQLITE_OK;
  144492. int bSeenBusy = 0;
  144493. #ifdef SQLITE_ENABLE_API_ARMOR
  144494. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  144495. #endif
  144496. sqlite3_mutex_enter(db->mutex);
  144497. sqlite3BtreeEnterAll(db);
  144498. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  144499. Btree *pBt = db->aDb[i].pBt;
  144500. if( pBt && sqlite3BtreeIsInTrans(pBt) ){
  144501. Pager *pPager = sqlite3BtreePager(pBt);
  144502. rc = sqlite3PagerFlush(pPager);
  144503. if( rc==SQLITE_BUSY ){
  144504. bSeenBusy = 1;
  144505. rc = SQLITE_OK;
  144506. }
  144507. }
  144508. }
  144509. sqlite3BtreeLeaveAll(db);
  144510. sqlite3_mutex_leave(db->mutex);
  144511. return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
  144512. }
  144513. /*
  144514. ** Configuration settings for an individual database connection
  144515. */
  144516. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  144517. va_list ap;
  144518. int rc;
  144519. va_start(ap, op);
  144520. switch( op ){
  144521. case SQLITE_DBCONFIG_MAINDBNAME: {
  144522. /* IMP: R-06824-28531 */
  144523. /* IMP: R-36257-52125 */
  144524. db->aDb[0].zDbSName = va_arg(ap,char*);
  144525. rc = SQLITE_OK;
  144526. break;
  144527. }
  144528. case SQLITE_DBCONFIG_LOOKASIDE: {
  144529. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  144530. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  144531. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  144532. rc = setupLookaside(db, pBuf, sz, cnt);
  144533. break;
  144534. }
  144535. default: {
  144536. static const struct {
  144537. int op; /* The opcode */
  144538. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  144539. } aFlagOp[] = {
  144540. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  144541. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  144542. { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
  144543. { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
  144544. { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
  144545. { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
  144546. { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
  144547. { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase },
  144548. { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive },
  144549. };
  144550. unsigned int i;
  144551. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  144552. for(i=0; i<ArraySize(aFlagOp); i++){
  144553. if( aFlagOp[i].op==op ){
  144554. int onoff = va_arg(ap, int);
  144555. int *pRes = va_arg(ap, int*);
  144556. u32 oldFlags = db->flags;
  144557. if( onoff>0 ){
  144558. db->flags |= aFlagOp[i].mask;
  144559. }else if( onoff==0 ){
  144560. db->flags &= ~aFlagOp[i].mask;
  144561. }
  144562. if( oldFlags!=db->flags ){
  144563. sqlite3ExpirePreparedStatements(db, 0);
  144564. }
  144565. if( pRes ){
  144566. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  144567. }
  144568. rc = SQLITE_OK;
  144569. break;
  144570. }
  144571. }
  144572. break;
  144573. }
  144574. }
  144575. va_end(ap);
  144576. return rc;
  144577. }
  144578. /*
  144579. ** Return true if the buffer z[0..n-1] contains all spaces.
  144580. */
  144581. static int allSpaces(const char *z, int n){
  144582. while( n>0 && z[n-1]==' ' ){ n--; }
  144583. return n==0;
  144584. }
  144585. /*
  144586. ** This is the default collating function named "BINARY" which is always
  144587. ** available.
  144588. **
  144589. ** If the padFlag argument is not NULL then space padding at the end
  144590. ** of strings is ignored. This implements the RTRIM collation.
  144591. */
  144592. static int binCollFunc(
  144593. void *padFlag,
  144594. int nKey1, const void *pKey1,
  144595. int nKey2, const void *pKey2
  144596. ){
  144597. int rc, n;
  144598. n = nKey1<nKey2 ? nKey1 : nKey2;
  144599. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  144600. ** strings byte by byte using the memcmp() function from the standard C
  144601. ** library. */
  144602. assert( pKey1 && pKey2 );
  144603. rc = memcmp(pKey1, pKey2, n);
  144604. if( rc==0 ){
  144605. if( padFlag
  144606. && allSpaces(((char*)pKey1)+n, nKey1-n)
  144607. && allSpaces(((char*)pKey2)+n, nKey2-n)
  144608. ){
  144609. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  144610. ** spaces at the end of either string do not change the result. In other
  144611. ** words, strings will compare equal to one another as long as they
  144612. ** differ only in the number of spaces at the end.
  144613. */
  144614. }else{
  144615. rc = nKey1 - nKey2;
  144616. }
  144617. }
  144618. return rc;
  144619. }
  144620. /*
  144621. ** Return true if CollSeq is the default built-in BINARY.
  144622. */
  144623. SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq *p){
  144624. assert( p==0 || p->xCmp!=binCollFunc || p->pUser!=0
  144625. || strcmp(p->zName,"BINARY")==0 );
  144626. return p==0 || (p->xCmp==binCollFunc && p->pUser==0);
  144627. }
  144628. /*
  144629. ** Another built-in collating sequence: NOCASE.
  144630. **
  144631. ** This collating sequence is intended to be used for "case independent
  144632. ** comparison". SQLite's knowledge of upper and lower case equivalents
  144633. ** extends only to the 26 characters used in the English language.
  144634. **
  144635. ** At the moment there is only a UTF-8 implementation.
  144636. */
  144637. static int nocaseCollatingFunc(
  144638. void *NotUsed,
  144639. int nKey1, const void *pKey1,
  144640. int nKey2, const void *pKey2
  144641. ){
  144642. int r = sqlite3StrNICmp(
  144643. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  144644. UNUSED_PARAMETER(NotUsed);
  144645. if( 0==r ){
  144646. r = nKey1-nKey2;
  144647. }
  144648. return r;
  144649. }
  144650. /*
  144651. ** Return the ROWID of the most recent insert
  144652. */
  144653. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  144654. #ifdef SQLITE_ENABLE_API_ARMOR
  144655. if( !sqlite3SafetyCheckOk(db) ){
  144656. (void)SQLITE_MISUSE_BKPT;
  144657. return 0;
  144658. }
  144659. #endif
  144660. return db->lastRowid;
  144661. }
  144662. /*
  144663. ** Set the value returned by the sqlite3_last_insert_rowid() API function.
  144664. */
  144665. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
  144666. #ifdef SQLITE_ENABLE_API_ARMOR
  144667. if( !sqlite3SafetyCheckOk(db) ){
  144668. (void)SQLITE_MISUSE_BKPT;
  144669. return;
  144670. }
  144671. #endif
  144672. sqlite3_mutex_enter(db->mutex);
  144673. db->lastRowid = iRowid;
  144674. sqlite3_mutex_leave(db->mutex);
  144675. }
  144676. /*
  144677. ** Return the number of changes in the most recent call to sqlite3_exec().
  144678. */
  144679. SQLITE_API int sqlite3_changes(sqlite3 *db){
  144680. #ifdef SQLITE_ENABLE_API_ARMOR
  144681. if( !sqlite3SafetyCheckOk(db) ){
  144682. (void)SQLITE_MISUSE_BKPT;
  144683. return 0;
  144684. }
  144685. #endif
  144686. return db->nChange;
  144687. }
  144688. /*
  144689. ** Return the number of changes since the database handle was opened.
  144690. */
  144691. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  144692. #ifdef SQLITE_ENABLE_API_ARMOR
  144693. if( !sqlite3SafetyCheckOk(db) ){
  144694. (void)SQLITE_MISUSE_BKPT;
  144695. return 0;
  144696. }
  144697. #endif
  144698. return db->nTotalChange;
  144699. }
  144700. /*
  144701. ** Close all open savepoints. This function only manipulates fields of the
  144702. ** database handle object, it does not close any savepoints that may be open
  144703. ** at the b-tree/pager level.
  144704. */
  144705. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  144706. while( db->pSavepoint ){
  144707. Savepoint *pTmp = db->pSavepoint;
  144708. db->pSavepoint = pTmp->pNext;
  144709. sqlite3DbFree(db, pTmp);
  144710. }
  144711. db->nSavepoint = 0;
  144712. db->nStatement = 0;
  144713. db->isTransactionSavepoint = 0;
  144714. }
  144715. /*
  144716. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  144717. ** if this is not the last copy of the function, do not invoke it. Multiple
  144718. ** copies of a single function are created when create_function() is called
  144719. ** with SQLITE_ANY as the encoding.
  144720. */
  144721. static void functionDestroy(sqlite3 *db, FuncDef *p){
  144722. FuncDestructor *pDestructor = p->u.pDestructor;
  144723. if( pDestructor ){
  144724. pDestructor->nRef--;
  144725. if( pDestructor->nRef==0 ){
  144726. pDestructor->xDestroy(pDestructor->pUserData);
  144727. sqlite3DbFree(db, pDestructor);
  144728. }
  144729. }
  144730. }
  144731. /*
  144732. ** Disconnect all sqlite3_vtab objects that belong to database connection
  144733. ** db. This is called when db is being closed.
  144734. */
  144735. static void disconnectAllVtab(sqlite3 *db){
  144736. #ifndef SQLITE_OMIT_VIRTUALTABLE
  144737. int i;
  144738. HashElem *p;
  144739. sqlite3BtreeEnterAll(db);
  144740. for(i=0; i<db->nDb; i++){
  144741. Schema *pSchema = db->aDb[i].pSchema;
  144742. if( pSchema ){
  144743. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  144744. Table *pTab = (Table *)sqliteHashData(p);
  144745. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  144746. }
  144747. }
  144748. }
  144749. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  144750. Module *pMod = (Module *)sqliteHashData(p);
  144751. if( pMod->pEpoTab ){
  144752. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  144753. }
  144754. }
  144755. sqlite3VtabUnlockList(db);
  144756. sqlite3BtreeLeaveAll(db);
  144757. #else
  144758. UNUSED_PARAMETER(db);
  144759. #endif
  144760. }
  144761. /*
  144762. ** Return TRUE if database connection db has unfinalized prepared
  144763. ** statements or unfinished sqlite3_backup objects.
  144764. */
  144765. static int connectionIsBusy(sqlite3 *db){
  144766. int j;
  144767. assert( sqlite3_mutex_held(db->mutex) );
  144768. if( db->pVdbe ) return 1;
  144769. for(j=0; j<db->nDb; j++){
  144770. Btree *pBt = db->aDb[j].pBt;
  144771. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  144772. }
  144773. return 0;
  144774. }
  144775. /*
  144776. ** Close an existing SQLite database
  144777. */
  144778. static int sqlite3Close(sqlite3 *db, int forceZombie){
  144779. if( !db ){
  144780. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  144781. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  144782. return SQLITE_OK;
  144783. }
  144784. if( !sqlite3SafetyCheckSickOrOk(db) ){
  144785. return SQLITE_MISUSE_BKPT;
  144786. }
  144787. sqlite3_mutex_enter(db->mutex);
  144788. if( db->mTrace & SQLITE_TRACE_CLOSE ){
  144789. db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
  144790. }
  144791. /* Force xDisconnect calls on all virtual tables */
  144792. disconnectAllVtab(db);
  144793. /* If a transaction is open, the disconnectAllVtab() call above
  144794. ** will not have called the xDisconnect() method on any virtual
  144795. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  144796. ** call will do so. We need to do this before the check for active
  144797. ** SQL statements below, as the v-table implementation may be storing
  144798. ** some prepared statements internally.
  144799. */
  144800. sqlite3VtabRollback(db);
  144801. /* Legacy behavior (sqlite3_close() behavior) is to return
  144802. ** SQLITE_BUSY if the connection can not be closed immediately.
  144803. */
  144804. if( !forceZombie && connectionIsBusy(db) ){
  144805. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  144806. "statements or unfinished backups");
  144807. sqlite3_mutex_leave(db->mutex);
  144808. return SQLITE_BUSY;
  144809. }
  144810. #ifdef SQLITE_ENABLE_SQLLOG
  144811. if( sqlite3GlobalConfig.xSqllog ){
  144812. /* Closing the handle. Fourth parameter is passed the value 2. */
  144813. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  144814. }
  144815. #endif
  144816. /* Convert the connection into a zombie and then close it.
  144817. */
  144818. db->magic = SQLITE_MAGIC_ZOMBIE;
  144819. sqlite3LeaveMutexAndCloseZombie(db);
  144820. return SQLITE_OK;
  144821. }
  144822. /*
  144823. ** Two variations on the public interface for closing a database
  144824. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  144825. ** leaves the connection option if there are unfinalized prepared
  144826. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  144827. ** version forces the connection to become a zombie if there are
  144828. ** unclosed resources, and arranges for deallocation when the last
  144829. ** prepare statement or sqlite3_backup closes.
  144830. */
  144831. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  144832. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  144833. /*
  144834. ** Close the mutex on database connection db.
  144835. **
  144836. ** Furthermore, if database connection db is a zombie (meaning that there
  144837. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  144838. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  144839. ** finished, then free all resources.
  144840. */
  144841. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  144842. HashElem *i; /* Hash table iterator */
  144843. int j;
  144844. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  144845. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  144846. ** then just leave the mutex and return.
  144847. */
  144848. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  144849. sqlite3_mutex_leave(db->mutex);
  144850. return;
  144851. }
  144852. /* If we reach this point, it means that the database connection has
  144853. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  144854. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  144855. ** go ahead and free all resources.
  144856. */
  144857. /* If a transaction is open, roll it back. This also ensures that if
  144858. ** any database schemas have been modified by an uncommitted transaction
  144859. ** they are reset. And that the required b-tree mutex is held to make
  144860. ** the pager rollback and schema reset an atomic operation. */
  144861. sqlite3RollbackAll(db, SQLITE_OK);
  144862. /* Free any outstanding Savepoint structures. */
  144863. sqlite3CloseSavepoints(db);
  144864. /* Close all database connections */
  144865. for(j=0; j<db->nDb; j++){
  144866. struct Db *pDb = &db->aDb[j];
  144867. if( pDb->pBt ){
  144868. sqlite3BtreeClose(pDb->pBt);
  144869. pDb->pBt = 0;
  144870. if( j!=1 ){
  144871. pDb->pSchema = 0;
  144872. }
  144873. }
  144874. }
  144875. /* Clear the TEMP schema separately and last */
  144876. if( db->aDb[1].pSchema ){
  144877. sqlite3SchemaClear(db->aDb[1].pSchema);
  144878. }
  144879. sqlite3VtabUnlockList(db);
  144880. /* Free up the array of auxiliary databases */
  144881. sqlite3CollapseDatabaseArray(db);
  144882. assert( db->nDb<=2 );
  144883. assert( db->aDb==db->aDbStatic );
  144884. /* Tell the code in notify.c that the connection no longer holds any
  144885. ** locks and does not require any further unlock-notify callbacks.
  144886. */
  144887. sqlite3ConnectionClosed(db);
  144888. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  144889. FuncDef *pNext, *p;
  144890. p = sqliteHashData(i);
  144891. do{
  144892. functionDestroy(db, p);
  144893. pNext = p->pNext;
  144894. sqlite3DbFree(db, p);
  144895. p = pNext;
  144896. }while( p );
  144897. }
  144898. sqlite3HashClear(&db->aFunc);
  144899. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  144900. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  144901. /* Invoke any destructors registered for collation sequence user data. */
  144902. for(j=0; j<3; j++){
  144903. if( pColl[j].xDel ){
  144904. pColl[j].xDel(pColl[j].pUser);
  144905. }
  144906. }
  144907. sqlite3DbFree(db, pColl);
  144908. }
  144909. sqlite3HashClear(&db->aCollSeq);
  144910. #ifndef SQLITE_OMIT_VIRTUALTABLE
  144911. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  144912. Module *pMod = (Module *)sqliteHashData(i);
  144913. if( pMod->xDestroy ){
  144914. pMod->xDestroy(pMod->pAux);
  144915. }
  144916. sqlite3VtabEponymousTableClear(db, pMod);
  144917. sqlite3DbFree(db, pMod);
  144918. }
  144919. sqlite3HashClear(&db->aModule);
  144920. #endif
  144921. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  144922. sqlite3ValueFree(db->pErr);
  144923. sqlite3CloseExtensions(db);
  144924. #if SQLITE_USER_AUTHENTICATION
  144925. sqlite3_free(db->auth.zAuthUser);
  144926. sqlite3_free(db->auth.zAuthPW);
  144927. #endif
  144928. db->magic = SQLITE_MAGIC_ERROR;
  144929. /* The temp-database schema is allocated differently from the other schema
  144930. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  144931. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  144932. ** the same sqliteMalloc() as the one that allocates the database
  144933. ** structure?
  144934. */
  144935. sqlite3DbFree(db, db->aDb[1].pSchema);
  144936. sqlite3_mutex_leave(db->mutex);
  144937. db->magic = SQLITE_MAGIC_CLOSED;
  144938. sqlite3_mutex_free(db->mutex);
  144939. assert( sqlite3LookasideUsed(db,0)==0 );
  144940. if( db->lookaside.bMalloced ){
  144941. sqlite3_free(db->lookaside.pStart);
  144942. }
  144943. sqlite3_free(db);
  144944. }
  144945. /*
  144946. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  144947. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  144948. ** breaker") and made to return tripCode if there are any further
  144949. ** attempts to use that cursor. Read cursors remain open and valid
  144950. ** but are "saved" in case the table pages are moved around.
  144951. */
  144952. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  144953. int i;
  144954. int inTrans = 0;
  144955. int schemaChange;
  144956. assert( sqlite3_mutex_held(db->mutex) );
  144957. sqlite3BeginBenignMalloc();
  144958. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  144959. ** This is important in case the transaction being rolled back has
  144960. ** modified the database schema. If the b-tree mutexes are not taken
  144961. ** here, then another shared-cache connection might sneak in between
  144962. ** the database rollback and schema reset, which can cause false
  144963. ** corruption reports in some cases. */
  144964. sqlite3BtreeEnterAll(db);
  144965. schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
  144966. for(i=0; i<db->nDb; i++){
  144967. Btree *p = db->aDb[i].pBt;
  144968. if( p ){
  144969. if( sqlite3BtreeIsInTrans(p) ){
  144970. inTrans = 1;
  144971. }
  144972. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  144973. }
  144974. }
  144975. sqlite3VtabRollback(db);
  144976. sqlite3EndBenignMalloc();
  144977. if( schemaChange ){
  144978. sqlite3ExpirePreparedStatements(db, 0);
  144979. sqlite3ResetAllSchemasOfConnection(db);
  144980. }
  144981. sqlite3BtreeLeaveAll(db);
  144982. /* Any deferred constraint violations have now been resolved. */
  144983. db->nDeferredCons = 0;
  144984. db->nDeferredImmCons = 0;
  144985. db->flags &= ~SQLITE_DeferFKs;
  144986. /* If one has been configured, invoke the rollback-hook callback */
  144987. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  144988. db->xRollbackCallback(db->pRollbackArg);
  144989. }
  144990. }
  144991. /*
  144992. ** Return a static string containing the name corresponding to the error code
  144993. ** specified in the argument.
  144994. */
  144995. #if defined(SQLITE_NEED_ERR_NAME)
  144996. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  144997. const char *zName = 0;
  144998. int i, origRc = rc;
  144999. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  145000. switch( rc ){
  145001. case SQLITE_OK: zName = "SQLITE_OK"; break;
  145002. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  145003. case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break;
  145004. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  145005. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  145006. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  145007. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  145008. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  145009. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  145010. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  145011. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  145012. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  145013. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  145014. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  145015. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  145016. case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
  145017. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  145018. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  145019. case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
  145020. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  145021. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  145022. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  145023. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  145024. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  145025. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  145026. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  145027. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  145028. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  145029. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  145030. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  145031. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  145032. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  145033. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  145034. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  145035. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  145036. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  145037. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  145038. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  145039. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  145040. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  145041. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  145042. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  145043. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  145044. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  145045. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  145046. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  145047. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  145048. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  145049. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  145050. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  145051. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  145052. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  145053. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  145054. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  145055. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  145056. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  145057. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  145058. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  145059. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  145060. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  145061. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  145062. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  145063. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  145064. case SQLITE_CONSTRAINT_FOREIGNKEY:
  145065. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  145066. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  145067. case SQLITE_CONSTRAINT_PRIMARYKEY:
  145068. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  145069. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  145070. case SQLITE_CONSTRAINT_COMMITHOOK:
  145071. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  145072. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  145073. case SQLITE_CONSTRAINT_FUNCTION:
  145074. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  145075. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  145076. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  145077. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  145078. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  145079. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  145080. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  145081. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  145082. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  145083. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  145084. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  145085. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  145086. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  145087. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  145088. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  145089. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  145090. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  145091. }
  145092. }
  145093. if( zName==0 ){
  145094. static char zBuf[50];
  145095. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  145096. zName = zBuf;
  145097. }
  145098. return zName;
  145099. }
  145100. #endif
  145101. /*
  145102. ** Return a static string that describes the kind of error specified in the
  145103. ** argument.
  145104. */
  145105. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  145106. static const char* const aMsg[] = {
  145107. /* SQLITE_OK */ "not an error",
  145108. /* SQLITE_ERROR */ "SQL logic error",
  145109. /* SQLITE_INTERNAL */ 0,
  145110. /* SQLITE_PERM */ "access permission denied",
  145111. /* SQLITE_ABORT */ "query aborted",
  145112. /* SQLITE_BUSY */ "database is locked",
  145113. /* SQLITE_LOCKED */ "database table is locked",
  145114. /* SQLITE_NOMEM */ "out of memory",
  145115. /* SQLITE_READONLY */ "attempt to write a readonly database",
  145116. /* SQLITE_INTERRUPT */ "interrupted",
  145117. /* SQLITE_IOERR */ "disk I/O error",
  145118. /* SQLITE_CORRUPT */ "database disk image is malformed",
  145119. /* SQLITE_NOTFOUND */ "unknown operation",
  145120. /* SQLITE_FULL */ "database or disk is full",
  145121. /* SQLITE_CANTOPEN */ "unable to open database file",
  145122. /* SQLITE_PROTOCOL */ "locking protocol",
  145123. /* SQLITE_EMPTY */ 0,
  145124. /* SQLITE_SCHEMA */ "database schema has changed",
  145125. /* SQLITE_TOOBIG */ "string or blob too big",
  145126. /* SQLITE_CONSTRAINT */ "constraint failed",
  145127. /* SQLITE_MISMATCH */ "datatype mismatch",
  145128. /* SQLITE_MISUSE */ "bad parameter or other API misuse",
  145129. #ifdef SQLITE_DISABLE_LFS
  145130. /* SQLITE_NOLFS */ "large file support is disabled",
  145131. #else
  145132. /* SQLITE_NOLFS */ 0,
  145133. #endif
  145134. /* SQLITE_AUTH */ "authorization denied",
  145135. /* SQLITE_FORMAT */ 0,
  145136. /* SQLITE_RANGE */ "column index out of range",
  145137. /* SQLITE_NOTADB */ "file is not a database",
  145138. /* SQLITE_NOTICE */ "notification message",
  145139. /* SQLITE_WARNING */ "warning message",
  145140. };
  145141. const char *zErr = "unknown error";
  145142. switch( rc ){
  145143. case SQLITE_ABORT_ROLLBACK: {
  145144. zErr = "abort due to ROLLBACK";
  145145. break;
  145146. }
  145147. case SQLITE_ROW: {
  145148. zErr = "another row available";
  145149. break;
  145150. }
  145151. case SQLITE_DONE: {
  145152. zErr = "no more rows available";
  145153. break;
  145154. }
  145155. default: {
  145156. rc &= 0xff;
  145157. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  145158. zErr = aMsg[rc];
  145159. }
  145160. break;
  145161. }
  145162. }
  145163. return zErr;
  145164. }
  145165. /*
  145166. ** This routine implements a busy callback that sleeps and tries
  145167. ** again until a timeout value is reached. The timeout value is
  145168. ** an integer number of milliseconds passed in as the first
  145169. ** argument.
  145170. **
  145171. ** Return non-zero to retry the lock. Return zero to stop trying
  145172. ** and cause SQLite to return SQLITE_BUSY.
  145173. */
  145174. static int sqliteDefaultBusyCallback(
  145175. void *ptr, /* Database connection */
  145176. int count, /* Number of times table has been busy */
  145177. sqlite3_file *pFile /* The file on which the lock occurred */
  145178. ){
  145179. #if SQLITE_OS_WIN || HAVE_USLEEP
  145180. /* This case is for systems that have support for sleeping for fractions of
  145181. ** a second. Examples: All windows systems, unix systems with usleep() */
  145182. static const u8 delays[] =
  145183. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  145184. static const u8 totals[] =
  145185. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  145186. # define NDELAY ArraySize(delays)
  145187. sqlite3 *db = (sqlite3 *)ptr;
  145188. int tmout = db->busyTimeout;
  145189. int delay, prior;
  145190. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  145191. if( sqlite3OsFileControl(pFile,SQLITE_FCNTL_LOCK_TIMEOUT,&tmout)==SQLITE_OK ){
  145192. if( count ){
  145193. tmout = 0;
  145194. sqlite3OsFileControl(pFile, SQLITE_FCNTL_LOCK_TIMEOUT, &tmout);
  145195. return 0;
  145196. }else{
  145197. return 1;
  145198. }
  145199. }
  145200. #else
  145201. UNUSED_PARAMETER(pFile);
  145202. #endif
  145203. assert( count>=0 );
  145204. if( count < NDELAY ){
  145205. delay = delays[count];
  145206. prior = totals[count];
  145207. }else{
  145208. delay = delays[NDELAY-1];
  145209. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  145210. }
  145211. if( prior + delay > tmout ){
  145212. delay = tmout - prior;
  145213. if( delay<=0 ) return 0;
  145214. }
  145215. sqlite3OsSleep(db->pVfs, delay*1000);
  145216. return 1;
  145217. #else
  145218. /* This case for unix systems that lack usleep() support. Sleeping
  145219. ** must be done in increments of whole seconds */
  145220. sqlite3 *db = (sqlite3 *)ptr;
  145221. int tmout = ((sqlite3 *)ptr)->busyTimeout;
  145222. UNUSED_PARAMETER(pFile);
  145223. if( (count+1)*1000 > tmout ){
  145224. return 0;
  145225. }
  145226. sqlite3OsSleep(db->pVfs, 1000000);
  145227. return 1;
  145228. #endif
  145229. }
  145230. /*
  145231. ** Invoke the given busy handler.
  145232. **
  145233. ** This routine is called when an operation failed to acquire a
  145234. ** lock on VFS file pFile.
  145235. **
  145236. ** If this routine returns non-zero, the lock is retried. If it
  145237. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  145238. */
  145239. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p, sqlite3_file *pFile){
  145240. int rc;
  145241. if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
  145242. if( p->bExtraFileArg ){
  145243. /* Add an extra parameter with the pFile pointer to the end of the
  145244. ** callback argument list */
  145245. int (*xTra)(void*,int,sqlite3_file*);
  145246. xTra = (int(*)(void*,int,sqlite3_file*))p->xBusyHandler;
  145247. rc = xTra(p->pBusyArg, p->nBusy, pFile);
  145248. }else{
  145249. /* Legacy style busy handler callback */
  145250. rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
  145251. }
  145252. if( rc==0 ){
  145253. p->nBusy = -1;
  145254. }else{
  145255. p->nBusy++;
  145256. }
  145257. return rc;
  145258. }
  145259. /*
  145260. ** This routine sets the busy callback for an Sqlite database to the
  145261. ** given callback function with the given argument.
  145262. */
  145263. SQLITE_API int sqlite3_busy_handler(
  145264. sqlite3 *db,
  145265. int (*xBusy)(void*,int),
  145266. void *pArg
  145267. ){
  145268. #ifdef SQLITE_ENABLE_API_ARMOR
  145269. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  145270. #endif
  145271. sqlite3_mutex_enter(db->mutex);
  145272. db->busyHandler.xBusyHandler = xBusy;
  145273. db->busyHandler.pBusyArg = pArg;
  145274. db->busyHandler.nBusy = 0;
  145275. db->busyHandler.bExtraFileArg = 0;
  145276. db->busyTimeout = 0;
  145277. sqlite3_mutex_leave(db->mutex);
  145278. return SQLITE_OK;
  145279. }
  145280. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  145281. /*
  145282. ** This routine sets the progress callback for an Sqlite database to the
  145283. ** given callback function with the given argument. The progress callback will
  145284. ** be invoked every nOps opcodes.
  145285. */
  145286. SQLITE_API void sqlite3_progress_handler(
  145287. sqlite3 *db,
  145288. int nOps,
  145289. int (*xProgress)(void*),
  145290. void *pArg
  145291. ){
  145292. #ifdef SQLITE_ENABLE_API_ARMOR
  145293. if( !sqlite3SafetyCheckOk(db) ){
  145294. (void)SQLITE_MISUSE_BKPT;
  145295. return;
  145296. }
  145297. #endif
  145298. sqlite3_mutex_enter(db->mutex);
  145299. if( nOps>0 ){
  145300. db->xProgress = xProgress;
  145301. db->nProgressOps = (unsigned)nOps;
  145302. db->pProgressArg = pArg;
  145303. }else{
  145304. db->xProgress = 0;
  145305. db->nProgressOps = 0;
  145306. db->pProgressArg = 0;
  145307. }
  145308. sqlite3_mutex_leave(db->mutex);
  145309. }
  145310. #endif
  145311. /*
  145312. ** This routine installs a default busy handler that waits for the
  145313. ** specified number of milliseconds before returning 0.
  145314. */
  145315. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  145316. #ifdef SQLITE_ENABLE_API_ARMOR
  145317. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  145318. #endif
  145319. if( ms>0 ){
  145320. sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
  145321. (void*)db);
  145322. db->busyTimeout = ms;
  145323. db->busyHandler.bExtraFileArg = 1;
  145324. }else{
  145325. sqlite3_busy_handler(db, 0, 0);
  145326. }
  145327. return SQLITE_OK;
  145328. }
  145329. /*
  145330. ** Cause any pending operation to stop at its earliest opportunity.
  145331. */
  145332. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  145333. #ifdef SQLITE_ENABLE_API_ARMOR
  145334. if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
  145335. (void)SQLITE_MISUSE_BKPT;
  145336. return;
  145337. }
  145338. #endif
  145339. db->u1.isInterrupted = 1;
  145340. }
  145341. /*
  145342. ** This function is exactly the same as sqlite3_create_function(), except
  145343. ** that it is designed to be called by internal code. The difference is
  145344. ** that if a malloc() fails in sqlite3_create_function(), an error code
  145345. ** is returned and the mallocFailed flag cleared.
  145346. */
  145347. SQLITE_PRIVATE int sqlite3CreateFunc(
  145348. sqlite3 *db,
  145349. const char *zFunctionName,
  145350. int nArg,
  145351. int enc,
  145352. void *pUserData,
  145353. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  145354. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  145355. void (*xFinal)(sqlite3_context*),
  145356. void (*xValue)(sqlite3_context*),
  145357. void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
  145358. FuncDestructor *pDestructor
  145359. ){
  145360. FuncDef *p;
  145361. int nName;
  145362. int extraFlags;
  145363. assert( sqlite3_mutex_held(db->mutex) );
  145364. assert( xValue==0 || xSFunc==0 );
  145365. if( zFunctionName==0 /* Must have a valid name */
  145366. || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */
  145367. || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */
  145368. || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */
  145369. || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
  145370. || (255<(nName = sqlite3Strlen30( zFunctionName)))
  145371. ){
  145372. return SQLITE_MISUSE_BKPT;
  145373. }
  145374. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  145375. extraFlags = enc & SQLITE_DETERMINISTIC;
  145376. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  145377. #ifndef SQLITE_OMIT_UTF16
  145378. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  145379. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  145380. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  145381. **
  145382. ** If SQLITE_ANY is specified, add three versions of the function
  145383. ** to the hash table.
  145384. */
  145385. if( enc==SQLITE_UTF16 ){
  145386. enc = SQLITE_UTF16NATIVE;
  145387. }else if( enc==SQLITE_ANY ){
  145388. int rc;
  145389. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  145390. pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
  145391. if( rc==SQLITE_OK ){
  145392. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  145393. pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
  145394. }
  145395. if( rc!=SQLITE_OK ){
  145396. return rc;
  145397. }
  145398. enc = SQLITE_UTF16BE;
  145399. }
  145400. #else
  145401. enc = SQLITE_UTF8;
  145402. #endif
  145403. /* Check if an existing function is being overridden or deleted. If so,
  145404. ** and there are active VMs, then return SQLITE_BUSY. If a function
  145405. ** is being overridden/deleted but there are no active VMs, allow the
  145406. ** operation to continue but invalidate all precompiled statements.
  145407. */
  145408. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
  145409. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
  145410. if( db->nVdbeActive ){
  145411. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  145412. "unable to delete/modify user-function due to active statements");
  145413. assert( !db->mallocFailed );
  145414. return SQLITE_BUSY;
  145415. }else{
  145416. sqlite3ExpirePreparedStatements(db, 0);
  145417. }
  145418. }
  145419. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
  145420. assert(p || db->mallocFailed);
  145421. if( !p ){
  145422. return SQLITE_NOMEM_BKPT;
  145423. }
  145424. /* If an older version of the function with a configured destructor is
  145425. ** being replaced invoke the destructor function here. */
  145426. functionDestroy(db, p);
  145427. if( pDestructor ){
  145428. pDestructor->nRef++;
  145429. }
  145430. p->u.pDestructor = pDestructor;
  145431. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  145432. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  145433. p->xSFunc = xSFunc ? xSFunc : xStep;
  145434. p->xFinalize = xFinal;
  145435. p->xValue = xValue;
  145436. p->xInverse = xInverse;
  145437. p->pUserData = pUserData;
  145438. p->nArg = (u16)nArg;
  145439. return SQLITE_OK;
  145440. }
  145441. /*
  145442. ** Worker function used by utf-8 APIs that create new functions:
  145443. **
  145444. ** sqlite3_create_function()
  145445. ** sqlite3_create_function_v2()
  145446. ** sqlite3_create_window_function()
  145447. */
  145448. static int createFunctionApi(
  145449. sqlite3 *db,
  145450. const char *zFunc,
  145451. int nArg,
  145452. int enc,
  145453. void *p,
  145454. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  145455. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  145456. void (*xFinal)(sqlite3_context*),
  145457. void (*xValue)(sqlite3_context*),
  145458. void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
  145459. void(*xDestroy)(void*)
  145460. ){
  145461. int rc = SQLITE_ERROR;
  145462. FuncDestructor *pArg = 0;
  145463. #ifdef SQLITE_ENABLE_API_ARMOR
  145464. if( !sqlite3SafetyCheckOk(db) ){
  145465. return SQLITE_MISUSE_BKPT;
  145466. }
  145467. #endif
  145468. sqlite3_mutex_enter(db->mutex);
  145469. if( xDestroy ){
  145470. pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
  145471. if( !pArg ){
  145472. sqlite3OomFault(db);
  145473. xDestroy(p);
  145474. goto out;
  145475. }
  145476. pArg->nRef = 0;
  145477. pArg->xDestroy = xDestroy;
  145478. pArg->pUserData = p;
  145479. }
  145480. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
  145481. xSFunc, xStep, xFinal, xValue, xInverse, pArg
  145482. );
  145483. if( pArg && pArg->nRef==0 ){
  145484. assert( rc!=SQLITE_OK );
  145485. xDestroy(p);
  145486. sqlite3_free(pArg);
  145487. }
  145488. out:
  145489. rc = sqlite3ApiExit(db, rc);
  145490. sqlite3_mutex_leave(db->mutex);
  145491. return rc;
  145492. }
  145493. /*
  145494. ** Create new user functions.
  145495. */
  145496. SQLITE_API int sqlite3_create_function(
  145497. sqlite3 *db,
  145498. const char *zFunc,
  145499. int nArg,
  145500. int enc,
  145501. void *p,
  145502. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  145503. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  145504. void (*xFinal)(sqlite3_context*)
  145505. ){
  145506. return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
  145507. xFinal, 0, 0, 0);
  145508. }
  145509. SQLITE_API int sqlite3_create_function_v2(
  145510. sqlite3 *db,
  145511. const char *zFunc,
  145512. int nArg,
  145513. int enc,
  145514. void *p,
  145515. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  145516. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  145517. void (*xFinal)(sqlite3_context*),
  145518. void (*xDestroy)(void *)
  145519. ){
  145520. return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
  145521. xFinal, 0, 0, xDestroy);
  145522. }
  145523. SQLITE_API int sqlite3_create_window_function(
  145524. sqlite3 *db,
  145525. const char *zFunc,
  145526. int nArg,
  145527. int enc,
  145528. void *p,
  145529. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  145530. void (*xFinal)(sqlite3_context*),
  145531. void (*xValue)(sqlite3_context*),
  145532. void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
  145533. void (*xDestroy)(void *)
  145534. ){
  145535. return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
  145536. xFinal, xValue, xInverse, xDestroy);
  145537. }
  145538. #ifndef SQLITE_OMIT_UTF16
  145539. SQLITE_API int sqlite3_create_function16(
  145540. sqlite3 *db,
  145541. const void *zFunctionName,
  145542. int nArg,
  145543. int eTextRep,
  145544. void *p,
  145545. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  145546. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  145547. void (*xFinal)(sqlite3_context*)
  145548. ){
  145549. int rc;
  145550. char *zFunc8;
  145551. #ifdef SQLITE_ENABLE_API_ARMOR
  145552. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  145553. #endif
  145554. sqlite3_mutex_enter(db->mutex);
  145555. assert( !db->mallocFailed );
  145556. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  145557. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
  145558. sqlite3DbFree(db, zFunc8);
  145559. rc = sqlite3ApiExit(db, rc);
  145560. sqlite3_mutex_leave(db->mutex);
  145561. return rc;
  145562. }
  145563. #endif
  145564. /*
  145565. ** The following is the implementation of an SQL function that always
  145566. ** fails with an error message stating that the function is used in the
  145567. ** wrong context. The sqlite3_overload_function() API might construct
  145568. ** SQL function that use this routine so that the functions will exist
  145569. ** for name resolution but are actually overloaded by the xFindFunction
  145570. ** method of virtual tables.
  145571. */
  145572. static void sqlite3InvalidFunction(
  145573. sqlite3_context *context, /* The function calling context */
  145574. int NotUsed, /* Number of arguments to the function */
  145575. sqlite3_value **NotUsed2 /* Value of each argument */
  145576. ){
  145577. const char *zName = (const char*)sqlite3_user_data(context);
  145578. char *zErr;
  145579. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  145580. zErr = sqlite3_mprintf(
  145581. "unable to use function %s in the requested context", zName);
  145582. sqlite3_result_error(context, zErr, -1);
  145583. sqlite3_free(zErr);
  145584. }
  145585. /*
  145586. ** Declare that a function has been overloaded by a virtual table.
  145587. **
  145588. ** If the function already exists as a regular global function, then
  145589. ** this routine is a no-op. If the function does not exist, then create
  145590. ** a new one that always throws a run-time error.
  145591. **
  145592. ** When virtual tables intend to provide an overloaded function, they
  145593. ** should call this routine to make sure the global function exists.
  145594. ** A global function must exist in order for name resolution to work
  145595. ** properly.
  145596. */
  145597. SQLITE_API int sqlite3_overload_function(
  145598. sqlite3 *db,
  145599. const char *zName,
  145600. int nArg
  145601. ){
  145602. int rc;
  145603. char *zCopy;
  145604. #ifdef SQLITE_ENABLE_API_ARMOR
  145605. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  145606. return SQLITE_MISUSE_BKPT;
  145607. }
  145608. #endif
  145609. sqlite3_mutex_enter(db->mutex);
  145610. rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
  145611. sqlite3_mutex_leave(db->mutex);
  145612. if( rc ) return SQLITE_OK;
  145613. zCopy = sqlite3_mprintf(zName);
  145614. if( zCopy==0 ) return SQLITE_NOMEM;
  145615. return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
  145616. zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
  145617. }
  145618. #ifndef SQLITE_OMIT_TRACE
  145619. /*
  145620. ** Register a trace function. The pArg from the previously registered trace
  145621. ** is returned.
  145622. **
  145623. ** A NULL trace function means that no tracing is executes. A non-NULL
  145624. ** trace is a pointer to a function that is invoked at the start of each
  145625. ** SQL statement.
  145626. */
  145627. #ifndef SQLITE_OMIT_DEPRECATED
  145628. SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
  145629. void *pOld;
  145630. #ifdef SQLITE_ENABLE_API_ARMOR
  145631. if( !sqlite3SafetyCheckOk(db) ){
  145632. (void)SQLITE_MISUSE_BKPT;
  145633. return 0;
  145634. }
  145635. #endif
  145636. sqlite3_mutex_enter(db->mutex);
  145637. pOld = db->pTraceArg;
  145638. db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
  145639. db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
  145640. db->pTraceArg = pArg;
  145641. sqlite3_mutex_leave(db->mutex);
  145642. return pOld;
  145643. }
  145644. #endif /* SQLITE_OMIT_DEPRECATED */
  145645. /* Register a trace callback using the version-2 interface.
  145646. */
  145647. SQLITE_API int sqlite3_trace_v2(
  145648. sqlite3 *db, /* Trace this connection */
  145649. unsigned mTrace, /* Mask of events to be traced */
  145650. int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
  145651. void *pArg /* Context */
  145652. ){
  145653. #ifdef SQLITE_ENABLE_API_ARMOR
  145654. if( !sqlite3SafetyCheckOk(db) ){
  145655. return SQLITE_MISUSE_BKPT;
  145656. }
  145657. #endif
  145658. sqlite3_mutex_enter(db->mutex);
  145659. if( mTrace==0 ) xTrace = 0;
  145660. if( xTrace==0 ) mTrace = 0;
  145661. db->mTrace = mTrace;
  145662. db->xTrace = xTrace;
  145663. db->pTraceArg = pArg;
  145664. sqlite3_mutex_leave(db->mutex);
  145665. return SQLITE_OK;
  145666. }
  145667. #ifndef SQLITE_OMIT_DEPRECATED
  145668. /*
  145669. ** Register a profile function. The pArg from the previously registered
  145670. ** profile function is returned.
  145671. **
  145672. ** A NULL profile function means that no profiling is executes. A non-NULL
  145673. ** profile is a pointer to a function that is invoked at the conclusion of
  145674. ** each SQL statement that is run.
  145675. */
  145676. SQLITE_API void *sqlite3_profile(
  145677. sqlite3 *db,
  145678. void (*xProfile)(void*,const char*,sqlite_uint64),
  145679. void *pArg
  145680. ){
  145681. void *pOld;
  145682. #ifdef SQLITE_ENABLE_API_ARMOR
  145683. if( !sqlite3SafetyCheckOk(db) ){
  145684. (void)SQLITE_MISUSE_BKPT;
  145685. return 0;
  145686. }
  145687. #endif
  145688. sqlite3_mutex_enter(db->mutex);
  145689. pOld = db->pProfileArg;
  145690. db->xProfile = xProfile;
  145691. db->pProfileArg = pArg;
  145692. sqlite3_mutex_leave(db->mutex);
  145693. return pOld;
  145694. }
  145695. #endif /* SQLITE_OMIT_DEPRECATED */
  145696. #endif /* SQLITE_OMIT_TRACE */
  145697. /*
  145698. ** Register a function to be invoked when a transaction commits.
  145699. ** If the invoked function returns non-zero, then the commit becomes a
  145700. ** rollback.
  145701. */
  145702. SQLITE_API void *sqlite3_commit_hook(
  145703. sqlite3 *db, /* Attach the hook to this database */
  145704. int (*xCallback)(void*), /* Function to invoke on each commit */
  145705. void *pArg /* Argument to the function */
  145706. ){
  145707. void *pOld;
  145708. #ifdef SQLITE_ENABLE_API_ARMOR
  145709. if( !sqlite3SafetyCheckOk(db) ){
  145710. (void)SQLITE_MISUSE_BKPT;
  145711. return 0;
  145712. }
  145713. #endif
  145714. sqlite3_mutex_enter(db->mutex);
  145715. pOld = db->pCommitArg;
  145716. db->xCommitCallback = xCallback;
  145717. db->pCommitArg = pArg;
  145718. sqlite3_mutex_leave(db->mutex);
  145719. return pOld;
  145720. }
  145721. /*
  145722. ** Register a callback to be invoked each time a row is updated,
  145723. ** inserted or deleted using this database connection.
  145724. */
  145725. SQLITE_API void *sqlite3_update_hook(
  145726. sqlite3 *db, /* Attach the hook to this database */
  145727. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  145728. void *pArg /* Argument to the function */
  145729. ){
  145730. void *pRet;
  145731. #ifdef SQLITE_ENABLE_API_ARMOR
  145732. if( !sqlite3SafetyCheckOk(db) ){
  145733. (void)SQLITE_MISUSE_BKPT;
  145734. return 0;
  145735. }
  145736. #endif
  145737. sqlite3_mutex_enter(db->mutex);
  145738. pRet = db->pUpdateArg;
  145739. db->xUpdateCallback = xCallback;
  145740. db->pUpdateArg = pArg;
  145741. sqlite3_mutex_leave(db->mutex);
  145742. return pRet;
  145743. }
  145744. /*
  145745. ** Register a callback to be invoked each time a transaction is rolled
  145746. ** back by this database connection.
  145747. */
  145748. SQLITE_API void *sqlite3_rollback_hook(
  145749. sqlite3 *db, /* Attach the hook to this database */
  145750. void (*xCallback)(void*), /* Callback function */
  145751. void *pArg /* Argument to the function */
  145752. ){
  145753. void *pRet;
  145754. #ifdef SQLITE_ENABLE_API_ARMOR
  145755. if( !sqlite3SafetyCheckOk(db) ){
  145756. (void)SQLITE_MISUSE_BKPT;
  145757. return 0;
  145758. }
  145759. #endif
  145760. sqlite3_mutex_enter(db->mutex);
  145761. pRet = db->pRollbackArg;
  145762. db->xRollbackCallback = xCallback;
  145763. db->pRollbackArg = pArg;
  145764. sqlite3_mutex_leave(db->mutex);
  145765. return pRet;
  145766. }
  145767. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  145768. /*
  145769. ** Register a callback to be invoked each time a row is updated,
  145770. ** inserted or deleted using this database connection.
  145771. */
  145772. SQLITE_API void *sqlite3_preupdate_hook(
  145773. sqlite3 *db, /* Attach the hook to this database */
  145774. void(*xCallback)( /* Callback function */
  145775. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
  145776. void *pArg /* First callback argument */
  145777. ){
  145778. void *pRet;
  145779. sqlite3_mutex_enter(db->mutex);
  145780. pRet = db->pPreUpdateArg;
  145781. db->xPreUpdateCallback = xCallback;
  145782. db->pPreUpdateArg = pArg;
  145783. sqlite3_mutex_leave(db->mutex);
  145784. return pRet;
  145785. }
  145786. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  145787. #ifndef SQLITE_OMIT_WAL
  145788. /*
  145789. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  145790. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  145791. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  145792. ** wal_autocheckpoint()).
  145793. */
  145794. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  145795. void *pClientData, /* Argument */
  145796. sqlite3 *db, /* Connection */
  145797. const char *zDb, /* Database */
  145798. int nFrame /* Size of WAL */
  145799. ){
  145800. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  145801. sqlite3BeginBenignMalloc();
  145802. sqlite3_wal_checkpoint(db, zDb);
  145803. sqlite3EndBenignMalloc();
  145804. }
  145805. return SQLITE_OK;
  145806. }
  145807. #endif /* SQLITE_OMIT_WAL */
  145808. /*
  145809. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  145810. ** a database after committing a transaction if there are nFrame or
  145811. ** more frames in the log file. Passing zero or a negative value as the
  145812. ** nFrame parameter disables automatic checkpoints entirely.
  145813. **
  145814. ** The callback registered by this function replaces any existing callback
  145815. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  145816. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  145817. ** configured by this function.
  145818. */
  145819. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  145820. #ifdef SQLITE_OMIT_WAL
  145821. UNUSED_PARAMETER(db);
  145822. UNUSED_PARAMETER(nFrame);
  145823. #else
  145824. #ifdef SQLITE_ENABLE_API_ARMOR
  145825. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  145826. #endif
  145827. if( nFrame>0 ){
  145828. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  145829. }else{
  145830. sqlite3_wal_hook(db, 0, 0);
  145831. }
  145832. #endif
  145833. return SQLITE_OK;
  145834. }
  145835. /*
  145836. ** Register a callback to be invoked each time a transaction is written
  145837. ** into the write-ahead-log by this database connection.
  145838. */
  145839. SQLITE_API void *sqlite3_wal_hook(
  145840. sqlite3 *db, /* Attach the hook to this db handle */
  145841. int(*xCallback)(void *, sqlite3*, const char*, int),
  145842. void *pArg /* First argument passed to xCallback() */
  145843. ){
  145844. #ifndef SQLITE_OMIT_WAL
  145845. void *pRet;
  145846. #ifdef SQLITE_ENABLE_API_ARMOR
  145847. if( !sqlite3SafetyCheckOk(db) ){
  145848. (void)SQLITE_MISUSE_BKPT;
  145849. return 0;
  145850. }
  145851. #endif
  145852. sqlite3_mutex_enter(db->mutex);
  145853. pRet = db->pWalArg;
  145854. db->xWalCallback = xCallback;
  145855. db->pWalArg = pArg;
  145856. sqlite3_mutex_leave(db->mutex);
  145857. return pRet;
  145858. #else
  145859. return 0;
  145860. #endif
  145861. }
  145862. /*
  145863. ** Checkpoint database zDb.
  145864. */
  145865. SQLITE_API int sqlite3_wal_checkpoint_v2(
  145866. sqlite3 *db, /* Database handle */
  145867. const char *zDb, /* Name of attached database (or NULL) */
  145868. int eMode, /* SQLITE_CHECKPOINT_* value */
  145869. int *pnLog, /* OUT: Size of WAL log in frames */
  145870. int *pnCkpt /* OUT: Total number of frames checkpointed */
  145871. ){
  145872. #ifdef SQLITE_OMIT_WAL
  145873. return SQLITE_OK;
  145874. #else
  145875. int rc; /* Return code */
  145876. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  145877. #ifdef SQLITE_ENABLE_API_ARMOR
  145878. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  145879. #endif
  145880. /* Initialize the output variables to -1 in case an error occurs. */
  145881. if( pnLog ) *pnLog = -1;
  145882. if( pnCkpt ) *pnCkpt = -1;
  145883. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  145884. assert( SQLITE_CHECKPOINT_FULL==1 );
  145885. assert( SQLITE_CHECKPOINT_RESTART==2 );
  145886. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  145887. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  145888. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  145889. ** mode: */
  145890. return SQLITE_MISUSE;
  145891. }
  145892. sqlite3_mutex_enter(db->mutex);
  145893. if( zDb && zDb[0] ){
  145894. iDb = sqlite3FindDbName(db, zDb);
  145895. }
  145896. if( iDb<0 ){
  145897. rc = SQLITE_ERROR;
  145898. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  145899. }else{
  145900. db->busyHandler.nBusy = 0;
  145901. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  145902. sqlite3Error(db, rc);
  145903. }
  145904. rc = sqlite3ApiExit(db, rc);
  145905. /* If there are no active statements, clear the interrupt flag at this
  145906. ** point. */
  145907. if( db->nVdbeActive==0 ){
  145908. db->u1.isInterrupted = 0;
  145909. }
  145910. sqlite3_mutex_leave(db->mutex);
  145911. return rc;
  145912. #endif
  145913. }
  145914. /*
  145915. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  145916. ** to contains a zero-length string, all attached databases are
  145917. ** checkpointed.
  145918. */
  145919. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  145920. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  145921. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  145922. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  145923. }
  145924. #ifndef SQLITE_OMIT_WAL
  145925. /*
  145926. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  145927. ** not currently open in WAL mode.
  145928. **
  145929. ** If a transaction is open on the database being checkpointed, this
  145930. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  145931. ** an error occurs while running the checkpoint, an SQLite error code is
  145932. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  145933. **
  145934. ** The mutex on database handle db should be held by the caller. The mutex
  145935. ** associated with the specific b-tree being checkpointed is taken by
  145936. ** this function while the checkpoint is running.
  145937. **
  145938. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  145939. ** checkpointed. If an error is encountered it is returned immediately -
  145940. ** no attempt is made to checkpoint any remaining databases.
  145941. **
  145942. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
  145943. ** or TRUNCATE.
  145944. */
  145945. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  145946. int rc = SQLITE_OK; /* Return code */
  145947. int i; /* Used to iterate through attached dbs */
  145948. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  145949. assert( sqlite3_mutex_held(db->mutex) );
  145950. assert( !pnLog || *pnLog==-1 );
  145951. assert( !pnCkpt || *pnCkpt==-1 );
  145952. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  145953. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  145954. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  145955. pnLog = 0;
  145956. pnCkpt = 0;
  145957. if( rc==SQLITE_BUSY ){
  145958. bBusy = 1;
  145959. rc = SQLITE_OK;
  145960. }
  145961. }
  145962. }
  145963. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  145964. }
  145965. #endif /* SQLITE_OMIT_WAL */
  145966. /*
  145967. ** This function returns true if main-memory should be used instead of
  145968. ** a temporary file for transient pager files and statement journals.
  145969. ** The value returned depends on the value of db->temp_store (runtime
  145970. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  145971. ** following table describes the relationship between these two values
  145972. ** and this functions return value.
  145973. **
  145974. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  145975. ** ----------------- -------------- ------------------------------
  145976. ** 0 any file (return 0)
  145977. ** 1 1 file (return 0)
  145978. ** 1 2 memory (return 1)
  145979. ** 1 0 file (return 0)
  145980. ** 2 1 file (return 0)
  145981. ** 2 2 memory (return 1)
  145982. ** 2 0 memory (return 1)
  145983. ** 3 any memory (return 1)
  145984. */
  145985. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  145986. #if SQLITE_TEMP_STORE==1
  145987. return ( db->temp_store==2 );
  145988. #endif
  145989. #if SQLITE_TEMP_STORE==2
  145990. return ( db->temp_store!=1 );
  145991. #endif
  145992. #if SQLITE_TEMP_STORE==3
  145993. UNUSED_PARAMETER(db);
  145994. return 1;
  145995. #endif
  145996. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  145997. UNUSED_PARAMETER(db);
  145998. return 0;
  145999. #endif
  146000. }
  146001. /*
  146002. ** Return UTF-8 encoded English language explanation of the most recent
  146003. ** error.
  146004. */
  146005. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  146006. const char *z;
  146007. if( !db ){
  146008. return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  146009. }
  146010. if( !sqlite3SafetyCheckSickOrOk(db) ){
  146011. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  146012. }
  146013. sqlite3_mutex_enter(db->mutex);
  146014. if( db->mallocFailed ){
  146015. z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  146016. }else{
  146017. testcase( db->pErr==0 );
  146018. z = (char*)sqlite3_value_text(db->pErr);
  146019. assert( !db->mallocFailed );
  146020. if( z==0 ){
  146021. z = sqlite3ErrStr(db->errCode);
  146022. }
  146023. }
  146024. sqlite3_mutex_leave(db->mutex);
  146025. return z;
  146026. }
  146027. #ifndef SQLITE_OMIT_UTF16
  146028. /*
  146029. ** Return UTF-16 encoded English language explanation of the most recent
  146030. ** error.
  146031. */
  146032. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  146033. static const u16 outOfMem[] = {
  146034. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  146035. };
  146036. static const u16 misuse[] = {
  146037. 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
  146038. 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
  146039. 'm', 'i', 's', 'u', 's', 'e', 0
  146040. };
  146041. const void *z;
  146042. if( !db ){
  146043. return (void *)outOfMem;
  146044. }
  146045. if( !sqlite3SafetyCheckSickOrOk(db) ){
  146046. return (void *)misuse;
  146047. }
  146048. sqlite3_mutex_enter(db->mutex);
  146049. if( db->mallocFailed ){
  146050. z = (void *)outOfMem;
  146051. }else{
  146052. z = sqlite3_value_text16(db->pErr);
  146053. if( z==0 ){
  146054. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  146055. z = sqlite3_value_text16(db->pErr);
  146056. }
  146057. /* A malloc() may have failed within the call to sqlite3_value_text16()
  146058. ** above. If this is the case, then the db->mallocFailed flag needs to
  146059. ** be cleared before returning. Do this directly, instead of via
  146060. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  146061. */
  146062. sqlite3OomClear(db);
  146063. }
  146064. sqlite3_mutex_leave(db->mutex);
  146065. return z;
  146066. }
  146067. #endif /* SQLITE_OMIT_UTF16 */
  146068. /*
  146069. ** Return the most recent error code generated by an SQLite routine. If NULL is
  146070. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  146071. */
  146072. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  146073. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  146074. return SQLITE_MISUSE_BKPT;
  146075. }
  146076. if( !db || db->mallocFailed ){
  146077. return SQLITE_NOMEM_BKPT;
  146078. }
  146079. return db->errCode & db->errMask;
  146080. }
  146081. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  146082. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  146083. return SQLITE_MISUSE_BKPT;
  146084. }
  146085. if( !db || db->mallocFailed ){
  146086. return SQLITE_NOMEM_BKPT;
  146087. }
  146088. return db->errCode;
  146089. }
  146090. SQLITE_API int sqlite3_system_errno(sqlite3 *db){
  146091. return db ? db->iSysErrno : 0;
  146092. }
  146093. /*
  146094. ** Return a string that describes the kind of error specified in the
  146095. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  146096. ** function.
  146097. */
  146098. SQLITE_API const char *sqlite3_errstr(int rc){
  146099. return sqlite3ErrStr(rc);
  146100. }
  146101. /*
  146102. ** Create a new collating function for database "db". The name is zName
  146103. ** and the encoding is enc.
  146104. */
  146105. static int createCollation(
  146106. sqlite3* db,
  146107. const char *zName,
  146108. u8 enc,
  146109. void* pCtx,
  146110. int(*xCompare)(void*,int,const void*,int,const void*),
  146111. void(*xDel)(void*)
  146112. ){
  146113. CollSeq *pColl;
  146114. int enc2;
  146115. assert( sqlite3_mutex_held(db->mutex) );
  146116. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  146117. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  146118. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  146119. */
  146120. enc2 = enc;
  146121. testcase( enc2==SQLITE_UTF16 );
  146122. testcase( enc2==SQLITE_UTF16_ALIGNED );
  146123. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  146124. enc2 = SQLITE_UTF16NATIVE;
  146125. }
  146126. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  146127. return SQLITE_MISUSE_BKPT;
  146128. }
  146129. /* Check if this call is removing or replacing an existing collation
  146130. ** sequence. If so, and there are active VMs, return busy. If there
  146131. ** are no active VMs, invalidate any pre-compiled statements.
  146132. */
  146133. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  146134. if( pColl && pColl->xCmp ){
  146135. if( db->nVdbeActive ){
  146136. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  146137. "unable to delete/modify collation sequence due to active statements");
  146138. return SQLITE_BUSY;
  146139. }
  146140. sqlite3ExpirePreparedStatements(db, 0);
  146141. /* If collation sequence pColl was created directly by a call to
  146142. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  146143. ** then any copies made by synthCollSeq() need to be invalidated.
  146144. ** Also, collation destructor - CollSeq.xDel() - function may need
  146145. ** to be called.
  146146. */
  146147. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  146148. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  146149. int j;
  146150. for(j=0; j<3; j++){
  146151. CollSeq *p = &aColl[j];
  146152. if( p->enc==pColl->enc ){
  146153. if( p->xDel ){
  146154. p->xDel(p->pUser);
  146155. }
  146156. p->xCmp = 0;
  146157. }
  146158. }
  146159. }
  146160. }
  146161. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  146162. if( pColl==0 ) return SQLITE_NOMEM_BKPT;
  146163. pColl->xCmp = xCompare;
  146164. pColl->pUser = pCtx;
  146165. pColl->xDel = xDel;
  146166. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  146167. sqlite3Error(db, SQLITE_OK);
  146168. return SQLITE_OK;
  146169. }
  146170. /*
  146171. ** This array defines hard upper bounds on limit values. The
  146172. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  146173. ** #defines in sqlite3.h.
  146174. */
  146175. static const int aHardLimit[] = {
  146176. SQLITE_MAX_LENGTH,
  146177. SQLITE_MAX_SQL_LENGTH,
  146178. SQLITE_MAX_COLUMN,
  146179. SQLITE_MAX_EXPR_DEPTH,
  146180. SQLITE_MAX_COMPOUND_SELECT,
  146181. SQLITE_MAX_VDBE_OP,
  146182. SQLITE_MAX_FUNCTION_ARG,
  146183. SQLITE_MAX_ATTACHED,
  146184. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  146185. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  146186. SQLITE_MAX_TRIGGER_DEPTH,
  146187. SQLITE_MAX_WORKER_THREADS,
  146188. };
  146189. /*
  146190. ** Make sure the hard limits are set to reasonable values
  146191. */
  146192. #if SQLITE_MAX_LENGTH<100
  146193. # error SQLITE_MAX_LENGTH must be at least 100
  146194. #endif
  146195. #if SQLITE_MAX_SQL_LENGTH<100
  146196. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  146197. #endif
  146198. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  146199. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  146200. #endif
  146201. #if SQLITE_MAX_COMPOUND_SELECT<2
  146202. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  146203. #endif
  146204. #if SQLITE_MAX_VDBE_OP<40
  146205. # error SQLITE_MAX_VDBE_OP must be at least 40
  146206. #endif
  146207. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
  146208. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
  146209. #endif
  146210. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  146211. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  146212. #endif
  146213. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  146214. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  146215. #endif
  146216. #if SQLITE_MAX_COLUMN>32767
  146217. # error SQLITE_MAX_COLUMN must not exceed 32767
  146218. #endif
  146219. #if SQLITE_MAX_TRIGGER_DEPTH<1
  146220. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  146221. #endif
  146222. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  146223. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  146224. #endif
  146225. /*
  146226. ** Change the value of a limit. Report the old value.
  146227. ** If an invalid limit index is supplied, report -1.
  146228. ** Make no changes but still report the old value if the
  146229. ** new limit is negative.
  146230. **
  146231. ** A new lower limit does not shrink existing constructs.
  146232. ** It merely prevents new constructs that exceed the limit
  146233. ** from forming.
  146234. */
  146235. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  146236. int oldLimit;
  146237. #ifdef SQLITE_ENABLE_API_ARMOR
  146238. if( !sqlite3SafetyCheckOk(db) ){
  146239. (void)SQLITE_MISUSE_BKPT;
  146240. return -1;
  146241. }
  146242. #endif
  146243. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  146244. ** there is a hard upper bound set at compile-time by a C preprocessor
  146245. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  146246. ** "_MAX_".)
  146247. */
  146248. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  146249. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  146250. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  146251. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  146252. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  146253. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  146254. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  146255. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  146256. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  146257. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  146258. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  146259. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  146260. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  146261. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  146262. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  146263. return -1;
  146264. }
  146265. oldLimit = db->aLimit[limitId];
  146266. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  146267. if( newLimit>aHardLimit[limitId] ){
  146268. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  146269. }
  146270. db->aLimit[limitId] = newLimit;
  146271. }
  146272. return oldLimit; /* IMP: R-53341-35419 */
  146273. }
  146274. /*
  146275. ** This function is used to parse both URIs and non-URI filenames passed by the
  146276. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  146277. ** URIs specified as part of ATTACH statements.
  146278. **
  146279. ** The first argument to this function is the name of the VFS to use (or
  146280. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  146281. ** query parameter. The second argument contains the URI (or non-URI filename)
  146282. ** itself. When this function is called the *pFlags variable should contain
  146283. ** the default flags to open the database handle with. The value stored in
  146284. ** *pFlags may be updated before returning if the URI filename contains
  146285. ** "cache=xxx" or "mode=xxx" query parameters.
  146286. **
  146287. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  146288. ** the VFS that should be used to open the database file. *pzFile is set to
  146289. ** point to a buffer containing the name of the file to open. It is the
  146290. ** responsibility of the caller to eventually call sqlite3_free() to release
  146291. ** this buffer.
  146292. **
  146293. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  146294. ** may be set to point to a buffer containing an English language error
  146295. ** message. It is the responsibility of the caller to eventually release
  146296. ** this buffer by calling sqlite3_free().
  146297. */
  146298. SQLITE_PRIVATE int sqlite3ParseUri(
  146299. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  146300. const char *zUri, /* Nul-terminated URI to parse */
  146301. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  146302. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  146303. char **pzFile, /* OUT: Filename component of URI */
  146304. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  146305. ){
  146306. int rc = SQLITE_OK;
  146307. unsigned int flags = *pFlags;
  146308. const char *zVfs = zDefaultVfs;
  146309. char *zFile;
  146310. char c;
  146311. int nUri = sqlite3Strlen30(zUri);
  146312. assert( *pzErrMsg==0 );
  146313. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  146314. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  146315. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  146316. ){
  146317. char *zOpt;
  146318. int eState; /* Parser state when parsing URI */
  146319. int iIn; /* Input character index */
  146320. int iOut = 0; /* Output character index */
  146321. u64 nByte = nUri+2; /* Bytes of space to allocate */
  146322. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  146323. ** method that there may be extra parameters following the file-name. */
  146324. flags |= SQLITE_OPEN_URI;
  146325. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  146326. zFile = sqlite3_malloc64(nByte);
  146327. if( !zFile ) return SQLITE_NOMEM_BKPT;
  146328. iIn = 5;
  146329. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  146330. if( strncmp(zUri+5, "///", 3)==0 ){
  146331. iIn = 7;
  146332. /* The following condition causes URIs with five leading / characters
  146333. ** like file://///host/path to be converted into UNCs like //host/path.
  146334. ** The correct URI for that UNC has only two or four leading / characters
  146335. ** file://host/path or file:////host/path. But 5 leading slashes is a
  146336. ** common error, we are told, so we handle it as a special case. */
  146337. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  146338. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  146339. iIn = 16;
  146340. }
  146341. #else
  146342. /* Discard the scheme and authority segments of the URI. */
  146343. if( zUri[5]=='/' && zUri[6]=='/' ){
  146344. iIn = 7;
  146345. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  146346. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  146347. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  146348. iIn-7, &zUri[7]);
  146349. rc = SQLITE_ERROR;
  146350. goto parse_uri_out;
  146351. }
  146352. }
  146353. #endif
  146354. /* Copy the filename and any query parameters into the zFile buffer.
  146355. ** Decode %HH escape codes along the way.
  146356. **
  146357. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  146358. ** on the parsing context. As follows:
  146359. **
  146360. ** 0: Parsing file-name.
  146361. ** 1: Parsing name section of a name=value query parameter.
  146362. ** 2: Parsing value section of a name=value query parameter.
  146363. */
  146364. eState = 0;
  146365. while( (c = zUri[iIn])!=0 && c!='#' ){
  146366. iIn++;
  146367. if( c=='%'
  146368. && sqlite3Isxdigit(zUri[iIn])
  146369. && sqlite3Isxdigit(zUri[iIn+1])
  146370. ){
  146371. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  146372. octet += sqlite3HexToInt(zUri[iIn++]);
  146373. assert( octet>=0 && octet<256 );
  146374. if( octet==0 ){
  146375. #ifndef SQLITE_ENABLE_URI_00_ERROR
  146376. /* This branch is taken when "%00" appears within the URI. In this
  146377. ** case we ignore all text in the remainder of the path, name or
  146378. ** value currently being parsed. So ignore the current character
  146379. ** and skip to the next "?", "=" or "&", as appropriate. */
  146380. while( (c = zUri[iIn])!=0 && c!='#'
  146381. && (eState!=0 || c!='?')
  146382. && (eState!=1 || (c!='=' && c!='&'))
  146383. && (eState!=2 || c!='&')
  146384. ){
  146385. iIn++;
  146386. }
  146387. continue;
  146388. #else
  146389. /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
  146390. *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
  146391. rc = SQLITE_ERROR;
  146392. goto parse_uri_out;
  146393. #endif
  146394. }
  146395. c = octet;
  146396. }else if( eState==1 && (c=='&' || c=='=') ){
  146397. if( zFile[iOut-1]==0 ){
  146398. /* An empty option name. Ignore this option altogether. */
  146399. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  146400. continue;
  146401. }
  146402. if( c=='&' ){
  146403. zFile[iOut++] = '\0';
  146404. }else{
  146405. eState = 2;
  146406. }
  146407. c = 0;
  146408. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  146409. c = 0;
  146410. eState = 1;
  146411. }
  146412. zFile[iOut++] = c;
  146413. }
  146414. if( eState==1 ) zFile[iOut++] = '\0';
  146415. zFile[iOut++] = '\0';
  146416. zFile[iOut++] = '\0';
  146417. /* Check if there were any options specified that should be interpreted
  146418. ** here. Options that are interpreted here include "vfs" and those that
  146419. ** correspond to flags that may be passed to the sqlite3_open_v2()
  146420. ** method. */
  146421. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  146422. while( zOpt[0] ){
  146423. int nOpt = sqlite3Strlen30(zOpt);
  146424. char *zVal = &zOpt[nOpt+1];
  146425. int nVal = sqlite3Strlen30(zVal);
  146426. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  146427. zVfs = zVal;
  146428. }else{
  146429. struct OpenMode {
  146430. const char *z;
  146431. int mode;
  146432. } *aMode = 0;
  146433. char *zModeType = 0;
  146434. int mask = 0;
  146435. int limit = 0;
  146436. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  146437. static struct OpenMode aCacheMode[] = {
  146438. { "shared", SQLITE_OPEN_SHAREDCACHE },
  146439. { "private", SQLITE_OPEN_PRIVATECACHE },
  146440. { 0, 0 }
  146441. };
  146442. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  146443. aMode = aCacheMode;
  146444. limit = mask;
  146445. zModeType = "cache";
  146446. }
  146447. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  146448. static struct OpenMode aOpenMode[] = {
  146449. { "ro", SQLITE_OPEN_READONLY },
  146450. { "rw", SQLITE_OPEN_READWRITE },
  146451. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  146452. { "memory", SQLITE_OPEN_MEMORY },
  146453. { 0, 0 }
  146454. };
  146455. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  146456. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  146457. aMode = aOpenMode;
  146458. limit = mask & flags;
  146459. zModeType = "access";
  146460. }
  146461. if( aMode ){
  146462. int i;
  146463. int mode = 0;
  146464. for(i=0; aMode[i].z; i++){
  146465. const char *z = aMode[i].z;
  146466. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  146467. mode = aMode[i].mode;
  146468. break;
  146469. }
  146470. }
  146471. if( mode==0 ){
  146472. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  146473. rc = SQLITE_ERROR;
  146474. goto parse_uri_out;
  146475. }
  146476. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  146477. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  146478. zModeType, zVal);
  146479. rc = SQLITE_PERM;
  146480. goto parse_uri_out;
  146481. }
  146482. flags = (flags & ~mask) | mode;
  146483. }
  146484. }
  146485. zOpt = &zVal[nVal+1];
  146486. }
  146487. }else{
  146488. zFile = sqlite3_malloc64(nUri+2);
  146489. if( !zFile ) return SQLITE_NOMEM_BKPT;
  146490. if( nUri ){
  146491. memcpy(zFile, zUri, nUri);
  146492. }
  146493. zFile[nUri] = '\0';
  146494. zFile[nUri+1] = '\0';
  146495. flags &= ~SQLITE_OPEN_URI;
  146496. }
  146497. *ppVfs = sqlite3_vfs_find(zVfs);
  146498. if( *ppVfs==0 ){
  146499. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  146500. rc = SQLITE_ERROR;
  146501. }
  146502. parse_uri_out:
  146503. if( rc!=SQLITE_OK ){
  146504. sqlite3_free(zFile);
  146505. zFile = 0;
  146506. }
  146507. *pFlags = flags;
  146508. *pzFile = zFile;
  146509. return rc;
  146510. }
  146511. /*
  146512. ** This routine does the work of opening a database on behalf of
  146513. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  146514. ** is UTF-8 encoded.
  146515. */
  146516. static int openDatabase(
  146517. const char *zFilename, /* Database filename UTF-8 encoded */
  146518. sqlite3 **ppDb, /* OUT: Returned database handle */
  146519. unsigned int flags, /* Operational flags */
  146520. const char *zVfs /* Name of the VFS to use */
  146521. ){
  146522. sqlite3 *db; /* Store allocated handle here */
  146523. int rc; /* Return code */
  146524. int isThreadsafe; /* True for threadsafe connections */
  146525. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  146526. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  146527. #ifdef SQLITE_ENABLE_API_ARMOR
  146528. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  146529. #endif
  146530. *ppDb = 0;
  146531. #ifndef SQLITE_OMIT_AUTOINIT
  146532. rc = sqlite3_initialize();
  146533. if( rc ) return rc;
  146534. #endif
  146535. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  146536. isThreadsafe = 0;
  146537. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  146538. isThreadsafe = 0;
  146539. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  146540. isThreadsafe = 1;
  146541. }else{
  146542. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  146543. }
  146544. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  146545. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  146546. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  146547. flags |= SQLITE_OPEN_SHAREDCACHE;
  146548. }
  146549. /* Remove harmful bits from the flags parameter
  146550. **
  146551. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  146552. ** dealt with in the previous code block. Besides these, the only
  146553. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  146554. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  146555. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  146556. ** off all other flags.
  146557. */
  146558. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  146559. SQLITE_OPEN_EXCLUSIVE |
  146560. SQLITE_OPEN_MAIN_DB |
  146561. SQLITE_OPEN_TEMP_DB |
  146562. SQLITE_OPEN_TRANSIENT_DB |
  146563. SQLITE_OPEN_MAIN_JOURNAL |
  146564. SQLITE_OPEN_TEMP_JOURNAL |
  146565. SQLITE_OPEN_SUBJOURNAL |
  146566. SQLITE_OPEN_MASTER_JOURNAL |
  146567. SQLITE_OPEN_NOMUTEX |
  146568. SQLITE_OPEN_FULLMUTEX |
  146569. SQLITE_OPEN_WAL
  146570. );
  146571. /* Allocate the sqlite data structure */
  146572. db = sqlite3MallocZero( sizeof(sqlite3) );
  146573. if( db==0 ) goto opendb_out;
  146574. if( isThreadsafe
  146575. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  146576. || sqlite3GlobalConfig.bCoreMutex
  146577. #endif
  146578. ){
  146579. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  146580. if( db->mutex==0 ){
  146581. sqlite3_free(db);
  146582. db = 0;
  146583. goto opendb_out;
  146584. }
  146585. if( isThreadsafe==0 ){
  146586. sqlite3MutexWarnOnContention(db->mutex);
  146587. }
  146588. }
  146589. sqlite3_mutex_enter(db->mutex);
  146590. db->errMask = 0xff;
  146591. db->nDb = 2;
  146592. db->magic = SQLITE_MAGIC_BUSY;
  146593. db->aDb = db->aDbStatic;
  146594. db->lookaside.bDisable = 1;
  146595. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  146596. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  146597. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  146598. db->autoCommit = 1;
  146599. db->nextAutovac = -1;
  146600. db->szMmap = sqlite3GlobalConfig.szMmap;
  146601. db->nextPagesize = 0;
  146602. db->nMaxSorterMmap = 0x7FFFFFFF;
  146603. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  146604. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  146605. | SQLITE_AutoIndex
  146606. #endif
  146607. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  146608. | SQLITE_CkptFullFSync
  146609. #endif
  146610. #if SQLITE_DEFAULT_FILE_FORMAT<4
  146611. | SQLITE_LegacyFileFmt
  146612. #endif
  146613. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  146614. | SQLITE_LoadExtension
  146615. #endif
  146616. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  146617. | SQLITE_RecTriggers
  146618. #endif
  146619. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  146620. | SQLITE_ForeignKeys
  146621. #endif
  146622. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  146623. | SQLITE_ReverseOrder
  146624. #endif
  146625. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  146626. | SQLITE_CellSizeCk
  146627. #endif
  146628. #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
  146629. | SQLITE_Fts3Tokenizer
  146630. #endif
  146631. #if defined(SQLITE_ENABLE_QPSG)
  146632. | SQLITE_EnableQPSG
  146633. #endif
  146634. #if defined(SQLITE_DEFAULT_DEFENSIVE)
  146635. | SQLITE_Defensive
  146636. #endif
  146637. ;
  146638. sqlite3HashInit(&db->aCollSeq);
  146639. #ifndef SQLITE_OMIT_VIRTUALTABLE
  146640. sqlite3HashInit(&db->aModule);
  146641. #endif
  146642. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  146643. ** and UTF-16, so add a version for each to avoid any unnecessary
  146644. ** conversions. The only error that can occur here is a malloc() failure.
  146645. **
  146646. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  146647. ** functions:
  146648. */
  146649. createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
  146650. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
  146651. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
  146652. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  146653. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  146654. if( db->mallocFailed ){
  146655. goto opendb_out;
  146656. }
  146657. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  146658. ** strings is BINARY.
  146659. */
  146660. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
  146661. assert( db->pDfltColl!=0 );
  146662. /* Parse the filename/URI argument
  146663. **
  146664. ** Only allow sensible combinations of bits in the flags argument.
  146665. ** Throw an error if any non-sense combination is used. If we
  146666. ** do not block illegal combinations here, it could trigger
  146667. ** assert() statements in deeper layers. Sensible combinations
  146668. ** are:
  146669. **
  146670. ** 1: SQLITE_OPEN_READONLY
  146671. ** 2: SQLITE_OPEN_READWRITE
  146672. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  146673. */
  146674. db->openFlags = flags;
  146675. assert( SQLITE_OPEN_READONLY == 0x01 );
  146676. assert( SQLITE_OPEN_READWRITE == 0x02 );
  146677. assert( SQLITE_OPEN_CREATE == 0x04 );
  146678. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  146679. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  146680. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  146681. if( ((1<<(flags&7)) & 0x46)==0 ){
  146682. rc = SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  146683. }else{
  146684. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  146685. }
  146686. if( rc!=SQLITE_OK ){
  146687. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  146688. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  146689. sqlite3_free(zErrMsg);
  146690. goto opendb_out;
  146691. }
  146692. /* Open the backend database driver */
  146693. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  146694. flags | SQLITE_OPEN_MAIN_DB);
  146695. if( rc!=SQLITE_OK ){
  146696. if( rc==SQLITE_IOERR_NOMEM ){
  146697. rc = SQLITE_NOMEM_BKPT;
  146698. }
  146699. sqlite3Error(db, rc);
  146700. goto opendb_out;
  146701. }
  146702. sqlite3BtreeEnter(db->aDb[0].pBt);
  146703. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  146704. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  146705. sqlite3BtreeLeave(db->aDb[0].pBt);
  146706. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  146707. /* The default safety_level for the main database is FULL; for the temp
  146708. ** database it is OFF. This matches the pager layer defaults.
  146709. */
  146710. db->aDb[0].zDbSName = "main";
  146711. db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  146712. db->aDb[1].zDbSName = "temp";
  146713. db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
  146714. db->magic = SQLITE_MAGIC_OPEN;
  146715. if( db->mallocFailed ){
  146716. goto opendb_out;
  146717. }
  146718. /* Register all built-in functions, but do not attempt to read the
  146719. ** database schema yet. This is delayed until the first time the database
  146720. ** is accessed.
  146721. */
  146722. sqlite3Error(db, SQLITE_OK);
  146723. sqlite3RegisterPerConnectionBuiltinFunctions(db);
  146724. rc = sqlite3_errcode(db);
  146725. #ifdef SQLITE_ENABLE_FTS5
  146726. /* Register any built-in FTS5 module before loading the automatic
  146727. ** extensions. This allows automatic extensions to register FTS5
  146728. ** tokenizers and auxiliary functions. */
  146729. if( !db->mallocFailed && rc==SQLITE_OK ){
  146730. rc = sqlite3Fts5Init(db);
  146731. }
  146732. #endif
  146733. /* Load automatic extensions - extensions that have been registered
  146734. ** using the sqlite3_automatic_extension() API.
  146735. */
  146736. if( rc==SQLITE_OK ){
  146737. sqlite3AutoLoadExtensions(db);
  146738. rc = sqlite3_errcode(db);
  146739. if( rc!=SQLITE_OK ){
  146740. goto opendb_out;
  146741. }
  146742. }
  146743. #ifdef SQLITE_ENABLE_FTS1
  146744. if( !db->mallocFailed ){
  146745. extern int sqlite3Fts1Init(sqlite3*);
  146746. rc = sqlite3Fts1Init(db);
  146747. }
  146748. #endif
  146749. #ifdef SQLITE_ENABLE_FTS2
  146750. if( !db->mallocFailed && rc==SQLITE_OK ){
  146751. extern int sqlite3Fts2Init(sqlite3*);
  146752. rc = sqlite3Fts2Init(db);
  146753. }
  146754. #endif
  146755. #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  146756. if( !db->mallocFailed && rc==SQLITE_OK ){
  146757. rc = sqlite3Fts3Init(db);
  146758. }
  146759. #endif
  146760. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  146761. if( !db->mallocFailed && rc==SQLITE_OK ){
  146762. rc = sqlite3IcuInit(db);
  146763. }
  146764. #endif
  146765. #ifdef SQLITE_ENABLE_RTREE
  146766. if( !db->mallocFailed && rc==SQLITE_OK){
  146767. rc = sqlite3RtreeInit(db);
  146768. }
  146769. #endif
  146770. #ifdef SQLITE_ENABLE_DBPAGE_VTAB
  146771. if( !db->mallocFailed && rc==SQLITE_OK){
  146772. rc = sqlite3DbpageRegister(db);
  146773. }
  146774. #endif
  146775. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  146776. if( !db->mallocFailed && rc==SQLITE_OK){
  146777. rc = sqlite3DbstatRegister(db);
  146778. }
  146779. #endif
  146780. #ifdef SQLITE_ENABLE_JSON1
  146781. if( !db->mallocFailed && rc==SQLITE_OK){
  146782. rc = sqlite3Json1Init(db);
  146783. }
  146784. #endif
  146785. #ifdef SQLITE_ENABLE_STMTVTAB
  146786. if( !db->mallocFailed && rc==SQLITE_OK){
  146787. rc = sqlite3StmtVtabInit(db);
  146788. }
  146789. #endif
  146790. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  146791. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  146792. ** mode. Doing nothing at all also makes NORMAL the default.
  146793. */
  146794. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  146795. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  146796. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  146797. SQLITE_DEFAULT_LOCKING_MODE);
  146798. #endif
  146799. if( rc ) sqlite3Error(db, rc);
  146800. /* Enable the lookaside-malloc subsystem */
  146801. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  146802. sqlite3GlobalConfig.nLookaside);
  146803. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  146804. opendb_out:
  146805. if( db ){
  146806. assert( db->mutex!=0 || isThreadsafe==0
  146807. || sqlite3GlobalConfig.bFullMutex==0 );
  146808. sqlite3_mutex_leave(db->mutex);
  146809. }
  146810. rc = sqlite3_errcode(db);
  146811. assert( db!=0 || rc==SQLITE_NOMEM );
  146812. if( rc==SQLITE_NOMEM ){
  146813. sqlite3_close(db);
  146814. db = 0;
  146815. }else if( rc!=SQLITE_OK ){
  146816. db->magic = SQLITE_MAGIC_SICK;
  146817. }
  146818. *ppDb = db;
  146819. #ifdef SQLITE_ENABLE_SQLLOG
  146820. if( sqlite3GlobalConfig.xSqllog ){
  146821. /* Opening a db handle. Fourth parameter is passed 0. */
  146822. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  146823. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  146824. }
  146825. #endif
  146826. #if defined(SQLITE_HAS_CODEC)
  146827. if( rc==SQLITE_OK ){
  146828. const char *zKey;
  146829. if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
  146830. u8 iByte;
  146831. int i;
  146832. char zDecoded[40];
  146833. for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
  146834. iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
  146835. if( (i&1)!=0 ) zDecoded[i/2] = iByte;
  146836. }
  146837. sqlite3_key_v2(db, 0, zDecoded, i/2);
  146838. }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
  146839. sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
  146840. }
  146841. }
  146842. #endif
  146843. sqlite3_free(zOpen);
  146844. return rc & 0xff;
  146845. }
  146846. /*
  146847. ** Open a new database handle.
  146848. */
  146849. SQLITE_API int sqlite3_open(
  146850. const char *zFilename,
  146851. sqlite3 **ppDb
  146852. ){
  146853. return openDatabase(zFilename, ppDb,
  146854. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  146855. }
  146856. SQLITE_API int sqlite3_open_v2(
  146857. const char *filename, /* Database filename (UTF-8) */
  146858. sqlite3 **ppDb, /* OUT: SQLite db handle */
  146859. int flags, /* Flags */
  146860. const char *zVfs /* Name of VFS module to use */
  146861. ){
  146862. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  146863. }
  146864. #ifndef SQLITE_OMIT_UTF16
  146865. /*
  146866. ** Open a new database handle.
  146867. */
  146868. SQLITE_API int sqlite3_open16(
  146869. const void *zFilename,
  146870. sqlite3 **ppDb
  146871. ){
  146872. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  146873. sqlite3_value *pVal;
  146874. int rc;
  146875. #ifdef SQLITE_ENABLE_API_ARMOR
  146876. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  146877. #endif
  146878. *ppDb = 0;
  146879. #ifndef SQLITE_OMIT_AUTOINIT
  146880. rc = sqlite3_initialize();
  146881. if( rc ) return rc;
  146882. #endif
  146883. if( zFilename==0 ) zFilename = "\000\000";
  146884. pVal = sqlite3ValueNew(0);
  146885. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  146886. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  146887. if( zFilename8 ){
  146888. rc = openDatabase(zFilename8, ppDb,
  146889. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  146890. assert( *ppDb || rc==SQLITE_NOMEM );
  146891. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  146892. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  146893. }
  146894. }else{
  146895. rc = SQLITE_NOMEM_BKPT;
  146896. }
  146897. sqlite3ValueFree(pVal);
  146898. return rc & 0xff;
  146899. }
  146900. #endif /* SQLITE_OMIT_UTF16 */
  146901. /*
  146902. ** Register a new collation sequence with the database handle db.
  146903. */
  146904. SQLITE_API int sqlite3_create_collation(
  146905. sqlite3* db,
  146906. const char *zName,
  146907. int enc,
  146908. void* pCtx,
  146909. int(*xCompare)(void*,int,const void*,int,const void*)
  146910. ){
  146911. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  146912. }
  146913. /*
  146914. ** Register a new collation sequence with the database handle db.
  146915. */
  146916. SQLITE_API int sqlite3_create_collation_v2(
  146917. sqlite3* db,
  146918. const char *zName,
  146919. int enc,
  146920. void* pCtx,
  146921. int(*xCompare)(void*,int,const void*,int,const void*),
  146922. void(*xDel)(void*)
  146923. ){
  146924. int rc;
  146925. #ifdef SQLITE_ENABLE_API_ARMOR
  146926. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  146927. #endif
  146928. sqlite3_mutex_enter(db->mutex);
  146929. assert( !db->mallocFailed );
  146930. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  146931. rc = sqlite3ApiExit(db, rc);
  146932. sqlite3_mutex_leave(db->mutex);
  146933. return rc;
  146934. }
  146935. #ifndef SQLITE_OMIT_UTF16
  146936. /*
  146937. ** Register a new collation sequence with the database handle db.
  146938. */
  146939. SQLITE_API int sqlite3_create_collation16(
  146940. sqlite3* db,
  146941. const void *zName,
  146942. int enc,
  146943. void* pCtx,
  146944. int(*xCompare)(void*,int,const void*,int,const void*)
  146945. ){
  146946. int rc = SQLITE_OK;
  146947. char *zName8;
  146948. #ifdef SQLITE_ENABLE_API_ARMOR
  146949. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  146950. #endif
  146951. sqlite3_mutex_enter(db->mutex);
  146952. assert( !db->mallocFailed );
  146953. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  146954. if( zName8 ){
  146955. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  146956. sqlite3DbFree(db, zName8);
  146957. }
  146958. rc = sqlite3ApiExit(db, rc);
  146959. sqlite3_mutex_leave(db->mutex);
  146960. return rc;
  146961. }
  146962. #endif /* SQLITE_OMIT_UTF16 */
  146963. /*
  146964. ** Register a collation sequence factory callback with the database handle
  146965. ** db. Replace any previously installed collation sequence factory.
  146966. */
  146967. SQLITE_API int sqlite3_collation_needed(
  146968. sqlite3 *db,
  146969. void *pCollNeededArg,
  146970. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  146971. ){
  146972. #ifdef SQLITE_ENABLE_API_ARMOR
  146973. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  146974. #endif
  146975. sqlite3_mutex_enter(db->mutex);
  146976. db->xCollNeeded = xCollNeeded;
  146977. db->xCollNeeded16 = 0;
  146978. db->pCollNeededArg = pCollNeededArg;
  146979. sqlite3_mutex_leave(db->mutex);
  146980. return SQLITE_OK;
  146981. }
  146982. #ifndef SQLITE_OMIT_UTF16
  146983. /*
  146984. ** Register a collation sequence factory callback with the database handle
  146985. ** db. Replace any previously installed collation sequence factory.
  146986. */
  146987. SQLITE_API int sqlite3_collation_needed16(
  146988. sqlite3 *db,
  146989. void *pCollNeededArg,
  146990. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  146991. ){
  146992. #ifdef SQLITE_ENABLE_API_ARMOR
  146993. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  146994. #endif
  146995. sqlite3_mutex_enter(db->mutex);
  146996. db->xCollNeeded = 0;
  146997. db->xCollNeeded16 = xCollNeeded16;
  146998. db->pCollNeededArg = pCollNeededArg;
  146999. sqlite3_mutex_leave(db->mutex);
  147000. return SQLITE_OK;
  147001. }
  147002. #endif /* SQLITE_OMIT_UTF16 */
  147003. #ifndef SQLITE_OMIT_DEPRECATED
  147004. /*
  147005. ** This function is now an anachronism. It used to be used to recover from a
  147006. ** malloc() failure, but SQLite now does this automatically.
  147007. */
  147008. SQLITE_API int sqlite3_global_recover(void){
  147009. return SQLITE_OK;
  147010. }
  147011. #endif
  147012. /*
  147013. ** Test to see whether or not the database connection is in autocommit
  147014. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  147015. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  147016. ** by the next COMMIT or ROLLBACK.
  147017. */
  147018. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  147019. #ifdef SQLITE_ENABLE_API_ARMOR
  147020. if( !sqlite3SafetyCheckOk(db) ){
  147021. (void)SQLITE_MISUSE_BKPT;
  147022. return 0;
  147023. }
  147024. #endif
  147025. return db->autoCommit;
  147026. }
  147027. /*
  147028. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  147029. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
  147030. ** constants. They serve two purposes:
  147031. **
  147032. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  147033. ** to detect when version error conditions occurs.
  147034. **
  147035. ** 2. Invoke sqlite3_log() to provide the source code location where
  147036. ** a low-level error is first detected.
  147037. */
  147038. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){
  147039. sqlite3_log(iErr, "%s at line %d of [%.10s]",
  147040. zType, lineno, 20+sqlite3_sourceid());
  147041. return iErr;
  147042. }
  147043. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  147044. testcase( sqlite3GlobalConfig.xLog!=0 );
  147045. return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
  147046. }
  147047. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  147048. testcase( sqlite3GlobalConfig.xLog!=0 );
  147049. return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
  147050. }
  147051. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  147052. testcase( sqlite3GlobalConfig.xLog!=0 );
  147053. return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
  147054. }
  147055. #ifdef SQLITE_DEBUG
  147056. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
  147057. char zMsg[100];
  147058. sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
  147059. testcase( sqlite3GlobalConfig.xLog!=0 );
  147060. return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  147061. }
  147062. SQLITE_PRIVATE int sqlite3NomemError(int lineno){
  147063. testcase( sqlite3GlobalConfig.xLog!=0 );
  147064. return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
  147065. }
  147066. SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
  147067. testcase( sqlite3GlobalConfig.xLog!=0 );
  147068. return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
  147069. }
  147070. #endif
  147071. #ifndef SQLITE_OMIT_DEPRECATED
  147072. /*
  147073. ** This is a convenience routine that makes sure that all thread-specific
  147074. ** data for this thread has been deallocated.
  147075. **
  147076. ** SQLite no longer uses thread-specific data so this routine is now a
  147077. ** no-op. It is retained for historical compatibility.
  147078. */
  147079. SQLITE_API void sqlite3_thread_cleanup(void){
  147080. }
  147081. #endif
  147082. /*
  147083. ** Return meta information about a specific column of a database table.
  147084. ** See comment in sqlite3.h (sqlite.h.in) for details.
  147085. */
  147086. SQLITE_API int sqlite3_table_column_metadata(
  147087. sqlite3 *db, /* Connection handle */
  147088. const char *zDbName, /* Database name or NULL */
  147089. const char *zTableName, /* Table name */
  147090. const char *zColumnName, /* Column name */
  147091. char const **pzDataType, /* OUTPUT: Declared data type */
  147092. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  147093. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  147094. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  147095. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  147096. ){
  147097. int rc;
  147098. char *zErrMsg = 0;
  147099. Table *pTab = 0;
  147100. Column *pCol = 0;
  147101. int iCol = 0;
  147102. char const *zDataType = 0;
  147103. char const *zCollSeq = 0;
  147104. int notnull = 0;
  147105. int primarykey = 0;
  147106. int autoinc = 0;
  147107. #ifdef SQLITE_ENABLE_API_ARMOR
  147108. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  147109. return SQLITE_MISUSE_BKPT;
  147110. }
  147111. #endif
  147112. /* Ensure the database schema has been loaded */
  147113. sqlite3_mutex_enter(db->mutex);
  147114. sqlite3BtreeEnterAll(db);
  147115. rc = sqlite3Init(db, &zErrMsg);
  147116. if( SQLITE_OK!=rc ){
  147117. goto error_out;
  147118. }
  147119. /* Locate the table in question */
  147120. pTab = sqlite3FindTable(db, zTableName, zDbName);
  147121. if( !pTab || pTab->pSelect ){
  147122. pTab = 0;
  147123. goto error_out;
  147124. }
  147125. /* Find the column for which info is requested */
  147126. if( zColumnName==0 ){
  147127. /* Query for existance of table only */
  147128. }else{
  147129. for(iCol=0; iCol<pTab->nCol; iCol++){
  147130. pCol = &pTab->aCol[iCol];
  147131. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  147132. break;
  147133. }
  147134. }
  147135. if( iCol==pTab->nCol ){
  147136. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  147137. iCol = pTab->iPKey;
  147138. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  147139. }else{
  147140. pTab = 0;
  147141. goto error_out;
  147142. }
  147143. }
  147144. }
  147145. /* The following block stores the meta information that will be returned
  147146. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  147147. ** and autoinc. At this point there are two possibilities:
  147148. **
  147149. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  147150. ** and there is no explicitly declared IPK column.
  147151. **
  147152. ** 2. The table is not a view and the column name identified an
  147153. ** explicitly declared column. Copy meta information from *pCol.
  147154. */
  147155. if( pCol ){
  147156. zDataType = sqlite3ColumnType(pCol,0);
  147157. zCollSeq = pCol->zColl;
  147158. notnull = pCol->notNull!=0;
  147159. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  147160. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  147161. }else{
  147162. zDataType = "INTEGER";
  147163. primarykey = 1;
  147164. }
  147165. if( !zCollSeq ){
  147166. zCollSeq = sqlite3StrBINARY;
  147167. }
  147168. error_out:
  147169. sqlite3BtreeLeaveAll(db);
  147170. /* Whether the function call succeeded or failed, set the output parameters
  147171. ** to whatever their local counterparts contain. If an error did occur,
  147172. ** this has the effect of zeroing all output parameters.
  147173. */
  147174. if( pzDataType ) *pzDataType = zDataType;
  147175. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  147176. if( pNotNull ) *pNotNull = notnull;
  147177. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  147178. if( pAutoinc ) *pAutoinc = autoinc;
  147179. if( SQLITE_OK==rc && !pTab ){
  147180. sqlite3DbFree(db, zErrMsg);
  147181. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  147182. zColumnName);
  147183. rc = SQLITE_ERROR;
  147184. }
  147185. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  147186. sqlite3DbFree(db, zErrMsg);
  147187. rc = sqlite3ApiExit(db, rc);
  147188. sqlite3_mutex_leave(db->mutex);
  147189. return rc;
  147190. }
  147191. /*
  147192. ** Sleep for a little while. Return the amount of time slept.
  147193. */
  147194. SQLITE_API int sqlite3_sleep(int ms){
  147195. sqlite3_vfs *pVfs;
  147196. int rc;
  147197. pVfs = sqlite3_vfs_find(0);
  147198. if( pVfs==0 ) return 0;
  147199. /* This function works in milliseconds, but the underlying OsSleep()
  147200. ** API uses microseconds. Hence the 1000's.
  147201. */
  147202. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  147203. return rc;
  147204. }
  147205. /*
  147206. ** Enable or disable the extended result codes.
  147207. */
  147208. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  147209. #ifdef SQLITE_ENABLE_API_ARMOR
  147210. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  147211. #endif
  147212. sqlite3_mutex_enter(db->mutex);
  147213. db->errMask = onoff ? 0xffffffff : 0xff;
  147214. sqlite3_mutex_leave(db->mutex);
  147215. return SQLITE_OK;
  147216. }
  147217. /*
  147218. ** Invoke the xFileControl method on a particular database.
  147219. */
  147220. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  147221. int rc = SQLITE_ERROR;
  147222. Btree *pBtree;
  147223. #ifdef SQLITE_ENABLE_API_ARMOR
  147224. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  147225. #endif
  147226. sqlite3_mutex_enter(db->mutex);
  147227. pBtree = sqlite3DbNameToBtree(db, zDbName);
  147228. if( pBtree ){
  147229. Pager *pPager;
  147230. sqlite3_file *fd;
  147231. sqlite3BtreeEnter(pBtree);
  147232. pPager = sqlite3BtreePager(pBtree);
  147233. assert( pPager!=0 );
  147234. fd = sqlite3PagerFile(pPager);
  147235. assert( fd!=0 );
  147236. if( op==SQLITE_FCNTL_FILE_POINTER ){
  147237. *(sqlite3_file**)pArg = fd;
  147238. rc = SQLITE_OK;
  147239. }else if( op==SQLITE_FCNTL_VFS_POINTER ){
  147240. *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
  147241. rc = SQLITE_OK;
  147242. }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
  147243. *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
  147244. rc = SQLITE_OK;
  147245. }else if( op==SQLITE_FCNTL_DATA_VERSION ){
  147246. *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
  147247. rc = SQLITE_OK;
  147248. }else{
  147249. rc = sqlite3OsFileControl(fd, op, pArg);
  147250. }
  147251. sqlite3BtreeLeave(pBtree);
  147252. }
  147253. sqlite3_mutex_leave(db->mutex);
  147254. return rc;
  147255. }
  147256. /*
  147257. ** Interface to the testing logic.
  147258. */
  147259. SQLITE_API int sqlite3_test_control(int op, ...){
  147260. int rc = 0;
  147261. #ifdef SQLITE_UNTESTABLE
  147262. UNUSED_PARAMETER(op);
  147263. #else
  147264. va_list ap;
  147265. va_start(ap, op);
  147266. switch( op ){
  147267. /*
  147268. ** Save the current state of the PRNG.
  147269. */
  147270. case SQLITE_TESTCTRL_PRNG_SAVE: {
  147271. sqlite3PrngSaveState();
  147272. break;
  147273. }
  147274. /*
  147275. ** Restore the state of the PRNG to the last state saved using
  147276. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  147277. ** this verb acts like PRNG_RESET.
  147278. */
  147279. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  147280. sqlite3PrngRestoreState();
  147281. break;
  147282. }
  147283. /*
  147284. ** Reset the PRNG back to its uninitialized state. The next call
  147285. ** to sqlite3_randomness() will reseed the PRNG using a single call
  147286. ** to the xRandomness method of the default VFS.
  147287. */
  147288. case SQLITE_TESTCTRL_PRNG_RESET: {
  147289. sqlite3_randomness(0,0);
  147290. break;
  147291. }
  147292. /*
  147293. ** sqlite3_test_control(BITVEC_TEST, size, program)
  147294. **
  147295. ** Run a test against a Bitvec object of size. The program argument
  147296. ** is an array of integers that defines the test. Return -1 on a
  147297. ** memory allocation error, 0 on success, or non-zero for an error.
  147298. ** See the sqlite3BitvecBuiltinTest() for additional information.
  147299. */
  147300. case SQLITE_TESTCTRL_BITVEC_TEST: {
  147301. int sz = va_arg(ap, int);
  147302. int *aProg = va_arg(ap, int*);
  147303. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  147304. break;
  147305. }
  147306. /*
  147307. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  147308. **
  147309. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  147310. ** if xCallback is not NULL.
  147311. **
  147312. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  147313. ** is called immediately after installing the new callback and the return
  147314. ** value from sqlite3FaultSim(0) becomes the return from
  147315. ** sqlite3_test_control().
  147316. */
  147317. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  147318. /* MSVC is picky about pulling func ptrs from va lists.
  147319. ** http://support.microsoft.com/kb/47961
  147320. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  147321. */
  147322. typedef int(*TESTCALLBACKFUNC_t)(int);
  147323. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  147324. rc = sqlite3FaultSim(0);
  147325. break;
  147326. }
  147327. /*
  147328. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  147329. **
  147330. ** Register hooks to call to indicate which malloc() failures
  147331. ** are benign.
  147332. */
  147333. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  147334. typedef void (*void_function)(void);
  147335. void_function xBenignBegin;
  147336. void_function xBenignEnd;
  147337. xBenignBegin = va_arg(ap, void_function);
  147338. xBenignEnd = va_arg(ap, void_function);
  147339. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  147340. break;
  147341. }
  147342. /*
  147343. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  147344. **
  147345. ** Set the PENDING byte to the value in the argument, if X>0.
  147346. ** Make no changes if X==0. Return the value of the pending byte
  147347. ** as it existing before this routine was called.
  147348. **
  147349. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  147350. ** an incompatible database file format. Changing the PENDING byte
  147351. ** while any database connection is open results in undefined and
  147352. ** deleterious behavior.
  147353. */
  147354. case SQLITE_TESTCTRL_PENDING_BYTE: {
  147355. rc = PENDING_BYTE;
  147356. #ifndef SQLITE_OMIT_WSD
  147357. {
  147358. unsigned int newVal = va_arg(ap, unsigned int);
  147359. if( newVal ) sqlite3PendingByte = newVal;
  147360. }
  147361. #endif
  147362. break;
  147363. }
  147364. /*
  147365. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  147366. **
  147367. ** This action provides a run-time test to see whether or not
  147368. ** assert() was enabled at compile-time. If X is true and assert()
  147369. ** is enabled, then the return value is true. If X is true and
  147370. ** assert() is disabled, then the return value is zero. If X is
  147371. ** false and assert() is enabled, then the assertion fires and the
  147372. ** process aborts. If X is false and assert() is disabled, then the
  147373. ** return value is zero.
  147374. */
  147375. case SQLITE_TESTCTRL_ASSERT: {
  147376. volatile int x = 0;
  147377. assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
  147378. rc = x;
  147379. break;
  147380. }
  147381. /*
  147382. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  147383. **
  147384. ** This action provides a run-time test to see how the ALWAYS and
  147385. ** NEVER macros were defined at compile-time.
  147386. **
  147387. ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
  147388. **
  147389. ** The recommended test is X==2. If the return value is 2, that means
  147390. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  147391. ** default setting. If the return value is 1, then ALWAYS() is either
  147392. ** hard-coded to true or else it asserts if its argument is false.
  147393. ** The first behavior (hard-coded to true) is the case if
  147394. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  147395. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  147396. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  147397. **
  147398. ** The run-time test procedure might look something like this:
  147399. **
  147400. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  147401. ** // ALWAYS() and NEVER() are no-op pass-through macros
  147402. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  147403. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  147404. ** }else{
  147405. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  147406. ** }
  147407. */
  147408. case SQLITE_TESTCTRL_ALWAYS: {
  147409. int x = va_arg(ap,int);
  147410. rc = x ? ALWAYS(x) : 0;
  147411. break;
  147412. }
  147413. /*
  147414. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  147415. **
  147416. ** The integer returned reveals the byte-order of the computer on which
  147417. ** SQLite is running:
  147418. **
  147419. ** 1 big-endian, determined at run-time
  147420. ** 10 little-endian, determined at run-time
  147421. ** 432101 big-endian, determined at compile-time
  147422. ** 123410 little-endian, determined at compile-time
  147423. */
  147424. case SQLITE_TESTCTRL_BYTEORDER: {
  147425. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  147426. break;
  147427. }
  147428. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  147429. **
  147430. ** Set the nReserve size to N for the main database on the database
  147431. ** connection db.
  147432. */
  147433. case SQLITE_TESTCTRL_RESERVE: {
  147434. sqlite3 *db = va_arg(ap, sqlite3*);
  147435. int x = va_arg(ap,int);
  147436. sqlite3_mutex_enter(db->mutex);
  147437. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  147438. sqlite3_mutex_leave(db->mutex);
  147439. break;
  147440. }
  147441. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  147442. **
  147443. ** Enable or disable various optimizations for testing purposes. The
  147444. ** argument N is a bitmask of optimizations to be disabled. For normal
  147445. ** operation N should be 0. The idea is that a test program (like the
  147446. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  147447. ** with various optimizations disabled to verify that the same answer
  147448. ** is obtained in every case.
  147449. */
  147450. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  147451. sqlite3 *db = va_arg(ap, sqlite3*);
  147452. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  147453. break;
  147454. }
  147455. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  147456. **
  147457. ** If parameter onoff is non-zero, subsequent calls to localtime()
  147458. ** and its variants fail. If onoff is zero, undo this setting.
  147459. */
  147460. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  147461. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  147462. break;
  147463. }
  147464. /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCS, int onoff);
  147465. **
  147466. ** If parameter onoff is non-zero, internal-use-only SQL functions
  147467. ** are visible to ordinary SQL. This is useful for testing but is
  147468. ** unsafe because invalid parameters to those internal-use-only functions
  147469. ** can result in crashes or segfaults.
  147470. */
  147471. case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
  147472. sqlite3GlobalConfig.bInternalFunctions = va_arg(ap, int);
  147473. break;
  147474. }
  147475. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  147476. **
  147477. ** Set or clear a flag that indicates that the database file is always well-
  147478. ** formed and never corrupt. This flag is clear by default, indicating that
  147479. ** database files might have arbitrary corruption. Setting the flag during
  147480. ** testing causes certain assert() statements in the code to be activated
  147481. ** that demonstrat invariants on well-formed database files.
  147482. */
  147483. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  147484. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  147485. break;
  147486. }
  147487. /* Set the threshold at which OP_Once counters reset back to zero.
  147488. ** By default this is 0x7ffffffe (over 2 billion), but that value is
  147489. ** too big to test in a reasonable amount of time, so this control is
  147490. ** provided to set a small and easily reachable reset value.
  147491. */
  147492. case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
  147493. sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
  147494. break;
  147495. }
  147496. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  147497. **
  147498. ** Set the VDBE coverage callback function to xCallback with context
  147499. ** pointer ptr.
  147500. */
  147501. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  147502. #ifdef SQLITE_VDBE_COVERAGE
  147503. typedef void (*branch_callback)(void*,unsigned int,
  147504. unsigned char,unsigned char);
  147505. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  147506. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  147507. #endif
  147508. break;
  147509. }
  147510. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  147511. case SQLITE_TESTCTRL_SORTER_MMAP: {
  147512. sqlite3 *db = va_arg(ap, sqlite3*);
  147513. db->nMaxSorterMmap = va_arg(ap, int);
  147514. break;
  147515. }
  147516. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  147517. **
  147518. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  147519. ** not.
  147520. */
  147521. case SQLITE_TESTCTRL_ISINIT: {
  147522. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  147523. break;
  147524. }
  147525. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  147526. **
  147527. ** This test control is used to create imposter tables. "db" is a pointer
  147528. ** to the database connection. dbName is the database name (ex: "main" or
  147529. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  147530. ** or off. "tnum" is the root page of the b-tree to which the imposter
  147531. ** table should connect.
  147532. **
  147533. ** Enable imposter mode only when the schema has already been parsed. Then
  147534. ** run a single CREATE TABLE statement to construct the imposter table in
  147535. ** the parsed schema. Then turn imposter mode back off again.
  147536. **
  147537. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  147538. ** the schema to be reparsed the next time it is needed. This has the
  147539. ** effect of erasing all imposter tables.
  147540. */
  147541. case SQLITE_TESTCTRL_IMPOSTER: {
  147542. sqlite3 *db = va_arg(ap, sqlite3*);
  147543. sqlite3_mutex_enter(db->mutex);
  147544. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  147545. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  147546. db->init.newTnum = va_arg(ap,int);
  147547. if( db->init.busy==0 && db->init.newTnum>0 ){
  147548. sqlite3ResetAllSchemasOfConnection(db);
  147549. }
  147550. sqlite3_mutex_leave(db->mutex);
  147551. break;
  147552. }
  147553. #if defined(YYCOVERAGE)
  147554. /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
  147555. **
  147556. ** This test control (only available when SQLite is compiled with
  147557. ** -DYYCOVERAGE) writes a report onto "out" that shows all
  147558. ** state/lookahead combinations in the parser state machine
  147559. ** which are never exercised. If any state is missed, make the
  147560. ** return code SQLITE_ERROR.
  147561. */
  147562. case SQLITE_TESTCTRL_PARSER_COVERAGE: {
  147563. FILE *out = va_arg(ap, FILE*);
  147564. if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
  147565. break;
  147566. }
  147567. #endif /* defined(YYCOVERAGE) */
  147568. }
  147569. va_end(ap);
  147570. #endif /* SQLITE_UNTESTABLE */
  147571. return rc;
  147572. }
  147573. /*
  147574. ** This is a utility routine, useful to VFS implementations, that checks
  147575. ** to see if a database file was a URI that contained a specific query
  147576. ** parameter, and if so obtains the value of the query parameter.
  147577. **
  147578. ** The zFilename argument is the filename pointer passed into the xOpen()
  147579. ** method of a VFS implementation. The zParam argument is the name of the
  147580. ** query parameter we seek. This routine returns the value of the zParam
  147581. ** parameter if it exists. If the parameter does not exist, this routine
  147582. ** returns a NULL pointer.
  147583. */
  147584. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  147585. if( zFilename==0 || zParam==0 ) return 0;
  147586. zFilename += sqlite3Strlen30(zFilename) + 1;
  147587. while( zFilename[0] ){
  147588. int x = strcmp(zFilename, zParam);
  147589. zFilename += sqlite3Strlen30(zFilename) + 1;
  147590. if( x==0 ) return zFilename;
  147591. zFilename += sqlite3Strlen30(zFilename) + 1;
  147592. }
  147593. return 0;
  147594. }
  147595. /*
  147596. ** Return a boolean value for a query parameter.
  147597. */
  147598. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  147599. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  147600. bDflt = bDflt!=0;
  147601. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  147602. }
  147603. /*
  147604. ** Return a 64-bit integer value for a query parameter.
  147605. */
  147606. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  147607. const char *zFilename, /* Filename as passed to xOpen */
  147608. const char *zParam, /* URI parameter sought */
  147609. sqlite3_int64 bDflt /* return if parameter is missing */
  147610. ){
  147611. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  147612. sqlite3_int64 v;
  147613. if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
  147614. bDflt = v;
  147615. }
  147616. return bDflt;
  147617. }
  147618. /*
  147619. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  147620. */
  147621. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  147622. int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
  147623. return iDb<0 ? 0 : db->aDb[iDb].pBt;
  147624. }
  147625. /*
  147626. ** Return the filename of the database associated with a database
  147627. ** connection.
  147628. */
  147629. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  147630. Btree *pBt;
  147631. #ifdef SQLITE_ENABLE_API_ARMOR
  147632. if( !sqlite3SafetyCheckOk(db) ){
  147633. (void)SQLITE_MISUSE_BKPT;
  147634. return 0;
  147635. }
  147636. #endif
  147637. pBt = sqlite3DbNameToBtree(db, zDbName);
  147638. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  147639. }
  147640. /*
  147641. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  147642. ** no such database exists.
  147643. */
  147644. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  147645. Btree *pBt;
  147646. #ifdef SQLITE_ENABLE_API_ARMOR
  147647. if( !sqlite3SafetyCheckOk(db) ){
  147648. (void)SQLITE_MISUSE_BKPT;
  147649. return -1;
  147650. }
  147651. #endif
  147652. pBt = sqlite3DbNameToBtree(db, zDbName);
  147653. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  147654. }
  147655. #ifdef SQLITE_ENABLE_SNAPSHOT
  147656. /*
  147657. ** Obtain a snapshot handle for the snapshot of database zDb currently
  147658. ** being read by handle db.
  147659. */
  147660. SQLITE_API int sqlite3_snapshot_get(
  147661. sqlite3 *db,
  147662. const char *zDb,
  147663. sqlite3_snapshot **ppSnapshot
  147664. ){
  147665. int rc = SQLITE_ERROR;
  147666. #ifndef SQLITE_OMIT_WAL
  147667. #ifdef SQLITE_ENABLE_API_ARMOR
  147668. if( !sqlite3SafetyCheckOk(db) ){
  147669. return SQLITE_MISUSE_BKPT;
  147670. }
  147671. #endif
  147672. sqlite3_mutex_enter(db->mutex);
  147673. if( db->autoCommit==0 ){
  147674. int iDb = sqlite3FindDbName(db, zDb);
  147675. if( iDb==0 || iDb>1 ){
  147676. Btree *pBt = db->aDb[iDb].pBt;
  147677. if( 0==sqlite3BtreeIsInTrans(pBt) ){
  147678. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  147679. if( rc==SQLITE_OK ){
  147680. rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
  147681. }
  147682. }
  147683. }
  147684. }
  147685. sqlite3_mutex_leave(db->mutex);
  147686. #endif /* SQLITE_OMIT_WAL */
  147687. return rc;
  147688. }
  147689. /*
  147690. ** Open a read-transaction on the snapshot idendified by pSnapshot.
  147691. */
  147692. SQLITE_API int sqlite3_snapshot_open(
  147693. sqlite3 *db,
  147694. const char *zDb,
  147695. sqlite3_snapshot *pSnapshot
  147696. ){
  147697. int rc = SQLITE_ERROR;
  147698. #ifndef SQLITE_OMIT_WAL
  147699. #ifdef SQLITE_ENABLE_API_ARMOR
  147700. if( !sqlite3SafetyCheckOk(db) ){
  147701. return SQLITE_MISUSE_BKPT;
  147702. }
  147703. #endif
  147704. sqlite3_mutex_enter(db->mutex);
  147705. if( db->autoCommit==0 ){
  147706. int iDb;
  147707. iDb = sqlite3FindDbName(db, zDb);
  147708. if( iDb==0 || iDb>1 ){
  147709. Btree *pBt = db->aDb[iDb].pBt;
  147710. if( sqlite3BtreeIsInTrans(pBt)==0 ){
  147711. Pager *pPager = sqlite3BtreePager(pBt);
  147712. int bUnlock = 0;
  147713. if( sqlite3BtreeIsInReadTrans(pBt) ){
  147714. if( db->nVdbeActive==0 ){
  147715. rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
  147716. if( rc==SQLITE_OK ){
  147717. bUnlock = 1;
  147718. rc = sqlite3BtreeCommit(pBt);
  147719. }
  147720. }
  147721. }else{
  147722. rc = SQLITE_OK;
  147723. }
  147724. if( rc==SQLITE_OK ){
  147725. rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
  147726. }
  147727. if( rc==SQLITE_OK ){
  147728. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  147729. sqlite3PagerSnapshotOpen(pPager, 0);
  147730. }
  147731. if( bUnlock ){
  147732. sqlite3PagerSnapshotUnlock(pPager);
  147733. }
  147734. }
  147735. }
  147736. }
  147737. sqlite3_mutex_leave(db->mutex);
  147738. #endif /* SQLITE_OMIT_WAL */
  147739. return rc;
  147740. }
  147741. /*
  147742. ** Recover as many snapshots as possible from the wal file associated with
  147743. ** schema zDb of database db.
  147744. */
  147745. SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
  147746. int rc = SQLITE_ERROR;
  147747. int iDb;
  147748. #ifndef SQLITE_OMIT_WAL
  147749. #ifdef SQLITE_ENABLE_API_ARMOR
  147750. if( !sqlite3SafetyCheckOk(db) ){
  147751. return SQLITE_MISUSE_BKPT;
  147752. }
  147753. #endif
  147754. sqlite3_mutex_enter(db->mutex);
  147755. iDb = sqlite3FindDbName(db, zDb);
  147756. if( iDb==0 || iDb>1 ){
  147757. Btree *pBt = db->aDb[iDb].pBt;
  147758. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  147759. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  147760. if( rc==SQLITE_OK ){
  147761. rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
  147762. sqlite3BtreeCommit(pBt);
  147763. }
  147764. }
  147765. }
  147766. sqlite3_mutex_leave(db->mutex);
  147767. #endif /* SQLITE_OMIT_WAL */
  147768. return rc;
  147769. }
  147770. /*
  147771. ** Free a snapshot handle obtained from sqlite3_snapshot_get().
  147772. */
  147773. SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
  147774. sqlite3_free(pSnapshot);
  147775. }
  147776. #endif /* SQLITE_ENABLE_SNAPSHOT */
  147777. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  147778. /*
  147779. ** Given the name of a compile-time option, return true if that option
  147780. ** was used and false if not.
  147781. **
  147782. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  147783. ** is not required for a match.
  147784. */
  147785. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  147786. int i, n;
  147787. int nOpt;
  147788. const char **azCompileOpt;
  147789. #if SQLITE_ENABLE_API_ARMOR
  147790. if( zOptName==0 ){
  147791. (void)SQLITE_MISUSE_BKPT;
  147792. return 0;
  147793. }
  147794. #endif
  147795. azCompileOpt = sqlite3CompileOptions(&nOpt);
  147796. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  147797. n = sqlite3Strlen30(zOptName);
  147798. /* Since nOpt is normally in single digits, a linear search is
  147799. ** adequate. No need for a binary search. */
  147800. for(i=0; i<nOpt; i++){
  147801. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  147802. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  147803. ){
  147804. return 1;
  147805. }
  147806. }
  147807. return 0;
  147808. }
  147809. /*
  147810. ** Return the N-th compile-time option string. If N is out of range,
  147811. ** return a NULL pointer.
  147812. */
  147813. SQLITE_API const char *sqlite3_compileoption_get(int N){
  147814. int nOpt;
  147815. const char **azCompileOpt;
  147816. azCompileOpt = sqlite3CompileOptions(&nOpt);
  147817. if( N>=0 && N<nOpt ){
  147818. return azCompileOpt[N];
  147819. }
  147820. return 0;
  147821. }
  147822. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  147823. /************** End of main.c ************************************************/
  147824. /************** Begin file notify.c ******************************************/
  147825. /*
  147826. ** 2009 March 3
  147827. **
  147828. ** The author disclaims copyright to this source code. In place of
  147829. ** a legal notice, here is a blessing:
  147830. **
  147831. ** May you do good and not evil.
  147832. ** May you find forgiveness for yourself and forgive others.
  147833. ** May you share freely, never taking more than you give.
  147834. **
  147835. *************************************************************************
  147836. **
  147837. ** This file contains the implementation of the sqlite3_unlock_notify()
  147838. ** API method and its associated functionality.
  147839. */
  147840. /* #include "sqliteInt.h" */
  147841. /* #include "btreeInt.h" */
  147842. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  147843. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  147844. /*
  147845. ** Public interfaces:
  147846. **
  147847. ** sqlite3ConnectionBlocked()
  147848. ** sqlite3ConnectionUnlocked()
  147849. ** sqlite3ConnectionClosed()
  147850. ** sqlite3_unlock_notify()
  147851. */
  147852. #define assertMutexHeld() \
  147853. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  147854. /*
  147855. ** Head of a linked list of all sqlite3 objects created by this process
  147856. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  147857. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  147858. ** mutex is held.
  147859. */
  147860. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  147861. #ifndef NDEBUG
  147862. /*
  147863. ** This function is a complex assert() that verifies the following
  147864. ** properties of the blocked connections list:
  147865. **
  147866. ** 1) Each entry in the list has a non-NULL value for either
  147867. ** pUnlockConnection or pBlockingConnection, or both.
  147868. **
  147869. ** 2) All entries in the list that share a common value for
  147870. ** xUnlockNotify are grouped together.
  147871. **
  147872. ** 3) If the argument db is not NULL, then none of the entries in the
  147873. ** blocked connections list have pUnlockConnection or pBlockingConnection
  147874. ** set to db. This is used when closing connection db.
  147875. */
  147876. static void checkListProperties(sqlite3 *db){
  147877. sqlite3 *p;
  147878. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  147879. int seen = 0;
  147880. sqlite3 *p2;
  147881. /* Verify property (1) */
  147882. assert( p->pUnlockConnection || p->pBlockingConnection );
  147883. /* Verify property (2) */
  147884. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  147885. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  147886. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  147887. assert( db==0 || p->pUnlockConnection!=db );
  147888. assert( db==0 || p->pBlockingConnection!=db );
  147889. }
  147890. }
  147891. }
  147892. #else
  147893. # define checkListProperties(x)
  147894. #endif
  147895. /*
  147896. ** Remove connection db from the blocked connections list. If connection
  147897. ** db is not currently a part of the list, this function is a no-op.
  147898. */
  147899. static void removeFromBlockedList(sqlite3 *db){
  147900. sqlite3 **pp;
  147901. assertMutexHeld();
  147902. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  147903. if( *pp==db ){
  147904. *pp = (*pp)->pNextBlocked;
  147905. break;
  147906. }
  147907. }
  147908. }
  147909. /*
  147910. ** Add connection db to the blocked connections list. It is assumed
  147911. ** that it is not already a part of the list.
  147912. */
  147913. static void addToBlockedList(sqlite3 *db){
  147914. sqlite3 **pp;
  147915. assertMutexHeld();
  147916. for(
  147917. pp=&sqlite3BlockedList;
  147918. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  147919. pp=&(*pp)->pNextBlocked
  147920. );
  147921. db->pNextBlocked = *pp;
  147922. *pp = db;
  147923. }
  147924. /*
  147925. ** Obtain the STATIC_MASTER mutex.
  147926. */
  147927. static void enterMutex(void){
  147928. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  147929. checkListProperties(0);
  147930. }
  147931. /*
  147932. ** Release the STATIC_MASTER mutex.
  147933. */
  147934. static void leaveMutex(void){
  147935. assertMutexHeld();
  147936. checkListProperties(0);
  147937. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  147938. }
  147939. /*
  147940. ** Register an unlock-notify callback.
  147941. **
  147942. ** This is called after connection "db" has attempted some operation
  147943. ** but has received an SQLITE_LOCKED error because another connection
  147944. ** (call it pOther) in the same process was busy using the same shared
  147945. ** cache. pOther is found by looking at db->pBlockingConnection.
  147946. **
  147947. ** If there is no blocking connection, the callback is invoked immediately,
  147948. ** before this routine returns.
  147949. **
  147950. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  147951. ** a deadlock.
  147952. **
  147953. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  147954. ** its locks.
  147955. **
  147956. ** Each call to this routine overrides any prior callbacks registered
  147957. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  147958. ** cancelled.
  147959. */
  147960. SQLITE_API int sqlite3_unlock_notify(
  147961. sqlite3 *db,
  147962. void (*xNotify)(void **, int),
  147963. void *pArg
  147964. ){
  147965. int rc = SQLITE_OK;
  147966. sqlite3_mutex_enter(db->mutex);
  147967. enterMutex();
  147968. if( xNotify==0 ){
  147969. removeFromBlockedList(db);
  147970. db->pBlockingConnection = 0;
  147971. db->pUnlockConnection = 0;
  147972. db->xUnlockNotify = 0;
  147973. db->pUnlockArg = 0;
  147974. }else if( 0==db->pBlockingConnection ){
  147975. /* The blocking transaction has been concluded. Or there never was a
  147976. ** blocking transaction. In either case, invoke the notify callback
  147977. ** immediately.
  147978. */
  147979. xNotify(&pArg, 1);
  147980. }else{
  147981. sqlite3 *p;
  147982. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  147983. if( p ){
  147984. rc = SQLITE_LOCKED; /* Deadlock detected. */
  147985. }else{
  147986. db->pUnlockConnection = db->pBlockingConnection;
  147987. db->xUnlockNotify = xNotify;
  147988. db->pUnlockArg = pArg;
  147989. removeFromBlockedList(db);
  147990. addToBlockedList(db);
  147991. }
  147992. }
  147993. leaveMutex();
  147994. assert( !db->mallocFailed );
  147995. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  147996. sqlite3_mutex_leave(db->mutex);
  147997. return rc;
  147998. }
  147999. /*
  148000. ** This function is called while stepping or preparing a statement
  148001. ** associated with connection db. The operation will return SQLITE_LOCKED
  148002. ** to the user because it requires a lock that will not be available
  148003. ** until connection pBlocker concludes its current transaction.
  148004. */
  148005. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  148006. enterMutex();
  148007. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  148008. addToBlockedList(db);
  148009. }
  148010. db->pBlockingConnection = pBlocker;
  148011. leaveMutex();
  148012. }
  148013. /*
  148014. ** This function is called when
  148015. ** the transaction opened by database db has just finished. Locks held
  148016. ** by database connection db have been released.
  148017. **
  148018. ** This function loops through each entry in the blocked connections
  148019. ** list and does the following:
  148020. **
  148021. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  148022. ** set to db, then set pBlockingConnection=0.
  148023. **
  148024. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  148025. ** set to db, then invoke the configured unlock-notify callback and
  148026. ** set pUnlockConnection=0.
  148027. **
  148028. ** 3) If the two steps above mean that pBlockingConnection==0 and
  148029. ** pUnlockConnection==0, remove the entry from the blocked connections
  148030. ** list.
  148031. */
  148032. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  148033. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  148034. int nArg = 0; /* Number of entries in aArg[] */
  148035. sqlite3 **pp; /* Iterator variable */
  148036. void **aArg; /* Arguments to the unlock callback */
  148037. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  148038. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  148039. aArg = aStatic;
  148040. enterMutex(); /* Enter STATIC_MASTER mutex */
  148041. /* This loop runs once for each entry in the blocked-connections list. */
  148042. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  148043. sqlite3 *p = *pp;
  148044. /* Step 1. */
  148045. if( p->pBlockingConnection==db ){
  148046. p->pBlockingConnection = 0;
  148047. }
  148048. /* Step 2. */
  148049. if( p->pUnlockConnection==db ){
  148050. assert( p->xUnlockNotify );
  148051. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  148052. xUnlockNotify(aArg, nArg);
  148053. nArg = 0;
  148054. }
  148055. sqlite3BeginBenignMalloc();
  148056. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  148057. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  148058. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  148059. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  148060. ){
  148061. /* The aArg[] array needs to grow. */
  148062. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  148063. if( pNew ){
  148064. memcpy(pNew, aArg, nArg*sizeof(void *));
  148065. sqlite3_free(aDyn);
  148066. aDyn = aArg = pNew;
  148067. }else{
  148068. /* This occurs when the array of context pointers that need to
  148069. ** be passed to the unlock-notify callback is larger than the
  148070. ** aStatic[] array allocated on the stack and the attempt to
  148071. ** allocate a larger array from the heap has failed.
  148072. **
  148073. ** This is a difficult situation to handle. Returning an error
  148074. ** code to the caller is insufficient, as even if an error code
  148075. ** is returned the transaction on connection db will still be
  148076. ** closed and the unlock-notify callbacks on blocked connections
  148077. ** will go unissued. This might cause the application to wait
  148078. ** indefinitely for an unlock-notify callback that will never
  148079. ** arrive.
  148080. **
  148081. ** Instead, invoke the unlock-notify callback with the context
  148082. ** array already accumulated. We can then clear the array and
  148083. ** begin accumulating any further context pointers without
  148084. ** requiring any dynamic allocation. This is sub-optimal because
  148085. ** it means that instead of one callback with a large array of
  148086. ** context pointers the application will receive two or more
  148087. ** callbacks with smaller arrays of context pointers, which will
  148088. ** reduce the applications ability to prioritize multiple
  148089. ** connections. But it is the best that can be done under the
  148090. ** circumstances.
  148091. */
  148092. xUnlockNotify(aArg, nArg);
  148093. nArg = 0;
  148094. }
  148095. }
  148096. sqlite3EndBenignMalloc();
  148097. aArg[nArg++] = p->pUnlockArg;
  148098. xUnlockNotify = p->xUnlockNotify;
  148099. p->pUnlockConnection = 0;
  148100. p->xUnlockNotify = 0;
  148101. p->pUnlockArg = 0;
  148102. }
  148103. /* Step 3. */
  148104. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  148105. /* Remove connection p from the blocked connections list. */
  148106. *pp = p->pNextBlocked;
  148107. p->pNextBlocked = 0;
  148108. }else{
  148109. pp = &p->pNextBlocked;
  148110. }
  148111. }
  148112. if( nArg!=0 ){
  148113. xUnlockNotify(aArg, nArg);
  148114. }
  148115. sqlite3_free(aDyn);
  148116. leaveMutex(); /* Leave STATIC_MASTER mutex */
  148117. }
  148118. /*
  148119. ** This is called when the database connection passed as an argument is
  148120. ** being closed. The connection is removed from the blocked list.
  148121. */
  148122. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  148123. sqlite3ConnectionUnlocked(db);
  148124. enterMutex();
  148125. removeFromBlockedList(db);
  148126. checkListProperties(db);
  148127. leaveMutex();
  148128. }
  148129. #endif
  148130. /************** End of notify.c **********************************************/
  148131. /************** Begin file fts3.c ********************************************/
  148132. /*
  148133. ** 2006 Oct 10
  148134. **
  148135. ** The author disclaims copyright to this source code. In place of
  148136. ** a legal notice, here is a blessing:
  148137. **
  148138. ** May you do good and not evil.
  148139. ** May you find forgiveness for yourself and forgive others.
  148140. ** May you share freely, never taking more than you give.
  148141. **
  148142. ******************************************************************************
  148143. **
  148144. ** This is an SQLite module implementing full-text search.
  148145. */
  148146. /*
  148147. ** The code in this file is only compiled if:
  148148. **
  148149. ** * The FTS3 module is being built as an extension
  148150. ** (in which case SQLITE_CORE is not defined), or
  148151. **
  148152. ** * The FTS3 module is being built into the core of
  148153. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  148154. */
  148155. /* The full-text index is stored in a series of b+tree (-like)
  148156. ** structures called segments which map terms to doclists. The
  148157. ** structures are like b+trees in layout, but are constructed from the
  148158. ** bottom up in optimal fashion and are not updatable. Since trees
  148159. ** are built from the bottom up, things will be described from the
  148160. ** bottom up.
  148161. **
  148162. **
  148163. **** Varints ****
  148164. ** The basic unit of encoding is a variable-length integer called a
  148165. ** varint. We encode variable-length integers in little-endian order
  148166. ** using seven bits * per byte as follows:
  148167. **
  148168. ** KEY:
  148169. ** A = 0xxxxxxx 7 bits of data and one flag bit
  148170. ** B = 1xxxxxxx 7 bits of data and one flag bit
  148171. **
  148172. ** 7 bits - A
  148173. ** 14 bits - BA
  148174. ** 21 bits - BBA
  148175. ** and so on.
  148176. **
  148177. ** This is similar in concept to how sqlite encodes "varints" but
  148178. ** the encoding is not the same. SQLite varints are big-endian
  148179. ** are are limited to 9 bytes in length whereas FTS3 varints are
  148180. ** little-endian and can be up to 10 bytes in length (in theory).
  148181. **
  148182. ** Example encodings:
  148183. **
  148184. ** 1: 0x01
  148185. ** 127: 0x7f
  148186. ** 128: 0x81 0x00
  148187. **
  148188. **
  148189. **** Document lists ****
  148190. ** A doclist (document list) holds a docid-sorted list of hits for a
  148191. ** given term. Doclists hold docids and associated token positions.
  148192. ** A docid is the unique integer identifier for a single document.
  148193. ** A position is the index of a word within the document. The first
  148194. ** word of the document has a position of 0.
  148195. **
  148196. ** FTS3 used to optionally store character offsets using a compile-time
  148197. ** option. But that functionality is no longer supported.
  148198. **
  148199. ** A doclist is stored like this:
  148200. **
  148201. ** array {
  148202. ** varint docid; (delta from previous doclist)
  148203. ** array { (position list for column 0)
  148204. ** varint position; (2 more than the delta from previous position)
  148205. ** }
  148206. ** array {
  148207. ** varint POS_COLUMN; (marks start of position list for new column)
  148208. ** varint column; (index of new column)
  148209. ** array {
  148210. ** varint position; (2 more than the delta from previous position)
  148211. ** }
  148212. ** }
  148213. ** varint POS_END; (marks end of positions for this document.
  148214. ** }
  148215. **
  148216. ** Here, array { X } means zero or more occurrences of X, adjacent in
  148217. ** memory. A "position" is an index of a token in the token stream
  148218. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  148219. ** in the same logical place as the position element, and act as sentinals
  148220. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  148221. ** The positions numbers are not stored literally but rather as two more
  148222. ** than the difference from the prior position, or the just the position plus
  148223. ** 2 for the first position. Example:
  148224. **
  148225. ** label: A B C D E F G H I J K
  148226. ** value: 123 5 9 1 1 14 35 0 234 72 0
  148227. **
  148228. ** The 123 value is the first docid. For column zero in this document
  148229. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  148230. ** at D signals the start of a new column; the 1 at E indicates that the
  148231. ** new column is column number 1. There are two positions at 12 and 45
  148232. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  148233. ** 234 at I is the delta to next docid (357). It has one position 70
  148234. ** (72-2) and then terminates with the 0 at K.
  148235. **
  148236. ** A "position-list" is the list of positions for multiple columns for
  148237. ** a single docid. A "column-list" is the set of positions for a single
  148238. ** column. Hence, a position-list consists of one or more column-lists,
  148239. ** a document record consists of a docid followed by a position-list and
  148240. ** a doclist consists of one or more document records.
  148241. **
  148242. ** A bare doclist omits the position information, becoming an
  148243. ** array of varint-encoded docids.
  148244. **
  148245. **** Segment leaf nodes ****
  148246. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  148247. ** nodes are written using LeafWriter, and read using LeafReader (to
  148248. ** iterate through a single leaf node's data) and LeavesReader (to
  148249. ** iterate through a segment's entire leaf layer). Leaf nodes have
  148250. ** the format:
  148251. **
  148252. ** varint iHeight; (height from leaf level, always 0)
  148253. ** varint nTerm; (length of first term)
  148254. ** char pTerm[nTerm]; (content of first term)
  148255. ** varint nDoclist; (length of term's associated doclist)
  148256. ** char pDoclist[nDoclist]; (content of doclist)
  148257. ** array {
  148258. ** (further terms are delta-encoded)
  148259. ** varint nPrefix; (length of prefix shared with previous term)
  148260. ** varint nSuffix; (length of unshared suffix)
  148261. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  148262. ** varint nDoclist; (length of term's associated doclist)
  148263. ** char pDoclist[nDoclist]; (content of doclist)
  148264. ** }
  148265. **
  148266. ** Here, array { X } means zero or more occurrences of X, adjacent in
  148267. ** memory.
  148268. **
  148269. ** Leaf nodes are broken into blocks which are stored contiguously in
  148270. ** the %_segments table in sorted order. This means that when the end
  148271. ** of a node is reached, the next term is in the node with the next
  148272. ** greater node id.
  148273. **
  148274. ** New data is spilled to a new leaf node when the current node
  148275. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  148276. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  148277. ** node (a leaf node with a single term and doclist). The goal of
  148278. ** these settings is to pack together groups of small doclists while
  148279. ** making it efficient to directly access large doclists. The
  148280. ** assumption is that large doclists represent terms which are more
  148281. ** likely to be query targets.
  148282. **
  148283. ** TODO(shess) It may be useful for blocking decisions to be more
  148284. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  148285. ** node rather than splitting into 2k and .5k nodes. My intuition is
  148286. ** that this might extend through 2x or 4x the pagesize.
  148287. **
  148288. **
  148289. **** Segment interior nodes ****
  148290. ** Segment interior nodes store blockids for subtree nodes and terms
  148291. ** to describe what data is stored by the each subtree. Interior
  148292. ** nodes are written using InteriorWriter, and read using
  148293. ** InteriorReader. InteriorWriters are created as needed when
  148294. ** SegmentWriter creates new leaf nodes, or when an interior node
  148295. ** itself grows too big and must be split. The format of interior
  148296. ** nodes:
  148297. **
  148298. ** varint iHeight; (height from leaf level, always >0)
  148299. ** varint iBlockid; (block id of node's leftmost subtree)
  148300. ** optional {
  148301. ** varint nTerm; (length of first term)
  148302. ** char pTerm[nTerm]; (content of first term)
  148303. ** array {
  148304. ** (further terms are delta-encoded)
  148305. ** varint nPrefix; (length of shared prefix with previous term)
  148306. ** varint nSuffix; (length of unshared suffix)
  148307. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  148308. ** }
  148309. ** }
  148310. **
  148311. ** Here, optional { X } means an optional element, while array { X }
  148312. ** means zero or more occurrences of X, adjacent in memory.
  148313. **
  148314. ** An interior node encodes n terms separating n+1 subtrees. The
  148315. ** subtree blocks are contiguous, so only the first subtree's blockid
  148316. ** is encoded. The subtree at iBlockid will contain all terms less
  148317. ** than the first term encoded (or all terms if no term is encoded).
  148318. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  148319. ** than pTerm[i+1], the subtree for that term will be rooted at
  148320. ** iBlockid+i. Interior nodes only store enough term data to
  148321. ** distinguish adjacent children (if the rightmost term of the left
  148322. ** child is "something", and the leftmost term of the right child is
  148323. ** "wicked", only "w" is stored).
  148324. **
  148325. ** New data is spilled to a new interior node at the same height when
  148326. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  148327. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  148328. ** interior nodes and making the tree too skinny. The interior nodes
  148329. ** at a given height are naturally tracked by interior nodes at
  148330. ** height+1, and so on.
  148331. **
  148332. **
  148333. **** Segment directory ****
  148334. ** The segment directory in table %_segdir stores meta-information for
  148335. ** merging and deleting segments, and also the root node of the
  148336. ** segment's tree.
  148337. **
  148338. ** The root node is the top node of the segment's tree after encoding
  148339. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  148340. ** This could be either a leaf node or an interior node. If the top
  148341. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  148342. ** and a new root interior node is generated (which should always fit
  148343. ** within ROOT_MAX because it only needs space for 2 varints, the
  148344. ** height and the blockid of the previous root).
  148345. **
  148346. ** The meta-information in the segment directory is:
  148347. ** level - segment level (see below)
  148348. ** idx - index within level
  148349. ** - (level,idx uniquely identify a segment)
  148350. ** start_block - first leaf node
  148351. ** leaves_end_block - last leaf node
  148352. ** end_block - last block (including interior nodes)
  148353. ** root - contents of root node
  148354. **
  148355. ** If the root node is a leaf node, then start_block,
  148356. ** leaves_end_block, and end_block are all 0.
  148357. **
  148358. **
  148359. **** Segment merging ****
  148360. ** To amortize update costs, segments are grouped into levels and
  148361. ** merged in batches. Each increase in level represents exponentially
  148362. ** more documents.
  148363. **
  148364. ** New documents (actually, document updates) are tokenized and
  148365. ** written individually (using LeafWriter) to a level 0 segment, with
  148366. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  148367. ** level 0 segments are merged into a single level 1 segment. Level 1
  148368. ** is populated like level 0, and eventually MERGE_COUNT level 1
  148369. ** segments are merged to a single level 2 segment (representing
  148370. ** MERGE_COUNT^2 updates), and so on.
  148371. **
  148372. ** A segment merge traverses all segments at a given level in
  148373. ** parallel, performing a straightforward sorted merge. Since segment
  148374. ** leaf nodes are written in to the %_segments table in order, this
  148375. ** merge traverses the underlying sqlite disk structures efficiently.
  148376. ** After the merge, all segment blocks from the merged level are
  148377. ** deleted.
  148378. **
  148379. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  148380. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  148381. ** very similar performance numbers to 16 on insertion, though they're
  148382. ** a tiny bit slower (perhaps due to more overhead in merge-time
  148383. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  148384. ** 16, 2 about 66% slower than 16.
  148385. **
  148386. ** At query time, high MERGE_COUNT increases the number of segments
  148387. ** which need to be scanned and merged. For instance, with 100k docs
  148388. ** inserted:
  148389. **
  148390. ** MERGE_COUNT segments
  148391. ** 16 25
  148392. ** 8 12
  148393. ** 4 10
  148394. ** 2 6
  148395. **
  148396. ** This appears to have only a moderate impact on queries for very
  148397. ** frequent terms (which are somewhat dominated by segment merge
  148398. ** costs), and infrequent and non-existent terms still seem to be fast
  148399. ** even with many segments.
  148400. **
  148401. ** TODO(shess) That said, it would be nice to have a better query-side
  148402. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  148403. ** optimizations to things like doclist merging will swing the sweet
  148404. ** spot around.
  148405. **
  148406. **
  148407. **
  148408. **** Handling of deletions and updates ****
  148409. ** Since we're using a segmented structure, with no docid-oriented
  148410. ** index into the term index, we clearly cannot simply update the term
  148411. ** index when a document is deleted or updated. For deletions, we
  148412. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  148413. ** we simply write the new doclist. Segment merges overwrite older
  148414. ** data for a particular docid with newer data, so deletes or updates
  148415. ** will eventually overtake the earlier data and knock it out. The
  148416. ** query logic likewise merges doclists so that newer data knocks out
  148417. ** older data.
  148418. */
  148419. /************** Include fts3Int.h in the middle of fts3.c ********************/
  148420. /************** Begin file fts3Int.h *****************************************/
  148421. /*
  148422. ** 2009 Nov 12
  148423. **
  148424. ** The author disclaims copyright to this source code. In place of
  148425. ** a legal notice, here is a blessing:
  148426. **
  148427. ** May you do good and not evil.
  148428. ** May you find forgiveness for yourself and forgive others.
  148429. ** May you share freely, never taking more than you give.
  148430. **
  148431. ******************************************************************************
  148432. **
  148433. */
  148434. #ifndef _FTSINT_H
  148435. #define _FTSINT_H
  148436. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  148437. # define NDEBUG 1
  148438. #endif
  148439. /* FTS3/FTS4 require virtual tables */
  148440. #ifdef SQLITE_OMIT_VIRTUALTABLE
  148441. # undef SQLITE_ENABLE_FTS3
  148442. # undef SQLITE_ENABLE_FTS4
  148443. #endif
  148444. /*
  148445. ** FTS4 is really an extension for FTS3. It is enabled using the
  148446. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  148447. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  148448. */
  148449. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  148450. # define SQLITE_ENABLE_FTS3
  148451. #endif
  148452. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  148453. /* If not building as part of the core, include sqlite3ext.h. */
  148454. #ifndef SQLITE_CORE
  148455. /* # include "sqlite3ext.h" */
  148456. SQLITE_EXTENSION_INIT3
  148457. #endif
  148458. /* #include "sqlite3.h" */
  148459. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  148460. /************** Begin file fts3_tokenizer.h **********************************/
  148461. /*
  148462. ** 2006 July 10
  148463. **
  148464. ** The author disclaims copyright to this source code.
  148465. **
  148466. *************************************************************************
  148467. ** Defines the interface to tokenizers used by fulltext-search. There
  148468. ** are three basic components:
  148469. **
  148470. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  148471. ** interface functions. This is essentially the class structure for
  148472. ** tokenizers.
  148473. **
  148474. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  148475. ** including customization information defined at creation time.
  148476. **
  148477. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  148478. ** tokens from a particular input.
  148479. */
  148480. #ifndef _FTS3_TOKENIZER_H_
  148481. #define _FTS3_TOKENIZER_H_
  148482. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  148483. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  148484. ** we will need a way to register the API consistently.
  148485. */
  148486. /* #include "sqlite3.h" */
  148487. /*
  148488. ** Structures used by the tokenizer interface. When a new tokenizer
  148489. ** implementation is registered, the caller provides a pointer to
  148490. ** an sqlite3_tokenizer_module containing pointers to the callback
  148491. ** functions that make up an implementation.
  148492. **
  148493. ** When an fts3 table is created, it passes any arguments passed to
  148494. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  148495. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  148496. ** implementation. The xCreate() function in turn returns an
  148497. ** sqlite3_tokenizer structure representing the specific tokenizer to
  148498. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  148499. **
  148500. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  148501. ** method is called. It returns an sqlite3_tokenizer_cursor object
  148502. ** that may be used to tokenize a specific input buffer based on
  148503. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  148504. ** object.
  148505. */
  148506. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  148507. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  148508. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  148509. struct sqlite3_tokenizer_module {
  148510. /*
  148511. ** Structure version. Should always be set to 0 or 1.
  148512. */
  148513. int iVersion;
  148514. /*
  148515. ** Create a new tokenizer. The values in the argv[] array are the
  148516. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  148517. ** TABLE statement that created the fts3 table. For example, if
  148518. ** the following SQL is executed:
  148519. **
  148520. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  148521. **
  148522. ** then argc is set to 2, and the argv[] array contains pointers
  148523. ** to the strings "arg1" and "arg2".
  148524. **
  148525. ** This method should return either SQLITE_OK (0), or an SQLite error
  148526. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  148527. ** to point at the newly created tokenizer structure. The generic
  148528. ** sqlite3_tokenizer.pModule variable should not be initialized by
  148529. ** this callback. The caller will do so.
  148530. */
  148531. int (*xCreate)(
  148532. int argc, /* Size of argv array */
  148533. const char *const*argv, /* Tokenizer argument strings */
  148534. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  148535. );
  148536. /*
  148537. ** Destroy an existing tokenizer. The fts3 module calls this method
  148538. ** exactly once for each successful call to xCreate().
  148539. */
  148540. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  148541. /*
  148542. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  148543. ** is responsible for ensuring that the input buffer remains valid
  148544. ** until the cursor is closed (using the xClose() method).
  148545. */
  148546. int (*xOpen)(
  148547. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  148548. const char *pInput, int nBytes, /* Input buffer */
  148549. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  148550. );
  148551. /*
  148552. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  148553. ** method exactly once for each successful call to xOpen().
  148554. */
  148555. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  148556. /*
  148557. ** Retrieve the next token from the tokenizer cursor pCursor. This
  148558. ** method should either return SQLITE_OK and set the values of the
  148559. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  148560. ** the end of the buffer has been reached, or an SQLite error code.
  148561. **
  148562. ** *ppToken should be set to point at a buffer containing the
  148563. ** normalized version of the token (i.e. after any case-folding and/or
  148564. ** stemming has been performed). *pnBytes should be set to the length
  148565. ** of this buffer in bytes. The input text that generated the token is
  148566. ** identified by the byte offsets returned in *piStartOffset and
  148567. ** *piEndOffset. *piStartOffset should be set to the index of the first
  148568. ** byte of the token in the input buffer. *piEndOffset should be set
  148569. ** to the index of the first byte just past the end of the token in
  148570. ** the input buffer.
  148571. **
  148572. ** The buffer *ppToken is set to point at is managed by the tokenizer
  148573. ** implementation. It is only required to be valid until the next call
  148574. ** to xNext() or xClose().
  148575. */
  148576. /* TODO(shess) current implementation requires pInput to be
  148577. ** nul-terminated. This should either be fixed, or pInput/nBytes
  148578. ** should be converted to zInput.
  148579. */
  148580. int (*xNext)(
  148581. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  148582. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  148583. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  148584. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  148585. int *piPosition /* OUT: Number of tokens returned before this one */
  148586. );
  148587. /***********************************************************************
  148588. ** Methods below this point are only available if iVersion>=1.
  148589. */
  148590. /*
  148591. ** Configure the language id of a tokenizer cursor.
  148592. */
  148593. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  148594. };
  148595. struct sqlite3_tokenizer {
  148596. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  148597. /* Tokenizer implementations will typically add additional fields */
  148598. };
  148599. struct sqlite3_tokenizer_cursor {
  148600. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  148601. /* Tokenizer implementations will typically add additional fields */
  148602. };
  148603. int fts3_global_term_cnt(int iTerm, int iCol);
  148604. int fts3_term_cnt(int iTerm, int iCol);
  148605. #endif /* _FTS3_TOKENIZER_H_ */
  148606. /************** End of fts3_tokenizer.h **************************************/
  148607. /************** Continuing where we left off in fts3Int.h ********************/
  148608. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  148609. /************** Begin file fts3_hash.h ***************************************/
  148610. /*
  148611. ** 2001 September 22
  148612. **
  148613. ** The author disclaims copyright to this source code. In place of
  148614. ** a legal notice, here is a blessing:
  148615. **
  148616. ** May you do good and not evil.
  148617. ** May you find forgiveness for yourself and forgive others.
  148618. ** May you share freely, never taking more than you give.
  148619. **
  148620. *************************************************************************
  148621. ** This is the header file for the generic hash-table implementation
  148622. ** used in SQLite. We've modified it slightly to serve as a standalone
  148623. ** hash table implementation for the full-text indexing module.
  148624. **
  148625. */
  148626. #ifndef _FTS3_HASH_H_
  148627. #define _FTS3_HASH_H_
  148628. /* Forward declarations of structures. */
  148629. typedef struct Fts3Hash Fts3Hash;
  148630. typedef struct Fts3HashElem Fts3HashElem;
  148631. /* A complete hash table is an instance of the following structure.
  148632. ** The internals of this structure are intended to be opaque -- client
  148633. ** code should not attempt to access or modify the fields of this structure
  148634. ** directly. Change this structure only by using the routines below.
  148635. ** However, many of the "procedures" and "functions" for modifying and
  148636. ** accessing this structure are really macros, so we can't really make
  148637. ** this structure opaque.
  148638. */
  148639. struct Fts3Hash {
  148640. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  148641. char copyKey; /* True if copy of key made on insert */
  148642. int count; /* Number of entries in this table */
  148643. Fts3HashElem *first; /* The first element of the array */
  148644. int htsize; /* Number of buckets in the hash table */
  148645. struct _fts3ht { /* the hash table */
  148646. int count; /* Number of entries with this hash */
  148647. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  148648. } *ht;
  148649. };
  148650. /* Each element in the hash table is an instance of the following
  148651. ** structure. All elements are stored on a single doubly-linked list.
  148652. **
  148653. ** Again, this structure is intended to be opaque, but it can't really
  148654. ** be opaque because it is used by macros.
  148655. */
  148656. struct Fts3HashElem {
  148657. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  148658. void *data; /* Data associated with this element */
  148659. void *pKey; int nKey; /* Key associated with this element */
  148660. };
  148661. /*
  148662. ** There are 2 different modes of operation for a hash table:
  148663. **
  148664. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  148665. ** (including the null-terminator, if any). Case
  148666. ** is respected in comparisons.
  148667. **
  148668. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  148669. ** memcmp() is used to compare keys.
  148670. **
  148671. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  148672. */
  148673. #define FTS3_HASH_STRING 1
  148674. #define FTS3_HASH_BINARY 2
  148675. /*
  148676. ** Access routines. To delete, insert a NULL pointer.
  148677. */
  148678. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  148679. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  148680. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  148681. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  148682. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  148683. /*
  148684. ** Shorthand for the functions above
  148685. */
  148686. #define fts3HashInit sqlite3Fts3HashInit
  148687. #define fts3HashInsert sqlite3Fts3HashInsert
  148688. #define fts3HashFind sqlite3Fts3HashFind
  148689. #define fts3HashClear sqlite3Fts3HashClear
  148690. #define fts3HashFindElem sqlite3Fts3HashFindElem
  148691. /*
  148692. ** Macros for looping over all elements of a hash table. The idiom is
  148693. ** like this:
  148694. **
  148695. ** Fts3Hash h;
  148696. ** Fts3HashElem *p;
  148697. ** ...
  148698. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  148699. ** SomeStructure *pData = fts3HashData(p);
  148700. ** // do something with pData
  148701. ** }
  148702. */
  148703. #define fts3HashFirst(H) ((H)->first)
  148704. #define fts3HashNext(E) ((E)->next)
  148705. #define fts3HashData(E) ((E)->data)
  148706. #define fts3HashKey(E) ((E)->pKey)
  148707. #define fts3HashKeysize(E) ((E)->nKey)
  148708. /*
  148709. ** Number of entries in a hash table
  148710. */
  148711. #define fts3HashCount(H) ((H)->count)
  148712. #endif /* _FTS3_HASH_H_ */
  148713. /************** End of fts3_hash.h *******************************************/
  148714. /************** Continuing where we left off in fts3Int.h ********************/
  148715. /*
  148716. ** This constant determines the maximum depth of an FTS expression tree
  148717. ** that the library will create and use. FTS uses recursion to perform
  148718. ** various operations on the query tree, so the disadvantage of a large
  148719. ** limit is that it may allow very large queries to use large amounts
  148720. ** of stack space (perhaps causing a stack overflow).
  148721. */
  148722. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  148723. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  148724. #endif
  148725. /*
  148726. ** This constant controls how often segments are merged. Once there are
  148727. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  148728. ** segment of level N+1.
  148729. */
  148730. #define FTS3_MERGE_COUNT 16
  148731. /*
  148732. ** This is the maximum amount of data (in bytes) to store in the
  148733. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  148734. ** populated as documents are inserted/updated/deleted in a transaction
  148735. ** and used to create a new segment when the transaction is committed.
  148736. ** However if this limit is reached midway through a transaction, a new
  148737. ** segment is created and the hash table cleared immediately.
  148738. */
  148739. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  148740. /*
  148741. ** Macro to return the number of elements in an array. SQLite has a
  148742. ** similar macro called ArraySize(). Use a different name to avoid
  148743. ** a collision when building an amalgamation with built-in FTS3.
  148744. */
  148745. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  148746. #ifndef MIN
  148747. # define MIN(x,y) ((x)<(y)?(x):(y))
  148748. #endif
  148749. #ifndef MAX
  148750. # define MAX(x,y) ((x)>(y)?(x):(y))
  148751. #endif
  148752. /*
  148753. ** Maximum length of a varint encoded integer. The varint format is different
  148754. ** from that used by SQLite, so the maximum length is 10, not 9.
  148755. */
  148756. #define FTS3_VARINT_MAX 10
  148757. /*
  148758. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  148759. ** in the document set and zero or more prefix indexes. All indexes are stored
  148760. ** as one or more b+-trees in the %_segments and %_segdir tables.
  148761. **
  148762. ** It is possible to determine which index a b+-tree belongs to based on the
  148763. ** value stored in the "%_segdir.level" column. Given this value L, the index
  148764. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  148765. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  148766. ** between 1024 and 2047 to index 1, and so on.
  148767. **
  148768. ** It is considered impossible for an index to use more than 1024 levels. In
  148769. ** theory though this may happen, but only after at least
  148770. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  148771. */
  148772. #define FTS3_SEGDIR_MAXLEVEL 1024
  148773. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  148774. /*
  148775. ** The testcase() macro is only used by the amalgamation. If undefined,
  148776. ** make it a no-op.
  148777. */
  148778. #ifndef testcase
  148779. # define testcase(X)
  148780. #endif
  148781. /*
  148782. ** Terminator values for position-lists and column-lists.
  148783. */
  148784. #define POS_COLUMN (1) /* Column-list terminator */
  148785. #define POS_END (0) /* Position-list terminator */
  148786. /*
  148787. ** This section provides definitions to allow the
  148788. ** FTS3 extension to be compiled outside of the
  148789. ** amalgamation.
  148790. */
  148791. #ifndef SQLITE_AMALGAMATION
  148792. /*
  148793. ** Macros indicating that conditional expressions are always true or
  148794. ** false.
  148795. */
  148796. #ifdef SQLITE_COVERAGE_TEST
  148797. # define ALWAYS(x) (1)
  148798. # define NEVER(X) (0)
  148799. #elif defined(SQLITE_DEBUG)
  148800. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  148801. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  148802. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  148803. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  148804. #else
  148805. # define ALWAYS(x) (x)
  148806. # define NEVER(x) (x)
  148807. #endif
  148808. /*
  148809. ** Internal types used by SQLite.
  148810. */
  148811. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  148812. typedef short int i16; /* 2-byte (or larger) signed integer */
  148813. typedef unsigned int u32; /* 4-byte unsigned integer */
  148814. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  148815. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  148816. /*
  148817. ** Macro used to suppress compiler warnings for unused parameters.
  148818. */
  148819. #define UNUSED_PARAMETER(x) (void)(x)
  148820. /*
  148821. ** Activate assert() only if SQLITE_TEST is enabled.
  148822. */
  148823. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  148824. # define NDEBUG 1
  148825. #endif
  148826. /*
  148827. ** The TESTONLY macro is used to enclose variable declarations or
  148828. ** other bits of code that are needed to support the arguments
  148829. ** within testcase() and assert() macros.
  148830. */
  148831. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  148832. # define TESTONLY(X) X
  148833. #else
  148834. # define TESTONLY(X)
  148835. #endif
  148836. #endif /* SQLITE_AMALGAMATION */
  148837. #ifdef SQLITE_DEBUG
  148838. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  148839. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  148840. #else
  148841. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  148842. #endif
  148843. typedef struct Fts3Table Fts3Table;
  148844. typedef struct Fts3Cursor Fts3Cursor;
  148845. typedef struct Fts3Expr Fts3Expr;
  148846. typedef struct Fts3Phrase Fts3Phrase;
  148847. typedef struct Fts3PhraseToken Fts3PhraseToken;
  148848. typedef struct Fts3Doclist Fts3Doclist;
  148849. typedef struct Fts3SegFilter Fts3SegFilter;
  148850. typedef struct Fts3DeferredToken Fts3DeferredToken;
  148851. typedef struct Fts3SegReader Fts3SegReader;
  148852. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  148853. typedef struct MatchinfoBuffer MatchinfoBuffer;
  148854. /*
  148855. ** A connection to a fulltext index is an instance of the following
  148856. ** structure. The xCreate and xConnect methods create an instance
  148857. ** of this structure and xDestroy and xDisconnect free that instance.
  148858. ** All other methods receive a pointer to the structure as one of their
  148859. ** arguments.
  148860. */
  148861. struct Fts3Table {
  148862. sqlite3_vtab base; /* Base class used by SQLite core */
  148863. sqlite3 *db; /* The database connection */
  148864. const char *zDb; /* logical database name */
  148865. const char *zName; /* virtual table name */
  148866. int nColumn; /* number of named columns in virtual table */
  148867. char **azColumn; /* column names. malloced */
  148868. u8 *abNotindexed; /* True for 'notindexed' columns */
  148869. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  148870. char *zContentTbl; /* content=xxx option, or NULL */
  148871. char *zLanguageid; /* languageid=xxx option, or NULL */
  148872. int nAutoincrmerge; /* Value configured by 'automerge' */
  148873. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  148874. /* Precompiled statements used by the implementation. Each of these
  148875. ** statements is run and reset within a single virtual table API call.
  148876. */
  148877. sqlite3_stmt *aStmt[40];
  148878. sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */
  148879. char *zReadExprlist;
  148880. char *zWriteExprlist;
  148881. int nNodeSize; /* Soft limit for node size */
  148882. u8 bFts4; /* True for FTS4, false for FTS3 */
  148883. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  148884. u8 bHasDocsize; /* True if %_docsize table exists */
  148885. u8 bDescIdx; /* True if doclists are in reverse order */
  148886. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  148887. int nPgsz; /* Page size for host database */
  148888. char *zSegmentsTbl; /* Name of %_segments table */
  148889. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  148890. /*
  148891. ** The following array of hash tables is used to buffer pending index
  148892. ** updates during transactions. All pending updates buffered at any one
  148893. ** time must share a common language-id (see the FTS4 langid= feature).
  148894. ** The current language id is stored in variable iPrevLangid.
  148895. **
  148896. ** A single FTS4 table may have multiple full-text indexes. For each index
  148897. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  148898. ** terms that appear in the document set. Each subsequent index in aIndex[]
  148899. ** is an index of prefixes of a specific length.
  148900. **
  148901. ** Variable nPendingData contains an estimate the memory consumed by the
  148902. ** pending data structures, including hash table overhead, but not including
  148903. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  148904. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  148905. ** recently inserted record.
  148906. */
  148907. int nIndex; /* Size of aIndex[] */
  148908. struct Fts3Index {
  148909. int nPrefix; /* Prefix length (0 for main terms index) */
  148910. Fts3Hash hPending; /* Pending terms table for this index */
  148911. } *aIndex;
  148912. int nMaxPendingData; /* Max pending data before flush to disk */
  148913. int nPendingData; /* Current bytes of pending data */
  148914. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  148915. int iPrevLangid; /* Langid of recently inserted document */
  148916. int bPrevDelete; /* True if last operation was a delete */
  148917. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  148918. /* State variables used for validating that the transaction control
  148919. ** methods of the virtual table are called at appropriate times. These
  148920. ** values do not contribute to FTS functionality; they are used for
  148921. ** verifying the operation of the SQLite core.
  148922. */
  148923. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  148924. int mxSavepoint; /* Largest valid xSavepoint integer */
  148925. #endif
  148926. #ifdef SQLITE_TEST
  148927. /* True to disable the incremental doclist optimization. This is controled
  148928. ** by special insert command 'test-no-incr-doclist'. */
  148929. int bNoIncrDoclist;
  148930. #endif
  148931. };
  148932. /*
  148933. ** When the core wants to read from the virtual table, it creates a
  148934. ** virtual table cursor (an instance of the following structure) using
  148935. ** the xOpen method. Cursors are destroyed using the xClose method.
  148936. */
  148937. struct Fts3Cursor {
  148938. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  148939. i16 eSearch; /* Search strategy (see below) */
  148940. u8 isEof; /* True if at End Of Results */
  148941. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  148942. u8 bSeekStmt; /* True if pStmt is a seek */
  148943. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  148944. Fts3Expr *pExpr; /* Parsed MATCH query string */
  148945. int iLangid; /* Language being queried for */
  148946. int nPhrase; /* Number of matchable phrases in query */
  148947. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  148948. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  148949. char *pNextId; /* Pointer into the body of aDoclist */
  148950. char *aDoclist; /* List of docids for full-text queries */
  148951. int nDoclist; /* Size of buffer at aDoclist */
  148952. u8 bDesc; /* True to sort in descending order */
  148953. int eEvalmode; /* An FTS3_EVAL_XX constant */
  148954. int nRowAvg; /* Average size of database rows, in pages */
  148955. sqlite3_int64 nDoc; /* Documents in table */
  148956. i64 iMinDocid; /* Minimum docid to return */
  148957. i64 iMaxDocid; /* Maximum docid to return */
  148958. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  148959. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  148960. };
  148961. #define FTS3_EVAL_FILTER 0
  148962. #define FTS3_EVAL_NEXT 1
  148963. #define FTS3_EVAL_MATCHINFO 2
  148964. /*
  148965. ** The Fts3Cursor.eSearch member is always set to one of the following.
  148966. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  148967. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  148968. ** of the column to be searched. For example, in
  148969. **
  148970. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  148971. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  148972. **
  148973. ** Because the LHS of the MATCH operator is 2nd column "b",
  148974. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  148975. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  148976. ** indicating that all columns should be searched,
  148977. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  148978. */
  148979. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  148980. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  148981. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  148982. /*
  148983. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  148984. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  148985. ** above. The upper 16-bits contain a combination of the following
  148986. ** bits, used to describe extra constraints on full-text searches.
  148987. */
  148988. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  148989. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  148990. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  148991. struct Fts3Doclist {
  148992. char *aAll; /* Array containing doclist (or NULL) */
  148993. int nAll; /* Size of a[] in bytes */
  148994. char *pNextDocid; /* Pointer to next docid */
  148995. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  148996. int bFreeList; /* True if pList should be sqlite3_free()d */
  148997. char *pList; /* Pointer to position list following iDocid */
  148998. int nList; /* Length of position list */
  148999. };
  149000. /*
  149001. ** A "phrase" is a sequence of one or more tokens that must match in
  149002. ** sequence. A single token is the base case and the most common case.
  149003. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  149004. ** nToken will be the number of tokens in the string.
  149005. */
  149006. struct Fts3PhraseToken {
  149007. char *z; /* Text of the token */
  149008. int n; /* Number of bytes in buffer z */
  149009. int isPrefix; /* True if token ends with a "*" character */
  149010. int bFirst; /* True if token must appear at position 0 */
  149011. /* Variables above this point are populated when the expression is
  149012. ** parsed (by code in fts3_expr.c). Below this point the variables are
  149013. ** used when evaluating the expression. */
  149014. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  149015. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  149016. };
  149017. struct Fts3Phrase {
  149018. /* Cache of doclist for this phrase. */
  149019. Fts3Doclist doclist;
  149020. int bIncr; /* True if doclist is loaded incrementally */
  149021. int iDoclistToken;
  149022. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  149023. ** OR condition. */
  149024. char *pOrPoslist;
  149025. i64 iOrDocid;
  149026. /* Variables below this point are populated by fts3_expr.c when parsing
  149027. ** a MATCH expression. Everything above is part of the evaluation phase.
  149028. */
  149029. int nToken; /* Number of tokens in the phrase */
  149030. int iColumn; /* Index of column this phrase must match */
  149031. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  149032. };
  149033. /*
  149034. ** A tree of these objects forms the RHS of a MATCH operator.
  149035. **
  149036. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  149037. ** points to a malloced buffer, size nDoclist bytes, containing the results
  149038. ** of this phrase query in FTS3 doclist format. As usual, the initial
  149039. ** "Length" field found in doclists stored on disk is omitted from this
  149040. ** buffer.
  149041. **
  149042. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  149043. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  149044. ** where nCol is the number of columns in the queried FTS table. The array
  149045. ** is populated as follows:
  149046. **
  149047. ** aMI[iCol*3 + 0] = Undefined
  149048. ** aMI[iCol*3 + 1] = Number of occurrences
  149049. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  149050. **
  149051. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  149052. ** when the expression node is.
  149053. */
  149054. struct Fts3Expr {
  149055. int eType; /* One of the FTSQUERY_XXX values defined below */
  149056. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  149057. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  149058. Fts3Expr *pLeft; /* Left operand */
  149059. Fts3Expr *pRight; /* Right operand */
  149060. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  149061. /* The following are used by the fts3_eval.c module. */
  149062. sqlite3_int64 iDocid; /* Current docid */
  149063. u8 bEof; /* True this expression is at EOF already */
  149064. u8 bStart; /* True if iDocid is valid */
  149065. u8 bDeferred; /* True if this expression is entirely deferred */
  149066. /* The following are used by the fts3_snippet.c module. */
  149067. int iPhrase; /* Index of this phrase in matchinfo() results */
  149068. u32 *aMI; /* See above */
  149069. };
  149070. /*
  149071. ** Candidate values for Fts3Query.eType. Note that the order of the first
  149072. ** four values is in order of precedence when parsing expressions. For
  149073. ** example, the following:
  149074. **
  149075. ** "a OR b AND c NOT d NEAR e"
  149076. **
  149077. ** is equivalent to:
  149078. **
  149079. ** "a OR (b AND (c NOT (d NEAR e)))"
  149080. */
  149081. #define FTSQUERY_NEAR 1
  149082. #define FTSQUERY_NOT 2
  149083. #define FTSQUERY_AND 3
  149084. #define FTSQUERY_OR 4
  149085. #define FTSQUERY_PHRASE 5
  149086. /* fts3_write.c */
  149087. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  149088. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  149089. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  149090. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  149091. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  149092. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  149093. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  149094. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  149095. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  149096. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  149097. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  149098. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  149099. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  149100. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  149101. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  149102. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  149103. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  149104. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  149105. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  149106. #else
  149107. # define sqlite3Fts3FreeDeferredTokens(x)
  149108. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  149109. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  149110. # define sqlite3Fts3FreeDeferredDoclists(x)
  149111. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  149112. #endif
  149113. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  149114. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  149115. /* Special values interpreted by sqlite3SegReaderCursor() */
  149116. #define FTS3_SEGCURSOR_PENDING -1
  149117. #define FTS3_SEGCURSOR_ALL -2
  149118. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  149119. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  149120. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  149121. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  149122. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  149123. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  149124. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  149125. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  149126. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  149127. #define FTS3_SEGMENT_PREFIX 0x00000008
  149128. #define FTS3_SEGMENT_SCAN 0x00000010
  149129. #define FTS3_SEGMENT_FIRST 0x00000020
  149130. /* Type passed as 4th argument to SegmentReaderIterate() */
  149131. struct Fts3SegFilter {
  149132. const char *zTerm;
  149133. int nTerm;
  149134. int iCol;
  149135. int flags;
  149136. };
  149137. struct Fts3MultiSegReader {
  149138. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  149139. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  149140. int nSegment; /* Size of apSegment array */
  149141. int nAdvance; /* How many seg-readers to advance */
  149142. Fts3SegFilter *pFilter; /* Pointer to filter object */
  149143. char *aBuffer; /* Buffer to merge doclists in */
  149144. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  149145. int iColFilter; /* If >=0, filter for this column */
  149146. int bRestart;
  149147. /* Used by fts3.c only. */
  149148. int nCost; /* Cost of running iterator */
  149149. int bLookup; /* True if a lookup of a single entry. */
  149150. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  149151. char *zTerm; /* Pointer to term buffer */
  149152. int nTerm; /* Size of zTerm in bytes */
  149153. char *aDoclist; /* Pointer to doclist buffer */
  149154. int nDoclist; /* Size of aDoclist[] in bytes */
  149155. };
  149156. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  149157. #define fts3GetVarint32(p, piVal) ( \
  149158. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  149159. )
  149160. /* fts3.c */
  149161. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  149162. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  149163. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  149164. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  149165. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  149166. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  149167. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  149168. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  149169. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  149170. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  149171. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  149172. /* fts3_tokenizer.c */
  149173. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  149174. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  149175. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  149176. sqlite3_tokenizer **, char **
  149177. );
  149178. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  149179. /* fts3_snippet.c */
  149180. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  149181. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  149182. const char *, const char *, int, int
  149183. );
  149184. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  149185. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  149186. /* fts3_expr.c */
  149187. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  149188. char **, int, int, int, const char *, int, Fts3Expr **, char **
  149189. );
  149190. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  149191. #ifdef SQLITE_TEST
  149192. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*);
  149193. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  149194. #endif
  149195. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  149196. sqlite3_tokenizer_cursor **
  149197. );
  149198. /* fts3_aux.c */
  149199. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  149200. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  149201. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  149202. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  149203. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  149204. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  149205. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  149206. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  149207. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  149208. /* fts3_tokenize_vtab.c */
  149209. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  149210. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  149211. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  149212. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  149213. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  149214. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  149215. #endif
  149216. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  149217. #endif /* _FTSINT_H */
  149218. /************** End of fts3Int.h *********************************************/
  149219. /************** Continuing where we left off in fts3.c ***********************/
  149220. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  149221. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  149222. # define SQLITE_CORE 1
  149223. #endif
  149224. /* #include <assert.h> */
  149225. /* #include <stdlib.h> */
  149226. /* #include <stddef.h> */
  149227. /* #include <stdio.h> */
  149228. /* #include <string.h> */
  149229. /* #include <stdarg.h> */
  149230. /* #include "fts3.h" */
  149231. #ifndef SQLITE_CORE
  149232. /* # include "sqlite3ext.h" */
  149233. SQLITE_EXTENSION_INIT1
  149234. #endif
  149235. static int fts3EvalNext(Fts3Cursor *pCsr);
  149236. static int fts3EvalStart(Fts3Cursor *pCsr);
  149237. static int fts3TermSegReaderCursor(
  149238. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  149239. #ifndef SQLITE_AMALGAMATION
  149240. # if defined(SQLITE_DEBUG)
  149241. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  149242. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  149243. # endif
  149244. #endif
  149245. /*
  149246. ** Write a 64-bit variable-length integer to memory starting at p[0].
  149247. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  149248. ** The number of bytes written is returned.
  149249. */
  149250. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  149251. unsigned char *q = (unsigned char *) p;
  149252. sqlite_uint64 vu = v;
  149253. do{
  149254. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  149255. vu >>= 7;
  149256. }while( vu!=0 );
  149257. q[-1] &= 0x7f; /* turn off high bit in final byte */
  149258. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  149259. return (int) (q - (unsigned char *)p);
  149260. }
  149261. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  149262. v = (v & mask1) | ( (*ptr++) << shift ); \
  149263. if( (v & mask2)==0 ){ var = v; return ret; }
  149264. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  149265. v = (*ptr++); \
  149266. if( (v & mask2)==0 ){ var = v; return ret; }
  149267. /*
  149268. ** Read a 64-bit variable-length integer from memory starting at p[0].
  149269. ** Return the number of bytes read, or 0 on error.
  149270. ** The value is stored in *v.
  149271. */
  149272. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
  149273. const unsigned char *p = (const unsigned char*)pBuf;
  149274. const unsigned char *pStart = p;
  149275. u32 a;
  149276. u64 b;
  149277. int shift;
  149278. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  149279. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  149280. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  149281. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  149282. b = (a & 0x0FFFFFFF );
  149283. for(shift=28; shift<=63; shift+=7){
  149284. u64 c = *p++;
  149285. b += (c&0x7F) << shift;
  149286. if( (c & 0x80)==0 ) break;
  149287. }
  149288. *v = b;
  149289. return (int)(p - pStart);
  149290. }
  149291. /*
  149292. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
  149293. ** a non-negative 32-bit integer before it is returned.
  149294. */
  149295. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  149296. u32 a;
  149297. #ifndef fts3GetVarint32
  149298. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  149299. #else
  149300. a = (*p++);
  149301. assert( a & 0x80 );
  149302. #endif
  149303. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  149304. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  149305. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  149306. a = (a & 0x0FFFFFFF );
  149307. *pi = (int)(a | ((u32)(*p & 0x07) << 28));
  149308. assert( 0==(a & 0x80000000) );
  149309. assert( *pi>=0 );
  149310. return 5;
  149311. }
  149312. /*
  149313. ** Return the number of bytes required to encode v as a varint
  149314. */
  149315. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  149316. int i = 0;
  149317. do{
  149318. i++;
  149319. v >>= 7;
  149320. }while( v!=0 );
  149321. return i;
  149322. }
  149323. /*
  149324. ** Convert an SQL-style quoted string into a normal string by removing
  149325. ** the quote characters. The conversion is done in-place. If the
  149326. ** input does not begin with a quote character, then this routine
  149327. ** is a no-op.
  149328. **
  149329. ** Examples:
  149330. **
  149331. ** "abc" becomes abc
  149332. ** 'xyz' becomes xyz
  149333. ** [pqr] becomes pqr
  149334. ** `mno` becomes mno
  149335. **
  149336. */
  149337. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  149338. char quote; /* Quote character (if any ) */
  149339. quote = z[0];
  149340. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  149341. int iIn = 1; /* Index of next byte to read from input */
  149342. int iOut = 0; /* Index of next byte to write to output */
  149343. /* If the first byte was a '[', then the close-quote character is a ']' */
  149344. if( quote=='[' ) quote = ']';
  149345. while( z[iIn] ){
  149346. if( z[iIn]==quote ){
  149347. if( z[iIn+1]!=quote ) break;
  149348. z[iOut++] = quote;
  149349. iIn += 2;
  149350. }else{
  149351. z[iOut++] = z[iIn++];
  149352. }
  149353. }
  149354. z[iOut] = '\0';
  149355. }
  149356. }
  149357. /*
  149358. ** Read a single varint from the doclist at *pp and advance *pp to point
  149359. ** to the first byte past the end of the varint. Add the value of the varint
  149360. ** to *pVal.
  149361. */
  149362. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  149363. sqlite3_int64 iVal;
  149364. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  149365. *pVal += iVal;
  149366. }
  149367. /*
  149368. ** When this function is called, *pp points to the first byte following a
  149369. ** varint that is part of a doclist (or position-list, or any other list
  149370. ** of varints). This function moves *pp to point to the start of that varint,
  149371. ** and sets *pVal by the varint value.
  149372. **
  149373. ** Argument pStart points to the first byte of the doclist that the
  149374. ** varint is part of.
  149375. */
  149376. static void fts3GetReverseVarint(
  149377. char **pp,
  149378. char *pStart,
  149379. sqlite3_int64 *pVal
  149380. ){
  149381. sqlite3_int64 iVal;
  149382. char *p;
  149383. /* Pointer p now points at the first byte past the varint we are
  149384. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  149385. ** clear on character p[-1]. */
  149386. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  149387. p++;
  149388. *pp = p;
  149389. sqlite3Fts3GetVarint(p, &iVal);
  149390. *pVal = iVal;
  149391. }
  149392. /*
  149393. ** The xDisconnect() virtual table method.
  149394. */
  149395. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  149396. Fts3Table *p = (Fts3Table *)pVtab;
  149397. int i;
  149398. assert( p->nPendingData==0 );
  149399. assert( p->pSegments==0 );
  149400. /* Free any prepared statements held */
  149401. sqlite3_finalize(p->pSeekStmt);
  149402. for(i=0; i<SizeofArray(p->aStmt); i++){
  149403. sqlite3_finalize(p->aStmt[i]);
  149404. }
  149405. sqlite3_free(p->zSegmentsTbl);
  149406. sqlite3_free(p->zReadExprlist);
  149407. sqlite3_free(p->zWriteExprlist);
  149408. sqlite3_free(p->zContentTbl);
  149409. sqlite3_free(p->zLanguageid);
  149410. /* Invoke the tokenizer destructor to free the tokenizer. */
  149411. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  149412. sqlite3_free(p);
  149413. return SQLITE_OK;
  149414. }
  149415. /*
  149416. ** Write an error message into *pzErr
  149417. */
  149418. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  149419. va_list ap;
  149420. sqlite3_free(*pzErr);
  149421. va_start(ap, zFormat);
  149422. *pzErr = sqlite3_vmprintf(zFormat, ap);
  149423. va_end(ap);
  149424. }
  149425. /*
  149426. ** Construct one or more SQL statements from the format string given
  149427. ** and then evaluate those statements. The success code is written
  149428. ** into *pRc.
  149429. **
  149430. ** If *pRc is initially non-zero then this routine is a no-op.
  149431. */
  149432. static void fts3DbExec(
  149433. int *pRc, /* Success code */
  149434. sqlite3 *db, /* Database in which to run SQL */
  149435. const char *zFormat, /* Format string for SQL */
  149436. ... /* Arguments to the format string */
  149437. ){
  149438. va_list ap;
  149439. char *zSql;
  149440. if( *pRc ) return;
  149441. va_start(ap, zFormat);
  149442. zSql = sqlite3_vmprintf(zFormat, ap);
  149443. va_end(ap);
  149444. if( zSql==0 ){
  149445. *pRc = SQLITE_NOMEM;
  149446. }else{
  149447. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  149448. sqlite3_free(zSql);
  149449. }
  149450. }
  149451. /*
  149452. ** The xDestroy() virtual table method.
  149453. */
  149454. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  149455. Fts3Table *p = (Fts3Table *)pVtab;
  149456. int rc = SQLITE_OK; /* Return code */
  149457. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  149458. sqlite3 *db = p->db; /* Database handle */
  149459. /* Drop the shadow tables */
  149460. if( p->zContentTbl==0 ){
  149461. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  149462. }
  149463. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  149464. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  149465. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  149466. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  149467. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  149468. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  149469. ** Otherwise, return an SQLite error code.
  149470. */
  149471. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  149472. }
  149473. /*
  149474. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  149475. ** passed as the first argument. This is done as part of the xConnect()
  149476. ** and xCreate() methods.
  149477. **
  149478. ** If *pRc is non-zero when this function is called, it is a no-op.
  149479. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  149480. ** before returning.
  149481. */
  149482. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  149483. if( *pRc==SQLITE_OK ){
  149484. int i; /* Iterator variable */
  149485. int rc; /* Return code */
  149486. char *zSql; /* SQL statement passed to declare_vtab() */
  149487. char *zCols; /* List of user defined columns */
  149488. const char *zLanguageid;
  149489. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  149490. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  149491. /* Create a list of user columns for the virtual table */
  149492. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  149493. for(i=1; zCols && i<p->nColumn; i++){
  149494. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  149495. }
  149496. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  149497. zSql = sqlite3_mprintf(
  149498. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  149499. zCols, p->zName, zLanguageid
  149500. );
  149501. if( !zCols || !zSql ){
  149502. rc = SQLITE_NOMEM;
  149503. }else{
  149504. rc = sqlite3_declare_vtab(p->db, zSql);
  149505. }
  149506. sqlite3_free(zSql);
  149507. sqlite3_free(zCols);
  149508. *pRc = rc;
  149509. }
  149510. }
  149511. /*
  149512. ** Create the %_stat table if it does not already exist.
  149513. */
  149514. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  149515. fts3DbExec(pRc, p->db,
  149516. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  149517. "(id INTEGER PRIMARY KEY, value BLOB);",
  149518. p->zDb, p->zName
  149519. );
  149520. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  149521. }
  149522. /*
  149523. ** Create the backing store tables (%_content, %_segments and %_segdir)
  149524. ** required by the FTS3 table passed as the only argument. This is done
  149525. ** as part of the vtab xCreate() method.
  149526. **
  149527. ** If the p->bHasDocsize boolean is true (indicating that this is an
  149528. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  149529. ** %_stat tables required by FTS4.
  149530. */
  149531. static int fts3CreateTables(Fts3Table *p){
  149532. int rc = SQLITE_OK; /* Return code */
  149533. int i; /* Iterator variable */
  149534. sqlite3 *db = p->db; /* The database connection */
  149535. if( p->zContentTbl==0 ){
  149536. const char *zLanguageid = p->zLanguageid;
  149537. char *zContentCols; /* Columns of %_content table */
  149538. /* Create a list of user columns for the content table */
  149539. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  149540. for(i=0; zContentCols && i<p->nColumn; i++){
  149541. char *z = p->azColumn[i];
  149542. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  149543. }
  149544. if( zLanguageid && zContentCols ){
  149545. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  149546. }
  149547. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  149548. /* Create the content table */
  149549. fts3DbExec(&rc, db,
  149550. "CREATE TABLE %Q.'%q_content'(%s)",
  149551. p->zDb, p->zName, zContentCols
  149552. );
  149553. sqlite3_free(zContentCols);
  149554. }
  149555. /* Create other tables */
  149556. fts3DbExec(&rc, db,
  149557. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  149558. p->zDb, p->zName
  149559. );
  149560. fts3DbExec(&rc, db,
  149561. "CREATE TABLE %Q.'%q_segdir'("
  149562. "level INTEGER,"
  149563. "idx INTEGER,"
  149564. "start_block INTEGER,"
  149565. "leaves_end_block INTEGER,"
  149566. "end_block INTEGER,"
  149567. "root BLOB,"
  149568. "PRIMARY KEY(level, idx)"
  149569. ");",
  149570. p->zDb, p->zName
  149571. );
  149572. if( p->bHasDocsize ){
  149573. fts3DbExec(&rc, db,
  149574. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  149575. p->zDb, p->zName
  149576. );
  149577. }
  149578. assert( p->bHasStat==p->bFts4 );
  149579. if( p->bHasStat ){
  149580. sqlite3Fts3CreateStatTable(&rc, p);
  149581. }
  149582. return rc;
  149583. }
  149584. /*
  149585. ** Store the current database page-size in bytes in p->nPgsz.
  149586. **
  149587. ** If *pRc is non-zero when this function is called, it is a no-op.
  149588. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  149589. ** before returning.
  149590. */
  149591. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  149592. if( *pRc==SQLITE_OK ){
  149593. int rc; /* Return code */
  149594. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  149595. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  149596. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  149597. if( !zSql ){
  149598. rc = SQLITE_NOMEM;
  149599. }else{
  149600. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  149601. if( rc==SQLITE_OK ){
  149602. sqlite3_step(pStmt);
  149603. p->nPgsz = sqlite3_column_int(pStmt, 0);
  149604. rc = sqlite3_finalize(pStmt);
  149605. }else if( rc==SQLITE_AUTH ){
  149606. p->nPgsz = 1024;
  149607. rc = SQLITE_OK;
  149608. }
  149609. }
  149610. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  149611. sqlite3_free(zSql);
  149612. *pRc = rc;
  149613. }
  149614. }
  149615. /*
  149616. ** "Special" FTS4 arguments are column specifications of the following form:
  149617. **
  149618. ** <key> = <value>
  149619. **
  149620. ** There may not be whitespace surrounding the "=" character. The <value>
  149621. ** term may be quoted, but the <key> may not.
  149622. */
  149623. static int fts3IsSpecialColumn(
  149624. const char *z,
  149625. int *pnKey,
  149626. char **pzValue
  149627. ){
  149628. char *zValue;
  149629. const char *zCsr = z;
  149630. while( *zCsr!='=' ){
  149631. if( *zCsr=='\0' ) return 0;
  149632. zCsr++;
  149633. }
  149634. *pnKey = (int)(zCsr-z);
  149635. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  149636. if( zValue ){
  149637. sqlite3Fts3Dequote(zValue);
  149638. }
  149639. *pzValue = zValue;
  149640. return 1;
  149641. }
  149642. /*
  149643. ** Append the output of a printf() style formatting to an existing string.
  149644. */
  149645. static void fts3Appendf(
  149646. int *pRc, /* IN/OUT: Error code */
  149647. char **pz, /* IN/OUT: Pointer to string buffer */
  149648. const char *zFormat, /* Printf format string to append */
  149649. ... /* Arguments for printf format string */
  149650. ){
  149651. if( *pRc==SQLITE_OK ){
  149652. va_list ap;
  149653. char *z;
  149654. va_start(ap, zFormat);
  149655. z = sqlite3_vmprintf(zFormat, ap);
  149656. va_end(ap);
  149657. if( z && *pz ){
  149658. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  149659. sqlite3_free(z);
  149660. z = z2;
  149661. }
  149662. if( z==0 ) *pRc = SQLITE_NOMEM;
  149663. sqlite3_free(*pz);
  149664. *pz = z;
  149665. }
  149666. }
  149667. /*
  149668. ** Return a copy of input string zInput enclosed in double-quotes (") and
  149669. ** with all double quote characters escaped. For example:
  149670. **
  149671. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  149672. **
  149673. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  149674. ** is the callers responsibility to call sqlite3_free() to release this
  149675. ** memory.
  149676. */
  149677. static char *fts3QuoteId(char const *zInput){
  149678. int nRet;
  149679. char *zRet;
  149680. nRet = 2 + (int)strlen(zInput)*2 + 1;
  149681. zRet = sqlite3_malloc(nRet);
  149682. if( zRet ){
  149683. int i;
  149684. char *z = zRet;
  149685. *(z++) = '"';
  149686. for(i=0; zInput[i]; i++){
  149687. if( zInput[i]=='"' ) *(z++) = '"';
  149688. *(z++) = zInput[i];
  149689. }
  149690. *(z++) = '"';
  149691. *(z++) = '\0';
  149692. }
  149693. return zRet;
  149694. }
  149695. /*
  149696. ** Return a list of comma separated SQL expressions and a FROM clause that
  149697. ** could be used in a SELECT statement such as the following:
  149698. **
  149699. ** SELECT <list of expressions> FROM %_content AS x ...
  149700. **
  149701. ** to return the docid, followed by each column of text data in order
  149702. ** from left to write. If parameter zFunc is not NULL, then instead of
  149703. ** being returned directly each column of text data is passed to an SQL
  149704. ** function named zFunc first. For example, if zFunc is "unzip" and the
  149705. ** table has the three user-defined columns "a", "b", and "c", the following
  149706. ** string is returned:
  149707. **
  149708. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  149709. **
  149710. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  149711. ** is the responsibility of the caller to eventually free it.
  149712. **
  149713. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  149714. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  149715. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  149716. ** no error occurs, *pRc is left unmodified.
  149717. */
  149718. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  149719. char *zRet = 0;
  149720. char *zFree = 0;
  149721. char *zFunction;
  149722. int i;
  149723. if( p->zContentTbl==0 ){
  149724. if( !zFunc ){
  149725. zFunction = "";
  149726. }else{
  149727. zFree = zFunction = fts3QuoteId(zFunc);
  149728. }
  149729. fts3Appendf(pRc, &zRet, "docid");
  149730. for(i=0; i<p->nColumn; i++){
  149731. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  149732. }
  149733. if( p->zLanguageid ){
  149734. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  149735. }
  149736. sqlite3_free(zFree);
  149737. }else{
  149738. fts3Appendf(pRc, &zRet, "rowid");
  149739. for(i=0; i<p->nColumn; i++){
  149740. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  149741. }
  149742. if( p->zLanguageid ){
  149743. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  149744. }
  149745. }
  149746. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  149747. p->zDb,
  149748. (p->zContentTbl ? p->zContentTbl : p->zName),
  149749. (p->zContentTbl ? "" : "_content")
  149750. );
  149751. return zRet;
  149752. }
  149753. /*
  149754. ** Return a list of N comma separated question marks, where N is the number
  149755. ** of columns in the %_content table (one for the docid plus one for each
  149756. ** user-defined text column).
  149757. **
  149758. ** If argument zFunc is not NULL, then all but the first question mark
  149759. ** is preceded by zFunc and an open bracket, and followed by a closed
  149760. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  149761. ** user-defined text columns, the following string is returned:
  149762. **
  149763. ** "?, zip(?), zip(?), zip(?)"
  149764. **
  149765. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  149766. ** is the responsibility of the caller to eventually free it.
  149767. **
  149768. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  149769. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  149770. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  149771. ** no error occurs, *pRc is left unmodified.
  149772. */
  149773. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  149774. char *zRet = 0;
  149775. char *zFree = 0;
  149776. char *zFunction;
  149777. int i;
  149778. if( !zFunc ){
  149779. zFunction = "";
  149780. }else{
  149781. zFree = zFunction = fts3QuoteId(zFunc);
  149782. }
  149783. fts3Appendf(pRc, &zRet, "?");
  149784. for(i=0; i<p->nColumn; i++){
  149785. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  149786. }
  149787. if( p->zLanguageid ){
  149788. fts3Appendf(pRc, &zRet, ", ?");
  149789. }
  149790. sqlite3_free(zFree);
  149791. return zRet;
  149792. }
  149793. /*
  149794. ** This function interprets the string at (*pp) as a non-negative integer
  149795. ** value. It reads the integer and sets *pnOut to the value read, then
  149796. ** sets *pp to point to the byte immediately following the last byte of
  149797. ** the integer value.
  149798. **
  149799. ** Only decimal digits ('0'..'9') may be part of an integer value.
  149800. **
  149801. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  149802. ** the output value undefined. Otherwise SQLITE_OK is returned.
  149803. **
  149804. ** This function is used when parsing the "prefix=" FTS4 parameter.
  149805. */
  149806. static int fts3GobbleInt(const char **pp, int *pnOut){
  149807. const int MAX_NPREFIX = 10000000;
  149808. const char *p; /* Iterator pointer */
  149809. int nInt = 0; /* Output value */
  149810. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  149811. nInt = nInt * 10 + (p[0] - '0');
  149812. if( nInt>MAX_NPREFIX ){
  149813. nInt = 0;
  149814. break;
  149815. }
  149816. }
  149817. if( p==*pp ) return SQLITE_ERROR;
  149818. *pnOut = nInt;
  149819. *pp = p;
  149820. return SQLITE_OK;
  149821. }
  149822. /*
  149823. ** This function is called to allocate an array of Fts3Index structures
  149824. ** representing the indexes maintained by the current FTS table. FTS tables
  149825. ** always maintain the main "terms" index, but may also maintain one or
  149826. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  149827. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  149828. **
  149829. ** Argument zParam is passed the value of the "prefix=" option if one was
  149830. ** specified, or NULL otherwise.
  149831. **
  149832. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  149833. ** the allocated array. *pnIndex is set to the number of elements in the
  149834. ** array. If an error does occur, an SQLite error code is returned.
  149835. **
  149836. ** Regardless of whether or not an error is returned, it is the responsibility
  149837. ** of the caller to call sqlite3_free() on the output array to free it.
  149838. */
  149839. static int fts3PrefixParameter(
  149840. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  149841. int *pnIndex, /* OUT: size of *apIndex[] array */
  149842. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  149843. ){
  149844. struct Fts3Index *aIndex; /* Allocated array */
  149845. int nIndex = 1; /* Number of entries in array */
  149846. if( zParam && zParam[0] ){
  149847. const char *p;
  149848. nIndex++;
  149849. for(p=zParam; *p; p++){
  149850. if( *p==',' ) nIndex++;
  149851. }
  149852. }
  149853. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  149854. *apIndex = aIndex;
  149855. if( !aIndex ){
  149856. return SQLITE_NOMEM;
  149857. }
  149858. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  149859. if( zParam ){
  149860. const char *p = zParam;
  149861. int i;
  149862. for(i=1; i<nIndex; i++){
  149863. int nPrefix = 0;
  149864. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  149865. assert( nPrefix>=0 );
  149866. if( nPrefix==0 ){
  149867. nIndex--;
  149868. i--;
  149869. }else{
  149870. aIndex[i].nPrefix = nPrefix;
  149871. }
  149872. p++;
  149873. }
  149874. }
  149875. *pnIndex = nIndex;
  149876. return SQLITE_OK;
  149877. }
  149878. /*
  149879. ** This function is called when initializing an FTS4 table that uses the
  149880. ** content=xxx option. It determines the number of and names of the columns
  149881. ** of the new FTS4 table.
  149882. **
  149883. ** The third argument passed to this function is the value passed to the
  149884. ** config=xxx option (i.e. "xxx"). This function queries the database for
  149885. ** a table of that name. If found, the output variables are populated
  149886. ** as follows:
  149887. **
  149888. ** *pnCol: Set to the number of columns table xxx has,
  149889. **
  149890. ** *pnStr: Set to the total amount of space required to store a copy
  149891. ** of each columns name, including the nul-terminator.
  149892. **
  149893. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  149894. ** the name of the corresponding column in table xxx. The array
  149895. ** and its contents are allocated using a single allocation. It
  149896. ** is the responsibility of the caller to free this allocation
  149897. ** by eventually passing the *pazCol value to sqlite3_free().
  149898. **
  149899. ** If the table cannot be found, an error code is returned and the output
  149900. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  149901. ** returned (and the output variables are undefined).
  149902. */
  149903. static int fts3ContentColumns(
  149904. sqlite3 *db, /* Database handle */
  149905. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  149906. const char *zTbl, /* Name of content table */
  149907. const char ***pazCol, /* OUT: Malloc'd array of column names */
  149908. int *pnCol, /* OUT: Size of array *pazCol */
  149909. int *pnStr, /* OUT: Bytes of string content */
  149910. char **pzErr /* OUT: error message */
  149911. ){
  149912. int rc = SQLITE_OK; /* Return code */
  149913. char *zSql; /* "SELECT *" statement on zTbl */
  149914. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  149915. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  149916. if( !zSql ){
  149917. rc = SQLITE_NOMEM;
  149918. }else{
  149919. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  149920. if( rc!=SQLITE_OK ){
  149921. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  149922. }
  149923. }
  149924. sqlite3_free(zSql);
  149925. if( rc==SQLITE_OK ){
  149926. const char **azCol; /* Output array */
  149927. int nStr = 0; /* Size of all column names (incl. 0x00) */
  149928. int nCol; /* Number of table columns */
  149929. int i; /* Used to iterate through columns */
  149930. /* Loop through the returned columns. Set nStr to the number of bytes of
  149931. ** space required to store a copy of each column name, including the
  149932. ** nul-terminator byte. */
  149933. nCol = sqlite3_column_count(pStmt);
  149934. for(i=0; i<nCol; i++){
  149935. const char *zCol = sqlite3_column_name(pStmt, i);
  149936. nStr += (int)strlen(zCol) + 1;
  149937. }
  149938. /* Allocate and populate the array to return. */
  149939. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  149940. if( azCol==0 ){
  149941. rc = SQLITE_NOMEM;
  149942. }else{
  149943. char *p = (char *)&azCol[nCol];
  149944. for(i=0; i<nCol; i++){
  149945. const char *zCol = sqlite3_column_name(pStmt, i);
  149946. int n = (int)strlen(zCol)+1;
  149947. memcpy(p, zCol, n);
  149948. azCol[i] = p;
  149949. p += n;
  149950. }
  149951. }
  149952. sqlite3_finalize(pStmt);
  149953. /* Set the output variables. */
  149954. *pnCol = nCol;
  149955. *pnStr = nStr;
  149956. *pazCol = azCol;
  149957. }
  149958. return rc;
  149959. }
  149960. /*
  149961. ** This function is the implementation of both the xConnect and xCreate
  149962. ** methods of the FTS3 virtual table.
  149963. **
  149964. ** The argv[] array contains the following:
  149965. **
  149966. ** argv[0] -> module name ("fts3" or "fts4")
  149967. ** argv[1] -> database name
  149968. ** argv[2] -> table name
  149969. ** argv[...] -> "column name" and other module argument fields.
  149970. */
  149971. static int fts3InitVtab(
  149972. int isCreate, /* True for xCreate, false for xConnect */
  149973. sqlite3 *db, /* The SQLite database connection */
  149974. void *pAux, /* Hash table containing tokenizers */
  149975. int argc, /* Number of elements in argv array */
  149976. const char * const *argv, /* xCreate/xConnect argument array */
  149977. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  149978. char **pzErr /* Write any error message here */
  149979. ){
  149980. Fts3Hash *pHash = (Fts3Hash *)pAux;
  149981. Fts3Table *p = 0; /* Pointer to allocated vtab */
  149982. int rc = SQLITE_OK; /* Return code */
  149983. int i; /* Iterator variable */
  149984. int nByte; /* Size of allocation used for *p */
  149985. int iCol; /* Column index */
  149986. int nString = 0; /* Bytes required to hold all column names */
  149987. int nCol = 0; /* Number of columns in the FTS table */
  149988. char *zCsr; /* Space for holding column names */
  149989. int nDb; /* Bytes required to hold database name */
  149990. int nName; /* Bytes required to hold table name */
  149991. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  149992. const char **aCol; /* Array of column names */
  149993. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  149994. int nIndex = 0; /* Size of aIndex[] array */
  149995. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  149996. /* The results of parsing supported FTS4 key=value options: */
  149997. int bNoDocsize = 0; /* True to omit %_docsize table */
  149998. int bDescIdx = 0; /* True to store descending indexes */
  149999. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  150000. char *zCompress = 0; /* compress=? parameter (or NULL) */
  150001. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  150002. char *zContent = 0; /* content=? parameter (or NULL) */
  150003. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  150004. char **azNotindexed = 0; /* The set of notindexed= columns */
  150005. int nNotindexed = 0; /* Size of azNotindexed[] array */
  150006. assert( strlen(argv[0])==4 );
  150007. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  150008. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  150009. );
  150010. nDb = (int)strlen(argv[1]) + 1;
  150011. nName = (int)strlen(argv[2]) + 1;
  150012. nByte = sizeof(const char *) * (argc-2);
  150013. aCol = (const char **)sqlite3_malloc(nByte);
  150014. if( aCol ){
  150015. memset((void*)aCol, 0, nByte);
  150016. azNotindexed = (char **)sqlite3_malloc(nByte);
  150017. }
  150018. if( azNotindexed ){
  150019. memset(azNotindexed, 0, nByte);
  150020. }
  150021. if( !aCol || !azNotindexed ){
  150022. rc = SQLITE_NOMEM;
  150023. goto fts3_init_out;
  150024. }
  150025. /* Loop through all of the arguments passed by the user to the FTS3/4
  150026. ** module (i.e. all the column names and special arguments). This loop
  150027. ** does the following:
  150028. **
  150029. ** + Figures out the number of columns the FTSX table will have, and
  150030. ** the number of bytes of space that must be allocated to store copies
  150031. ** of the column names.
  150032. **
  150033. ** + If there is a tokenizer specification included in the arguments,
  150034. ** initializes the tokenizer pTokenizer.
  150035. */
  150036. for(i=3; rc==SQLITE_OK && i<argc; i++){
  150037. char const *z = argv[i];
  150038. int nKey;
  150039. char *zVal;
  150040. /* Check if this is a tokenizer specification */
  150041. if( !pTokenizer
  150042. && strlen(z)>8
  150043. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  150044. && 0==sqlite3Fts3IsIdChar(z[8])
  150045. ){
  150046. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  150047. }
  150048. /* Check if it is an FTS4 special argument. */
  150049. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  150050. struct Fts4Option {
  150051. const char *zOpt;
  150052. int nOpt;
  150053. } aFts4Opt[] = {
  150054. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  150055. { "prefix", 6 }, /* 1 -> PREFIX */
  150056. { "compress", 8 }, /* 2 -> COMPRESS */
  150057. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  150058. { "order", 5 }, /* 4 -> ORDER */
  150059. { "content", 7 }, /* 5 -> CONTENT */
  150060. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  150061. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  150062. };
  150063. int iOpt;
  150064. if( !zVal ){
  150065. rc = SQLITE_NOMEM;
  150066. }else{
  150067. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  150068. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  150069. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  150070. break;
  150071. }
  150072. }
  150073. switch( iOpt ){
  150074. case 0: /* MATCHINFO */
  150075. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  150076. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  150077. rc = SQLITE_ERROR;
  150078. }
  150079. bNoDocsize = 1;
  150080. break;
  150081. case 1: /* PREFIX */
  150082. sqlite3_free(zPrefix);
  150083. zPrefix = zVal;
  150084. zVal = 0;
  150085. break;
  150086. case 2: /* COMPRESS */
  150087. sqlite3_free(zCompress);
  150088. zCompress = zVal;
  150089. zVal = 0;
  150090. break;
  150091. case 3: /* UNCOMPRESS */
  150092. sqlite3_free(zUncompress);
  150093. zUncompress = zVal;
  150094. zVal = 0;
  150095. break;
  150096. case 4: /* ORDER */
  150097. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  150098. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  150099. ){
  150100. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  150101. rc = SQLITE_ERROR;
  150102. }
  150103. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  150104. break;
  150105. case 5: /* CONTENT */
  150106. sqlite3_free(zContent);
  150107. zContent = zVal;
  150108. zVal = 0;
  150109. break;
  150110. case 6: /* LANGUAGEID */
  150111. assert( iOpt==6 );
  150112. sqlite3_free(zLanguageid);
  150113. zLanguageid = zVal;
  150114. zVal = 0;
  150115. break;
  150116. case 7: /* NOTINDEXED */
  150117. azNotindexed[nNotindexed++] = zVal;
  150118. zVal = 0;
  150119. break;
  150120. default:
  150121. assert( iOpt==SizeofArray(aFts4Opt) );
  150122. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  150123. rc = SQLITE_ERROR;
  150124. break;
  150125. }
  150126. sqlite3_free(zVal);
  150127. }
  150128. }
  150129. /* Otherwise, the argument is a column name. */
  150130. else {
  150131. nString += (int)(strlen(z) + 1);
  150132. aCol[nCol++] = z;
  150133. }
  150134. }
  150135. /* If a content=xxx option was specified, the following:
  150136. **
  150137. ** 1. Ignore any compress= and uncompress= options.
  150138. **
  150139. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  150140. ** TABLE statement, use all columns from the content table.
  150141. */
  150142. if( rc==SQLITE_OK && zContent ){
  150143. sqlite3_free(zCompress);
  150144. sqlite3_free(zUncompress);
  150145. zCompress = 0;
  150146. zUncompress = 0;
  150147. if( nCol==0 ){
  150148. sqlite3_free((void*)aCol);
  150149. aCol = 0;
  150150. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  150151. /* If a languageid= option was specified, remove the language id
  150152. ** column from the aCol[] array. */
  150153. if( rc==SQLITE_OK && zLanguageid ){
  150154. int j;
  150155. for(j=0; j<nCol; j++){
  150156. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  150157. int k;
  150158. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  150159. nCol--;
  150160. break;
  150161. }
  150162. }
  150163. }
  150164. }
  150165. }
  150166. if( rc!=SQLITE_OK ) goto fts3_init_out;
  150167. if( nCol==0 ){
  150168. assert( nString==0 );
  150169. aCol[0] = "content";
  150170. nString = 8;
  150171. nCol = 1;
  150172. }
  150173. if( pTokenizer==0 ){
  150174. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  150175. if( rc!=SQLITE_OK ) goto fts3_init_out;
  150176. }
  150177. assert( pTokenizer );
  150178. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  150179. if( rc==SQLITE_ERROR ){
  150180. assert( zPrefix );
  150181. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  150182. }
  150183. if( rc!=SQLITE_OK ) goto fts3_init_out;
  150184. /* Allocate and populate the Fts3Table structure. */
  150185. nByte = sizeof(Fts3Table) + /* Fts3Table */
  150186. nCol * sizeof(char *) + /* azColumn */
  150187. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  150188. nCol * sizeof(u8) + /* abNotindexed */
  150189. nName + /* zName */
  150190. nDb + /* zDb */
  150191. nString; /* Space for azColumn strings */
  150192. p = (Fts3Table*)sqlite3_malloc(nByte);
  150193. if( p==0 ){
  150194. rc = SQLITE_NOMEM;
  150195. goto fts3_init_out;
  150196. }
  150197. memset(p, 0, nByte);
  150198. p->db = db;
  150199. p->nColumn = nCol;
  150200. p->nPendingData = 0;
  150201. p->azColumn = (char **)&p[1];
  150202. p->pTokenizer = pTokenizer;
  150203. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  150204. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  150205. p->bHasStat = (u8)isFts4;
  150206. p->bFts4 = (u8)isFts4;
  150207. p->bDescIdx = (u8)bDescIdx;
  150208. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  150209. p->zContentTbl = zContent;
  150210. p->zLanguageid = zLanguageid;
  150211. zContent = 0;
  150212. zLanguageid = 0;
  150213. TESTONLY( p->inTransaction = -1 );
  150214. TESTONLY( p->mxSavepoint = -1 );
  150215. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  150216. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  150217. p->nIndex = nIndex;
  150218. for(i=0; i<nIndex; i++){
  150219. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  150220. }
  150221. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  150222. /* Fill in the zName and zDb fields of the vtab structure. */
  150223. zCsr = (char *)&p->abNotindexed[nCol];
  150224. p->zName = zCsr;
  150225. memcpy(zCsr, argv[2], nName);
  150226. zCsr += nName;
  150227. p->zDb = zCsr;
  150228. memcpy(zCsr, argv[1], nDb);
  150229. zCsr += nDb;
  150230. /* Fill in the azColumn array */
  150231. for(iCol=0; iCol<nCol; iCol++){
  150232. char *z;
  150233. int n = 0;
  150234. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  150235. if( n>0 ){
  150236. memcpy(zCsr, z, n);
  150237. }
  150238. zCsr[n] = '\0';
  150239. sqlite3Fts3Dequote(zCsr);
  150240. p->azColumn[iCol] = zCsr;
  150241. zCsr += n+1;
  150242. assert( zCsr <= &((char *)p)[nByte] );
  150243. }
  150244. /* Fill in the abNotindexed array */
  150245. for(iCol=0; iCol<nCol; iCol++){
  150246. int n = (int)strlen(p->azColumn[iCol]);
  150247. for(i=0; i<nNotindexed; i++){
  150248. char *zNot = azNotindexed[i];
  150249. if( zNot && n==(int)strlen(zNot)
  150250. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  150251. ){
  150252. p->abNotindexed[iCol] = 1;
  150253. sqlite3_free(zNot);
  150254. azNotindexed[i] = 0;
  150255. }
  150256. }
  150257. }
  150258. for(i=0; i<nNotindexed; i++){
  150259. if( azNotindexed[i] ){
  150260. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  150261. rc = SQLITE_ERROR;
  150262. }
  150263. }
  150264. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  150265. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  150266. rc = SQLITE_ERROR;
  150267. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  150268. }
  150269. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  150270. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  150271. if( rc!=SQLITE_OK ) goto fts3_init_out;
  150272. /* If this is an xCreate call, create the underlying tables in the
  150273. ** database. TODO: For xConnect(), it could verify that said tables exist.
  150274. */
  150275. if( isCreate ){
  150276. rc = fts3CreateTables(p);
  150277. }
  150278. /* Check to see if a legacy fts3 table has been "upgraded" by the
  150279. ** addition of a %_stat table so that it can use incremental merge.
  150280. */
  150281. if( !isFts4 && !isCreate ){
  150282. p->bHasStat = 2;
  150283. }
  150284. /* Figure out the page-size for the database. This is required in order to
  150285. ** estimate the cost of loading large doclists from the database. */
  150286. fts3DatabasePageSize(&rc, p);
  150287. p->nNodeSize = p->nPgsz-35;
  150288. /* Declare the table schema to SQLite. */
  150289. fts3DeclareVtab(&rc, p);
  150290. fts3_init_out:
  150291. sqlite3_free(zPrefix);
  150292. sqlite3_free(aIndex);
  150293. sqlite3_free(zCompress);
  150294. sqlite3_free(zUncompress);
  150295. sqlite3_free(zContent);
  150296. sqlite3_free(zLanguageid);
  150297. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  150298. sqlite3_free((void *)aCol);
  150299. sqlite3_free((void *)azNotindexed);
  150300. if( rc!=SQLITE_OK ){
  150301. if( p ){
  150302. fts3DisconnectMethod((sqlite3_vtab *)p);
  150303. }else if( pTokenizer ){
  150304. pTokenizer->pModule->xDestroy(pTokenizer);
  150305. }
  150306. }else{
  150307. assert( p->pSegments==0 );
  150308. *ppVTab = &p->base;
  150309. }
  150310. return rc;
  150311. }
  150312. /*
  150313. ** The xConnect() and xCreate() methods for the virtual table. All the
  150314. ** work is done in function fts3InitVtab().
  150315. */
  150316. static int fts3ConnectMethod(
  150317. sqlite3 *db, /* Database connection */
  150318. void *pAux, /* Pointer to tokenizer hash table */
  150319. int argc, /* Number of elements in argv array */
  150320. const char * const *argv, /* xCreate/xConnect argument array */
  150321. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  150322. char **pzErr /* OUT: sqlite3_malloc'd error message */
  150323. ){
  150324. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  150325. }
  150326. static int fts3CreateMethod(
  150327. sqlite3 *db, /* Database connection */
  150328. void *pAux, /* Pointer to tokenizer hash table */
  150329. int argc, /* Number of elements in argv array */
  150330. const char * const *argv, /* xCreate/xConnect argument array */
  150331. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  150332. char **pzErr /* OUT: sqlite3_malloc'd error message */
  150333. ){
  150334. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  150335. }
  150336. /*
  150337. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  150338. ** extension is currently being used by a version of SQLite too old to
  150339. ** support estimatedRows. In that case this function is a no-op.
  150340. */
  150341. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  150342. #if SQLITE_VERSION_NUMBER>=3008002
  150343. if( sqlite3_libversion_number()>=3008002 ){
  150344. pIdxInfo->estimatedRows = nRow;
  150345. }
  150346. #endif
  150347. }
  150348. /*
  150349. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  150350. ** extension is currently being used by a version of SQLite too old to
  150351. ** support index-info flags. In that case this function is a no-op.
  150352. */
  150353. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  150354. #if SQLITE_VERSION_NUMBER>=3008012
  150355. if( sqlite3_libversion_number()>=3008012 ){
  150356. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  150357. }
  150358. #endif
  150359. }
  150360. /*
  150361. ** Implementation of the xBestIndex method for FTS3 tables. There
  150362. ** are three possible strategies, in order of preference:
  150363. **
  150364. ** 1. Direct lookup by rowid or docid.
  150365. ** 2. Full-text search using a MATCH operator on a non-docid column.
  150366. ** 3. Linear scan of %_content table.
  150367. */
  150368. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  150369. Fts3Table *p = (Fts3Table *)pVTab;
  150370. int i; /* Iterator variable */
  150371. int iCons = -1; /* Index of constraint to use */
  150372. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  150373. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  150374. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  150375. int iIdx;
  150376. /* By default use a full table scan. This is an expensive option,
  150377. ** so search through the constraints to see if a more efficient
  150378. ** strategy is possible.
  150379. */
  150380. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  150381. pInfo->estimatedCost = 5000000;
  150382. for(i=0; i<pInfo->nConstraint; i++){
  150383. int bDocid; /* True if this constraint is on docid */
  150384. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  150385. if( pCons->usable==0 ){
  150386. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  150387. /* There exists an unusable MATCH constraint. This means that if
  150388. ** the planner does elect to use the results of this call as part
  150389. ** of the overall query plan the user will see an "unable to use
  150390. ** function MATCH in the requested context" error. To discourage
  150391. ** this, return a very high cost here. */
  150392. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  150393. pInfo->estimatedCost = 1e50;
  150394. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  150395. return SQLITE_OK;
  150396. }
  150397. continue;
  150398. }
  150399. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  150400. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  150401. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  150402. pInfo->idxNum = FTS3_DOCID_SEARCH;
  150403. pInfo->estimatedCost = 1.0;
  150404. iCons = i;
  150405. }
  150406. /* A MATCH constraint. Use a full-text search.
  150407. **
  150408. ** If there is more than one MATCH constraint available, use the first
  150409. ** one encountered. If there is both a MATCH constraint and a direct
  150410. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  150411. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  150412. ** it would lead to an "unable to use function MATCH in the requested
  150413. ** context" error.
  150414. */
  150415. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  150416. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  150417. ){
  150418. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  150419. pInfo->estimatedCost = 2.0;
  150420. iCons = i;
  150421. }
  150422. /* Equality constraint on the langid column */
  150423. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  150424. && pCons->iColumn==p->nColumn + 2
  150425. ){
  150426. iLangidCons = i;
  150427. }
  150428. if( bDocid ){
  150429. switch( pCons->op ){
  150430. case SQLITE_INDEX_CONSTRAINT_GE:
  150431. case SQLITE_INDEX_CONSTRAINT_GT:
  150432. iDocidGe = i;
  150433. break;
  150434. case SQLITE_INDEX_CONSTRAINT_LE:
  150435. case SQLITE_INDEX_CONSTRAINT_LT:
  150436. iDocidLe = i;
  150437. break;
  150438. }
  150439. }
  150440. }
  150441. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  150442. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  150443. iIdx = 1;
  150444. if( iCons>=0 ){
  150445. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  150446. pInfo->aConstraintUsage[iCons].omit = 1;
  150447. }
  150448. if( iLangidCons>=0 ){
  150449. pInfo->idxNum |= FTS3_HAVE_LANGID;
  150450. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  150451. }
  150452. if( iDocidGe>=0 ){
  150453. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  150454. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  150455. }
  150456. if( iDocidLe>=0 ){
  150457. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  150458. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  150459. }
  150460. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  150461. ** docid) order. Both ascending and descending are possible.
  150462. */
  150463. if( pInfo->nOrderBy==1 ){
  150464. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  150465. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  150466. if( pOrder->desc ){
  150467. pInfo->idxStr = "DESC";
  150468. }else{
  150469. pInfo->idxStr = "ASC";
  150470. }
  150471. pInfo->orderByConsumed = 1;
  150472. }
  150473. }
  150474. assert( p->pSegments==0 );
  150475. return SQLITE_OK;
  150476. }
  150477. /*
  150478. ** Implementation of xOpen method.
  150479. */
  150480. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  150481. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  150482. UNUSED_PARAMETER(pVTab);
  150483. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  150484. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  150485. ** if the allocation fails, return SQLITE_NOMEM.
  150486. */
  150487. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  150488. if( !pCsr ){
  150489. return SQLITE_NOMEM;
  150490. }
  150491. memset(pCsr, 0, sizeof(Fts3Cursor));
  150492. return SQLITE_OK;
  150493. }
  150494. /*
  150495. ** Finalize the statement handle at pCsr->pStmt.
  150496. **
  150497. ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
  150498. ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
  150499. ** pointer there instead of finalizing it.
  150500. */
  150501. static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
  150502. if( pCsr->bSeekStmt ){
  150503. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  150504. if( p->pSeekStmt==0 ){
  150505. p->pSeekStmt = pCsr->pStmt;
  150506. sqlite3_reset(pCsr->pStmt);
  150507. pCsr->pStmt = 0;
  150508. }
  150509. pCsr->bSeekStmt = 0;
  150510. }
  150511. sqlite3_finalize(pCsr->pStmt);
  150512. }
  150513. /*
  150514. ** Free all resources currently held by the cursor passed as the only
  150515. ** argument.
  150516. */
  150517. static void fts3ClearCursor(Fts3Cursor *pCsr){
  150518. fts3CursorFinalizeStmt(pCsr);
  150519. sqlite3Fts3FreeDeferredTokens(pCsr);
  150520. sqlite3_free(pCsr->aDoclist);
  150521. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  150522. sqlite3Fts3ExprFree(pCsr->pExpr);
  150523. memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  150524. }
  150525. /*
  150526. ** Close the cursor. For additional information see the documentation
  150527. ** on the xClose method of the virtual table interface.
  150528. */
  150529. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  150530. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  150531. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  150532. fts3ClearCursor(pCsr);
  150533. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  150534. sqlite3_free(pCsr);
  150535. return SQLITE_OK;
  150536. }
  150537. /*
  150538. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  150539. ** compose and prepare an SQL statement of the form:
  150540. **
  150541. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  150542. **
  150543. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  150544. ** it. If an error occurs, return an SQLite error code.
  150545. */
  150546. static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
  150547. int rc = SQLITE_OK;
  150548. if( pCsr->pStmt==0 ){
  150549. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  150550. char *zSql;
  150551. if( p->pSeekStmt ){
  150552. pCsr->pStmt = p->pSeekStmt;
  150553. p->pSeekStmt = 0;
  150554. }else{
  150555. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  150556. if( !zSql ) return SQLITE_NOMEM;
  150557. rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  150558. sqlite3_free(zSql);
  150559. }
  150560. if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
  150561. }
  150562. return rc;
  150563. }
  150564. /*
  150565. ** Position the pCsr->pStmt statement so that it is on the row
  150566. ** of the %_content table that contains the last match. Return
  150567. ** SQLITE_OK on success.
  150568. */
  150569. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  150570. int rc = SQLITE_OK;
  150571. if( pCsr->isRequireSeek ){
  150572. rc = fts3CursorSeekStmt(pCsr);
  150573. if( rc==SQLITE_OK ){
  150574. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  150575. pCsr->isRequireSeek = 0;
  150576. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  150577. return SQLITE_OK;
  150578. }else{
  150579. rc = sqlite3_reset(pCsr->pStmt);
  150580. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  150581. /* If no row was found and no error has occurred, then the %_content
  150582. ** table is missing a row that is present in the full-text index.
  150583. ** The data structures are corrupt. */
  150584. rc = FTS_CORRUPT_VTAB;
  150585. pCsr->isEof = 1;
  150586. }
  150587. }
  150588. }
  150589. }
  150590. if( rc!=SQLITE_OK && pContext ){
  150591. sqlite3_result_error_code(pContext, rc);
  150592. }
  150593. return rc;
  150594. }
  150595. /*
  150596. ** This function is used to process a single interior node when searching
  150597. ** a b-tree for a term or term prefix. The node data is passed to this
  150598. ** function via the zNode/nNode parameters. The term to search for is
  150599. ** passed in zTerm/nTerm.
  150600. **
  150601. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  150602. ** of the child node that heads the sub-tree that may contain the term.
  150603. **
  150604. ** If piLast is not NULL, then *piLast is set to the right-most child node
  150605. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  150606. ** a prefix.
  150607. **
  150608. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  150609. */
  150610. static int fts3ScanInteriorNode(
  150611. const char *zTerm, /* Term to select leaves for */
  150612. int nTerm, /* Size of term zTerm in bytes */
  150613. const char *zNode, /* Buffer containing segment interior node */
  150614. int nNode, /* Size of buffer at zNode */
  150615. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  150616. sqlite3_int64 *piLast /* OUT: Selected child node */
  150617. ){
  150618. int rc = SQLITE_OK; /* Return code */
  150619. const char *zCsr = zNode; /* Cursor to iterate through node */
  150620. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  150621. char *zBuffer = 0; /* Buffer to load terms into */
  150622. i64 nAlloc = 0; /* Size of allocated buffer */
  150623. int isFirstTerm = 1; /* True when processing first term on page */
  150624. sqlite3_int64 iChild; /* Block id of child node to descend to */
  150625. /* Skip over the 'height' varint that occurs at the start of every
  150626. ** interior node. Then load the blockid of the left-child of the b-tree
  150627. ** node into variable iChild.
  150628. **
  150629. ** Even if the data structure on disk is corrupted, this (reading two
  150630. ** varints from the buffer) does not risk an overread. If zNode is a
  150631. ** root node, then the buffer comes from a SELECT statement. SQLite does
  150632. ** not make this guarantee explicitly, but in practice there are always
  150633. ** either more than 20 bytes of allocated space following the nNode bytes of
  150634. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  150635. ** table, then there are always 20 bytes of zeroed padding following the
  150636. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  150637. */
  150638. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  150639. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  150640. if( zCsr>zEnd ){
  150641. return FTS_CORRUPT_VTAB;
  150642. }
  150643. while( zCsr<zEnd && (piFirst || piLast) ){
  150644. int cmp; /* memcmp() result */
  150645. int nSuffix; /* Size of term suffix */
  150646. int nPrefix = 0; /* Size of term prefix */
  150647. int nBuffer; /* Total term size */
  150648. /* Load the next term on the node into zBuffer. Use realloc() to expand
  150649. ** the size of zBuffer if required. */
  150650. if( !isFirstTerm ){
  150651. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  150652. }
  150653. isFirstTerm = 0;
  150654. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  150655. assert( nPrefix>=0 && nSuffix>=0 );
  150656. if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr ){
  150657. rc = FTS_CORRUPT_VTAB;
  150658. goto finish_scan;
  150659. }
  150660. if( (i64)nPrefix+nSuffix>nAlloc ){
  150661. char *zNew;
  150662. nAlloc = ((i64)nPrefix+nSuffix) * 2;
  150663. zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc);
  150664. if( !zNew ){
  150665. rc = SQLITE_NOMEM;
  150666. goto finish_scan;
  150667. }
  150668. zBuffer = zNew;
  150669. }
  150670. assert( zBuffer );
  150671. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  150672. nBuffer = nPrefix + nSuffix;
  150673. zCsr += nSuffix;
  150674. /* Compare the term we are searching for with the term just loaded from
  150675. ** the interior node. If the specified term is greater than or equal
  150676. ** to the term from the interior node, then all terms on the sub-tree
  150677. ** headed by node iChild are smaller than zTerm. No need to search
  150678. ** iChild.
  150679. **
  150680. ** If the interior node term is larger than the specified term, then
  150681. ** the tree headed by iChild may contain the specified term.
  150682. */
  150683. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  150684. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  150685. *piFirst = iChild;
  150686. piFirst = 0;
  150687. }
  150688. if( piLast && cmp<0 ){
  150689. *piLast = iChild;
  150690. piLast = 0;
  150691. }
  150692. iChild++;
  150693. };
  150694. if( piFirst ) *piFirst = iChild;
  150695. if( piLast ) *piLast = iChild;
  150696. finish_scan:
  150697. sqlite3_free(zBuffer);
  150698. return rc;
  150699. }
  150700. /*
  150701. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  150702. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  150703. ** contains a term. This function searches the sub-tree headed by the zNode
  150704. ** node for the range of leaf nodes that may contain the specified term
  150705. ** or terms for which the specified term is a prefix.
  150706. **
  150707. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  150708. ** left-most leaf node in the tree that may contain the specified term.
  150709. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  150710. ** right-most leaf node that may contain a term for which the specified
  150711. ** term is a prefix.
  150712. **
  150713. ** It is possible that the range of returned leaf nodes does not contain
  150714. ** the specified term or any terms for which it is a prefix. However, if the
  150715. ** segment does contain any such terms, they are stored within the identified
  150716. ** range. Because this function only inspects interior segment nodes (and
  150717. ** never loads leaf nodes into memory), it is not possible to be sure.
  150718. **
  150719. ** If an error occurs, an error code other than SQLITE_OK is returned.
  150720. */
  150721. static int fts3SelectLeaf(
  150722. Fts3Table *p, /* Virtual table handle */
  150723. const char *zTerm, /* Term to select leaves for */
  150724. int nTerm, /* Size of term zTerm in bytes */
  150725. const char *zNode, /* Buffer containing segment interior node */
  150726. int nNode, /* Size of buffer at zNode */
  150727. sqlite3_int64 *piLeaf, /* Selected leaf node */
  150728. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  150729. ){
  150730. int rc = SQLITE_OK; /* Return code */
  150731. int iHeight; /* Height of this node in tree */
  150732. assert( piLeaf || piLeaf2 );
  150733. fts3GetVarint32(zNode, &iHeight);
  150734. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  150735. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  150736. if( rc==SQLITE_OK && iHeight>1 ){
  150737. char *zBlob = 0; /* Blob read from %_segments table */
  150738. int nBlob = 0; /* Size of zBlob in bytes */
  150739. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  150740. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  150741. if( rc==SQLITE_OK ){
  150742. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  150743. }
  150744. sqlite3_free(zBlob);
  150745. piLeaf = 0;
  150746. zBlob = 0;
  150747. }
  150748. if( rc==SQLITE_OK ){
  150749. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  150750. }
  150751. if( rc==SQLITE_OK ){
  150752. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  150753. }
  150754. sqlite3_free(zBlob);
  150755. }
  150756. return rc;
  150757. }
  150758. /*
  150759. ** This function is used to create delta-encoded serialized lists of FTS3
  150760. ** varints. Each call to this function appends a single varint to a list.
  150761. */
  150762. static void fts3PutDeltaVarint(
  150763. char **pp, /* IN/OUT: Output pointer */
  150764. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  150765. sqlite3_int64 iVal /* Write this value to the list */
  150766. ){
  150767. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  150768. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  150769. *piPrev = iVal;
  150770. }
  150771. /*
  150772. ** When this function is called, *ppPoslist is assumed to point to the
  150773. ** start of a position-list. After it returns, *ppPoslist points to the
  150774. ** first byte after the position-list.
  150775. **
  150776. ** A position list is list of positions (delta encoded) and columns for
  150777. ** a single document record of a doclist. So, in other words, this
  150778. ** routine advances *ppPoslist so that it points to the next docid in
  150779. ** the doclist, or to the first byte past the end of the doclist.
  150780. **
  150781. ** If pp is not NULL, then the contents of the position list are copied
  150782. ** to *pp. *pp is set to point to the first byte past the last byte copied
  150783. ** before this function returns.
  150784. */
  150785. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  150786. char *pEnd = *ppPoslist;
  150787. char c = 0;
  150788. /* The end of a position list is marked by a zero encoded as an FTS3
  150789. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  150790. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  150791. ** of some other, multi-byte, value.
  150792. **
  150793. ** The following while-loop moves pEnd to point to the first byte that is not
  150794. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  150795. ** pEnd once more so that it points to the byte immediately following the
  150796. ** last byte in the position-list.
  150797. */
  150798. while( *pEnd | c ){
  150799. c = *pEnd++ & 0x80;
  150800. testcase( c!=0 && (*pEnd)==0 );
  150801. }
  150802. pEnd++; /* Advance past the POS_END terminator byte */
  150803. if( pp ){
  150804. int n = (int)(pEnd - *ppPoslist);
  150805. char *p = *pp;
  150806. memcpy(p, *ppPoslist, n);
  150807. p += n;
  150808. *pp = p;
  150809. }
  150810. *ppPoslist = pEnd;
  150811. }
  150812. /*
  150813. ** When this function is called, *ppPoslist is assumed to point to the
  150814. ** start of a column-list. After it returns, *ppPoslist points to the
  150815. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  150816. **
  150817. ** A column-list is list of delta-encoded positions for a single column
  150818. ** within a single document within a doclist.
  150819. **
  150820. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  150821. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  150822. ** the POS_COLUMN or POS_END that terminates the column-list.
  150823. **
  150824. ** If pp is not NULL, then the contents of the column-list are copied
  150825. ** to *pp. *pp is set to point to the first byte past the last byte copied
  150826. ** before this function returns. The POS_COLUMN or POS_END terminator
  150827. ** is not copied into *pp.
  150828. */
  150829. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  150830. char *pEnd = *ppPoslist;
  150831. char c = 0;
  150832. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  150833. ** not part of a multi-byte varint.
  150834. */
  150835. while( 0xFE & (*pEnd | c) ){
  150836. c = *pEnd++ & 0x80;
  150837. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  150838. }
  150839. if( pp ){
  150840. int n = (int)(pEnd - *ppPoslist);
  150841. char *p = *pp;
  150842. memcpy(p, *ppPoslist, n);
  150843. p += n;
  150844. *pp = p;
  150845. }
  150846. *ppPoslist = pEnd;
  150847. }
  150848. /*
  150849. ** Value used to signify the end of an position-list. This is safe because
  150850. ** it is not possible to have a document with 2^31 terms.
  150851. */
  150852. #define POSITION_LIST_END 0x7fffffff
  150853. /*
  150854. ** This function is used to help parse position-lists. When this function is
  150855. ** called, *pp may point to the start of the next varint in the position-list
  150856. ** being parsed, or it may point to 1 byte past the end of the position-list
  150857. ** (in which case **pp will be a terminator bytes POS_END (0) or
  150858. ** (1)).
  150859. **
  150860. ** If *pp points past the end of the current position-list, set *pi to
  150861. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  150862. ** increment the current value of *pi by the value read, and set *pp to
  150863. ** point to the next value before returning.
  150864. **
  150865. ** Before calling this routine *pi must be initialized to the value of
  150866. ** the previous position, or zero if we are reading the first position
  150867. ** in the position-list. Because positions are delta-encoded, the value
  150868. ** of the previous position is needed in order to compute the value of
  150869. ** the next position.
  150870. */
  150871. static void fts3ReadNextPos(
  150872. char **pp, /* IN/OUT: Pointer into position-list buffer */
  150873. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  150874. ){
  150875. if( (**pp)&0xFE ){
  150876. fts3GetDeltaVarint(pp, pi);
  150877. *pi -= 2;
  150878. }else{
  150879. *pi = POSITION_LIST_END;
  150880. }
  150881. }
  150882. /*
  150883. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  150884. ** the value of iCol encoded as a varint to *pp. This will start a new
  150885. ** column list.
  150886. **
  150887. ** Set *pp to point to the byte just after the last byte written before
  150888. ** returning (do not modify it if iCol==0). Return the total number of bytes
  150889. ** written (0 if iCol==0).
  150890. */
  150891. static int fts3PutColNumber(char **pp, int iCol){
  150892. int n = 0; /* Number of bytes written */
  150893. if( iCol ){
  150894. char *p = *pp; /* Output pointer */
  150895. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  150896. *p = 0x01;
  150897. *pp = &p[n];
  150898. }
  150899. return n;
  150900. }
  150901. /*
  150902. ** Compute the union of two position lists. The output written
  150903. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  150904. ** order and with any duplicates removed. All pointers are
  150905. ** updated appropriately. The caller is responsible for insuring
  150906. ** that there is enough space in *pp to hold the complete output.
  150907. */
  150908. static void fts3PoslistMerge(
  150909. char **pp, /* Output buffer */
  150910. char **pp1, /* Left input list */
  150911. char **pp2 /* Right input list */
  150912. ){
  150913. char *p = *pp;
  150914. char *p1 = *pp1;
  150915. char *p2 = *pp2;
  150916. while( *p1 || *p2 ){
  150917. int iCol1; /* The current column index in pp1 */
  150918. int iCol2; /* The current column index in pp2 */
  150919. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  150920. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  150921. else iCol1 = 0;
  150922. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  150923. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  150924. else iCol2 = 0;
  150925. if( iCol1==iCol2 ){
  150926. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  150927. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  150928. sqlite3_int64 iPrev = 0;
  150929. int n = fts3PutColNumber(&p, iCol1);
  150930. p1 += n;
  150931. p2 += n;
  150932. /* At this point, both p1 and p2 point to the start of column-lists
  150933. ** for the same column (the column with index iCol1 and iCol2).
  150934. ** A column-list is a list of non-negative delta-encoded varints, each
  150935. ** incremented by 2 before being stored. Each list is terminated by a
  150936. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  150937. ** and writes the results to buffer p. p is left pointing to the byte
  150938. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  150939. ** written to the output.
  150940. */
  150941. fts3GetDeltaVarint(&p1, &i1);
  150942. fts3GetDeltaVarint(&p2, &i2);
  150943. do {
  150944. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  150945. iPrev -= 2;
  150946. if( i1==i2 ){
  150947. fts3ReadNextPos(&p1, &i1);
  150948. fts3ReadNextPos(&p2, &i2);
  150949. }else if( i1<i2 ){
  150950. fts3ReadNextPos(&p1, &i1);
  150951. }else{
  150952. fts3ReadNextPos(&p2, &i2);
  150953. }
  150954. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  150955. }else if( iCol1<iCol2 ){
  150956. p1 += fts3PutColNumber(&p, iCol1);
  150957. fts3ColumnlistCopy(&p, &p1);
  150958. }else{
  150959. p2 += fts3PutColNumber(&p, iCol2);
  150960. fts3ColumnlistCopy(&p, &p2);
  150961. }
  150962. }
  150963. *p++ = POS_END;
  150964. *pp = p;
  150965. *pp1 = p1 + 1;
  150966. *pp2 = p2 + 1;
  150967. }
  150968. /*
  150969. ** This function is used to merge two position lists into one. When it is
  150970. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  150971. ** the part of a doclist that follows each document id. For example, if a row
  150972. ** contains:
  150973. **
  150974. ** 'a b c'|'x y z'|'a b b a'
  150975. **
  150976. ** Then the position list for this row for token 'b' would consist of:
  150977. **
  150978. ** 0x02 0x01 0x02 0x03 0x03 0x00
  150979. **
  150980. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  150981. ** byte following the 0x00 terminator of their respective position lists.
  150982. **
  150983. ** If isSaveLeft is 0, an entry is added to the output position list for
  150984. ** each position in *pp2 for which there exists one or more positions in
  150985. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  150986. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  150987. ** slots before it.
  150988. **
  150989. ** e.g. nToken==1 searches for adjacent positions.
  150990. */
  150991. static int fts3PoslistPhraseMerge(
  150992. char **pp, /* IN/OUT: Preallocated output buffer */
  150993. int nToken, /* Maximum difference in token positions */
  150994. int isSaveLeft, /* Save the left position */
  150995. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  150996. char **pp1, /* IN/OUT: Left input list */
  150997. char **pp2 /* IN/OUT: Right input list */
  150998. ){
  150999. char *p = *pp;
  151000. char *p1 = *pp1;
  151001. char *p2 = *pp2;
  151002. int iCol1 = 0;
  151003. int iCol2 = 0;
  151004. /* Never set both isSaveLeft and isExact for the same invocation. */
  151005. assert( isSaveLeft==0 || isExact==0 );
  151006. assert( p!=0 && *p1!=0 && *p2!=0 );
  151007. if( *p1==POS_COLUMN ){
  151008. p1++;
  151009. p1 += fts3GetVarint32(p1, &iCol1);
  151010. }
  151011. if( *p2==POS_COLUMN ){
  151012. p2++;
  151013. p2 += fts3GetVarint32(p2, &iCol2);
  151014. }
  151015. while( 1 ){
  151016. if( iCol1==iCol2 ){
  151017. char *pSave = p;
  151018. sqlite3_int64 iPrev = 0;
  151019. sqlite3_int64 iPos1 = 0;
  151020. sqlite3_int64 iPos2 = 0;
  151021. if( iCol1 ){
  151022. *p++ = POS_COLUMN;
  151023. p += sqlite3Fts3PutVarint(p, iCol1);
  151024. }
  151025. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  151026. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  151027. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  151028. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  151029. while( 1 ){
  151030. if( iPos2==iPos1+nToken
  151031. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  151032. ){
  151033. sqlite3_int64 iSave;
  151034. iSave = isSaveLeft ? iPos1 : iPos2;
  151035. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  151036. pSave = 0;
  151037. assert( p );
  151038. }
  151039. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  151040. if( (*p2&0xFE)==0 ) break;
  151041. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  151042. }else{
  151043. if( (*p1&0xFE)==0 ) break;
  151044. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  151045. }
  151046. }
  151047. if( pSave ){
  151048. assert( pp && p );
  151049. p = pSave;
  151050. }
  151051. fts3ColumnlistCopy(0, &p1);
  151052. fts3ColumnlistCopy(0, &p2);
  151053. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  151054. if( 0==*p1 || 0==*p2 ) break;
  151055. p1++;
  151056. p1 += fts3GetVarint32(p1, &iCol1);
  151057. p2++;
  151058. p2 += fts3GetVarint32(p2, &iCol2);
  151059. }
  151060. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  151061. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  151062. ** end of the position list, or the 0x01 that precedes the next
  151063. ** column-number in the position list.
  151064. */
  151065. else if( iCol1<iCol2 ){
  151066. fts3ColumnlistCopy(0, &p1);
  151067. if( 0==*p1 ) break;
  151068. p1++;
  151069. p1 += fts3GetVarint32(p1, &iCol1);
  151070. }else{
  151071. fts3ColumnlistCopy(0, &p2);
  151072. if( 0==*p2 ) break;
  151073. p2++;
  151074. p2 += fts3GetVarint32(p2, &iCol2);
  151075. }
  151076. }
  151077. fts3PoslistCopy(0, &p2);
  151078. fts3PoslistCopy(0, &p1);
  151079. *pp1 = p1;
  151080. *pp2 = p2;
  151081. if( *pp==p ){
  151082. return 0;
  151083. }
  151084. *p++ = 0x00;
  151085. *pp = p;
  151086. return 1;
  151087. }
  151088. /*
  151089. ** Merge two position-lists as required by the NEAR operator. The argument
  151090. ** position lists correspond to the left and right phrases of an expression
  151091. ** like:
  151092. **
  151093. ** "phrase 1" NEAR "phrase number 2"
  151094. **
  151095. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  151096. ** expression and *pp2 to the right. As usual, the indexes in the position
  151097. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  151098. ** in the example above).
  151099. **
  151100. ** The output position list - written to *pp - is a copy of *pp2 with those
  151101. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  151102. */
  151103. static int fts3PoslistNearMerge(
  151104. char **pp, /* Output buffer */
  151105. char *aTmp, /* Temporary buffer space */
  151106. int nRight, /* Maximum difference in token positions */
  151107. int nLeft, /* Maximum difference in token positions */
  151108. char **pp1, /* IN/OUT: Left input list */
  151109. char **pp2 /* IN/OUT: Right input list */
  151110. ){
  151111. char *p1 = *pp1;
  151112. char *p2 = *pp2;
  151113. char *pTmp1 = aTmp;
  151114. char *pTmp2;
  151115. char *aTmp2;
  151116. int res = 1;
  151117. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  151118. aTmp2 = pTmp2 = pTmp1;
  151119. *pp1 = p1;
  151120. *pp2 = p2;
  151121. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  151122. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  151123. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  151124. }else if( pTmp1!=aTmp ){
  151125. fts3PoslistCopy(pp, &aTmp);
  151126. }else if( pTmp2!=aTmp2 ){
  151127. fts3PoslistCopy(pp, &aTmp2);
  151128. }else{
  151129. res = 0;
  151130. }
  151131. return res;
  151132. }
  151133. /*
  151134. ** An instance of this function is used to merge together the (potentially
  151135. ** large number of) doclists for each term that matches a prefix query.
  151136. ** See function fts3TermSelectMerge() for details.
  151137. */
  151138. typedef struct TermSelect TermSelect;
  151139. struct TermSelect {
  151140. char *aaOutput[16]; /* Malloc'd output buffers */
  151141. int anOutput[16]; /* Size each output buffer in bytes */
  151142. };
  151143. /*
  151144. ** This function is used to read a single varint from a buffer. Parameter
  151145. ** pEnd points 1 byte past the end of the buffer. When this function is
  151146. ** called, if *pp points to pEnd or greater, then the end of the buffer
  151147. ** has been reached. In this case *pp is set to 0 and the function returns.
  151148. **
  151149. ** If *pp does not point to or past pEnd, then a single varint is read
  151150. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  151151. **
  151152. ** If bDescIdx is false, the value read is added to *pVal before returning.
  151153. ** If it is true, the value read is subtracted from *pVal before this
  151154. ** function returns.
  151155. */
  151156. static void fts3GetDeltaVarint3(
  151157. char **pp, /* IN/OUT: Point to read varint from */
  151158. char *pEnd, /* End of buffer */
  151159. int bDescIdx, /* True if docids are descending */
  151160. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  151161. ){
  151162. if( *pp>=pEnd ){
  151163. *pp = 0;
  151164. }else{
  151165. sqlite3_int64 iVal;
  151166. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  151167. if( bDescIdx ){
  151168. *pVal -= iVal;
  151169. }else{
  151170. *pVal += iVal;
  151171. }
  151172. }
  151173. }
  151174. /*
  151175. ** This function is used to write a single varint to a buffer. The varint
  151176. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  151177. ** end of the value written.
  151178. **
  151179. ** If *pbFirst is zero when this function is called, the value written to
  151180. ** the buffer is that of parameter iVal.
  151181. **
  151182. ** If *pbFirst is non-zero when this function is called, then the value
  151183. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  151184. ** (if bDescIdx is non-zero).
  151185. **
  151186. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  151187. ** to the value of parameter iVal.
  151188. */
  151189. static void fts3PutDeltaVarint3(
  151190. char **pp, /* IN/OUT: Output pointer */
  151191. int bDescIdx, /* True for descending docids */
  151192. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  151193. int *pbFirst, /* IN/OUT: True after first int written */
  151194. sqlite3_int64 iVal /* Write this value to the list */
  151195. ){
  151196. sqlite3_int64 iWrite;
  151197. if( bDescIdx==0 || *pbFirst==0 ){
  151198. iWrite = iVal - *piPrev;
  151199. }else{
  151200. iWrite = *piPrev - iVal;
  151201. }
  151202. assert( *pbFirst || *piPrev==0 );
  151203. assert( *pbFirst==0 || iWrite>0 );
  151204. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  151205. *piPrev = iVal;
  151206. *pbFirst = 1;
  151207. }
  151208. /*
  151209. ** This macro is used by various functions that merge doclists. The two
  151210. ** arguments are 64-bit docid values. If the value of the stack variable
  151211. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  151212. ** Otherwise, (i2-i1).
  151213. **
  151214. ** Using this makes it easier to write code that can merge doclists that are
  151215. ** sorted in either ascending or descending order.
  151216. */
  151217. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  151218. /*
  151219. ** This function does an "OR" merge of two doclists (output contains all
  151220. ** positions contained in either argument doclist). If the docids in the
  151221. ** input doclists are sorted in ascending order, parameter bDescDoclist
  151222. ** should be false. If they are sorted in ascending order, it should be
  151223. ** passed a non-zero value.
  151224. **
  151225. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  151226. ** containing the output doclist and SQLITE_OK is returned. In this case
  151227. ** *pnOut is set to the number of bytes in the output doclist.
  151228. **
  151229. ** If an error occurs, an SQLite error code is returned. The output values
  151230. ** are undefined in this case.
  151231. */
  151232. static int fts3DoclistOrMerge(
  151233. int bDescDoclist, /* True if arguments are desc */
  151234. char *a1, int n1, /* First doclist */
  151235. char *a2, int n2, /* Second doclist */
  151236. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  151237. ){
  151238. sqlite3_int64 i1 = 0;
  151239. sqlite3_int64 i2 = 0;
  151240. sqlite3_int64 iPrev = 0;
  151241. char *pEnd1 = &a1[n1];
  151242. char *pEnd2 = &a2[n2];
  151243. char *p1 = a1;
  151244. char *p2 = a2;
  151245. char *p;
  151246. char *aOut;
  151247. int bFirstOut = 0;
  151248. *paOut = 0;
  151249. *pnOut = 0;
  151250. /* Allocate space for the output. Both the input and output doclists
  151251. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  151252. ** then the first docid in each list is simply encoded as a varint. For
  151253. ** each subsequent docid, the varint stored is the difference between the
  151254. ** current and previous docid (a positive number - since the list is in
  151255. ** ascending order).
  151256. **
  151257. ** The first docid written to the output is therefore encoded using the
  151258. ** same number of bytes as it is in whichever of the input lists it is
  151259. ** read from. And each subsequent docid read from the same input list
  151260. ** consumes either the same or less bytes as it did in the input (since
  151261. ** the difference between it and the previous value in the output must
  151262. ** be a positive value less than or equal to the delta value read from
  151263. ** the input list). The same argument applies to all but the first docid
  151264. ** read from the 'other' list. And to the contents of all position lists
  151265. ** that will be copied and merged from the input to the output.
  151266. **
  151267. ** However, if the first docid copied to the output is a negative number,
  151268. ** then the encoding of the first docid from the 'other' input list may
  151269. ** be larger in the output than it was in the input (since the delta value
  151270. ** may be a larger positive integer than the actual docid).
  151271. **
  151272. ** The space required to store the output is therefore the sum of the
  151273. ** sizes of the two inputs, plus enough space for exactly one of the input
  151274. ** docids to grow.
  151275. **
  151276. ** A symetric argument may be made if the doclists are in descending
  151277. ** order.
  151278. */
  151279. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  151280. if( !aOut ) return SQLITE_NOMEM;
  151281. p = aOut;
  151282. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  151283. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  151284. while( p1 || p2 ){
  151285. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  151286. if( p2 && p1 && iDiff==0 ){
  151287. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  151288. fts3PoslistMerge(&p, &p1, &p2);
  151289. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  151290. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  151291. }else if( !p2 || (p1 && iDiff<0) ){
  151292. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  151293. fts3PoslistCopy(&p, &p1);
  151294. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  151295. }else{
  151296. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  151297. fts3PoslistCopy(&p, &p2);
  151298. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  151299. }
  151300. }
  151301. *paOut = aOut;
  151302. *pnOut = (int)(p-aOut);
  151303. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  151304. return SQLITE_OK;
  151305. }
  151306. /*
  151307. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  151308. ** the output contains a copy of each position from the right-hand input
  151309. ** doclist for which there is a position in the left-hand input doclist
  151310. ** exactly nDist tokens before it.
  151311. **
  151312. ** If the docids in the input doclists are sorted in ascending order,
  151313. ** parameter bDescDoclist should be false. If they are sorted in ascending
  151314. ** order, it should be passed a non-zero value.
  151315. **
  151316. ** The right-hand input doclist is overwritten by this function.
  151317. */
  151318. static int fts3DoclistPhraseMerge(
  151319. int bDescDoclist, /* True if arguments are desc */
  151320. int nDist, /* Distance from left to right (1=adjacent) */
  151321. char *aLeft, int nLeft, /* Left doclist */
  151322. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  151323. ){
  151324. sqlite3_int64 i1 = 0;
  151325. sqlite3_int64 i2 = 0;
  151326. sqlite3_int64 iPrev = 0;
  151327. char *aRight = *paRight;
  151328. char *pEnd1 = &aLeft[nLeft];
  151329. char *pEnd2 = &aRight[*pnRight];
  151330. char *p1 = aLeft;
  151331. char *p2 = aRight;
  151332. char *p;
  151333. int bFirstOut = 0;
  151334. char *aOut;
  151335. assert( nDist>0 );
  151336. if( bDescDoclist ){
  151337. aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
  151338. if( aOut==0 ) return SQLITE_NOMEM;
  151339. }else{
  151340. aOut = aRight;
  151341. }
  151342. p = aOut;
  151343. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  151344. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  151345. while( p1 && p2 ){
  151346. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  151347. if( iDiff==0 ){
  151348. char *pSave = p;
  151349. sqlite3_int64 iPrevSave = iPrev;
  151350. int bFirstOutSave = bFirstOut;
  151351. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  151352. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  151353. p = pSave;
  151354. iPrev = iPrevSave;
  151355. bFirstOut = bFirstOutSave;
  151356. }
  151357. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  151358. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  151359. }else if( iDiff<0 ){
  151360. fts3PoslistCopy(0, &p1);
  151361. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  151362. }else{
  151363. fts3PoslistCopy(0, &p2);
  151364. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  151365. }
  151366. }
  151367. *pnRight = (int)(p - aOut);
  151368. if( bDescDoclist ){
  151369. sqlite3_free(aRight);
  151370. *paRight = aOut;
  151371. }
  151372. return SQLITE_OK;
  151373. }
  151374. /*
  151375. ** Argument pList points to a position list nList bytes in size. This
  151376. ** function checks to see if the position list contains any entries for
  151377. ** a token in position 0 (of any column). If so, it writes argument iDelta
  151378. ** to the output buffer pOut, followed by a position list consisting only
  151379. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  151380. ** The value returned is the number of bytes written to pOut (if any).
  151381. */
  151382. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  151383. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  151384. char *pList, /* Position list (no 0x00 term) */
  151385. int nList, /* Size of pList in bytes */
  151386. char *pOut /* Write output here */
  151387. ){
  151388. int nOut = 0;
  151389. int bWritten = 0; /* True once iDelta has been written */
  151390. char *p = pList;
  151391. char *pEnd = &pList[nList];
  151392. if( *p!=0x01 ){
  151393. if( *p==0x02 ){
  151394. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  151395. pOut[nOut++] = 0x02;
  151396. bWritten = 1;
  151397. }
  151398. fts3ColumnlistCopy(0, &p);
  151399. }
  151400. while( p<pEnd ){
  151401. sqlite3_int64 iCol;
  151402. p++;
  151403. p += sqlite3Fts3GetVarint(p, &iCol);
  151404. if( *p==0x02 ){
  151405. if( bWritten==0 ){
  151406. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  151407. bWritten = 1;
  151408. }
  151409. pOut[nOut++] = 0x01;
  151410. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  151411. pOut[nOut++] = 0x02;
  151412. }
  151413. fts3ColumnlistCopy(0, &p);
  151414. }
  151415. if( bWritten ){
  151416. pOut[nOut++] = 0x00;
  151417. }
  151418. return nOut;
  151419. }
  151420. /*
  151421. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  151422. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  151423. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  151424. **
  151425. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  151426. ** the responsibility of the caller to free any doclists left in the
  151427. ** TermSelect.aaOutput[] array.
  151428. */
  151429. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  151430. char *aOut = 0;
  151431. int nOut = 0;
  151432. int i;
  151433. /* Loop through the doclists in the aaOutput[] array. Merge them all
  151434. ** into a single doclist.
  151435. */
  151436. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  151437. if( pTS->aaOutput[i] ){
  151438. if( !aOut ){
  151439. aOut = pTS->aaOutput[i];
  151440. nOut = pTS->anOutput[i];
  151441. pTS->aaOutput[i] = 0;
  151442. }else{
  151443. int nNew;
  151444. char *aNew;
  151445. int rc = fts3DoclistOrMerge(p->bDescIdx,
  151446. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  151447. );
  151448. if( rc!=SQLITE_OK ){
  151449. sqlite3_free(aOut);
  151450. return rc;
  151451. }
  151452. sqlite3_free(pTS->aaOutput[i]);
  151453. sqlite3_free(aOut);
  151454. pTS->aaOutput[i] = 0;
  151455. aOut = aNew;
  151456. nOut = nNew;
  151457. }
  151458. }
  151459. }
  151460. pTS->aaOutput[0] = aOut;
  151461. pTS->anOutput[0] = nOut;
  151462. return SQLITE_OK;
  151463. }
  151464. /*
  151465. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  151466. ** as the first argument. The merge is an "OR" merge (see function
  151467. ** fts3DoclistOrMerge() for details).
  151468. **
  151469. ** This function is called with the doclist for each term that matches
  151470. ** a queried prefix. It merges all these doclists into one, the doclist
  151471. ** for the specified prefix. Since there can be a very large number of
  151472. ** doclists to merge, the merging is done pair-wise using the TermSelect
  151473. ** object.
  151474. **
  151475. ** This function returns SQLITE_OK if the merge is successful, or an
  151476. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  151477. */
  151478. static int fts3TermSelectMerge(
  151479. Fts3Table *p, /* FTS table handle */
  151480. TermSelect *pTS, /* TermSelect object to merge into */
  151481. char *aDoclist, /* Pointer to doclist */
  151482. int nDoclist /* Size of aDoclist in bytes */
  151483. ){
  151484. if( pTS->aaOutput[0]==0 ){
  151485. /* If this is the first term selected, copy the doclist to the output
  151486. ** buffer using memcpy().
  151487. **
  151488. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  151489. ** allocation. This is so as to ensure that the buffer is big enough
  151490. ** to hold the current doclist AND'd with any other doclist. If the
  151491. ** doclists are stored in order=ASC order, this padding would not be
  151492. ** required (since the size of [doclistA AND doclistB] is always less
  151493. ** than or equal to the size of [doclistA] in that case). But this is
  151494. ** not true for order=DESC. For example, a doclist containing (1, -1)
  151495. ** may be smaller than (-1), as in the first example the -1 may be stored
  151496. ** as a single-byte delta, whereas in the second it must be stored as a
  151497. ** FTS3_VARINT_MAX byte varint.
  151498. **
  151499. ** Similar padding is added in the fts3DoclistOrMerge() function.
  151500. */
  151501. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  151502. pTS->anOutput[0] = nDoclist;
  151503. if( pTS->aaOutput[0] ){
  151504. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  151505. }else{
  151506. return SQLITE_NOMEM;
  151507. }
  151508. }else{
  151509. char *aMerge = aDoclist;
  151510. int nMerge = nDoclist;
  151511. int iOut;
  151512. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  151513. if( pTS->aaOutput[iOut]==0 ){
  151514. assert( iOut>0 );
  151515. pTS->aaOutput[iOut] = aMerge;
  151516. pTS->anOutput[iOut] = nMerge;
  151517. break;
  151518. }else{
  151519. char *aNew;
  151520. int nNew;
  151521. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  151522. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  151523. );
  151524. if( rc!=SQLITE_OK ){
  151525. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  151526. return rc;
  151527. }
  151528. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  151529. sqlite3_free(pTS->aaOutput[iOut]);
  151530. pTS->aaOutput[iOut] = 0;
  151531. aMerge = aNew;
  151532. nMerge = nNew;
  151533. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  151534. pTS->aaOutput[iOut] = aMerge;
  151535. pTS->anOutput[iOut] = nMerge;
  151536. }
  151537. }
  151538. }
  151539. }
  151540. return SQLITE_OK;
  151541. }
  151542. /*
  151543. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  151544. */
  151545. static int fts3SegReaderCursorAppend(
  151546. Fts3MultiSegReader *pCsr,
  151547. Fts3SegReader *pNew
  151548. ){
  151549. if( (pCsr->nSegment%16)==0 ){
  151550. Fts3SegReader **apNew;
  151551. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  151552. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  151553. if( !apNew ){
  151554. sqlite3Fts3SegReaderFree(pNew);
  151555. return SQLITE_NOMEM;
  151556. }
  151557. pCsr->apSegment = apNew;
  151558. }
  151559. pCsr->apSegment[pCsr->nSegment++] = pNew;
  151560. return SQLITE_OK;
  151561. }
  151562. /*
  151563. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  151564. ** 8th argument.
  151565. **
  151566. ** This function returns SQLITE_OK if successful, or an SQLite error code
  151567. ** otherwise.
  151568. */
  151569. static int fts3SegReaderCursor(
  151570. Fts3Table *p, /* FTS3 table handle */
  151571. int iLangid, /* Language id */
  151572. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  151573. int iLevel, /* Level of segments to scan */
  151574. const char *zTerm, /* Term to query for */
  151575. int nTerm, /* Size of zTerm in bytes */
  151576. int isPrefix, /* True for a prefix search */
  151577. int isScan, /* True to scan from zTerm to EOF */
  151578. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  151579. ){
  151580. int rc = SQLITE_OK; /* Error code */
  151581. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  151582. int rc2; /* Result of sqlite3_reset() */
  151583. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  151584. ** for the pending-terms. If this is a scan, then this call must be being
  151585. ** made by an fts4aux module, not an FTS table. In this case calling
  151586. ** Fts3SegReaderPending might segfault, as the data structures used by
  151587. ** fts4aux are not completely populated. So it's easiest to filter these
  151588. ** calls out here. */
  151589. if( iLevel<0 && p->aIndex ){
  151590. Fts3SegReader *pSeg = 0;
  151591. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  151592. if( rc==SQLITE_OK && pSeg ){
  151593. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  151594. }
  151595. }
  151596. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  151597. if( rc==SQLITE_OK ){
  151598. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  151599. }
  151600. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  151601. Fts3SegReader *pSeg = 0;
  151602. /* Read the values returned by the SELECT into local variables. */
  151603. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  151604. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  151605. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  151606. int nRoot = sqlite3_column_bytes(pStmt, 4);
  151607. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  151608. /* If zTerm is not NULL, and this segment is not stored entirely on its
  151609. ** root node, the range of leaves scanned can be reduced. Do this. */
  151610. if( iStartBlock && zTerm ){
  151611. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  151612. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  151613. if( rc!=SQLITE_OK ) goto finished;
  151614. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  151615. }
  151616. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  151617. (isPrefix==0 && isScan==0),
  151618. iStartBlock, iLeavesEndBlock,
  151619. iEndBlock, zRoot, nRoot, &pSeg
  151620. );
  151621. if( rc!=SQLITE_OK ) goto finished;
  151622. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  151623. }
  151624. }
  151625. finished:
  151626. rc2 = sqlite3_reset(pStmt);
  151627. if( rc==SQLITE_DONE ) rc = rc2;
  151628. return rc;
  151629. }
  151630. /*
  151631. ** Set up a cursor object for iterating through a full-text index or a
  151632. ** single level therein.
  151633. */
  151634. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  151635. Fts3Table *p, /* FTS3 table handle */
  151636. int iLangid, /* Language-id to search */
  151637. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  151638. int iLevel, /* Level of segments to scan */
  151639. const char *zTerm, /* Term to query for */
  151640. int nTerm, /* Size of zTerm in bytes */
  151641. int isPrefix, /* True for a prefix search */
  151642. int isScan, /* True to scan from zTerm to EOF */
  151643. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  151644. ){
  151645. assert( iIndex>=0 && iIndex<p->nIndex );
  151646. assert( iLevel==FTS3_SEGCURSOR_ALL
  151647. || iLevel==FTS3_SEGCURSOR_PENDING
  151648. || iLevel>=0
  151649. );
  151650. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  151651. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  151652. assert( isPrefix==0 || isScan==0 );
  151653. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  151654. return fts3SegReaderCursor(
  151655. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  151656. );
  151657. }
  151658. /*
  151659. ** In addition to its current configuration, have the Fts3MultiSegReader
  151660. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  151661. **
  151662. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  151663. */
  151664. static int fts3SegReaderCursorAddZero(
  151665. Fts3Table *p, /* FTS virtual table handle */
  151666. int iLangid,
  151667. const char *zTerm, /* Term to scan doclist of */
  151668. int nTerm, /* Number of bytes in zTerm */
  151669. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  151670. ){
  151671. return fts3SegReaderCursor(p,
  151672. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  151673. );
  151674. }
  151675. /*
  151676. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  151677. ** if isPrefix is true, to scan the doclist for all terms for which
  151678. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  151679. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  151680. ** an SQLite error code.
  151681. **
  151682. ** It is the responsibility of the caller to free this object by eventually
  151683. ** passing it to fts3SegReaderCursorFree()
  151684. **
  151685. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  151686. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  151687. */
  151688. static int fts3TermSegReaderCursor(
  151689. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  151690. const char *zTerm, /* Term to query for */
  151691. int nTerm, /* Size of zTerm in bytes */
  151692. int isPrefix, /* True for a prefix search */
  151693. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  151694. ){
  151695. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  151696. int rc = SQLITE_NOMEM; /* Return code */
  151697. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  151698. if( pSegcsr ){
  151699. int i;
  151700. int bFound = 0; /* True once an index has been found */
  151701. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  151702. if( isPrefix ){
  151703. for(i=1; bFound==0 && i<p->nIndex; i++){
  151704. if( p->aIndex[i].nPrefix==nTerm ){
  151705. bFound = 1;
  151706. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  151707. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  151708. );
  151709. pSegcsr->bLookup = 1;
  151710. }
  151711. }
  151712. for(i=1; bFound==0 && i<p->nIndex; i++){
  151713. if( p->aIndex[i].nPrefix==nTerm+1 ){
  151714. bFound = 1;
  151715. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  151716. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  151717. );
  151718. if( rc==SQLITE_OK ){
  151719. rc = fts3SegReaderCursorAddZero(
  151720. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  151721. );
  151722. }
  151723. }
  151724. }
  151725. }
  151726. if( bFound==0 ){
  151727. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  151728. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  151729. );
  151730. pSegcsr->bLookup = !isPrefix;
  151731. }
  151732. }
  151733. *ppSegcsr = pSegcsr;
  151734. return rc;
  151735. }
  151736. /*
  151737. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  151738. */
  151739. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  151740. sqlite3Fts3SegReaderFinish(pSegcsr);
  151741. sqlite3_free(pSegcsr);
  151742. }
  151743. /*
  151744. ** This function retrieves the doclist for the specified term (or term
  151745. ** prefix) from the database.
  151746. */
  151747. static int fts3TermSelect(
  151748. Fts3Table *p, /* Virtual table handle */
  151749. Fts3PhraseToken *pTok, /* Token to query for */
  151750. int iColumn, /* Column to query (or -ve for all columns) */
  151751. int *pnOut, /* OUT: Size of buffer at *ppOut */
  151752. char **ppOut /* OUT: Malloced result buffer */
  151753. ){
  151754. int rc; /* Return code */
  151755. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  151756. TermSelect tsc; /* Object for pair-wise doclist merging */
  151757. Fts3SegFilter filter; /* Segment term filter configuration */
  151758. pSegcsr = pTok->pSegcsr;
  151759. memset(&tsc, 0, sizeof(TermSelect));
  151760. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  151761. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  151762. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  151763. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  151764. filter.iCol = iColumn;
  151765. filter.zTerm = pTok->z;
  151766. filter.nTerm = pTok->n;
  151767. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  151768. while( SQLITE_OK==rc
  151769. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  151770. ){
  151771. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  151772. }
  151773. if( rc==SQLITE_OK ){
  151774. rc = fts3TermSelectFinishMerge(p, &tsc);
  151775. }
  151776. if( rc==SQLITE_OK ){
  151777. *ppOut = tsc.aaOutput[0];
  151778. *pnOut = tsc.anOutput[0];
  151779. }else{
  151780. int i;
  151781. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  151782. sqlite3_free(tsc.aaOutput[i]);
  151783. }
  151784. }
  151785. fts3SegReaderCursorFree(pSegcsr);
  151786. pTok->pSegcsr = 0;
  151787. return rc;
  151788. }
  151789. /*
  151790. ** This function counts the total number of docids in the doclist stored
  151791. ** in buffer aList[], size nList bytes.
  151792. **
  151793. ** If the isPoslist argument is true, then it is assumed that the doclist
  151794. ** contains a position-list following each docid. Otherwise, it is assumed
  151795. ** that the doclist is simply a list of docids stored as delta encoded
  151796. ** varints.
  151797. */
  151798. static int fts3DoclistCountDocids(char *aList, int nList){
  151799. int nDoc = 0; /* Return value */
  151800. if( aList ){
  151801. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  151802. char *p = aList; /* Cursor */
  151803. while( p<aEnd ){
  151804. nDoc++;
  151805. while( (*p++)&0x80 ); /* Skip docid varint */
  151806. fts3PoslistCopy(0, &p); /* Skip over position list */
  151807. }
  151808. }
  151809. return nDoc;
  151810. }
  151811. /*
  151812. ** Advance the cursor to the next row in the %_content table that
  151813. ** matches the search criteria. For a MATCH search, this will be
  151814. ** the next row that matches. For a full-table scan, this will be
  151815. ** simply the next row in the %_content table. For a docid lookup,
  151816. ** this routine simply sets the EOF flag.
  151817. **
  151818. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  151819. ** even if we reach end-of-file. The fts3EofMethod() will be called
  151820. ** subsequently to determine whether or not an EOF was hit.
  151821. */
  151822. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  151823. int rc;
  151824. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  151825. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  151826. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  151827. pCsr->isEof = 1;
  151828. rc = sqlite3_reset(pCsr->pStmt);
  151829. }else{
  151830. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  151831. rc = SQLITE_OK;
  151832. }
  151833. }else{
  151834. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  151835. }
  151836. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  151837. return rc;
  151838. }
  151839. /*
  151840. ** The following are copied from sqliteInt.h.
  151841. **
  151842. ** Constants for the largest and smallest possible 64-bit signed integers.
  151843. ** These macros are designed to work correctly on both 32-bit and 64-bit
  151844. ** compilers.
  151845. */
  151846. #ifndef SQLITE_AMALGAMATION
  151847. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  151848. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  151849. #endif
  151850. /*
  151851. ** If the numeric type of argument pVal is "integer", then return it
  151852. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  151853. ** the second parameter, iDefault.
  151854. */
  151855. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  151856. if( pVal ){
  151857. int eType = sqlite3_value_numeric_type(pVal);
  151858. if( eType==SQLITE_INTEGER ){
  151859. return sqlite3_value_int64(pVal);
  151860. }
  151861. }
  151862. return iDefault;
  151863. }
  151864. /*
  151865. ** This is the xFilter interface for the virtual table. See
  151866. ** the virtual table xFilter method documentation for additional
  151867. ** information.
  151868. **
  151869. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  151870. ** the %_content table.
  151871. **
  151872. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  151873. ** in the %_content table.
  151874. **
  151875. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  151876. ** column on the left-hand side of the MATCH operator is column
  151877. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  151878. ** side of the MATCH operator.
  151879. */
  151880. static int fts3FilterMethod(
  151881. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  151882. int idxNum, /* Strategy index */
  151883. const char *idxStr, /* Unused */
  151884. int nVal, /* Number of elements in apVal */
  151885. sqlite3_value **apVal /* Arguments for the indexing scheme */
  151886. ){
  151887. int rc = SQLITE_OK;
  151888. char *zSql; /* SQL statement used to access %_content */
  151889. int eSearch;
  151890. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  151891. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  151892. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  151893. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  151894. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  151895. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  151896. int iIdx;
  151897. UNUSED_PARAMETER(idxStr);
  151898. UNUSED_PARAMETER(nVal);
  151899. eSearch = (idxNum & 0x0000FFFF);
  151900. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  151901. assert( p->pSegments==0 );
  151902. /* Collect arguments into local variables */
  151903. iIdx = 0;
  151904. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  151905. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  151906. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  151907. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  151908. assert( iIdx==nVal );
  151909. /* In case the cursor has been used before, clear it now. */
  151910. fts3ClearCursor(pCsr);
  151911. /* Set the lower and upper bounds on docids to return */
  151912. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  151913. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  151914. if( idxStr ){
  151915. pCsr->bDesc = (idxStr[0]=='D');
  151916. }else{
  151917. pCsr->bDesc = p->bDescIdx;
  151918. }
  151919. pCsr->eSearch = (i16)eSearch;
  151920. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  151921. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  151922. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  151923. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  151924. return SQLITE_NOMEM;
  151925. }
  151926. pCsr->iLangid = 0;
  151927. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  151928. assert( p->base.zErrMsg==0 );
  151929. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  151930. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  151931. &p->base.zErrMsg
  151932. );
  151933. if( rc!=SQLITE_OK ){
  151934. return rc;
  151935. }
  151936. rc = fts3EvalStart(pCsr);
  151937. sqlite3Fts3SegmentsClose(p);
  151938. if( rc!=SQLITE_OK ) return rc;
  151939. pCsr->pNextId = pCsr->aDoclist;
  151940. pCsr->iPrevId = 0;
  151941. }
  151942. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  151943. ** statement loops through all rows of the %_content table. For a
  151944. ** full-text query or docid lookup, the statement retrieves a single
  151945. ** row by docid.
  151946. */
  151947. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  151948. if( pDocidGe || pDocidLe ){
  151949. zSql = sqlite3_mprintf(
  151950. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  151951. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  151952. (pCsr->bDesc ? "DESC" : "ASC")
  151953. );
  151954. }else{
  151955. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  151956. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  151957. );
  151958. }
  151959. if( zSql ){
  151960. rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  151961. sqlite3_free(zSql);
  151962. }else{
  151963. rc = SQLITE_NOMEM;
  151964. }
  151965. }else if( eSearch==FTS3_DOCID_SEARCH ){
  151966. rc = fts3CursorSeekStmt(pCsr);
  151967. if( rc==SQLITE_OK ){
  151968. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  151969. }
  151970. }
  151971. if( rc!=SQLITE_OK ) return rc;
  151972. return fts3NextMethod(pCursor);
  151973. }
  151974. /*
  151975. ** This is the xEof method of the virtual table. SQLite calls this
  151976. ** routine to find out if it has reached the end of a result set.
  151977. */
  151978. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  151979. Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
  151980. if( pCsr->isEof ){
  151981. fts3ClearCursor(pCsr);
  151982. pCsr->isEof = 1;
  151983. }
  151984. return pCsr->isEof;
  151985. }
  151986. /*
  151987. ** This is the xRowid method. The SQLite core calls this routine to
  151988. ** retrieve the rowid for the current row of the result set. fts3
  151989. ** exposes %_content.docid as the rowid for the virtual table. The
  151990. ** rowid should be written to *pRowid.
  151991. */
  151992. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  151993. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  151994. *pRowid = pCsr->iPrevId;
  151995. return SQLITE_OK;
  151996. }
  151997. /*
  151998. ** This is the xColumn method, called by SQLite to request a value from
  151999. ** the row that the supplied cursor currently points to.
  152000. **
  152001. ** If:
  152002. **
  152003. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  152004. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  152005. ** (iCol == p->nColumn+1) -> Docid column
  152006. ** (iCol == p->nColumn+2) -> Langid column
  152007. */
  152008. static int fts3ColumnMethod(
  152009. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  152010. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  152011. int iCol /* Index of column to read value from */
  152012. ){
  152013. int rc = SQLITE_OK; /* Return Code */
  152014. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  152015. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  152016. /* The column value supplied by SQLite must be in range. */
  152017. assert( iCol>=0 && iCol<=p->nColumn+2 );
  152018. switch( iCol-p->nColumn ){
  152019. case 0:
  152020. /* The special 'table-name' column */
  152021. sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
  152022. break;
  152023. case 1:
  152024. /* The docid column */
  152025. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  152026. break;
  152027. case 2:
  152028. if( pCsr->pExpr ){
  152029. sqlite3_result_int64(pCtx, pCsr->iLangid);
  152030. break;
  152031. }else if( p->zLanguageid==0 ){
  152032. sqlite3_result_int(pCtx, 0);
  152033. break;
  152034. }else{
  152035. iCol = p->nColumn;
  152036. /* fall-through */
  152037. }
  152038. default:
  152039. /* A user column. Or, if this is a full-table scan, possibly the
  152040. ** language-id column. Seek the cursor. */
  152041. rc = fts3CursorSeek(0, pCsr);
  152042. if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
  152043. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  152044. }
  152045. break;
  152046. }
  152047. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  152048. return rc;
  152049. }
  152050. /*
  152051. ** This function is the implementation of the xUpdate callback used by
  152052. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  152053. ** inserted, updated or deleted.
  152054. */
  152055. static int fts3UpdateMethod(
  152056. sqlite3_vtab *pVtab, /* Virtual table handle */
  152057. int nArg, /* Size of argument array */
  152058. sqlite3_value **apVal, /* Array of arguments */
  152059. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  152060. ){
  152061. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  152062. }
  152063. /*
  152064. ** Implementation of xSync() method. Flush the contents of the pending-terms
  152065. ** hash-table to the database.
  152066. */
  152067. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  152068. /* Following an incremental-merge operation, assuming that the input
  152069. ** segments are not completely consumed (the usual case), they are updated
  152070. ** in place to remove the entries that have already been merged. This
  152071. ** involves updating the leaf block that contains the smallest unmerged
  152072. ** entry and each block (if any) between the leaf and the root node. So
  152073. ** if the height of the input segment b-trees is N, and input segments
  152074. ** are merged eight at a time, updating the input segments at the end
  152075. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  152076. ** small - often between 0 and 2. So the overhead of the incremental
  152077. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  152078. ** dwarfing the actual productive work accomplished, the incremental merge
  152079. ** is only attempted if it will write at least 64 leaf blocks. Hence
  152080. ** nMinMerge.
  152081. **
  152082. ** Of course, updating the input segments also involves deleting a bunch
  152083. ** of blocks from the segments table. But this is not considered overhead
  152084. ** as it would also be required by a crisis-merge that used the same input
  152085. ** segments.
  152086. */
  152087. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  152088. Fts3Table *p = (Fts3Table*)pVtab;
  152089. int rc;
  152090. i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
  152091. rc = sqlite3Fts3PendingTermsFlush(p);
  152092. if( rc==SQLITE_OK
  152093. && p->nLeafAdd>(nMinMerge/16)
  152094. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  152095. ){
  152096. int mxLevel = 0; /* Maximum relative level value in db */
  152097. int A; /* Incr-merge parameter A */
  152098. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  152099. assert( rc==SQLITE_OK || mxLevel==0 );
  152100. A = p->nLeafAdd * mxLevel;
  152101. A += (A/2);
  152102. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  152103. }
  152104. sqlite3Fts3SegmentsClose(p);
  152105. sqlite3_set_last_insert_rowid(p->db, iLastRowid);
  152106. return rc;
  152107. }
  152108. /*
  152109. ** If it is currently unknown whether or not the FTS table has an %_stat
  152110. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  152111. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  152112. ** if an error occurs.
  152113. */
  152114. static int fts3SetHasStat(Fts3Table *p){
  152115. int rc = SQLITE_OK;
  152116. if( p->bHasStat==2 ){
  152117. char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
  152118. if( zTbl ){
  152119. int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
  152120. sqlite3_free(zTbl);
  152121. p->bHasStat = (res==SQLITE_OK);
  152122. }else{
  152123. rc = SQLITE_NOMEM;
  152124. }
  152125. }
  152126. return rc;
  152127. }
  152128. /*
  152129. ** Implementation of xBegin() method.
  152130. */
  152131. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  152132. Fts3Table *p = (Fts3Table*)pVtab;
  152133. UNUSED_PARAMETER(pVtab);
  152134. assert( p->pSegments==0 );
  152135. assert( p->nPendingData==0 );
  152136. assert( p->inTransaction!=1 );
  152137. TESTONLY( p->inTransaction = 1 );
  152138. TESTONLY( p->mxSavepoint = -1; );
  152139. p->nLeafAdd = 0;
  152140. return fts3SetHasStat(p);
  152141. }
  152142. /*
  152143. ** Implementation of xCommit() method. This is a no-op. The contents of
  152144. ** the pending-terms hash-table have already been flushed into the database
  152145. ** by fts3SyncMethod().
  152146. */
  152147. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  152148. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  152149. UNUSED_PARAMETER(pVtab);
  152150. assert( p->nPendingData==0 );
  152151. assert( p->inTransaction!=0 );
  152152. assert( p->pSegments==0 );
  152153. TESTONLY( p->inTransaction = 0 );
  152154. TESTONLY( p->mxSavepoint = -1; );
  152155. return SQLITE_OK;
  152156. }
  152157. /*
  152158. ** Implementation of xRollback(). Discard the contents of the pending-terms
  152159. ** hash-table. Any changes made to the database are reverted by SQLite.
  152160. */
  152161. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  152162. Fts3Table *p = (Fts3Table*)pVtab;
  152163. sqlite3Fts3PendingTermsClear(p);
  152164. assert( p->inTransaction!=0 );
  152165. TESTONLY( p->inTransaction = 0 );
  152166. TESTONLY( p->mxSavepoint = -1; );
  152167. return SQLITE_OK;
  152168. }
  152169. /*
  152170. ** When called, *ppPoslist must point to the byte immediately following the
  152171. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  152172. ** moves *ppPoslist so that it instead points to the first byte of the
  152173. ** same position list.
  152174. */
  152175. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  152176. char *p = &(*ppPoslist)[-2];
  152177. char c = 0;
  152178. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  152179. while( p>pStart && (c=*p--)==0 );
  152180. /* Search backwards for a varint with value zero (the end of the previous
  152181. ** poslist). This is an 0x00 byte preceded by some byte that does not
  152182. ** have the 0x80 bit set. */
  152183. while( p>pStart && (*p & 0x80) | c ){
  152184. c = *p--;
  152185. }
  152186. assert( p==pStart || c==0 );
  152187. /* At this point p points to that preceding byte without the 0x80 bit
  152188. ** set. So to find the start of the poslist, skip forward 2 bytes then
  152189. ** over a varint.
  152190. **
  152191. ** Normally. The other case is that p==pStart and the poslist to return
  152192. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  152193. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  152194. ** is required for cases where the first byte of a doclist and the
  152195. ** doclist is empty. For example, if the first docid is 10, a doclist
  152196. ** that begins with:
  152197. **
  152198. ** 0x0A 0x00 <next docid delta varint>
  152199. */
  152200. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  152201. while( *p++&0x80 );
  152202. *ppPoslist = p;
  152203. }
  152204. /*
  152205. ** Helper function used by the implementation of the overloaded snippet(),
  152206. ** offsets() and optimize() SQL functions.
  152207. **
  152208. ** If the value passed as the third argument is a blob of size
  152209. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  152210. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  152211. ** message is written to context pContext and SQLITE_ERROR returned. The
  152212. ** string passed via zFunc is used as part of the error message.
  152213. */
  152214. static int fts3FunctionArg(
  152215. sqlite3_context *pContext, /* SQL function call context */
  152216. const char *zFunc, /* Function name */
  152217. sqlite3_value *pVal, /* argv[0] passed to function */
  152218. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  152219. ){
  152220. int rc;
  152221. *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
  152222. if( (*ppCsr)!=0 ){
  152223. rc = SQLITE_OK;
  152224. }else{
  152225. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  152226. sqlite3_result_error(pContext, zErr, -1);
  152227. sqlite3_free(zErr);
  152228. rc = SQLITE_ERROR;
  152229. }
  152230. return rc;
  152231. }
  152232. /*
  152233. ** Implementation of the snippet() function for FTS3
  152234. */
  152235. static void fts3SnippetFunc(
  152236. sqlite3_context *pContext, /* SQLite function call context */
  152237. int nVal, /* Size of apVal[] array */
  152238. sqlite3_value **apVal /* Array of arguments */
  152239. ){
  152240. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  152241. const char *zStart = "<b>";
  152242. const char *zEnd = "</b>";
  152243. const char *zEllipsis = "<b>...</b>";
  152244. int iCol = -1;
  152245. int nToken = 15; /* Default number of tokens in snippet */
  152246. /* There must be at least one argument passed to this function (otherwise
  152247. ** the non-overloaded version would have been called instead of this one).
  152248. */
  152249. assert( nVal>=1 );
  152250. if( nVal>6 ){
  152251. sqlite3_result_error(pContext,
  152252. "wrong number of arguments to function snippet()", -1);
  152253. return;
  152254. }
  152255. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  152256. switch( nVal ){
  152257. case 6: nToken = sqlite3_value_int(apVal[5]);
  152258. case 5: iCol = sqlite3_value_int(apVal[4]);
  152259. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  152260. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  152261. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  152262. }
  152263. if( !zEllipsis || !zEnd || !zStart ){
  152264. sqlite3_result_error_nomem(pContext);
  152265. }else if( nToken==0 ){
  152266. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  152267. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  152268. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  152269. }
  152270. }
  152271. /*
  152272. ** Implementation of the offsets() function for FTS3
  152273. */
  152274. static void fts3OffsetsFunc(
  152275. sqlite3_context *pContext, /* SQLite function call context */
  152276. int nVal, /* Size of argument array */
  152277. sqlite3_value **apVal /* Array of arguments */
  152278. ){
  152279. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  152280. UNUSED_PARAMETER(nVal);
  152281. assert( nVal==1 );
  152282. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  152283. assert( pCsr );
  152284. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  152285. sqlite3Fts3Offsets(pContext, pCsr);
  152286. }
  152287. }
  152288. /*
  152289. ** Implementation of the special optimize() function for FTS3. This
  152290. ** function merges all segments in the database to a single segment.
  152291. ** Example usage is:
  152292. **
  152293. ** SELECT optimize(t) FROM t LIMIT 1;
  152294. **
  152295. ** where 't' is the name of an FTS3 table.
  152296. */
  152297. static void fts3OptimizeFunc(
  152298. sqlite3_context *pContext, /* SQLite function call context */
  152299. int nVal, /* Size of argument array */
  152300. sqlite3_value **apVal /* Array of arguments */
  152301. ){
  152302. int rc; /* Return code */
  152303. Fts3Table *p; /* Virtual table handle */
  152304. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  152305. UNUSED_PARAMETER(nVal);
  152306. assert( nVal==1 );
  152307. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  152308. p = (Fts3Table *)pCursor->base.pVtab;
  152309. assert( p );
  152310. rc = sqlite3Fts3Optimize(p);
  152311. switch( rc ){
  152312. case SQLITE_OK:
  152313. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  152314. break;
  152315. case SQLITE_DONE:
  152316. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  152317. break;
  152318. default:
  152319. sqlite3_result_error_code(pContext, rc);
  152320. break;
  152321. }
  152322. }
  152323. /*
  152324. ** Implementation of the matchinfo() function for FTS3
  152325. */
  152326. static void fts3MatchinfoFunc(
  152327. sqlite3_context *pContext, /* SQLite function call context */
  152328. int nVal, /* Size of argument array */
  152329. sqlite3_value **apVal /* Array of arguments */
  152330. ){
  152331. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  152332. assert( nVal==1 || nVal==2 );
  152333. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  152334. const char *zArg = 0;
  152335. if( nVal>1 ){
  152336. zArg = (const char *)sqlite3_value_text(apVal[1]);
  152337. }
  152338. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  152339. }
  152340. }
  152341. /*
  152342. ** This routine implements the xFindFunction method for the FTS3
  152343. ** virtual table.
  152344. */
  152345. static int fts3FindFunctionMethod(
  152346. sqlite3_vtab *pVtab, /* Virtual table handle */
  152347. int nArg, /* Number of SQL function arguments */
  152348. const char *zName, /* Name of SQL function */
  152349. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  152350. void **ppArg /* Unused */
  152351. ){
  152352. struct Overloaded {
  152353. const char *zName;
  152354. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  152355. } aOverload[] = {
  152356. { "snippet", fts3SnippetFunc },
  152357. { "offsets", fts3OffsetsFunc },
  152358. { "optimize", fts3OptimizeFunc },
  152359. { "matchinfo", fts3MatchinfoFunc },
  152360. };
  152361. int i; /* Iterator variable */
  152362. UNUSED_PARAMETER(pVtab);
  152363. UNUSED_PARAMETER(nArg);
  152364. UNUSED_PARAMETER(ppArg);
  152365. for(i=0; i<SizeofArray(aOverload); i++){
  152366. if( strcmp(zName, aOverload[i].zName)==0 ){
  152367. *pxFunc = aOverload[i].xFunc;
  152368. return 1;
  152369. }
  152370. }
  152371. /* No function of the specified name was found. Return 0. */
  152372. return 0;
  152373. }
  152374. /*
  152375. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  152376. */
  152377. static int fts3RenameMethod(
  152378. sqlite3_vtab *pVtab, /* Virtual table handle */
  152379. const char *zName /* New name of table */
  152380. ){
  152381. Fts3Table *p = (Fts3Table *)pVtab;
  152382. sqlite3 *db = p->db; /* Database connection */
  152383. int rc; /* Return Code */
  152384. /* At this point it must be known if the %_stat table exists or not.
  152385. ** So bHasStat may not be 2. */
  152386. rc = fts3SetHasStat(p);
  152387. /* As it happens, the pending terms table is always empty here. This is
  152388. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  152389. ** always opens a savepoint transaction. And the xSavepoint() method
  152390. ** flushes the pending terms table. But leave the (no-op) call to
  152391. ** PendingTermsFlush() in in case that changes.
  152392. */
  152393. assert( p->nPendingData==0 );
  152394. if( rc==SQLITE_OK ){
  152395. rc = sqlite3Fts3PendingTermsFlush(p);
  152396. }
  152397. if( p->zContentTbl==0 ){
  152398. fts3DbExec(&rc, db,
  152399. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  152400. p->zDb, p->zName, zName
  152401. );
  152402. }
  152403. if( p->bHasDocsize ){
  152404. fts3DbExec(&rc, db,
  152405. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  152406. p->zDb, p->zName, zName
  152407. );
  152408. }
  152409. if( p->bHasStat ){
  152410. fts3DbExec(&rc, db,
  152411. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  152412. p->zDb, p->zName, zName
  152413. );
  152414. }
  152415. fts3DbExec(&rc, db,
  152416. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  152417. p->zDb, p->zName, zName
  152418. );
  152419. fts3DbExec(&rc, db,
  152420. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  152421. p->zDb, p->zName, zName
  152422. );
  152423. return rc;
  152424. }
  152425. /*
  152426. ** The xSavepoint() method.
  152427. **
  152428. ** Flush the contents of the pending-terms table to disk.
  152429. */
  152430. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  152431. int rc = SQLITE_OK;
  152432. UNUSED_PARAMETER(iSavepoint);
  152433. assert( ((Fts3Table *)pVtab)->inTransaction );
  152434. assert( ((Fts3Table *)pVtab)->mxSavepoint <= iSavepoint );
  152435. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  152436. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  152437. rc = fts3SyncMethod(pVtab);
  152438. }
  152439. return rc;
  152440. }
  152441. /*
  152442. ** The xRelease() method.
  152443. **
  152444. ** This is a no-op.
  152445. */
  152446. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  152447. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  152448. UNUSED_PARAMETER(iSavepoint);
  152449. UNUSED_PARAMETER(pVtab);
  152450. assert( p->inTransaction );
  152451. assert( p->mxSavepoint >= iSavepoint );
  152452. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  152453. return SQLITE_OK;
  152454. }
  152455. /*
  152456. ** The xRollbackTo() method.
  152457. **
  152458. ** Discard the contents of the pending terms table.
  152459. */
  152460. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  152461. Fts3Table *p = (Fts3Table*)pVtab;
  152462. UNUSED_PARAMETER(iSavepoint);
  152463. assert( p->inTransaction );
  152464. assert( p->mxSavepoint >= iSavepoint );
  152465. TESTONLY( p->mxSavepoint = iSavepoint );
  152466. sqlite3Fts3PendingTermsClear(p);
  152467. return SQLITE_OK;
  152468. }
  152469. /*
  152470. ** Return true if zName is the extension on one of the shadow tables used
  152471. ** by this module.
  152472. */
  152473. static int fts3ShadowName(const char *zName){
  152474. static const char *azName[] = {
  152475. "content", "docsize", "segdir", "segments", "stat",
  152476. };
  152477. unsigned int i;
  152478. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  152479. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  152480. }
  152481. return 0;
  152482. }
  152483. static const sqlite3_module fts3Module = {
  152484. /* iVersion */ 3,
  152485. /* xCreate */ fts3CreateMethod,
  152486. /* xConnect */ fts3ConnectMethod,
  152487. /* xBestIndex */ fts3BestIndexMethod,
  152488. /* xDisconnect */ fts3DisconnectMethod,
  152489. /* xDestroy */ fts3DestroyMethod,
  152490. /* xOpen */ fts3OpenMethod,
  152491. /* xClose */ fts3CloseMethod,
  152492. /* xFilter */ fts3FilterMethod,
  152493. /* xNext */ fts3NextMethod,
  152494. /* xEof */ fts3EofMethod,
  152495. /* xColumn */ fts3ColumnMethod,
  152496. /* xRowid */ fts3RowidMethod,
  152497. /* xUpdate */ fts3UpdateMethod,
  152498. /* xBegin */ fts3BeginMethod,
  152499. /* xSync */ fts3SyncMethod,
  152500. /* xCommit */ fts3CommitMethod,
  152501. /* xRollback */ fts3RollbackMethod,
  152502. /* xFindFunction */ fts3FindFunctionMethod,
  152503. /* xRename */ fts3RenameMethod,
  152504. /* xSavepoint */ fts3SavepointMethod,
  152505. /* xRelease */ fts3ReleaseMethod,
  152506. /* xRollbackTo */ fts3RollbackToMethod,
  152507. /* xShadowName */ fts3ShadowName,
  152508. };
  152509. /*
  152510. ** This function is registered as the module destructor (called when an
  152511. ** FTS3 enabled database connection is closed). It frees the memory
  152512. ** allocated for the tokenizer hash table.
  152513. */
  152514. static void hashDestroy(void *p){
  152515. Fts3Hash *pHash = (Fts3Hash *)p;
  152516. sqlite3Fts3HashClear(pHash);
  152517. sqlite3_free(pHash);
  152518. }
  152519. /*
  152520. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  152521. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  152522. ** respectively. The following three forward declarations are for functions
  152523. ** declared in these files used to retrieve the respective implementations.
  152524. **
  152525. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  152526. ** to by the argument to point to the "simple" tokenizer implementation.
  152527. ** And so on.
  152528. */
  152529. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  152530. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  152531. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  152532. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  152533. #endif
  152534. #ifdef SQLITE_ENABLE_ICU
  152535. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  152536. #endif
  152537. /*
  152538. ** Initialize the fts3 extension. If this extension is built as part
  152539. ** of the sqlite library, then this function is called directly by
  152540. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  152541. ** function is called by the sqlite3_extension_init() entry point.
  152542. */
  152543. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  152544. int rc = SQLITE_OK;
  152545. Fts3Hash *pHash = 0;
  152546. const sqlite3_tokenizer_module *pSimple = 0;
  152547. const sqlite3_tokenizer_module *pPorter = 0;
  152548. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  152549. const sqlite3_tokenizer_module *pUnicode = 0;
  152550. #endif
  152551. #ifdef SQLITE_ENABLE_ICU
  152552. const sqlite3_tokenizer_module *pIcu = 0;
  152553. sqlite3Fts3IcuTokenizerModule(&pIcu);
  152554. #endif
  152555. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  152556. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  152557. #endif
  152558. #ifdef SQLITE_TEST
  152559. rc = sqlite3Fts3InitTerm(db);
  152560. if( rc!=SQLITE_OK ) return rc;
  152561. #endif
  152562. rc = sqlite3Fts3InitAux(db);
  152563. if( rc!=SQLITE_OK ) return rc;
  152564. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  152565. sqlite3Fts3PorterTokenizerModule(&pPorter);
  152566. /* Allocate and initialize the hash-table used to store tokenizers. */
  152567. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  152568. if( !pHash ){
  152569. rc = SQLITE_NOMEM;
  152570. }else{
  152571. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  152572. }
  152573. /* Load the built-in tokenizers into the hash table */
  152574. if( rc==SQLITE_OK ){
  152575. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  152576. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  152577. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  152578. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  152579. #endif
  152580. #ifdef SQLITE_ENABLE_ICU
  152581. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  152582. #endif
  152583. ){
  152584. rc = SQLITE_NOMEM;
  152585. }
  152586. }
  152587. #ifdef SQLITE_TEST
  152588. if( rc==SQLITE_OK ){
  152589. rc = sqlite3Fts3ExprInitTestInterface(db, pHash);
  152590. }
  152591. #endif
  152592. /* Create the virtual table wrapper around the hash-table and overload
  152593. ** the four scalar functions. If this is successful, register the
  152594. ** module with sqlite.
  152595. */
  152596. if( SQLITE_OK==rc
  152597. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  152598. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  152599. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  152600. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  152601. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  152602. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  152603. ){
  152604. rc = sqlite3_create_module_v2(
  152605. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  152606. );
  152607. if( rc==SQLITE_OK ){
  152608. rc = sqlite3_create_module_v2(
  152609. db, "fts4", &fts3Module, (void *)pHash, 0
  152610. );
  152611. }
  152612. if( rc==SQLITE_OK ){
  152613. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  152614. }
  152615. return rc;
  152616. }
  152617. /* An error has occurred. Delete the hash table and return the error code. */
  152618. assert( rc!=SQLITE_OK );
  152619. if( pHash ){
  152620. sqlite3Fts3HashClear(pHash);
  152621. sqlite3_free(pHash);
  152622. }
  152623. return rc;
  152624. }
  152625. /*
  152626. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  152627. ** by pExpr.
  152628. **
  152629. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  152630. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  152631. ** Fts3SegReader objects internally to provide an interface to seek or scan
  152632. ** within the union of all segments of a b-tree. Hence the name.
  152633. **
  152634. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  152635. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  152636. ** there exists prefix b-tree of the right length) then it may be traversed
  152637. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  152638. ** doclist and then traversed.
  152639. */
  152640. static void fts3EvalAllocateReaders(
  152641. Fts3Cursor *pCsr, /* FTS cursor handle */
  152642. Fts3Expr *pExpr, /* Allocate readers for this expression */
  152643. int *pnToken, /* OUT: Total number of tokens in phrase. */
  152644. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  152645. int *pRc /* IN/OUT: Error code */
  152646. ){
  152647. if( pExpr && SQLITE_OK==*pRc ){
  152648. if( pExpr->eType==FTSQUERY_PHRASE ){
  152649. int i;
  152650. int nToken = pExpr->pPhrase->nToken;
  152651. *pnToken += nToken;
  152652. for(i=0; i<nToken; i++){
  152653. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  152654. int rc = fts3TermSegReaderCursor(pCsr,
  152655. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  152656. );
  152657. if( rc!=SQLITE_OK ){
  152658. *pRc = rc;
  152659. return;
  152660. }
  152661. }
  152662. assert( pExpr->pPhrase->iDoclistToken==0 );
  152663. pExpr->pPhrase->iDoclistToken = -1;
  152664. }else{
  152665. *pnOr += (pExpr->eType==FTSQUERY_OR);
  152666. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  152667. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  152668. }
  152669. }
  152670. }
  152671. /*
  152672. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  152673. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  152674. **
  152675. ** This function assumes that pList points to a buffer allocated using
  152676. ** sqlite3_malloc(). This function takes responsibility for eventually
  152677. ** freeing the buffer.
  152678. **
  152679. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  152680. */
  152681. static int fts3EvalPhraseMergeToken(
  152682. Fts3Table *pTab, /* FTS Table pointer */
  152683. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  152684. int iToken, /* Token pList/nList corresponds to */
  152685. char *pList, /* Pointer to doclist */
  152686. int nList /* Number of bytes in pList */
  152687. ){
  152688. int rc = SQLITE_OK;
  152689. assert( iToken!=p->iDoclistToken );
  152690. if( pList==0 ){
  152691. sqlite3_free(p->doclist.aAll);
  152692. p->doclist.aAll = 0;
  152693. p->doclist.nAll = 0;
  152694. }
  152695. else if( p->iDoclistToken<0 ){
  152696. p->doclist.aAll = pList;
  152697. p->doclist.nAll = nList;
  152698. }
  152699. else if( p->doclist.aAll==0 ){
  152700. sqlite3_free(pList);
  152701. }
  152702. else {
  152703. char *pLeft;
  152704. char *pRight;
  152705. int nLeft;
  152706. int nRight;
  152707. int nDiff;
  152708. if( p->iDoclistToken<iToken ){
  152709. pLeft = p->doclist.aAll;
  152710. nLeft = p->doclist.nAll;
  152711. pRight = pList;
  152712. nRight = nList;
  152713. nDiff = iToken - p->iDoclistToken;
  152714. }else{
  152715. pRight = p->doclist.aAll;
  152716. nRight = p->doclist.nAll;
  152717. pLeft = pList;
  152718. nLeft = nList;
  152719. nDiff = p->iDoclistToken - iToken;
  152720. }
  152721. rc = fts3DoclistPhraseMerge(
  152722. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  152723. );
  152724. sqlite3_free(pLeft);
  152725. p->doclist.aAll = pRight;
  152726. p->doclist.nAll = nRight;
  152727. }
  152728. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  152729. return rc;
  152730. }
  152731. /*
  152732. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  152733. ** does not take deferred tokens into account.
  152734. **
  152735. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  152736. */
  152737. static int fts3EvalPhraseLoad(
  152738. Fts3Cursor *pCsr, /* FTS Cursor handle */
  152739. Fts3Phrase *p /* Phrase object */
  152740. ){
  152741. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152742. int iToken;
  152743. int rc = SQLITE_OK;
  152744. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  152745. Fts3PhraseToken *pToken = &p->aToken[iToken];
  152746. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  152747. if( pToken->pSegcsr ){
  152748. int nThis = 0;
  152749. char *pThis = 0;
  152750. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  152751. if( rc==SQLITE_OK ){
  152752. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  152753. }
  152754. }
  152755. assert( pToken->pSegcsr==0 );
  152756. }
  152757. return rc;
  152758. }
  152759. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  152760. /*
  152761. ** This function is called on each phrase after the position lists for
  152762. ** any deferred tokens have been loaded into memory. It updates the phrases
  152763. ** current position list to include only those positions that are really
  152764. ** instances of the phrase (after considering deferred tokens). If this
  152765. ** means that the phrase does not appear in the current row, doclist.pList
  152766. ** and doclist.nList are both zeroed.
  152767. **
  152768. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  152769. */
  152770. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  152771. int iToken; /* Used to iterate through phrase tokens */
  152772. char *aPoslist = 0; /* Position list for deferred tokens */
  152773. int nPoslist = 0; /* Number of bytes in aPoslist */
  152774. int iPrev = -1; /* Token number of previous deferred token */
  152775. assert( pPhrase->doclist.bFreeList==0 );
  152776. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  152777. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  152778. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  152779. if( pDeferred ){
  152780. char *pList;
  152781. int nList;
  152782. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  152783. if( rc!=SQLITE_OK ) return rc;
  152784. if( pList==0 ){
  152785. sqlite3_free(aPoslist);
  152786. pPhrase->doclist.pList = 0;
  152787. pPhrase->doclist.nList = 0;
  152788. return SQLITE_OK;
  152789. }else if( aPoslist==0 ){
  152790. aPoslist = pList;
  152791. nPoslist = nList;
  152792. }else{
  152793. char *aOut = pList;
  152794. char *p1 = aPoslist;
  152795. char *p2 = aOut;
  152796. assert( iPrev>=0 );
  152797. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  152798. sqlite3_free(aPoslist);
  152799. aPoslist = pList;
  152800. nPoslist = (int)(aOut - aPoslist);
  152801. if( nPoslist==0 ){
  152802. sqlite3_free(aPoslist);
  152803. pPhrase->doclist.pList = 0;
  152804. pPhrase->doclist.nList = 0;
  152805. return SQLITE_OK;
  152806. }
  152807. }
  152808. iPrev = iToken;
  152809. }
  152810. }
  152811. if( iPrev>=0 ){
  152812. int nMaxUndeferred = pPhrase->iDoclistToken;
  152813. if( nMaxUndeferred<0 ){
  152814. pPhrase->doclist.pList = aPoslist;
  152815. pPhrase->doclist.nList = nPoslist;
  152816. pPhrase->doclist.iDocid = pCsr->iPrevId;
  152817. pPhrase->doclist.bFreeList = 1;
  152818. }else{
  152819. int nDistance;
  152820. char *p1;
  152821. char *p2;
  152822. char *aOut;
  152823. if( nMaxUndeferred>iPrev ){
  152824. p1 = aPoslist;
  152825. p2 = pPhrase->doclist.pList;
  152826. nDistance = nMaxUndeferred - iPrev;
  152827. }else{
  152828. p1 = pPhrase->doclist.pList;
  152829. p2 = aPoslist;
  152830. nDistance = iPrev - nMaxUndeferred;
  152831. }
  152832. aOut = (char *)sqlite3_malloc(nPoslist+8);
  152833. if( !aOut ){
  152834. sqlite3_free(aPoslist);
  152835. return SQLITE_NOMEM;
  152836. }
  152837. pPhrase->doclist.pList = aOut;
  152838. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  152839. pPhrase->doclist.bFreeList = 1;
  152840. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  152841. }else{
  152842. sqlite3_free(aOut);
  152843. pPhrase->doclist.pList = 0;
  152844. pPhrase->doclist.nList = 0;
  152845. }
  152846. sqlite3_free(aPoslist);
  152847. }
  152848. }
  152849. return SQLITE_OK;
  152850. }
  152851. #endif /* SQLITE_DISABLE_FTS4_DEFERRED */
  152852. /*
  152853. ** Maximum number of tokens a phrase may have to be considered for the
  152854. ** incremental doclists strategy.
  152855. */
  152856. #define MAX_INCR_PHRASE_TOKENS 4
  152857. /*
  152858. ** This function is called for each Fts3Phrase in a full-text query
  152859. ** expression to initialize the mechanism for returning rows. Once this
  152860. ** function has been called successfully on an Fts3Phrase, it may be
  152861. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  152862. **
  152863. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  152864. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  152865. ** memory within this call.
  152866. **
  152867. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  152868. */
  152869. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  152870. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152871. int rc = SQLITE_OK; /* Error code */
  152872. int i;
  152873. /* Determine if doclists may be loaded from disk incrementally. This is
  152874. ** possible if the bOptOk argument is true, the FTS doclists will be
  152875. ** scanned in forward order, and the phrase consists of
  152876. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  152877. ** tokens or prefix tokens that cannot use a prefix-index. */
  152878. int bHaveIncr = 0;
  152879. int bIncrOk = (bOptOk
  152880. && pCsr->bDesc==pTab->bDescIdx
  152881. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  152882. #ifdef SQLITE_TEST
  152883. && pTab->bNoIncrDoclist==0
  152884. #endif
  152885. );
  152886. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  152887. Fts3PhraseToken *pToken = &p->aToken[i];
  152888. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  152889. bIncrOk = 0;
  152890. }
  152891. if( pToken->pSegcsr ) bHaveIncr = 1;
  152892. }
  152893. if( bIncrOk && bHaveIncr ){
  152894. /* Use the incremental approach. */
  152895. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  152896. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  152897. Fts3PhraseToken *pToken = &p->aToken[i];
  152898. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  152899. if( pSegcsr ){
  152900. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  152901. }
  152902. }
  152903. p->bIncr = 1;
  152904. }else{
  152905. /* Load the full doclist for the phrase into memory. */
  152906. rc = fts3EvalPhraseLoad(pCsr, p);
  152907. p->bIncr = 0;
  152908. }
  152909. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  152910. return rc;
  152911. }
  152912. /*
  152913. ** This function is used to iterate backwards (from the end to start)
  152914. ** through doclists. It is used by this module to iterate through phrase
  152915. ** doclists in reverse and by the fts3_write.c module to iterate through
  152916. ** pending-terms lists when writing to databases with "order=desc".
  152917. **
  152918. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  152919. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  152920. ** function iterates from the end of the doclist to the beginning.
  152921. */
  152922. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  152923. int bDescIdx, /* True if the doclist is desc */
  152924. char *aDoclist, /* Pointer to entire doclist */
  152925. int nDoclist, /* Length of aDoclist in bytes */
  152926. char **ppIter, /* IN/OUT: Iterator pointer */
  152927. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  152928. int *pnList, /* OUT: List length pointer */
  152929. u8 *pbEof /* OUT: End-of-file flag */
  152930. ){
  152931. char *p = *ppIter;
  152932. assert( nDoclist>0 );
  152933. assert( *pbEof==0 );
  152934. assert( p || *piDocid==0 );
  152935. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  152936. if( p==0 ){
  152937. sqlite3_int64 iDocid = 0;
  152938. char *pNext = 0;
  152939. char *pDocid = aDoclist;
  152940. char *pEnd = &aDoclist[nDoclist];
  152941. int iMul = 1;
  152942. while( pDocid<pEnd ){
  152943. sqlite3_int64 iDelta;
  152944. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  152945. iDocid += (iMul * iDelta);
  152946. pNext = pDocid;
  152947. fts3PoslistCopy(0, &pDocid);
  152948. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  152949. iMul = (bDescIdx ? -1 : 1);
  152950. }
  152951. *pnList = (int)(pEnd - pNext);
  152952. *ppIter = pNext;
  152953. *piDocid = iDocid;
  152954. }else{
  152955. int iMul = (bDescIdx ? -1 : 1);
  152956. sqlite3_int64 iDelta;
  152957. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  152958. *piDocid -= (iMul * iDelta);
  152959. if( p==aDoclist ){
  152960. *pbEof = 1;
  152961. }else{
  152962. char *pSave = p;
  152963. fts3ReversePoslist(aDoclist, &p);
  152964. *pnList = (int)(pSave - p);
  152965. }
  152966. *ppIter = p;
  152967. }
  152968. }
  152969. /*
  152970. ** Iterate forwards through a doclist.
  152971. */
  152972. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  152973. int bDescIdx, /* True if the doclist is desc */
  152974. char *aDoclist, /* Pointer to entire doclist */
  152975. int nDoclist, /* Length of aDoclist in bytes */
  152976. char **ppIter, /* IN/OUT: Iterator pointer */
  152977. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  152978. u8 *pbEof /* OUT: End-of-file flag */
  152979. ){
  152980. char *p = *ppIter;
  152981. assert( nDoclist>0 );
  152982. assert( *pbEof==0 );
  152983. assert( p || *piDocid==0 );
  152984. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  152985. if( p==0 ){
  152986. p = aDoclist;
  152987. p += sqlite3Fts3GetVarint(p, piDocid);
  152988. }else{
  152989. fts3PoslistCopy(0, &p);
  152990. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  152991. if( p>=&aDoclist[nDoclist] ){
  152992. *pbEof = 1;
  152993. }else{
  152994. sqlite3_int64 iVar;
  152995. p += sqlite3Fts3GetVarint(p, &iVar);
  152996. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  152997. }
  152998. }
  152999. *ppIter = p;
  153000. }
  153001. /*
  153002. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  153003. ** to true if EOF is reached.
  153004. */
  153005. static void fts3EvalDlPhraseNext(
  153006. Fts3Table *pTab,
  153007. Fts3Doclist *pDL,
  153008. u8 *pbEof
  153009. ){
  153010. char *pIter; /* Used to iterate through aAll */
  153011. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  153012. if( pDL->pNextDocid ){
  153013. pIter = pDL->pNextDocid;
  153014. }else{
  153015. pIter = pDL->aAll;
  153016. }
  153017. if( pIter>=pEnd ){
  153018. /* We have already reached the end of this doclist. EOF. */
  153019. *pbEof = 1;
  153020. }else{
  153021. sqlite3_int64 iDelta;
  153022. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  153023. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  153024. pDL->iDocid += iDelta;
  153025. }else{
  153026. pDL->iDocid -= iDelta;
  153027. }
  153028. pDL->pList = pIter;
  153029. fts3PoslistCopy(0, &pIter);
  153030. pDL->nList = (int)(pIter - pDL->pList);
  153031. /* pIter now points just past the 0x00 that terminates the position-
  153032. ** list for document pDL->iDocid. However, if this position-list was
  153033. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  153034. ** point to the start of the next docid value. The following line deals
  153035. ** with this case by advancing pIter past the zero-padding added by
  153036. ** fts3EvalNearTrim(). */
  153037. while( pIter<pEnd && *pIter==0 ) pIter++;
  153038. pDL->pNextDocid = pIter;
  153039. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  153040. *pbEof = 0;
  153041. }
  153042. }
  153043. /*
  153044. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  153045. */
  153046. typedef struct TokenDoclist TokenDoclist;
  153047. struct TokenDoclist {
  153048. int bIgnore;
  153049. sqlite3_int64 iDocid;
  153050. char *pList;
  153051. int nList;
  153052. };
  153053. /*
  153054. ** Token pToken is an incrementally loaded token that is part of a
  153055. ** multi-token phrase. Advance it to the next matching document in the
  153056. ** database and populate output variable *p with the details of the new
  153057. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  153058. **
  153059. ** If an error occurs, return an SQLite error code. Otherwise, return
  153060. ** SQLITE_OK.
  153061. */
  153062. static int incrPhraseTokenNext(
  153063. Fts3Table *pTab, /* Virtual table handle */
  153064. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  153065. int iToken, /* Specific token to advance */
  153066. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  153067. u8 *pbEof /* OUT: True if iterator is at EOF */
  153068. ){
  153069. int rc = SQLITE_OK;
  153070. if( pPhrase->iDoclistToken==iToken ){
  153071. assert( p->bIgnore==0 );
  153072. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  153073. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  153074. p->pList = pPhrase->doclist.pList;
  153075. p->nList = pPhrase->doclist.nList;
  153076. p->iDocid = pPhrase->doclist.iDocid;
  153077. }else{
  153078. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  153079. assert( pToken->pDeferred==0 );
  153080. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  153081. if( pToken->pSegcsr ){
  153082. assert( p->bIgnore==0 );
  153083. rc = sqlite3Fts3MsrIncrNext(
  153084. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  153085. );
  153086. if( p->pList==0 ) *pbEof = 1;
  153087. }else{
  153088. p->bIgnore = 1;
  153089. }
  153090. }
  153091. return rc;
  153092. }
  153093. /*
  153094. ** The phrase iterator passed as the second argument:
  153095. **
  153096. ** * features at least one token that uses an incremental doclist, and
  153097. **
  153098. ** * does not contain any deferred tokens.
  153099. **
  153100. ** Advance it to the next matching documnent in the database and populate
  153101. ** the Fts3Doclist.pList and nList fields.
  153102. **
  153103. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  153104. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  153105. ** successfully advanced, *pbEof is set to 0.
  153106. **
  153107. ** If an error occurs, return an SQLite error code. Otherwise, return
  153108. ** SQLITE_OK.
  153109. */
  153110. static int fts3EvalIncrPhraseNext(
  153111. Fts3Cursor *pCsr, /* FTS Cursor handle */
  153112. Fts3Phrase *p, /* Phrase object to advance to next docid */
  153113. u8 *pbEof /* OUT: Set to 1 if EOF */
  153114. ){
  153115. int rc = SQLITE_OK;
  153116. Fts3Doclist *pDL = &p->doclist;
  153117. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  153118. u8 bEof = 0;
  153119. /* This is only called if it is guaranteed that the phrase has at least
  153120. ** one incremental token. In which case the bIncr flag is set. */
  153121. assert( p->bIncr==1 );
  153122. if( p->nToken==1 ){
  153123. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  153124. &pDL->iDocid, &pDL->pList, &pDL->nList
  153125. );
  153126. if( pDL->pList==0 ) bEof = 1;
  153127. }else{
  153128. int bDescDoclist = pCsr->bDesc;
  153129. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  153130. memset(a, 0, sizeof(a));
  153131. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  153132. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  153133. while( bEof==0 ){
  153134. int bMaxSet = 0;
  153135. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  153136. int i; /* Used to iterate through tokens */
  153137. /* Advance the iterator for each token in the phrase once. */
  153138. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  153139. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  153140. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  153141. iMax = a[i].iDocid;
  153142. bMaxSet = 1;
  153143. }
  153144. }
  153145. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  153146. assert( rc!=SQLITE_OK || bMaxSet );
  153147. /* Keep advancing iterators until they all point to the same document */
  153148. for(i=0; i<p->nToken; i++){
  153149. while( rc==SQLITE_OK && bEof==0
  153150. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  153151. ){
  153152. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  153153. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  153154. iMax = a[i].iDocid;
  153155. i = 0;
  153156. }
  153157. }
  153158. }
  153159. /* Check if the current entries really are a phrase match */
  153160. if( bEof==0 ){
  153161. int nList = 0;
  153162. int nByte = a[p->nToken-1].nList;
  153163. char *aDoclist = sqlite3_malloc(nByte+1);
  153164. if( !aDoclist ) return SQLITE_NOMEM;
  153165. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  153166. for(i=0; i<(p->nToken-1); i++){
  153167. if( a[i].bIgnore==0 ){
  153168. char *pL = a[i].pList;
  153169. char *pR = aDoclist;
  153170. char *pOut = aDoclist;
  153171. int nDist = p->nToken-1-i;
  153172. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  153173. if( res==0 ) break;
  153174. nList = (int)(pOut - aDoclist);
  153175. }
  153176. }
  153177. if( i==(p->nToken-1) ){
  153178. pDL->iDocid = iMax;
  153179. pDL->pList = aDoclist;
  153180. pDL->nList = nList;
  153181. pDL->bFreeList = 1;
  153182. break;
  153183. }
  153184. sqlite3_free(aDoclist);
  153185. }
  153186. }
  153187. }
  153188. *pbEof = bEof;
  153189. return rc;
  153190. }
  153191. /*
  153192. ** Attempt to move the phrase iterator to point to the next matching docid.
  153193. ** If an error occurs, return an SQLite error code. Otherwise, return
  153194. ** SQLITE_OK.
  153195. **
  153196. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  153197. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  153198. ** successfully advanced, *pbEof is set to 0.
  153199. */
  153200. static int fts3EvalPhraseNext(
  153201. Fts3Cursor *pCsr, /* FTS Cursor handle */
  153202. Fts3Phrase *p, /* Phrase object to advance to next docid */
  153203. u8 *pbEof /* OUT: Set to 1 if EOF */
  153204. ){
  153205. int rc = SQLITE_OK;
  153206. Fts3Doclist *pDL = &p->doclist;
  153207. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  153208. if( p->bIncr ){
  153209. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  153210. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  153211. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  153212. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  153213. );
  153214. pDL->pList = pDL->pNextDocid;
  153215. }else{
  153216. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  153217. }
  153218. return rc;
  153219. }
  153220. /*
  153221. **
  153222. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  153223. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  153224. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  153225. ** expressions for which all descendent tokens are deferred.
  153226. **
  153227. ** If parameter bOptOk is zero, then it is guaranteed that the
  153228. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  153229. ** each phrase in the expression (subject to deferred token processing).
  153230. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  153231. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  153232. **
  153233. ** If an error occurs within this function, *pRc is set to an SQLite error
  153234. ** code before returning.
  153235. */
  153236. static void fts3EvalStartReaders(
  153237. Fts3Cursor *pCsr, /* FTS Cursor handle */
  153238. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  153239. int *pRc /* IN/OUT: Error code */
  153240. ){
  153241. if( pExpr && SQLITE_OK==*pRc ){
  153242. if( pExpr->eType==FTSQUERY_PHRASE ){
  153243. int nToken = pExpr->pPhrase->nToken;
  153244. if( nToken ){
  153245. int i;
  153246. for(i=0; i<nToken; i++){
  153247. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  153248. }
  153249. pExpr->bDeferred = (i==nToken);
  153250. }
  153251. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  153252. }else{
  153253. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  153254. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  153255. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  153256. }
  153257. }
  153258. }
  153259. /*
  153260. ** An array of the following structures is assembled as part of the process
  153261. ** of selecting tokens to defer before the query starts executing (as part
  153262. ** of the xFilter() method). There is one element in the array for each
  153263. ** token in the FTS expression.
  153264. **
  153265. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  153266. ** to phrases that are connected only by AND and NEAR operators (not OR or
  153267. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  153268. ** separately. The root of a tokens AND/NEAR cluster is stored in
  153269. ** Fts3TokenAndCost.pRoot.
  153270. */
  153271. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  153272. struct Fts3TokenAndCost {
  153273. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  153274. int iToken; /* Position of token in phrase */
  153275. Fts3PhraseToken *pToken; /* The token itself */
  153276. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  153277. int nOvfl; /* Number of overflow pages to load doclist */
  153278. int iCol; /* The column the token must match */
  153279. };
  153280. /*
  153281. ** This function is used to populate an allocated Fts3TokenAndCost array.
  153282. **
  153283. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  153284. ** Otherwise, if an error occurs during execution, *pRc is set to an
  153285. ** SQLite error code.
  153286. */
  153287. static void fts3EvalTokenCosts(
  153288. Fts3Cursor *pCsr, /* FTS Cursor handle */
  153289. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  153290. Fts3Expr *pExpr, /* Expression to consider */
  153291. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  153292. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  153293. int *pRc /* IN/OUT: Error code */
  153294. ){
  153295. if( *pRc==SQLITE_OK ){
  153296. if( pExpr->eType==FTSQUERY_PHRASE ){
  153297. Fts3Phrase *pPhrase = pExpr->pPhrase;
  153298. int i;
  153299. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  153300. Fts3TokenAndCost *pTC = (*ppTC)++;
  153301. pTC->pPhrase = pPhrase;
  153302. pTC->iToken = i;
  153303. pTC->pRoot = pRoot;
  153304. pTC->pToken = &pPhrase->aToken[i];
  153305. pTC->iCol = pPhrase->iColumn;
  153306. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  153307. }
  153308. }else if( pExpr->eType!=FTSQUERY_NOT ){
  153309. assert( pExpr->eType==FTSQUERY_OR
  153310. || pExpr->eType==FTSQUERY_AND
  153311. || pExpr->eType==FTSQUERY_NEAR
  153312. );
  153313. assert( pExpr->pLeft && pExpr->pRight );
  153314. if( pExpr->eType==FTSQUERY_OR ){
  153315. pRoot = pExpr->pLeft;
  153316. **ppOr = pRoot;
  153317. (*ppOr)++;
  153318. }
  153319. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  153320. if( pExpr->eType==FTSQUERY_OR ){
  153321. pRoot = pExpr->pRight;
  153322. **ppOr = pRoot;
  153323. (*ppOr)++;
  153324. }
  153325. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  153326. }
  153327. }
  153328. }
  153329. /*
  153330. ** Determine the average document (row) size in pages. If successful,
  153331. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  153332. ** an SQLite error code.
  153333. **
  153334. ** The average document size in pages is calculated by first calculating
  153335. ** determining the average size in bytes, B. If B is less than the amount
  153336. ** of data that will fit on a single leaf page of an intkey table in
  153337. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  153338. ** the number of overflow pages consumed by a record B bytes in size.
  153339. */
  153340. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  153341. int rc = SQLITE_OK;
  153342. if( pCsr->nRowAvg==0 ){
  153343. /* The average document size, which is required to calculate the cost
  153344. ** of each doclist, has not yet been determined. Read the required
  153345. ** data from the %_stat table to calculate it.
  153346. **
  153347. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  153348. ** varints, where nCol is the number of columns in the FTS3 table.
  153349. ** The first varint is the number of documents currently stored in
  153350. ** the table. The following nCol varints contain the total amount of
  153351. ** data stored in all rows of each column of the table, from left
  153352. ** to right.
  153353. */
  153354. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  153355. sqlite3_stmt *pStmt;
  153356. sqlite3_int64 nDoc = 0;
  153357. sqlite3_int64 nByte = 0;
  153358. const char *pEnd;
  153359. const char *a;
  153360. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  153361. if( rc!=SQLITE_OK ) return rc;
  153362. a = sqlite3_column_blob(pStmt, 0);
  153363. assert( a );
  153364. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  153365. a += sqlite3Fts3GetVarint(a, &nDoc);
  153366. while( a<pEnd ){
  153367. a += sqlite3Fts3GetVarint(a, &nByte);
  153368. }
  153369. if( nDoc==0 || nByte==0 ){
  153370. sqlite3_reset(pStmt);
  153371. return FTS_CORRUPT_VTAB;
  153372. }
  153373. pCsr->nDoc = nDoc;
  153374. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  153375. assert( pCsr->nRowAvg>0 );
  153376. rc = sqlite3_reset(pStmt);
  153377. }
  153378. *pnPage = pCsr->nRowAvg;
  153379. return rc;
  153380. }
  153381. /*
  153382. ** This function is called to select the tokens (if any) that will be
  153383. ** deferred. The array aTC[] has already been populated when this is
  153384. ** called.
  153385. **
  153386. ** This function is called once for each AND/NEAR cluster in the
  153387. ** expression. Each invocation determines which tokens to defer within
  153388. ** the cluster with root node pRoot. See comments above the definition
  153389. ** of struct Fts3TokenAndCost for more details.
  153390. **
  153391. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  153392. ** called on each token to defer. Otherwise, an SQLite error code is
  153393. ** returned.
  153394. */
  153395. static int fts3EvalSelectDeferred(
  153396. Fts3Cursor *pCsr, /* FTS Cursor handle */
  153397. Fts3Expr *pRoot, /* Consider tokens with this root node */
  153398. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  153399. int nTC /* Number of entries in aTC[] */
  153400. ){
  153401. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  153402. int nDocSize = 0; /* Number of pages per doc loaded */
  153403. int rc = SQLITE_OK; /* Return code */
  153404. int ii; /* Iterator variable for various purposes */
  153405. int nOvfl = 0; /* Total overflow pages used by doclists */
  153406. int nToken = 0; /* Total number of tokens in cluster */
  153407. int nMinEst = 0; /* The minimum count for any phrase so far. */
  153408. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  153409. /* Tokens are never deferred for FTS tables created using the content=xxx
  153410. ** option. The reason being that it is not guaranteed that the content
  153411. ** table actually contains the same data as the index. To prevent this from
  153412. ** causing any problems, the deferred token optimization is completely
  153413. ** disabled for content=xxx tables. */
  153414. if( pTab->zContentTbl ){
  153415. return SQLITE_OK;
  153416. }
  153417. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  153418. ** associated with the tokens spill onto overflow pages, or if there is
  153419. ** only 1 token, exit early. No tokens to defer in this case. */
  153420. for(ii=0; ii<nTC; ii++){
  153421. if( aTC[ii].pRoot==pRoot ){
  153422. nOvfl += aTC[ii].nOvfl;
  153423. nToken++;
  153424. }
  153425. }
  153426. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  153427. /* Obtain the average docsize (in pages). */
  153428. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  153429. assert( rc!=SQLITE_OK || nDocSize>0 );
  153430. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  153431. ** of the number of overflow pages that will be loaded by the pager layer
  153432. ** to retrieve the entire doclist for the token from the full-text index.
  153433. ** Load the doclists for tokens that are either:
  153434. **
  153435. ** a. The cheapest token in the entire query (i.e. the one visited by the
  153436. ** first iteration of this loop), or
  153437. **
  153438. ** b. Part of a multi-token phrase.
  153439. **
  153440. ** After each token doclist is loaded, merge it with the others from the
  153441. ** same phrase and count the number of documents that the merged doclist
  153442. ** contains. Set variable "nMinEst" to the smallest number of documents in
  153443. ** any phrase doclist for which 1 or more token doclists have been loaded.
  153444. ** Let nOther be the number of other phrases for which it is certain that
  153445. ** one or more tokens will not be deferred.
  153446. **
  153447. ** Then, for each token, defer it if loading the doclist would result in
  153448. ** loading N or more overflow pages into memory, where N is computed as:
  153449. **
  153450. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  153451. */
  153452. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  153453. int iTC; /* Used to iterate through aTC[] array. */
  153454. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  153455. /* Set pTC to point to the cheapest remaining token. */
  153456. for(iTC=0; iTC<nTC; iTC++){
  153457. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  153458. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  153459. ){
  153460. pTC = &aTC[iTC];
  153461. }
  153462. }
  153463. assert( pTC );
  153464. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  153465. /* The number of overflow pages to load for this (and therefore all
  153466. ** subsequent) tokens is greater than the estimated number of pages
  153467. ** that will be loaded if all subsequent tokens are deferred.
  153468. */
  153469. Fts3PhraseToken *pToken = pTC->pToken;
  153470. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  153471. fts3SegReaderCursorFree(pToken->pSegcsr);
  153472. pToken->pSegcsr = 0;
  153473. }else{
  153474. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  153475. ** for-loop. Except, limit the value to 2^24 to prevent it from
  153476. ** overflowing the 32-bit integer it is stored in. */
  153477. if( ii<12 ) nLoad4 = nLoad4*4;
  153478. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  153479. /* Either this is the cheapest token in the entire query, or it is
  153480. ** part of a multi-token phrase. Either way, the entire doclist will
  153481. ** (eventually) be loaded into memory. It may as well be now. */
  153482. Fts3PhraseToken *pToken = pTC->pToken;
  153483. int nList = 0;
  153484. char *pList = 0;
  153485. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  153486. assert( rc==SQLITE_OK || pList==0 );
  153487. if( rc==SQLITE_OK ){
  153488. rc = fts3EvalPhraseMergeToken(
  153489. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  153490. );
  153491. }
  153492. if( rc==SQLITE_OK ){
  153493. int nCount;
  153494. nCount = fts3DoclistCountDocids(
  153495. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  153496. );
  153497. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  153498. }
  153499. }
  153500. }
  153501. pTC->pToken = 0;
  153502. }
  153503. return rc;
  153504. }
  153505. /*
  153506. ** This function is called from within the xFilter method. It initializes
  153507. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  153508. ** the results of a query, the caller does:
  153509. **
  153510. ** fts3EvalStart(pCsr);
  153511. ** while( 1 ){
  153512. ** fts3EvalNext(pCsr);
  153513. ** if( pCsr->bEof ) break;
  153514. ** ... return row pCsr->iPrevId to the caller ...
  153515. ** }
  153516. */
  153517. static int fts3EvalStart(Fts3Cursor *pCsr){
  153518. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  153519. int rc = SQLITE_OK;
  153520. int nToken = 0;
  153521. int nOr = 0;
  153522. /* Allocate a MultiSegReader for each token in the expression. */
  153523. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  153524. /* Determine which, if any, tokens in the expression should be deferred. */
  153525. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  153526. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  153527. Fts3TokenAndCost *aTC;
  153528. Fts3Expr **apOr;
  153529. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  153530. sizeof(Fts3TokenAndCost) * nToken
  153531. + sizeof(Fts3Expr *) * nOr * 2
  153532. );
  153533. apOr = (Fts3Expr **)&aTC[nToken];
  153534. if( !aTC ){
  153535. rc = SQLITE_NOMEM;
  153536. }else{
  153537. int ii;
  153538. Fts3TokenAndCost *pTC = aTC;
  153539. Fts3Expr **ppOr = apOr;
  153540. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  153541. nToken = (int)(pTC-aTC);
  153542. nOr = (int)(ppOr-apOr);
  153543. if( rc==SQLITE_OK ){
  153544. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  153545. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  153546. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  153547. }
  153548. }
  153549. sqlite3_free(aTC);
  153550. }
  153551. }
  153552. #endif
  153553. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  153554. return rc;
  153555. }
  153556. /*
  153557. ** Invalidate the current position list for phrase pPhrase.
  153558. */
  153559. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  153560. if( pPhrase->doclist.bFreeList ){
  153561. sqlite3_free(pPhrase->doclist.pList);
  153562. }
  153563. pPhrase->doclist.pList = 0;
  153564. pPhrase->doclist.nList = 0;
  153565. pPhrase->doclist.bFreeList = 0;
  153566. }
  153567. /*
  153568. ** This function is called to edit the position list associated with
  153569. ** the phrase object passed as the fifth argument according to a NEAR
  153570. ** condition. For example:
  153571. **
  153572. ** abc NEAR/5 "def ghi"
  153573. **
  153574. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  153575. ** the example above). When this function is called, *paPoslist points to
  153576. ** the position list, and *pnToken is the number of phrase tokens in, the
  153577. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  153578. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  153579. ** the position list associated with phrase "abc".
  153580. **
  153581. ** All positions in the pPhrase position list that are not sufficiently
  153582. ** close to a position in the *paPoslist position list are removed. If this
  153583. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  153584. **
  153585. ** Before returning, *paPoslist is set to point to the position lsit
  153586. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  153587. ** pPhrase.
  153588. */
  153589. static int fts3EvalNearTrim(
  153590. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  153591. char *aTmp, /* Temporary space to use */
  153592. char **paPoslist, /* IN/OUT: Position list */
  153593. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  153594. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  153595. ){
  153596. int nParam1 = nNear + pPhrase->nToken;
  153597. int nParam2 = nNear + *pnToken;
  153598. int nNew;
  153599. char *p2;
  153600. char *pOut;
  153601. int res;
  153602. assert( pPhrase->doclist.pList );
  153603. p2 = pOut = pPhrase->doclist.pList;
  153604. res = fts3PoslistNearMerge(
  153605. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  153606. );
  153607. if( res ){
  153608. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  153609. assert( pPhrase->doclist.pList[nNew]=='\0' );
  153610. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  153611. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  153612. pPhrase->doclist.nList = nNew;
  153613. *paPoslist = pPhrase->doclist.pList;
  153614. *pnToken = pPhrase->nToken;
  153615. }
  153616. return res;
  153617. }
  153618. /*
  153619. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  153620. ** Otherwise, it advances the expression passed as the second argument to
  153621. ** point to the next matching row in the database. Expressions iterate through
  153622. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  153623. ** or descending if it is non-zero.
  153624. **
  153625. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  153626. ** successful, the following variables in pExpr are set:
  153627. **
  153628. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  153629. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  153630. **
  153631. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  153632. ** at EOF, then the following variables are populated with the position list
  153633. ** for the phrase for the visited row:
  153634. **
  153635. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  153636. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  153637. **
  153638. ** It says above that this function advances the expression to the next
  153639. ** matching row. This is usually true, but there are the following exceptions:
  153640. **
  153641. ** 1. Deferred tokens are not taken into account. If a phrase consists
  153642. ** entirely of deferred tokens, it is assumed to match every row in
  153643. ** the db. In this case the position-list is not populated at all.
  153644. **
  153645. ** Or, if a phrase contains one or more deferred tokens and one or
  153646. ** more non-deferred tokens, then the expression is advanced to the
  153647. ** next possible match, considering only non-deferred tokens. In other
  153648. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  153649. ** is advanced to the next row that contains an instance of "A * C",
  153650. ** where "*" may match any single token. The position list in this case
  153651. ** is populated as for "A * C" before returning.
  153652. **
  153653. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  153654. ** advanced to point to the next row that matches "x AND y".
  153655. **
  153656. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  153657. ** really a match, taking into account deferred tokens and NEAR operators.
  153658. */
  153659. static void fts3EvalNextRow(
  153660. Fts3Cursor *pCsr, /* FTS Cursor handle */
  153661. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  153662. int *pRc /* IN/OUT: Error code */
  153663. ){
  153664. if( *pRc==SQLITE_OK ){
  153665. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  153666. assert( pExpr->bEof==0 );
  153667. pExpr->bStart = 1;
  153668. switch( pExpr->eType ){
  153669. case FTSQUERY_NEAR:
  153670. case FTSQUERY_AND: {
  153671. Fts3Expr *pLeft = pExpr->pLeft;
  153672. Fts3Expr *pRight = pExpr->pRight;
  153673. assert( !pLeft->bDeferred || !pRight->bDeferred );
  153674. if( pLeft->bDeferred ){
  153675. /* LHS is entirely deferred. So we assume it matches every row.
  153676. ** Advance the RHS iterator to find the next row visited. */
  153677. fts3EvalNextRow(pCsr, pRight, pRc);
  153678. pExpr->iDocid = pRight->iDocid;
  153679. pExpr->bEof = pRight->bEof;
  153680. }else if( pRight->bDeferred ){
  153681. /* RHS is entirely deferred. So we assume it matches every row.
  153682. ** Advance the LHS iterator to find the next row visited. */
  153683. fts3EvalNextRow(pCsr, pLeft, pRc);
  153684. pExpr->iDocid = pLeft->iDocid;
  153685. pExpr->bEof = pLeft->bEof;
  153686. }else{
  153687. /* Neither the RHS or LHS are deferred. */
  153688. fts3EvalNextRow(pCsr, pLeft, pRc);
  153689. fts3EvalNextRow(pCsr, pRight, pRc);
  153690. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  153691. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  153692. if( iDiff==0 ) break;
  153693. if( iDiff<0 ){
  153694. fts3EvalNextRow(pCsr, pLeft, pRc);
  153695. }else{
  153696. fts3EvalNextRow(pCsr, pRight, pRc);
  153697. }
  153698. }
  153699. pExpr->iDocid = pLeft->iDocid;
  153700. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  153701. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  153702. assert( pRight->eType==FTSQUERY_PHRASE );
  153703. if( pRight->pPhrase->doclist.aAll ){
  153704. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  153705. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  153706. memset(pDl->pList, 0, pDl->nList);
  153707. fts3EvalNextRow(pCsr, pRight, pRc);
  153708. }
  153709. }
  153710. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  153711. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  153712. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  153713. memset(pDl->pList, 0, pDl->nList);
  153714. fts3EvalNextRow(pCsr, pLeft, pRc);
  153715. }
  153716. }
  153717. }
  153718. }
  153719. break;
  153720. }
  153721. case FTSQUERY_OR: {
  153722. Fts3Expr *pLeft = pExpr->pLeft;
  153723. Fts3Expr *pRight = pExpr->pRight;
  153724. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  153725. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  153726. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  153727. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  153728. fts3EvalNextRow(pCsr, pLeft, pRc);
  153729. }else if( pLeft->bEof || iCmp>0 ){
  153730. fts3EvalNextRow(pCsr, pRight, pRc);
  153731. }else{
  153732. fts3EvalNextRow(pCsr, pLeft, pRc);
  153733. fts3EvalNextRow(pCsr, pRight, pRc);
  153734. }
  153735. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  153736. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  153737. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  153738. pExpr->iDocid = pLeft->iDocid;
  153739. }else{
  153740. pExpr->iDocid = pRight->iDocid;
  153741. }
  153742. break;
  153743. }
  153744. case FTSQUERY_NOT: {
  153745. Fts3Expr *pLeft = pExpr->pLeft;
  153746. Fts3Expr *pRight = pExpr->pRight;
  153747. if( pRight->bStart==0 ){
  153748. fts3EvalNextRow(pCsr, pRight, pRc);
  153749. assert( *pRc!=SQLITE_OK || pRight->bStart );
  153750. }
  153751. fts3EvalNextRow(pCsr, pLeft, pRc);
  153752. if( pLeft->bEof==0 ){
  153753. while( !*pRc
  153754. && !pRight->bEof
  153755. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  153756. ){
  153757. fts3EvalNextRow(pCsr, pRight, pRc);
  153758. }
  153759. }
  153760. pExpr->iDocid = pLeft->iDocid;
  153761. pExpr->bEof = pLeft->bEof;
  153762. break;
  153763. }
  153764. default: {
  153765. Fts3Phrase *pPhrase = pExpr->pPhrase;
  153766. fts3EvalInvalidatePoslist(pPhrase);
  153767. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  153768. pExpr->iDocid = pPhrase->doclist.iDocid;
  153769. break;
  153770. }
  153771. }
  153772. }
  153773. }
  153774. /*
  153775. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  153776. ** cluster, then this function returns 1 immediately.
  153777. **
  153778. ** Otherwise, it checks if the current row really does match the NEAR
  153779. ** expression, using the data currently stored in the position lists
  153780. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  153781. **
  153782. ** If the current row is a match, the position list associated with each
  153783. ** phrase in the NEAR expression is edited in place to contain only those
  153784. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  153785. ** constraints. In this case it returns 1. If the NEAR expression does not
  153786. ** match the current row, 0 is returned. The position lists may or may not
  153787. ** be edited if 0 is returned.
  153788. */
  153789. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  153790. int res = 1;
  153791. /* The following block runs if pExpr is the root of a NEAR query.
  153792. ** For example, the query:
  153793. **
  153794. ** "w" NEAR "x" NEAR "y" NEAR "z"
  153795. **
  153796. ** which is represented in tree form as:
  153797. **
  153798. ** |
  153799. ** +--NEAR--+ <-- root of NEAR query
  153800. ** | |
  153801. ** +--NEAR--+ "z"
  153802. ** | |
  153803. ** +--NEAR--+ "y"
  153804. ** | |
  153805. ** "w" "x"
  153806. **
  153807. ** The right-hand child of a NEAR node is always a phrase. The
  153808. ** left-hand child may be either a phrase or a NEAR node. There are
  153809. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  153810. */
  153811. if( *pRc==SQLITE_OK
  153812. && pExpr->eType==FTSQUERY_NEAR
  153813. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  153814. ){
  153815. Fts3Expr *p;
  153816. int nTmp = 0; /* Bytes of temp space */
  153817. char *aTmp; /* Temp space for PoslistNearMerge() */
  153818. /* Allocate temporary working space. */
  153819. for(p=pExpr; p->pLeft; p=p->pLeft){
  153820. assert( p->pRight->pPhrase->doclist.nList>0 );
  153821. nTmp += p->pRight->pPhrase->doclist.nList;
  153822. }
  153823. nTmp += p->pPhrase->doclist.nList;
  153824. aTmp = sqlite3_malloc(nTmp*2);
  153825. if( !aTmp ){
  153826. *pRc = SQLITE_NOMEM;
  153827. res = 0;
  153828. }else{
  153829. char *aPoslist = p->pPhrase->doclist.pList;
  153830. int nToken = p->pPhrase->nToken;
  153831. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  153832. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  153833. int nNear = p->nNear;
  153834. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  153835. }
  153836. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  153837. nToken = pExpr->pRight->pPhrase->nToken;
  153838. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  153839. int nNear;
  153840. Fts3Phrase *pPhrase;
  153841. assert( p->pParent && p->pParent->pLeft==p );
  153842. nNear = p->pParent->nNear;
  153843. pPhrase = (
  153844. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  153845. );
  153846. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  153847. }
  153848. }
  153849. sqlite3_free(aTmp);
  153850. }
  153851. return res;
  153852. }
  153853. /*
  153854. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  153855. ** Assuming no error occurs or has occurred, It returns non-zero if the
  153856. ** expression passed as the second argument matches the row that pCsr
  153857. ** currently points to, or zero if it does not.
  153858. **
  153859. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  153860. ** If an error occurs during execution of this function, *pRc is set to
  153861. ** the appropriate SQLite error code. In this case the returned value is
  153862. ** undefined.
  153863. */
  153864. static int fts3EvalTestExpr(
  153865. Fts3Cursor *pCsr, /* FTS cursor handle */
  153866. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  153867. int *pRc /* IN/OUT: Error code */
  153868. ){
  153869. int bHit = 1; /* Return value */
  153870. if( *pRc==SQLITE_OK ){
  153871. switch( pExpr->eType ){
  153872. case FTSQUERY_NEAR:
  153873. case FTSQUERY_AND:
  153874. bHit = (
  153875. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  153876. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  153877. && fts3EvalNearTest(pExpr, pRc)
  153878. );
  153879. /* If the NEAR expression does not match any rows, zero the doclist for
  153880. ** all phrases involved in the NEAR. This is because the snippet(),
  153881. ** offsets() and matchinfo() functions are not supposed to recognize
  153882. ** any instances of phrases that are part of unmatched NEAR queries.
  153883. ** For example if this expression:
  153884. **
  153885. ** ... MATCH 'a OR (b NEAR c)'
  153886. **
  153887. ** is matched against a row containing:
  153888. **
  153889. ** 'a b d e'
  153890. **
  153891. ** then any snippet() should ony highlight the "a" term, not the "b"
  153892. ** (as "b" is part of a non-matching NEAR clause).
  153893. */
  153894. if( bHit==0
  153895. && pExpr->eType==FTSQUERY_NEAR
  153896. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  153897. ){
  153898. Fts3Expr *p;
  153899. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  153900. if( p->pRight->iDocid==pCsr->iPrevId ){
  153901. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  153902. }
  153903. }
  153904. if( p->iDocid==pCsr->iPrevId ){
  153905. fts3EvalInvalidatePoslist(p->pPhrase);
  153906. }
  153907. }
  153908. break;
  153909. case FTSQUERY_OR: {
  153910. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  153911. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  153912. bHit = bHit1 || bHit2;
  153913. break;
  153914. }
  153915. case FTSQUERY_NOT:
  153916. bHit = (
  153917. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  153918. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  153919. );
  153920. break;
  153921. default: {
  153922. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  153923. if( pCsr->pDeferred
  153924. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  153925. ){
  153926. Fts3Phrase *pPhrase = pExpr->pPhrase;
  153927. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  153928. if( pExpr->bDeferred ){
  153929. fts3EvalInvalidatePoslist(pPhrase);
  153930. }
  153931. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  153932. bHit = (pPhrase->doclist.pList!=0);
  153933. pExpr->iDocid = pCsr->iPrevId;
  153934. }else
  153935. #endif
  153936. {
  153937. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  153938. }
  153939. break;
  153940. }
  153941. }
  153942. }
  153943. return bHit;
  153944. }
  153945. /*
  153946. ** This function is called as the second part of each xNext operation when
  153947. ** iterating through the results of a full-text query. At this point the
  153948. ** cursor points to a row that matches the query expression, with the
  153949. ** following caveats:
  153950. **
  153951. ** * Up until this point, "NEAR" operators in the expression have been
  153952. ** treated as "AND".
  153953. **
  153954. ** * Deferred tokens have not yet been considered.
  153955. **
  153956. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  153957. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  153958. ** operators and deferred tokens the current row is still a match for the
  153959. ** expression. It returns 1 if both of the following are true:
  153960. **
  153961. ** 1. *pRc is SQLITE_OK when this function returns, and
  153962. **
  153963. ** 2. After scanning the current FTS table row for the deferred tokens,
  153964. ** it is determined that the row does *not* match the query.
  153965. **
  153966. ** Or, if no error occurs and it seems the current row does match the FTS
  153967. ** query, return 0.
  153968. */
  153969. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  153970. int rc = *pRc;
  153971. int bMiss = 0;
  153972. if( rc==SQLITE_OK ){
  153973. /* If there are one or more deferred tokens, load the current row into
  153974. ** memory and scan it to determine the position list for each deferred
  153975. ** token. Then, see if this row is really a match, considering deferred
  153976. ** tokens and NEAR operators (neither of which were taken into account
  153977. ** earlier, by fts3EvalNextRow()).
  153978. */
  153979. if( pCsr->pDeferred ){
  153980. rc = fts3CursorSeek(0, pCsr);
  153981. if( rc==SQLITE_OK ){
  153982. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  153983. }
  153984. }
  153985. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  153986. /* Free the position-lists accumulated for each deferred token above. */
  153987. sqlite3Fts3FreeDeferredDoclists(pCsr);
  153988. *pRc = rc;
  153989. }
  153990. return (rc==SQLITE_OK && bMiss);
  153991. }
  153992. /*
  153993. ** Advance to the next document that matches the FTS expression in
  153994. ** Fts3Cursor.pExpr.
  153995. */
  153996. static int fts3EvalNext(Fts3Cursor *pCsr){
  153997. int rc = SQLITE_OK; /* Return Code */
  153998. Fts3Expr *pExpr = pCsr->pExpr;
  153999. assert( pCsr->isEof==0 );
  154000. if( pExpr==0 ){
  154001. pCsr->isEof = 1;
  154002. }else{
  154003. do {
  154004. if( pCsr->isRequireSeek==0 ){
  154005. sqlite3_reset(pCsr->pStmt);
  154006. }
  154007. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  154008. fts3EvalNextRow(pCsr, pExpr, &rc);
  154009. pCsr->isEof = pExpr->bEof;
  154010. pCsr->isRequireSeek = 1;
  154011. pCsr->isMatchinfoNeeded = 1;
  154012. pCsr->iPrevId = pExpr->iDocid;
  154013. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  154014. }
  154015. /* Check if the cursor is past the end of the docid range specified
  154016. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  154017. if( rc==SQLITE_OK && (
  154018. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  154019. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  154020. )){
  154021. pCsr->isEof = 1;
  154022. }
  154023. return rc;
  154024. }
  154025. /*
  154026. ** Restart interation for expression pExpr so that the next call to
  154027. ** fts3EvalNext() visits the first row. Do not allow incremental
  154028. ** loading or merging of phrase doclists for this iteration.
  154029. **
  154030. ** If *pRc is other than SQLITE_OK when this function is called, it is
  154031. ** a no-op. If an error occurs within this function, *pRc is set to an
  154032. ** SQLite error code before returning.
  154033. */
  154034. static void fts3EvalRestart(
  154035. Fts3Cursor *pCsr,
  154036. Fts3Expr *pExpr,
  154037. int *pRc
  154038. ){
  154039. if( pExpr && *pRc==SQLITE_OK ){
  154040. Fts3Phrase *pPhrase = pExpr->pPhrase;
  154041. if( pPhrase ){
  154042. fts3EvalInvalidatePoslist(pPhrase);
  154043. if( pPhrase->bIncr ){
  154044. int i;
  154045. for(i=0; i<pPhrase->nToken; i++){
  154046. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  154047. assert( pToken->pDeferred==0 );
  154048. if( pToken->pSegcsr ){
  154049. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  154050. }
  154051. }
  154052. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  154053. }
  154054. pPhrase->doclist.pNextDocid = 0;
  154055. pPhrase->doclist.iDocid = 0;
  154056. pPhrase->pOrPoslist = 0;
  154057. }
  154058. pExpr->iDocid = 0;
  154059. pExpr->bEof = 0;
  154060. pExpr->bStart = 0;
  154061. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  154062. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  154063. }
  154064. }
  154065. /*
  154066. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  154067. ** expression rooted at pExpr, the cursor iterates through all rows matched
  154068. ** by pExpr, calling this function for each row. This function increments
  154069. ** the values in Fts3Expr.aMI[] according to the position-list currently
  154070. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  154071. ** expression nodes.
  154072. */
  154073. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  154074. if( pExpr ){
  154075. Fts3Phrase *pPhrase = pExpr->pPhrase;
  154076. if( pPhrase && pPhrase->doclist.pList ){
  154077. int iCol = 0;
  154078. char *p = pPhrase->doclist.pList;
  154079. assert( *p );
  154080. while( 1 ){
  154081. u8 c = 0;
  154082. int iCnt = 0;
  154083. while( 0xFE & (*p | c) ){
  154084. if( (c&0x80)==0 ) iCnt++;
  154085. c = *p++ & 0x80;
  154086. }
  154087. /* aMI[iCol*3 + 1] = Number of occurrences
  154088. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  154089. */
  154090. pExpr->aMI[iCol*3 + 1] += iCnt;
  154091. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  154092. if( *p==0x00 ) break;
  154093. p++;
  154094. p += fts3GetVarint32(p, &iCol);
  154095. }
  154096. }
  154097. fts3EvalUpdateCounts(pExpr->pLeft);
  154098. fts3EvalUpdateCounts(pExpr->pRight);
  154099. }
  154100. }
  154101. /*
  154102. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  154103. **
  154104. ** If it is not already allocated and populated, this function allocates and
  154105. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  154106. ** of a NEAR expression, then it also allocates and populates the same array
  154107. ** for all other phrases that are part of the NEAR expression.
  154108. **
  154109. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  154110. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  154111. */
  154112. static int fts3EvalGatherStats(
  154113. Fts3Cursor *pCsr, /* Cursor object */
  154114. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  154115. ){
  154116. int rc = SQLITE_OK; /* Return code */
  154117. assert( pExpr->eType==FTSQUERY_PHRASE );
  154118. if( pExpr->aMI==0 ){
  154119. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  154120. Fts3Expr *pRoot; /* Root of NEAR expression */
  154121. Fts3Expr *p; /* Iterator used for several purposes */
  154122. sqlite3_int64 iPrevId = pCsr->iPrevId;
  154123. sqlite3_int64 iDocid;
  154124. u8 bEof;
  154125. /* Find the root of the NEAR expression */
  154126. pRoot = pExpr;
  154127. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  154128. pRoot = pRoot->pParent;
  154129. }
  154130. iDocid = pRoot->iDocid;
  154131. bEof = pRoot->bEof;
  154132. assert( pRoot->bStart );
  154133. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  154134. for(p=pRoot; p; p=p->pLeft){
  154135. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  154136. assert( pE->aMI==0 );
  154137. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  154138. if( !pE->aMI ) return SQLITE_NOMEM;
  154139. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  154140. }
  154141. fts3EvalRestart(pCsr, pRoot, &rc);
  154142. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  154143. do {
  154144. /* Ensure the %_content statement is reset. */
  154145. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  154146. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  154147. /* Advance to the next document */
  154148. fts3EvalNextRow(pCsr, pRoot, &rc);
  154149. pCsr->isEof = pRoot->bEof;
  154150. pCsr->isRequireSeek = 1;
  154151. pCsr->isMatchinfoNeeded = 1;
  154152. pCsr->iPrevId = pRoot->iDocid;
  154153. }while( pCsr->isEof==0
  154154. && pRoot->eType==FTSQUERY_NEAR
  154155. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  154156. );
  154157. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  154158. fts3EvalUpdateCounts(pRoot);
  154159. }
  154160. }
  154161. pCsr->isEof = 0;
  154162. pCsr->iPrevId = iPrevId;
  154163. if( bEof ){
  154164. pRoot->bEof = bEof;
  154165. }else{
  154166. /* Caution: pRoot may iterate through docids in ascending or descending
  154167. ** order. For this reason, even though it seems more defensive, the
  154168. ** do loop can not be written:
  154169. **
  154170. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  154171. */
  154172. fts3EvalRestart(pCsr, pRoot, &rc);
  154173. do {
  154174. fts3EvalNextRow(pCsr, pRoot, &rc);
  154175. assert( pRoot->bEof==0 );
  154176. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  154177. }
  154178. }
  154179. return rc;
  154180. }
  154181. /*
  154182. ** This function is used by the matchinfo() module to query a phrase
  154183. ** expression node for the following information:
  154184. **
  154185. ** 1. The total number of occurrences of the phrase in each column of
  154186. ** the FTS table (considering all rows), and
  154187. **
  154188. ** 2. For each column, the number of rows in the table for which the
  154189. ** column contains at least one instance of the phrase.
  154190. **
  154191. ** If no error occurs, SQLITE_OK is returned and the values for each column
  154192. ** written into the array aiOut as follows:
  154193. **
  154194. ** aiOut[iCol*3 + 1] = Number of occurrences
  154195. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  154196. **
  154197. ** Caveats:
  154198. **
  154199. ** * If a phrase consists entirely of deferred tokens, then all output
  154200. ** values are set to the number of documents in the table. In other
  154201. ** words we assume that very common tokens occur exactly once in each
  154202. ** column of each row of the table.
  154203. **
  154204. ** * If a phrase contains some deferred tokens (and some non-deferred
  154205. ** tokens), count the potential occurrence identified by considering
  154206. ** the non-deferred tokens instead of actual phrase occurrences.
  154207. **
  154208. ** * If the phrase is part of a NEAR expression, then only phrase instances
  154209. ** that meet the NEAR constraint are included in the counts.
  154210. */
  154211. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  154212. Fts3Cursor *pCsr, /* FTS cursor handle */
  154213. Fts3Expr *pExpr, /* Phrase expression */
  154214. u32 *aiOut /* Array to write results into (see above) */
  154215. ){
  154216. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  154217. int rc = SQLITE_OK;
  154218. int iCol;
  154219. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  154220. assert( pCsr->nDoc>0 );
  154221. for(iCol=0; iCol<pTab->nColumn; iCol++){
  154222. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  154223. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  154224. }
  154225. }else{
  154226. rc = fts3EvalGatherStats(pCsr, pExpr);
  154227. if( rc==SQLITE_OK ){
  154228. assert( pExpr->aMI );
  154229. for(iCol=0; iCol<pTab->nColumn; iCol++){
  154230. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  154231. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  154232. }
  154233. }
  154234. }
  154235. return rc;
  154236. }
  154237. /*
  154238. ** The expression pExpr passed as the second argument to this function
  154239. ** must be of type FTSQUERY_PHRASE.
  154240. **
  154241. ** The returned value is either NULL or a pointer to a buffer containing
  154242. ** a position-list indicating the occurrences of the phrase in column iCol
  154243. ** of the current row.
  154244. **
  154245. ** More specifically, the returned buffer contains 1 varint for each
  154246. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  154247. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  154248. ** if the requested column contains "a b X c d X X" and the position-list
  154249. ** for 'X' is requested, the buffer returned may contain:
  154250. **
  154251. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  154252. **
  154253. ** This function works regardless of whether or not the phrase is deferred,
  154254. ** incremental, or neither.
  154255. */
  154256. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  154257. Fts3Cursor *pCsr, /* FTS3 cursor object */
  154258. Fts3Expr *pExpr, /* Phrase to return doclist for */
  154259. int iCol, /* Column to return position list for */
  154260. char **ppOut /* OUT: Pointer to position list */
  154261. ){
  154262. Fts3Phrase *pPhrase = pExpr->pPhrase;
  154263. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  154264. char *pIter;
  154265. int iThis;
  154266. sqlite3_int64 iDocid;
  154267. /* If this phrase is applies specifically to some column other than
  154268. ** column iCol, return a NULL pointer. */
  154269. *ppOut = 0;
  154270. assert( iCol>=0 && iCol<pTab->nColumn );
  154271. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  154272. return SQLITE_OK;
  154273. }
  154274. iDocid = pExpr->iDocid;
  154275. pIter = pPhrase->doclist.pList;
  154276. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  154277. int rc = SQLITE_OK;
  154278. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  154279. int bOr = 0;
  154280. u8 bTreeEof = 0;
  154281. Fts3Expr *p; /* Used to iterate from pExpr to root */
  154282. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  154283. int bMatch;
  154284. /* Check if this phrase descends from an OR expression node. If not,
  154285. ** return NULL. Otherwise, the entry that corresponds to docid
  154286. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  154287. ** tree that the node is part of has been marked as EOF, but the node
  154288. ** itself is not EOF, then it may point to an earlier entry. */
  154289. pNear = pExpr;
  154290. for(p=pExpr->pParent; p; p=p->pParent){
  154291. if( p->eType==FTSQUERY_OR ) bOr = 1;
  154292. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  154293. if( p->bEof ) bTreeEof = 1;
  154294. }
  154295. if( bOr==0 ) return SQLITE_OK;
  154296. /* This is the descendent of an OR node. In this case we cannot use
  154297. ** an incremental phrase. Load the entire doclist for the phrase
  154298. ** into memory in this case. */
  154299. if( pPhrase->bIncr ){
  154300. int bEofSave = pNear->bEof;
  154301. fts3EvalRestart(pCsr, pNear, &rc);
  154302. while( rc==SQLITE_OK && !pNear->bEof ){
  154303. fts3EvalNextRow(pCsr, pNear, &rc);
  154304. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  154305. }
  154306. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  154307. }
  154308. if( bTreeEof ){
  154309. while( rc==SQLITE_OK && !pNear->bEof ){
  154310. fts3EvalNextRow(pCsr, pNear, &rc);
  154311. }
  154312. }
  154313. if( rc!=SQLITE_OK ) return rc;
  154314. bMatch = 1;
  154315. for(p=pNear; p; p=p->pLeft){
  154316. u8 bEof = 0;
  154317. Fts3Expr *pTest = p;
  154318. Fts3Phrase *pPh;
  154319. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  154320. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  154321. assert( pTest->eType==FTSQUERY_PHRASE );
  154322. pPh = pTest->pPhrase;
  154323. pIter = pPh->pOrPoslist;
  154324. iDocid = pPh->iOrDocid;
  154325. if( pCsr->bDesc==bDescDoclist ){
  154326. bEof = !pPh->doclist.nAll ||
  154327. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  154328. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  154329. sqlite3Fts3DoclistNext(
  154330. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  154331. &pIter, &iDocid, &bEof
  154332. );
  154333. }
  154334. }else{
  154335. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  154336. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  154337. int dummy;
  154338. sqlite3Fts3DoclistPrev(
  154339. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  154340. &pIter, &iDocid, &dummy, &bEof
  154341. );
  154342. }
  154343. }
  154344. pPh->pOrPoslist = pIter;
  154345. pPh->iOrDocid = iDocid;
  154346. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  154347. }
  154348. if( bMatch ){
  154349. pIter = pPhrase->pOrPoslist;
  154350. }else{
  154351. pIter = 0;
  154352. }
  154353. }
  154354. if( pIter==0 ) return SQLITE_OK;
  154355. if( *pIter==0x01 ){
  154356. pIter++;
  154357. pIter += fts3GetVarint32(pIter, &iThis);
  154358. }else{
  154359. iThis = 0;
  154360. }
  154361. while( iThis<iCol ){
  154362. fts3ColumnlistCopy(0, &pIter);
  154363. if( *pIter==0x00 ) return SQLITE_OK;
  154364. pIter++;
  154365. pIter += fts3GetVarint32(pIter, &iThis);
  154366. }
  154367. if( *pIter==0x00 ){
  154368. pIter = 0;
  154369. }
  154370. *ppOut = ((iCol==iThis)?pIter:0);
  154371. return SQLITE_OK;
  154372. }
  154373. /*
  154374. ** Free all components of the Fts3Phrase structure that were allocated by
  154375. ** the eval module. Specifically, this means to free:
  154376. **
  154377. ** * the contents of pPhrase->doclist, and
  154378. ** * any Fts3MultiSegReader objects held by phrase tokens.
  154379. */
  154380. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  154381. if( pPhrase ){
  154382. int i;
  154383. sqlite3_free(pPhrase->doclist.aAll);
  154384. fts3EvalInvalidatePoslist(pPhrase);
  154385. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  154386. for(i=0; i<pPhrase->nToken; i++){
  154387. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  154388. pPhrase->aToken[i].pSegcsr = 0;
  154389. }
  154390. }
  154391. }
  154392. /*
  154393. ** Return SQLITE_CORRUPT_VTAB.
  154394. */
  154395. #ifdef SQLITE_DEBUG
  154396. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  154397. return SQLITE_CORRUPT_VTAB;
  154398. }
  154399. #endif
  154400. #if !SQLITE_CORE
  154401. /*
  154402. ** Initialize API pointer table, if required.
  154403. */
  154404. #ifdef _WIN32
  154405. __declspec(dllexport)
  154406. #endif
  154407. SQLITE_API int sqlite3_fts3_init(
  154408. sqlite3 *db,
  154409. char **pzErrMsg,
  154410. const sqlite3_api_routines *pApi
  154411. ){
  154412. SQLITE_EXTENSION_INIT2(pApi)
  154413. return sqlite3Fts3Init(db);
  154414. }
  154415. #endif
  154416. #endif
  154417. /************** End of fts3.c ************************************************/
  154418. /************** Begin file fts3_aux.c ****************************************/
  154419. /*
  154420. ** 2011 Jan 27
  154421. **
  154422. ** The author disclaims copyright to this source code. In place of
  154423. ** a legal notice, here is a blessing:
  154424. **
  154425. ** May you do good and not evil.
  154426. ** May you find forgiveness for yourself and forgive others.
  154427. ** May you share freely, never taking more than you give.
  154428. **
  154429. ******************************************************************************
  154430. **
  154431. */
  154432. /* #include "fts3Int.h" */
  154433. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  154434. /* #include <string.h> */
  154435. /* #include <assert.h> */
  154436. typedef struct Fts3auxTable Fts3auxTable;
  154437. typedef struct Fts3auxCursor Fts3auxCursor;
  154438. struct Fts3auxTable {
  154439. sqlite3_vtab base; /* Base class used by SQLite core */
  154440. Fts3Table *pFts3Tab;
  154441. };
  154442. struct Fts3auxCursor {
  154443. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  154444. Fts3MultiSegReader csr; /* Must be right after "base" */
  154445. Fts3SegFilter filter;
  154446. char *zStop;
  154447. int nStop; /* Byte-length of string zStop */
  154448. int iLangid; /* Language id to query */
  154449. int isEof; /* True if cursor is at EOF */
  154450. sqlite3_int64 iRowid; /* Current rowid */
  154451. int iCol; /* Current value of 'col' column */
  154452. int nStat; /* Size of aStat[] array */
  154453. struct Fts3auxColstats {
  154454. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  154455. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  154456. } *aStat;
  154457. };
  154458. /*
  154459. ** Schema of the terms table.
  154460. */
  154461. #define FTS3_AUX_SCHEMA \
  154462. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  154463. /*
  154464. ** This function does all the work for both the xConnect and xCreate methods.
  154465. ** These tables have no persistent representation of their own, so xConnect
  154466. ** and xCreate are identical operations.
  154467. */
  154468. static int fts3auxConnectMethod(
  154469. sqlite3 *db, /* Database connection */
  154470. void *pUnused, /* Unused */
  154471. int argc, /* Number of elements in argv array */
  154472. const char * const *argv, /* xCreate/xConnect argument array */
  154473. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  154474. char **pzErr /* OUT: sqlite3_malloc'd error message */
  154475. ){
  154476. char const *zDb; /* Name of database (e.g. "main") */
  154477. char const *zFts3; /* Name of fts3 table */
  154478. int nDb; /* Result of strlen(zDb) */
  154479. int nFts3; /* Result of strlen(zFts3) */
  154480. int nByte; /* Bytes of space to allocate here */
  154481. int rc; /* value returned by declare_vtab() */
  154482. Fts3auxTable *p; /* Virtual table object to return */
  154483. UNUSED_PARAMETER(pUnused);
  154484. /* The user should invoke this in one of two forms:
  154485. **
  154486. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  154487. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  154488. */
  154489. if( argc!=4 && argc!=5 ) goto bad_args;
  154490. zDb = argv[1];
  154491. nDb = (int)strlen(zDb);
  154492. if( argc==5 ){
  154493. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  154494. zDb = argv[3];
  154495. nDb = (int)strlen(zDb);
  154496. zFts3 = argv[4];
  154497. }else{
  154498. goto bad_args;
  154499. }
  154500. }else{
  154501. zFts3 = argv[3];
  154502. }
  154503. nFts3 = (int)strlen(zFts3);
  154504. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  154505. if( rc!=SQLITE_OK ) return rc;
  154506. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  154507. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  154508. if( !p ) return SQLITE_NOMEM;
  154509. memset(p, 0, nByte);
  154510. p->pFts3Tab = (Fts3Table *)&p[1];
  154511. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  154512. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  154513. p->pFts3Tab->db = db;
  154514. p->pFts3Tab->nIndex = 1;
  154515. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  154516. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  154517. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  154518. *ppVtab = (sqlite3_vtab *)p;
  154519. return SQLITE_OK;
  154520. bad_args:
  154521. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  154522. return SQLITE_ERROR;
  154523. }
  154524. /*
  154525. ** This function does the work for both the xDisconnect and xDestroy methods.
  154526. ** These tables have no persistent representation of their own, so xDisconnect
  154527. ** and xDestroy are identical operations.
  154528. */
  154529. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  154530. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  154531. Fts3Table *pFts3 = p->pFts3Tab;
  154532. int i;
  154533. /* Free any prepared statements held */
  154534. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  154535. sqlite3_finalize(pFts3->aStmt[i]);
  154536. }
  154537. sqlite3_free(pFts3->zSegmentsTbl);
  154538. sqlite3_free(p);
  154539. return SQLITE_OK;
  154540. }
  154541. #define FTS4AUX_EQ_CONSTRAINT 1
  154542. #define FTS4AUX_GE_CONSTRAINT 2
  154543. #define FTS4AUX_LE_CONSTRAINT 4
  154544. /*
  154545. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  154546. */
  154547. static int fts3auxBestIndexMethod(
  154548. sqlite3_vtab *pVTab,
  154549. sqlite3_index_info *pInfo
  154550. ){
  154551. int i;
  154552. int iEq = -1;
  154553. int iGe = -1;
  154554. int iLe = -1;
  154555. int iLangid = -1;
  154556. int iNext = 1; /* Next free argvIndex value */
  154557. UNUSED_PARAMETER(pVTab);
  154558. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  154559. if( pInfo->nOrderBy==1
  154560. && pInfo->aOrderBy[0].iColumn==0
  154561. && pInfo->aOrderBy[0].desc==0
  154562. ){
  154563. pInfo->orderByConsumed = 1;
  154564. }
  154565. /* Search for equality and range constraints on the "term" column.
  154566. ** And equality constraints on the hidden "languageid" column. */
  154567. for(i=0; i<pInfo->nConstraint; i++){
  154568. if( pInfo->aConstraint[i].usable ){
  154569. int op = pInfo->aConstraint[i].op;
  154570. int iCol = pInfo->aConstraint[i].iColumn;
  154571. if( iCol==0 ){
  154572. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  154573. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  154574. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  154575. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  154576. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  154577. }
  154578. if( iCol==4 ){
  154579. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  154580. }
  154581. }
  154582. }
  154583. if( iEq>=0 ){
  154584. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  154585. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  154586. pInfo->estimatedCost = 5;
  154587. }else{
  154588. pInfo->idxNum = 0;
  154589. pInfo->estimatedCost = 20000;
  154590. if( iGe>=0 ){
  154591. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  154592. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  154593. pInfo->estimatedCost /= 2;
  154594. }
  154595. if( iLe>=0 ){
  154596. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  154597. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  154598. pInfo->estimatedCost /= 2;
  154599. }
  154600. }
  154601. if( iLangid>=0 ){
  154602. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  154603. pInfo->estimatedCost--;
  154604. }
  154605. return SQLITE_OK;
  154606. }
  154607. /*
  154608. ** xOpen - Open a cursor.
  154609. */
  154610. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  154611. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  154612. UNUSED_PARAMETER(pVTab);
  154613. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  154614. if( !pCsr ) return SQLITE_NOMEM;
  154615. memset(pCsr, 0, sizeof(Fts3auxCursor));
  154616. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  154617. return SQLITE_OK;
  154618. }
  154619. /*
  154620. ** xClose - Close a cursor.
  154621. */
  154622. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  154623. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  154624. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  154625. sqlite3Fts3SegmentsClose(pFts3);
  154626. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  154627. sqlite3_free((void *)pCsr->filter.zTerm);
  154628. sqlite3_free(pCsr->zStop);
  154629. sqlite3_free(pCsr->aStat);
  154630. sqlite3_free(pCsr);
  154631. return SQLITE_OK;
  154632. }
  154633. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  154634. if( nSize>pCsr->nStat ){
  154635. struct Fts3auxColstats *aNew;
  154636. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  154637. sizeof(struct Fts3auxColstats) * nSize
  154638. );
  154639. if( aNew==0 ) return SQLITE_NOMEM;
  154640. memset(&aNew[pCsr->nStat], 0,
  154641. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  154642. );
  154643. pCsr->aStat = aNew;
  154644. pCsr->nStat = nSize;
  154645. }
  154646. return SQLITE_OK;
  154647. }
  154648. /*
  154649. ** xNext - Advance the cursor to the next row, if any.
  154650. */
  154651. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  154652. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  154653. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  154654. int rc;
  154655. /* Increment our pretend rowid value. */
  154656. pCsr->iRowid++;
  154657. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  154658. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  154659. }
  154660. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  154661. if( rc==SQLITE_ROW ){
  154662. int i = 0;
  154663. int nDoclist = pCsr->csr.nDoclist;
  154664. char *aDoclist = pCsr->csr.aDoclist;
  154665. int iCol;
  154666. int eState = 0;
  154667. if( pCsr->zStop ){
  154668. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  154669. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  154670. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  154671. pCsr->isEof = 1;
  154672. return SQLITE_OK;
  154673. }
  154674. }
  154675. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  154676. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  154677. iCol = 0;
  154678. while( i<nDoclist ){
  154679. sqlite3_int64 v = 0;
  154680. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  154681. switch( eState ){
  154682. /* State 0. In this state the integer just read was a docid. */
  154683. case 0:
  154684. pCsr->aStat[0].nDoc++;
  154685. eState = 1;
  154686. iCol = 0;
  154687. break;
  154688. /* State 1. In this state we are expecting either a 1, indicating
  154689. ** that the following integer will be a column number, or the
  154690. ** start of a position list for column 0.
  154691. **
  154692. ** The only difference between state 1 and state 2 is that if the
  154693. ** integer encountered in state 1 is not 0 or 1, then we need to
  154694. ** increment the column 0 "nDoc" count for this term.
  154695. */
  154696. case 1:
  154697. assert( iCol==0 );
  154698. if( v>1 ){
  154699. pCsr->aStat[1].nDoc++;
  154700. }
  154701. eState = 2;
  154702. /* fall through */
  154703. case 2:
  154704. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  154705. eState = 0;
  154706. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  154707. eState = 3;
  154708. }else{ /* 2 or greater. A position. */
  154709. pCsr->aStat[iCol+1].nOcc++;
  154710. pCsr->aStat[0].nOcc++;
  154711. }
  154712. break;
  154713. /* State 3. The integer just read is a column number. */
  154714. default: assert( eState==3 );
  154715. iCol = (int)v;
  154716. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  154717. pCsr->aStat[iCol+1].nDoc++;
  154718. eState = 2;
  154719. break;
  154720. }
  154721. }
  154722. pCsr->iCol = 0;
  154723. rc = SQLITE_OK;
  154724. }else{
  154725. pCsr->isEof = 1;
  154726. }
  154727. return rc;
  154728. }
  154729. /*
  154730. ** xFilter - Initialize a cursor to point at the start of its data.
  154731. */
  154732. static int fts3auxFilterMethod(
  154733. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  154734. int idxNum, /* Strategy index */
  154735. const char *idxStr, /* Unused */
  154736. int nVal, /* Number of elements in apVal */
  154737. sqlite3_value **apVal /* Arguments for the indexing scheme */
  154738. ){
  154739. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  154740. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  154741. int rc;
  154742. int isScan = 0;
  154743. int iLangVal = 0; /* Language id to query */
  154744. int iEq = -1; /* Index of term=? value in apVal */
  154745. int iGe = -1; /* Index of term>=? value in apVal */
  154746. int iLe = -1; /* Index of term<=? value in apVal */
  154747. int iLangid = -1; /* Index of languageid=? value in apVal */
  154748. int iNext = 0;
  154749. UNUSED_PARAMETER(nVal);
  154750. UNUSED_PARAMETER(idxStr);
  154751. assert( idxStr==0 );
  154752. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  154753. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  154754. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  154755. );
  154756. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  154757. iEq = iNext++;
  154758. }else{
  154759. isScan = 1;
  154760. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  154761. iGe = iNext++;
  154762. }
  154763. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  154764. iLe = iNext++;
  154765. }
  154766. }
  154767. if( iNext<nVal ){
  154768. iLangid = iNext++;
  154769. }
  154770. /* In case this cursor is being reused, close and zero it. */
  154771. testcase(pCsr->filter.zTerm);
  154772. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  154773. sqlite3_free((void *)pCsr->filter.zTerm);
  154774. sqlite3_free(pCsr->aStat);
  154775. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  154776. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  154777. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  154778. if( iEq>=0 || iGe>=0 ){
  154779. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  154780. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  154781. if( zStr ){
  154782. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  154783. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  154784. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  154785. }
  154786. }
  154787. if( iLe>=0 ){
  154788. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  154789. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  154790. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  154791. }
  154792. if( iLangid>=0 ){
  154793. iLangVal = sqlite3_value_int(apVal[iLangid]);
  154794. /* If the user specified a negative value for the languageid, use zero
  154795. ** instead. This works, as the "languageid=?" constraint will also
  154796. ** be tested by the VDBE layer. The test will always be false (since
  154797. ** this module will not return a row with a negative languageid), and
  154798. ** so the overall query will return zero rows. */
  154799. if( iLangVal<0 ) iLangVal = 0;
  154800. }
  154801. pCsr->iLangid = iLangVal;
  154802. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  154803. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  154804. );
  154805. if( rc==SQLITE_OK ){
  154806. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  154807. }
  154808. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  154809. return rc;
  154810. }
  154811. /*
  154812. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  154813. */
  154814. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  154815. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  154816. return pCsr->isEof;
  154817. }
  154818. /*
  154819. ** xColumn - Return a column value.
  154820. */
  154821. static int fts3auxColumnMethod(
  154822. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  154823. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  154824. int iCol /* Index of column to read value from */
  154825. ){
  154826. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  154827. assert( p->isEof==0 );
  154828. switch( iCol ){
  154829. case 0: /* term */
  154830. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  154831. break;
  154832. case 1: /* col */
  154833. if( p->iCol ){
  154834. sqlite3_result_int(pCtx, p->iCol-1);
  154835. }else{
  154836. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  154837. }
  154838. break;
  154839. case 2: /* documents */
  154840. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  154841. break;
  154842. case 3: /* occurrences */
  154843. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  154844. break;
  154845. default: /* languageid */
  154846. assert( iCol==4 );
  154847. sqlite3_result_int(pCtx, p->iLangid);
  154848. break;
  154849. }
  154850. return SQLITE_OK;
  154851. }
  154852. /*
  154853. ** xRowid - Return the current rowid for the cursor.
  154854. */
  154855. static int fts3auxRowidMethod(
  154856. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  154857. sqlite_int64 *pRowid /* OUT: Rowid value */
  154858. ){
  154859. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  154860. *pRowid = pCsr->iRowid;
  154861. return SQLITE_OK;
  154862. }
  154863. /*
  154864. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  154865. ** if successful or an error code if sqlite3_create_module() fails.
  154866. */
  154867. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  154868. static const sqlite3_module fts3aux_module = {
  154869. 0, /* iVersion */
  154870. fts3auxConnectMethod, /* xCreate */
  154871. fts3auxConnectMethod, /* xConnect */
  154872. fts3auxBestIndexMethod, /* xBestIndex */
  154873. fts3auxDisconnectMethod, /* xDisconnect */
  154874. fts3auxDisconnectMethod, /* xDestroy */
  154875. fts3auxOpenMethod, /* xOpen */
  154876. fts3auxCloseMethod, /* xClose */
  154877. fts3auxFilterMethod, /* xFilter */
  154878. fts3auxNextMethod, /* xNext */
  154879. fts3auxEofMethod, /* xEof */
  154880. fts3auxColumnMethod, /* xColumn */
  154881. fts3auxRowidMethod, /* xRowid */
  154882. 0, /* xUpdate */
  154883. 0, /* xBegin */
  154884. 0, /* xSync */
  154885. 0, /* xCommit */
  154886. 0, /* xRollback */
  154887. 0, /* xFindFunction */
  154888. 0, /* xRename */
  154889. 0, /* xSavepoint */
  154890. 0, /* xRelease */
  154891. 0, /* xRollbackTo */
  154892. 0 /* xShadowName */
  154893. };
  154894. int rc; /* Return code */
  154895. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  154896. return rc;
  154897. }
  154898. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  154899. /************** End of fts3_aux.c ********************************************/
  154900. /************** Begin file fts3_expr.c ***************************************/
  154901. /*
  154902. ** 2008 Nov 28
  154903. **
  154904. ** The author disclaims copyright to this source code. In place of
  154905. ** a legal notice, here is a blessing:
  154906. **
  154907. ** May you do good and not evil.
  154908. ** May you find forgiveness for yourself and forgive others.
  154909. ** May you share freely, never taking more than you give.
  154910. **
  154911. ******************************************************************************
  154912. **
  154913. ** This module contains code that implements a parser for fts3 query strings
  154914. ** (the right-hand argument to the MATCH operator). Because the supported
  154915. ** syntax is relatively simple, the whole tokenizer/parser system is
  154916. ** hand-coded.
  154917. */
  154918. /* #include "fts3Int.h" */
  154919. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  154920. /*
  154921. ** By default, this module parses the legacy syntax that has been
  154922. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  154923. ** is defined, then it uses the new syntax. The differences between
  154924. ** the new and the old syntaxes are:
  154925. **
  154926. ** a) The new syntax supports parenthesis. The old does not.
  154927. **
  154928. ** b) The new syntax supports the AND and NOT operators. The old does not.
  154929. **
  154930. ** c) The old syntax supports the "-" token qualifier. This is not
  154931. ** supported by the new syntax (it is replaced by the NOT operator).
  154932. **
  154933. ** d) When using the old syntax, the OR operator has a greater precedence
  154934. ** than an implicit AND. When using the new, both implicity and explicit
  154935. ** AND operators have a higher precedence than OR.
  154936. **
  154937. ** If compiled with SQLITE_TEST defined, then this module exports the
  154938. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  154939. ** to zero causes the module to use the old syntax. If it is set to
  154940. ** non-zero the new syntax is activated. This is so both syntaxes can
  154941. ** be tested using a single build of testfixture.
  154942. **
  154943. ** The following describes the syntax supported by the fts3 MATCH
  154944. ** operator in a similar format to that used by the lemon parser
  154945. ** generator. This module does not use actually lemon, it uses a
  154946. ** custom parser.
  154947. **
  154948. ** query ::= andexpr (OR andexpr)*.
  154949. **
  154950. ** andexpr ::= notexpr (AND? notexpr)*.
  154951. **
  154952. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  154953. ** notexpr ::= LP query RP.
  154954. **
  154955. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  154956. **
  154957. ** distance_opt ::= .
  154958. ** distance_opt ::= / INTEGER.
  154959. **
  154960. ** phrase ::= TOKEN.
  154961. ** phrase ::= COLUMN:TOKEN.
  154962. ** phrase ::= "TOKEN TOKEN TOKEN...".
  154963. */
  154964. #ifdef SQLITE_TEST
  154965. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  154966. #else
  154967. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  154968. # define sqlite3_fts3_enable_parentheses 1
  154969. # else
  154970. # define sqlite3_fts3_enable_parentheses 0
  154971. # endif
  154972. #endif
  154973. /*
  154974. ** Default span for NEAR operators.
  154975. */
  154976. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  154977. /* #include <string.h> */
  154978. /* #include <assert.h> */
  154979. /*
  154980. ** isNot:
  154981. ** This variable is used by function getNextNode(). When getNextNode() is
  154982. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  154983. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  154984. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  154985. ** zero.
  154986. */
  154987. typedef struct ParseContext ParseContext;
  154988. struct ParseContext {
  154989. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  154990. int iLangid; /* Language id used with tokenizer */
  154991. const char **azCol; /* Array of column names for fts3 table */
  154992. int bFts4; /* True to allow FTS4-only syntax */
  154993. int nCol; /* Number of entries in azCol[] */
  154994. int iDefaultCol; /* Default column to query */
  154995. int isNot; /* True if getNextNode() sees a unary - */
  154996. sqlite3_context *pCtx; /* Write error message here */
  154997. int nNest; /* Number of nested brackets */
  154998. };
  154999. /*
  155000. ** This function is equivalent to the standard isspace() function.
  155001. **
  155002. ** The standard isspace() can be awkward to use safely, because although it
  155003. ** is defined to accept an argument of type int, its behavior when passed
  155004. ** an integer that falls outside of the range of the unsigned char type
  155005. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  155006. ** is defined to accept an argument of type char, and always returns 0 for
  155007. ** any values that fall outside of the range of the unsigned char type (i.e.
  155008. ** negative values).
  155009. */
  155010. static int fts3isspace(char c){
  155011. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  155012. }
  155013. /*
  155014. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  155015. ** zero the memory before returning a pointer to it. If unsuccessful,
  155016. ** return NULL.
  155017. */
  155018. static void *fts3MallocZero(int nByte){
  155019. void *pRet = sqlite3_malloc(nByte);
  155020. if( pRet ) memset(pRet, 0, nByte);
  155021. return pRet;
  155022. }
  155023. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  155024. sqlite3_tokenizer *pTokenizer,
  155025. int iLangid,
  155026. const char *z,
  155027. int n,
  155028. sqlite3_tokenizer_cursor **ppCsr
  155029. ){
  155030. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  155031. sqlite3_tokenizer_cursor *pCsr = 0;
  155032. int rc;
  155033. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  155034. assert( rc==SQLITE_OK || pCsr==0 );
  155035. if( rc==SQLITE_OK ){
  155036. pCsr->pTokenizer = pTokenizer;
  155037. if( pModule->iVersion>=1 ){
  155038. rc = pModule->xLanguageid(pCsr, iLangid);
  155039. if( rc!=SQLITE_OK ){
  155040. pModule->xClose(pCsr);
  155041. pCsr = 0;
  155042. }
  155043. }
  155044. }
  155045. *ppCsr = pCsr;
  155046. return rc;
  155047. }
  155048. /*
  155049. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  155050. ** call fts3ExprParse(). So this forward declaration is required.
  155051. */
  155052. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  155053. /*
  155054. ** Extract the next token from buffer z (length n) using the tokenizer
  155055. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  155056. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  155057. ** single token and set *ppExpr to point to it. If the end of the buffer is
  155058. ** reached before a token is found, set *ppExpr to zero. It is the
  155059. ** responsibility of the caller to eventually deallocate the allocated
  155060. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  155061. **
  155062. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  155063. ** fails.
  155064. */
  155065. static int getNextToken(
  155066. ParseContext *pParse, /* fts3 query parse context */
  155067. int iCol, /* Value for Fts3Phrase.iColumn */
  155068. const char *z, int n, /* Input string */
  155069. Fts3Expr **ppExpr, /* OUT: expression */
  155070. int *pnConsumed /* OUT: Number of bytes consumed */
  155071. ){
  155072. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  155073. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  155074. int rc;
  155075. sqlite3_tokenizer_cursor *pCursor;
  155076. Fts3Expr *pRet = 0;
  155077. int i = 0;
  155078. /* Set variable i to the maximum number of bytes of input to tokenize. */
  155079. for(i=0; i<n; i++){
  155080. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  155081. if( z[i]=='"' ) break;
  155082. }
  155083. *pnConsumed = i;
  155084. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  155085. if( rc==SQLITE_OK ){
  155086. const char *zToken;
  155087. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  155088. int nByte; /* total space to allocate */
  155089. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  155090. if( rc==SQLITE_OK ){
  155091. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  155092. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  155093. if( !pRet ){
  155094. rc = SQLITE_NOMEM;
  155095. }else{
  155096. pRet->eType = FTSQUERY_PHRASE;
  155097. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  155098. pRet->pPhrase->nToken = 1;
  155099. pRet->pPhrase->iColumn = iCol;
  155100. pRet->pPhrase->aToken[0].n = nToken;
  155101. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  155102. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  155103. if( iEnd<n && z[iEnd]=='*' ){
  155104. pRet->pPhrase->aToken[0].isPrefix = 1;
  155105. iEnd++;
  155106. }
  155107. while( 1 ){
  155108. if( !sqlite3_fts3_enable_parentheses
  155109. && iStart>0 && z[iStart-1]=='-'
  155110. ){
  155111. pParse->isNot = 1;
  155112. iStart--;
  155113. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  155114. pRet->pPhrase->aToken[0].bFirst = 1;
  155115. iStart--;
  155116. }else{
  155117. break;
  155118. }
  155119. }
  155120. }
  155121. *pnConsumed = iEnd;
  155122. }else if( i && rc==SQLITE_DONE ){
  155123. rc = SQLITE_OK;
  155124. }
  155125. pModule->xClose(pCursor);
  155126. }
  155127. *ppExpr = pRet;
  155128. return rc;
  155129. }
  155130. /*
  155131. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  155132. ** then free the old allocation.
  155133. */
  155134. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  155135. void *pRet = sqlite3_realloc(pOrig, nNew);
  155136. if( !pRet ){
  155137. sqlite3_free(pOrig);
  155138. }
  155139. return pRet;
  155140. }
  155141. /*
  155142. ** Buffer zInput, length nInput, contains the contents of a quoted string
  155143. ** that appeared as part of an fts3 query expression. Neither quote character
  155144. ** is included in the buffer. This function attempts to tokenize the entire
  155145. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  155146. ** containing the results.
  155147. **
  155148. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  155149. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  155150. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  155151. ** to 0.
  155152. */
  155153. static int getNextString(
  155154. ParseContext *pParse, /* fts3 query parse context */
  155155. const char *zInput, int nInput, /* Input string */
  155156. Fts3Expr **ppExpr /* OUT: expression */
  155157. ){
  155158. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  155159. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  155160. int rc;
  155161. Fts3Expr *p = 0;
  155162. sqlite3_tokenizer_cursor *pCursor = 0;
  155163. char *zTemp = 0;
  155164. int nTemp = 0;
  155165. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  155166. int nToken = 0;
  155167. /* The final Fts3Expr data structure, including the Fts3Phrase,
  155168. ** Fts3PhraseToken structures token buffers are all stored as a single
  155169. ** allocation so that the expression can be freed with a single call to
  155170. ** sqlite3_free(). Setting this up requires a two pass approach.
  155171. **
  155172. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  155173. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  155174. ** to assemble data in two dynamic buffers:
  155175. **
  155176. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  155177. ** structure, followed by the array of Fts3PhraseToken
  155178. ** structures. This pass only populates the Fts3PhraseToken array.
  155179. **
  155180. ** Buffer zTemp: Contains copies of all tokens.
  155181. **
  155182. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  155183. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  155184. ** structures.
  155185. */
  155186. rc = sqlite3Fts3OpenTokenizer(
  155187. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  155188. if( rc==SQLITE_OK ){
  155189. int ii;
  155190. for(ii=0; rc==SQLITE_OK; ii++){
  155191. const char *zByte;
  155192. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  155193. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  155194. if( rc==SQLITE_OK ){
  155195. Fts3PhraseToken *pToken;
  155196. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  155197. if( !p ) goto no_mem;
  155198. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  155199. if( !zTemp ) goto no_mem;
  155200. assert( nToken==ii );
  155201. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  155202. memset(pToken, 0, sizeof(Fts3PhraseToken));
  155203. memcpy(&zTemp[nTemp], zByte, nByte);
  155204. nTemp += nByte;
  155205. pToken->n = nByte;
  155206. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  155207. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  155208. nToken = ii+1;
  155209. }
  155210. }
  155211. pModule->xClose(pCursor);
  155212. pCursor = 0;
  155213. }
  155214. if( rc==SQLITE_DONE ){
  155215. int jj;
  155216. char *zBuf = 0;
  155217. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  155218. if( !p ) goto no_mem;
  155219. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  155220. p->eType = FTSQUERY_PHRASE;
  155221. p->pPhrase = (Fts3Phrase *)&p[1];
  155222. p->pPhrase->iColumn = pParse->iDefaultCol;
  155223. p->pPhrase->nToken = nToken;
  155224. zBuf = (char *)&p->pPhrase->aToken[nToken];
  155225. if( zTemp ){
  155226. memcpy(zBuf, zTemp, nTemp);
  155227. sqlite3_free(zTemp);
  155228. }else{
  155229. assert( nTemp==0 );
  155230. }
  155231. for(jj=0; jj<p->pPhrase->nToken; jj++){
  155232. p->pPhrase->aToken[jj].z = zBuf;
  155233. zBuf += p->pPhrase->aToken[jj].n;
  155234. }
  155235. rc = SQLITE_OK;
  155236. }
  155237. *ppExpr = p;
  155238. return rc;
  155239. no_mem:
  155240. if( pCursor ){
  155241. pModule->xClose(pCursor);
  155242. }
  155243. sqlite3_free(zTemp);
  155244. sqlite3_free(p);
  155245. *ppExpr = 0;
  155246. return SQLITE_NOMEM;
  155247. }
  155248. /*
  155249. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  155250. ** structure, or set to 0 if the end of the input buffer is reached.
  155251. **
  155252. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  155253. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  155254. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  155255. */
  155256. static int getNextNode(
  155257. ParseContext *pParse, /* fts3 query parse context */
  155258. const char *z, int n, /* Input string */
  155259. Fts3Expr **ppExpr, /* OUT: expression */
  155260. int *pnConsumed /* OUT: Number of bytes consumed */
  155261. ){
  155262. static const struct Fts3Keyword {
  155263. char *z; /* Keyword text */
  155264. unsigned char n; /* Length of the keyword */
  155265. unsigned char parenOnly; /* Only valid in paren mode */
  155266. unsigned char eType; /* Keyword code */
  155267. } aKeyword[] = {
  155268. { "OR" , 2, 0, FTSQUERY_OR },
  155269. { "AND", 3, 1, FTSQUERY_AND },
  155270. { "NOT", 3, 1, FTSQUERY_NOT },
  155271. { "NEAR", 4, 0, FTSQUERY_NEAR }
  155272. };
  155273. int ii;
  155274. int iCol;
  155275. int iColLen;
  155276. int rc;
  155277. Fts3Expr *pRet = 0;
  155278. const char *zInput = z;
  155279. int nInput = n;
  155280. pParse->isNot = 0;
  155281. /* Skip over any whitespace before checking for a keyword, an open or
  155282. ** close bracket, or a quoted string.
  155283. */
  155284. while( nInput>0 && fts3isspace(*zInput) ){
  155285. nInput--;
  155286. zInput++;
  155287. }
  155288. if( nInput==0 ){
  155289. return SQLITE_DONE;
  155290. }
  155291. /* See if we are dealing with a keyword. */
  155292. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  155293. const struct Fts3Keyword *pKey = &aKeyword[ii];
  155294. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  155295. continue;
  155296. }
  155297. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  155298. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  155299. int nKey = pKey->n;
  155300. char cNext;
  155301. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  155302. if( pKey->eType==FTSQUERY_NEAR ){
  155303. assert( nKey==4 );
  155304. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  155305. nNear = 0;
  155306. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  155307. nNear = nNear * 10 + (zInput[nKey] - '0');
  155308. }
  155309. }
  155310. }
  155311. /* At this point this is probably a keyword. But for that to be true,
  155312. ** the next byte must contain either whitespace, an open or close
  155313. ** parenthesis, a quote character, or EOF.
  155314. */
  155315. cNext = zInput[nKey];
  155316. if( fts3isspace(cNext)
  155317. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  155318. ){
  155319. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  155320. if( !pRet ){
  155321. return SQLITE_NOMEM;
  155322. }
  155323. pRet->eType = pKey->eType;
  155324. pRet->nNear = nNear;
  155325. *ppExpr = pRet;
  155326. *pnConsumed = (int)((zInput - z) + nKey);
  155327. return SQLITE_OK;
  155328. }
  155329. /* Turns out that wasn't a keyword after all. This happens if the
  155330. ** user has supplied a token such as "ORacle". Continue.
  155331. */
  155332. }
  155333. }
  155334. /* See if we are dealing with a quoted phrase. If this is the case, then
  155335. ** search for the closing quote and pass the whole string to getNextString()
  155336. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  155337. ** a quote character embedded in a string.
  155338. */
  155339. if( *zInput=='"' ){
  155340. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  155341. *pnConsumed = (int)((zInput - z) + ii + 1);
  155342. if( ii==nInput ){
  155343. return SQLITE_ERROR;
  155344. }
  155345. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  155346. }
  155347. if( sqlite3_fts3_enable_parentheses ){
  155348. if( *zInput=='(' ){
  155349. int nConsumed = 0;
  155350. pParse->nNest++;
  155351. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  155352. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  155353. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  155354. return rc;
  155355. }else if( *zInput==')' ){
  155356. pParse->nNest--;
  155357. *pnConsumed = (int)((zInput - z) + 1);
  155358. *ppExpr = 0;
  155359. return SQLITE_DONE;
  155360. }
  155361. }
  155362. /* If control flows to this point, this must be a regular token, or
  155363. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  155364. ** interface. Before doing so, figure out if there is an explicit
  155365. ** column specifier for the token.
  155366. **
  155367. ** TODO: Strangely, it is not possible to associate a column specifier
  155368. ** with a quoted phrase, only with a single token. Not sure if this was
  155369. ** an implementation artifact or an intentional decision when fts3 was
  155370. ** first implemented. Whichever it was, this module duplicates the
  155371. ** limitation.
  155372. */
  155373. iCol = pParse->iDefaultCol;
  155374. iColLen = 0;
  155375. for(ii=0; ii<pParse->nCol; ii++){
  155376. const char *zStr = pParse->azCol[ii];
  155377. int nStr = (int)strlen(zStr);
  155378. if( nInput>nStr && zInput[nStr]==':'
  155379. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  155380. ){
  155381. iCol = ii;
  155382. iColLen = (int)((zInput - z) + nStr + 1);
  155383. break;
  155384. }
  155385. }
  155386. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  155387. *pnConsumed += iColLen;
  155388. return rc;
  155389. }
  155390. /*
  155391. ** The argument is an Fts3Expr structure for a binary operator (any type
  155392. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  155393. ** precedence of the operator. Lower values have a higher precedence (i.e.
  155394. ** group more tightly). For example, in the C language, the == operator
  155395. ** groups more tightly than ||, and would therefore have a higher precedence.
  155396. **
  155397. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  155398. ** is defined), the order of the operators in precedence from highest to
  155399. ** lowest is:
  155400. **
  155401. ** NEAR
  155402. ** NOT
  155403. ** AND (including implicit ANDs)
  155404. ** OR
  155405. **
  155406. ** Note that when using the old query syntax, the OR operator has a higher
  155407. ** precedence than the AND operator.
  155408. */
  155409. static int opPrecedence(Fts3Expr *p){
  155410. assert( p->eType!=FTSQUERY_PHRASE );
  155411. if( sqlite3_fts3_enable_parentheses ){
  155412. return p->eType;
  155413. }else if( p->eType==FTSQUERY_NEAR ){
  155414. return 1;
  155415. }else if( p->eType==FTSQUERY_OR ){
  155416. return 2;
  155417. }
  155418. assert( p->eType==FTSQUERY_AND );
  155419. return 3;
  155420. }
  155421. /*
  155422. ** Argument ppHead contains a pointer to the current head of a query
  155423. ** expression tree being parsed. pPrev is the expression node most recently
  155424. ** inserted into the tree. This function adds pNew, which is always a binary
  155425. ** operator node, into the expression tree based on the relative precedence
  155426. ** of pNew and the existing nodes of the tree. This may result in the head
  155427. ** of the tree changing, in which case *ppHead is set to the new root node.
  155428. */
  155429. static void insertBinaryOperator(
  155430. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  155431. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  155432. Fts3Expr *pNew /* New binary node to insert into expression tree */
  155433. ){
  155434. Fts3Expr *pSplit = pPrev;
  155435. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  155436. pSplit = pSplit->pParent;
  155437. }
  155438. if( pSplit->pParent ){
  155439. assert( pSplit->pParent->pRight==pSplit );
  155440. pSplit->pParent->pRight = pNew;
  155441. pNew->pParent = pSplit->pParent;
  155442. }else{
  155443. *ppHead = pNew;
  155444. }
  155445. pNew->pLeft = pSplit;
  155446. pSplit->pParent = pNew;
  155447. }
  155448. /*
  155449. ** Parse the fts3 query expression found in buffer z, length n. This function
  155450. ** returns either when the end of the buffer is reached or an unmatched
  155451. ** closing bracket - ')' - is encountered.
  155452. **
  155453. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  155454. ** parsed form of the expression and *pnConsumed is set to the number of
  155455. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  155456. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  155457. */
  155458. static int fts3ExprParse(
  155459. ParseContext *pParse, /* fts3 query parse context */
  155460. const char *z, int n, /* Text of MATCH query */
  155461. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  155462. int *pnConsumed /* OUT: Number of bytes consumed */
  155463. ){
  155464. Fts3Expr *pRet = 0;
  155465. Fts3Expr *pPrev = 0;
  155466. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  155467. int nIn = n;
  155468. const char *zIn = z;
  155469. int rc = SQLITE_OK;
  155470. int isRequirePhrase = 1;
  155471. while( rc==SQLITE_OK ){
  155472. Fts3Expr *p = 0;
  155473. int nByte = 0;
  155474. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  155475. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  155476. if( rc==SQLITE_OK ){
  155477. if( p ){
  155478. int isPhrase;
  155479. if( !sqlite3_fts3_enable_parentheses
  155480. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  155481. ){
  155482. /* Create an implicit NOT operator. */
  155483. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  155484. if( !pNot ){
  155485. sqlite3Fts3ExprFree(p);
  155486. rc = SQLITE_NOMEM;
  155487. goto exprparse_out;
  155488. }
  155489. pNot->eType = FTSQUERY_NOT;
  155490. pNot->pRight = p;
  155491. p->pParent = pNot;
  155492. if( pNotBranch ){
  155493. pNot->pLeft = pNotBranch;
  155494. pNotBranch->pParent = pNot;
  155495. }
  155496. pNotBranch = pNot;
  155497. p = pPrev;
  155498. }else{
  155499. int eType = p->eType;
  155500. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  155501. /* The isRequirePhrase variable is set to true if a phrase or
  155502. ** an expression contained in parenthesis is required. If a
  155503. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  155504. ** isRequirePhrase is set, this is a syntax error.
  155505. */
  155506. if( !isPhrase && isRequirePhrase ){
  155507. sqlite3Fts3ExprFree(p);
  155508. rc = SQLITE_ERROR;
  155509. goto exprparse_out;
  155510. }
  155511. if( isPhrase && !isRequirePhrase ){
  155512. /* Insert an implicit AND operator. */
  155513. Fts3Expr *pAnd;
  155514. assert( pRet && pPrev );
  155515. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  155516. if( !pAnd ){
  155517. sqlite3Fts3ExprFree(p);
  155518. rc = SQLITE_NOMEM;
  155519. goto exprparse_out;
  155520. }
  155521. pAnd->eType = FTSQUERY_AND;
  155522. insertBinaryOperator(&pRet, pPrev, pAnd);
  155523. pPrev = pAnd;
  155524. }
  155525. /* This test catches attempts to make either operand of a NEAR
  155526. ** operator something other than a phrase. For example, either of
  155527. ** the following:
  155528. **
  155529. ** (bracketed expression) NEAR phrase
  155530. ** phrase NEAR (bracketed expression)
  155531. **
  155532. ** Return an error in either case.
  155533. */
  155534. if( pPrev && (
  155535. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  155536. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  155537. )){
  155538. sqlite3Fts3ExprFree(p);
  155539. rc = SQLITE_ERROR;
  155540. goto exprparse_out;
  155541. }
  155542. if( isPhrase ){
  155543. if( pRet ){
  155544. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  155545. pPrev->pRight = p;
  155546. p->pParent = pPrev;
  155547. }else{
  155548. pRet = p;
  155549. }
  155550. }else{
  155551. insertBinaryOperator(&pRet, pPrev, p);
  155552. }
  155553. isRequirePhrase = !isPhrase;
  155554. }
  155555. pPrev = p;
  155556. }
  155557. assert( nByte>0 );
  155558. }
  155559. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  155560. nIn -= nByte;
  155561. zIn += nByte;
  155562. }
  155563. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  155564. rc = SQLITE_ERROR;
  155565. }
  155566. if( rc==SQLITE_DONE ){
  155567. rc = SQLITE_OK;
  155568. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  155569. if( !pRet ){
  155570. rc = SQLITE_ERROR;
  155571. }else{
  155572. Fts3Expr *pIter = pNotBranch;
  155573. while( pIter->pLeft ){
  155574. pIter = pIter->pLeft;
  155575. }
  155576. pIter->pLeft = pRet;
  155577. pRet->pParent = pIter;
  155578. pRet = pNotBranch;
  155579. }
  155580. }
  155581. }
  155582. *pnConsumed = n - nIn;
  155583. exprparse_out:
  155584. if( rc!=SQLITE_OK ){
  155585. sqlite3Fts3ExprFree(pRet);
  155586. sqlite3Fts3ExprFree(pNotBranch);
  155587. pRet = 0;
  155588. }
  155589. *ppExpr = pRet;
  155590. return rc;
  155591. }
  155592. /*
  155593. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  155594. ** as the only argument is more than nMaxDepth.
  155595. */
  155596. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  155597. int rc = SQLITE_OK;
  155598. if( p ){
  155599. if( nMaxDepth<0 ){
  155600. rc = SQLITE_TOOBIG;
  155601. }else{
  155602. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  155603. if( rc==SQLITE_OK ){
  155604. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  155605. }
  155606. }
  155607. }
  155608. return rc;
  155609. }
  155610. /*
  155611. ** This function attempts to transform the expression tree at (*pp) to
  155612. ** an equivalent but more balanced form. The tree is modified in place.
  155613. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  155614. ** new root expression node.
  155615. **
  155616. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  155617. **
  155618. ** Otherwise, if an error occurs, an SQLite error code is returned and
  155619. ** expression (*pp) freed.
  155620. */
  155621. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  155622. int rc = SQLITE_OK; /* Return code */
  155623. Fts3Expr *pRoot = *pp; /* Initial root node */
  155624. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  155625. int eType = pRoot->eType; /* Type of node in this tree */
  155626. if( nMaxDepth==0 ){
  155627. rc = SQLITE_ERROR;
  155628. }
  155629. if( rc==SQLITE_OK ){
  155630. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  155631. Fts3Expr **apLeaf;
  155632. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  155633. if( 0==apLeaf ){
  155634. rc = SQLITE_NOMEM;
  155635. }else{
  155636. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  155637. }
  155638. if( rc==SQLITE_OK ){
  155639. int i;
  155640. Fts3Expr *p;
  155641. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  155642. for(p=pRoot; p->eType==eType; p=p->pLeft){
  155643. assert( p->pParent==0 || p->pParent->pLeft==p );
  155644. assert( p->pLeft && p->pRight );
  155645. }
  155646. /* This loop runs once for each leaf in the tree of eType nodes. */
  155647. while( 1 ){
  155648. int iLvl;
  155649. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  155650. assert( pParent==0 || pParent->pLeft==p );
  155651. p->pParent = 0;
  155652. if( pParent ){
  155653. pParent->pLeft = 0;
  155654. }else{
  155655. pRoot = 0;
  155656. }
  155657. rc = fts3ExprBalance(&p, nMaxDepth-1);
  155658. if( rc!=SQLITE_OK ) break;
  155659. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  155660. if( apLeaf[iLvl]==0 ){
  155661. apLeaf[iLvl] = p;
  155662. p = 0;
  155663. }else{
  155664. assert( pFree );
  155665. pFree->pLeft = apLeaf[iLvl];
  155666. pFree->pRight = p;
  155667. pFree->pLeft->pParent = pFree;
  155668. pFree->pRight->pParent = pFree;
  155669. p = pFree;
  155670. pFree = pFree->pParent;
  155671. p->pParent = 0;
  155672. apLeaf[iLvl] = 0;
  155673. }
  155674. }
  155675. if( p ){
  155676. sqlite3Fts3ExprFree(p);
  155677. rc = SQLITE_TOOBIG;
  155678. break;
  155679. }
  155680. /* If that was the last leaf node, break out of the loop */
  155681. if( pParent==0 ) break;
  155682. /* Set $p to point to the next leaf in the tree of eType nodes */
  155683. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  155684. /* Remove pParent from the original tree. */
  155685. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  155686. pParent->pRight->pParent = pParent->pParent;
  155687. if( pParent->pParent ){
  155688. pParent->pParent->pLeft = pParent->pRight;
  155689. }else{
  155690. assert( pParent==pRoot );
  155691. pRoot = pParent->pRight;
  155692. }
  155693. /* Link pParent into the free node list. It will be used as an
  155694. ** internal node of the new tree. */
  155695. pParent->pParent = pFree;
  155696. pFree = pParent;
  155697. }
  155698. if( rc==SQLITE_OK ){
  155699. p = 0;
  155700. for(i=0; i<nMaxDepth; i++){
  155701. if( apLeaf[i] ){
  155702. if( p==0 ){
  155703. p = apLeaf[i];
  155704. p->pParent = 0;
  155705. }else{
  155706. assert( pFree!=0 );
  155707. pFree->pRight = p;
  155708. pFree->pLeft = apLeaf[i];
  155709. pFree->pLeft->pParent = pFree;
  155710. pFree->pRight->pParent = pFree;
  155711. p = pFree;
  155712. pFree = pFree->pParent;
  155713. p->pParent = 0;
  155714. }
  155715. }
  155716. }
  155717. pRoot = p;
  155718. }else{
  155719. /* An error occurred. Delete the contents of the apLeaf[] array
  155720. ** and pFree list. Everything else is cleaned up by the call to
  155721. ** sqlite3Fts3ExprFree(pRoot) below. */
  155722. Fts3Expr *pDel;
  155723. for(i=0; i<nMaxDepth; i++){
  155724. sqlite3Fts3ExprFree(apLeaf[i]);
  155725. }
  155726. while( (pDel=pFree)!=0 ){
  155727. pFree = pDel->pParent;
  155728. sqlite3_free(pDel);
  155729. }
  155730. }
  155731. assert( pFree==0 );
  155732. sqlite3_free( apLeaf );
  155733. }
  155734. }else if( eType==FTSQUERY_NOT ){
  155735. Fts3Expr *pLeft = pRoot->pLeft;
  155736. Fts3Expr *pRight = pRoot->pRight;
  155737. pRoot->pLeft = 0;
  155738. pRoot->pRight = 0;
  155739. pLeft->pParent = 0;
  155740. pRight->pParent = 0;
  155741. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  155742. if( rc==SQLITE_OK ){
  155743. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  155744. }
  155745. if( rc!=SQLITE_OK ){
  155746. sqlite3Fts3ExprFree(pRight);
  155747. sqlite3Fts3ExprFree(pLeft);
  155748. }else{
  155749. assert( pLeft && pRight );
  155750. pRoot->pLeft = pLeft;
  155751. pLeft->pParent = pRoot;
  155752. pRoot->pRight = pRight;
  155753. pRight->pParent = pRoot;
  155754. }
  155755. }
  155756. }
  155757. if( rc!=SQLITE_OK ){
  155758. sqlite3Fts3ExprFree(pRoot);
  155759. pRoot = 0;
  155760. }
  155761. *pp = pRoot;
  155762. return rc;
  155763. }
  155764. /*
  155765. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  155766. ** differences:
  155767. **
  155768. ** 1. It does not do expression rebalancing.
  155769. ** 2. It does not check that the expression does not exceed the
  155770. ** maximum allowable depth.
  155771. ** 3. Even if it fails, *ppExpr may still be set to point to an
  155772. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  155773. ** in this case.
  155774. */
  155775. static int fts3ExprParseUnbalanced(
  155776. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  155777. int iLangid, /* Language id for tokenizer */
  155778. char **azCol, /* Array of column names for fts3 table */
  155779. int bFts4, /* True to allow FTS4-only syntax */
  155780. int nCol, /* Number of entries in azCol[] */
  155781. int iDefaultCol, /* Default column to query */
  155782. const char *z, int n, /* Text of MATCH query */
  155783. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  155784. ){
  155785. int nParsed;
  155786. int rc;
  155787. ParseContext sParse;
  155788. memset(&sParse, 0, sizeof(ParseContext));
  155789. sParse.pTokenizer = pTokenizer;
  155790. sParse.iLangid = iLangid;
  155791. sParse.azCol = (const char **)azCol;
  155792. sParse.nCol = nCol;
  155793. sParse.iDefaultCol = iDefaultCol;
  155794. sParse.bFts4 = bFts4;
  155795. if( z==0 ){
  155796. *ppExpr = 0;
  155797. return SQLITE_OK;
  155798. }
  155799. if( n<0 ){
  155800. n = (int)strlen(z);
  155801. }
  155802. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  155803. assert( rc==SQLITE_OK || *ppExpr==0 );
  155804. /* Check for mismatched parenthesis */
  155805. if( rc==SQLITE_OK && sParse.nNest ){
  155806. rc = SQLITE_ERROR;
  155807. }
  155808. return rc;
  155809. }
  155810. /*
  155811. ** Parameters z and n contain a pointer to and length of a buffer containing
  155812. ** an fts3 query expression, respectively. This function attempts to parse the
  155813. ** query expression and create a tree of Fts3Expr structures representing the
  155814. ** parsed expression. If successful, *ppExpr is set to point to the head
  155815. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  155816. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  155817. ** error) is returned and *ppExpr is set to 0.
  155818. **
  155819. ** If parameter n is a negative number, then z is assumed to point to a
  155820. ** nul-terminated string and the length is determined using strlen().
  155821. **
  155822. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  155823. ** use to normalize query tokens while parsing the expression. The azCol[]
  155824. ** array, which is assumed to contain nCol entries, should contain the names
  155825. ** of each column in the target fts3 table, in order from left to right.
  155826. ** Column names must be nul-terminated strings.
  155827. **
  155828. ** The iDefaultCol parameter should be passed the index of the table column
  155829. ** that appears on the left-hand-side of the MATCH operator (the default
  155830. ** column to match against for tokens for which a column name is not explicitly
  155831. ** specified as part of the query string), or -1 if tokens may by default
  155832. ** match any table column.
  155833. */
  155834. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  155835. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  155836. int iLangid, /* Language id for tokenizer */
  155837. char **azCol, /* Array of column names for fts3 table */
  155838. int bFts4, /* True to allow FTS4-only syntax */
  155839. int nCol, /* Number of entries in azCol[] */
  155840. int iDefaultCol, /* Default column to query */
  155841. const char *z, int n, /* Text of MATCH query */
  155842. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  155843. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  155844. ){
  155845. int rc = fts3ExprParseUnbalanced(
  155846. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  155847. );
  155848. /* Rebalance the expression. And check that its depth does not exceed
  155849. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  155850. if( rc==SQLITE_OK && *ppExpr ){
  155851. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  155852. if( rc==SQLITE_OK ){
  155853. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  155854. }
  155855. }
  155856. if( rc!=SQLITE_OK ){
  155857. sqlite3Fts3ExprFree(*ppExpr);
  155858. *ppExpr = 0;
  155859. if( rc==SQLITE_TOOBIG ){
  155860. sqlite3Fts3ErrMsg(pzErr,
  155861. "FTS expression tree is too large (maximum depth %d)",
  155862. SQLITE_FTS3_MAX_EXPR_DEPTH
  155863. );
  155864. rc = SQLITE_ERROR;
  155865. }else if( rc==SQLITE_ERROR ){
  155866. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  155867. }
  155868. }
  155869. return rc;
  155870. }
  155871. /*
  155872. ** Free a single node of an expression tree.
  155873. */
  155874. static void fts3FreeExprNode(Fts3Expr *p){
  155875. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  155876. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  155877. sqlite3_free(p->aMI);
  155878. sqlite3_free(p);
  155879. }
  155880. /*
  155881. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  155882. **
  155883. ** This function would be simpler if it recursively called itself. But
  155884. ** that would mean passing a sufficiently large expression to ExprParse()
  155885. ** could cause a stack overflow.
  155886. */
  155887. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  155888. Fts3Expr *p;
  155889. assert( pDel==0 || pDel->pParent==0 );
  155890. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  155891. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  155892. }
  155893. while( p ){
  155894. Fts3Expr *pParent = p->pParent;
  155895. fts3FreeExprNode(p);
  155896. if( pParent && p==pParent->pLeft && pParent->pRight ){
  155897. p = pParent->pRight;
  155898. while( p && (p->pLeft || p->pRight) ){
  155899. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  155900. p = (p->pLeft ? p->pLeft : p->pRight);
  155901. }
  155902. }else{
  155903. p = pParent;
  155904. }
  155905. }
  155906. }
  155907. /****************************************************************************
  155908. *****************************************************************************
  155909. ** Everything after this point is just test code.
  155910. */
  155911. #ifdef SQLITE_TEST
  155912. /* #include <stdio.h> */
  155913. /*
  155914. ** Return a pointer to a buffer containing a text representation of the
  155915. ** expression passed as the first argument. The buffer is obtained from
  155916. ** sqlite3_malloc(). It is the responsibility of the caller to use
  155917. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  155918. ** NULL is returned.
  155919. **
  155920. ** If the second argument is not NULL, then its contents are prepended to
  155921. ** the returned expression text and then freed using sqlite3_free().
  155922. */
  155923. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  155924. if( pExpr==0 ){
  155925. return sqlite3_mprintf("");
  155926. }
  155927. switch( pExpr->eType ){
  155928. case FTSQUERY_PHRASE: {
  155929. Fts3Phrase *pPhrase = pExpr->pPhrase;
  155930. int i;
  155931. zBuf = sqlite3_mprintf(
  155932. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  155933. for(i=0; zBuf && i<pPhrase->nToken; i++){
  155934. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  155935. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  155936. (pPhrase->aToken[i].isPrefix?"+":"")
  155937. );
  155938. }
  155939. return zBuf;
  155940. }
  155941. case FTSQUERY_NEAR:
  155942. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  155943. break;
  155944. case FTSQUERY_NOT:
  155945. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  155946. break;
  155947. case FTSQUERY_AND:
  155948. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  155949. break;
  155950. case FTSQUERY_OR:
  155951. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  155952. break;
  155953. }
  155954. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  155955. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  155956. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  155957. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  155958. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  155959. return zBuf;
  155960. }
  155961. /*
  155962. ** This is the implementation of a scalar SQL function used to test the
  155963. ** expression parser. It should be called as follows:
  155964. **
  155965. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  155966. **
  155967. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  155968. ** to parse the query expression (see README.tokenizers). The second argument
  155969. ** is the query expression to parse. Each subsequent argument is the name
  155970. ** of a column of the fts3 table that the query expression may refer to.
  155971. ** For example:
  155972. **
  155973. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  155974. */
  155975. static void fts3ExprTestCommon(
  155976. int bRebalance,
  155977. sqlite3_context *context,
  155978. int argc,
  155979. sqlite3_value **argv
  155980. ){
  155981. sqlite3_tokenizer *pTokenizer = 0;
  155982. int rc;
  155983. char **azCol = 0;
  155984. const char *zExpr;
  155985. int nExpr;
  155986. int nCol;
  155987. int ii;
  155988. Fts3Expr *pExpr;
  155989. char *zBuf = 0;
  155990. Fts3Hash *pHash = (Fts3Hash*)sqlite3_user_data(context);
  155991. const char *zTokenizer = 0;
  155992. char *zErr = 0;
  155993. if( argc<3 ){
  155994. sqlite3_result_error(context,
  155995. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  155996. );
  155997. return;
  155998. }
  155999. zTokenizer = (const char*)sqlite3_value_text(argv[0]);
  156000. rc = sqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr);
  156001. if( rc!=SQLITE_OK ){
  156002. if( rc==SQLITE_NOMEM ){
  156003. sqlite3_result_error_nomem(context);
  156004. }else{
  156005. sqlite3_result_error(context, zErr, -1);
  156006. }
  156007. sqlite3_free(zErr);
  156008. return;
  156009. }
  156010. zExpr = (const char *)sqlite3_value_text(argv[1]);
  156011. nExpr = sqlite3_value_bytes(argv[1]);
  156012. nCol = argc-2;
  156013. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  156014. if( !azCol ){
  156015. sqlite3_result_error_nomem(context);
  156016. goto exprtest_out;
  156017. }
  156018. for(ii=0; ii<nCol; ii++){
  156019. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  156020. }
  156021. if( bRebalance ){
  156022. char *zDummy = 0;
  156023. rc = sqlite3Fts3ExprParse(
  156024. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  156025. );
  156026. assert( rc==SQLITE_OK || pExpr==0 );
  156027. sqlite3_free(zDummy);
  156028. }else{
  156029. rc = fts3ExprParseUnbalanced(
  156030. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  156031. );
  156032. }
  156033. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  156034. sqlite3Fts3ExprFree(pExpr);
  156035. sqlite3_result_error(context, "Error parsing expression", -1);
  156036. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  156037. sqlite3_result_error_nomem(context);
  156038. }else{
  156039. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  156040. sqlite3_free(zBuf);
  156041. }
  156042. sqlite3Fts3ExprFree(pExpr);
  156043. exprtest_out:
  156044. if( pTokenizer ){
  156045. rc = pTokenizer->pModule->xDestroy(pTokenizer);
  156046. }
  156047. sqlite3_free(azCol);
  156048. }
  156049. static void fts3ExprTest(
  156050. sqlite3_context *context,
  156051. int argc,
  156052. sqlite3_value **argv
  156053. ){
  156054. fts3ExprTestCommon(0, context, argc, argv);
  156055. }
  156056. static void fts3ExprTestRebalance(
  156057. sqlite3_context *context,
  156058. int argc,
  156059. sqlite3_value **argv
  156060. ){
  156061. fts3ExprTestCommon(1, context, argc, argv);
  156062. }
  156063. /*
  156064. ** Register the query expression parser test function fts3_exprtest()
  156065. ** with database connection db.
  156066. */
  156067. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
  156068. int rc = sqlite3_create_function(
  156069. db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
  156070. );
  156071. if( rc==SQLITE_OK ){
  156072. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  156073. -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
  156074. );
  156075. }
  156076. return rc;
  156077. }
  156078. #endif
  156079. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  156080. /************** End of fts3_expr.c *******************************************/
  156081. /************** Begin file fts3_hash.c ***************************************/
  156082. /*
  156083. ** 2001 September 22
  156084. **
  156085. ** The author disclaims copyright to this source code. In place of
  156086. ** a legal notice, here is a blessing:
  156087. **
  156088. ** May you do good and not evil.
  156089. ** May you find forgiveness for yourself and forgive others.
  156090. ** May you share freely, never taking more than you give.
  156091. **
  156092. *************************************************************************
  156093. ** This is the implementation of generic hash-tables used in SQLite.
  156094. ** We've modified it slightly to serve as a standalone hash table
  156095. ** implementation for the full-text indexing module.
  156096. */
  156097. /*
  156098. ** The code in this file is only compiled if:
  156099. **
  156100. ** * The FTS3 module is being built as an extension
  156101. ** (in which case SQLITE_CORE is not defined), or
  156102. **
  156103. ** * The FTS3 module is being built into the core of
  156104. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  156105. */
  156106. /* #include "fts3Int.h" */
  156107. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  156108. /* #include <assert.h> */
  156109. /* #include <stdlib.h> */
  156110. /* #include <string.h> */
  156111. /* #include "fts3_hash.h" */
  156112. /*
  156113. ** Malloc and Free functions
  156114. */
  156115. static void *fts3HashMalloc(int n){
  156116. void *p = sqlite3_malloc(n);
  156117. if( p ){
  156118. memset(p, 0, n);
  156119. }
  156120. return p;
  156121. }
  156122. static void fts3HashFree(void *p){
  156123. sqlite3_free(p);
  156124. }
  156125. /* Turn bulk memory into a hash table object by initializing the
  156126. ** fields of the Hash structure.
  156127. **
  156128. ** "pNew" is a pointer to the hash table that is to be initialized.
  156129. ** keyClass is one of the constants
  156130. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  156131. ** determines what kind of key the hash table will use. "copyKey" is
  156132. ** true if the hash table should make its own private copy of keys and
  156133. ** false if it should just use the supplied pointer.
  156134. */
  156135. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  156136. assert( pNew!=0 );
  156137. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  156138. pNew->keyClass = keyClass;
  156139. pNew->copyKey = copyKey;
  156140. pNew->first = 0;
  156141. pNew->count = 0;
  156142. pNew->htsize = 0;
  156143. pNew->ht = 0;
  156144. }
  156145. /* Remove all entries from a hash table. Reclaim all memory.
  156146. ** Call this routine to delete a hash table or to reset a hash table
  156147. ** to the empty state.
  156148. */
  156149. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  156150. Fts3HashElem *elem; /* For looping over all elements of the table */
  156151. assert( pH!=0 );
  156152. elem = pH->first;
  156153. pH->first = 0;
  156154. fts3HashFree(pH->ht);
  156155. pH->ht = 0;
  156156. pH->htsize = 0;
  156157. while( elem ){
  156158. Fts3HashElem *next_elem = elem->next;
  156159. if( pH->copyKey && elem->pKey ){
  156160. fts3HashFree(elem->pKey);
  156161. }
  156162. fts3HashFree(elem);
  156163. elem = next_elem;
  156164. }
  156165. pH->count = 0;
  156166. }
  156167. /*
  156168. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  156169. */
  156170. static int fts3StrHash(const void *pKey, int nKey){
  156171. const char *z = (const char *)pKey;
  156172. unsigned h = 0;
  156173. if( nKey<=0 ) nKey = (int) strlen(z);
  156174. while( nKey > 0 ){
  156175. h = (h<<3) ^ h ^ *z++;
  156176. nKey--;
  156177. }
  156178. return (int)(h & 0x7fffffff);
  156179. }
  156180. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  156181. if( n1!=n2 ) return 1;
  156182. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  156183. }
  156184. /*
  156185. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  156186. */
  156187. static int fts3BinHash(const void *pKey, int nKey){
  156188. int h = 0;
  156189. const char *z = (const char *)pKey;
  156190. while( nKey-- > 0 ){
  156191. h = (h<<3) ^ h ^ *(z++);
  156192. }
  156193. return h & 0x7fffffff;
  156194. }
  156195. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  156196. if( n1!=n2 ) return 1;
  156197. return memcmp(pKey1,pKey2,n1);
  156198. }
  156199. /*
  156200. ** Return a pointer to the appropriate hash function given the key class.
  156201. **
  156202. ** The C syntax in this function definition may be unfamilar to some
  156203. ** programmers, so we provide the following additional explanation:
  156204. **
  156205. ** The name of the function is "ftsHashFunction". The function takes a
  156206. ** single parameter "keyClass". The return value of ftsHashFunction()
  156207. ** is a pointer to another function. Specifically, the return value
  156208. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  156209. ** with types "const void*" and "int" and returns an "int".
  156210. */
  156211. static int (*ftsHashFunction(int keyClass))(const void*,int){
  156212. if( keyClass==FTS3_HASH_STRING ){
  156213. return &fts3StrHash;
  156214. }else{
  156215. assert( keyClass==FTS3_HASH_BINARY );
  156216. return &fts3BinHash;
  156217. }
  156218. }
  156219. /*
  156220. ** Return a pointer to the appropriate hash function given the key class.
  156221. **
  156222. ** For help in interpreted the obscure C code in the function definition,
  156223. ** see the header comment on the previous function.
  156224. */
  156225. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  156226. if( keyClass==FTS3_HASH_STRING ){
  156227. return &fts3StrCompare;
  156228. }else{
  156229. assert( keyClass==FTS3_HASH_BINARY );
  156230. return &fts3BinCompare;
  156231. }
  156232. }
  156233. /* Link an element into the hash table
  156234. */
  156235. static void fts3HashInsertElement(
  156236. Fts3Hash *pH, /* The complete hash table */
  156237. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  156238. Fts3HashElem *pNew /* The element to be inserted */
  156239. ){
  156240. Fts3HashElem *pHead; /* First element already in pEntry */
  156241. pHead = pEntry->chain;
  156242. if( pHead ){
  156243. pNew->next = pHead;
  156244. pNew->prev = pHead->prev;
  156245. if( pHead->prev ){ pHead->prev->next = pNew; }
  156246. else { pH->first = pNew; }
  156247. pHead->prev = pNew;
  156248. }else{
  156249. pNew->next = pH->first;
  156250. if( pH->first ){ pH->first->prev = pNew; }
  156251. pNew->prev = 0;
  156252. pH->first = pNew;
  156253. }
  156254. pEntry->count++;
  156255. pEntry->chain = pNew;
  156256. }
  156257. /* Resize the hash table so that it cantains "new_size" buckets.
  156258. ** "new_size" must be a power of 2. The hash table might fail
  156259. ** to resize if sqliteMalloc() fails.
  156260. **
  156261. ** Return non-zero if a memory allocation error occurs.
  156262. */
  156263. static int fts3Rehash(Fts3Hash *pH, int new_size){
  156264. struct _fts3ht *new_ht; /* The new hash table */
  156265. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  156266. int (*xHash)(const void*,int); /* The hash function */
  156267. assert( (new_size & (new_size-1))==0 );
  156268. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  156269. if( new_ht==0 ) return 1;
  156270. fts3HashFree(pH->ht);
  156271. pH->ht = new_ht;
  156272. pH->htsize = new_size;
  156273. xHash = ftsHashFunction(pH->keyClass);
  156274. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  156275. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  156276. next_elem = elem->next;
  156277. fts3HashInsertElement(pH, &new_ht[h], elem);
  156278. }
  156279. return 0;
  156280. }
  156281. /* This function (for internal use only) locates an element in an
  156282. ** hash table that matches the given key. The hash for this key has
  156283. ** already been computed and is passed as the 4th parameter.
  156284. */
  156285. static Fts3HashElem *fts3FindElementByHash(
  156286. const Fts3Hash *pH, /* The pH to be searched */
  156287. const void *pKey, /* The key we are searching for */
  156288. int nKey,
  156289. int h /* The hash for this key. */
  156290. ){
  156291. Fts3HashElem *elem; /* Used to loop thru the element list */
  156292. int count; /* Number of elements left to test */
  156293. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  156294. if( pH->ht ){
  156295. struct _fts3ht *pEntry = &pH->ht[h];
  156296. elem = pEntry->chain;
  156297. count = pEntry->count;
  156298. xCompare = ftsCompareFunction(pH->keyClass);
  156299. while( count-- && elem ){
  156300. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  156301. return elem;
  156302. }
  156303. elem = elem->next;
  156304. }
  156305. }
  156306. return 0;
  156307. }
  156308. /* Remove a single entry from the hash table given a pointer to that
  156309. ** element and a hash on the element's key.
  156310. */
  156311. static void fts3RemoveElementByHash(
  156312. Fts3Hash *pH, /* The pH containing "elem" */
  156313. Fts3HashElem* elem, /* The element to be removed from the pH */
  156314. int h /* Hash value for the element */
  156315. ){
  156316. struct _fts3ht *pEntry;
  156317. if( elem->prev ){
  156318. elem->prev->next = elem->next;
  156319. }else{
  156320. pH->first = elem->next;
  156321. }
  156322. if( elem->next ){
  156323. elem->next->prev = elem->prev;
  156324. }
  156325. pEntry = &pH->ht[h];
  156326. if( pEntry->chain==elem ){
  156327. pEntry->chain = elem->next;
  156328. }
  156329. pEntry->count--;
  156330. if( pEntry->count<=0 ){
  156331. pEntry->chain = 0;
  156332. }
  156333. if( pH->copyKey && elem->pKey ){
  156334. fts3HashFree(elem->pKey);
  156335. }
  156336. fts3HashFree( elem );
  156337. pH->count--;
  156338. if( pH->count<=0 ){
  156339. assert( pH->first==0 );
  156340. assert( pH->count==0 );
  156341. fts3HashClear(pH);
  156342. }
  156343. }
  156344. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  156345. const Fts3Hash *pH,
  156346. const void *pKey,
  156347. int nKey
  156348. ){
  156349. int h; /* A hash on key */
  156350. int (*xHash)(const void*,int); /* The hash function */
  156351. if( pH==0 || pH->ht==0 ) return 0;
  156352. xHash = ftsHashFunction(pH->keyClass);
  156353. assert( xHash!=0 );
  156354. h = (*xHash)(pKey,nKey);
  156355. assert( (pH->htsize & (pH->htsize-1))==0 );
  156356. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  156357. }
  156358. /*
  156359. ** Attempt to locate an element of the hash table pH with a key
  156360. ** that matches pKey,nKey. Return the data for this element if it is
  156361. ** found, or NULL if there is no match.
  156362. */
  156363. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  156364. Fts3HashElem *pElem; /* The element that matches key (if any) */
  156365. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  156366. return pElem ? pElem->data : 0;
  156367. }
  156368. /* Insert an element into the hash table pH. The key is pKey,nKey
  156369. ** and the data is "data".
  156370. **
  156371. ** If no element exists with a matching key, then a new
  156372. ** element is created. A copy of the key is made if the copyKey
  156373. ** flag is set. NULL is returned.
  156374. **
  156375. ** If another element already exists with the same key, then the
  156376. ** new data replaces the old data and the old data is returned.
  156377. ** The key is not copied in this instance. If a malloc fails, then
  156378. ** the new data is returned and the hash table is unchanged.
  156379. **
  156380. ** If the "data" parameter to this function is NULL, then the
  156381. ** element corresponding to "key" is removed from the hash table.
  156382. */
  156383. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  156384. Fts3Hash *pH, /* The hash table to insert into */
  156385. const void *pKey, /* The key */
  156386. int nKey, /* Number of bytes in the key */
  156387. void *data /* The data */
  156388. ){
  156389. int hraw; /* Raw hash value of the key */
  156390. int h; /* the hash of the key modulo hash table size */
  156391. Fts3HashElem *elem; /* Used to loop thru the element list */
  156392. Fts3HashElem *new_elem; /* New element added to the pH */
  156393. int (*xHash)(const void*,int); /* The hash function */
  156394. assert( pH!=0 );
  156395. xHash = ftsHashFunction(pH->keyClass);
  156396. assert( xHash!=0 );
  156397. hraw = (*xHash)(pKey, nKey);
  156398. assert( (pH->htsize & (pH->htsize-1))==0 );
  156399. h = hraw & (pH->htsize-1);
  156400. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  156401. if( elem ){
  156402. void *old_data = elem->data;
  156403. if( data==0 ){
  156404. fts3RemoveElementByHash(pH,elem,h);
  156405. }else{
  156406. elem->data = data;
  156407. }
  156408. return old_data;
  156409. }
  156410. if( data==0 ) return 0;
  156411. if( (pH->htsize==0 && fts3Rehash(pH,8))
  156412. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  156413. ){
  156414. pH->count = 0;
  156415. return data;
  156416. }
  156417. assert( pH->htsize>0 );
  156418. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  156419. if( new_elem==0 ) return data;
  156420. if( pH->copyKey && pKey!=0 ){
  156421. new_elem->pKey = fts3HashMalloc( nKey );
  156422. if( new_elem->pKey==0 ){
  156423. fts3HashFree(new_elem);
  156424. return data;
  156425. }
  156426. memcpy((void*)new_elem->pKey, pKey, nKey);
  156427. }else{
  156428. new_elem->pKey = (void*)pKey;
  156429. }
  156430. new_elem->nKey = nKey;
  156431. pH->count++;
  156432. assert( pH->htsize>0 );
  156433. assert( (pH->htsize & (pH->htsize-1))==0 );
  156434. h = hraw & (pH->htsize-1);
  156435. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  156436. new_elem->data = data;
  156437. return 0;
  156438. }
  156439. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  156440. /************** End of fts3_hash.c *******************************************/
  156441. /************** Begin file fts3_porter.c *************************************/
  156442. /*
  156443. ** 2006 September 30
  156444. **
  156445. ** The author disclaims copyright to this source code. In place of
  156446. ** a legal notice, here is a blessing:
  156447. **
  156448. ** May you do good and not evil.
  156449. ** May you find forgiveness for yourself and forgive others.
  156450. ** May you share freely, never taking more than you give.
  156451. **
  156452. *************************************************************************
  156453. ** Implementation of the full-text-search tokenizer that implements
  156454. ** a Porter stemmer.
  156455. */
  156456. /*
  156457. ** The code in this file is only compiled if:
  156458. **
  156459. ** * The FTS3 module is being built as an extension
  156460. ** (in which case SQLITE_CORE is not defined), or
  156461. **
  156462. ** * The FTS3 module is being built into the core of
  156463. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  156464. */
  156465. /* #include "fts3Int.h" */
  156466. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  156467. /* #include <assert.h> */
  156468. /* #include <stdlib.h> */
  156469. /* #include <stdio.h> */
  156470. /* #include <string.h> */
  156471. /* #include "fts3_tokenizer.h" */
  156472. /*
  156473. ** Class derived from sqlite3_tokenizer
  156474. */
  156475. typedef struct porter_tokenizer {
  156476. sqlite3_tokenizer base; /* Base class */
  156477. } porter_tokenizer;
  156478. /*
  156479. ** Class derived from sqlite3_tokenizer_cursor
  156480. */
  156481. typedef struct porter_tokenizer_cursor {
  156482. sqlite3_tokenizer_cursor base;
  156483. const char *zInput; /* input we are tokenizing */
  156484. int nInput; /* size of the input */
  156485. int iOffset; /* current position in zInput */
  156486. int iToken; /* index of next token to be returned */
  156487. char *zToken; /* storage for current token */
  156488. int nAllocated; /* space allocated to zToken buffer */
  156489. } porter_tokenizer_cursor;
  156490. /*
  156491. ** Create a new tokenizer instance.
  156492. */
  156493. static int porterCreate(
  156494. int argc, const char * const *argv,
  156495. sqlite3_tokenizer **ppTokenizer
  156496. ){
  156497. porter_tokenizer *t;
  156498. UNUSED_PARAMETER(argc);
  156499. UNUSED_PARAMETER(argv);
  156500. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  156501. if( t==NULL ) return SQLITE_NOMEM;
  156502. memset(t, 0, sizeof(*t));
  156503. *ppTokenizer = &t->base;
  156504. return SQLITE_OK;
  156505. }
  156506. /*
  156507. ** Destroy a tokenizer
  156508. */
  156509. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  156510. sqlite3_free(pTokenizer);
  156511. return SQLITE_OK;
  156512. }
  156513. /*
  156514. ** Prepare to begin tokenizing a particular string. The input
  156515. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  156516. ** used to incrementally tokenize this string is returned in
  156517. ** *ppCursor.
  156518. */
  156519. static int porterOpen(
  156520. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  156521. const char *zInput, int nInput, /* String to be tokenized */
  156522. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  156523. ){
  156524. porter_tokenizer_cursor *c;
  156525. UNUSED_PARAMETER(pTokenizer);
  156526. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  156527. if( c==NULL ) return SQLITE_NOMEM;
  156528. c->zInput = zInput;
  156529. if( zInput==0 ){
  156530. c->nInput = 0;
  156531. }else if( nInput<0 ){
  156532. c->nInput = (int)strlen(zInput);
  156533. }else{
  156534. c->nInput = nInput;
  156535. }
  156536. c->iOffset = 0; /* start tokenizing at the beginning */
  156537. c->iToken = 0;
  156538. c->zToken = NULL; /* no space allocated, yet. */
  156539. c->nAllocated = 0;
  156540. *ppCursor = &c->base;
  156541. return SQLITE_OK;
  156542. }
  156543. /*
  156544. ** Close a tokenization cursor previously opened by a call to
  156545. ** porterOpen() above.
  156546. */
  156547. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  156548. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  156549. sqlite3_free(c->zToken);
  156550. sqlite3_free(c);
  156551. return SQLITE_OK;
  156552. }
  156553. /*
  156554. ** Vowel or consonant
  156555. */
  156556. static const char cType[] = {
  156557. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  156558. 1, 1, 1, 2, 1
  156559. };
  156560. /*
  156561. ** isConsonant() and isVowel() determine if their first character in
  156562. ** the string they point to is a consonant or a vowel, according
  156563. ** to Porter ruls.
  156564. **
  156565. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  156566. ** 'Y' is a consonant unless it follows another consonant,
  156567. ** in which case it is a vowel.
  156568. **
  156569. ** In these routine, the letters are in reverse order. So the 'y' rule
  156570. ** is that 'y' is a consonant unless it is followed by another
  156571. ** consonent.
  156572. */
  156573. static int isVowel(const char*);
  156574. static int isConsonant(const char *z){
  156575. int j;
  156576. char x = *z;
  156577. if( x==0 ) return 0;
  156578. assert( x>='a' && x<='z' );
  156579. j = cType[x-'a'];
  156580. if( j<2 ) return j;
  156581. return z[1]==0 || isVowel(z + 1);
  156582. }
  156583. static int isVowel(const char *z){
  156584. int j;
  156585. char x = *z;
  156586. if( x==0 ) return 0;
  156587. assert( x>='a' && x<='z' );
  156588. j = cType[x-'a'];
  156589. if( j<2 ) return 1-j;
  156590. return isConsonant(z + 1);
  156591. }
  156592. /*
  156593. ** Let any sequence of one or more vowels be represented by V and let
  156594. ** C be sequence of one or more consonants. Then every word can be
  156595. ** represented as:
  156596. **
  156597. ** [C] (VC){m} [V]
  156598. **
  156599. ** In prose: A word is an optional consonant followed by zero or
  156600. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  156601. ** number of vowel consonant pairs. This routine computes the value
  156602. ** of m for the first i bytes of a word.
  156603. **
  156604. ** Return true if the m-value for z is 1 or more. In other words,
  156605. ** return true if z contains at least one vowel that is followed
  156606. ** by a consonant.
  156607. **
  156608. ** In this routine z[] is in reverse order. So we are really looking
  156609. ** for an instance of a consonant followed by a vowel.
  156610. */
  156611. static int m_gt_0(const char *z){
  156612. while( isVowel(z) ){ z++; }
  156613. if( *z==0 ) return 0;
  156614. while( isConsonant(z) ){ z++; }
  156615. return *z!=0;
  156616. }
  156617. /* Like mgt0 above except we are looking for a value of m which is
  156618. ** exactly 1
  156619. */
  156620. static int m_eq_1(const char *z){
  156621. while( isVowel(z) ){ z++; }
  156622. if( *z==0 ) return 0;
  156623. while( isConsonant(z) ){ z++; }
  156624. if( *z==0 ) return 0;
  156625. while( isVowel(z) ){ z++; }
  156626. if( *z==0 ) return 1;
  156627. while( isConsonant(z) ){ z++; }
  156628. return *z==0;
  156629. }
  156630. /* Like mgt0 above except we are looking for a value of m>1 instead
  156631. ** or m>0
  156632. */
  156633. static int m_gt_1(const char *z){
  156634. while( isVowel(z) ){ z++; }
  156635. if( *z==0 ) return 0;
  156636. while( isConsonant(z) ){ z++; }
  156637. if( *z==0 ) return 0;
  156638. while( isVowel(z) ){ z++; }
  156639. if( *z==0 ) return 0;
  156640. while( isConsonant(z) ){ z++; }
  156641. return *z!=0;
  156642. }
  156643. /*
  156644. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  156645. */
  156646. static int hasVowel(const char *z){
  156647. while( isConsonant(z) ){ z++; }
  156648. return *z!=0;
  156649. }
  156650. /*
  156651. ** Return TRUE if the word ends in a double consonant.
  156652. **
  156653. ** The text is reversed here. So we are really looking at
  156654. ** the first two characters of z[].
  156655. */
  156656. static int doubleConsonant(const char *z){
  156657. return isConsonant(z) && z[0]==z[1];
  156658. }
  156659. /*
  156660. ** Return TRUE if the word ends with three letters which
  156661. ** are consonant-vowel-consonent and where the final consonant
  156662. ** is not 'w', 'x', or 'y'.
  156663. **
  156664. ** The word is reversed here. So we are really checking the
  156665. ** first three letters and the first one cannot be in [wxy].
  156666. */
  156667. static int star_oh(const char *z){
  156668. return
  156669. isConsonant(z) &&
  156670. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  156671. isVowel(z+1) &&
  156672. isConsonant(z+2);
  156673. }
  156674. /*
  156675. ** If the word ends with zFrom and xCond() is true for the stem
  156676. ** of the word that preceeds the zFrom ending, then change the
  156677. ** ending to zTo.
  156678. **
  156679. ** The input word *pz and zFrom are both in reverse order. zTo
  156680. ** is in normal order.
  156681. **
  156682. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  156683. ** match. Not that TRUE is returned even if xCond() fails and
  156684. ** no substitution occurs.
  156685. */
  156686. static int stem(
  156687. char **pz, /* The word being stemmed (Reversed) */
  156688. const char *zFrom, /* If the ending matches this... (Reversed) */
  156689. const char *zTo, /* ... change the ending to this (not reversed) */
  156690. int (*xCond)(const char*) /* Condition that must be true */
  156691. ){
  156692. char *z = *pz;
  156693. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  156694. if( *zFrom!=0 ) return 0;
  156695. if( xCond && !xCond(z) ) return 1;
  156696. while( *zTo ){
  156697. *(--z) = *(zTo++);
  156698. }
  156699. *pz = z;
  156700. return 1;
  156701. }
  156702. /*
  156703. ** This is the fallback stemmer used when the porter stemmer is
  156704. ** inappropriate. The input word is copied into the output with
  156705. ** US-ASCII case folding. If the input word is too long (more
  156706. ** than 20 bytes if it contains no digits or more than 6 bytes if
  156707. ** it contains digits) then word is truncated to 20 or 6 bytes
  156708. ** by taking 10 or 3 bytes from the beginning and end.
  156709. */
  156710. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  156711. int i, mx, j;
  156712. int hasDigit = 0;
  156713. for(i=0; i<nIn; i++){
  156714. char c = zIn[i];
  156715. if( c>='A' && c<='Z' ){
  156716. zOut[i] = c - 'A' + 'a';
  156717. }else{
  156718. if( c>='0' && c<='9' ) hasDigit = 1;
  156719. zOut[i] = c;
  156720. }
  156721. }
  156722. mx = hasDigit ? 3 : 10;
  156723. if( nIn>mx*2 ){
  156724. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  156725. zOut[j] = zOut[i];
  156726. }
  156727. i = j;
  156728. }
  156729. zOut[i] = 0;
  156730. *pnOut = i;
  156731. }
  156732. /*
  156733. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  156734. ** zOut is at least big enough to hold nIn bytes. Write the actual
  156735. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  156736. **
  156737. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  156738. ** are converted to lower case. Upper-case UTF characters are
  156739. ** unchanged.
  156740. **
  156741. ** Words that are longer than about 20 bytes are stemmed by retaining
  156742. ** a few bytes from the beginning and the end of the word. If the
  156743. ** word contains digits, 3 bytes are taken from the beginning and
  156744. ** 3 bytes from the end. For long words without digits, 10 bytes
  156745. ** are taken from each end. US-ASCII case folding still applies.
  156746. **
  156747. ** If the input word contains not digits but does characters not
  156748. ** in [a-zA-Z] then no stemming is attempted and this routine just
  156749. ** copies the input into the input into the output with US-ASCII
  156750. ** case folding.
  156751. **
  156752. ** Stemming never increases the length of the word. So there is
  156753. ** no chance of overflowing the zOut buffer.
  156754. */
  156755. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  156756. int i, j;
  156757. char zReverse[28];
  156758. char *z, *z2;
  156759. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  156760. /* The word is too big or too small for the porter stemmer.
  156761. ** Fallback to the copy stemmer */
  156762. copy_stemmer(zIn, nIn, zOut, pnOut);
  156763. return;
  156764. }
  156765. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  156766. char c = zIn[i];
  156767. if( c>='A' && c<='Z' ){
  156768. zReverse[j] = c + 'a' - 'A';
  156769. }else if( c>='a' && c<='z' ){
  156770. zReverse[j] = c;
  156771. }else{
  156772. /* The use of a character not in [a-zA-Z] means that we fallback
  156773. ** to the copy stemmer */
  156774. copy_stemmer(zIn, nIn, zOut, pnOut);
  156775. return;
  156776. }
  156777. }
  156778. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  156779. z = &zReverse[j+1];
  156780. /* Step 1a */
  156781. if( z[0]=='s' ){
  156782. if(
  156783. !stem(&z, "sess", "ss", 0) &&
  156784. !stem(&z, "sei", "i", 0) &&
  156785. !stem(&z, "ss", "ss", 0)
  156786. ){
  156787. z++;
  156788. }
  156789. }
  156790. /* Step 1b */
  156791. z2 = z;
  156792. if( stem(&z, "dee", "ee", m_gt_0) ){
  156793. /* Do nothing. The work was all in the test */
  156794. }else if(
  156795. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  156796. && z!=z2
  156797. ){
  156798. if( stem(&z, "ta", "ate", 0) ||
  156799. stem(&z, "lb", "ble", 0) ||
  156800. stem(&z, "zi", "ize", 0) ){
  156801. /* Do nothing. The work was all in the test */
  156802. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  156803. z++;
  156804. }else if( m_eq_1(z) && star_oh(z) ){
  156805. *(--z) = 'e';
  156806. }
  156807. }
  156808. /* Step 1c */
  156809. if( z[0]=='y' && hasVowel(z+1) ){
  156810. z[0] = 'i';
  156811. }
  156812. /* Step 2 */
  156813. switch( z[1] ){
  156814. case 'a':
  156815. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  156816. stem(&z, "lanoit", "tion", m_gt_0);
  156817. }
  156818. break;
  156819. case 'c':
  156820. if( !stem(&z, "icne", "ence", m_gt_0) ){
  156821. stem(&z, "icna", "ance", m_gt_0);
  156822. }
  156823. break;
  156824. case 'e':
  156825. stem(&z, "rezi", "ize", m_gt_0);
  156826. break;
  156827. case 'g':
  156828. stem(&z, "igol", "log", m_gt_0);
  156829. break;
  156830. case 'l':
  156831. if( !stem(&z, "ilb", "ble", m_gt_0)
  156832. && !stem(&z, "illa", "al", m_gt_0)
  156833. && !stem(&z, "iltne", "ent", m_gt_0)
  156834. && !stem(&z, "ile", "e", m_gt_0)
  156835. ){
  156836. stem(&z, "ilsuo", "ous", m_gt_0);
  156837. }
  156838. break;
  156839. case 'o':
  156840. if( !stem(&z, "noitazi", "ize", m_gt_0)
  156841. && !stem(&z, "noita", "ate", m_gt_0)
  156842. ){
  156843. stem(&z, "rota", "ate", m_gt_0);
  156844. }
  156845. break;
  156846. case 's':
  156847. if( !stem(&z, "msila", "al", m_gt_0)
  156848. && !stem(&z, "ssenevi", "ive", m_gt_0)
  156849. && !stem(&z, "ssenluf", "ful", m_gt_0)
  156850. ){
  156851. stem(&z, "ssensuo", "ous", m_gt_0);
  156852. }
  156853. break;
  156854. case 't':
  156855. if( !stem(&z, "itila", "al", m_gt_0)
  156856. && !stem(&z, "itivi", "ive", m_gt_0)
  156857. ){
  156858. stem(&z, "itilib", "ble", m_gt_0);
  156859. }
  156860. break;
  156861. }
  156862. /* Step 3 */
  156863. switch( z[0] ){
  156864. case 'e':
  156865. if( !stem(&z, "etaci", "ic", m_gt_0)
  156866. && !stem(&z, "evita", "", m_gt_0)
  156867. ){
  156868. stem(&z, "ezila", "al", m_gt_0);
  156869. }
  156870. break;
  156871. case 'i':
  156872. stem(&z, "itici", "ic", m_gt_0);
  156873. break;
  156874. case 'l':
  156875. if( !stem(&z, "laci", "ic", m_gt_0) ){
  156876. stem(&z, "luf", "", m_gt_0);
  156877. }
  156878. break;
  156879. case 's':
  156880. stem(&z, "ssen", "", m_gt_0);
  156881. break;
  156882. }
  156883. /* Step 4 */
  156884. switch( z[1] ){
  156885. case 'a':
  156886. if( z[0]=='l' && m_gt_1(z+2) ){
  156887. z += 2;
  156888. }
  156889. break;
  156890. case 'c':
  156891. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  156892. z += 4;
  156893. }
  156894. break;
  156895. case 'e':
  156896. if( z[0]=='r' && m_gt_1(z+2) ){
  156897. z += 2;
  156898. }
  156899. break;
  156900. case 'i':
  156901. if( z[0]=='c' && m_gt_1(z+2) ){
  156902. z += 2;
  156903. }
  156904. break;
  156905. case 'l':
  156906. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  156907. z += 4;
  156908. }
  156909. break;
  156910. case 'n':
  156911. if( z[0]=='t' ){
  156912. if( z[2]=='a' ){
  156913. if( m_gt_1(z+3) ){
  156914. z += 3;
  156915. }
  156916. }else if( z[2]=='e' ){
  156917. if( !stem(&z, "tneme", "", m_gt_1)
  156918. && !stem(&z, "tnem", "", m_gt_1)
  156919. ){
  156920. stem(&z, "tne", "", m_gt_1);
  156921. }
  156922. }
  156923. }
  156924. break;
  156925. case 'o':
  156926. if( z[0]=='u' ){
  156927. if( m_gt_1(z+2) ){
  156928. z += 2;
  156929. }
  156930. }else if( z[3]=='s' || z[3]=='t' ){
  156931. stem(&z, "noi", "", m_gt_1);
  156932. }
  156933. break;
  156934. case 's':
  156935. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  156936. z += 3;
  156937. }
  156938. break;
  156939. case 't':
  156940. if( !stem(&z, "eta", "", m_gt_1) ){
  156941. stem(&z, "iti", "", m_gt_1);
  156942. }
  156943. break;
  156944. case 'u':
  156945. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  156946. z += 3;
  156947. }
  156948. break;
  156949. case 'v':
  156950. case 'z':
  156951. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  156952. z += 3;
  156953. }
  156954. break;
  156955. }
  156956. /* Step 5a */
  156957. if( z[0]=='e' ){
  156958. if( m_gt_1(z+1) ){
  156959. z++;
  156960. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  156961. z++;
  156962. }
  156963. }
  156964. /* Step 5b */
  156965. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  156966. z++;
  156967. }
  156968. /* z[] is now the stemmed word in reverse order. Flip it back
  156969. ** around into forward order and return.
  156970. */
  156971. *pnOut = i = (int)strlen(z);
  156972. zOut[i] = 0;
  156973. while( *z ){
  156974. zOut[--i] = *(z++);
  156975. }
  156976. }
  156977. /*
  156978. ** Characters that can be part of a token. We assume any character
  156979. ** whose value is greater than 0x80 (any UTF character) can be
  156980. ** part of a token. In other words, delimiters all must have
  156981. ** values of 0x7f or lower.
  156982. */
  156983. static const char porterIdChar[] = {
  156984. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  156985. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  156986. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  156987. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  156988. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  156989. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  156990. };
  156991. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  156992. /*
  156993. ** Extract the next token from a tokenization cursor. The cursor must
  156994. ** have been opened by a prior call to porterOpen().
  156995. */
  156996. static int porterNext(
  156997. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  156998. const char **pzToken, /* OUT: *pzToken is the token text */
  156999. int *pnBytes, /* OUT: Number of bytes in token */
  157000. int *piStartOffset, /* OUT: Starting offset of token */
  157001. int *piEndOffset, /* OUT: Ending offset of token */
  157002. int *piPosition /* OUT: Position integer of token */
  157003. ){
  157004. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  157005. const char *z = c->zInput;
  157006. while( c->iOffset<c->nInput ){
  157007. int iStartOffset, ch;
  157008. /* Scan past delimiter characters */
  157009. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  157010. c->iOffset++;
  157011. }
  157012. /* Count non-delimiter characters. */
  157013. iStartOffset = c->iOffset;
  157014. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  157015. c->iOffset++;
  157016. }
  157017. if( c->iOffset>iStartOffset ){
  157018. int n = c->iOffset-iStartOffset;
  157019. if( n>c->nAllocated ){
  157020. char *pNew;
  157021. c->nAllocated = n+20;
  157022. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  157023. if( !pNew ) return SQLITE_NOMEM;
  157024. c->zToken = pNew;
  157025. }
  157026. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  157027. *pzToken = c->zToken;
  157028. *piStartOffset = iStartOffset;
  157029. *piEndOffset = c->iOffset;
  157030. *piPosition = c->iToken++;
  157031. return SQLITE_OK;
  157032. }
  157033. }
  157034. return SQLITE_DONE;
  157035. }
  157036. /*
  157037. ** The set of routines that implement the porter-stemmer tokenizer
  157038. */
  157039. static const sqlite3_tokenizer_module porterTokenizerModule = {
  157040. 0,
  157041. porterCreate,
  157042. porterDestroy,
  157043. porterOpen,
  157044. porterClose,
  157045. porterNext,
  157046. 0
  157047. };
  157048. /*
  157049. ** Allocate a new porter tokenizer. Return a pointer to the new
  157050. ** tokenizer in *ppModule
  157051. */
  157052. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  157053. sqlite3_tokenizer_module const**ppModule
  157054. ){
  157055. *ppModule = &porterTokenizerModule;
  157056. }
  157057. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  157058. /************** End of fts3_porter.c *****************************************/
  157059. /************** Begin file fts3_tokenizer.c **********************************/
  157060. /*
  157061. ** 2007 June 22
  157062. **
  157063. ** The author disclaims copyright to this source code. In place of
  157064. ** a legal notice, here is a blessing:
  157065. **
  157066. ** May you do good and not evil.
  157067. ** May you find forgiveness for yourself and forgive others.
  157068. ** May you share freely, never taking more than you give.
  157069. **
  157070. ******************************************************************************
  157071. **
  157072. ** This is part of an SQLite module implementing full-text search.
  157073. ** This particular file implements the generic tokenizer interface.
  157074. */
  157075. /*
  157076. ** The code in this file is only compiled if:
  157077. **
  157078. ** * The FTS3 module is being built as an extension
  157079. ** (in which case SQLITE_CORE is not defined), or
  157080. **
  157081. ** * The FTS3 module is being built into the core of
  157082. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  157083. */
  157084. /* #include "fts3Int.h" */
  157085. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  157086. /* #include <assert.h> */
  157087. /* #include <string.h> */
  157088. /*
  157089. ** Return true if the two-argument version of fts3_tokenizer()
  157090. ** has been activated via a prior call to sqlite3_db_config(db,
  157091. ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
  157092. */
  157093. static int fts3TokenizerEnabled(sqlite3_context *context){
  157094. sqlite3 *db = sqlite3_context_db_handle(context);
  157095. int isEnabled = 0;
  157096. sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
  157097. return isEnabled;
  157098. }
  157099. /*
  157100. ** Implementation of the SQL scalar function for accessing the underlying
  157101. ** hash table. This function may be called as follows:
  157102. **
  157103. ** SELECT <function-name>(<key-name>);
  157104. ** SELECT <function-name>(<key-name>, <pointer>);
  157105. **
  157106. ** where <function-name> is the name passed as the second argument
  157107. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  157108. **
  157109. ** If the <pointer> argument is specified, it must be a blob value
  157110. ** containing a pointer to be stored as the hash data corresponding
  157111. ** to the string <key-name>. If <pointer> is not specified, then
  157112. ** the string <key-name> must already exist in the has table. Otherwise,
  157113. ** an error is returned.
  157114. **
  157115. ** Whether or not the <pointer> argument is specified, the value returned
  157116. ** is a blob containing the pointer stored as the hash data corresponding
  157117. ** to string <key-name> (after the hash-table is updated, if applicable).
  157118. */
  157119. static void fts3TokenizerFunc(
  157120. sqlite3_context *context,
  157121. int argc,
  157122. sqlite3_value **argv
  157123. ){
  157124. Fts3Hash *pHash;
  157125. void *pPtr = 0;
  157126. const unsigned char *zName;
  157127. int nName;
  157128. assert( argc==1 || argc==2 );
  157129. pHash = (Fts3Hash *)sqlite3_user_data(context);
  157130. zName = sqlite3_value_text(argv[0]);
  157131. nName = sqlite3_value_bytes(argv[0])+1;
  157132. if( argc==2 ){
  157133. if( fts3TokenizerEnabled(context) ){
  157134. void *pOld;
  157135. int n = sqlite3_value_bytes(argv[1]);
  157136. if( zName==0 || n!=sizeof(pPtr) ){
  157137. sqlite3_result_error(context, "argument type mismatch", -1);
  157138. return;
  157139. }
  157140. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  157141. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  157142. if( pOld==pPtr ){
  157143. sqlite3_result_error(context, "out of memory", -1);
  157144. }
  157145. }else{
  157146. sqlite3_result_error(context, "fts3tokenize disabled", -1);
  157147. return;
  157148. }
  157149. }else{
  157150. if( zName ){
  157151. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  157152. }
  157153. if( !pPtr ){
  157154. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  157155. sqlite3_result_error(context, zErr, -1);
  157156. sqlite3_free(zErr);
  157157. return;
  157158. }
  157159. }
  157160. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  157161. }
  157162. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  157163. static const char isFtsIdChar[] = {
  157164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  157165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  157166. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  157167. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  157168. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  157169. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  157170. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  157171. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  157172. };
  157173. return (c&0x80 || isFtsIdChar[(int)(c)]);
  157174. }
  157175. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  157176. const char *z1;
  157177. const char *z2 = 0;
  157178. /* Find the start of the next token. */
  157179. z1 = zStr;
  157180. while( z2==0 ){
  157181. char c = *z1;
  157182. switch( c ){
  157183. case '\0': return 0; /* No more tokens here */
  157184. case '\'':
  157185. case '"':
  157186. case '`': {
  157187. z2 = z1;
  157188. while( *++z2 && (*z2!=c || *++z2==c) );
  157189. break;
  157190. }
  157191. case '[':
  157192. z2 = &z1[1];
  157193. while( *z2 && z2[0]!=']' ) z2++;
  157194. if( *z2 ) z2++;
  157195. break;
  157196. default:
  157197. if( sqlite3Fts3IsIdChar(*z1) ){
  157198. z2 = &z1[1];
  157199. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  157200. }else{
  157201. z1++;
  157202. }
  157203. }
  157204. }
  157205. *pn = (int)(z2-z1);
  157206. return z1;
  157207. }
  157208. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  157209. Fts3Hash *pHash, /* Tokenizer hash table */
  157210. const char *zArg, /* Tokenizer name */
  157211. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  157212. char **pzErr /* OUT: Set to malloced error message */
  157213. ){
  157214. int rc;
  157215. char *z = (char *)zArg;
  157216. int n = 0;
  157217. char *zCopy;
  157218. char *zEnd; /* Pointer to nul-term of zCopy */
  157219. sqlite3_tokenizer_module *m;
  157220. zCopy = sqlite3_mprintf("%s", zArg);
  157221. if( !zCopy ) return SQLITE_NOMEM;
  157222. zEnd = &zCopy[strlen(zCopy)];
  157223. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  157224. if( z==0 ){
  157225. assert( n==0 );
  157226. z = zCopy;
  157227. }
  157228. z[n] = '\0';
  157229. sqlite3Fts3Dequote(z);
  157230. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  157231. if( !m ){
  157232. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  157233. rc = SQLITE_ERROR;
  157234. }else{
  157235. char const **aArg = 0;
  157236. int iArg = 0;
  157237. z = &z[n+1];
  157238. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  157239. int nNew = sizeof(char *)*(iArg+1);
  157240. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  157241. if( !aNew ){
  157242. sqlite3_free(zCopy);
  157243. sqlite3_free((void *)aArg);
  157244. return SQLITE_NOMEM;
  157245. }
  157246. aArg = aNew;
  157247. aArg[iArg++] = z;
  157248. z[n] = '\0';
  157249. sqlite3Fts3Dequote(z);
  157250. z = &z[n+1];
  157251. }
  157252. rc = m->xCreate(iArg, aArg, ppTok);
  157253. assert( rc!=SQLITE_OK || *ppTok );
  157254. if( rc!=SQLITE_OK ){
  157255. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  157256. }else{
  157257. (*ppTok)->pModule = m;
  157258. }
  157259. sqlite3_free((void *)aArg);
  157260. }
  157261. sqlite3_free(zCopy);
  157262. return rc;
  157263. }
  157264. #ifdef SQLITE_TEST
  157265. #if defined(INCLUDE_SQLITE_TCL_H)
  157266. # include "sqlite_tcl.h"
  157267. #else
  157268. # include "tcl.h"
  157269. #endif
  157270. /* #include <string.h> */
  157271. /*
  157272. ** Implementation of a special SQL scalar function for testing tokenizers
  157273. ** designed to be used in concert with the Tcl testing framework. This
  157274. ** function must be called with two or more arguments:
  157275. **
  157276. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  157277. **
  157278. ** where <function-name> is the name passed as the second argument
  157279. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  157280. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  157281. **
  157282. ** The return value is a string that may be interpreted as a Tcl
  157283. ** list. For each token in the <input-string>, three elements are
  157284. ** added to the returned list. The first is the token position, the
  157285. ** second is the token text (folded, stemmed, etc.) and the third is the
  157286. ** substring of <input-string> associated with the token. For example,
  157287. ** using the built-in "simple" tokenizer:
  157288. **
  157289. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  157290. **
  157291. ** will return the string:
  157292. **
  157293. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  157294. **
  157295. */
  157296. static void testFunc(
  157297. sqlite3_context *context,
  157298. int argc,
  157299. sqlite3_value **argv
  157300. ){
  157301. Fts3Hash *pHash;
  157302. sqlite3_tokenizer_module *p;
  157303. sqlite3_tokenizer *pTokenizer = 0;
  157304. sqlite3_tokenizer_cursor *pCsr = 0;
  157305. const char *zErr = 0;
  157306. const char *zName;
  157307. int nName;
  157308. const char *zInput;
  157309. int nInput;
  157310. const char *azArg[64];
  157311. const char *zToken;
  157312. int nToken = 0;
  157313. int iStart = 0;
  157314. int iEnd = 0;
  157315. int iPos = 0;
  157316. int i;
  157317. Tcl_Obj *pRet;
  157318. if( argc<2 ){
  157319. sqlite3_result_error(context, "insufficient arguments", -1);
  157320. return;
  157321. }
  157322. nName = sqlite3_value_bytes(argv[0]);
  157323. zName = (const char *)sqlite3_value_text(argv[0]);
  157324. nInput = sqlite3_value_bytes(argv[argc-1]);
  157325. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  157326. pHash = (Fts3Hash *)sqlite3_user_data(context);
  157327. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  157328. if( !p ){
  157329. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  157330. sqlite3_result_error(context, zErr2, -1);
  157331. sqlite3_free(zErr2);
  157332. return;
  157333. }
  157334. pRet = Tcl_NewObj();
  157335. Tcl_IncrRefCount(pRet);
  157336. for(i=1; i<argc-1; i++){
  157337. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  157338. }
  157339. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  157340. zErr = "error in xCreate()";
  157341. goto finish;
  157342. }
  157343. pTokenizer->pModule = p;
  157344. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  157345. zErr = "error in xOpen()";
  157346. goto finish;
  157347. }
  157348. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  157349. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  157350. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  157351. zToken = &zInput[iStart];
  157352. nToken = iEnd-iStart;
  157353. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  157354. }
  157355. if( SQLITE_OK!=p->xClose(pCsr) ){
  157356. zErr = "error in xClose()";
  157357. goto finish;
  157358. }
  157359. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  157360. zErr = "error in xDestroy()";
  157361. goto finish;
  157362. }
  157363. finish:
  157364. if( zErr ){
  157365. sqlite3_result_error(context, zErr, -1);
  157366. }else{
  157367. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  157368. }
  157369. Tcl_DecrRefCount(pRet);
  157370. }
  157371. static
  157372. int registerTokenizer(
  157373. sqlite3 *db,
  157374. char *zName,
  157375. const sqlite3_tokenizer_module *p
  157376. ){
  157377. int rc;
  157378. sqlite3_stmt *pStmt;
  157379. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  157380. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  157381. if( rc!=SQLITE_OK ){
  157382. return rc;
  157383. }
  157384. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  157385. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  157386. sqlite3_step(pStmt);
  157387. return sqlite3_finalize(pStmt);
  157388. }
  157389. static
  157390. int queryTokenizer(
  157391. sqlite3 *db,
  157392. char *zName,
  157393. const sqlite3_tokenizer_module **pp
  157394. ){
  157395. int rc;
  157396. sqlite3_stmt *pStmt;
  157397. const char zSql[] = "SELECT fts3_tokenizer(?)";
  157398. *pp = 0;
  157399. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  157400. if( rc!=SQLITE_OK ){
  157401. return rc;
  157402. }
  157403. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  157404. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  157405. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  157406. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  157407. }
  157408. }
  157409. return sqlite3_finalize(pStmt);
  157410. }
  157411. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  157412. /*
  157413. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  157414. ** This function is used for testing only, it is not included in the
  157415. ** build unless SQLITE_TEST is defined.
  157416. **
  157417. ** The purpose of this is to test that the fts3_tokenizer() function
  157418. ** can be used as designed by the C-code in the queryTokenizer and
  157419. ** registerTokenizer() functions above. These two functions are repeated
  157420. ** in the README.tokenizer file as an example, so it is important to
  157421. ** test them.
  157422. **
  157423. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  157424. ** function with no arguments. An assert() will fail if a problem is
  157425. ** detected. i.e.:
  157426. **
  157427. ** SELECT fts3_tokenizer_internal_test();
  157428. **
  157429. */
  157430. static void intTestFunc(
  157431. sqlite3_context *context,
  157432. int argc,
  157433. sqlite3_value **argv
  157434. ){
  157435. int rc;
  157436. const sqlite3_tokenizer_module *p1;
  157437. const sqlite3_tokenizer_module *p2;
  157438. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  157439. UNUSED_PARAMETER(argc);
  157440. UNUSED_PARAMETER(argv);
  157441. /* Test the query function */
  157442. sqlite3Fts3SimpleTokenizerModule(&p1);
  157443. rc = queryTokenizer(db, "simple", &p2);
  157444. assert( rc==SQLITE_OK );
  157445. assert( p1==p2 );
  157446. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  157447. assert( rc==SQLITE_ERROR );
  157448. assert( p2==0 );
  157449. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  157450. /* Test the storage function */
  157451. if( fts3TokenizerEnabled(context) ){
  157452. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  157453. assert( rc==SQLITE_OK );
  157454. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  157455. assert( rc==SQLITE_OK );
  157456. assert( p2==p1 );
  157457. }
  157458. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  157459. }
  157460. #endif
  157461. /*
  157462. ** Set up SQL objects in database db used to access the contents of
  157463. ** the hash table pointed to by argument pHash. The hash table must
  157464. ** been initialized to use string keys, and to take a private copy
  157465. ** of the key when a value is inserted. i.e. by a call similar to:
  157466. **
  157467. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  157468. **
  157469. ** This function adds a scalar function (see header comment above
  157470. ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
  157471. ** defined at compilation time, a temporary virtual table (see header
  157472. ** comment above struct HashTableVtab) to the database schema. Both
  157473. ** provide read/write access to the contents of *pHash.
  157474. **
  157475. ** The third argument to this function, zName, is used as the name
  157476. ** of both the scalar and, if created, the virtual table.
  157477. */
  157478. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  157479. sqlite3 *db,
  157480. Fts3Hash *pHash,
  157481. const char *zName
  157482. ){
  157483. int rc = SQLITE_OK;
  157484. void *p = (void *)pHash;
  157485. const int any = SQLITE_ANY;
  157486. #ifdef SQLITE_TEST
  157487. char *zTest = 0;
  157488. char *zTest2 = 0;
  157489. void *pdb = (void *)db;
  157490. zTest = sqlite3_mprintf("%s_test", zName);
  157491. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  157492. if( !zTest || !zTest2 ){
  157493. rc = SQLITE_NOMEM;
  157494. }
  157495. #endif
  157496. if( SQLITE_OK==rc ){
  157497. rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
  157498. }
  157499. if( SQLITE_OK==rc ){
  157500. rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
  157501. }
  157502. #ifdef SQLITE_TEST
  157503. if( SQLITE_OK==rc ){
  157504. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  157505. }
  157506. if( SQLITE_OK==rc ){
  157507. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  157508. }
  157509. #endif
  157510. #ifdef SQLITE_TEST
  157511. sqlite3_free(zTest);
  157512. sqlite3_free(zTest2);
  157513. #endif
  157514. return rc;
  157515. }
  157516. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  157517. /************** End of fts3_tokenizer.c **************************************/
  157518. /************** Begin file fts3_tokenizer1.c *********************************/
  157519. /*
  157520. ** 2006 Oct 10
  157521. **
  157522. ** The author disclaims copyright to this source code. In place of
  157523. ** a legal notice, here is a blessing:
  157524. **
  157525. ** May you do good and not evil.
  157526. ** May you find forgiveness for yourself and forgive others.
  157527. ** May you share freely, never taking more than you give.
  157528. **
  157529. ******************************************************************************
  157530. **
  157531. ** Implementation of the "simple" full-text-search tokenizer.
  157532. */
  157533. /*
  157534. ** The code in this file is only compiled if:
  157535. **
  157536. ** * The FTS3 module is being built as an extension
  157537. ** (in which case SQLITE_CORE is not defined), or
  157538. **
  157539. ** * The FTS3 module is being built into the core of
  157540. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  157541. */
  157542. /* #include "fts3Int.h" */
  157543. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  157544. /* #include <assert.h> */
  157545. /* #include <stdlib.h> */
  157546. /* #include <stdio.h> */
  157547. /* #include <string.h> */
  157548. /* #include "fts3_tokenizer.h" */
  157549. typedef struct simple_tokenizer {
  157550. sqlite3_tokenizer base;
  157551. char delim[128]; /* flag ASCII delimiters */
  157552. } simple_tokenizer;
  157553. typedef struct simple_tokenizer_cursor {
  157554. sqlite3_tokenizer_cursor base;
  157555. const char *pInput; /* input we are tokenizing */
  157556. int nBytes; /* size of the input */
  157557. int iOffset; /* current position in pInput */
  157558. int iToken; /* index of next token to be returned */
  157559. char *pToken; /* storage for current token */
  157560. int nTokenAllocated; /* space allocated to zToken buffer */
  157561. } simple_tokenizer_cursor;
  157562. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  157563. return c<0x80 && t->delim[c];
  157564. }
  157565. static int fts3_isalnum(int x){
  157566. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  157567. }
  157568. /*
  157569. ** Create a new tokenizer instance.
  157570. */
  157571. static int simpleCreate(
  157572. int argc, const char * const *argv,
  157573. sqlite3_tokenizer **ppTokenizer
  157574. ){
  157575. simple_tokenizer *t;
  157576. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  157577. if( t==NULL ) return SQLITE_NOMEM;
  157578. memset(t, 0, sizeof(*t));
  157579. /* TODO(shess) Delimiters need to remain the same from run to run,
  157580. ** else we need to reindex. One solution would be a meta-table to
  157581. ** track such information in the database, then we'd only want this
  157582. ** information on the initial create.
  157583. */
  157584. if( argc>1 ){
  157585. int i, n = (int)strlen(argv[1]);
  157586. for(i=0; i<n; i++){
  157587. unsigned char ch = argv[1][i];
  157588. /* We explicitly don't support UTF-8 delimiters for now. */
  157589. if( ch>=0x80 ){
  157590. sqlite3_free(t);
  157591. return SQLITE_ERROR;
  157592. }
  157593. t->delim[ch] = 1;
  157594. }
  157595. } else {
  157596. /* Mark non-alphanumeric ASCII characters as delimiters */
  157597. int i;
  157598. for(i=1; i<0x80; i++){
  157599. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  157600. }
  157601. }
  157602. *ppTokenizer = &t->base;
  157603. return SQLITE_OK;
  157604. }
  157605. /*
  157606. ** Destroy a tokenizer
  157607. */
  157608. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  157609. sqlite3_free(pTokenizer);
  157610. return SQLITE_OK;
  157611. }
  157612. /*
  157613. ** Prepare to begin tokenizing a particular string. The input
  157614. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  157615. ** used to incrementally tokenize this string is returned in
  157616. ** *ppCursor.
  157617. */
  157618. static int simpleOpen(
  157619. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  157620. const char *pInput, int nBytes, /* String to be tokenized */
  157621. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  157622. ){
  157623. simple_tokenizer_cursor *c;
  157624. UNUSED_PARAMETER(pTokenizer);
  157625. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  157626. if( c==NULL ) return SQLITE_NOMEM;
  157627. c->pInput = pInput;
  157628. if( pInput==0 ){
  157629. c->nBytes = 0;
  157630. }else if( nBytes<0 ){
  157631. c->nBytes = (int)strlen(pInput);
  157632. }else{
  157633. c->nBytes = nBytes;
  157634. }
  157635. c->iOffset = 0; /* start tokenizing at the beginning */
  157636. c->iToken = 0;
  157637. c->pToken = NULL; /* no space allocated, yet. */
  157638. c->nTokenAllocated = 0;
  157639. *ppCursor = &c->base;
  157640. return SQLITE_OK;
  157641. }
  157642. /*
  157643. ** Close a tokenization cursor previously opened by a call to
  157644. ** simpleOpen() above.
  157645. */
  157646. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  157647. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  157648. sqlite3_free(c->pToken);
  157649. sqlite3_free(c);
  157650. return SQLITE_OK;
  157651. }
  157652. /*
  157653. ** Extract the next token from a tokenization cursor. The cursor must
  157654. ** have been opened by a prior call to simpleOpen().
  157655. */
  157656. static int simpleNext(
  157657. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  157658. const char **ppToken, /* OUT: *ppToken is the token text */
  157659. int *pnBytes, /* OUT: Number of bytes in token */
  157660. int *piStartOffset, /* OUT: Starting offset of token */
  157661. int *piEndOffset, /* OUT: Ending offset of token */
  157662. int *piPosition /* OUT: Position integer of token */
  157663. ){
  157664. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  157665. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  157666. unsigned char *p = (unsigned char *)c->pInput;
  157667. while( c->iOffset<c->nBytes ){
  157668. int iStartOffset;
  157669. /* Scan past delimiter characters */
  157670. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  157671. c->iOffset++;
  157672. }
  157673. /* Count non-delimiter characters. */
  157674. iStartOffset = c->iOffset;
  157675. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  157676. c->iOffset++;
  157677. }
  157678. if( c->iOffset>iStartOffset ){
  157679. int i, n = c->iOffset-iStartOffset;
  157680. if( n>c->nTokenAllocated ){
  157681. char *pNew;
  157682. c->nTokenAllocated = n+20;
  157683. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  157684. if( !pNew ) return SQLITE_NOMEM;
  157685. c->pToken = pNew;
  157686. }
  157687. for(i=0; i<n; i++){
  157688. /* TODO(shess) This needs expansion to handle UTF-8
  157689. ** case-insensitivity.
  157690. */
  157691. unsigned char ch = p[iStartOffset+i];
  157692. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  157693. }
  157694. *ppToken = c->pToken;
  157695. *pnBytes = n;
  157696. *piStartOffset = iStartOffset;
  157697. *piEndOffset = c->iOffset;
  157698. *piPosition = c->iToken++;
  157699. return SQLITE_OK;
  157700. }
  157701. }
  157702. return SQLITE_DONE;
  157703. }
  157704. /*
  157705. ** The set of routines that implement the simple tokenizer
  157706. */
  157707. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  157708. 0,
  157709. simpleCreate,
  157710. simpleDestroy,
  157711. simpleOpen,
  157712. simpleClose,
  157713. simpleNext,
  157714. 0,
  157715. };
  157716. /*
  157717. ** Allocate a new simple tokenizer. Return a pointer to the new
  157718. ** tokenizer in *ppModule
  157719. */
  157720. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  157721. sqlite3_tokenizer_module const**ppModule
  157722. ){
  157723. *ppModule = &simpleTokenizerModule;
  157724. }
  157725. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  157726. /************** End of fts3_tokenizer1.c *************************************/
  157727. /************** Begin file fts3_tokenize_vtab.c ******************************/
  157728. /*
  157729. ** 2013 Apr 22
  157730. **
  157731. ** The author disclaims copyright to this source code. In place of
  157732. ** a legal notice, here is a blessing:
  157733. **
  157734. ** May you do good and not evil.
  157735. ** May you find forgiveness for yourself and forgive others.
  157736. ** May you share freely, never taking more than you give.
  157737. **
  157738. ******************************************************************************
  157739. **
  157740. ** This file contains code for the "fts3tokenize" virtual table module.
  157741. ** An fts3tokenize virtual table is created as follows:
  157742. **
  157743. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  157744. ** <tokenizer-name>, <arg-1>, ...
  157745. ** );
  157746. **
  157747. ** The table created has the following schema:
  157748. **
  157749. ** CREATE TABLE <tbl>(input, token, start, end, position)
  157750. **
  157751. ** When queried, the query must include a WHERE clause of type:
  157752. **
  157753. ** input = <string>
  157754. **
  157755. ** The virtual table module tokenizes this <string>, using the FTS3
  157756. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  157757. ** statement and returns one row for each token in the result. With
  157758. ** fields set as follows:
  157759. **
  157760. ** input: Always set to a copy of <string>
  157761. ** token: A token from the input.
  157762. ** start: Byte offset of the token within the input <string>.
  157763. ** end: Byte offset of the byte immediately following the end of the
  157764. ** token within the input string.
  157765. ** pos: Token offset of token within input.
  157766. **
  157767. */
  157768. /* #include "fts3Int.h" */
  157769. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  157770. /* #include <string.h> */
  157771. /* #include <assert.h> */
  157772. typedef struct Fts3tokTable Fts3tokTable;
  157773. typedef struct Fts3tokCursor Fts3tokCursor;
  157774. /*
  157775. ** Virtual table structure.
  157776. */
  157777. struct Fts3tokTable {
  157778. sqlite3_vtab base; /* Base class used by SQLite core */
  157779. const sqlite3_tokenizer_module *pMod;
  157780. sqlite3_tokenizer *pTok;
  157781. };
  157782. /*
  157783. ** Virtual table cursor structure.
  157784. */
  157785. struct Fts3tokCursor {
  157786. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  157787. char *zInput; /* Input string */
  157788. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  157789. int iRowid; /* Current 'rowid' value */
  157790. const char *zToken; /* Current 'token' value */
  157791. int nToken; /* Size of zToken in bytes */
  157792. int iStart; /* Current 'start' value */
  157793. int iEnd; /* Current 'end' value */
  157794. int iPos; /* Current 'pos' value */
  157795. };
  157796. /*
  157797. ** Query FTS for the tokenizer implementation named zName.
  157798. */
  157799. static int fts3tokQueryTokenizer(
  157800. Fts3Hash *pHash,
  157801. const char *zName,
  157802. const sqlite3_tokenizer_module **pp,
  157803. char **pzErr
  157804. ){
  157805. sqlite3_tokenizer_module *p;
  157806. int nName = (int)strlen(zName);
  157807. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  157808. if( !p ){
  157809. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  157810. return SQLITE_ERROR;
  157811. }
  157812. *pp = p;
  157813. return SQLITE_OK;
  157814. }
  157815. /*
  157816. ** The second argument, argv[], is an array of pointers to nul-terminated
  157817. ** strings. This function makes a copy of the array and strings into a
  157818. ** single block of memory. It then dequotes any of the strings that appear
  157819. ** to be quoted.
  157820. **
  157821. ** If successful, output parameter *pazDequote is set to point at the
  157822. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  157823. ** responsible for eventually calling sqlite3_free() to free the array
  157824. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  157825. ** The final value of *pazDequote is undefined in this case.
  157826. */
  157827. static int fts3tokDequoteArray(
  157828. int argc, /* Number of elements in argv[] */
  157829. const char * const *argv, /* Input array */
  157830. char ***pazDequote /* Output array */
  157831. ){
  157832. int rc = SQLITE_OK; /* Return code */
  157833. if( argc==0 ){
  157834. *pazDequote = 0;
  157835. }else{
  157836. int i;
  157837. int nByte = 0;
  157838. char **azDequote;
  157839. for(i=0; i<argc; i++){
  157840. nByte += (int)(strlen(argv[i]) + 1);
  157841. }
  157842. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  157843. if( azDequote==0 ){
  157844. rc = SQLITE_NOMEM;
  157845. }else{
  157846. char *pSpace = (char *)&azDequote[argc];
  157847. for(i=0; i<argc; i++){
  157848. int n = (int)strlen(argv[i]);
  157849. azDequote[i] = pSpace;
  157850. memcpy(pSpace, argv[i], n+1);
  157851. sqlite3Fts3Dequote(pSpace);
  157852. pSpace += (n+1);
  157853. }
  157854. }
  157855. }
  157856. return rc;
  157857. }
  157858. /*
  157859. ** Schema of the tokenizer table.
  157860. */
  157861. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  157862. /*
  157863. ** This function does all the work for both the xConnect and xCreate methods.
  157864. ** These tables have no persistent representation of their own, so xConnect
  157865. ** and xCreate are identical operations.
  157866. **
  157867. ** argv[0]: module name
  157868. ** argv[1]: database name
  157869. ** argv[2]: table name
  157870. ** argv[3]: first argument (tokenizer name)
  157871. */
  157872. static int fts3tokConnectMethod(
  157873. sqlite3 *db, /* Database connection */
  157874. void *pHash, /* Hash table of tokenizers */
  157875. int argc, /* Number of elements in argv array */
  157876. const char * const *argv, /* xCreate/xConnect argument array */
  157877. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  157878. char **pzErr /* OUT: sqlite3_malloc'd error message */
  157879. ){
  157880. Fts3tokTable *pTab = 0;
  157881. const sqlite3_tokenizer_module *pMod = 0;
  157882. sqlite3_tokenizer *pTok = 0;
  157883. int rc;
  157884. char **azDequote = 0;
  157885. int nDequote;
  157886. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  157887. if( rc!=SQLITE_OK ) return rc;
  157888. nDequote = argc-3;
  157889. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  157890. if( rc==SQLITE_OK ){
  157891. const char *zModule;
  157892. if( nDequote<1 ){
  157893. zModule = "simple";
  157894. }else{
  157895. zModule = azDequote[0];
  157896. }
  157897. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  157898. }
  157899. assert( (rc==SQLITE_OK)==(pMod!=0) );
  157900. if( rc==SQLITE_OK ){
  157901. const char * const *azArg = (const char * const *)&azDequote[1];
  157902. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  157903. }
  157904. if( rc==SQLITE_OK ){
  157905. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  157906. if( pTab==0 ){
  157907. rc = SQLITE_NOMEM;
  157908. }
  157909. }
  157910. if( rc==SQLITE_OK ){
  157911. memset(pTab, 0, sizeof(Fts3tokTable));
  157912. pTab->pMod = pMod;
  157913. pTab->pTok = pTok;
  157914. *ppVtab = &pTab->base;
  157915. }else{
  157916. if( pTok ){
  157917. pMod->xDestroy(pTok);
  157918. }
  157919. }
  157920. sqlite3_free(azDequote);
  157921. return rc;
  157922. }
  157923. /*
  157924. ** This function does the work for both the xDisconnect and xDestroy methods.
  157925. ** These tables have no persistent representation of their own, so xDisconnect
  157926. ** and xDestroy are identical operations.
  157927. */
  157928. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  157929. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  157930. pTab->pMod->xDestroy(pTab->pTok);
  157931. sqlite3_free(pTab);
  157932. return SQLITE_OK;
  157933. }
  157934. /*
  157935. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  157936. */
  157937. static int fts3tokBestIndexMethod(
  157938. sqlite3_vtab *pVTab,
  157939. sqlite3_index_info *pInfo
  157940. ){
  157941. int i;
  157942. UNUSED_PARAMETER(pVTab);
  157943. for(i=0; i<pInfo->nConstraint; i++){
  157944. if( pInfo->aConstraint[i].usable
  157945. && pInfo->aConstraint[i].iColumn==0
  157946. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  157947. ){
  157948. pInfo->idxNum = 1;
  157949. pInfo->aConstraintUsage[i].argvIndex = 1;
  157950. pInfo->aConstraintUsage[i].omit = 1;
  157951. pInfo->estimatedCost = 1;
  157952. return SQLITE_OK;
  157953. }
  157954. }
  157955. pInfo->idxNum = 0;
  157956. assert( pInfo->estimatedCost>1000000.0 );
  157957. return SQLITE_OK;
  157958. }
  157959. /*
  157960. ** xOpen - Open a cursor.
  157961. */
  157962. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  157963. Fts3tokCursor *pCsr;
  157964. UNUSED_PARAMETER(pVTab);
  157965. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  157966. if( pCsr==0 ){
  157967. return SQLITE_NOMEM;
  157968. }
  157969. memset(pCsr, 0, sizeof(Fts3tokCursor));
  157970. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  157971. return SQLITE_OK;
  157972. }
  157973. /*
  157974. ** Reset the tokenizer cursor passed as the only argument. As if it had
  157975. ** just been returned by fts3tokOpenMethod().
  157976. */
  157977. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  157978. if( pCsr->pCsr ){
  157979. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  157980. pTab->pMod->xClose(pCsr->pCsr);
  157981. pCsr->pCsr = 0;
  157982. }
  157983. sqlite3_free(pCsr->zInput);
  157984. pCsr->zInput = 0;
  157985. pCsr->zToken = 0;
  157986. pCsr->nToken = 0;
  157987. pCsr->iStart = 0;
  157988. pCsr->iEnd = 0;
  157989. pCsr->iPos = 0;
  157990. pCsr->iRowid = 0;
  157991. }
  157992. /*
  157993. ** xClose - Close a cursor.
  157994. */
  157995. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  157996. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  157997. fts3tokResetCursor(pCsr);
  157998. sqlite3_free(pCsr);
  157999. return SQLITE_OK;
  158000. }
  158001. /*
  158002. ** xNext - Advance the cursor to the next row, if any.
  158003. */
  158004. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  158005. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  158006. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  158007. int rc; /* Return code */
  158008. pCsr->iRowid++;
  158009. rc = pTab->pMod->xNext(pCsr->pCsr,
  158010. &pCsr->zToken, &pCsr->nToken,
  158011. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  158012. );
  158013. if( rc!=SQLITE_OK ){
  158014. fts3tokResetCursor(pCsr);
  158015. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  158016. }
  158017. return rc;
  158018. }
  158019. /*
  158020. ** xFilter - Initialize a cursor to point at the start of its data.
  158021. */
  158022. static int fts3tokFilterMethod(
  158023. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  158024. int idxNum, /* Strategy index */
  158025. const char *idxStr, /* Unused */
  158026. int nVal, /* Number of elements in apVal */
  158027. sqlite3_value **apVal /* Arguments for the indexing scheme */
  158028. ){
  158029. int rc = SQLITE_ERROR;
  158030. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  158031. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  158032. UNUSED_PARAMETER(idxStr);
  158033. UNUSED_PARAMETER(nVal);
  158034. fts3tokResetCursor(pCsr);
  158035. if( idxNum==1 ){
  158036. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  158037. int nByte = sqlite3_value_bytes(apVal[0]);
  158038. pCsr->zInput = sqlite3_malloc(nByte+1);
  158039. if( pCsr->zInput==0 ){
  158040. rc = SQLITE_NOMEM;
  158041. }else{
  158042. memcpy(pCsr->zInput, zByte, nByte);
  158043. pCsr->zInput[nByte] = 0;
  158044. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  158045. if( rc==SQLITE_OK ){
  158046. pCsr->pCsr->pTokenizer = pTab->pTok;
  158047. }
  158048. }
  158049. }
  158050. if( rc!=SQLITE_OK ) return rc;
  158051. return fts3tokNextMethod(pCursor);
  158052. }
  158053. /*
  158054. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  158055. */
  158056. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  158057. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  158058. return (pCsr->zToken==0);
  158059. }
  158060. /*
  158061. ** xColumn - Return a column value.
  158062. */
  158063. static int fts3tokColumnMethod(
  158064. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  158065. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  158066. int iCol /* Index of column to read value from */
  158067. ){
  158068. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  158069. /* CREATE TABLE x(input, token, start, end, position) */
  158070. switch( iCol ){
  158071. case 0:
  158072. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  158073. break;
  158074. case 1:
  158075. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  158076. break;
  158077. case 2:
  158078. sqlite3_result_int(pCtx, pCsr->iStart);
  158079. break;
  158080. case 3:
  158081. sqlite3_result_int(pCtx, pCsr->iEnd);
  158082. break;
  158083. default:
  158084. assert( iCol==4 );
  158085. sqlite3_result_int(pCtx, pCsr->iPos);
  158086. break;
  158087. }
  158088. return SQLITE_OK;
  158089. }
  158090. /*
  158091. ** xRowid - Return the current rowid for the cursor.
  158092. */
  158093. static int fts3tokRowidMethod(
  158094. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  158095. sqlite_int64 *pRowid /* OUT: Rowid value */
  158096. ){
  158097. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  158098. *pRowid = (sqlite3_int64)pCsr->iRowid;
  158099. return SQLITE_OK;
  158100. }
  158101. /*
  158102. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  158103. ** if successful or an error code if sqlite3_create_module() fails.
  158104. */
  158105. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  158106. static const sqlite3_module fts3tok_module = {
  158107. 0, /* iVersion */
  158108. fts3tokConnectMethod, /* xCreate */
  158109. fts3tokConnectMethod, /* xConnect */
  158110. fts3tokBestIndexMethod, /* xBestIndex */
  158111. fts3tokDisconnectMethod, /* xDisconnect */
  158112. fts3tokDisconnectMethod, /* xDestroy */
  158113. fts3tokOpenMethod, /* xOpen */
  158114. fts3tokCloseMethod, /* xClose */
  158115. fts3tokFilterMethod, /* xFilter */
  158116. fts3tokNextMethod, /* xNext */
  158117. fts3tokEofMethod, /* xEof */
  158118. fts3tokColumnMethod, /* xColumn */
  158119. fts3tokRowidMethod, /* xRowid */
  158120. 0, /* xUpdate */
  158121. 0, /* xBegin */
  158122. 0, /* xSync */
  158123. 0, /* xCommit */
  158124. 0, /* xRollback */
  158125. 0, /* xFindFunction */
  158126. 0, /* xRename */
  158127. 0, /* xSavepoint */
  158128. 0, /* xRelease */
  158129. 0, /* xRollbackTo */
  158130. 0 /* xShadowName */
  158131. };
  158132. int rc; /* Return code */
  158133. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  158134. return rc;
  158135. }
  158136. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  158137. /************** End of fts3_tokenize_vtab.c **********************************/
  158138. /************** Begin file fts3_write.c **************************************/
  158139. /*
  158140. ** 2009 Oct 23
  158141. **
  158142. ** The author disclaims copyright to this source code. In place of
  158143. ** a legal notice, here is a blessing:
  158144. **
  158145. ** May you do good and not evil.
  158146. ** May you find forgiveness for yourself and forgive others.
  158147. ** May you share freely, never taking more than you give.
  158148. **
  158149. ******************************************************************************
  158150. **
  158151. ** This file is part of the SQLite FTS3 extension module. Specifically,
  158152. ** this file contains code to insert, update and delete rows from FTS3
  158153. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  158154. ** of the sub-routines used to merge segments are also used by the query
  158155. ** code in fts3.c.
  158156. */
  158157. /* #include "fts3Int.h" */
  158158. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  158159. /* #include <string.h> */
  158160. /* #include <assert.h> */
  158161. /* #include <stdlib.h> */
  158162. #define FTS_MAX_APPENDABLE_HEIGHT 16
  158163. /*
  158164. ** When full-text index nodes are loaded from disk, the buffer that they
  158165. ** are loaded into has the following number of bytes of padding at the end
  158166. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  158167. ** of 920 bytes is allocated for it.
  158168. **
  158169. ** This means that if we have a pointer into a buffer containing node data,
  158170. ** it is always safe to read up to two varints from it without risking an
  158171. ** overread, even if the node data is corrupted.
  158172. */
  158173. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  158174. /*
  158175. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  158176. ** memory incrementally instead of all at once. This can be a big performance
  158177. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  158178. ** method before retrieving all query results (as may happen, for example,
  158179. ** if a query has a LIMIT clause).
  158180. **
  158181. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  158182. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  158183. ** The code is written so that the hard lower-limit for each of these values
  158184. ** is 1. Clearly such small values would be inefficient, but can be useful
  158185. ** for testing purposes.
  158186. **
  158187. ** If this module is built with SQLITE_TEST defined, these constants may
  158188. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  158189. ** a Tcl interface to read and write the values.
  158190. */
  158191. #ifdef SQLITE_TEST
  158192. int test_fts3_node_chunksize = (4*1024);
  158193. int test_fts3_node_chunk_threshold = (4*1024)*4;
  158194. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  158195. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  158196. #else
  158197. # define FTS3_NODE_CHUNKSIZE (4*1024)
  158198. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  158199. #endif
  158200. /*
  158201. ** The two values that may be meaningfully bound to the :1 parameter in
  158202. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  158203. */
  158204. #define FTS_STAT_DOCTOTAL 0
  158205. #define FTS_STAT_INCRMERGEHINT 1
  158206. #define FTS_STAT_AUTOINCRMERGE 2
  158207. /*
  158208. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  158209. ** and incremental merge operation that takes place. This is used for
  158210. ** debugging FTS only, it should not usually be turned on in production
  158211. ** systems.
  158212. */
  158213. #ifdef FTS3_LOG_MERGES
  158214. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  158215. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  158216. }
  158217. #else
  158218. #define fts3LogMerge(x, y)
  158219. #endif
  158220. typedef struct PendingList PendingList;
  158221. typedef struct SegmentNode SegmentNode;
  158222. typedef struct SegmentWriter SegmentWriter;
  158223. /*
  158224. ** An instance of the following data structure is used to build doclists
  158225. ** incrementally. See function fts3PendingListAppend() for details.
  158226. */
  158227. struct PendingList {
  158228. int nData;
  158229. char *aData;
  158230. int nSpace;
  158231. sqlite3_int64 iLastDocid;
  158232. sqlite3_int64 iLastCol;
  158233. sqlite3_int64 iLastPos;
  158234. };
  158235. /*
  158236. ** Each cursor has a (possibly empty) linked list of the following objects.
  158237. */
  158238. struct Fts3DeferredToken {
  158239. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  158240. int iCol; /* Column token must occur in */
  158241. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  158242. PendingList *pList; /* Doclist is assembled here */
  158243. };
  158244. /*
  158245. ** An instance of this structure is used to iterate through the terms on
  158246. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  158247. ** this structure are only manipulated by code in this file, opaque handles
  158248. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  158249. ** terms when querying the full-text index. See functions:
  158250. **
  158251. ** sqlite3Fts3SegReaderNew()
  158252. ** sqlite3Fts3SegReaderFree()
  158253. ** sqlite3Fts3SegReaderIterate()
  158254. **
  158255. ** Methods used to manipulate Fts3SegReader structures:
  158256. **
  158257. ** fts3SegReaderNext()
  158258. ** fts3SegReaderFirstDocid()
  158259. ** fts3SegReaderNextDocid()
  158260. */
  158261. struct Fts3SegReader {
  158262. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  158263. u8 bLookup; /* True for a lookup only */
  158264. u8 rootOnly; /* True for a root-only reader */
  158265. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  158266. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  158267. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  158268. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  158269. char *aNode; /* Pointer to node data (or NULL) */
  158270. int nNode; /* Size of buffer at aNode (or 0) */
  158271. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  158272. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  158273. Fts3HashElem **ppNextElem;
  158274. /* Variables set by fts3SegReaderNext(). These may be read directly
  158275. ** by the caller. They are valid from the time SegmentReaderNew() returns
  158276. ** until SegmentReaderNext() returns something other than SQLITE_OK
  158277. ** (i.e. SQLITE_DONE).
  158278. */
  158279. int nTerm; /* Number of bytes in current term */
  158280. char *zTerm; /* Pointer to current term */
  158281. int nTermAlloc; /* Allocated size of zTerm buffer */
  158282. char *aDoclist; /* Pointer to doclist of current entry */
  158283. int nDoclist; /* Size of doclist in current entry */
  158284. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  158285. ** through the current doclist (aDoclist/nDoclist).
  158286. */
  158287. char *pOffsetList;
  158288. int nOffsetList; /* For descending pending seg-readers only */
  158289. sqlite3_int64 iDocid;
  158290. };
  158291. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  158292. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  158293. /*
  158294. ** An instance of this structure is used to create a segment b-tree in the
  158295. ** database. The internal details of this type are only accessed by the
  158296. ** following functions:
  158297. **
  158298. ** fts3SegWriterAdd()
  158299. ** fts3SegWriterFlush()
  158300. ** fts3SegWriterFree()
  158301. */
  158302. struct SegmentWriter {
  158303. SegmentNode *pTree; /* Pointer to interior tree structure */
  158304. sqlite3_int64 iFirst; /* First slot in %_segments written */
  158305. sqlite3_int64 iFree; /* Next free slot in %_segments */
  158306. char *zTerm; /* Pointer to previous term buffer */
  158307. int nTerm; /* Number of bytes in zTerm */
  158308. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  158309. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  158310. int nSize; /* Size of allocation at aData */
  158311. int nData; /* Bytes of data in aData */
  158312. char *aData; /* Pointer to block from malloc() */
  158313. i64 nLeafData; /* Number of bytes of leaf data written */
  158314. };
  158315. /*
  158316. ** Type SegmentNode is used by the following three functions to create
  158317. ** the interior part of the segment b+-tree structures (everything except
  158318. ** the leaf nodes). These functions and type are only ever used by code
  158319. ** within the fts3SegWriterXXX() family of functions described above.
  158320. **
  158321. ** fts3NodeAddTerm()
  158322. ** fts3NodeWrite()
  158323. ** fts3NodeFree()
  158324. **
  158325. ** When a b+tree is written to the database (either as a result of a merge
  158326. ** or the pending-terms table being flushed), leaves are written into the
  158327. ** database file as soon as they are completely populated. The interior of
  158328. ** the tree is assembled in memory and written out only once all leaves have
  158329. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  158330. ** very large, meaning that the interior of the tree consumes relatively
  158331. ** little memory.
  158332. */
  158333. struct SegmentNode {
  158334. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  158335. SegmentNode *pRight; /* Pointer to right-sibling */
  158336. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  158337. int nEntry; /* Number of terms written to node so far */
  158338. char *zTerm; /* Pointer to previous term buffer */
  158339. int nTerm; /* Number of bytes in zTerm */
  158340. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  158341. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  158342. int nData; /* Bytes of valid data so far */
  158343. char *aData; /* Node data */
  158344. };
  158345. /*
  158346. ** Valid values for the second argument to fts3SqlStmt().
  158347. */
  158348. #define SQL_DELETE_CONTENT 0
  158349. #define SQL_IS_EMPTY 1
  158350. #define SQL_DELETE_ALL_CONTENT 2
  158351. #define SQL_DELETE_ALL_SEGMENTS 3
  158352. #define SQL_DELETE_ALL_SEGDIR 4
  158353. #define SQL_DELETE_ALL_DOCSIZE 5
  158354. #define SQL_DELETE_ALL_STAT 6
  158355. #define SQL_SELECT_CONTENT_BY_ROWID 7
  158356. #define SQL_NEXT_SEGMENT_INDEX 8
  158357. #define SQL_INSERT_SEGMENTS 9
  158358. #define SQL_NEXT_SEGMENTS_ID 10
  158359. #define SQL_INSERT_SEGDIR 11
  158360. #define SQL_SELECT_LEVEL 12
  158361. #define SQL_SELECT_LEVEL_RANGE 13
  158362. #define SQL_SELECT_LEVEL_COUNT 14
  158363. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  158364. #define SQL_DELETE_SEGDIR_LEVEL 16
  158365. #define SQL_DELETE_SEGMENTS_RANGE 17
  158366. #define SQL_CONTENT_INSERT 18
  158367. #define SQL_DELETE_DOCSIZE 19
  158368. #define SQL_REPLACE_DOCSIZE 20
  158369. #define SQL_SELECT_DOCSIZE 21
  158370. #define SQL_SELECT_STAT 22
  158371. #define SQL_REPLACE_STAT 23
  158372. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  158373. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  158374. #define SQL_DELETE_SEGDIR_RANGE 26
  158375. #define SQL_SELECT_ALL_LANGID 27
  158376. #define SQL_FIND_MERGE_LEVEL 28
  158377. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  158378. #define SQL_DELETE_SEGDIR_ENTRY 30
  158379. #define SQL_SHIFT_SEGDIR_ENTRY 31
  158380. #define SQL_SELECT_SEGDIR 32
  158381. #define SQL_CHOMP_SEGDIR 33
  158382. #define SQL_SEGMENT_IS_APPENDABLE 34
  158383. #define SQL_SELECT_INDEXES 35
  158384. #define SQL_SELECT_MXLEVEL 36
  158385. #define SQL_SELECT_LEVEL_RANGE2 37
  158386. #define SQL_UPDATE_LEVEL_IDX 38
  158387. #define SQL_UPDATE_LEVEL 39
  158388. /*
  158389. ** This function is used to obtain an SQLite prepared statement handle
  158390. ** for the statement identified by the second argument. If successful,
  158391. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  158392. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  158393. **
  158394. ** If argument apVal is not NULL, then it must point to an array with
  158395. ** at least as many entries as the requested statement has bound
  158396. ** parameters. The values are bound to the statements parameters before
  158397. ** returning.
  158398. */
  158399. static int fts3SqlStmt(
  158400. Fts3Table *p, /* Virtual table handle */
  158401. int eStmt, /* One of the SQL_XXX constants above */
  158402. sqlite3_stmt **pp, /* OUT: Statement handle */
  158403. sqlite3_value **apVal /* Values to bind to statement */
  158404. ){
  158405. const char *azSql[] = {
  158406. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  158407. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  158408. /* 2 */ "DELETE FROM %Q.'%q_content'",
  158409. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  158410. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  158411. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  158412. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  158413. /* 7 */ "SELECT %s WHERE rowid=?",
  158414. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  158415. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  158416. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  158417. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  158418. /* Return segments in order from oldest to newest.*/
  158419. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  158420. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  158421. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  158422. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  158423. "ORDER BY level DESC, idx ASC",
  158424. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  158425. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  158426. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  158427. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  158428. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  158429. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  158430. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  158431. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  158432. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  158433. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  158434. /* 24 */ "",
  158435. /* 25 */ "",
  158436. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  158437. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  158438. /* This statement is used to determine which level to read the input from
  158439. ** when performing an incremental merge. It returns the absolute level number
  158440. ** of the oldest level in the db that contains at least ? segments. Or,
  158441. ** if no level in the FTS index contains more than ? segments, the statement
  158442. ** returns zero rows. */
  158443. /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
  158444. " GROUP BY level HAVING cnt>=?"
  158445. " ORDER BY (level %% 1024) ASC LIMIT 1",
  158446. /* Estimate the upper limit on the number of leaf nodes in a new segment
  158447. ** created by merging the oldest :2 segments from absolute level :1. See
  158448. ** function sqlite3Fts3Incrmerge() for details. */
  158449. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  158450. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  158451. /* SQL_DELETE_SEGDIR_ENTRY
  158452. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  158453. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  158454. /* SQL_SHIFT_SEGDIR_ENTRY
  158455. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  158456. ** to :1. */
  158457. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  158458. /* SQL_SELECT_SEGDIR
  158459. ** Read a single entry from the %_segdir table. The entry from absolute
  158460. ** level :1 with index value :2. */
  158461. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  158462. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  158463. /* SQL_CHOMP_SEGDIR
  158464. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  158465. ** entry located on absolute level :3 with index :4. */
  158466. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  158467. "WHERE level = ? AND idx = ?",
  158468. /* SQL_SEGMENT_IS_APPENDABLE
  158469. ** Return a single row if the segment with end_block=? is appendable. Or
  158470. ** no rows otherwise. */
  158471. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  158472. /* SQL_SELECT_INDEXES
  158473. ** Return the list of valid segment indexes for absolute level ? */
  158474. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  158475. /* SQL_SELECT_MXLEVEL
  158476. ** Return the largest relative level in the FTS index or indexes. */
  158477. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  158478. /* Return segments in order from oldest to newest.*/
  158479. /* 37 */ "SELECT level, idx, end_block "
  158480. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  158481. "ORDER BY level DESC, idx ASC",
  158482. /* Update statements used while promoting segments */
  158483. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  158484. "WHERE level=? AND idx=?",
  158485. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  158486. };
  158487. int rc = SQLITE_OK;
  158488. sqlite3_stmt *pStmt;
  158489. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  158490. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  158491. pStmt = p->aStmt[eStmt];
  158492. if( !pStmt ){
  158493. char *zSql;
  158494. if( eStmt==SQL_CONTENT_INSERT ){
  158495. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  158496. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  158497. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  158498. }else{
  158499. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  158500. }
  158501. if( !zSql ){
  158502. rc = SQLITE_NOMEM;
  158503. }else{
  158504. rc = sqlite3_prepare_v3(p->db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
  158505. &pStmt, NULL);
  158506. sqlite3_free(zSql);
  158507. assert( rc==SQLITE_OK || pStmt==0 );
  158508. p->aStmt[eStmt] = pStmt;
  158509. }
  158510. }
  158511. if( apVal ){
  158512. int i;
  158513. int nParam = sqlite3_bind_parameter_count(pStmt);
  158514. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  158515. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  158516. }
  158517. }
  158518. *pp = pStmt;
  158519. return rc;
  158520. }
  158521. static int fts3SelectDocsize(
  158522. Fts3Table *pTab, /* FTS3 table handle */
  158523. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  158524. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  158525. ){
  158526. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  158527. int rc; /* Return code */
  158528. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  158529. if( rc==SQLITE_OK ){
  158530. sqlite3_bind_int64(pStmt, 1, iDocid);
  158531. rc = sqlite3_step(pStmt);
  158532. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  158533. rc = sqlite3_reset(pStmt);
  158534. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  158535. pStmt = 0;
  158536. }else{
  158537. rc = SQLITE_OK;
  158538. }
  158539. }
  158540. *ppStmt = pStmt;
  158541. return rc;
  158542. }
  158543. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  158544. Fts3Table *pTab, /* Fts3 table handle */
  158545. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  158546. ){
  158547. sqlite3_stmt *pStmt = 0;
  158548. int rc;
  158549. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  158550. if( rc==SQLITE_OK ){
  158551. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  158552. if( sqlite3_step(pStmt)!=SQLITE_ROW
  158553. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  158554. ){
  158555. rc = sqlite3_reset(pStmt);
  158556. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  158557. pStmt = 0;
  158558. }
  158559. }
  158560. *ppStmt = pStmt;
  158561. return rc;
  158562. }
  158563. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  158564. Fts3Table *pTab, /* Fts3 table handle */
  158565. sqlite3_int64 iDocid, /* Docid to read size data for */
  158566. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  158567. ){
  158568. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  158569. }
  158570. /*
  158571. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  158572. ** array apVal[] to the SQL statement identified by eStmt, the statement
  158573. ** is executed.
  158574. **
  158575. ** Returns SQLITE_OK if the statement is successfully executed, or an
  158576. ** SQLite error code otherwise.
  158577. */
  158578. static void fts3SqlExec(
  158579. int *pRC, /* Result code */
  158580. Fts3Table *p, /* The FTS3 table */
  158581. int eStmt, /* Index of statement to evaluate */
  158582. sqlite3_value **apVal /* Parameters to bind */
  158583. ){
  158584. sqlite3_stmt *pStmt;
  158585. int rc;
  158586. if( *pRC ) return;
  158587. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  158588. if( rc==SQLITE_OK ){
  158589. sqlite3_step(pStmt);
  158590. rc = sqlite3_reset(pStmt);
  158591. }
  158592. *pRC = rc;
  158593. }
  158594. /*
  158595. ** This function ensures that the caller has obtained an exclusive
  158596. ** shared-cache table-lock on the %_segdir table. This is required before
  158597. ** writing data to the fts3 table. If this lock is not acquired first, then
  158598. ** the caller may end up attempting to take this lock as part of committing
  158599. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  158600. ** LOCKED_SHAREDCACHEto a COMMIT command.
  158601. **
  158602. ** It is best to avoid this because if FTS3 returns any error when
  158603. ** committing a transaction, the whole transaction will be rolled back.
  158604. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  158605. ** It can still happen if the user locks the underlying tables directly
  158606. ** instead of accessing them via FTS.
  158607. */
  158608. static int fts3Writelock(Fts3Table *p){
  158609. int rc = SQLITE_OK;
  158610. if( p->nPendingData==0 ){
  158611. sqlite3_stmt *pStmt;
  158612. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  158613. if( rc==SQLITE_OK ){
  158614. sqlite3_bind_null(pStmt, 1);
  158615. sqlite3_step(pStmt);
  158616. rc = sqlite3_reset(pStmt);
  158617. }
  158618. }
  158619. return rc;
  158620. }
  158621. /*
  158622. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  158623. ** Within each language id, a separate index is maintained to store the
  158624. ** document terms, and each configured prefix size (configured the FTS
  158625. ** "prefix=" option). And each index consists of multiple levels ("relative
  158626. ** levels").
  158627. **
  158628. ** All three of these values (the language id, the specific index and the
  158629. ** level within the index) are encoded in 64-bit integer values stored
  158630. ** in the %_segdir table on disk. This function is used to convert three
  158631. ** separate component values into the single 64-bit integer value that
  158632. ** can be used to query the %_segdir table.
  158633. **
  158634. ** Specifically, each language-id/index combination is allocated 1024
  158635. ** 64-bit integer level values ("absolute levels"). The main terms index
  158636. ** for language-id 0 is allocate values 0-1023. The first prefix index
  158637. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  158638. ** Language 1 indexes are allocated immediately following language 0.
  158639. **
  158640. ** So, for a system with nPrefix prefix indexes configured, the block of
  158641. ** absolute levels that corresponds to language-id iLangid and index
  158642. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  158643. */
  158644. static sqlite3_int64 getAbsoluteLevel(
  158645. Fts3Table *p, /* FTS3 table handle */
  158646. int iLangid, /* Language id */
  158647. int iIndex, /* Index in p->aIndex[] */
  158648. int iLevel /* Level of segments */
  158649. ){
  158650. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  158651. assert( iLangid>=0 );
  158652. assert( p->nIndex>0 );
  158653. assert( iIndex>=0 && iIndex<p->nIndex );
  158654. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  158655. return iBase + iLevel;
  158656. }
  158657. /*
  158658. ** Set *ppStmt to a statement handle that may be used to iterate through
  158659. ** all rows in the %_segdir table, from oldest to newest. If successful,
  158660. ** return SQLITE_OK. If an error occurs while preparing the statement,
  158661. ** return an SQLite error code.
  158662. **
  158663. ** There is only ever one instance of this SQL statement compiled for
  158664. ** each FTS3 table.
  158665. **
  158666. ** The statement returns the following columns from the %_segdir table:
  158667. **
  158668. ** 0: idx
  158669. ** 1: start_block
  158670. ** 2: leaves_end_block
  158671. ** 3: end_block
  158672. ** 4: root
  158673. */
  158674. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  158675. Fts3Table *p, /* FTS3 table */
  158676. int iLangid, /* Language being queried */
  158677. int iIndex, /* Index for p->aIndex[] */
  158678. int iLevel, /* Level to select (relative level) */
  158679. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  158680. ){
  158681. int rc;
  158682. sqlite3_stmt *pStmt = 0;
  158683. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  158684. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  158685. assert( iIndex>=0 && iIndex<p->nIndex );
  158686. if( iLevel<0 ){
  158687. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  158688. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  158689. if( rc==SQLITE_OK ){
  158690. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  158691. sqlite3_bind_int64(pStmt, 2,
  158692. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  158693. );
  158694. }
  158695. }else{
  158696. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  158697. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  158698. if( rc==SQLITE_OK ){
  158699. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  158700. }
  158701. }
  158702. *ppStmt = pStmt;
  158703. return rc;
  158704. }
  158705. /*
  158706. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  158707. ** if successful, or an SQLite error code otherwise.
  158708. **
  158709. ** This function also serves to allocate the PendingList structure itself.
  158710. ** For example, to create a new PendingList structure containing two
  158711. ** varints:
  158712. **
  158713. ** PendingList *p = 0;
  158714. ** fts3PendingListAppendVarint(&p, 1);
  158715. ** fts3PendingListAppendVarint(&p, 2);
  158716. */
  158717. static int fts3PendingListAppendVarint(
  158718. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  158719. sqlite3_int64 i /* Value to append to data */
  158720. ){
  158721. PendingList *p = *pp;
  158722. /* Allocate or grow the PendingList as required. */
  158723. if( !p ){
  158724. p = sqlite3_malloc(sizeof(*p) + 100);
  158725. if( !p ){
  158726. return SQLITE_NOMEM;
  158727. }
  158728. p->nSpace = 100;
  158729. p->aData = (char *)&p[1];
  158730. p->nData = 0;
  158731. }
  158732. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  158733. int nNew = p->nSpace * 2;
  158734. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  158735. if( !p ){
  158736. sqlite3_free(*pp);
  158737. *pp = 0;
  158738. return SQLITE_NOMEM;
  158739. }
  158740. p->nSpace = nNew;
  158741. p->aData = (char *)&p[1];
  158742. }
  158743. /* Append the new serialized varint to the end of the list. */
  158744. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  158745. p->aData[p->nData] = '\0';
  158746. *pp = p;
  158747. return SQLITE_OK;
  158748. }
  158749. /*
  158750. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  158751. ** is returned if the structure is sqlite3_realloced as part of adding
  158752. ** the entry. Otherwise, zero.
  158753. **
  158754. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  158755. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  158756. ** it is set to SQLITE_OK.
  158757. */
  158758. static int fts3PendingListAppend(
  158759. PendingList **pp, /* IN/OUT: PendingList structure */
  158760. sqlite3_int64 iDocid, /* Docid for entry to add */
  158761. sqlite3_int64 iCol, /* Column for entry to add */
  158762. sqlite3_int64 iPos, /* Position of term for entry to add */
  158763. int *pRc /* OUT: Return code */
  158764. ){
  158765. PendingList *p = *pp;
  158766. int rc = SQLITE_OK;
  158767. assert( !p || p->iLastDocid<=iDocid );
  158768. if( !p || p->iLastDocid!=iDocid ){
  158769. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  158770. if( p ){
  158771. assert( p->nData<p->nSpace );
  158772. assert( p->aData[p->nData]==0 );
  158773. p->nData++;
  158774. }
  158775. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  158776. goto pendinglistappend_out;
  158777. }
  158778. p->iLastCol = -1;
  158779. p->iLastPos = 0;
  158780. p->iLastDocid = iDocid;
  158781. }
  158782. if( iCol>0 && p->iLastCol!=iCol ){
  158783. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  158784. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  158785. ){
  158786. goto pendinglistappend_out;
  158787. }
  158788. p->iLastCol = iCol;
  158789. p->iLastPos = 0;
  158790. }
  158791. if( iCol>=0 ){
  158792. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  158793. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  158794. if( rc==SQLITE_OK ){
  158795. p->iLastPos = iPos;
  158796. }
  158797. }
  158798. pendinglistappend_out:
  158799. *pRc = rc;
  158800. if( p!=*pp ){
  158801. *pp = p;
  158802. return 1;
  158803. }
  158804. return 0;
  158805. }
  158806. /*
  158807. ** Free a PendingList object allocated by fts3PendingListAppend().
  158808. */
  158809. static void fts3PendingListDelete(PendingList *pList){
  158810. sqlite3_free(pList);
  158811. }
  158812. /*
  158813. ** Add an entry to one of the pending-terms hash tables.
  158814. */
  158815. static int fts3PendingTermsAddOne(
  158816. Fts3Table *p,
  158817. int iCol,
  158818. int iPos,
  158819. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  158820. const char *zToken,
  158821. int nToken
  158822. ){
  158823. PendingList *pList;
  158824. int rc = SQLITE_OK;
  158825. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  158826. if( pList ){
  158827. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  158828. }
  158829. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  158830. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  158831. /* Malloc failed while inserting the new entry. This can only
  158832. ** happen if there was no previous entry for this token.
  158833. */
  158834. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  158835. sqlite3_free(pList);
  158836. rc = SQLITE_NOMEM;
  158837. }
  158838. }
  158839. if( rc==SQLITE_OK ){
  158840. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  158841. }
  158842. return rc;
  158843. }
  158844. /*
  158845. ** Tokenize the nul-terminated string zText and add all tokens to the
  158846. ** pending-terms hash-table. The docid used is that currently stored in
  158847. ** p->iPrevDocid, and the column is specified by argument iCol.
  158848. **
  158849. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  158850. */
  158851. static int fts3PendingTermsAdd(
  158852. Fts3Table *p, /* Table into which text will be inserted */
  158853. int iLangid, /* Language id to use */
  158854. const char *zText, /* Text of document to be inserted */
  158855. int iCol, /* Column into which text is being inserted */
  158856. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  158857. ){
  158858. int rc;
  158859. int iStart = 0;
  158860. int iEnd = 0;
  158861. int iPos = 0;
  158862. int nWord = 0;
  158863. char const *zToken;
  158864. int nToken = 0;
  158865. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  158866. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  158867. sqlite3_tokenizer_cursor *pCsr;
  158868. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  158869. const char**,int*,int*,int*,int*);
  158870. assert( pTokenizer && pModule );
  158871. /* If the user has inserted a NULL value, this function may be called with
  158872. ** zText==0. In this case, add zero token entries to the hash table and
  158873. ** return early. */
  158874. if( zText==0 ){
  158875. *pnWord = 0;
  158876. return SQLITE_OK;
  158877. }
  158878. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  158879. if( rc!=SQLITE_OK ){
  158880. return rc;
  158881. }
  158882. xNext = pModule->xNext;
  158883. while( SQLITE_OK==rc
  158884. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  158885. ){
  158886. int i;
  158887. if( iPos>=nWord ) nWord = iPos+1;
  158888. /* Positions cannot be negative; we use -1 as a terminator internally.
  158889. ** Tokens must have a non-zero length.
  158890. */
  158891. if( iPos<0 || !zToken || nToken<=0 ){
  158892. rc = SQLITE_ERROR;
  158893. break;
  158894. }
  158895. /* Add the term to the terms index */
  158896. rc = fts3PendingTermsAddOne(
  158897. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  158898. );
  158899. /* Add the term to each of the prefix indexes that it is not too
  158900. ** short for. */
  158901. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  158902. struct Fts3Index *pIndex = &p->aIndex[i];
  158903. if( nToken<pIndex->nPrefix ) continue;
  158904. rc = fts3PendingTermsAddOne(
  158905. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  158906. );
  158907. }
  158908. }
  158909. pModule->xClose(pCsr);
  158910. *pnWord += nWord;
  158911. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  158912. }
  158913. /*
  158914. ** Calling this function indicates that subsequent calls to
  158915. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  158916. ** contents of the document with docid iDocid.
  158917. */
  158918. static int fts3PendingTermsDocid(
  158919. Fts3Table *p, /* Full-text table handle */
  158920. int bDelete, /* True if this op is a delete */
  158921. int iLangid, /* Language id of row being written */
  158922. sqlite_int64 iDocid /* Docid of row being written */
  158923. ){
  158924. assert( iLangid>=0 );
  158925. assert( bDelete==1 || bDelete==0 );
  158926. /* TODO(shess) Explore whether partially flushing the buffer on
  158927. ** forced-flush would provide better performance. I suspect that if
  158928. ** we ordered the doclists by size and flushed the largest until the
  158929. ** buffer was half empty, that would let the less frequent terms
  158930. ** generate longer doclists.
  158931. */
  158932. if( iDocid<p->iPrevDocid
  158933. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  158934. || p->iPrevLangid!=iLangid
  158935. || p->nPendingData>p->nMaxPendingData
  158936. ){
  158937. int rc = sqlite3Fts3PendingTermsFlush(p);
  158938. if( rc!=SQLITE_OK ) return rc;
  158939. }
  158940. p->iPrevDocid = iDocid;
  158941. p->iPrevLangid = iLangid;
  158942. p->bPrevDelete = bDelete;
  158943. return SQLITE_OK;
  158944. }
  158945. /*
  158946. ** Discard the contents of the pending-terms hash tables.
  158947. */
  158948. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  158949. int i;
  158950. for(i=0; i<p->nIndex; i++){
  158951. Fts3HashElem *pElem;
  158952. Fts3Hash *pHash = &p->aIndex[i].hPending;
  158953. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  158954. PendingList *pList = (PendingList *)fts3HashData(pElem);
  158955. fts3PendingListDelete(pList);
  158956. }
  158957. fts3HashClear(pHash);
  158958. }
  158959. p->nPendingData = 0;
  158960. }
  158961. /*
  158962. ** This function is called by the xUpdate() method as part of an INSERT
  158963. ** operation. It adds entries for each term in the new record to the
  158964. ** pendingTerms hash table.
  158965. **
  158966. ** Argument apVal is the same as the similarly named argument passed to
  158967. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  158968. */
  158969. static int fts3InsertTerms(
  158970. Fts3Table *p,
  158971. int iLangid,
  158972. sqlite3_value **apVal,
  158973. u32 *aSz
  158974. ){
  158975. int i; /* Iterator variable */
  158976. for(i=2; i<p->nColumn+2; i++){
  158977. int iCol = i-2;
  158978. if( p->abNotindexed[iCol]==0 ){
  158979. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  158980. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  158981. if( rc!=SQLITE_OK ){
  158982. return rc;
  158983. }
  158984. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  158985. }
  158986. }
  158987. return SQLITE_OK;
  158988. }
  158989. /*
  158990. ** This function is called by the xUpdate() method for an INSERT operation.
  158991. ** The apVal parameter is passed a copy of the apVal argument passed by
  158992. ** SQLite to the xUpdate() method. i.e:
  158993. **
  158994. ** apVal[0] Not used for INSERT.
  158995. ** apVal[1] rowid
  158996. ** apVal[2] Left-most user-defined column
  158997. ** ...
  158998. ** apVal[p->nColumn+1] Right-most user-defined column
  158999. ** apVal[p->nColumn+2] Hidden column with same name as table
  159000. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  159001. ** apVal[p->nColumn+4] Hidden languageid column
  159002. */
  159003. static int fts3InsertData(
  159004. Fts3Table *p, /* Full-text table */
  159005. sqlite3_value **apVal, /* Array of values to insert */
  159006. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  159007. ){
  159008. int rc; /* Return code */
  159009. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  159010. if( p->zContentTbl ){
  159011. sqlite3_value *pRowid = apVal[p->nColumn+3];
  159012. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  159013. pRowid = apVal[1];
  159014. }
  159015. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  159016. return SQLITE_CONSTRAINT;
  159017. }
  159018. *piDocid = sqlite3_value_int64(pRowid);
  159019. return SQLITE_OK;
  159020. }
  159021. /* Locate the statement handle used to insert data into the %_content
  159022. ** table. The SQL for this statement is:
  159023. **
  159024. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  159025. **
  159026. ** The statement features N '?' variables, where N is the number of user
  159027. ** defined columns in the FTS3 table, plus one for the docid field.
  159028. */
  159029. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  159030. if( rc==SQLITE_OK && p->zLanguageid ){
  159031. rc = sqlite3_bind_int(
  159032. pContentInsert, p->nColumn+2,
  159033. sqlite3_value_int(apVal[p->nColumn+4])
  159034. );
  159035. }
  159036. if( rc!=SQLITE_OK ) return rc;
  159037. /* There is a quirk here. The users INSERT statement may have specified
  159038. ** a value for the "rowid" field, for the "docid" field, or for both.
  159039. ** Which is a problem, since "rowid" and "docid" are aliases for the
  159040. ** same value. For example:
  159041. **
  159042. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  159043. **
  159044. ** In FTS3, this is an error. It is an error to specify non-NULL values
  159045. ** for both docid and some other rowid alias.
  159046. */
  159047. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  159048. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  159049. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  159050. ){
  159051. /* A rowid/docid conflict. */
  159052. return SQLITE_ERROR;
  159053. }
  159054. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  159055. if( rc!=SQLITE_OK ) return rc;
  159056. }
  159057. /* Execute the statement to insert the record. Set *piDocid to the
  159058. ** new docid value.
  159059. */
  159060. sqlite3_step(pContentInsert);
  159061. rc = sqlite3_reset(pContentInsert);
  159062. *piDocid = sqlite3_last_insert_rowid(p->db);
  159063. return rc;
  159064. }
  159065. /*
  159066. ** Remove all data from the FTS3 table. Clear the hash table containing
  159067. ** pending terms.
  159068. */
  159069. static int fts3DeleteAll(Fts3Table *p, int bContent){
  159070. int rc = SQLITE_OK; /* Return code */
  159071. /* Discard the contents of the pending-terms hash table. */
  159072. sqlite3Fts3PendingTermsClear(p);
  159073. /* Delete everything from the shadow tables. Except, leave %_content as
  159074. ** is if bContent is false. */
  159075. assert( p->zContentTbl==0 || bContent==0 );
  159076. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  159077. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  159078. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  159079. if( p->bHasDocsize ){
  159080. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  159081. }
  159082. if( p->bHasStat ){
  159083. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  159084. }
  159085. return rc;
  159086. }
  159087. /*
  159088. **
  159089. */
  159090. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  159091. int iLangid = 0;
  159092. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  159093. return iLangid;
  159094. }
  159095. /*
  159096. ** The first element in the apVal[] array is assumed to contain the docid
  159097. ** (an integer) of a row about to be deleted. Remove all terms from the
  159098. ** full-text index.
  159099. */
  159100. static void fts3DeleteTerms(
  159101. int *pRC, /* Result code */
  159102. Fts3Table *p, /* The FTS table to delete from */
  159103. sqlite3_value *pRowid, /* The docid to be deleted */
  159104. u32 *aSz, /* Sizes of deleted document written here */
  159105. int *pbFound /* OUT: Set to true if row really does exist */
  159106. ){
  159107. int rc;
  159108. sqlite3_stmt *pSelect;
  159109. assert( *pbFound==0 );
  159110. if( *pRC ) return;
  159111. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  159112. if( rc==SQLITE_OK ){
  159113. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  159114. int i;
  159115. int iLangid = langidFromSelect(p, pSelect);
  159116. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  159117. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  159118. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  159119. int iCol = i-1;
  159120. if( p->abNotindexed[iCol]==0 ){
  159121. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  159122. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  159123. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  159124. }
  159125. }
  159126. if( rc!=SQLITE_OK ){
  159127. sqlite3_reset(pSelect);
  159128. *pRC = rc;
  159129. return;
  159130. }
  159131. *pbFound = 1;
  159132. }
  159133. rc = sqlite3_reset(pSelect);
  159134. }else{
  159135. sqlite3_reset(pSelect);
  159136. }
  159137. *pRC = rc;
  159138. }
  159139. /*
  159140. ** Forward declaration to account for the circular dependency between
  159141. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  159142. */
  159143. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  159144. /*
  159145. ** This function allocates a new level iLevel index in the segdir table.
  159146. ** Usually, indexes are allocated within a level sequentially starting
  159147. ** with 0, so the allocated index is one greater than the value returned
  159148. ** by:
  159149. **
  159150. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  159151. **
  159152. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  159153. ** level, they are merged into a single level (iLevel+1) segment and the
  159154. ** allocated index is 0.
  159155. **
  159156. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  159157. ** returned. Otherwise, an SQLite error code is returned.
  159158. */
  159159. static int fts3AllocateSegdirIdx(
  159160. Fts3Table *p,
  159161. int iLangid, /* Language id */
  159162. int iIndex, /* Index for p->aIndex */
  159163. int iLevel,
  159164. int *piIdx
  159165. ){
  159166. int rc; /* Return Code */
  159167. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  159168. int iNext = 0; /* Result of query pNextIdx */
  159169. assert( iLangid>=0 );
  159170. assert( p->nIndex>=1 );
  159171. /* Set variable iNext to the next available segdir index at level iLevel. */
  159172. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  159173. if( rc==SQLITE_OK ){
  159174. sqlite3_bind_int64(
  159175. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  159176. );
  159177. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  159178. iNext = sqlite3_column_int(pNextIdx, 0);
  159179. }
  159180. rc = sqlite3_reset(pNextIdx);
  159181. }
  159182. if( rc==SQLITE_OK ){
  159183. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  159184. ** full, merge all segments in level iLevel into a single iLevel+1
  159185. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  159186. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  159187. */
  159188. if( iNext>=FTS3_MERGE_COUNT ){
  159189. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  159190. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  159191. *piIdx = 0;
  159192. }else{
  159193. *piIdx = iNext;
  159194. }
  159195. }
  159196. return rc;
  159197. }
  159198. /*
  159199. ** The %_segments table is declared as follows:
  159200. **
  159201. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  159202. **
  159203. ** This function reads data from a single row of the %_segments table. The
  159204. ** specific row is identified by the iBlockid parameter. If paBlob is not
  159205. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  159206. ** with the contents of the blob stored in the "block" column of the
  159207. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  159208. ** to the size of the blob in bytes before returning.
  159209. **
  159210. ** If an error occurs, or the table does not contain the specified row,
  159211. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  159212. ** paBlob is non-NULL, then it is the responsibility of the caller to
  159213. ** eventually free the returned buffer.
  159214. **
  159215. ** This function may leave an open sqlite3_blob* handle in the
  159216. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  159217. ** to this function. The handle may be closed by calling the
  159218. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  159219. ** performance improvement, but the blob handle should always be closed
  159220. ** before control is returned to the user (to prevent a lock being held
  159221. ** on the database file for longer than necessary). Thus, any virtual table
  159222. ** method (xFilter etc.) that may directly or indirectly call this function
  159223. ** must call sqlite3Fts3SegmentsClose() before returning.
  159224. */
  159225. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  159226. Fts3Table *p, /* FTS3 table handle */
  159227. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  159228. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  159229. int *pnBlob, /* OUT: Size of blob data */
  159230. int *pnLoad /* OUT: Bytes actually loaded */
  159231. ){
  159232. int rc; /* Return code */
  159233. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  159234. assert( pnBlob );
  159235. if( p->pSegments ){
  159236. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  159237. }else{
  159238. if( 0==p->zSegmentsTbl ){
  159239. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  159240. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  159241. }
  159242. rc = sqlite3_blob_open(
  159243. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  159244. );
  159245. }
  159246. if( rc==SQLITE_OK ){
  159247. int nByte = sqlite3_blob_bytes(p->pSegments);
  159248. *pnBlob = nByte;
  159249. if( paBlob ){
  159250. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  159251. if( !aByte ){
  159252. rc = SQLITE_NOMEM;
  159253. }else{
  159254. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  159255. nByte = FTS3_NODE_CHUNKSIZE;
  159256. *pnLoad = nByte;
  159257. }
  159258. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  159259. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  159260. if( rc!=SQLITE_OK ){
  159261. sqlite3_free(aByte);
  159262. aByte = 0;
  159263. }
  159264. }
  159265. *paBlob = aByte;
  159266. }
  159267. }
  159268. return rc;
  159269. }
  159270. /*
  159271. ** Close the blob handle at p->pSegments, if it is open. See comments above
  159272. ** the sqlite3Fts3ReadBlock() function for details.
  159273. */
  159274. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  159275. sqlite3_blob_close(p->pSegments);
  159276. p->pSegments = 0;
  159277. }
  159278. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  159279. int nRead; /* Number of bytes to read */
  159280. int rc; /* Return code */
  159281. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  159282. rc = sqlite3_blob_read(
  159283. pReader->pBlob,
  159284. &pReader->aNode[pReader->nPopulate],
  159285. nRead,
  159286. pReader->nPopulate
  159287. );
  159288. if( rc==SQLITE_OK ){
  159289. pReader->nPopulate += nRead;
  159290. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  159291. if( pReader->nPopulate==pReader->nNode ){
  159292. sqlite3_blob_close(pReader->pBlob);
  159293. pReader->pBlob = 0;
  159294. pReader->nPopulate = 0;
  159295. }
  159296. }
  159297. return rc;
  159298. }
  159299. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  159300. int rc = SQLITE_OK;
  159301. assert( !pReader->pBlob
  159302. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  159303. );
  159304. while( pReader->pBlob && rc==SQLITE_OK
  159305. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  159306. ){
  159307. rc = fts3SegReaderIncrRead(pReader);
  159308. }
  159309. return rc;
  159310. }
  159311. /*
  159312. ** Set an Fts3SegReader cursor to point at EOF.
  159313. */
  159314. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  159315. if( !fts3SegReaderIsRootOnly(pSeg) ){
  159316. sqlite3_free(pSeg->aNode);
  159317. sqlite3_blob_close(pSeg->pBlob);
  159318. pSeg->pBlob = 0;
  159319. }
  159320. pSeg->aNode = 0;
  159321. }
  159322. /*
  159323. ** Move the iterator passed as the first argument to the next term in the
  159324. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  159325. ** SQLITE_DONE. Otherwise, an SQLite error code.
  159326. */
  159327. static int fts3SegReaderNext(
  159328. Fts3Table *p,
  159329. Fts3SegReader *pReader,
  159330. int bIncr
  159331. ){
  159332. int rc; /* Return code of various sub-routines */
  159333. char *pNext; /* Cursor variable */
  159334. int nPrefix; /* Number of bytes in term prefix */
  159335. int nSuffix; /* Number of bytes in term suffix */
  159336. if( !pReader->aDoclist ){
  159337. pNext = pReader->aNode;
  159338. }else{
  159339. pNext = &pReader->aDoclist[pReader->nDoclist];
  159340. }
  159341. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  159342. if( fts3SegReaderIsPending(pReader) ){
  159343. Fts3HashElem *pElem = *(pReader->ppNextElem);
  159344. sqlite3_free(pReader->aNode);
  159345. pReader->aNode = 0;
  159346. if( pElem ){
  159347. char *aCopy;
  159348. PendingList *pList = (PendingList *)fts3HashData(pElem);
  159349. int nCopy = pList->nData+1;
  159350. pReader->zTerm = (char *)fts3HashKey(pElem);
  159351. pReader->nTerm = fts3HashKeysize(pElem);
  159352. aCopy = (char*)sqlite3_malloc(nCopy);
  159353. if( !aCopy ) return SQLITE_NOMEM;
  159354. memcpy(aCopy, pList->aData, nCopy);
  159355. pReader->nNode = pReader->nDoclist = nCopy;
  159356. pReader->aNode = pReader->aDoclist = aCopy;
  159357. pReader->ppNextElem++;
  159358. assert( pReader->aNode );
  159359. }
  159360. return SQLITE_OK;
  159361. }
  159362. fts3SegReaderSetEof(pReader);
  159363. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  159364. ** blocks have already been traversed. */
  159365. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  159366. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  159367. return SQLITE_OK;
  159368. }
  159369. rc = sqlite3Fts3ReadBlock(
  159370. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  159371. (bIncr ? &pReader->nPopulate : 0)
  159372. );
  159373. if( rc!=SQLITE_OK ) return rc;
  159374. assert( pReader->pBlob==0 );
  159375. if( bIncr && pReader->nPopulate<pReader->nNode ){
  159376. pReader->pBlob = p->pSegments;
  159377. p->pSegments = 0;
  159378. }
  159379. pNext = pReader->aNode;
  159380. }
  159381. assert( !fts3SegReaderIsPending(pReader) );
  159382. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  159383. if( rc!=SQLITE_OK ) return rc;
  159384. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  159385. ** safe (no risk of overread) even if the node data is corrupted. */
  159386. pNext += fts3GetVarint32(pNext, &nPrefix);
  159387. pNext += fts3GetVarint32(pNext, &nSuffix);
  159388. if( nSuffix<=0
  159389. || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix
  159390. || nPrefix>pReader->nTermAlloc
  159391. ){
  159392. return FTS_CORRUPT_VTAB;
  159393. }
  159394. /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are
  159395. ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer
  159396. ** overflow - hence the (i64) casts. */
  159397. if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){
  159398. i64 nNew = ((i64)nPrefix+nSuffix)*2;
  159399. char *zNew = sqlite3_realloc64(pReader->zTerm, nNew);
  159400. if( !zNew ){
  159401. return SQLITE_NOMEM;
  159402. }
  159403. pReader->zTerm = zNew;
  159404. pReader->nTermAlloc = nNew;
  159405. }
  159406. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  159407. if( rc!=SQLITE_OK ) return rc;
  159408. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  159409. pReader->nTerm = nPrefix+nSuffix;
  159410. pNext += nSuffix;
  159411. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  159412. pReader->aDoclist = pNext;
  159413. pReader->pOffsetList = 0;
  159414. /* Check that the doclist does not appear to extend past the end of the
  159415. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  159416. ** of these statements is untrue, then the data structure is corrupt.
  159417. */
  159418. if( (&pReader->aNode[pReader->nNode] - pReader->aDoclist)<pReader->nDoclist
  159419. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  159420. ){
  159421. return FTS_CORRUPT_VTAB;
  159422. }
  159423. return SQLITE_OK;
  159424. }
  159425. /*
  159426. ** Set the SegReader to point to the first docid in the doclist associated
  159427. ** with the current term.
  159428. */
  159429. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  159430. int rc = SQLITE_OK;
  159431. assert( pReader->aDoclist );
  159432. assert( !pReader->pOffsetList );
  159433. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  159434. u8 bEof = 0;
  159435. pReader->iDocid = 0;
  159436. pReader->nOffsetList = 0;
  159437. sqlite3Fts3DoclistPrev(0,
  159438. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  159439. &pReader->iDocid, &pReader->nOffsetList, &bEof
  159440. );
  159441. }else{
  159442. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  159443. if( rc==SQLITE_OK ){
  159444. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  159445. pReader->pOffsetList = &pReader->aDoclist[n];
  159446. }
  159447. }
  159448. return rc;
  159449. }
  159450. /*
  159451. ** Advance the SegReader to point to the next docid in the doclist
  159452. ** associated with the current term.
  159453. **
  159454. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  159455. ** *ppOffsetList is set to point to the first column-offset list
  159456. ** in the doclist entry (i.e. immediately past the docid varint).
  159457. ** *pnOffsetList is set to the length of the set of column-offset
  159458. ** lists, not including the nul-terminator byte. For example:
  159459. */
  159460. static int fts3SegReaderNextDocid(
  159461. Fts3Table *pTab,
  159462. Fts3SegReader *pReader, /* Reader to advance to next docid */
  159463. char **ppOffsetList, /* OUT: Pointer to current position-list */
  159464. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  159465. ){
  159466. int rc = SQLITE_OK;
  159467. char *p = pReader->pOffsetList;
  159468. char c = 0;
  159469. assert( p );
  159470. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  159471. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  159472. ** Pending-terms doclists are always built up in ascending order, so
  159473. ** we have to iterate through them backwards here. */
  159474. u8 bEof = 0;
  159475. if( ppOffsetList ){
  159476. *ppOffsetList = pReader->pOffsetList;
  159477. *pnOffsetList = pReader->nOffsetList - 1;
  159478. }
  159479. sqlite3Fts3DoclistPrev(0,
  159480. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  159481. &pReader->nOffsetList, &bEof
  159482. );
  159483. if( bEof ){
  159484. pReader->pOffsetList = 0;
  159485. }else{
  159486. pReader->pOffsetList = p;
  159487. }
  159488. }else{
  159489. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  159490. /* Pointer p currently points at the first byte of an offset list. The
  159491. ** following block advances it to point one byte past the end of
  159492. ** the same offset list. */
  159493. while( 1 ){
  159494. /* The following line of code (and the "p++" below the while() loop) is
  159495. ** normally all that is required to move pointer p to the desired
  159496. ** position. The exception is if this node is being loaded from disk
  159497. ** incrementally and pointer "p" now points to the first byte past
  159498. ** the populated part of pReader->aNode[].
  159499. */
  159500. while( *p | c ) c = *p++ & 0x80;
  159501. assert( *p==0 );
  159502. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  159503. rc = fts3SegReaderIncrRead(pReader);
  159504. if( rc!=SQLITE_OK ) return rc;
  159505. }
  159506. p++;
  159507. /* If required, populate the output variables with a pointer to and the
  159508. ** size of the previous offset-list.
  159509. */
  159510. if( ppOffsetList ){
  159511. *ppOffsetList = pReader->pOffsetList;
  159512. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  159513. }
  159514. /* List may have been edited in place by fts3EvalNearTrim() */
  159515. while( p<pEnd && *p==0 ) p++;
  159516. /* If there are no more entries in the doclist, set pOffsetList to
  159517. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  159518. ** Fts3SegReader.pOffsetList to point to the next offset list before
  159519. ** returning.
  159520. */
  159521. if( p>=pEnd ){
  159522. pReader->pOffsetList = 0;
  159523. }else{
  159524. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  159525. if( rc==SQLITE_OK ){
  159526. sqlite3_int64 iDelta;
  159527. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  159528. if( pTab->bDescIdx ){
  159529. pReader->iDocid -= iDelta;
  159530. }else{
  159531. pReader->iDocid += iDelta;
  159532. }
  159533. }
  159534. }
  159535. }
  159536. return SQLITE_OK;
  159537. }
  159538. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  159539. Fts3Cursor *pCsr,
  159540. Fts3MultiSegReader *pMsr,
  159541. int *pnOvfl
  159542. ){
  159543. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  159544. int nOvfl = 0;
  159545. int ii;
  159546. int rc = SQLITE_OK;
  159547. int pgsz = p->nPgsz;
  159548. assert( p->bFts4 );
  159549. assert( pgsz>0 );
  159550. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  159551. Fts3SegReader *pReader = pMsr->apSegment[ii];
  159552. if( !fts3SegReaderIsPending(pReader)
  159553. && !fts3SegReaderIsRootOnly(pReader)
  159554. ){
  159555. sqlite3_int64 jj;
  159556. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  159557. int nBlob;
  159558. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  159559. if( rc!=SQLITE_OK ) break;
  159560. if( (nBlob+35)>pgsz ){
  159561. nOvfl += (nBlob + 34)/pgsz;
  159562. }
  159563. }
  159564. }
  159565. }
  159566. *pnOvfl = nOvfl;
  159567. return rc;
  159568. }
  159569. /*
  159570. ** Free all allocations associated with the iterator passed as the
  159571. ** second argument.
  159572. */
  159573. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  159574. if( pReader ){
  159575. if( !fts3SegReaderIsPending(pReader) ){
  159576. sqlite3_free(pReader->zTerm);
  159577. }
  159578. if( !fts3SegReaderIsRootOnly(pReader) ){
  159579. sqlite3_free(pReader->aNode);
  159580. }
  159581. sqlite3_blob_close(pReader->pBlob);
  159582. }
  159583. sqlite3_free(pReader);
  159584. }
  159585. /*
  159586. ** Allocate a new SegReader object.
  159587. */
  159588. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  159589. int iAge, /* Segment "age". */
  159590. int bLookup, /* True for a lookup only */
  159591. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  159592. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  159593. sqlite3_int64 iEndBlock, /* Final block of segment */
  159594. const char *zRoot, /* Buffer containing root node */
  159595. int nRoot, /* Size of buffer containing root node */
  159596. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  159597. ){
  159598. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  159599. int nExtra = 0; /* Bytes to allocate segment root node */
  159600. assert( iStartLeaf<=iEndLeaf );
  159601. if( iStartLeaf==0 ){
  159602. nExtra = nRoot + FTS3_NODE_PADDING;
  159603. }
  159604. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  159605. if( !pReader ){
  159606. return SQLITE_NOMEM;
  159607. }
  159608. memset(pReader, 0, sizeof(Fts3SegReader));
  159609. pReader->iIdx = iAge;
  159610. pReader->bLookup = bLookup!=0;
  159611. pReader->iStartBlock = iStartLeaf;
  159612. pReader->iLeafEndBlock = iEndLeaf;
  159613. pReader->iEndBlock = iEndBlock;
  159614. if( nExtra ){
  159615. /* The entire segment is stored in the root node. */
  159616. pReader->aNode = (char *)&pReader[1];
  159617. pReader->rootOnly = 1;
  159618. pReader->nNode = nRoot;
  159619. memcpy(pReader->aNode, zRoot, nRoot);
  159620. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  159621. }else{
  159622. pReader->iCurrentBlock = iStartLeaf-1;
  159623. }
  159624. *ppReader = pReader;
  159625. return SQLITE_OK;
  159626. }
  159627. /*
  159628. ** This is a comparison function used as a qsort() callback when sorting
  159629. ** an array of pending terms by term. This occurs as part of flushing
  159630. ** the contents of the pending-terms hash table to the database.
  159631. */
  159632. static int SQLITE_CDECL fts3CompareElemByTerm(
  159633. const void *lhs,
  159634. const void *rhs
  159635. ){
  159636. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  159637. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  159638. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  159639. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  159640. int n = (n1<n2 ? n1 : n2);
  159641. int c = memcmp(z1, z2, n);
  159642. if( c==0 ){
  159643. c = n1 - n2;
  159644. }
  159645. return c;
  159646. }
  159647. /*
  159648. ** This function is used to allocate an Fts3SegReader that iterates through
  159649. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  159650. **
  159651. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  159652. ** through each term in the pending-terms table. Or, if isPrefixIter is
  159653. ** non-zero, it iterates through each term and its prefixes. For example, if
  159654. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  159655. ** "firebird", then the iterator visits the following 'terms' (in the order
  159656. ** shown):
  159657. **
  159658. ** f fi fir fire fireb firebi firebir firebird
  159659. ** m my mys mysq mysql
  159660. ** s sq sql sqli sqlit sqlite
  159661. **
  159662. ** Whereas if isPrefixIter is zero, the terms visited are:
  159663. **
  159664. ** firebird mysql sqlite
  159665. */
  159666. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  159667. Fts3Table *p, /* Virtual table handle */
  159668. int iIndex, /* Index for p->aIndex */
  159669. const char *zTerm, /* Term to search for */
  159670. int nTerm, /* Size of buffer zTerm */
  159671. int bPrefix, /* True for a prefix iterator */
  159672. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  159673. ){
  159674. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  159675. Fts3HashElem *pE; /* Iterator variable */
  159676. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  159677. int nElem = 0; /* Size of array at aElem */
  159678. int rc = SQLITE_OK; /* Return Code */
  159679. Fts3Hash *pHash;
  159680. pHash = &p->aIndex[iIndex].hPending;
  159681. if( bPrefix ){
  159682. int nAlloc = 0; /* Size of allocated array at aElem */
  159683. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  159684. char *zKey = (char *)fts3HashKey(pE);
  159685. int nKey = fts3HashKeysize(pE);
  159686. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  159687. if( nElem==nAlloc ){
  159688. Fts3HashElem **aElem2;
  159689. nAlloc += 16;
  159690. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  159691. aElem, nAlloc*sizeof(Fts3HashElem *)
  159692. );
  159693. if( !aElem2 ){
  159694. rc = SQLITE_NOMEM;
  159695. nElem = 0;
  159696. break;
  159697. }
  159698. aElem = aElem2;
  159699. }
  159700. aElem[nElem++] = pE;
  159701. }
  159702. }
  159703. /* If more than one term matches the prefix, sort the Fts3HashElem
  159704. ** objects in term order using qsort(). This uses the same comparison
  159705. ** callback as is used when flushing terms to disk.
  159706. */
  159707. if( nElem>1 ){
  159708. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  159709. }
  159710. }else{
  159711. /* The query is a simple term lookup that matches at most one term in
  159712. ** the index. All that is required is a straight hash-lookup.
  159713. **
  159714. ** Because the stack address of pE may be accessed via the aElem pointer
  159715. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  159716. ** within this entire function, not just this "else{...}" block.
  159717. */
  159718. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  159719. if( pE ){
  159720. aElem = &pE;
  159721. nElem = 1;
  159722. }
  159723. }
  159724. if( nElem>0 ){
  159725. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  159726. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  159727. if( !pReader ){
  159728. rc = SQLITE_NOMEM;
  159729. }else{
  159730. memset(pReader, 0, nByte);
  159731. pReader->iIdx = 0x7FFFFFFF;
  159732. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  159733. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  159734. }
  159735. }
  159736. if( bPrefix ){
  159737. sqlite3_free(aElem);
  159738. }
  159739. *ppReader = pReader;
  159740. return rc;
  159741. }
  159742. /*
  159743. ** Compare the entries pointed to by two Fts3SegReader structures.
  159744. ** Comparison is as follows:
  159745. **
  159746. ** 1) EOF is greater than not EOF.
  159747. **
  159748. ** 2) The current terms (if any) are compared using memcmp(). If one
  159749. ** term is a prefix of another, the longer term is considered the
  159750. ** larger.
  159751. **
  159752. ** 3) By segment age. An older segment is considered larger.
  159753. */
  159754. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  159755. int rc;
  159756. if( pLhs->aNode && pRhs->aNode ){
  159757. int rc2 = pLhs->nTerm - pRhs->nTerm;
  159758. if( rc2<0 ){
  159759. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  159760. }else{
  159761. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  159762. }
  159763. if( rc==0 ){
  159764. rc = rc2;
  159765. }
  159766. }else{
  159767. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  159768. }
  159769. if( rc==0 ){
  159770. rc = pRhs->iIdx - pLhs->iIdx;
  159771. }
  159772. assert( rc!=0 );
  159773. return rc;
  159774. }
  159775. /*
  159776. ** A different comparison function for SegReader structures. In this
  159777. ** version, it is assumed that each SegReader points to an entry in
  159778. ** a doclist for identical terms. Comparison is made as follows:
  159779. **
  159780. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  159781. **
  159782. ** 2) By current docid.
  159783. **
  159784. ** 3) By segment age. An older segment is considered larger.
  159785. */
  159786. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  159787. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  159788. if( rc==0 ){
  159789. if( pLhs->iDocid==pRhs->iDocid ){
  159790. rc = pRhs->iIdx - pLhs->iIdx;
  159791. }else{
  159792. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  159793. }
  159794. }
  159795. assert( pLhs->aNode && pRhs->aNode );
  159796. return rc;
  159797. }
  159798. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  159799. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  159800. if( rc==0 ){
  159801. if( pLhs->iDocid==pRhs->iDocid ){
  159802. rc = pRhs->iIdx - pLhs->iIdx;
  159803. }else{
  159804. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  159805. }
  159806. }
  159807. assert( pLhs->aNode && pRhs->aNode );
  159808. return rc;
  159809. }
  159810. /*
  159811. ** Compare the term that the Fts3SegReader object passed as the first argument
  159812. ** points to with the term specified by arguments zTerm and nTerm.
  159813. **
  159814. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  159815. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  159816. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  159817. */
  159818. static int fts3SegReaderTermCmp(
  159819. Fts3SegReader *pSeg, /* Segment reader object */
  159820. const char *zTerm, /* Term to compare to */
  159821. int nTerm /* Size of term zTerm in bytes */
  159822. ){
  159823. int res = 0;
  159824. if( pSeg->aNode ){
  159825. if( pSeg->nTerm>nTerm ){
  159826. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  159827. }else{
  159828. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  159829. }
  159830. if( res==0 ){
  159831. res = pSeg->nTerm-nTerm;
  159832. }
  159833. }
  159834. return res;
  159835. }
  159836. /*
  159837. ** Argument apSegment is an array of nSegment elements. It is known that
  159838. ** the final (nSegment-nSuspect) members are already in sorted order
  159839. ** (according to the comparison function provided). This function shuffles
  159840. ** the array around until all entries are in sorted order.
  159841. */
  159842. static void fts3SegReaderSort(
  159843. Fts3SegReader **apSegment, /* Array to sort entries of */
  159844. int nSegment, /* Size of apSegment array */
  159845. int nSuspect, /* Unsorted entry count */
  159846. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  159847. ){
  159848. int i; /* Iterator variable */
  159849. assert( nSuspect<=nSegment );
  159850. if( nSuspect==nSegment ) nSuspect--;
  159851. for(i=nSuspect-1; i>=0; i--){
  159852. int j;
  159853. for(j=i; j<(nSegment-1); j++){
  159854. Fts3SegReader *pTmp;
  159855. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  159856. pTmp = apSegment[j+1];
  159857. apSegment[j+1] = apSegment[j];
  159858. apSegment[j] = pTmp;
  159859. }
  159860. }
  159861. #ifndef NDEBUG
  159862. /* Check that the list really is sorted now. */
  159863. for(i=0; i<(nSuspect-1); i++){
  159864. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  159865. }
  159866. #endif
  159867. }
  159868. /*
  159869. ** Insert a record into the %_segments table.
  159870. */
  159871. static int fts3WriteSegment(
  159872. Fts3Table *p, /* Virtual table handle */
  159873. sqlite3_int64 iBlock, /* Block id for new block */
  159874. char *z, /* Pointer to buffer containing block data */
  159875. int n /* Size of buffer z in bytes */
  159876. ){
  159877. sqlite3_stmt *pStmt;
  159878. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  159879. if( rc==SQLITE_OK ){
  159880. sqlite3_bind_int64(pStmt, 1, iBlock);
  159881. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  159882. sqlite3_step(pStmt);
  159883. rc = sqlite3_reset(pStmt);
  159884. sqlite3_bind_null(pStmt, 2);
  159885. }
  159886. return rc;
  159887. }
  159888. /*
  159889. ** Find the largest relative level number in the table. If successful, set
  159890. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  159891. ** set *pnMax to zero and return an SQLite error code.
  159892. */
  159893. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  159894. int rc;
  159895. int mxLevel = 0;
  159896. sqlite3_stmt *pStmt = 0;
  159897. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  159898. if( rc==SQLITE_OK ){
  159899. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  159900. mxLevel = sqlite3_column_int(pStmt, 0);
  159901. }
  159902. rc = sqlite3_reset(pStmt);
  159903. }
  159904. *pnMax = mxLevel;
  159905. return rc;
  159906. }
  159907. /*
  159908. ** Insert a record into the %_segdir table.
  159909. */
  159910. static int fts3WriteSegdir(
  159911. Fts3Table *p, /* Virtual table handle */
  159912. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  159913. int iIdx, /* Value for "idx" field */
  159914. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  159915. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  159916. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  159917. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  159918. char *zRoot, /* Blob value for "root" field */
  159919. int nRoot /* Number of bytes in buffer zRoot */
  159920. ){
  159921. sqlite3_stmt *pStmt;
  159922. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  159923. if( rc==SQLITE_OK ){
  159924. sqlite3_bind_int64(pStmt, 1, iLevel);
  159925. sqlite3_bind_int(pStmt, 2, iIdx);
  159926. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  159927. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  159928. if( nLeafData==0 ){
  159929. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  159930. }else{
  159931. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  159932. if( !zEnd ) return SQLITE_NOMEM;
  159933. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  159934. }
  159935. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  159936. sqlite3_step(pStmt);
  159937. rc = sqlite3_reset(pStmt);
  159938. sqlite3_bind_null(pStmt, 6);
  159939. }
  159940. return rc;
  159941. }
  159942. /*
  159943. ** Return the size of the common prefix (if any) shared by zPrev and
  159944. ** zNext, in bytes. For example,
  159945. **
  159946. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  159947. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  159948. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  159949. */
  159950. static int fts3PrefixCompress(
  159951. const char *zPrev, /* Buffer containing previous term */
  159952. int nPrev, /* Size of buffer zPrev in bytes */
  159953. const char *zNext, /* Buffer containing next term */
  159954. int nNext /* Size of buffer zNext in bytes */
  159955. ){
  159956. int n;
  159957. UNUSED_PARAMETER(nNext);
  159958. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  159959. return n;
  159960. }
  159961. /*
  159962. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  159963. ** (according to memcmp) than the previous term.
  159964. */
  159965. static int fts3NodeAddTerm(
  159966. Fts3Table *p, /* Virtual table handle */
  159967. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  159968. int isCopyTerm, /* True if zTerm/nTerm is transient */
  159969. const char *zTerm, /* Pointer to buffer containing term */
  159970. int nTerm /* Size of term in bytes */
  159971. ){
  159972. SegmentNode *pTree = *ppTree;
  159973. int rc;
  159974. SegmentNode *pNew;
  159975. /* First try to append the term to the current node. Return early if
  159976. ** this is possible.
  159977. */
  159978. if( pTree ){
  159979. int nData = pTree->nData; /* Current size of node in bytes */
  159980. int nReq = nData; /* Required space after adding zTerm */
  159981. int nPrefix; /* Number of bytes of prefix compression */
  159982. int nSuffix; /* Suffix length */
  159983. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  159984. nSuffix = nTerm-nPrefix;
  159985. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  159986. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  159987. if( nReq>p->nNodeSize ){
  159988. /* An unusual case: this is the first term to be added to the node
  159989. ** and the static node buffer (p->nNodeSize bytes) is not large
  159990. ** enough. Use a separately malloced buffer instead This wastes
  159991. ** p->nNodeSize bytes, but since this scenario only comes about when
  159992. ** the database contain two terms that share a prefix of almost 2KB,
  159993. ** this is not expected to be a serious problem.
  159994. */
  159995. assert( pTree->aData==(char *)&pTree[1] );
  159996. pTree->aData = (char *)sqlite3_malloc(nReq);
  159997. if( !pTree->aData ){
  159998. return SQLITE_NOMEM;
  159999. }
  160000. }
  160001. if( pTree->zTerm ){
  160002. /* There is no prefix-length field for first term in a node */
  160003. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  160004. }
  160005. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  160006. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  160007. pTree->nData = nData + nSuffix;
  160008. pTree->nEntry++;
  160009. if( isCopyTerm ){
  160010. if( pTree->nMalloc<nTerm ){
  160011. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  160012. if( !zNew ){
  160013. return SQLITE_NOMEM;
  160014. }
  160015. pTree->nMalloc = nTerm*2;
  160016. pTree->zMalloc = zNew;
  160017. }
  160018. pTree->zTerm = pTree->zMalloc;
  160019. memcpy(pTree->zTerm, zTerm, nTerm);
  160020. pTree->nTerm = nTerm;
  160021. }else{
  160022. pTree->zTerm = (char *)zTerm;
  160023. pTree->nTerm = nTerm;
  160024. }
  160025. return SQLITE_OK;
  160026. }
  160027. }
  160028. /* If control flows to here, it was not possible to append zTerm to the
  160029. ** current node. Create a new node (a right-sibling of the current node).
  160030. ** If this is the first node in the tree, the term is added to it.
  160031. **
  160032. ** Otherwise, the term is not added to the new node, it is left empty for
  160033. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  160034. ** has no parent, one is created here.
  160035. */
  160036. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  160037. if( !pNew ){
  160038. return SQLITE_NOMEM;
  160039. }
  160040. memset(pNew, 0, sizeof(SegmentNode));
  160041. pNew->nData = 1 + FTS3_VARINT_MAX;
  160042. pNew->aData = (char *)&pNew[1];
  160043. if( pTree ){
  160044. SegmentNode *pParent = pTree->pParent;
  160045. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  160046. if( pTree->pParent==0 ){
  160047. pTree->pParent = pParent;
  160048. }
  160049. pTree->pRight = pNew;
  160050. pNew->pLeftmost = pTree->pLeftmost;
  160051. pNew->pParent = pParent;
  160052. pNew->zMalloc = pTree->zMalloc;
  160053. pNew->nMalloc = pTree->nMalloc;
  160054. pTree->zMalloc = 0;
  160055. }else{
  160056. pNew->pLeftmost = pNew;
  160057. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  160058. }
  160059. *ppTree = pNew;
  160060. return rc;
  160061. }
  160062. /*
  160063. ** Helper function for fts3NodeWrite().
  160064. */
  160065. static int fts3TreeFinishNode(
  160066. SegmentNode *pTree,
  160067. int iHeight,
  160068. sqlite3_int64 iLeftChild
  160069. ){
  160070. int nStart;
  160071. assert( iHeight>=1 && iHeight<128 );
  160072. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  160073. pTree->aData[nStart] = (char)iHeight;
  160074. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  160075. return nStart;
  160076. }
  160077. /*
  160078. ** Write the buffer for the segment node pTree and all of its peers to the
  160079. ** database. Then call this function recursively to write the parent of
  160080. ** pTree and its peers to the database.
  160081. **
  160082. ** Except, if pTree is a root node, do not write it to the database. Instead,
  160083. ** set output variables *paRoot and *pnRoot to contain the root node.
  160084. **
  160085. ** If successful, SQLITE_OK is returned and output variable *piLast is
  160086. ** set to the largest blockid written to the database (or zero if no
  160087. ** blocks were written to the db). Otherwise, an SQLite error code is
  160088. ** returned.
  160089. */
  160090. static int fts3NodeWrite(
  160091. Fts3Table *p, /* Virtual table handle */
  160092. SegmentNode *pTree, /* SegmentNode handle */
  160093. int iHeight, /* Height of this node in tree */
  160094. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  160095. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  160096. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  160097. char **paRoot, /* OUT: Data for root node */
  160098. int *pnRoot /* OUT: Size of root node in bytes */
  160099. ){
  160100. int rc = SQLITE_OK;
  160101. if( !pTree->pParent ){
  160102. /* Root node of the tree. */
  160103. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  160104. *piLast = iFree-1;
  160105. *pnRoot = pTree->nData - nStart;
  160106. *paRoot = &pTree->aData[nStart];
  160107. }else{
  160108. SegmentNode *pIter;
  160109. sqlite3_int64 iNextFree = iFree;
  160110. sqlite3_int64 iNextLeaf = iLeaf;
  160111. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  160112. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  160113. int nWrite = pIter->nData - nStart;
  160114. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  160115. iNextFree++;
  160116. iNextLeaf += (pIter->nEntry+1);
  160117. }
  160118. if( rc==SQLITE_OK ){
  160119. assert( iNextLeaf==iFree );
  160120. rc = fts3NodeWrite(
  160121. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  160122. );
  160123. }
  160124. }
  160125. return rc;
  160126. }
  160127. /*
  160128. ** Free all memory allocations associated with the tree pTree.
  160129. */
  160130. static void fts3NodeFree(SegmentNode *pTree){
  160131. if( pTree ){
  160132. SegmentNode *p = pTree->pLeftmost;
  160133. fts3NodeFree(p->pParent);
  160134. while( p ){
  160135. SegmentNode *pRight = p->pRight;
  160136. if( p->aData!=(char *)&p[1] ){
  160137. sqlite3_free(p->aData);
  160138. }
  160139. assert( pRight==0 || p->zMalloc==0 );
  160140. sqlite3_free(p->zMalloc);
  160141. sqlite3_free(p);
  160142. p = pRight;
  160143. }
  160144. }
  160145. }
  160146. /*
  160147. ** Add a term to the segment being constructed by the SegmentWriter object
  160148. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  160149. ** be passed NULL. This function will allocate a new SegmentWriter object
  160150. ** and return it via the input/output variable *ppWriter in this case.
  160151. **
  160152. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  160153. */
  160154. static int fts3SegWriterAdd(
  160155. Fts3Table *p, /* Virtual table handle */
  160156. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  160157. int isCopyTerm, /* True if buffer zTerm must be copied */
  160158. const char *zTerm, /* Pointer to buffer containing term */
  160159. int nTerm, /* Size of term in bytes */
  160160. const char *aDoclist, /* Pointer to buffer containing doclist */
  160161. int nDoclist /* Size of doclist in bytes */
  160162. ){
  160163. int nPrefix; /* Size of term prefix in bytes */
  160164. int nSuffix; /* Size of term suffix in bytes */
  160165. int nReq; /* Number of bytes required on leaf page */
  160166. int nData;
  160167. SegmentWriter *pWriter = *ppWriter;
  160168. if( !pWriter ){
  160169. int rc;
  160170. sqlite3_stmt *pStmt;
  160171. /* Allocate the SegmentWriter structure */
  160172. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  160173. if( !pWriter ) return SQLITE_NOMEM;
  160174. memset(pWriter, 0, sizeof(SegmentWriter));
  160175. *ppWriter = pWriter;
  160176. /* Allocate a buffer in which to accumulate data */
  160177. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  160178. if( !pWriter->aData ) return SQLITE_NOMEM;
  160179. pWriter->nSize = p->nNodeSize;
  160180. /* Find the next free blockid in the %_segments table */
  160181. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  160182. if( rc!=SQLITE_OK ) return rc;
  160183. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  160184. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  160185. pWriter->iFirst = pWriter->iFree;
  160186. }
  160187. rc = sqlite3_reset(pStmt);
  160188. if( rc!=SQLITE_OK ) return rc;
  160189. }
  160190. nData = pWriter->nData;
  160191. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  160192. nSuffix = nTerm-nPrefix;
  160193. /* Figure out how many bytes are required by this new entry */
  160194. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  160195. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  160196. nSuffix + /* Term suffix */
  160197. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  160198. nDoclist; /* Doclist data */
  160199. if( nData>0 && nData+nReq>p->nNodeSize ){
  160200. int rc;
  160201. /* The current leaf node is full. Write it out to the database. */
  160202. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  160203. if( rc!=SQLITE_OK ) return rc;
  160204. p->nLeafAdd++;
  160205. /* Add the current term to the interior node tree. The term added to
  160206. ** the interior tree must:
  160207. **
  160208. ** a) be greater than the largest term on the leaf node just written
  160209. ** to the database (still available in pWriter->zTerm), and
  160210. **
  160211. ** b) be less than or equal to the term about to be added to the new
  160212. ** leaf node (zTerm/nTerm).
  160213. **
  160214. ** In other words, it must be the prefix of zTerm 1 byte longer than
  160215. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  160216. */
  160217. assert( nPrefix<nTerm );
  160218. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  160219. if( rc!=SQLITE_OK ) return rc;
  160220. nData = 0;
  160221. pWriter->nTerm = 0;
  160222. nPrefix = 0;
  160223. nSuffix = nTerm;
  160224. nReq = 1 + /* varint containing prefix size */
  160225. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  160226. nTerm + /* Term suffix */
  160227. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  160228. nDoclist; /* Doclist data */
  160229. }
  160230. /* Increase the total number of bytes written to account for the new entry. */
  160231. pWriter->nLeafData += nReq;
  160232. /* If the buffer currently allocated is too small for this entry, realloc
  160233. ** the buffer to make it large enough.
  160234. */
  160235. if( nReq>pWriter->nSize ){
  160236. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  160237. if( !aNew ) return SQLITE_NOMEM;
  160238. pWriter->aData = aNew;
  160239. pWriter->nSize = nReq;
  160240. }
  160241. assert( nData+nReq<=pWriter->nSize );
  160242. /* Append the prefix-compressed term and doclist to the buffer. */
  160243. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  160244. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  160245. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  160246. nData += nSuffix;
  160247. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  160248. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  160249. pWriter->nData = nData + nDoclist;
  160250. /* Save the current term so that it can be used to prefix-compress the next.
  160251. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  160252. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  160253. ** store a copy of the pointer.
  160254. */
  160255. if( isCopyTerm ){
  160256. if( nTerm>pWriter->nMalloc ){
  160257. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  160258. if( !zNew ){
  160259. return SQLITE_NOMEM;
  160260. }
  160261. pWriter->nMalloc = nTerm*2;
  160262. pWriter->zMalloc = zNew;
  160263. pWriter->zTerm = zNew;
  160264. }
  160265. assert( pWriter->zTerm==pWriter->zMalloc );
  160266. memcpy(pWriter->zTerm, zTerm, nTerm);
  160267. }else{
  160268. pWriter->zTerm = (char *)zTerm;
  160269. }
  160270. pWriter->nTerm = nTerm;
  160271. return SQLITE_OK;
  160272. }
  160273. /*
  160274. ** Flush all data associated with the SegmentWriter object pWriter to the
  160275. ** database. This function must be called after all terms have been added
  160276. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  160277. ** returned. Otherwise, an SQLite error code.
  160278. */
  160279. static int fts3SegWriterFlush(
  160280. Fts3Table *p, /* Virtual table handle */
  160281. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  160282. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  160283. int iIdx /* Value for 'idx' column of %_segdir */
  160284. ){
  160285. int rc; /* Return code */
  160286. if( pWriter->pTree ){
  160287. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  160288. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  160289. char *zRoot = NULL; /* Pointer to buffer containing root node */
  160290. int nRoot = 0; /* Size of buffer zRoot */
  160291. iLastLeaf = pWriter->iFree;
  160292. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  160293. if( rc==SQLITE_OK ){
  160294. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  160295. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  160296. }
  160297. if( rc==SQLITE_OK ){
  160298. rc = fts3WriteSegdir(p, iLevel, iIdx,
  160299. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  160300. }
  160301. }else{
  160302. /* The entire tree fits on the root node. Write it to the segdir table. */
  160303. rc = fts3WriteSegdir(p, iLevel, iIdx,
  160304. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  160305. }
  160306. p->nLeafAdd++;
  160307. return rc;
  160308. }
  160309. /*
  160310. ** Release all memory held by the SegmentWriter object passed as the
  160311. ** first argument.
  160312. */
  160313. static void fts3SegWriterFree(SegmentWriter *pWriter){
  160314. if( pWriter ){
  160315. sqlite3_free(pWriter->aData);
  160316. sqlite3_free(pWriter->zMalloc);
  160317. fts3NodeFree(pWriter->pTree);
  160318. sqlite3_free(pWriter);
  160319. }
  160320. }
  160321. /*
  160322. ** The first value in the apVal[] array is assumed to contain an integer.
  160323. ** This function tests if there exist any documents with docid values that
  160324. ** are different from that integer. i.e. if deleting the document with docid
  160325. ** pRowid would mean the FTS3 table were empty.
  160326. **
  160327. ** If successful, *pisEmpty is set to true if the table is empty except for
  160328. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  160329. ** error occurs, an SQLite error code is returned.
  160330. */
  160331. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  160332. sqlite3_stmt *pStmt;
  160333. int rc;
  160334. if( p->zContentTbl ){
  160335. /* If using the content=xxx option, assume the table is never empty */
  160336. *pisEmpty = 0;
  160337. rc = SQLITE_OK;
  160338. }else{
  160339. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  160340. if( rc==SQLITE_OK ){
  160341. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  160342. *pisEmpty = sqlite3_column_int(pStmt, 0);
  160343. }
  160344. rc = sqlite3_reset(pStmt);
  160345. }
  160346. }
  160347. return rc;
  160348. }
  160349. /*
  160350. ** Set *pnMax to the largest segment level in the database for the index
  160351. ** iIndex.
  160352. **
  160353. ** Segment levels are stored in the 'level' column of the %_segdir table.
  160354. **
  160355. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  160356. */
  160357. static int fts3SegmentMaxLevel(
  160358. Fts3Table *p,
  160359. int iLangid,
  160360. int iIndex,
  160361. sqlite3_int64 *pnMax
  160362. ){
  160363. sqlite3_stmt *pStmt;
  160364. int rc;
  160365. assert( iIndex>=0 && iIndex<p->nIndex );
  160366. /* Set pStmt to the compiled version of:
  160367. **
  160368. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  160369. **
  160370. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  160371. */
  160372. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  160373. if( rc!=SQLITE_OK ) return rc;
  160374. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  160375. sqlite3_bind_int64(pStmt, 2,
  160376. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  160377. );
  160378. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  160379. *pnMax = sqlite3_column_int64(pStmt, 0);
  160380. }
  160381. return sqlite3_reset(pStmt);
  160382. }
  160383. /*
  160384. ** iAbsLevel is an absolute level that may be assumed to exist within
  160385. ** the database. This function checks if it is the largest level number
  160386. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  160387. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  160388. ** is returned. If an error occurs, an error code is returned and the
  160389. ** final value of *pbMax is undefined.
  160390. */
  160391. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  160392. /* Set pStmt to the compiled version of:
  160393. **
  160394. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  160395. **
  160396. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  160397. */
  160398. sqlite3_stmt *pStmt;
  160399. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  160400. if( rc!=SQLITE_OK ) return rc;
  160401. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  160402. sqlite3_bind_int64(pStmt, 2,
  160403. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  160404. );
  160405. *pbMax = 0;
  160406. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  160407. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  160408. }
  160409. return sqlite3_reset(pStmt);
  160410. }
  160411. /*
  160412. ** Delete all entries in the %_segments table associated with the segment
  160413. ** opened with seg-reader pSeg. This function does not affect the contents
  160414. ** of the %_segdir table.
  160415. */
  160416. static int fts3DeleteSegment(
  160417. Fts3Table *p, /* FTS table handle */
  160418. Fts3SegReader *pSeg /* Segment to delete */
  160419. ){
  160420. int rc = SQLITE_OK; /* Return code */
  160421. if( pSeg->iStartBlock ){
  160422. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  160423. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  160424. if( rc==SQLITE_OK ){
  160425. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  160426. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  160427. sqlite3_step(pDelete);
  160428. rc = sqlite3_reset(pDelete);
  160429. }
  160430. }
  160431. return rc;
  160432. }
  160433. /*
  160434. ** This function is used after merging multiple segments into a single large
  160435. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  160436. ** it:
  160437. **
  160438. ** 1) Deletes all %_segments entries for the segments associated with
  160439. ** each of the SegReader objects in the array passed as the third
  160440. ** argument, and
  160441. **
  160442. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  160443. ** entries regardless of level if (iLevel<0).
  160444. **
  160445. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  160446. */
  160447. static int fts3DeleteSegdir(
  160448. Fts3Table *p, /* Virtual table handle */
  160449. int iLangid, /* Language id */
  160450. int iIndex, /* Index for p->aIndex */
  160451. int iLevel, /* Level of %_segdir entries to delete */
  160452. Fts3SegReader **apSegment, /* Array of SegReader objects */
  160453. int nReader /* Size of array apSegment */
  160454. ){
  160455. int rc = SQLITE_OK; /* Return Code */
  160456. int i; /* Iterator variable */
  160457. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  160458. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  160459. rc = fts3DeleteSegment(p, apSegment[i]);
  160460. }
  160461. if( rc!=SQLITE_OK ){
  160462. return rc;
  160463. }
  160464. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  160465. if( iLevel==FTS3_SEGCURSOR_ALL ){
  160466. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  160467. if( rc==SQLITE_OK ){
  160468. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  160469. sqlite3_bind_int64(pDelete, 2,
  160470. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  160471. );
  160472. }
  160473. }else{
  160474. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  160475. if( rc==SQLITE_OK ){
  160476. sqlite3_bind_int64(
  160477. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  160478. );
  160479. }
  160480. }
  160481. if( rc==SQLITE_OK ){
  160482. sqlite3_step(pDelete);
  160483. rc = sqlite3_reset(pDelete);
  160484. }
  160485. return rc;
  160486. }
  160487. /*
  160488. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  160489. ** a position list that may (or may not) feature multiple columns. This
  160490. ** function adjusts the pointer *ppList and the length *pnList so that they
  160491. ** identify the subset of the position list that corresponds to column iCol.
  160492. **
  160493. ** If there are no entries in the input position list for column iCol, then
  160494. ** *pnList is set to zero before returning.
  160495. **
  160496. ** If parameter bZero is non-zero, then any part of the input list following
  160497. ** the end of the output list is zeroed before returning.
  160498. */
  160499. static void fts3ColumnFilter(
  160500. int iCol, /* Column to filter on */
  160501. int bZero, /* Zero out anything following *ppList */
  160502. char **ppList, /* IN/OUT: Pointer to position list */
  160503. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  160504. ){
  160505. char *pList = *ppList;
  160506. int nList = *pnList;
  160507. char *pEnd = &pList[nList];
  160508. int iCurrent = 0;
  160509. char *p = pList;
  160510. assert( iCol>=0 );
  160511. while( 1 ){
  160512. char c = 0;
  160513. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  160514. if( iCol==iCurrent ){
  160515. nList = (int)(p - pList);
  160516. break;
  160517. }
  160518. nList -= (int)(p - pList);
  160519. pList = p;
  160520. if( nList==0 ){
  160521. break;
  160522. }
  160523. p = &pList[1];
  160524. p += fts3GetVarint32(p, &iCurrent);
  160525. }
  160526. if( bZero && &pList[nList]!=pEnd ){
  160527. memset(&pList[nList], 0, pEnd - &pList[nList]);
  160528. }
  160529. *ppList = pList;
  160530. *pnList = nList;
  160531. }
  160532. /*
  160533. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  160534. ** existing data). Grow the buffer if required.
  160535. **
  160536. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  160537. ** trying to resize the buffer, return SQLITE_NOMEM.
  160538. */
  160539. static int fts3MsrBufferData(
  160540. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  160541. char *pList,
  160542. int nList
  160543. ){
  160544. if( nList>pMsr->nBuffer ){
  160545. char *pNew;
  160546. pMsr->nBuffer = nList*2;
  160547. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  160548. if( !pNew ) return SQLITE_NOMEM;
  160549. pMsr->aBuffer = pNew;
  160550. }
  160551. memcpy(pMsr->aBuffer, pList, nList);
  160552. return SQLITE_OK;
  160553. }
  160554. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  160555. Fts3Table *p, /* Virtual table handle */
  160556. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  160557. sqlite3_int64 *piDocid, /* OUT: Docid value */
  160558. char **paPoslist, /* OUT: Pointer to position list */
  160559. int *pnPoslist /* OUT: Size of position list in bytes */
  160560. ){
  160561. int nMerge = pMsr->nAdvance;
  160562. Fts3SegReader **apSegment = pMsr->apSegment;
  160563. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  160564. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  160565. );
  160566. if( nMerge==0 ){
  160567. *paPoslist = 0;
  160568. return SQLITE_OK;
  160569. }
  160570. while( 1 ){
  160571. Fts3SegReader *pSeg;
  160572. pSeg = pMsr->apSegment[0];
  160573. if( pSeg->pOffsetList==0 ){
  160574. *paPoslist = 0;
  160575. break;
  160576. }else{
  160577. int rc;
  160578. char *pList;
  160579. int nList;
  160580. int j;
  160581. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  160582. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  160583. j = 1;
  160584. while( rc==SQLITE_OK
  160585. && j<nMerge
  160586. && apSegment[j]->pOffsetList
  160587. && apSegment[j]->iDocid==iDocid
  160588. ){
  160589. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  160590. j++;
  160591. }
  160592. if( rc!=SQLITE_OK ) return rc;
  160593. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  160594. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  160595. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  160596. if( rc!=SQLITE_OK ) return rc;
  160597. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  160598. pList = pMsr->aBuffer;
  160599. }
  160600. if( pMsr->iColFilter>=0 ){
  160601. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  160602. }
  160603. if( nList>0 ){
  160604. *paPoslist = pList;
  160605. *piDocid = iDocid;
  160606. *pnPoslist = nList;
  160607. break;
  160608. }
  160609. }
  160610. }
  160611. return SQLITE_OK;
  160612. }
  160613. static int fts3SegReaderStart(
  160614. Fts3Table *p, /* Virtual table handle */
  160615. Fts3MultiSegReader *pCsr, /* Cursor object */
  160616. const char *zTerm, /* Term searched for (or NULL) */
  160617. int nTerm /* Length of zTerm in bytes */
  160618. ){
  160619. int i;
  160620. int nSeg = pCsr->nSegment;
  160621. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  160622. ** for, then advance each segment iterator until it points to a term of
  160623. ** equal or greater value than the specified term. This prevents many
  160624. ** unnecessary merge/sort operations for the case where single segment
  160625. ** b-tree leaf nodes contain more than one term.
  160626. */
  160627. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  160628. int res = 0;
  160629. Fts3SegReader *pSeg = pCsr->apSegment[i];
  160630. do {
  160631. int rc = fts3SegReaderNext(p, pSeg, 0);
  160632. if( rc!=SQLITE_OK ) return rc;
  160633. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  160634. if( pSeg->bLookup && res!=0 ){
  160635. fts3SegReaderSetEof(pSeg);
  160636. }
  160637. }
  160638. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  160639. return SQLITE_OK;
  160640. }
  160641. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  160642. Fts3Table *p, /* Virtual table handle */
  160643. Fts3MultiSegReader *pCsr, /* Cursor object */
  160644. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  160645. ){
  160646. pCsr->pFilter = pFilter;
  160647. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  160648. }
  160649. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  160650. Fts3Table *p, /* Virtual table handle */
  160651. Fts3MultiSegReader *pCsr, /* Cursor object */
  160652. int iCol, /* Column to match on. */
  160653. const char *zTerm, /* Term to iterate through a doclist for */
  160654. int nTerm /* Number of bytes in zTerm */
  160655. ){
  160656. int i;
  160657. int rc;
  160658. int nSegment = pCsr->nSegment;
  160659. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  160660. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  160661. );
  160662. assert( pCsr->pFilter==0 );
  160663. assert( zTerm && nTerm>0 );
  160664. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  160665. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  160666. if( rc!=SQLITE_OK ) return rc;
  160667. /* Determine how many of the segments actually point to zTerm/nTerm. */
  160668. for(i=0; i<nSegment; i++){
  160669. Fts3SegReader *pSeg = pCsr->apSegment[i];
  160670. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  160671. break;
  160672. }
  160673. }
  160674. pCsr->nAdvance = i;
  160675. /* Advance each of the segments to point to the first docid. */
  160676. for(i=0; i<pCsr->nAdvance; i++){
  160677. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  160678. if( rc!=SQLITE_OK ) return rc;
  160679. }
  160680. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  160681. assert( iCol<0 || iCol<p->nColumn );
  160682. pCsr->iColFilter = iCol;
  160683. return SQLITE_OK;
  160684. }
  160685. /*
  160686. ** This function is called on a MultiSegReader that has been started using
  160687. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  160688. ** have been made. Calling this function puts the MultiSegReader in such
  160689. ** a state that if the next two calls are:
  160690. **
  160691. ** sqlite3Fts3SegReaderStart()
  160692. ** sqlite3Fts3SegReaderStep()
  160693. **
  160694. ** then the entire doclist for the term is available in
  160695. ** MultiSegReader.aDoclist/nDoclist.
  160696. */
  160697. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  160698. int i; /* Used to iterate through segment-readers */
  160699. assert( pCsr->zTerm==0 );
  160700. assert( pCsr->nTerm==0 );
  160701. assert( pCsr->aDoclist==0 );
  160702. assert( pCsr->nDoclist==0 );
  160703. pCsr->nAdvance = 0;
  160704. pCsr->bRestart = 1;
  160705. for(i=0; i<pCsr->nSegment; i++){
  160706. pCsr->apSegment[i]->pOffsetList = 0;
  160707. pCsr->apSegment[i]->nOffsetList = 0;
  160708. pCsr->apSegment[i]->iDocid = 0;
  160709. }
  160710. return SQLITE_OK;
  160711. }
  160712. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  160713. Fts3Table *p, /* Virtual table handle */
  160714. Fts3MultiSegReader *pCsr /* Cursor object */
  160715. ){
  160716. int rc = SQLITE_OK;
  160717. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  160718. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  160719. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  160720. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  160721. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  160722. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  160723. Fts3SegReader **apSegment = pCsr->apSegment;
  160724. int nSegment = pCsr->nSegment;
  160725. Fts3SegFilter *pFilter = pCsr->pFilter;
  160726. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  160727. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  160728. );
  160729. if( pCsr->nSegment==0 ) return SQLITE_OK;
  160730. do {
  160731. int nMerge;
  160732. int i;
  160733. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  160734. ** forward. Then sort the list in order of current term again.
  160735. */
  160736. for(i=0; i<pCsr->nAdvance; i++){
  160737. Fts3SegReader *pSeg = apSegment[i];
  160738. if( pSeg->bLookup ){
  160739. fts3SegReaderSetEof(pSeg);
  160740. }else{
  160741. rc = fts3SegReaderNext(p, pSeg, 0);
  160742. }
  160743. if( rc!=SQLITE_OK ) return rc;
  160744. }
  160745. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  160746. pCsr->nAdvance = 0;
  160747. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  160748. assert( rc==SQLITE_OK );
  160749. if( apSegment[0]->aNode==0 ) break;
  160750. pCsr->nTerm = apSegment[0]->nTerm;
  160751. pCsr->zTerm = apSegment[0]->zTerm;
  160752. /* If this is a prefix-search, and if the term that apSegment[0] points
  160753. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  160754. ** required callbacks have been made. In this case exit early.
  160755. **
  160756. ** Similarly, if this is a search for an exact match, and the first term
  160757. ** of segment apSegment[0] is not a match, exit early.
  160758. */
  160759. if( pFilter->zTerm && !isScan ){
  160760. if( pCsr->nTerm<pFilter->nTerm
  160761. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  160762. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  160763. ){
  160764. break;
  160765. }
  160766. }
  160767. nMerge = 1;
  160768. while( nMerge<nSegment
  160769. && apSegment[nMerge]->aNode
  160770. && apSegment[nMerge]->nTerm==pCsr->nTerm
  160771. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  160772. ){
  160773. nMerge++;
  160774. }
  160775. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  160776. if( nMerge==1
  160777. && !isIgnoreEmpty
  160778. && !isFirst
  160779. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  160780. ){
  160781. pCsr->nDoclist = apSegment[0]->nDoclist;
  160782. if( fts3SegReaderIsPending(apSegment[0]) ){
  160783. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  160784. pCsr->aDoclist = pCsr->aBuffer;
  160785. }else{
  160786. pCsr->aDoclist = apSegment[0]->aDoclist;
  160787. }
  160788. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  160789. }else{
  160790. int nDoclist = 0; /* Size of doclist */
  160791. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  160792. /* The current term of the first nMerge entries in the array
  160793. ** of Fts3SegReader objects is the same. The doclists must be merged
  160794. ** and a single term returned with the merged doclist.
  160795. */
  160796. for(i=0; i<nMerge; i++){
  160797. fts3SegReaderFirstDocid(p, apSegment[i]);
  160798. }
  160799. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  160800. while( apSegment[0]->pOffsetList ){
  160801. int j; /* Number of segments that share a docid */
  160802. char *pList = 0;
  160803. int nList = 0;
  160804. int nByte;
  160805. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  160806. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  160807. j = 1;
  160808. while( j<nMerge
  160809. && apSegment[j]->pOffsetList
  160810. && apSegment[j]->iDocid==iDocid
  160811. ){
  160812. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  160813. j++;
  160814. }
  160815. if( isColFilter ){
  160816. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  160817. }
  160818. if( !isIgnoreEmpty || nList>0 ){
  160819. /* Calculate the 'docid' delta value to write into the merged
  160820. ** doclist. */
  160821. sqlite3_int64 iDelta;
  160822. if( p->bDescIdx && nDoclist>0 ){
  160823. iDelta = iPrev - iDocid;
  160824. }else{
  160825. iDelta = iDocid - iPrev;
  160826. }
  160827. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  160828. assert( nDoclist>0 || iDelta==iDocid );
  160829. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  160830. if( nDoclist+nByte>pCsr->nBuffer ){
  160831. char *aNew;
  160832. pCsr->nBuffer = (nDoclist+nByte)*2;
  160833. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  160834. if( !aNew ){
  160835. return SQLITE_NOMEM;
  160836. }
  160837. pCsr->aBuffer = aNew;
  160838. }
  160839. if( isFirst ){
  160840. char *a = &pCsr->aBuffer[nDoclist];
  160841. int nWrite;
  160842. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  160843. if( nWrite ){
  160844. iPrev = iDocid;
  160845. nDoclist += nWrite;
  160846. }
  160847. }else{
  160848. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  160849. iPrev = iDocid;
  160850. if( isRequirePos ){
  160851. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  160852. nDoclist += nList;
  160853. pCsr->aBuffer[nDoclist++] = '\0';
  160854. }
  160855. }
  160856. }
  160857. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  160858. }
  160859. if( nDoclist>0 ){
  160860. pCsr->aDoclist = pCsr->aBuffer;
  160861. pCsr->nDoclist = nDoclist;
  160862. rc = SQLITE_ROW;
  160863. }
  160864. }
  160865. pCsr->nAdvance = nMerge;
  160866. }while( rc==SQLITE_OK );
  160867. return rc;
  160868. }
  160869. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  160870. Fts3MultiSegReader *pCsr /* Cursor object */
  160871. ){
  160872. if( pCsr ){
  160873. int i;
  160874. for(i=0; i<pCsr->nSegment; i++){
  160875. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  160876. }
  160877. sqlite3_free(pCsr->apSegment);
  160878. sqlite3_free(pCsr->aBuffer);
  160879. pCsr->nSegment = 0;
  160880. pCsr->apSegment = 0;
  160881. pCsr->aBuffer = 0;
  160882. }
  160883. }
  160884. /*
  160885. ** Decode the "end_block" field, selected by column iCol of the SELECT
  160886. ** statement passed as the first argument.
  160887. **
  160888. ** The "end_block" field may contain either an integer, or a text field
  160889. ** containing the text representation of two non-negative integers separated
  160890. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  160891. ** to the integer value and *pnByte to zero before returning. In the second,
  160892. ** set *piEndBlock to the first value and *pnByte to the second.
  160893. */
  160894. static void fts3ReadEndBlockField(
  160895. sqlite3_stmt *pStmt,
  160896. int iCol,
  160897. i64 *piEndBlock,
  160898. i64 *pnByte
  160899. ){
  160900. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  160901. if( zText ){
  160902. int i;
  160903. int iMul = 1;
  160904. i64 iVal = 0;
  160905. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  160906. iVal = iVal*10 + (zText[i] - '0');
  160907. }
  160908. *piEndBlock = iVal;
  160909. while( zText[i]==' ' ) i++;
  160910. iVal = 0;
  160911. if( zText[i]=='-' ){
  160912. i++;
  160913. iMul = -1;
  160914. }
  160915. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  160916. iVal = iVal*10 + (zText[i] - '0');
  160917. }
  160918. *pnByte = (iVal * (i64)iMul);
  160919. }
  160920. }
  160921. /*
  160922. ** A segment of size nByte bytes has just been written to absolute level
  160923. ** iAbsLevel. Promote any segments that should be promoted as a result.
  160924. */
  160925. static int fts3PromoteSegments(
  160926. Fts3Table *p, /* FTS table handle */
  160927. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  160928. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  160929. ){
  160930. int rc = SQLITE_OK;
  160931. sqlite3_stmt *pRange;
  160932. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  160933. if( rc==SQLITE_OK ){
  160934. int bOk = 0;
  160935. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  160936. i64 nLimit = (nByte*3)/2;
  160937. /* Loop through all entries in the %_segdir table corresponding to
  160938. ** segments in this index on levels greater than iAbsLevel. If there is
  160939. ** at least one such segment, and it is possible to determine that all
  160940. ** such segments are smaller than nLimit bytes in size, they will be
  160941. ** promoted to level iAbsLevel. */
  160942. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  160943. sqlite3_bind_int64(pRange, 2, iLast);
  160944. while( SQLITE_ROW==sqlite3_step(pRange) ){
  160945. i64 nSize = 0, dummy;
  160946. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  160947. if( nSize<=0 || nSize>nLimit ){
  160948. /* If nSize==0, then the %_segdir.end_block field does not not
  160949. ** contain a size value. This happens if it was written by an
  160950. ** old version of FTS. In this case it is not possible to determine
  160951. ** the size of the segment, and so segment promotion does not
  160952. ** take place. */
  160953. bOk = 0;
  160954. break;
  160955. }
  160956. bOk = 1;
  160957. }
  160958. rc = sqlite3_reset(pRange);
  160959. if( bOk ){
  160960. int iIdx = 0;
  160961. sqlite3_stmt *pUpdate1 = 0;
  160962. sqlite3_stmt *pUpdate2 = 0;
  160963. if( rc==SQLITE_OK ){
  160964. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  160965. }
  160966. if( rc==SQLITE_OK ){
  160967. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  160968. }
  160969. if( rc==SQLITE_OK ){
  160970. /* Loop through all %_segdir entries for segments in this index with
  160971. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  160972. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  160973. ** oldest segment in the range, 1 for the next oldest, and so on.
  160974. **
  160975. ** In other words, move all segments being promoted to level -1,
  160976. ** setting the "idx" fields as appropriate to keep them in the same
  160977. ** order. The contents of level -1 (which is never used, except
  160978. ** transiently here), will be moved back to level iAbsLevel below. */
  160979. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  160980. while( SQLITE_ROW==sqlite3_step(pRange) ){
  160981. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  160982. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  160983. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  160984. sqlite3_step(pUpdate1);
  160985. rc = sqlite3_reset(pUpdate1);
  160986. if( rc!=SQLITE_OK ){
  160987. sqlite3_reset(pRange);
  160988. break;
  160989. }
  160990. }
  160991. }
  160992. if( rc==SQLITE_OK ){
  160993. rc = sqlite3_reset(pRange);
  160994. }
  160995. /* Move level -1 to level iAbsLevel */
  160996. if( rc==SQLITE_OK ){
  160997. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  160998. sqlite3_step(pUpdate2);
  160999. rc = sqlite3_reset(pUpdate2);
  161000. }
  161001. }
  161002. }
  161003. return rc;
  161004. }
  161005. /*
  161006. ** Merge all level iLevel segments in the database into a single
  161007. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  161008. ** single segment with a level equal to the numerically largest level
  161009. ** currently present in the database.
  161010. **
  161011. ** If this function is called with iLevel<0, but there is only one
  161012. ** segment in the database, SQLITE_DONE is returned immediately.
  161013. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  161014. ** an SQLite error code is returned.
  161015. */
  161016. static int fts3SegmentMerge(
  161017. Fts3Table *p,
  161018. int iLangid, /* Language id to merge */
  161019. int iIndex, /* Index in p->aIndex[] to merge */
  161020. int iLevel /* Level to merge */
  161021. ){
  161022. int rc; /* Return code */
  161023. int iIdx = 0; /* Index of new segment */
  161024. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  161025. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  161026. Fts3SegFilter filter; /* Segment term filter condition */
  161027. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  161028. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  161029. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  161030. assert( iLevel==FTS3_SEGCURSOR_ALL
  161031. || iLevel==FTS3_SEGCURSOR_PENDING
  161032. || iLevel>=0
  161033. );
  161034. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  161035. assert( iIndex>=0 && iIndex<p->nIndex );
  161036. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  161037. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  161038. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  161039. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  161040. if( rc!=SQLITE_OK ) goto finished;
  161041. }
  161042. if( iLevel==FTS3_SEGCURSOR_ALL ){
  161043. /* This call is to merge all segments in the database to a single
  161044. ** segment. The level of the new segment is equal to the numerically
  161045. ** greatest segment level currently present in the database for this
  161046. ** index. The idx of the new segment is always 0. */
  161047. if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
  161048. rc = SQLITE_DONE;
  161049. goto finished;
  161050. }
  161051. iNewLevel = iMaxLevel;
  161052. bIgnoreEmpty = 1;
  161053. }else{
  161054. /* This call is to merge all segments at level iLevel. find the next
  161055. ** available segment index at level iLevel+1. The call to
  161056. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  161057. ** a single iLevel+2 segment if necessary. */
  161058. assert( FTS3_SEGCURSOR_PENDING==-1 );
  161059. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  161060. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  161061. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  161062. }
  161063. if( rc!=SQLITE_OK ) goto finished;
  161064. assert( csr.nSegment>0 );
  161065. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  161066. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  161067. memset(&filter, 0, sizeof(Fts3SegFilter));
  161068. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  161069. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  161070. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  161071. while( SQLITE_OK==rc ){
  161072. rc = sqlite3Fts3SegReaderStep(p, &csr);
  161073. if( rc!=SQLITE_ROW ) break;
  161074. rc = fts3SegWriterAdd(p, &pWriter, 1,
  161075. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  161076. }
  161077. if( rc!=SQLITE_OK ) goto finished;
  161078. assert( pWriter || bIgnoreEmpty );
  161079. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  161080. rc = fts3DeleteSegdir(
  161081. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  161082. );
  161083. if( rc!=SQLITE_OK ) goto finished;
  161084. }
  161085. if( pWriter ){
  161086. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  161087. if( rc==SQLITE_OK ){
  161088. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  161089. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  161090. }
  161091. }
  161092. }
  161093. finished:
  161094. fts3SegWriterFree(pWriter);
  161095. sqlite3Fts3SegReaderFinish(&csr);
  161096. return rc;
  161097. }
  161098. /*
  161099. ** Flush the contents of pendingTerms to level 0 segments.
  161100. */
  161101. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  161102. int rc = SQLITE_OK;
  161103. int i;
  161104. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  161105. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  161106. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  161107. }
  161108. sqlite3Fts3PendingTermsClear(p);
  161109. /* Determine the auto-incr-merge setting if unknown. If enabled,
  161110. ** estimate the number of leaf blocks of content to be written
  161111. */
  161112. if( rc==SQLITE_OK && p->bHasStat
  161113. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  161114. ){
  161115. sqlite3_stmt *pStmt = 0;
  161116. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  161117. if( rc==SQLITE_OK ){
  161118. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  161119. rc = sqlite3_step(pStmt);
  161120. if( rc==SQLITE_ROW ){
  161121. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  161122. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  161123. }else if( rc==SQLITE_DONE ){
  161124. p->nAutoincrmerge = 0;
  161125. }
  161126. rc = sqlite3_reset(pStmt);
  161127. }
  161128. }
  161129. return rc;
  161130. }
  161131. /*
  161132. ** Encode N integers as varints into a blob.
  161133. */
  161134. static void fts3EncodeIntArray(
  161135. int N, /* The number of integers to encode */
  161136. u32 *a, /* The integer values */
  161137. char *zBuf, /* Write the BLOB here */
  161138. int *pNBuf /* Write number of bytes if zBuf[] used here */
  161139. ){
  161140. int i, j;
  161141. for(i=j=0; i<N; i++){
  161142. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  161143. }
  161144. *pNBuf = j;
  161145. }
  161146. /*
  161147. ** Decode a blob of varints into N integers
  161148. */
  161149. static void fts3DecodeIntArray(
  161150. int N, /* The number of integers to decode */
  161151. u32 *a, /* Write the integer values */
  161152. const char *zBuf, /* The BLOB containing the varints */
  161153. int nBuf /* size of the BLOB */
  161154. ){
  161155. int i, j;
  161156. UNUSED_PARAMETER(nBuf);
  161157. for(i=j=0; i<N; i++){
  161158. sqlite3_int64 x;
  161159. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  161160. assert(j<=nBuf);
  161161. a[i] = (u32)(x & 0xffffffff);
  161162. }
  161163. }
  161164. /*
  161165. ** Insert the sizes (in tokens) for each column of the document
  161166. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  161167. ** a blob of varints.
  161168. */
  161169. static void fts3InsertDocsize(
  161170. int *pRC, /* Result code */
  161171. Fts3Table *p, /* Table into which to insert */
  161172. u32 *aSz /* Sizes of each column, in tokens */
  161173. ){
  161174. char *pBlob; /* The BLOB encoding of the document size */
  161175. int nBlob; /* Number of bytes in the BLOB */
  161176. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  161177. int rc; /* Result code from subfunctions */
  161178. if( *pRC ) return;
  161179. pBlob = sqlite3_malloc( 10*p->nColumn );
  161180. if( pBlob==0 ){
  161181. *pRC = SQLITE_NOMEM;
  161182. return;
  161183. }
  161184. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  161185. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  161186. if( rc ){
  161187. sqlite3_free(pBlob);
  161188. *pRC = rc;
  161189. return;
  161190. }
  161191. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  161192. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  161193. sqlite3_step(pStmt);
  161194. *pRC = sqlite3_reset(pStmt);
  161195. }
  161196. /*
  161197. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  161198. ** where N is the number of user defined columns in the fts3 table plus
  161199. ** two. If nCol is the number of user defined columns, then values of the
  161200. ** varints are set as follows:
  161201. **
  161202. ** Varint 0: Total number of rows in the table.
  161203. **
  161204. ** Varint 1..nCol: For each column, the total number of tokens stored in
  161205. ** the column for all rows of the table.
  161206. **
  161207. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  161208. ** columns of all rows of the table.
  161209. **
  161210. */
  161211. static void fts3UpdateDocTotals(
  161212. int *pRC, /* The result code */
  161213. Fts3Table *p, /* Table being updated */
  161214. u32 *aSzIns, /* Size increases */
  161215. u32 *aSzDel, /* Size decreases */
  161216. int nChng /* Change in the number of documents */
  161217. ){
  161218. char *pBlob; /* Storage for BLOB written into %_stat */
  161219. int nBlob; /* Size of BLOB written into %_stat */
  161220. u32 *a; /* Array of integers that becomes the BLOB */
  161221. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  161222. int i; /* Loop counter */
  161223. int rc; /* Result code from subfunctions */
  161224. const int nStat = p->nColumn+2;
  161225. if( *pRC ) return;
  161226. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  161227. if( a==0 ){
  161228. *pRC = SQLITE_NOMEM;
  161229. return;
  161230. }
  161231. pBlob = (char*)&a[nStat];
  161232. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  161233. if( rc ){
  161234. sqlite3_free(a);
  161235. *pRC = rc;
  161236. return;
  161237. }
  161238. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  161239. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  161240. fts3DecodeIntArray(nStat, a,
  161241. sqlite3_column_blob(pStmt, 0),
  161242. sqlite3_column_bytes(pStmt, 0));
  161243. }else{
  161244. memset(a, 0, sizeof(u32)*(nStat) );
  161245. }
  161246. rc = sqlite3_reset(pStmt);
  161247. if( rc!=SQLITE_OK ){
  161248. sqlite3_free(a);
  161249. *pRC = rc;
  161250. return;
  161251. }
  161252. if( nChng<0 && a[0]<(u32)(-nChng) ){
  161253. a[0] = 0;
  161254. }else{
  161255. a[0] += nChng;
  161256. }
  161257. for(i=0; i<p->nColumn+1; i++){
  161258. u32 x = a[i+1];
  161259. if( x+aSzIns[i] < aSzDel[i] ){
  161260. x = 0;
  161261. }else{
  161262. x = x + aSzIns[i] - aSzDel[i];
  161263. }
  161264. a[i+1] = x;
  161265. }
  161266. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  161267. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  161268. if( rc ){
  161269. sqlite3_free(a);
  161270. *pRC = rc;
  161271. return;
  161272. }
  161273. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  161274. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  161275. sqlite3_step(pStmt);
  161276. *pRC = sqlite3_reset(pStmt);
  161277. sqlite3_bind_null(pStmt, 2);
  161278. sqlite3_free(a);
  161279. }
  161280. /*
  161281. ** Merge the entire database so that there is one segment for each
  161282. ** iIndex/iLangid combination.
  161283. */
  161284. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  161285. int bSeenDone = 0;
  161286. int rc;
  161287. sqlite3_stmt *pAllLangid = 0;
  161288. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  161289. if( rc==SQLITE_OK ){
  161290. int rc2;
  161291. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  161292. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  161293. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  161294. int i;
  161295. int iLangid = sqlite3_column_int(pAllLangid, 0);
  161296. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  161297. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  161298. if( rc==SQLITE_DONE ){
  161299. bSeenDone = 1;
  161300. rc = SQLITE_OK;
  161301. }
  161302. }
  161303. }
  161304. rc2 = sqlite3_reset(pAllLangid);
  161305. if( rc==SQLITE_OK ) rc = rc2;
  161306. }
  161307. sqlite3Fts3SegmentsClose(p);
  161308. sqlite3Fts3PendingTermsClear(p);
  161309. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  161310. }
  161311. /*
  161312. ** This function is called when the user executes the following statement:
  161313. **
  161314. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  161315. **
  161316. ** The entire FTS index is discarded and rebuilt. If the table is one
  161317. ** created using the content=xxx option, then the new index is based on
  161318. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  161319. ** on the contents of the %_content table.
  161320. */
  161321. static int fts3DoRebuild(Fts3Table *p){
  161322. int rc; /* Return Code */
  161323. rc = fts3DeleteAll(p, 0);
  161324. if( rc==SQLITE_OK ){
  161325. u32 *aSz = 0;
  161326. u32 *aSzIns = 0;
  161327. u32 *aSzDel = 0;
  161328. sqlite3_stmt *pStmt = 0;
  161329. int nEntry = 0;
  161330. /* Compose and prepare an SQL statement to loop through the content table */
  161331. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  161332. if( !zSql ){
  161333. rc = SQLITE_NOMEM;
  161334. }else{
  161335. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  161336. sqlite3_free(zSql);
  161337. }
  161338. if( rc==SQLITE_OK ){
  161339. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  161340. aSz = (u32 *)sqlite3_malloc(nByte);
  161341. if( aSz==0 ){
  161342. rc = SQLITE_NOMEM;
  161343. }else{
  161344. memset(aSz, 0, nByte);
  161345. aSzIns = &aSz[p->nColumn+1];
  161346. aSzDel = &aSzIns[p->nColumn+1];
  161347. }
  161348. }
  161349. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  161350. int iCol;
  161351. int iLangid = langidFromSelect(p, pStmt);
  161352. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  161353. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  161354. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  161355. if( p->abNotindexed[iCol]==0 ){
  161356. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  161357. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  161358. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  161359. }
  161360. }
  161361. if( p->bHasDocsize ){
  161362. fts3InsertDocsize(&rc, p, aSz);
  161363. }
  161364. if( rc!=SQLITE_OK ){
  161365. sqlite3_finalize(pStmt);
  161366. pStmt = 0;
  161367. }else{
  161368. nEntry++;
  161369. for(iCol=0; iCol<=p->nColumn; iCol++){
  161370. aSzIns[iCol] += aSz[iCol];
  161371. }
  161372. }
  161373. }
  161374. if( p->bFts4 ){
  161375. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  161376. }
  161377. sqlite3_free(aSz);
  161378. if( pStmt ){
  161379. int rc2 = sqlite3_finalize(pStmt);
  161380. if( rc==SQLITE_OK ){
  161381. rc = rc2;
  161382. }
  161383. }
  161384. }
  161385. return rc;
  161386. }
  161387. /*
  161388. ** This function opens a cursor used to read the input data for an
  161389. ** incremental merge operation. Specifically, it opens a cursor to scan
  161390. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  161391. ** level iAbsLevel.
  161392. */
  161393. static int fts3IncrmergeCsr(
  161394. Fts3Table *p, /* FTS3 table handle */
  161395. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  161396. int nSeg, /* Number of segments to merge */
  161397. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  161398. ){
  161399. int rc; /* Return Code */
  161400. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  161401. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  161402. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  161403. memset(pCsr, 0, sizeof(*pCsr));
  161404. nByte = sizeof(Fts3SegReader *) * nSeg;
  161405. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  161406. if( pCsr->apSegment==0 ){
  161407. rc = SQLITE_NOMEM;
  161408. }else{
  161409. memset(pCsr->apSegment, 0, nByte);
  161410. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  161411. }
  161412. if( rc==SQLITE_OK ){
  161413. int i;
  161414. int rc2;
  161415. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  161416. assert( pCsr->nSegment==0 );
  161417. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  161418. rc = sqlite3Fts3SegReaderNew(i, 0,
  161419. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  161420. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  161421. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  161422. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  161423. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  161424. &pCsr->apSegment[i]
  161425. );
  161426. pCsr->nSegment++;
  161427. }
  161428. rc2 = sqlite3_reset(pStmt);
  161429. if( rc==SQLITE_OK ) rc = rc2;
  161430. }
  161431. return rc;
  161432. }
  161433. typedef struct IncrmergeWriter IncrmergeWriter;
  161434. typedef struct NodeWriter NodeWriter;
  161435. typedef struct Blob Blob;
  161436. typedef struct NodeReader NodeReader;
  161437. /*
  161438. ** An instance of the following structure is used as a dynamic buffer
  161439. ** to build up nodes or other blobs of data in.
  161440. **
  161441. ** The function blobGrowBuffer() is used to extend the allocation.
  161442. */
  161443. struct Blob {
  161444. char *a; /* Pointer to allocation */
  161445. int n; /* Number of valid bytes of data in a[] */
  161446. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  161447. };
  161448. /*
  161449. ** This structure is used to build up buffers containing segment b-tree
  161450. ** nodes (blocks).
  161451. */
  161452. struct NodeWriter {
  161453. sqlite3_int64 iBlock; /* Current block id */
  161454. Blob key; /* Last key written to the current block */
  161455. Blob block; /* Current block image */
  161456. };
  161457. /*
  161458. ** An object of this type contains the state required to create or append
  161459. ** to an appendable b-tree segment.
  161460. */
  161461. struct IncrmergeWriter {
  161462. int nLeafEst; /* Space allocated for leaf blocks */
  161463. int nWork; /* Number of leaf pages flushed */
  161464. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  161465. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  161466. sqlite3_int64 iStart; /* Block number of first allocated block */
  161467. sqlite3_int64 iEnd; /* Block number of last allocated block */
  161468. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  161469. u8 bNoLeafData; /* If true, store 0 for segment size */
  161470. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  161471. };
  161472. /*
  161473. ** An object of the following type is used to read data from a single
  161474. ** FTS segment node. See the following functions:
  161475. **
  161476. ** nodeReaderInit()
  161477. ** nodeReaderNext()
  161478. ** nodeReaderRelease()
  161479. */
  161480. struct NodeReader {
  161481. const char *aNode;
  161482. int nNode;
  161483. int iOff; /* Current offset within aNode[] */
  161484. /* Output variables. Containing the current node entry. */
  161485. sqlite3_int64 iChild; /* Pointer to child node */
  161486. Blob term; /* Current term */
  161487. const char *aDoclist; /* Pointer to doclist */
  161488. int nDoclist; /* Size of doclist in bytes */
  161489. };
  161490. /*
  161491. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  161492. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  161493. ** bytes in size, extend (realloc) it to be so.
  161494. **
  161495. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  161496. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  161497. ** to reflect the new size of the pBlob->a[] buffer.
  161498. */
  161499. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  161500. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  161501. int nAlloc = nMin;
  161502. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  161503. if( a ){
  161504. pBlob->nAlloc = nAlloc;
  161505. pBlob->a = a;
  161506. }else{
  161507. *pRc = SQLITE_NOMEM;
  161508. }
  161509. }
  161510. }
  161511. /*
  161512. ** Attempt to advance the node-reader object passed as the first argument to
  161513. ** the next entry on the node.
  161514. **
  161515. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  161516. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  161517. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  161518. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  161519. ** variables for the new entry.
  161520. */
  161521. static int nodeReaderNext(NodeReader *p){
  161522. int bFirst = (p->term.n==0); /* True for first term on the node */
  161523. int nPrefix = 0; /* Bytes to copy from previous term */
  161524. int nSuffix = 0; /* Bytes to append to the prefix */
  161525. int rc = SQLITE_OK; /* Return code */
  161526. assert( p->aNode );
  161527. if( p->iChild && bFirst==0 ) p->iChild++;
  161528. if( p->iOff>=p->nNode ){
  161529. /* EOF */
  161530. p->aNode = 0;
  161531. }else{
  161532. if( bFirst==0 ){
  161533. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  161534. }
  161535. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  161536. if( nPrefix>p->iOff || nSuffix>p->nNode-p->iOff ){
  161537. return SQLITE_CORRUPT_VTAB;
  161538. }
  161539. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  161540. if( rc==SQLITE_OK ){
  161541. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  161542. p->term.n = nPrefix+nSuffix;
  161543. p->iOff += nSuffix;
  161544. if( p->iChild==0 ){
  161545. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  161546. if( (p->nNode-p->iOff)<p->nDoclist ){
  161547. return SQLITE_CORRUPT_VTAB;
  161548. }
  161549. p->aDoclist = &p->aNode[p->iOff];
  161550. p->iOff += p->nDoclist;
  161551. }
  161552. }
  161553. }
  161554. assert( p->iOff<=p->nNode );
  161555. return rc;
  161556. }
  161557. /*
  161558. ** Release all dynamic resources held by node-reader object *p.
  161559. */
  161560. static void nodeReaderRelease(NodeReader *p){
  161561. sqlite3_free(p->term.a);
  161562. }
  161563. /*
  161564. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  161565. **
  161566. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  161567. ** point to the first entry on the node (if any). Otherwise, an SQLite
  161568. ** error code is returned.
  161569. */
  161570. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  161571. memset(p, 0, sizeof(NodeReader));
  161572. p->aNode = aNode;
  161573. p->nNode = nNode;
  161574. /* Figure out if this is a leaf or an internal node. */
  161575. if( p->aNode[0] ){
  161576. /* An internal node. */
  161577. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  161578. }else{
  161579. p->iOff = 1;
  161580. }
  161581. return nodeReaderNext(p);
  161582. }
  161583. /*
  161584. ** This function is called while writing an FTS segment each time a leaf o
  161585. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  161586. ** to be greater than the largest key on the node just written, but smaller
  161587. ** than or equal to the first key that will be written to the next leaf
  161588. ** node.
  161589. **
  161590. ** The block id of the leaf node just written to disk may be found in
  161591. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  161592. */
  161593. static int fts3IncrmergePush(
  161594. Fts3Table *p, /* Fts3 table handle */
  161595. IncrmergeWriter *pWriter, /* Writer object */
  161596. const char *zTerm, /* Term to write to internal node */
  161597. int nTerm /* Bytes at zTerm */
  161598. ){
  161599. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  161600. int iLayer;
  161601. assert( nTerm>0 );
  161602. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  161603. sqlite3_int64 iNextPtr = 0;
  161604. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  161605. int rc = SQLITE_OK;
  161606. int nPrefix;
  161607. int nSuffix;
  161608. int nSpace;
  161609. /* Figure out how much space the key will consume if it is written to
  161610. ** the current node of layer iLayer. Due to the prefix compression,
  161611. ** the space required changes depending on which node the key is to
  161612. ** be added to. */
  161613. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  161614. nSuffix = nTerm - nPrefix;
  161615. nSpace = sqlite3Fts3VarintLen(nPrefix);
  161616. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  161617. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  161618. /* If the current node of layer iLayer contains zero keys, or if adding
  161619. ** the key to it will not cause it to grow to larger than nNodeSize
  161620. ** bytes in size, write the key here. */
  161621. Blob *pBlk = &pNode->block;
  161622. if( pBlk->n==0 ){
  161623. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  161624. if( rc==SQLITE_OK ){
  161625. pBlk->a[0] = (char)iLayer;
  161626. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  161627. }
  161628. }
  161629. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  161630. blobGrowBuffer(&pNode->key, nTerm, &rc);
  161631. if( rc==SQLITE_OK ){
  161632. if( pNode->key.n ){
  161633. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  161634. }
  161635. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  161636. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  161637. pBlk->n += nSuffix;
  161638. memcpy(pNode->key.a, zTerm, nTerm);
  161639. pNode->key.n = nTerm;
  161640. }
  161641. }else{
  161642. /* Otherwise, flush the current node of layer iLayer to disk.
  161643. ** Then allocate a new, empty sibling node. The key will be written
  161644. ** into the parent of this node. */
  161645. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  161646. assert( pNode->block.nAlloc>=p->nNodeSize );
  161647. pNode->block.a[0] = (char)iLayer;
  161648. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  161649. iNextPtr = pNode->iBlock;
  161650. pNode->iBlock++;
  161651. pNode->key.n = 0;
  161652. }
  161653. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  161654. iPtr = iNextPtr;
  161655. }
  161656. assert( 0 );
  161657. return 0;
  161658. }
  161659. /*
  161660. ** Append a term and (optionally) doclist to the FTS segment node currently
  161661. ** stored in blob *pNode. The node need not contain any terms, but the
  161662. ** header must be written before this function is called.
  161663. **
  161664. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  161665. ** followed by the left-hand-child varint for an internal node.
  161666. **
  161667. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  161668. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  161669. ** node, both aDoclist and nDoclist must be passed 0.
  161670. **
  161671. ** If the size of the value in blob pPrev is zero, then this is the first
  161672. ** term written to the node. Otherwise, pPrev contains a copy of the
  161673. ** previous term. Before this function returns, it is updated to contain a
  161674. ** copy of zTerm/nTerm.
  161675. **
  161676. ** It is assumed that the buffer associated with pNode is already large
  161677. ** enough to accommodate the new entry. The buffer associated with pPrev
  161678. ** is extended by this function if requrired.
  161679. **
  161680. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  161681. ** returned. Otherwise, SQLITE_OK.
  161682. */
  161683. static int fts3AppendToNode(
  161684. Blob *pNode, /* Current node image to append to */
  161685. Blob *pPrev, /* Buffer containing previous term written */
  161686. const char *zTerm, /* New term to write */
  161687. int nTerm, /* Size of zTerm in bytes */
  161688. const char *aDoclist, /* Doclist (or NULL) to write */
  161689. int nDoclist /* Size of aDoclist in bytes */
  161690. ){
  161691. int rc = SQLITE_OK; /* Return code */
  161692. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  161693. int nPrefix; /* Size of term prefix in bytes */
  161694. int nSuffix; /* Size of term suffix in bytes */
  161695. /* Node must have already been started. There must be a doclist for a
  161696. ** leaf node, and there must not be a doclist for an internal node. */
  161697. assert( pNode->n>0 );
  161698. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  161699. blobGrowBuffer(pPrev, nTerm, &rc);
  161700. if( rc!=SQLITE_OK ) return rc;
  161701. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  161702. nSuffix = nTerm - nPrefix;
  161703. memcpy(pPrev->a, zTerm, nTerm);
  161704. pPrev->n = nTerm;
  161705. if( bFirst==0 ){
  161706. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  161707. }
  161708. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  161709. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  161710. pNode->n += nSuffix;
  161711. if( aDoclist ){
  161712. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  161713. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  161714. pNode->n += nDoclist;
  161715. }
  161716. assert( pNode->n<=pNode->nAlloc );
  161717. return SQLITE_OK;
  161718. }
  161719. /*
  161720. ** Append the current term and doclist pointed to by cursor pCsr to the
  161721. ** appendable b-tree segment opened for writing by pWriter.
  161722. **
  161723. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  161724. */
  161725. static int fts3IncrmergeAppend(
  161726. Fts3Table *p, /* Fts3 table handle */
  161727. IncrmergeWriter *pWriter, /* Writer object */
  161728. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  161729. ){
  161730. const char *zTerm = pCsr->zTerm;
  161731. int nTerm = pCsr->nTerm;
  161732. const char *aDoclist = pCsr->aDoclist;
  161733. int nDoclist = pCsr->nDoclist;
  161734. int rc = SQLITE_OK; /* Return code */
  161735. int nSpace; /* Total space in bytes required on leaf */
  161736. int nPrefix; /* Size of prefix shared with previous term */
  161737. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  161738. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  161739. pLeaf = &pWriter->aNodeWriter[0];
  161740. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  161741. nSuffix = nTerm - nPrefix;
  161742. nSpace = sqlite3Fts3VarintLen(nPrefix);
  161743. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  161744. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  161745. /* If the current block is not empty, and if adding this term/doclist
  161746. ** to the current block would make it larger than Fts3Table.nNodeSize
  161747. ** bytes, write this block out to the database. */
  161748. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  161749. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  161750. pWriter->nWork++;
  161751. /* Add the current term to the parent node. The term added to the
  161752. ** parent must:
  161753. **
  161754. ** a) be greater than the largest term on the leaf node just written
  161755. ** to the database (still available in pLeaf->key), and
  161756. **
  161757. ** b) be less than or equal to the term about to be added to the new
  161758. ** leaf node (zTerm/nTerm).
  161759. **
  161760. ** In other words, it must be the prefix of zTerm 1 byte longer than
  161761. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  161762. */
  161763. if( rc==SQLITE_OK ){
  161764. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  161765. }
  161766. /* Advance to the next output block */
  161767. pLeaf->iBlock++;
  161768. pLeaf->key.n = 0;
  161769. pLeaf->block.n = 0;
  161770. nSuffix = nTerm;
  161771. nSpace = 1;
  161772. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  161773. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  161774. }
  161775. pWriter->nLeafData += nSpace;
  161776. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  161777. if( rc==SQLITE_OK ){
  161778. if( pLeaf->block.n==0 ){
  161779. pLeaf->block.n = 1;
  161780. pLeaf->block.a[0] = '\0';
  161781. }
  161782. rc = fts3AppendToNode(
  161783. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  161784. );
  161785. }
  161786. return rc;
  161787. }
  161788. /*
  161789. ** This function is called to release all dynamic resources held by the
  161790. ** merge-writer object pWriter, and if no error has occurred, to flush
  161791. ** all outstanding node buffers held by pWriter to disk.
  161792. **
  161793. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  161794. ** is made to write any data to disk. Instead, this function serves only
  161795. ** to release outstanding resources.
  161796. **
  161797. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  161798. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  161799. ** returning.
  161800. */
  161801. static void fts3IncrmergeRelease(
  161802. Fts3Table *p, /* FTS3 table handle */
  161803. IncrmergeWriter *pWriter, /* Merge-writer object */
  161804. int *pRc /* IN/OUT: Error code */
  161805. ){
  161806. int i; /* Used to iterate through non-root layers */
  161807. int iRoot; /* Index of root in pWriter->aNodeWriter */
  161808. NodeWriter *pRoot; /* NodeWriter for root node */
  161809. int rc = *pRc; /* Error code */
  161810. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  161811. ** root node. If the segment fits entirely on a single leaf node, iRoot
  161812. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  161813. ** will be 1. And so on. */
  161814. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  161815. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  161816. if( pNode->block.n>0 ) break;
  161817. assert( *pRc || pNode->block.nAlloc==0 );
  161818. assert( *pRc || pNode->key.nAlloc==0 );
  161819. sqlite3_free(pNode->block.a);
  161820. sqlite3_free(pNode->key.a);
  161821. }
  161822. /* Empty output segment. This is a no-op. */
  161823. if( iRoot<0 ) return;
  161824. /* The entire output segment fits on a single node. Normally, this means
  161825. ** the node would be stored as a blob in the "root" column of the %_segdir
  161826. ** table. However, this is not permitted in this case. The problem is that
  161827. ** space has already been reserved in the %_segments table, and so the
  161828. ** start_block and end_block fields of the %_segdir table must be populated.
  161829. ** And, by design or by accident, released versions of FTS cannot handle
  161830. ** segments that fit entirely on the root node with start_block!=0.
  161831. **
  161832. ** Instead, create a synthetic root node that contains nothing but a
  161833. ** pointer to the single content node. So that the segment consists of a
  161834. ** single leaf and a single interior (root) node.
  161835. **
  161836. ** Todo: Better might be to defer allocating space in the %_segments
  161837. ** table until we are sure it is needed.
  161838. */
  161839. if( iRoot==0 ){
  161840. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  161841. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  161842. if( rc==SQLITE_OK ){
  161843. pBlock->a[0] = 0x01;
  161844. pBlock->n = 1 + sqlite3Fts3PutVarint(
  161845. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  161846. );
  161847. }
  161848. iRoot = 1;
  161849. }
  161850. pRoot = &pWriter->aNodeWriter[iRoot];
  161851. /* Flush all currently outstanding nodes to disk. */
  161852. for(i=0; i<iRoot; i++){
  161853. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  161854. if( pNode->block.n>0 && rc==SQLITE_OK ){
  161855. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  161856. }
  161857. sqlite3_free(pNode->block.a);
  161858. sqlite3_free(pNode->key.a);
  161859. }
  161860. /* Write the %_segdir record. */
  161861. if( rc==SQLITE_OK ){
  161862. rc = fts3WriteSegdir(p,
  161863. pWriter->iAbsLevel+1, /* level */
  161864. pWriter->iIdx, /* idx */
  161865. pWriter->iStart, /* start_block */
  161866. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  161867. pWriter->iEnd, /* end_block */
  161868. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  161869. pRoot->block.a, pRoot->block.n /* root */
  161870. );
  161871. }
  161872. sqlite3_free(pRoot->block.a);
  161873. sqlite3_free(pRoot->key.a);
  161874. *pRc = rc;
  161875. }
  161876. /*
  161877. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  161878. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  161879. ** the other, it is considered to be smaller than the other.
  161880. **
  161881. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  161882. ** if it is greater.
  161883. */
  161884. static int fts3TermCmp(
  161885. const char *zLhs, int nLhs, /* LHS of comparison */
  161886. const char *zRhs, int nRhs /* RHS of comparison */
  161887. ){
  161888. int nCmp = MIN(nLhs, nRhs);
  161889. int res;
  161890. res = memcmp(zLhs, zRhs, nCmp);
  161891. if( res==0 ) res = nLhs - nRhs;
  161892. return res;
  161893. }
  161894. /*
  161895. ** Query to see if the entry in the %_segments table with blockid iEnd is
  161896. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  161897. ** returning. Otherwise, set *pbRes to 0.
  161898. **
  161899. ** Or, if an error occurs while querying the database, return an SQLite
  161900. ** error code. The final value of *pbRes is undefined in this case.
  161901. **
  161902. ** This is used to test if a segment is an "appendable" segment. If it
  161903. ** is, then a NULL entry has been inserted into the %_segments table
  161904. ** with blockid %_segdir.end_block.
  161905. */
  161906. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  161907. int bRes = 0; /* Result to set *pbRes to */
  161908. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  161909. int rc; /* Return code */
  161910. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  161911. if( rc==SQLITE_OK ){
  161912. sqlite3_bind_int64(pCheck, 1, iEnd);
  161913. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  161914. rc = sqlite3_reset(pCheck);
  161915. }
  161916. *pbRes = bRes;
  161917. return rc;
  161918. }
  161919. /*
  161920. ** This function is called when initializing an incremental-merge operation.
  161921. ** It checks if the existing segment with index value iIdx at absolute level
  161922. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  161923. ** merge-writer object *pWriter is initialized to write to it.
  161924. **
  161925. ** An existing segment can be appended to by an incremental merge if:
  161926. **
  161927. ** * It was initially created as an appendable segment (with all required
  161928. ** space pre-allocated), and
  161929. **
  161930. ** * The first key read from the input (arguments zKey and nKey) is
  161931. ** greater than the largest key currently stored in the potential
  161932. ** output segment.
  161933. */
  161934. static int fts3IncrmergeLoad(
  161935. Fts3Table *p, /* Fts3 table handle */
  161936. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  161937. int iIdx, /* Index of candidate output segment */
  161938. const char *zKey, /* First key to write */
  161939. int nKey, /* Number of bytes in nKey */
  161940. IncrmergeWriter *pWriter /* Populate this object */
  161941. ){
  161942. int rc; /* Return code */
  161943. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  161944. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  161945. if( rc==SQLITE_OK ){
  161946. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  161947. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  161948. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  161949. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  161950. int nRoot = 0; /* Size of aRoot[] in bytes */
  161951. int rc2; /* Return code from sqlite3_reset() */
  161952. int bAppendable = 0; /* Set to true if segment is appendable */
  161953. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  161954. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  161955. sqlite3_bind_int(pSelect, 2, iIdx);
  161956. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  161957. iStart = sqlite3_column_int64(pSelect, 1);
  161958. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  161959. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  161960. if( pWriter->nLeafData<0 ){
  161961. pWriter->nLeafData = pWriter->nLeafData * -1;
  161962. }
  161963. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  161964. nRoot = sqlite3_column_bytes(pSelect, 4);
  161965. aRoot = sqlite3_column_blob(pSelect, 4);
  161966. }else{
  161967. return sqlite3_reset(pSelect);
  161968. }
  161969. /* Check for the zero-length marker in the %_segments table */
  161970. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  161971. /* Check that zKey/nKey is larger than the largest key the candidate */
  161972. if( rc==SQLITE_OK && bAppendable ){
  161973. char *aLeaf = 0;
  161974. int nLeaf = 0;
  161975. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  161976. if( rc==SQLITE_OK ){
  161977. NodeReader reader;
  161978. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  161979. rc==SQLITE_OK && reader.aNode;
  161980. rc = nodeReaderNext(&reader)
  161981. ){
  161982. assert( reader.aNode );
  161983. }
  161984. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  161985. bAppendable = 0;
  161986. }
  161987. nodeReaderRelease(&reader);
  161988. }
  161989. sqlite3_free(aLeaf);
  161990. }
  161991. if( rc==SQLITE_OK && bAppendable ){
  161992. /* It is possible to append to this segment. Set up the IncrmergeWriter
  161993. ** object to do so. */
  161994. int i;
  161995. int nHeight = (int)aRoot[0];
  161996. NodeWriter *pNode;
  161997. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  161998. pWriter->iStart = iStart;
  161999. pWriter->iEnd = iEnd;
  162000. pWriter->iAbsLevel = iAbsLevel;
  162001. pWriter->iIdx = iIdx;
  162002. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  162003. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  162004. }
  162005. pNode = &pWriter->aNodeWriter[nHeight];
  162006. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  162007. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  162008. if( rc==SQLITE_OK ){
  162009. memcpy(pNode->block.a, aRoot, nRoot);
  162010. pNode->block.n = nRoot;
  162011. }
  162012. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  162013. NodeReader reader;
  162014. pNode = &pWriter->aNodeWriter[i];
  162015. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  162016. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  162017. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  162018. if( rc==SQLITE_OK ){
  162019. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  162020. pNode->key.n = reader.term.n;
  162021. if( i>0 ){
  162022. char *aBlock = 0;
  162023. int nBlock = 0;
  162024. pNode = &pWriter->aNodeWriter[i-1];
  162025. pNode->iBlock = reader.iChild;
  162026. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  162027. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  162028. if( rc==SQLITE_OK ){
  162029. memcpy(pNode->block.a, aBlock, nBlock);
  162030. pNode->block.n = nBlock;
  162031. }
  162032. sqlite3_free(aBlock);
  162033. }
  162034. }
  162035. nodeReaderRelease(&reader);
  162036. }
  162037. }
  162038. rc2 = sqlite3_reset(pSelect);
  162039. if( rc==SQLITE_OK ) rc = rc2;
  162040. }
  162041. return rc;
  162042. }
  162043. /*
  162044. ** Determine the largest segment index value that exists within absolute
  162045. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  162046. ** one before returning SQLITE_OK. Or, if there are no segments at all
  162047. ** within level iAbsLevel, set *piIdx to zero.
  162048. **
  162049. ** If an error occurs, return an SQLite error code. The final value of
  162050. ** *piIdx is undefined in this case.
  162051. */
  162052. static int fts3IncrmergeOutputIdx(
  162053. Fts3Table *p, /* FTS Table handle */
  162054. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  162055. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  162056. ){
  162057. int rc;
  162058. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  162059. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  162060. if( rc==SQLITE_OK ){
  162061. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  162062. sqlite3_step(pOutputIdx);
  162063. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  162064. rc = sqlite3_reset(pOutputIdx);
  162065. }
  162066. return rc;
  162067. }
  162068. /*
  162069. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  162070. ** with idx value iIdx.
  162071. **
  162072. ** In the %_segdir table, a segment is defined by the values in three
  162073. ** columns:
  162074. **
  162075. ** start_block
  162076. ** leaves_end_block
  162077. ** end_block
  162078. **
  162079. ** When an appendable segment is allocated, it is estimated that the
  162080. ** maximum number of leaf blocks that may be required is the sum of the
  162081. ** number of leaf blocks consumed by the input segments, plus the number
  162082. ** of input segments, multiplied by two. This value is stored in stack
  162083. ** variable nLeafEst.
  162084. **
  162085. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  162086. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  162087. ** array of leaf nodes starts at the first block allocated. The array
  162088. ** of interior nodes that are parents of the leaf nodes start at block
  162089. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  162090. **
  162091. ** In the actual code below, the value "16" is replaced with the
  162092. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  162093. */
  162094. static int fts3IncrmergeWriter(
  162095. Fts3Table *p, /* Fts3 table handle */
  162096. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  162097. int iIdx, /* Index of new output segment */
  162098. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  162099. IncrmergeWriter *pWriter /* Populate this object */
  162100. ){
  162101. int rc; /* Return Code */
  162102. int i; /* Iterator variable */
  162103. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  162104. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  162105. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  162106. /* Calculate nLeafEst. */
  162107. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  162108. if( rc==SQLITE_OK ){
  162109. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  162110. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  162111. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  162112. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  162113. }
  162114. rc = sqlite3_reset(pLeafEst);
  162115. }
  162116. if( rc!=SQLITE_OK ) return rc;
  162117. /* Calculate the first block to use in the output segment */
  162118. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  162119. if( rc==SQLITE_OK ){
  162120. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  162121. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  162122. pWriter->iEnd = pWriter->iStart - 1;
  162123. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  162124. }
  162125. rc = sqlite3_reset(pFirstBlock);
  162126. }
  162127. if( rc!=SQLITE_OK ) return rc;
  162128. /* Insert the marker in the %_segments table to make sure nobody tries
  162129. ** to steal the space just allocated. This is also used to identify
  162130. ** appendable segments. */
  162131. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  162132. if( rc!=SQLITE_OK ) return rc;
  162133. pWriter->iAbsLevel = iAbsLevel;
  162134. pWriter->nLeafEst = nLeafEst;
  162135. pWriter->iIdx = iIdx;
  162136. /* Set up the array of NodeWriter objects */
  162137. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  162138. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  162139. }
  162140. return SQLITE_OK;
  162141. }
  162142. /*
  162143. ** Remove an entry from the %_segdir table. This involves running the
  162144. ** following two statements:
  162145. **
  162146. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  162147. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  162148. **
  162149. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  162150. ** statement ensures that the remaining segments have contiguously allocated
  162151. ** idx values.
  162152. */
  162153. static int fts3RemoveSegdirEntry(
  162154. Fts3Table *p, /* FTS3 table handle */
  162155. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  162156. int iIdx /* Index of %_segdir entry to delete */
  162157. ){
  162158. int rc; /* Return code */
  162159. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  162160. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  162161. if( rc==SQLITE_OK ){
  162162. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  162163. sqlite3_bind_int(pDelete, 2, iIdx);
  162164. sqlite3_step(pDelete);
  162165. rc = sqlite3_reset(pDelete);
  162166. }
  162167. return rc;
  162168. }
  162169. /*
  162170. ** One or more segments have just been removed from absolute level iAbsLevel.
  162171. ** Update the 'idx' values of the remaining segments in the level so that
  162172. ** the idx values are a contiguous sequence starting from 0.
  162173. */
  162174. static int fts3RepackSegdirLevel(
  162175. Fts3Table *p, /* FTS3 table handle */
  162176. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  162177. ){
  162178. int rc; /* Return code */
  162179. int *aIdx = 0; /* Array of remaining idx values */
  162180. int nIdx = 0; /* Valid entries in aIdx[] */
  162181. int nAlloc = 0; /* Allocated size of aIdx[] */
  162182. int i; /* Iterator variable */
  162183. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  162184. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  162185. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  162186. if( rc==SQLITE_OK ){
  162187. int rc2;
  162188. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  162189. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  162190. if( nIdx>=nAlloc ){
  162191. int *aNew;
  162192. nAlloc += 16;
  162193. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  162194. if( !aNew ){
  162195. rc = SQLITE_NOMEM;
  162196. break;
  162197. }
  162198. aIdx = aNew;
  162199. }
  162200. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  162201. }
  162202. rc2 = sqlite3_reset(pSelect);
  162203. if( rc==SQLITE_OK ) rc = rc2;
  162204. }
  162205. if( rc==SQLITE_OK ){
  162206. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  162207. }
  162208. if( rc==SQLITE_OK ){
  162209. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  162210. }
  162211. assert( p->bIgnoreSavepoint==0 );
  162212. p->bIgnoreSavepoint = 1;
  162213. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  162214. if( aIdx[i]!=i ){
  162215. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  162216. sqlite3_bind_int(pUpdate, 1, i);
  162217. sqlite3_step(pUpdate);
  162218. rc = sqlite3_reset(pUpdate);
  162219. }
  162220. }
  162221. p->bIgnoreSavepoint = 0;
  162222. sqlite3_free(aIdx);
  162223. return rc;
  162224. }
  162225. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  162226. pNode->a[0] = (char)iHeight;
  162227. if( iChild ){
  162228. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  162229. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  162230. }else{
  162231. assert( pNode->nAlloc>=1 );
  162232. pNode->n = 1;
  162233. }
  162234. }
  162235. /*
  162236. ** The first two arguments are a pointer to and the size of a segment b-tree
  162237. ** node. The node may be a leaf or an internal node.
  162238. **
  162239. ** This function creates a new node image in blob object *pNew by copying
  162240. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  162241. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  162242. */
  162243. static int fts3TruncateNode(
  162244. const char *aNode, /* Current node image */
  162245. int nNode, /* Size of aNode in bytes */
  162246. Blob *pNew, /* OUT: Write new node image here */
  162247. const char *zTerm, /* Omit all terms smaller than this */
  162248. int nTerm, /* Size of zTerm in bytes */
  162249. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  162250. ){
  162251. NodeReader reader; /* Reader object */
  162252. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  162253. int rc = SQLITE_OK; /* Return code */
  162254. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  162255. /* Allocate required output space */
  162256. blobGrowBuffer(pNew, nNode, &rc);
  162257. if( rc!=SQLITE_OK ) return rc;
  162258. pNew->n = 0;
  162259. /* Populate new node buffer */
  162260. for(rc = nodeReaderInit(&reader, aNode, nNode);
  162261. rc==SQLITE_OK && reader.aNode;
  162262. rc = nodeReaderNext(&reader)
  162263. ){
  162264. if( pNew->n==0 ){
  162265. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  162266. if( res<0 || (bLeaf==0 && res==0) ) continue;
  162267. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  162268. *piBlock = reader.iChild;
  162269. }
  162270. rc = fts3AppendToNode(
  162271. pNew, &prev, reader.term.a, reader.term.n,
  162272. reader.aDoclist, reader.nDoclist
  162273. );
  162274. if( rc!=SQLITE_OK ) break;
  162275. }
  162276. if( pNew->n==0 ){
  162277. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  162278. *piBlock = reader.iChild;
  162279. }
  162280. assert( pNew->n<=pNew->nAlloc );
  162281. nodeReaderRelease(&reader);
  162282. sqlite3_free(prev.a);
  162283. return rc;
  162284. }
  162285. /*
  162286. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  162287. ** level iAbsLevel. This may involve deleting entries from the %_segments
  162288. ** table, and modifying existing entries in both the %_segments and %_segdir
  162289. ** tables.
  162290. **
  162291. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  162292. ** SQLite error code otherwise.
  162293. */
  162294. static int fts3TruncateSegment(
  162295. Fts3Table *p, /* FTS3 table handle */
  162296. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  162297. int iIdx, /* Index within level of segment to modify */
  162298. const char *zTerm, /* Remove terms smaller than this */
  162299. int nTerm /* Number of bytes in buffer zTerm */
  162300. ){
  162301. int rc = SQLITE_OK; /* Return code */
  162302. Blob root = {0,0,0}; /* New root page image */
  162303. Blob block = {0,0,0}; /* Buffer used for any other block */
  162304. sqlite3_int64 iBlock = 0; /* Block id */
  162305. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  162306. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  162307. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  162308. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  162309. if( rc==SQLITE_OK ){
  162310. int rc2; /* sqlite3_reset() return code */
  162311. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  162312. sqlite3_bind_int(pFetch, 2, iIdx);
  162313. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  162314. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  162315. int nRoot = sqlite3_column_bytes(pFetch, 4);
  162316. iOldStart = sqlite3_column_int64(pFetch, 1);
  162317. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  162318. }
  162319. rc2 = sqlite3_reset(pFetch);
  162320. if( rc==SQLITE_OK ) rc = rc2;
  162321. }
  162322. while( rc==SQLITE_OK && iBlock ){
  162323. char *aBlock = 0;
  162324. int nBlock = 0;
  162325. iNewStart = iBlock;
  162326. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  162327. if( rc==SQLITE_OK ){
  162328. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  162329. }
  162330. if( rc==SQLITE_OK ){
  162331. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  162332. }
  162333. sqlite3_free(aBlock);
  162334. }
  162335. /* Variable iNewStart now contains the first valid leaf node. */
  162336. if( rc==SQLITE_OK && iNewStart ){
  162337. sqlite3_stmt *pDel = 0;
  162338. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  162339. if( rc==SQLITE_OK ){
  162340. sqlite3_bind_int64(pDel, 1, iOldStart);
  162341. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  162342. sqlite3_step(pDel);
  162343. rc = sqlite3_reset(pDel);
  162344. }
  162345. }
  162346. if( rc==SQLITE_OK ){
  162347. sqlite3_stmt *pChomp = 0;
  162348. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  162349. if( rc==SQLITE_OK ){
  162350. sqlite3_bind_int64(pChomp, 1, iNewStart);
  162351. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  162352. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  162353. sqlite3_bind_int(pChomp, 4, iIdx);
  162354. sqlite3_step(pChomp);
  162355. rc = sqlite3_reset(pChomp);
  162356. sqlite3_bind_null(pChomp, 2);
  162357. }
  162358. }
  162359. sqlite3_free(root.a);
  162360. sqlite3_free(block.a);
  162361. return rc;
  162362. }
  162363. /*
  162364. ** This function is called after an incrmental-merge operation has run to
  162365. ** merge (or partially merge) two or more segments from absolute level
  162366. ** iAbsLevel.
  162367. **
  162368. ** Each input segment is either removed from the db completely (if all of
  162369. ** its data was copied to the output segment by the incrmerge operation)
  162370. ** or modified in place so that it no longer contains those entries that
  162371. ** have been duplicated in the output segment.
  162372. */
  162373. static int fts3IncrmergeChomp(
  162374. Fts3Table *p, /* FTS table handle */
  162375. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  162376. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  162377. int *pnRem /* Number of segments not deleted */
  162378. ){
  162379. int i;
  162380. int nRem = 0;
  162381. int rc = SQLITE_OK;
  162382. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  162383. Fts3SegReader *pSeg = 0;
  162384. int j;
  162385. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  162386. ** somewhere in the pCsr->apSegment[] array. */
  162387. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  162388. pSeg = pCsr->apSegment[j];
  162389. if( pSeg->iIdx==i ) break;
  162390. }
  162391. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  162392. if( pSeg->aNode==0 ){
  162393. /* Seg-reader is at EOF. Remove the entire input segment. */
  162394. rc = fts3DeleteSegment(p, pSeg);
  162395. if( rc==SQLITE_OK ){
  162396. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  162397. }
  162398. *pnRem = 0;
  162399. }else{
  162400. /* The incremental merge did not copy all the data from this
  162401. ** segment to the upper level. The segment is modified in place
  162402. ** so that it contains no keys smaller than zTerm/nTerm. */
  162403. const char *zTerm = pSeg->zTerm;
  162404. int nTerm = pSeg->nTerm;
  162405. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  162406. nRem++;
  162407. }
  162408. }
  162409. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  162410. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  162411. }
  162412. *pnRem = nRem;
  162413. return rc;
  162414. }
  162415. /*
  162416. ** Store an incr-merge hint in the database.
  162417. */
  162418. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  162419. sqlite3_stmt *pReplace = 0;
  162420. int rc; /* Return code */
  162421. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  162422. if( rc==SQLITE_OK ){
  162423. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  162424. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  162425. sqlite3_step(pReplace);
  162426. rc = sqlite3_reset(pReplace);
  162427. sqlite3_bind_null(pReplace, 2);
  162428. }
  162429. return rc;
  162430. }
  162431. /*
  162432. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  162433. ** exists, is stored in the rowid==1 row of the %_stat table.
  162434. **
  162435. ** If successful, populate blob *pHint with the value read from the %_stat
  162436. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  162437. ** SQLite error code.
  162438. */
  162439. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  162440. sqlite3_stmt *pSelect = 0;
  162441. int rc;
  162442. pHint->n = 0;
  162443. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  162444. if( rc==SQLITE_OK ){
  162445. int rc2;
  162446. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  162447. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  162448. const char *aHint = sqlite3_column_blob(pSelect, 0);
  162449. int nHint = sqlite3_column_bytes(pSelect, 0);
  162450. if( aHint ){
  162451. blobGrowBuffer(pHint, nHint, &rc);
  162452. if( rc==SQLITE_OK ){
  162453. memcpy(pHint->a, aHint, nHint);
  162454. pHint->n = nHint;
  162455. }
  162456. }
  162457. }
  162458. rc2 = sqlite3_reset(pSelect);
  162459. if( rc==SQLITE_OK ) rc = rc2;
  162460. }
  162461. return rc;
  162462. }
  162463. /*
  162464. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  162465. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  162466. ** consists of two varints, the absolute level number of the input segments
  162467. ** and the number of input segments.
  162468. **
  162469. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  162470. ** set *pRc to an SQLite error code before returning.
  162471. */
  162472. static void fts3IncrmergeHintPush(
  162473. Blob *pHint, /* Hint blob to append to */
  162474. i64 iAbsLevel, /* First varint to store in hint */
  162475. int nInput, /* Second varint to store in hint */
  162476. int *pRc /* IN/OUT: Error code */
  162477. ){
  162478. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  162479. if( *pRc==SQLITE_OK ){
  162480. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  162481. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  162482. }
  162483. }
  162484. /*
  162485. ** Read the last entry (most recently pushed) from the hint blob *pHint
  162486. ** and then remove the entry. Write the two values read to *piAbsLevel and
  162487. ** *pnInput before returning.
  162488. **
  162489. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  162490. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  162491. */
  162492. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  162493. const int nHint = pHint->n;
  162494. int i;
  162495. i = pHint->n-2;
  162496. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  162497. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  162498. pHint->n = i;
  162499. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  162500. i += fts3GetVarint32(&pHint->a[i], pnInput);
  162501. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  162502. return SQLITE_OK;
  162503. }
  162504. /*
  162505. ** Attempt an incremental merge that writes nMerge leaf blocks.
  162506. **
  162507. ** Incremental merges happen nMin segments at a time. The segments
  162508. ** to be merged are the nMin oldest segments (the ones with the smallest
  162509. ** values for the _segdir.idx field) in the highest level that contains
  162510. ** at least nMin segments. Multiple merges might occur in an attempt to
  162511. ** write the quota of nMerge leaf blocks.
  162512. */
  162513. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  162514. int rc; /* Return code */
  162515. int nRem = nMerge; /* Number of leaf pages yet to be written */
  162516. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  162517. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  162518. IncrmergeWriter *pWriter; /* Writer object */
  162519. int nSeg = 0; /* Number of input segments */
  162520. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  162521. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  162522. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  162523. /* Allocate space for the cursor, filter and writer objects */
  162524. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  162525. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  162526. if( !pWriter ) return SQLITE_NOMEM;
  162527. pFilter = (Fts3SegFilter *)&pWriter[1];
  162528. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  162529. rc = fts3IncrmergeHintLoad(p, &hint);
  162530. while( rc==SQLITE_OK && nRem>0 ){
  162531. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  162532. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  162533. int bUseHint = 0; /* True if attempting to append */
  162534. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  162535. /* Search the %_segdir table for the absolute level with the smallest
  162536. ** relative level number that contains at least nMin segments, if any.
  162537. ** If one is found, set iAbsLevel to the absolute level number and
  162538. ** nSeg to nMin. If no level with at least nMin segments can be found,
  162539. ** set nSeg to -1.
  162540. */
  162541. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  162542. sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
  162543. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  162544. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  162545. nSeg = sqlite3_column_int(pFindLevel, 1);
  162546. assert( nSeg>=2 );
  162547. }else{
  162548. nSeg = -1;
  162549. }
  162550. rc = sqlite3_reset(pFindLevel);
  162551. /* If the hint read from the %_stat table is not empty, check if the
  162552. ** last entry in it specifies a relative level smaller than or equal
  162553. ** to the level identified by the block above (if any). If so, this
  162554. ** iteration of the loop will work on merging at the hinted level.
  162555. */
  162556. if( rc==SQLITE_OK && hint.n ){
  162557. int nHint = hint.n;
  162558. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  162559. int nHintSeg = 0; /* Hint number of segments */
  162560. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  162561. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  162562. iAbsLevel = iHintAbsLevel;
  162563. nSeg = nHintSeg;
  162564. bUseHint = 1;
  162565. bDirtyHint = 1;
  162566. }else{
  162567. /* This undoes the effect of the HintPop() above - so that no entry
  162568. ** is removed from the hint blob. */
  162569. hint.n = nHint;
  162570. }
  162571. }
  162572. /* If nSeg is less that zero, then there is no level with at least
  162573. ** nMin segments and no hint in the %_stat table. No work to do.
  162574. ** Exit early in this case. */
  162575. if( nSeg<0 ) break;
  162576. /* Open a cursor to iterate through the contents of the oldest nSeg
  162577. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  162578. ** the 'hint' parameters, it is possible that there are less than nSeg
  162579. ** segments available in level iAbsLevel. In this case, no work is
  162580. ** done on iAbsLevel - fall through to the next iteration of the loop
  162581. ** to start work on some other level. */
  162582. memset(pWriter, 0, nAlloc);
  162583. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  162584. if( rc==SQLITE_OK ){
  162585. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  162586. assert( bUseHint==1 || bUseHint==0 );
  162587. if( iIdx==0 || (bUseHint && iIdx==1) ){
  162588. int bIgnore = 0;
  162589. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  162590. if( bIgnore ){
  162591. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  162592. }
  162593. }
  162594. }
  162595. if( rc==SQLITE_OK ){
  162596. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  162597. }
  162598. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  162599. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  162600. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  162601. ){
  162602. if( bUseHint && iIdx>0 ){
  162603. const char *zKey = pCsr->zTerm;
  162604. int nKey = pCsr->nTerm;
  162605. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  162606. }else{
  162607. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  162608. }
  162609. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  162610. fts3LogMerge(nSeg, iAbsLevel);
  162611. do {
  162612. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  162613. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  162614. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  162615. }while( rc==SQLITE_ROW );
  162616. /* Update or delete the input segments */
  162617. if( rc==SQLITE_OK ){
  162618. nRem -= (1 + pWriter->nWork);
  162619. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  162620. if( nSeg!=0 ){
  162621. bDirtyHint = 1;
  162622. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  162623. }
  162624. }
  162625. }
  162626. if( nSeg!=0 ){
  162627. pWriter->nLeafData = pWriter->nLeafData * -1;
  162628. }
  162629. fts3IncrmergeRelease(p, pWriter, &rc);
  162630. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  162631. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  162632. }
  162633. }
  162634. sqlite3Fts3SegReaderFinish(pCsr);
  162635. }
  162636. /* Write the hint values into the %_stat table for the next incr-merger */
  162637. if( bDirtyHint && rc==SQLITE_OK ){
  162638. rc = fts3IncrmergeHintStore(p, &hint);
  162639. }
  162640. sqlite3_free(pWriter);
  162641. sqlite3_free(hint.a);
  162642. return rc;
  162643. }
  162644. /*
  162645. ** Convert the text beginning at *pz into an integer and return
  162646. ** its value. Advance *pz to point to the first character past
  162647. ** the integer.
  162648. **
  162649. ** This function used for parameters to merge= and incrmerge=
  162650. ** commands.
  162651. */
  162652. static int fts3Getint(const char **pz){
  162653. const char *z = *pz;
  162654. int i = 0;
  162655. while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
  162656. *pz = z;
  162657. return i;
  162658. }
  162659. /*
  162660. ** Process statements of the form:
  162661. **
  162662. ** INSERT INTO table(table) VALUES('merge=A,B');
  162663. **
  162664. ** A and B are integers that decode to be the number of leaf pages
  162665. ** written for the merge, and the minimum number of segments on a level
  162666. ** before it will be selected for a merge, respectively.
  162667. */
  162668. static int fts3DoIncrmerge(
  162669. Fts3Table *p, /* FTS3 table handle */
  162670. const char *zParam /* Nul-terminated string containing "A,B" */
  162671. ){
  162672. int rc;
  162673. int nMin = (FTS3_MERGE_COUNT / 2);
  162674. int nMerge = 0;
  162675. const char *z = zParam;
  162676. /* Read the first integer value */
  162677. nMerge = fts3Getint(&z);
  162678. /* If the first integer value is followed by a ',', read the second
  162679. ** integer value. */
  162680. if( z[0]==',' && z[1]!='\0' ){
  162681. z++;
  162682. nMin = fts3Getint(&z);
  162683. }
  162684. if( z[0]!='\0' || nMin<2 ){
  162685. rc = SQLITE_ERROR;
  162686. }else{
  162687. rc = SQLITE_OK;
  162688. if( !p->bHasStat ){
  162689. assert( p->bFts4==0 );
  162690. sqlite3Fts3CreateStatTable(&rc, p);
  162691. }
  162692. if( rc==SQLITE_OK ){
  162693. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  162694. }
  162695. sqlite3Fts3SegmentsClose(p);
  162696. }
  162697. return rc;
  162698. }
  162699. /*
  162700. ** Process statements of the form:
  162701. **
  162702. ** INSERT INTO table(table) VALUES('automerge=X');
  162703. **
  162704. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  162705. ** turn it on. The setting is persistent.
  162706. */
  162707. static int fts3DoAutoincrmerge(
  162708. Fts3Table *p, /* FTS3 table handle */
  162709. const char *zParam /* Nul-terminated string containing boolean */
  162710. ){
  162711. int rc = SQLITE_OK;
  162712. sqlite3_stmt *pStmt = 0;
  162713. p->nAutoincrmerge = fts3Getint(&zParam);
  162714. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  162715. p->nAutoincrmerge = 8;
  162716. }
  162717. if( !p->bHasStat ){
  162718. assert( p->bFts4==0 );
  162719. sqlite3Fts3CreateStatTable(&rc, p);
  162720. if( rc ) return rc;
  162721. }
  162722. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  162723. if( rc ) return rc;
  162724. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  162725. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  162726. sqlite3_step(pStmt);
  162727. rc = sqlite3_reset(pStmt);
  162728. return rc;
  162729. }
  162730. /*
  162731. ** Return a 64-bit checksum for the FTS index entry specified by the
  162732. ** arguments to this function.
  162733. */
  162734. static u64 fts3ChecksumEntry(
  162735. const char *zTerm, /* Pointer to buffer containing term */
  162736. int nTerm, /* Size of zTerm in bytes */
  162737. int iLangid, /* Language id for current row */
  162738. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  162739. i64 iDocid, /* Docid for current row. */
  162740. int iCol, /* Column number */
  162741. int iPos /* Position */
  162742. ){
  162743. int i;
  162744. u64 ret = (u64)iDocid;
  162745. ret += (ret<<3) + iLangid;
  162746. ret += (ret<<3) + iIndex;
  162747. ret += (ret<<3) + iCol;
  162748. ret += (ret<<3) + iPos;
  162749. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  162750. return ret;
  162751. }
  162752. /*
  162753. ** Return a checksum of all entries in the FTS index that correspond to
  162754. ** language id iLangid. The checksum is calculated by XORing the checksums
  162755. ** of each individual entry (see fts3ChecksumEntry()) together.
  162756. **
  162757. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  162758. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  162759. ** return value is undefined in this case.
  162760. */
  162761. static u64 fts3ChecksumIndex(
  162762. Fts3Table *p, /* FTS3 table handle */
  162763. int iLangid, /* Language id to return cksum for */
  162764. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  162765. int *pRc /* OUT: Return code */
  162766. ){
  162767. Fts3SegFilter filter;
  162768. Fts3MultiSegReader csr;
  162769. int rc;
  162770. u64 cksum = 0;
  162771. assert( *pRc==SQLITE_OK );
  162772. memset(&filter, 0, sizeof(filter));
  162773. memset(&csr, 0, sizeof(csr));
  162774. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  162775. filter.flags |= FTS3_SEGMENT_SCAN;
  162776. rc = sqlite3Fts3SegReaderCursor(
  162777. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  162778. );
  162779. if( rc==SQLITE_OK ){
  162780. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  162781. }
  162782. if( rc==SQLITE_OK ){
  162783. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  162784. char *pCsr = csr.aDoclist;
  162785. char *pEnd = &pCsr[csr.nDoclist];
  162786. i64 iDocid = 0;
  162787. i64 iCol = 0;
  162788. i64 iPos = 0;
  162789. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  162790. while( pCsr<pEnd ){
  162791. i64 iVal = 0;
  162792. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  162793. if( pCsr<pEnd ){
  162794. if( iVal==0 || iVal==1 ){
  162795. iCol = 0;
  162796. iPos = 0;
  162797. if( iVal ){
  162798. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  162799. }else{
  162800. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  162801. iDocid += iVal;
  162802. }
  162803. }else{
  162804. iPos += (iVal - 2);
  162805. cksum = cksum ^ fts3ChecksumEntry(
  162806. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  162807. (int)iCol, (int)iPos
  162808. );
  162809. }
  162810. }
  162811. }
  162812. }
  162813. }
  162814. sqlite3Fts3SegReaderFinish(&csr);
  162815. *pRc = rc;
  162816. return cksum;
  162817. }
  162818. /*
  162819. ** Check if the contents of the FTS index match the current contents of the
  162820. ** content table. If no error occurs and the contents do match, set *pbOk
  162821. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  162822. ** to false before returning.
  162823. **
  162824. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  162825. ** code. The final value of *pbOk is undefined in this case.
  162826. */
  162827. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  162828. int rc = SQLITE_OK; /* Return code */
  162829. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  162830. u64 cksum2 = 0; /* Checksum based on %_content contents */
  162831. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  162832. /* This block calculates the checksum according to the FTS index. */
  162833. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  162834. if( rc==SQLITE_OK ){
  162835. int rc2;
  162836. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  162837. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  162838. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  162839. int iLangid = sqlite3_column_int(pAllLangid, 0);
  162840. int i;
  162841. for(i=0; i<p->nIndex; i++){
  162842. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  162843. }
  162844. }
  162845. rc2 = sqlite3_reset(pAllLangid);
  162846. if( rc==SQLITE_OK ) rc = rc2;
  162847. }
  162848. /* This block calculates the checksum according to the %_content table */
  162849. if( rc==SQLITE_OK ){
  162850. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  162851. sqlite3_stmt *pStmt = 0;
  162852. char *zSql;
  162853. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  162854. if( !zSql ){
  162855. rc = SQLITE_NOMEM;
  162856. }else{
  162857. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  162858. sqlite3_free(zSql);
  162859. }
  162860. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  162861. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  162862. int iLang = langidFromSelect(p, pStmt);
  162863. int iCol;
  162864. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  162865. if( p->abNotindexed[iCol]==0 ){
  162866. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  162867. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  162868. sqlite3_tokenizer_cursor *pT = 0;
  162869. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  162870. while( rc==SQLITE_OK ){
  162871. char const *zToken; /* Buffer containing token */
  162872. int nToken = 0; /* Number of bytes in token */
  162873. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  162874. int iPos = 0; /* Position of token in zText */
  162875. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  162876. if( rc==SQLITE_OK ){
  162877. int i;
  162878. cksum2 = cksum2 ^ fts3ChecksumEntry(
  162879. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  162880. );
  162881. for(i=1; i<p->nIndex; i++){
  162882. if( p->aIndex[i].nPrefix<=nToken ){
  162883. cksum2 = cksum2 ^ fts3ChecksumEntry(
  162884. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  162885. );
  162886. }
  162887. }
  162888. }
  162889. }
  162890. if( pT ) pModule->xClose(pT);
  162891. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  162892. }
  162893. }
  162894. }
  162895. sqlite3_finalize(pStmt);
  162896. }
  162897. *pbOk = (cksum1==cksum2);
  162898. return rc;
  162899. }
  162900. /*
  162901. ** Run the integrity-check. If no error occurs and the current contents of
  162902. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  162903. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  162904. **
  162905. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  162906. ** error code.
  162907. **
  162908. ** The integrity-check works as follows. For each token and indexed token
  162909. ** prefix in the document set, a 64-bit checksum is calculated (by code
  162910. ** in fts3ChecksumEntry()) based on the following:
  162911. **
  162912. ** + The index number (0 for the main index, 1 for the first prefix
  162913. ** index etc.),
  162914. ** + The token (or token prefix) text itself,
  162915. ** + The language-id of the row it appears in,
  162916. ** + The docid of the row it appears in,
  162917. ** + The column it appears in, and
  162918. ** + The tokens position within that column.
  162919. **
  162920. ** The checksums for all entries in the index are XORed together to create
  162921. ** a single checksum for the entire index.
  162922. **
  162923. ** The integrity-check code calculates the same checksum in two ways:
  162924. **
  162925. ** 1. By scanning the contents of the FTS index, and
  162926. ** 2. By scanning and tokenizing the content table.
  162927. **
  162928. ** If the two checksums are identical, the integrity-check is deemed to have
  162929. ** passed.
  162930. */
  162931. static int fts3DoIntegrityCheck(
  162932. Fts3Table *p /* FTS3 table handle */
  162933. ){
  162934. int rc;
  162935. int bOk = 0;
  162936. rc = fts3IntegrityCheck(p, &bOk);
  162937. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  162938. return rc;
  162939. }
  162940. /*
  162941. ** Handle a 'special' INSERT of the form:
  162942. **
  162943. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  162944. **
  162945. ** Argument pVal contains the result of <expr>. Currently the only
  162946. ** meaningful value to insert is the text 'optimize'.
  162947. */
  162948. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  162949. int rc; /* Return Code */
  162950. const char *zVal = (const char *)sqlite3_value_text(pVal);
  162951. int nVal = sqlite3_value_bytes(pVal);
  162952. if( !zVal ){
  162953. return SQLITE_NOMEM;
  162954. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  162955. rc = fts3DoOptimize(p, 0);
  162956. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  162957. rc = fts3DoRebuild(p);
  162958. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  162959. rc = fts3DoIntegrityCheck(p);
  162960. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  162961. rc = fts3DoIncrmerge(p, &zVal[6]);
  162962. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  162963. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  162964. #ifdef SQLITE_TEST
  162965. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  162966. p->nNodeSize = atoi(&zVal[9]);
  162967. rc = SQLITE_OK;
  162968. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  162969. p->nMaxPendingData = atoi(&zVal[11]);
  162970. rc = SQLITE_OK;
  162971. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  162972. p->bNoIncrDoclist = atoi(&zVal[21]);
  162973. rc = SQLITE_OK;
  162974. #endif
  162975. }else{
  162976. rc = SQLITE_ERROR;
  162977. }
  162978. return rc;
  162979. }
  162980. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  162981. /*
  162982. ** Delete all cached deferred doclists. Deferred doclists are cached
  162983. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  162984. */
  162985. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  162986. Fts3DeferredToken *pDef;
  162987. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  162988. fts3PendingListDelete(pDef->pList);
  162989. pDef->pList = 0;
  162990. }
  162991. }
  162992. /*
  162993. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  162994. ** this list using sqlite3Fts3DeferToken().
  162995. */
  162996. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  162997. Fts3DeferredToken *pDef;
  162998. Fts3DeferredToken *pNext;
  162999. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  163000. pNext = pDef->pNext;
  163001. fts3PendingListDelete(pDef->pList);
  163002. sqlite3_free(pDef);
  163003. }
  163004. pCsr->pDeferred = 0;
  163005. }
  163006. /*
  163007. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  163008. ** based on the row that pCsr currently points to.
  163009. **
  163010. ** A deferred-doclist is like any other doclist with position information
  163011. ** included, except that it only contains entries for a single row of the
  163012. ** table, not for all rows.
  163013. */
  163014. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  163015. int rc = SQLITE_OK; /* Return code */
  163016. if( pCsr->pDeferred ){
  163017. int i; /* Used to iterate through table columns */
  163018. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  163019. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  163020. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  163021. sqlite3_tokenizer *pT = p->pTokenizer;
  163022. sqlite3_tokenizer_module const *pModule = pT->pModule;
  163023. assert( pCsr->isRequireSeek==0 );
  163024. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  163025. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  163026. if( p->abNotindexed[i]==0 ){
  163027. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  163028. sqlite3_tokenizer_cursor *pTC = 0;
  163029. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  163030. while( rc==SQLITE_OK ){
  163031. char const *zToken; /* Buffer containing token */
  163032. int nToken = 0; /* Number of bytes in token */
  163033. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  163034. int iPos = 0; /* Position of token in zText */
  163035. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  163036. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  163037. Fts3PhraseToken *pPT = pDef->pToken;
  163038. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  163039. && (pPT->bFirst==0 || iPos==0)
  163040. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  163041. && (0==memcmp(zToken, pPT->z, pPT->n))
  163042. ){
  163043. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  163044. }
  163045. }
  163046. }
  163047. if( pTC ) pModule->xClose(pTC);
  163048. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  163049. }
  163050. }
  163051. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  163052. if( pDef->pList ){
  163053. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  163054. }
  163055. }
  163056. }
  163057. return rc;
  163058. }
  163059. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  163060. Fts3DeferredToken *p,
  163061. char **ppData,
  163062. int *pnData
  163063. ){
  163064. char *pRet;
  163065. int nSkip;
  163066. sqlite3_int64 dummy;
  163067. *ppData = 0;
  163068. *pnData = 0;
  163069. if( p->pList==0 ){
  163070. return SQLITE_OK;
  163071. }
  163072. pRet = (char *)sqlite3_malloc(p->pList->nData);
  163073. if( !pRet ) return SQLITE_NOMEM;
  163074. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  163075. *pnData = p->pList->nData - nSkip;
  163076. *ppData = pRet;
  163077. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  163078. return SQLITE_OK;
  163079. }
  163080. /*
  163081. ** Add an entry for token pToken to the pCsr->pDeferred list.
  163082. */
  163083. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  163084. Fts3Cursor *pCsr, /* Fts3 table cursor */
  163085. Fts3PhraseToken *pToken, /* Token to defer */
  163086. int iCol /* Column that token must appear in (or -1) */
  163087. ){
  163088. Fts3DeferredToken *pDeferred;
  163089. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  163090. if( !pDeferred ){
  163091. return SQLITE_NOMEM;
  163092. }
  163093. memset(pDeferred, 0, sizeof(*pDeferred));
  163094. pDeferred->pToken = pToken;
  163095. pDeferred->pNext = pCsr->pDeferred;
  163096. pDeferred->iCol = iCol;
  163097. pCsr->pDeferred = pDeferred;
  163098. assert( pToken->pDeferred==0 );
  163099. pToken->pDeferred = pDeferred;
  163100. return SQLITE_OK;
  163101. }
  163102. #endif
  163103. /*
  163104. ** SQLite value pRowid contains the rowid of a row that may or may not be
  163105. ** present in the FTS3 table. If it is, delete it and adjust the contents
  163106. ** of subsiduary data structures accordingly.
  163107. */
  163108. static int fts3DeleteByRowid(
  163109. Fts3Table *p,
  163110. sqlite3_value *pRowid,
  163111. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  163112. u32 *aSzDel
  163113. ){
  163114. int rc = SQLITE_OK; /* Return code */
  163115. int bFound = 0; /* True if *pRowid really is in the table */
  163116. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  163117. if( bFound && rc==SQLITE_OK ){
  163118. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  163119. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  163120. if( rc==SQLITE_OK ){
  163121. if( isEmpty ){
  163122. /* Deleting this row means the whole table is empty. In this case
  163123. ** delete the contents of all three tables and throw away any
  163124. ** data in the pendingTerms hash table. */
  163125. rc = fts3DeleteAll(p, 1);
  163126. *pnChng = 0;
  163127. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  163128. }else{
  163129. *pnChng = *pnChng - 1;
  163130. if( p->zContentTbl==0 ){
  163131. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  163132. }
  163133. if( p->bHasDocsize ){
  163134. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  163135. }
  163136. }
  163137. }
  163138. }
  163139. return rc;
  163140. }
  163141. /*
  163142. ** This function does the work for the xUpdate method of FTS3 virtual
  163143. ** tables. The schema of the virtual table being:
  163144. **
  163145. ** CREATE TABLE <table name>(
  163146. ** <user columns>,
  163147. ** <table name> HIDDEN,
  163148. ** docid HIDDEN,
  163149. ** <langid> HIDDEN
  163150. ** );
  163151. **
  163152. **
  163153. */
  163154. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  163155. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  163156. int nArg, /* Size of argument array */
  163157. sqlite3_value **apVal, /* Array of arguments */
  163158. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  163159. ){
  163160. Fts3Table *p = (Fts3Table *)pVtab;
  163161. int rc = SQLITE_OK; /* Return Code */
  163162. u32 *aSzIns = 0; /* Sizes of inserted documents */
  163163. u32 *aSzDel = 0; /* Sizes of deleted documents */
  163164. int nChng = 0; /* Net change in number of documents */
  163165. int bInsertDone = 0;
  163166. /* At this point it must be known if the %_stat table exists or not.
  163167. ** So bHasStat may not be 2. */
  163168. assert( p->bHasStat==0 || p->bHasStat==1 );
  163169. assert( p->pSegments==0 );
  163170. assert(
  163171. nArg==1 /* DELETE operations */
  163172. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  163173. );
  163174. /* Check for a "special" INSERT operation. One of the form:
  163175. **
  163176. ** INSERT INTO xyz(xyz) VALUES('command');
  163177. */
  163178. if( nArg>1
  163179. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  163180. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  163181. ){
  163182. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  163183. goto update_out;
  163184. }
  163185. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  163186. rc = SQLITE_CONSTRAINT;
  163187. goto update_out;
  163188. }
  163189. /* Allocate space to hold the change in document sizes */
  163190. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  163191. if( aSzDel==0 ){
  163192. rc = SQLITE_NOMEM;
  163193. goto update_out;
  163194. }
  163195. aSzIns = &aSzDel[p->nColumn+1];
  163196. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  163197. rc = fts3Writelock(p);
  163198. if( rc!=SQLITE_OK ) goto update_out;
  163199. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  163200. ** value, then this operation requires constraint handling.
  163201. **
  163202. ** If the on-conflict mode is REPLACE, this means that the existing row
  163203. ** should be deleted from the database before inserting the new row. Or,
  163204. ** if the on-conflict mode is other than REPLACE, then this method must
  163205. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  163206. ** modify the database file.
  163207. */
  163208. if( nArg>1 && p->zContentTbl==0 ){
  163209. /* Find the value object that holds the new rowid value. */
  163210. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  163211. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  163212. pNewRowid = apVal[1];
  163213. }
  163214. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  163215. sqlite3_value_type(apVal[0])==SQLITE_NULL
  163216. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  163217. )){
  163218. /* The new rowid is not NULL (in this case the rowid will be
  163219. ** automatically assigned and there is no chance of a conflict), and
  163220. ** the statement is either an INSERT or an UPDATE that modifies the
  163221. ** rowid column. So if the conflict mode is REPLACE, then delete any
  163222. ** existing row with rowid=pNewRowid.
  163223. **
  163224. ** Or, if the conflict mode is not REPLACE, insert the new record into
  163225. ** the %_content table. If we hit the duplicate rowid constraint (or any
  163226. ** other error) while doing so, return immediately.
  163227. **
  163228. ** This branch may also run if pNewRowid contains a value that cannot
  163229. ** be losslessly converted to an integer. In this case, the eventual
  163230. ** call to fts3InsertData() (either just below or further on in this
  163231. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  163232. ** invoked, it will delete zero rows (since no row will have
  163233. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  163234. */
  163235. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  163236. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  163237. }else{
  163238. rc = fts3InsertData(p, apVal, pRowid);
  163239. bInsertDone = 1;
  163240. }
  163241. }
  163242. }
  163243. if( rc!=SQLITE_OK ){
  163244. goto update_out;
  163245. }
  163246. /* If this is a DELETE or UPDATE operation, remove the old record. */
  163247. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  163248. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  163249. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  163250. }
  163251. /* If this is an INSERT or UPDATE operation, insert the new record. */
  163252. if( nArg>1 && rc==SQLITE_OK ){
  163253. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  163254. if( bInsertDone==0 ){
  163255. rc = fts3InsertData(p, apVal, pRowid);
  163256. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  163257. rc = FTS_CORRUPT_VTAB;
  163258. }
  163259. }
  163260. if( rc==SQLITE_OK ){
  163261. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  163262. }
  163263. if( rc==SQLITE_OK ){
  163264. assert( p->iPrevDocid==*pRowid );
  163265. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  163266. }
  163267. if( p->bHasDocsize ){
  163268. fts3InsertDocsize(&rc, p, aSzIns);
  163269. }
  163270. nChng++;
  163271. }
  163272. if( p->bFts4 ){
  163273. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  163274. }
  163275. update_out:
  163276. sqlite3_free(aSzDel);
  163277. sqlite3Fts3SegmentsClose(p);
  163278. return rc;
  163279. }
  163280. /*
  163281. ** Flush any data in the pending-terms hash table to disk. If successful,
  163282. ** merge all segments in the database (including the new segment, if
  163283. ** there was any data to flush) into a single segment.
  163284. */
  163285. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  163286. int rc;
  163287. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  163288. if( rc==SQLITE_OK ){
  163289. rc = fts3DoOptimize(p, 1);
  163290. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  163291. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  163292. if( rc2!=SQLITE_OK ) rc = rc2;
  163293. }else{
  163294. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  163295. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  163296. }
  163297. }
  163298. sqlite3Fts3SegmentsClose(p);
  163299. return rc;
  163300. }
  163301. #endif
  163302. /************** End of fts3_write.c ******************************************/
  163303. /************** Begin file fts3_snippet.c ************************************/
  163304. /*
  163305. ** 2009 Oct 23
  163306. **
  163307. ** The author disclaims copyright to this source code. In place of
  163308. ** a legal notice, here is a blessing:
  163309. **
  163310. ** May you do good and not evil.
  163311. ** May you find forgiveness for yourself and forgive others.
  163312. ** May you share freely, never taking more than you give.
  163313. **
  163314. ******************************************************************************
  163315. */
  163316. /* #include "fts3Int.h" */
  163317. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  163318. /* #include <string.h> */
  163319. /* #include <assert.h> */
  163320. /*
  163321. ** Characters that may appear in the second argument to matchinfo().
  163322. */
  163323. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  163324. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  163325. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  163326. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  163327. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  163328. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  163329. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  163330. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  163331. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  163332. /*
  163333. ** The default value for the second argument to matchinfo().
  163334. */
  163335. #define FTS3_MATCHINFO_DEFAULT "pcx"
  163336. /*
  163337. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  163338. ** Fts3Expr.aDoclist[]/nDoclist.
  163339. */
  163340. typedef struct LoadDoclistCtx LoadDoclistCtx;
  163341. struct LoadDoclistCtx {
  163342. Fts3Cursor *pCsr; /* FTS3 Cursor */
  163343. int nPhrase; /* Number of phrases seen so far */
  163344. int nToken; /* Number of tokens seen so far */
  163345. };
  163346. /*
  163347. ** The following types are used as part of the implementation of the
  163348. ** fts3BestSnippet() routine.
  163349. */
  163350. typedef struct SnippetIter SnippetIter;
  163351. typedef struct SnippetPhrase SnippetPhrase;
  163352. typedef struct SnippetFragment SnippetFragment;
  163353. struct SnippetIter {
  163354. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  163355. int iCol; /* Extract snippet from this column */
  163356. int nSnippet; /* Requested snippet length (in tokens) */
  163357. int nPhrase; /* Number of phrases in query */
  163358. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  163359. int iCurrent; /* First token of current snippet */
  163360. };
  163361. struct SnippetPhrase {
  163362. int nToken; /* Number of tokens in phrase */
  163363. char *pList; /* Pointer to start of phrase position list */
  163364. int iHead; /* Next value in position list */
  163365. char *pHead; /* Position list data following iHead */
  163366. int iTail; /* Next value in trailing position list */
  163367. char *pTail; /* Position list data following iTail */
  163368. };
  163369. struct SnippetFragment {
  163370. int iCol; /* Column snippet is extracted from */
  163371. int iPos; /* Index of first token in snippet */
  163372. u64 covered; /* Mask of query phrases covered */
  163373. u64 hlmask; /* Mask of snippet terms to highlight */
  163374. };
  163375. /*
  163376. ** This type is used as an fts3ExprIterate() context object while
  163377. ** accumulating the data returned by the matchinfo() function.
  163378. */
  163379. typedef struct MatchInfo MatchInfo;
  163380. struct MatchInfo {
  163381. Fts3Cursor *pCursor; /* FTS3 Cursor */
  163382. int nCol; /* Number of columns in table */
  163383. int nPhrase; /* Number of matchable phrases in query */
  163384. sqlite3_int64 nDoc; /* Number of docs in database */
  163385. char flag;
  163386. u32 *aMatchinfo; /* Pre-allocated buffer */
  163387. };
  163388. /*
  163389. ** An instance of this structure is used to manage a pair of buffers, each
  163390. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  163391. ** for details.
  163392. */
  163393. struct MatchinfoBuffer {
  163394. u8 aRef[3];
  163395. int nElem;
  163396. int bGlobal; /* Set if global data is loaded */
  163397. char *zMatchinfo;
  163398. u32 aMatchinfo[1];
  163399. };
  163400. /*
  163401. ** The snippet() and offsets() functions both return text values. An instance
  163402. ** of the following structure is used to accumulate those values while the
  163403. ** functions are running. See fts3StringAppend() for details.
  163404. */
  163405. typedef struct StrBuffer StrBuffer;
  163406. struct StrBuffer {
  163407. char *z; /* Pointer to buffer containing string */
  163408. int n; /* Length of z in bytes (excl. nul-term) */
  163409. int nAlloc; /* Allocated size of buffer z in bytes */
  163410. };
  163411. /*************************************************************************
  163412. ** Start of MatchinfoBuffer code.
  163413. */
  163414. /*
  163415. ** Allocate a two-slot MatchinfoBuffer object.
  163416. */
  163417. static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
  163418. MatchinfoBuffer *pRet;
  163419. int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
  163420. int nStr = (int)strlen(zMatchinfo);
  163421. pRet = sqlite3_malloc(nByte + nStr+1);
  163422. if( pRet ){
  163423. memset(pRet, 0, nByte);
  163424. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  163425. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
  163426. pRet->nElem = nElem;
  163427. pRet->zMatchinfo = ((char*)pRet) + nByte;
  163428. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  163429. pRet->aRef[0] = 1;
  163430. }
  163431. return pRet;
  163432. }
  163433. static void fts3MIBufferFree(void *p){
  163434. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  163435. assert( (u32*)p==&pBuf->aMatchinfo[1]
  163436. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  163437. );
  163438. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  163439. pBuf->aRef[1] = 0;
  163440. }else{
  163441. pBuf->aRef[2] = 0;
  163442. }
  163443. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  163444. sqlite3_free(pBuf);
  163445. }
  163446. }
  163447. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  163448. void (*xRet)(void*) = 0;
  163449. u32 *aOut = 0;
  163450. if( p->aRef[1]==0 ){
  163451. p->aRef[1] = 1;
  163452. aOut = &p->aMatchinfo[1];
  163453. xRet = fts3MIBufferFree;
  163454. }
  163455. else if( p->aRef[2]==0 ){
  163456. p->aRef[2] = 1;
  163457. aOut = &p->aMatchinfo[p->nElem+2];
  163458. xRet = fts3MIBufferFree;
  163459. }else{
  163460. aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
  163461. if( aOut ){
  163462. xRet = sqlite3_free;
  163463. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  163464. }
  163465. }
  163466. *paOut = aOut;
  163467. return xRet;
  163468. }
  163469. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  163470. p->bGlobal = 1;
  163471. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  163472. }
  163473. /*
  163474. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  163475. */
  163476. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  163477. if( p ){
  163478. assert( p->aRef[0]==1 );
  163479. p->aRef[0] = 0;
  163480. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  163481. sqlite3_free(p);
  163482. }
  163483. }
  163484. }
  163485. /*
  163486. ** End of MatchinfoBuffer code.
  163487. *************************************************************************/
  163488. /*
  163489. ** This function is used to help iterate through a position-list. A position
  163490. ** list is a list of unique integers, sorted from smallest to largest. Each
  163491. ** element of the list is represented by an FTS3 varint that takes the value
  163492. ** of the difference between the current element and the previous one plus
  163493. ** two. For example, to store the position-list:
  163494. **
  163495. ** 4 9 113
  163496. **
  163497. ** the three varints:
  163498. **
  163499. ** 6 7 106
  163500. **
  163501. ** are encoded.
  163502. **
  163503. ** When this function is called, *pp points to the start of an element of
  163504. ** the list. *piPos contains the value of the previous entry in the list.
  163505. ** After it returns, *piPos contains the value of the next element of the
  163506. ** list and *pp is advanced to the following varint.
  163507. */
  163508. static void fts3GetDeltaPosition(char **pp, int *piPos){
  163509. int iVal;
  163510. *pp += fts3GetVarint32(*pp, &iVal);
  163511. *piPos += (iVal-2);
  163512. }
  163513. /*
  163514. ** Helper function for fts3ExprIterate() (see below).
  163515. */
  163516. static int fts3ExprIterate2(
  163517. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  163518. int *piPhrase, /* Pointer to phrase counter */
  163519. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  163520. void *pCtx /* Second argument to pass to callback */
  163521. ){
  163522. int rc; /* Return code */
  163523. int eType = pExpr->eType; /* Type of expression node pExpr */
  163524. if( eType!=FTSQUERY_PHRASE ){
  163525. assert( pExpr->pLeft && pExpr->pRight );
  163526. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  163527. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  163528. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  163529. }
  163530. }else{
  163531. rc = x(pExpr, *piPhrase, pCtx);
  163532. (*piPhrase)++;
  163533. }
  163534. return rc;
  163535. }
  163536. /*
  163537. ** Iterate through all phrase nodes in an FTS3 query, except those that
  163538. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  163539. ** For each phrase node found, the supplied callback function is invoked.
  163540. **
  163541. ** If the callback function returns anything other than SQLITE_OK,
  163542. ** the iteration is abandoned and the error code returned immediately.
  163543. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  163544. ** all eligible phrase nodes.
  163545. */
  163546. static int fts3ExprIterate(
  163547. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  163548. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  163549. void *pCtx /* Second argument to pass to callback */
  163550. ){
  163551. int iPhrase = 0; /* Variable used as the phrase counter */
  163552. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  163553. }
  163554. /*
  163555. ** This is an fts3ExprIterate() callback used while loading the doclists
  163556. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  163557. ** fts3ExprLoadDoclists().
  163558. */
  163559. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  163560. int rc = SQLITE_OK;
  163561. Fts3Phrase *pPhrase = pExpr->pPhrase;
  163562. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  163563. UNUSED_PARAMETER(iPhrase);
  163564. p->nPhrase++;
  163565. p->nToken += pPhrase->nToken;
  163566. return rc;
  163567. }
  163568. /*
  163569. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  163570. ** pCsr.
  163571. **
  163572. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  163573. ** phrases in the expression (all phrases except those directly or
  163574. ** indirectly descended from the right-hand-side of a NOT operator). If
  163575. ** pnToken is not NULL, then it is set to the number of tokens in all
  163576. ** matchable phrases of the expression.
  163577. */
  163578. static int fts3ExprLoadDoclists(
  163579. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  163580. int *pnPhrase, /* OUT: Number of phrases in query */
  163581. int *pnToken /* OUT: Number of tokens in query */
  163582. ){
  163583. int rc; /* Return Code */
  163584. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  163585. sCtx.pCsr = pCsr;
  163586. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  163587. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  163588. if( pnToken ) *pnToken = sCtx.nToken;
  163589. return rc;
  163590. }
  163591. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  163592. (*(int *)ctx)++;
  163593. pExpr->iPhrase = iPhrase;
  163594. return SQLITE_OK;
  163595. }
  163596. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  163597. int nPhrase = 0;
  163598. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  163599. return nPhrase;
  163600. }
  163601. /*
  163602. ** Advance the position list iterator specified by the first two
  163603. ** arguments so that it points to the first element with a value greater
  163604. ** than or equal to parameter iNext.
  163605. */
  163606. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  163607. char *pIter = *ppIter;
  163608. if( pIter ){
  163609. int iIter = *piIter;
  163610. while( iIter<iNext ){
  163611. if( 0==(*pIter & 0xFE) ){
  163612. iIter = -1;
  163613. pIter = 0;
  163614. break;
  163615. }
  163616. fts3GetDeltaPosition(&pIter, &iIter);
  163617. }
  163618. *piIter = iIter;
  163619. *ppIter = pIter;
  163620. }
  163621. }
  163622. /*
  163623. ** Advance the snippet iterator to the next candidate snippet.
  163624. */
  163625. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  163626. int i; /* Loop counter */
  163627. if( pIter->iCurrent<0 ){
  163628. /* The SnippetIter object has just been initialized. The first snippet
  163629. ** candidate always starts at offset 0 (even if this candidate has a
  163630. ** score of 0.0).
  163631. */
  163632. pIter->iCurrent = 0;
  163633. /* Advance the 'head' iterator of each phrase to the first offset that
  163634. ** is greater than or equal to (iNext+nSnippet).
  163635. */
  163636. for(i=0; i<pIter->nPhrase; i++){
  163637. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  163638. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  163639. }
  163640. }else{
  163641. int iStart;
  163642. int iEnd = 0x7FFFFFFF;
  163643. for(i=0; i<pIter->nPhrase; i++){
  163644. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  163645. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  163646. iEnd = pPhrase->iHead;
  163647. }
  163648. }
  163649. if( iEnd==0x7FFFFFFF ){
  163650. return 1;
  163651. }
  163652. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  163653. for(i=0; i<pIter->nPhrase; i++){
  163654. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  163655. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  163656. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  163657. }
  163658. }
  163659. return 0;
  163660. }
  163661. /*
  163662. ** Retrieve information about the current candidate snippet of snippet
  163663. ** iterator pIter.
  163664. */
  163665. static void fts3SnippetDetails(
  163666. SnippetIter *pIter, /* Snippet iterator */
  163667. u64 mCovered, /* Bitmask of phrases already covered */
  163668. int *piToken, /* OUT: First token of proposed snippet */
  163669. int *piScore, /* OUT: "Score" for this snippet */
  163670. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  163671. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  163672. ){
  163673. int iStart = pIter->iCurrent; /* First token of snippet */
  163674. int iScore = 0; /* Score of this snippet */
  163675. int i; /* Loop counter */
  163676. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  163677. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  163678. for(i=0; i<pIter->nPhrase; i++){
  163679. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  163680. if( pPhrase->pTail ){
  163681. char *pCsr = pPhrase->pTail;
  163682. int iCsr = pPhrase->iTail;
  163683. while( iCsr<(iStart+pIter->nSnippet) ){
  163684. int j;
  163685. u64 mPhrase = (u64)1 << i;
  163686. u64 mPos = (u64)1 << (iCsr - iStart);
  163687. assert( iCsr>=iStart );
  163688. if( (mCover|mCovered)&mPhrase ){
  163689. iScore++;
  163690. }else{
  163691. iScore += 1000;
  163692. }
  163693. mCover |= mPhrase;
  163694. for(j=0; j<pPhrase->nToken; j++){
  163695. mHighlight |= (mPos>>j);
  163696. }
  163697. if( 0==(*pCsr & 0x0FE) ) break;
  163698. fts3GetDeltaPosition(&pCsr, &iCsr);
  163699. }
  163700. }
  163701. }
  163702. /* Set the output variables before returning. */
  163703. *piToken = iStart;
  163704. *piScore = iScore;
  163705. *pmCover = mCover;
  163706. *pmHighlight = mHighlight;
  163707. }
  163708. /*
  163709. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  163710. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  163711. */
  163712. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  163713. SnippetIter *p = (SnippetIter *)ctx;
  163714. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  163715. char *pCsr;
  163716. int rc;
  163717. pPhrase->nToken = pExpr->pPhrase->nToken;
  163718. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  163719. assert( rc==SQLITE_OK || pCsr==0 );
  163720. if( pCsr ){
  163721. int iFirst = 0;
  163722. pPhrase->pList = pCsr;
  163723. fts3GetDeltaPosition(&pCsr, &iFirst);
  163724. assert( iFirst>=0 );
  163725. pPhrase->pHead = pCsr;
  163726. pPhrase->pTail = pCsr;
  163727. pPhrase->iHead = iFirst;
  163728. pPhrase->iTail = iFirst;
  163729. }else{
  163730. assert( rc!=SQLITE_OK || (
  163731. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  163732. ));
  163733. }
  163734. return rc;
  163735. }
  163736. /*
  163737. ** Select the fragment of text consisting of nFragment contiguous tokens
  163738. ** from column iCol that represent the "best" snippet. The best snippet
  163739. ** is the snippet with the highest score, where scores are calculated
  163740. ** by adding:
  163741. **
  163742. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  163743. **
  163744. ** (b) +1000 points for the first occurrence of each matchable phrase in
  163745. ** the snippet for which the corresponding mCovered bit is not set.
  163746. **
  163747. ** The selected snippet parameters are stored in structure *pFragment before
  163748. ** returning. The score of the selected snippet is stored in *piScore
  163749. ** before returning.
  163750. */
  163751. static int fts3BestSnippet(
  163752. int nSnippet, /* Desired snippet length */
  163753. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  163754. int iCol, /* Index of column to create snippet from */
  163755. u64 mCovered, /* Mask of phrases already covered */
  163756. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  163757. SnippetFragment *pFragment, /* OUT: Best snippet found */
  163758. int *piScore /* OUT: Score of snippet pFragment */
  163759. ){
  163760. int rc; /* Return Code */
  163761. int nList; /* Number of phrases in expression */
  163762. SnippetIter sIter; /* Iterates through snippet candidates */
  163763. int nByte; /* Number of bytes of space to allocate */
  163764. int iBestScore = -1; /* Best snippet score found so far */
  163765. int i; /* Loop counter */
  163766. memset(&sIter, 0, sizeof(sIter));
  163767. /* Iterate through the phrases in the expression to count them. The same
  163768. ** callback makes sure the doclists are loaded for each phrase.
  163769. */
  163770. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  163771. if( rc!=SQLITE_OK ){
  163772. return rc;
  163773. }
  163774. /* Now that it is known how many phrases there are, allocate and zero
  163775. ** the required space using malloc().
  163776. */
  163777. nByte = sizeof(SnippetPhrase) * nList;
  163778. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  163779. if( !sIter.aPhrase ){
  163780. return SQLITE_NOMEM;
  163781. }
  163782. memset(sIter.aPhrase, 0, nByte);
  163783. /* Initialize the contents of the SnippetIter object. Then iterate through
  163784. ** the set of phrases in the expression to populate the aPhrase[] array.
  163785. */
  163786. sIter.pCsr = pCsr;
  163787. sIter.iCol = iCol;
  163788. sIter.nSnippet = nSnippet;
  163789. sIter.nPhrase = nList;
  163790. sIter.iCurrent = -1;
  163791. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  163792. if( rc==SQLITE_OK ){
  163793. /* Set the *pmSeen output variable. */
  163794. for(i=0; i<nList; i++){
  163795. if( sIter.aPhrase[i].pHead ){
  163796. *pmSeen |= (u64)1 << i;
  163797. }
  163798. }
  163799. /* Loop through all candidate snippets. Store the best snippet in
  163800. ** *pFragment. Store its associated 'score' in iBestScore.
  163801. */
  163802. pFragment->iCol = iCol;
  163803. while( !fts3SnippetNextCandidate(&sIter) ){
  163804. int iPos;
  163805. int iScore;
  163806. u64 mCover;
  163807. u64 mHighlite;
  163808. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  163809. assert( iScore>=0 );
  163810. if( iScore>iBestScore ){
  163811. pFragment->iPos = iPos;
  163812. pFragment->hlmask = mHighlite;
  163813. pFragment->covered = mCover;
  163814. iBestScore = iScore;
  163815. }
  163816. }
  163817. *piScore = iBestScore;
  163818. }
  163819. sqlite3_free(sIter.aPhrase);
  163820. return rc;
  163821. }
  163822. /*
  163823. ** Append a string to the string-buffer passed as the first argument.
  163824. **
  163825. ** If nAppend is negative, then the length of the string zAppend is
  163826. ** determined using strlen().
  163827. */
  163828. static int fts3StringAppend(
  163829. StrBuffer *pStr, /* Buffer to append to */
  163830. const char *zAppend, /* Pointer to data to append to buffer */
  163831. int nAppend /* Size of zAppend in bytes (or -1) */
  163832. ){
  163833. if( nAppend<0 ){
  163834. nAppend = (int)strlen(zAppend);
  163835. }
  163836. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  163837. ** to grow the buffer until so that it is big enough to accomadate the
  163838. ** appended data.
  163839. */
  163840. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  163841. int nAlloc = pStr->nAlloc+nAppend+100;
  163842. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  163843. if( !zNew ){
  163844. return SQLITE_NOMEM;
  163845. }
  163846. pStr->z = zNew;
  163847. pStr->nAlloc = nAlloc;
  163848. }
  163849. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  163850. /* Append the data to the string buffer. */
  163851. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  163852. pStr->n += nAppend;
  163853. pStr->z[pStr->n] = '\0';
  163854. return SQLITE_OK;
  163855. }
  163856. /*
  163857. ** The fts3BestSnippet() function often selects snippets that end with a
  163858. ** query term. That is, the final term of the snippet is always a term
  163859. ** that requires highlighting. For example, if 'X' is a highlighted term
  163860. ** and '.' is a non-highlighted term, BestSnippet() may select:
  163861. **
  163862. ** ........X.....X
  163863. **
  163864. ** This function "shifts" the beginning of the snippet forward in the
  163865. ** document so that there are approximately the same number of
  163866. ** non-highlighted terms to the right of the final highlighted term as there
  163867. ** are to the left of the first highlighted term. For example, to this:
  163868. **
  163869. ** ....X.....X....
  163870. **
  163871. ** This is done as part of extracting the snippet text, not when selecting
  163872. ** the snippet. Snippet selection is done based on doclists only, so there
  163873. ** is no way for fts3BestSnippet() to know whether or not the document
  163874. ** actually contains terms that follow the final highlighted term.
  163875. */
  163876. static int fts3SnippetShift(
  163877. Fts3Table *pTab, /* FTS3 table snippet comes from */
  163878. int iLangid, /* Language id to use in tokenizing */
  163879. int nSnippet, /* Number of tokens desired for snippet */
  163880. const char *zDoc, /* Document text to extract snippet from */
  163881. int nDoc, /* Size of buffer zDoc in bytes */
  163882. int *piPos, /* IN/OUT: First token of snippet */
  163883. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  163884. ){
  163885. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  163886. if( hlmask ){
  163887. int nLeft; /* Tokens to the left of first highlight */
  163888. int nRight; /* Tokens to the right of last highlight */
  163889. int nDesired; /* Ideal number of tokens to shift forward */
  163890. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  163891. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  163892. nDesired = (nLeft-nRight)/2;
  163893. /* Ideally, the start of the snippet should be pushed forward in the
  163894. ** document nDesired tokens. This block checks if there are actually
  163895. ** nDesired tokens to the right of the snippet. If so, *piPos and
  163896. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  163897. ** right. Otherwise, the snippet is shifted by the number of tokens
  163898. ** available.
  163899. */
  163900. if( nDesired>0 ){
  163901. int nShift; /* Number of tokens to shift snippet by */
  163902. int iCurrent = 0; /* Token counter */
  163903. int rc; /* Return Code */
  163904. sqlite3_tokenizer_module *pMod;
  163905. sqlite3_tokenizer_cursor *pC;
  163906. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  163907. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  163908. ** or more tokens in zDoc/nDoc.
  163909. */
  163910. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  163911. if( rc!=SQLITE_OK ){
  163912. return rc;
  163913. }
  163914. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  163915. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  163916. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  163917. }
  163918. pMod->xClose(pC);
  163919. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  163920. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  163921. assert( nShift<=nDesired );
  163922. if( nShift>0 ){
  163923. *piPos += nShift;
  163924. *pHlmask = hlmask >> nShift;
  163925. }
  163926. }
  163927. }
  163928. return SQLITE_OK;
  163929. }
  163930. /*
  163931. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  163932. ** append it to string buffer pOut.
  163933. */
  163934. static int fts3SnippetText(
  163935. Fts3Cursor *pCsr, /* FTS3 Cursor */
  163936. SnippetFragment *pFragment, /* Snippet to extract */
  163937. int iFragment, /* Fragment number */
  163938. int isLast, /* True for final fragment in snippet */
  163939. int nSnippet, /* Number of tokens in extracted snippet */
  163940. const char *zOpen, /* String inserted before highlighted term */
  163941. const char *zClose, /* String inserted after highlighted term */
  163942. const char *zEllipsis, /* String inserted between snippets */
  163943. StrBuffer *pOut /* Write output here */
  163944. ){
  163945. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  163946. int rc; /* Return code */
  163947. const char *zDoc; /* Document text to extract snippet from */
  163948. int nDoc; /* Size of zDoc in bytes */
  163949. int iCurrent = 0; /* Current token number of document */
  163950. int iEnd = 0; /* Byte offset of end of current token */
  163951. int isShiftDone = 0; /* True after snippet is shifted */
  163952. int iPos = pFragment->iPos; /* First token of snippet */
  163953. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  163954. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  163955. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  163956. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  163957. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  163958. if( zDoc==0 ){
  163959. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  163960. return SQLITE_NOMEM;
  163961. }
  163962. return SQLITE_OK;
  163963. }
  163964. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  163965. /* Open a token cursor on the document. */
  163966. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  163967. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  163968. if( rc!=SQLITE_OK ){
  163969. return rc;
  163970. }
  163971. while( rc==SQLITE_OK ){
  163972. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  163973. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  163974. int iBegin = 0; /* Offset in zDoc of start of token */
  163975. int iFin = 0; /* Offset in zDoc of end of token */
  163976. int isHighlight = 0; /* True for highlighted terms */
  163977. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  163978. ** in the FTS code the variable that the third argument to xNext points to
  163979. ** is initialized to zero before the first (*but not necessarily
  163980. ** subsequent*) call to xNext(). This is done for a particular application
  163981. ** that needs to know whether or not the tokenizer is being used for
  163982. ** snippet generation or for some other purpose.
  163983. **
  163984. ** Extreme care is required when writing code to depend on this
  163985. ** initialization. It is not a documented part of the tokenizer interface.
  163986. ** If a tokenizer is used directly by any code outside of FTS, this
  163987. ** convention might not be respected. */
  163988. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  163989. if( rc!=SQLITE_OK ){
  163990. if( rc==SQLITE_DONE ){
  163991. /* Special case - the last token of the snippet is also the last token
  163992. ** of the column. Append any punctuation that occurred between the end
  163993. ** of the previous token and the end of the document to the output.
  163994. ** Then break out of the loop. */
  163995. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  163996. }
  163997. break;
  163998. }
  163999. if( iCurrent<iPos ){ continue; }
  164000. if( !isShiftDone ){
  164001. int n = nDoc - iBegin;
  164002. rc = fts3SnippetShift(
  164003. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  164004. );
  164005. isShiftDone = 1;
  164006. /* Now that the shift has been done, check if the initial "..." are
  164007. ** required. They are required if (a) this is not the first fragment,
  164008. ** or (b) this fragment does not begin at position 0 of its column.
  164009. */
  164010. if( rc==SQLITE_OK ){
  164011. if( iPos>0 || iFragment>0 ){
  164012. rc = fts3StringAppend(pOut, zEllipsis, -1);
  164013. }else if( iBegin ){
  164014. rc = fts3StringAppend(pOut, zDoc, iBegin);
  164015. }
  164016. }
  164017. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  164018. }
  164019. if( iCurrent>=(iPos+nSnippet) ){
  164020. if( isLast ){
  164021. rc = fts3StringAppend(pOut, zEllipsis, -1);
  164022. }
  164023. break;
  164024. }
  164025. /* Set isHighlight to true if this term should be highlighted. */
  164026. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  164027. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  164028. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  164029. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  164030. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  164031. iEnd = iFin;
  164032. }
  164033. pMod->xClose(pC);
  164034. return rc;
  164035. }
  164036. /*
  164037. ** This function is used to count the entries in a column-list (a
  164038. ** delta-encoded list of term offsets within a single column of a single
  164039. ** row). When this function is called, *ppCollist should point to the
  164040. ** beginning of the first varint in the column-list (the varint that
  164041. ** contains the position of the first matching term in the column data).
  164042. ** Before returning, *ppCollist is set to point to the first byte after
  164043. ** the last varint in the column-list (either the 0x00 signifying the end
  164044. ** of the position-list, or the 0x01 that precedes the column number of
  164045. ** the next column in the position-list).
  164046. **
  164047. ** The number of elements in the column-list is returned.
  164048. */
  164049. static int fts3ColumnlistCount(char **ppCollist){
  164050. char *pEnd = *ppCollist;
  164051. char c = 0;
  164052. int nEntry = 0;
  164053. /* A column-list is terminated by either a 0x01 or 0x00. */
  164054. while( 0xFE & (*pEnd | c) ){
  164055. c = *pEnd++ & 0x80;
  164056. if( !c ) nEntry++;
  164057. }
  164058. *ppCollist = pEnd;
  164059. return nEntry;
  164060. }
  164061. /*
  164062. ** This function gathers 'y' or 'b' data for a single phrase.
  164063. */
  164064. static void fts3ExprLHits(
  164065. Fts3Expr *pExpr, /* Phrase expression node */
  164066. MatchInfo *p /* Matchinfo context */
  164067. ){
  164068. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  164069. int iStart;
  164070. Fts3Phrase *pPhrase = pExpr->pPhrase;
  164071. char *pIter = pPhrase->doclist.pList;
  164072. int iCol = 0;
  164073. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  164074. if( p->flag==FTS3_MATCHINFO_LHITS ){
  164075. iStart = pExpr->iPhrase * p->nCol;
  164076. }else{
  164077. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  164078. }
  164079. while( 1 ){
  164080. int nHit = fts3ColumnlistCount(&pIter);
  164081. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  164082. if( p->flag==FTS3_MATCHINFO_LHITS ){
  164083. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  164084. }else if( nHit ){
  164085. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  164086. }
  164087. }
  164088. assert( *pIter==0x00 || *pIter==0x01 );
  164089. if( *pIter!=0x01 ) break;
  164090. pIter++;
  164091. pIter += fts3GetVarint32(pIter, &iCol);
  164092. }
  164093. }
  164094. /*
  164095. ** Gather the results for matchinfo directives 'y' and 'b'.
  164096. */
  164097. static void fts3ExprLHitGather(
  164098. Fts3Expr *pExpr,
  164099. MatchInfo *p
  164100. ){
  164101. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  164102. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  164103. if( pExpr->pLeft ){
  164104. fts3ExprLHitGather(pExpr->pLeft, p);
  164105. fts3ExprLHitGather(pExpr->pRight, p);
  164106. }else{
  164107. fts3ExprLHits(pExpr, p);
  164108. }
  164109. }
  164110. }
  164111. /*
  164112. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  164113. ** for a single query.
  164114. **
  164115. ** fts3ExprIterate() callback to load the 'global' elements of a
  164116. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  164117. ** of the matchinfo array that are constant for all rows returned by the
  164118. ** current query.
  164119. **
  164120. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  164121. ** function populates Matchinfo.aMatchinfo[] as follows:
  164122. **
  164123. ** for(iCol=0; iCol<nCol; iCol++){
  164124. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  164125. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  164126. ** }
  164127. **
  164128. ** where X is the number of matches for phrase iPhrase is column iCol of all
  164129. ** rows of the table. Y is the number of rows for which column iCol contains
  164130. ** at least one instance of phrase iPhrase.
  164131. **
  164132. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  164133. ** Y values are set to nDoc, where nDoc is the number of documents in the
  164134. ** file system. This is done because the full-text index doclist is required
  164135. ** to calculate these values properly, and the full-text index doclist is
  164136. ** not available for deferred tokens.
  164137. */
  164138. static int fts3ExprGlobalHitsCb(
  164139. Fts3Expr *pExpr, /* Phrase expression node */
  164140. int iPhrase, /* Phrase number (numbered from zero) */
  164141. void *pCtx /* Pointer to MatchInfo structure */
  164142. ){
  164143. MatchInfo *p = (MatchInfo *)pCtx;
  164144. return sqlite3Fts3EvalPhraseStats(
  164145. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  164146. );
  164147. }
  164148. /*
  164149. ** fts3ExprIterate() callback used to collect the "local" part of the
  164150. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  164151. ** array that are different for each row returned by the query.
  164152. */
  164153. static int fts3ExprLocalHitsCb(
  164154. Fts3Expr *pExpr, /* Phrase expression node */
  164155. int iPhrase, /* Phrase number */
  164156. void *pCtx /* Pointer to MatchInfo structure */
  164157. ){
  164158. int rc = SQLITE_OK;
  164159. MatchInfo *p = (MatchInfo *)pCtx;
  164160. int iStart = iPhrase * p->nCol * 3;
  164161. int i;
  164162. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  164163. char *pCsr;
  164164. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  164165. if( pCsr ){
  164166. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  164167. }else{
  164168. p->aMatchinfo[iStart+i*3] = 0;
  164169. }
  164170. }
  164171. return rc;
  164172. }
  164173. static int fts3MatchinfoCheck(
  164174. Fts3Table *pTab,
  164175. char cArg,
  164176. char **pzErr
  164177. ){
  164178. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  164179. || (cArg==FTS3_MATCHINFO_NCOL)
  164180. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  164181. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  164182. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  164183. || (cArg==FTS3_MATCHINFO_LCS)
  164184. || (cArg==FTS3_MATCHINFO_HITS)
  164185. || (cArg==FTS3_MATCHINFO_LHITS)
  164186. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  164187. ){
  164188. return SQLITE_OK;
  164189. }
  164190. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  164191. return SQLITE_ERROR;
  164192. }
  164193. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  164194. int nVal; /* Number of integers output by cArg */
  164195. switch( cArg ){
  164196. case FTS3_MATCHINFO_NDOC:
  164197. case FTS3_MATCHINFO_NPHRASE:
  164198. case FTS3_MATCHINFO_NCOL:
  164199. nVal = 1;
  164200. break;
  164201. case FTS3_MATCHINFO_AVGLENGTH:
  164202. case FTS3_MATCHINFO_LENGTH:
  164203. case FTS3_MATCHINFO_LCS:
  164204. nVal = pInfo->nCol;
  164205. break;
  164206. case FTS3_MATCHINFO_LHITS:
  164207. nVal = pInfo->nCol * pInfo->nPhrase;
  164208. break;
  164209. case FTS3_MATCHINFO_LHITS_BM:
  164210. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  164211. break;
  164212. default:
  164213. assert( cArg==FTS3_MATCHINFO_HITS );
  164214. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  164215. break;
  164216. }
  164217. return nVal;
  164218. }
  164219. static int fts3MatchinfoSelectDoctotal(
  164220. Fts3Table *pTab,
  164221. sqlite3_stmt **ppStmt,
  164222. sqlite3_int64 *pnDoc,
  164223. const char **paLen
  164224. ){
  164225. sqlite3_stmt *pStmt;
  164226. const char *a;
  164227. sqlite3_int64 nDoc;
  164228. if( !*ppStmt ){
  164229. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  164230. if( rc!=SQLITE_OK ) return rc;
  164231. }
  164232. pStmt = *ppStmt;
  164233. assert( sqlite3_data_count(pStmt)==1 );
  164234. a = sqlite3_column_blob(pStmt, 0);
  164235. a += sqlite3Fts3GetVarint(a, &nDoc);
  164236. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  164237. *pnDoc = (u32)nDoc;
  164238. if( paLen ) *paLen = a;
  164239. return SQLITE_OK;
  164240. }
  164241. /*
  164242. ** An instance of the following structure is used to store state while
  164243. ** iterating through a multi-column position-list corresponding to the
  164244. ** hits for a single phrase on a single row in order to calculate the
  164245. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  164246. */
  164247. typedef struct LcsIterator LcsIterator;
  164248. struct LcsIterator {
  164249. Fts3Expr *pExpr; /* Pointer to phrase expression */
  164250. int iPosOffset; /* Tokens count up to end of this phrase */
  164251. char *pRead; /* Cursor used to iterate through aDoclist */
  164252. int iPos; /* Current position */
  164253. };
  164254. /*
  164255. ** If LcsIterator.iCol is set to the following value, the iterator has
  164256. ** finished iterating through all offsets for all columns.
  164257. */
  164258. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  164259. static int fts3MatchinfoLcsCb(
  164260. Fts3Expr *pExpr, /* Phrase expression node */
  164261. int iPhrase, /* Phrase number (numbered from zero) */
  164262. void *pCtx /* Pointer to MatchInfo structure */
  164263. ){
  164264. LcsIterator *aIter = (LcsIterator *)pCtx;
  164265. aIter[iPhrase].pExpr = pExpr;
  164266. return SQLITE_OK;
  164267. }
  164268. /*
  164269. ** Advance the iterator passed as an argument to the next position. Return
  164270. ** 1 if the iterator is at EOF or if it now points to the start of the
  164271. ** position list for the next column.
  164272. */
  164273. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  164274. char *pRead = pIter->pRead;
  164275. sqlite3_int64 iRead;
  164276. int rc = 0;
  164277. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  164278. if( iRead==0 || iRead==1 ){
  164279. pRead = 0;
  164280. rc = 1;
  164281. }else{
  164282. pIter->iPos += (int)(iRead-2);
  164283. }
  164284. pIter->pRead = pRead;
  164285. return rc;
  164286. }
  164287. /*
  164288. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  164289. **
  164290. ** If the call is successful, the longest-common-substring lengths for each
  164291. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  164292. ** array before returning. SQLITE_OK is returned in this case.
  164293. **
  164294. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  164295. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  164296. ** undefined.
  164297. */
  164298. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  164299. LcsIterator *aIter;
  164300. int i;
  164301. int iCol;
  164302. int nToken = 0;
  164303. /* Allocate and populate the array of LcsIterator objects. The array
  164304. ** contains one element for each matchable phrase in the query.
  164305. **/
  164306. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  164307. if( !aIter ) return SQLITE_NOMEM;
  164308. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  164309. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  164310. for(i=0; i<pInfo->nPhrase; i++){
  164311. LcsIterator *pIter = &aIter[i];
  164312. nToken -= pIter->pExpr->pPhrase->nToken;
  164313. pIter->iPosOffset = nToken;
  164314. }
  164315. for(iCol=0; iCol<pInfo->nCol; iCol++){
  164316. int nLcs = 0; /* LCS value for this column */
  164317. int nLive = 0; /* Number of iterators in aIter not at EOF */
  164318. for(i=0; i<pInfo->nPhrase; i++){
  164319. int rc;
  164320. LcsIterator *pIt = &aIter[i];
  164321. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  164322. if( rc!=SQLITE_OK ) return rc;
  164323. if( pIt->pRead ){
  164324. pIt->iPos = pIt->iPosOffset;
  164325. fts3LcsIteratorAdvance(&aIter[i]);
  164326. nLive++;
  164327. }
  164328. }
  164329. while( nLive>0 ){
  164330. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  164331. int nThisLcs = 0; /* LCS for the current iterator positions */
  164332. for(i=0; i<pInfo->nPhrase; i++){
  164333. LcsIterator *pIter = &aIter[i];
  164334. if( pIter->pRead==0 ){
  164335. /* This iterator is already at EOF for this column. */
  164336. nThisLcs = 0;
  164337. }else{
  164338. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  164339. pAdv = pIter;
  164340. }
  164341. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  164342. nThisLcs++;
  164343. }else{
  164344. nThisLcs = 1;
  164345. }
  164346. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  164347. }
  164348. }
  164349. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  164350. }
  164351. pInfo->aMatchinfo[iCol] = nLcs;
  164352. }
  164353. sqlite3_free(aIter);
  164354. return SQLITE_OK;
  164355. }
  164356. /*
  164357. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  164358. ** be returned by the matchinfo() function. Argument zArg contains the
  164359. ** format string passed as the second argument to matchinfo (or the
  164360. ** default value "pcx" if no second argument was specified). The format
  164361. ** string has already been validated and the pInfo->aMatchinfo[] array
  164362. ** is guaranteed to be large enough for the output.
  164363. **
  164364. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  164365. ** If it is false, then assume that those fields that do not change between
  164366. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  164367. ** have already been populated.
  164368. **
  164369. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  164370. ** occurs. If a value other than SQLITE_OK is returned, the state the
  164371. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  164372. */
  164373. static int fts3MatchinfoValues(
  164374. Fts3Cursor *pCsr, /* FTS3 cursor object */
  164375. int bGlobal, /* True to grab the global stats */
  164376. MatchInfo *pInfo, /* Matchinfo context object */
  164377. const char *zArg /* Matchinfo format string */
  164378. ){
  164379. int rc = SQLITE_OK;
  164380. int i;
  164381. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  164382. sqlite3_stmt *pSelect = 0;
  164383. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  164384. pInfo->flag = zArg[i];
  164385. switch( zArg[i] ){
  164386. case FTS3_MATCHINFO_NPHRASE:
  164387. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  164388. break;
  164389. case FTS3_MATCHINFO_NCOL:
  164390. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  164391. break;
  164392. case FTS3_MATCHINFO_NDOC:
  164393. if( bGlobal ){
  164394. sqlite3_int64 nDoc = 0;
  164395. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  164396. pInfo->aMatchinfo[0] = (u32)nDoc;
  164397. }
  164398. break;
  164399. case FTS3_MATCHINFO_AVGLENGTH:
  164400. if( bGlobal ){
  164401. sqlite3_int64 nDoc; /* Number of rows in table */
  164402. const char *a; /* Aggregate column length array */
  164403. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  164404. if( rc==SQLITE_OK ){
  164405. int iCol;
  164406. for(iCol=0; iCol<pInfo->nCol; iCol++){
  164407. u32 iVal;
  164408. sqlite3_int64 nToken;
  164409. a += sqlite3Fts3GetVarint(a, &nToken);
  164410. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  164411. pInfo->aMatchinfo[iCol] = iVal;
  164412. }
  164413. }
  164414. }
  164415. break;
  164416. case FTS3_MATCHINFO_LENGTH: {
  164417. sqlite3_stmt *pSelectDocsize = 0;
  164418. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  164419. if( rc==SQLITE_OK ){
  164420. int iCol;
  164421. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  164422. for(iCol=0; iCol<pInfo->nCol; iCol++){
  164423. sqlite3_int64 nToken;
  164424. a += sqlite3Fts3GetVarint(a, &nToken);
  164425. pInfo->aMatchinfo[iCol] = (u32)nToken;
  164426. }
  164427. }
  164428. sqlite3_reset(pSelectDocsize);
  164429. break;
  164430. }
  164431. case FTS3_MATCHINFO_LCS:
  164432. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  164433. if( rc==SQLITE_OK ){
  164434. rc = fts3MatchinfoLcs(pCsr, pInfo);
  164435. }
  164436. break;
  164437. case FTS3_MATCHINFO_LHITS_BM:
  164438. case FTS3_MATCHINFO_LHITS: {
  164439. int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  164440. memset(pInfo->aMatchinfo, 0, nZero);
  164441. fts3ExprLHitGather(pCsr->pExpr, pInfo);
  164442. break;
  164443. }
  164444. default: {
  164445. Fts3Expr *pExpr;
  164446. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  164447. pExpr = pCsr->pExpr;
  164448. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  164449. if( rc!=SQLITE_OK ) break;
  164450. if( bGlobal ){
  164451. if( pCsr->pDeferred ){
  164452. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  164453. if( rc!=SQLITE_OK ) break;
  164454. }
  164455. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  164456. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  164457. if( rc!=SQLITE_OK ) break;
  164458. }
  164459. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  164460. break;
  164461. }
  164462. }
  164463. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  164464. }
  164465. sqlite3_reset(pSelect);
  164466. return rc;
  164467. }
  164468. /*
  164469. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  164470. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  164471. */
  164472. static void fts3GetMatchinfo(
  164473. sqlite3_context *pCtx, /* Return results here */
  164474. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  164475. const char *zArg /* Second argument to matchinfo() function */
  164476. ){
  164477. MatchInfo sInfo;
  164478. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  164479. int rc = SQLITE_OK;
  164480. int bGlobal = 0; /* Collect 'global' stats as well as local */
  164481. u32 *aOut = 0;
  164482. void (*xDestroyOut)(void*) = 0;
  164483. memset(&sInfo, 0, sizeof(MatchInfo));
  164484. sInfo.pCursor = pCsr;
  164485. sInfo.nCol = pTab->nColumn;
  164486. /* If there is cached matchinfo() data, but the format string for the
  164487. ** cache does not match the format string for this request, discard
  164488. ** the cached data. */
  164489. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  164490. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  164491. pCsr->pMIBuffer = 0;
  164492. }
  164493. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  164494. ** matchinfo function has been called for this query. In this case
  164495. ** allocate the array used to accumulate the matchinfo data and
  164496. ** initialize those elements that are constant for every row.
  164497. */
  164498. if( pCsr->pMIBuffer==0 ){
  164499. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  164500. int i; /* Used to iterate through zArg */
  164501. /* Determine the number of phrases in the query */
  164502. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  164503. sInfo.nPhrase = pCsr->nPhrase;
  164504. /* Determine the number of integers in the buffer returned by this call. */
  164505. for(i=0; zArg[i]; i++){
  164506. char *zErr = 0;
  164507. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  164508. sqlite3_result_error(pCtx, zErr, -1);
  164509. sqlite3_free(zErr);
  164510. return;
  164511. }
  164512. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  164513. }
  164514. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  164515. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  164516. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  164517. pCsr->isMatchinfoNeeded = 1;
  164518. bGlobal = 1;
  164519. }
  164520. if( rc==SQLITE_OK ){
  164521. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  164522. if( xDestroyOut==0 ){
  164523. rc = SQLITE_NOMEM;
  164524. }
  164525. }
  164526. if( rc==SQLITE_OK ){
  164527. sInfo.aMatchinfo = aOut;
  164528. sInfo.nPhrase = pCsr->nPhrase;
  164529. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  164530. if( bGlobal ){
  164531. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  164532. }
  164533. }
  164534. if( rc!=SQLITE_OK ){
  164535. sqlite3_result_error_code(pCtx, rc);
  164536. if( xDestroyOut ) xDestroyOut(aOut);
  164537. }else{
  164538. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  164539. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  164540. }
  164541. }
  164542. /*
  164543. ** Implementation of snippet() function.
  164544. */
  164545. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  164546. sqlite3_context *pCtx, /* SQLite function call context */
  164547. Fts3Cursor *pCsr, /* Cursor object */
  164548. const char *zStart, /* Snippet start text - "<b>" */
  164549. const char *zEnd, /* Snippet end text - "</b>" */
  164550. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  164551. int iCol, /* Extract snippet from this column */
  164552. int nToken /* Approximate number of tokens in snippet */
  164553. ){
  164554. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  164555. int rc = SQLITE_OK;
  164556. int i;
  164557. StrBuffer res = {0, 0, 0};
  164558. /* The returned text includes up to four fragments of text extracted from
  164559. ** the data in the current row. The first iteration of the for(...) loop
  164560. ** below attempts to locate a single fragment of text nToken tokens in
  164561. ** size that contains at least one instance of all phrases in the query
  164562. ** expression that appear in the current row. If such a fragment of text
  164563. ** cannot be found, the second iteration of the loop attempts to locate
  164564. ** a pair of fragments, and so on.
  164565. */
  164566. int nSnippet = 0; /* Number of fragments in this snippet */
  164567. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  164568. int nFToken = -1; /* Number of tokens in each fragment */
  164569. if( !pCsr->pExpr ){
  164570. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  164571. return;
  164572. }
  164573. for(nSnippet=1; 1; nSnippet++){
  164574. int iSnip; /* Loop counter 0..nSnippet-1 */
  164575. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  164576. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  164577. if( nToken>=0 ){
  164578. nFToken = (nToken+nSnippet-1) / nSnippet;
  164579. }else{
  164580. nFToken = -1 * nToken;
  164581. }
  164582. for(iSnip=0; iSnip<nSnippet; iSnip++){
  164583. int iBestScore = -1; /* Best score of columns checked so far */
  164584. int iRead; /* Used to iterate through columns */
  164585. SnippetFragment *pFragment = &aSnippet[iSnip];
  164586. memset(pFragment, 0, sizeof(*pFragment));
  164587. /* Loop through all columns of the table being considered for snippets.
  164588. ** If the iCol argument to this function was negative, this means all
  164589. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  164590. */
  164591. for(iRead=0; iRead<pTab->nColumn; iRead++){
  164592. SnippetFragment sF = {0, 0, 0, 0};
  164593. int iS = 0;
  164594. if( iCol>=0 && iRead!=iCol ) continue;
  164595. /* Find the best snippet of nFToken tokens in column iRead. */
  164596. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  164597. if( rc!=SQLITE_OK ){
  164598. goto snippet_out;
  164599. }
  164600. if( iS>iBestScore ){
  164601. *pFragment = sF;
  164602. iBestScore = iS;
  164603. }
  164604. }
  164605. mCovered |= pFragment->covered;
  164606. }
  164607. /* If all query phrases seen by fts3BestSnippet() are present in at least
  164608. ** one of the nSnippet snippet fragments, break out of the loop.
  164609. */
  164610. assert( (mCovered&mSeen)==mCovered );
  164611. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  164612. }
  164613. assert( nFToken>0 );
  164614. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  164615. rc = fts3SnippetText(pCsr, &aSnippet[i],
  164616. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  164617. );
  164618. }
  164619. snippet_out:
  164620. sqlite3Fts3SegmentsClose(pTab);
  164621. if( rc!=SQLITE_OK ){
  164622. sqlite3_result_error_code(pCtx, rc);
  164623. sqlite3_free(res.z);
  164624. }else{
  164625. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  164626. }
  164627. }
  164628. typedef struct TermOffset TermOffset;
  164629. typedef struct TermOffsetCtx TermOffsetCtx;
  164630. struct TermOffset {
  164631. char *pList; /* Position-list */
  164632. int iPos; /* Position just read from pList */
  164633. int iOff; /* Offset of this term from read positions */
  164634. };
  164635. struct TermOffsetCtx {
  164636. Fts3Cursor *pCsr;
  164637. int iCol; /* Column of table to populate aTerm for */
  164638. int iTerm;
  164639. sqlite3_int64 iDocid;
  164640. TermOffset *aTerm;
  164641. };
  164642. /*
  164643. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  164644. */
  164645. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  164646. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  164647. int nTerm; /* Number of tokens in phrase */
  164648. int iTerm; /* For looping through nTerm phrase terms */
  164649. char *pList; /* Pointer to position list for phrase */
  164650. int iPos = 0; /* First position in position-list */
  164651. int rc;
  164652. UNUSED_PARAMETER(iPhrase);
  164653. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  164654. nTerm = pExpr->pPhrase->nToken;
  164655. if( pList ){
  164656. fts3GetDeltaPosition(&pList, &iPos);
  164657. assert( iPos>=0 );
  164658. }
  164659. for(iTerm=0; iTerm<nTerm; iTerm++){
  164660. TermOffset *pT = &p->aTerm[p->iTerm++];
  164661. pT->iOff = nTerm-iTerm-1;
  164662. pT->pList = pList;
  164663. pT->iPos = iPos;
  164664. }
  164665. return rc;
  164666. }
  164667. /*
  164668. ** Implementation of offsets() function.
  164669. */
  164670. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  164671. sqlite3_context *pCtx, /* SQLite function call context */
  164672. Fts3Cursor *pCsr /* Cursor object */
  164673. ){
  164674. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  164675. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  164676. int rc; /* Return Code */
  164677. int nToken; /* Number of tokens in query */
  164678. int iCol; /* Column currently being processed */
  164679. StrBuffer res = {0, 0, 0}; /* Result string */
  164680. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  164681. if( !pCsr->pExpr ){
  164682. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  164683. return;
  164684. }
  164685. memset(&sCtx, 0, sizeof(sCtx));
  164686. assert( pCsr->isRequireSeek==0 );
  164687. /* Count the number of terms in the query */
  164688. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  164689. if( rc!=SQLITE_OK ) goto offsets_out;
  164690. /* Allocate the array of TermOffset iterators. */
  164691. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  164692. if( 0==sCtx.aTerm ){
  164693. rc = SQLITE_NOMEM;
  164694. goto offsets_out;
  164695. }
  164696. sCtx.iDocid = pCsr->iPrevId;
  164697. sCtx.pCsr = pCsr;
  164698. /* Loop through the table columns, appending offset information to
  164699. ** string-buffer res for each column.
  164700. */
  164701. for(iCol=0; iCol<pTab->nColumn; iCol++){
  164702. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  164703. const char *ZDUMMY; /* Dummy argument used with xNext() */
  164704. int NDUMMY = 0; /* Dummy argument used with xNext() */
  164705. int iStart = 0;
  164706. int iEnd = 0;
  164707. int iCurrent = 0;
  164708. const char *zDoc;
  164709. int nDoc;
  164710. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  164711. ** no way that this operation can fail, so the return code from
  164712. ** fts3ExprIterate() can be discarded.
  164713. */
  164714. sCtx.iCol = iCol;
  164715. sCtx.iTerm = 0;
  164716. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  164717. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  164718. ** in column iCol, jump immediately to the next iteration of the loop.
  164719. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  164720. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  164721. ** to the caller.
  164722. */
  164723. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  164724. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  164725. if( zDoc==0 ){
  164726. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  164727. continue;
  164728. }
  164729. rc = SQLITE_NOMEM;
  164730. goto offsets_out;
  164731. }
  164732. /* Initialize a tokenizer iterator to iterate through column iCol. */
  164733. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  164734. zDoc, nDoc, &pC
  164735. );
  164736. if( rc!=SQLITE_OK ) goto offsets_out;
  164737. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  164738. while( rc==SQLITE_OK ){
  164739. int i; /* Used to loop through terms */
  164740. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  164741. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  164742. for(i=0; i<nToken; i++){
  164743. TermOffset *pT = &sCtx.aTerm[i];
  164744. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  164745. iMinPos = pT->iPos-pT->iOff;
  164746. pTerm = pT;
  164747. }
  164748. }
  164749. if( !pTerm ){
  164750. /* All offsets for this column have been gathered. */
  164751. rc = SQLITE_DONE;
  164752. }else{
  164753. assert( iCurrent<=iMinPos );
  164754. if( 0==(0xFE&*pTerm->pList) ){
  164755. pTerm->pList = 0;
  164756. }else{
  164757. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  164758. }
  164759. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  164760. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  164761. }
  164762. if( rc==SQLITE_OK ){
  164763. char aBuffer[64];
  164764. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  164765. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  164766. );
  164767. rc = fts3StringAppend(&res, aBuffer, -1);
  164768. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  164769. rc = FTS_CORRUPT_VTAB;
  164770. }
  164771. }
  164772. }
  164773. if( rc==SQLITE_DONE ){
  164774. rc = SQLITE_OK;
  164775. }
  164776. pMod->xClose(pC);
  164777. if( rc!=SQLITE_OK ) goto offsets_out;
  164778. }
  164779. offsets_out:
  164780. sqlite3_free(sCtx.aTerm);
  164781. assert( rc!=SQLITE_DONE );
  164782. sqlite3Fts3SegmentsClose(pTab);
  164783. if( rc!=SQLITE_OK ){
  164784. sqlite3_result_error_code(pCtx, rc);
  164785. sqlite3_free(res.z);
  164786. }else{
  164787. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  164788. }
  164789. return;
  164790. }
  164791. /*
  164792. ** Implementation of matchinfo() function.
  164793. */
  164794. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  164795. sqlite3_context *pContext, /* Function call context */
  164796. Fts3Cursor *pCsr, /* FTS3 table cursor */
  164797. const char *zArg /* Second arg to matchinfo() function */
  164798. ){
  164799. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  164800. const char *zFormat;
  164801. if( zArg ){
  164802. zFormat = zArg;
  164803. }else{
  164804. zFormat = FTS3_MATCHINFO_DEFAULT;
  164805. }
  164806. if( !pCsr->pExpr ){
  164807. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  164808. return;
  164809. }else{
  164810. /* Retrieve matchinfo() data. */
  164811. fts3GetMatchinfo(pContext, pCsr, zFormat);
  164812. sqlite3Fts3SegmentsClose(pTab);
  164813. }
  164814. }
  164815. #endif
  164816. /************** End of fts3_snippet.c ****************************************/
  164817. /************** Begin file fts3_unicode.c ************************************/
  164818. /*
  164819. ** 2012 May 24
  164820. **
  164821. ** The author disclaims copyright to this source code. In place of
  164822. ** a legal notice, here is a blessing:
  164823. **
  164824. ** May you do good and not evil.
  164825. ** May you find forgiveness for yourself and forgive others.
  164826. ** May you share freely, never taking more than you give.
  164827. **
  164828. ******************************************************************************
  164829. **
  164830. ** Implementation of the "unicode" full-text-search tokenizer.
  164831. */
  164832. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  164833. /* #include "fts3Int.h" */
  164834. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  164835. /* #include <assert.h> */
  164836. /* #include <stdlib.h> */
  164837. /* #include <stdio.h> */
  164838. /* #include <string.h> */
  164839. /* #include "fts3_tokenizer.h" */
  164840. /*
  164841. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  164842. ** from the sqlite3 source file utf.c. If this file is compiled as part
  164843. ** of the amalgamation, they are not required.
  164844. */
  164845. #ifndef SQLITE_AMALGAMATION
  164846. static const unsigned char sqlite3Utf8Trans1[] = {
  164847. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  164848. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  164849. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  164850. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  164851. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  164852. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  164853. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  164854. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  164855. };
  164856. #define READ_UTF8(zIn, zTerm, c) \
  164857. c = *(zIn++); \
  164858. if( c>=0xc0 ){ \
  164859. c = sqlite3Utf8Trans1[c-0xc0]; \
  164860. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  164861. c = (c<<6) + (0x3f & *(zIn++)); \
  164862. } \
  164863. if( c<0x80 \
  164864. || (c&0xFFFFF800)==0xD800 \
  164865. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  164866. }
  164867. #define WRITE_UTF8(zOut, c) { \
  164868. if( c<0x00080 ){ \
  164869. *zOut++ = (u8)(c&0xFF); \
  164870. } \
  164871. else if( c<0x00800 ){ \
  164872. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  164873. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  164874. } \
  164875. else if( c<0x10000 ){ \
  164876. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  164877. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  164878. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  164879. }else{ \
  164880. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  164881. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  164882. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  164883. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  164884. } \
  164885. }
  164886. #endif /* ifndef SQLITE_AMALGAMATION */
  164887. typedef struct unicode_tokenizer unicode_tokenizer;
  164888. typedef struct unicode_cursor unicode_cursor;
  164889. struct unicode_tokenizer {
  164890. sqlite3_tokenizer base;
  164891. int bRemoveDiacritic;
  164892. int nException;
  164893. int *aiException;
  164894. };
  164895. struct unicode_cursor {
  164896. sqlite3_tokenizer_cursor base;
  164897. const unsigned char *aInput; /* Input text being tokenized */
  164898. int nInput; /* Size of aInput[] in bytes */
  164899. int iOff; /* Current offset within aInput[] */
  164900. int iToken; /* Index of next token to be returned */
  164901. char *zToken; /* storage for current token */
  164902. int nAlloc; /* space allocated at zToken */
  164903. };
  164904. /*
  164905. ** Destroy a tokenizer allocated by unicodeCreate().
  164906. */
  164907. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  164908. if( pTokenizer ){
  164909. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  164910. sqlite3_free(p->aiException);
  164911. sqlite3_free(p);
  164912. }
  164913. return SQLITE_OK;
  164914. }
  164915. /*
  164916. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  164917. ** statement has specified that the tokenizer for this table shall consider
  164918. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  164919. ** token characters (if bAlnum==1).
  164920. **
  164921. ** For each codepoint in the zIn/nIn string, this function checks if the
  164922. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  164923. ** If so, no action is taken. Otherwise, the codepoint is added to the
  164924. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  164925. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  164926. ** codepoints in the aiException[] array.
  164927. **
  164928. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  164929. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  164930. ** It is not possible to change the behavior of the tokenizer with respect
  164931. ** to these codepoints.
  164932. */
  164933. static int unicodeAddExceptions(
  164934. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  164935. int bAlnum, /* Replace Isalnum() return value with this */
  164936. const char *zIn, /* Array of characters to make exceptions */
  164937. int nIn /* Length of z in bytes */
  164938. ){
  164939. const unsigned char *z = (const unsigned char *)zIn;
  164940. const unsigned char *zTerm = &z[nIn];
  164941. unsigned int iCode;
  164942. int nEntry = 0;
  164943. assert( bAlnum==0 || bAlnum==1 );
  164944. while( z<zTerm ){
  164945. READ_UTF8(z, zTerm, iCode);
  164946. assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
  164947. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  164948. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  164949. ){
  164950. nEntry++;
  164951. }
  164952. }
  164953. if( nEntry ){
  164954. int *aNew; /* New aiException[] array */
  164955. int nNew; /* Number of valid entries in array aNew[] */
  164956. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  164957. if( aNew==0 ) return SQLITE_NOMEM;
  164958. nNew = p->nException;
  164959. z = (const unsigned char *)zIn;
  164960. while( z<zTerm ){
  164961. READ_UTF8(z, zTerm, iCode);
  164962. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  164963. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  164964. ){
  164965. int i, j;
  164966. for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
  164967. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  164968. aNew[i] = (int)iCode;
  164969. nNew++;
  164970. }
  164971. }
  164972. p->aiException = aNew;
  164973. p->nException = nNew;
  164974. }
  164975. return SQLITE_OK;
  164976. }
  164977. /*
  164978. ** Return true if the p->aiException[] array contains the value iCode.
  164979. */
  164980. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  164981. if( p->nException>0 ){
  164982. int *a = p->aiException;
  164983. int iLo = 0;
  164984. int iHi = p->nException-1;
  164985. while( iHi>=iLo ){
  164986. int iTest = (iHi + iLo) / 2;
  164987. if( iCode==a[iTest] ){
  164988. return 1;
  164989. }else if( iCode>a[iTest] ){
  164990. iLo = iTest+1;
  164991. }else{
  164992. iHi = iTest-1;
  164993. }
  164994. }
  164995. }
  164996. return 0;
  164997. }
  164998. /*
  164999. ** Return true if, for the purposes of tokenization, codepoint iCode is
  165000. ** considered a token character (not a separator).
  165001. */
  165002. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  165003. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  165004. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  165005. }
  165006. /*
  165007. ** Create a new tokenizer instance.
  165008. */
  165009. static int unicodeCreate(
  165010. int nArg, /* Size of array argv[] */
  165011. const char * const *azArg, /* Tokenizer creation arguments */
  165012. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  165013. ){
  165014. unicode_tokenizer *pNew; /* New tokenizer object */
  165015. int i;
  165016. int rc = SQLITE_OK;
  165017. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  165018. if( pNew==NULL ) return SQLITE_NOMEM;
  165019. memset(pNew, 0, sizeof(unicode_tokenizer));
  165020. pNew->bRemoveDiacritic = 1;
  165021. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  165022. const char *z = azArg[i];
  165023. int n = (int)strlen(z);
  165024. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  165025. pNew->bRemoveDiacritic = 1;
  165026. }
  165027. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  165028. pNew->bRemoveDiacritic = 0;
  165029. }
  165030. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  165031. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  165032. }
  165033. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  165034. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  165035. }
  165036. else{
  165037. /* Unrecognized argument */
  165038. rc = SQLITE_ERROR;
  165039. }
  165040. }
  165041. if( rc!=SQLITE_OK ){
  165042. unicodeDestroy((sqlite3_tokenizer *)pNew);
  165043. pNew = 0;
  165044. }
  165045. *pp = (sqlite3_tokenizer *)pNew;
  165046. return rc;
  165047. }
  165048. /*
  165049. ** Prepare to begin tokenizing a particular string. The input
  165050. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  165051. ** used to incrementally tokenize this string is returned in
  165052. ** *ppCursor.
  165053. */
  165054. static int unicodeOpen(
  165055. sqlite3_tokenizer *p, /* The tokenizer */
  165056. const char *aInput, /* Input string */
  165057. int nInput, /* Size of string aInput in bytes */
  165058. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  165059. ){
  165060. unicode_cursor *pCsr;
  165061. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  165062. if( pCsr==0 ){
  165063. return SQLITE_NOMEM;
  165064. }
  165065. memset(pCsr, 0, sizeof(unicode_cursor));
  165066. pCsr->aInput = (const unsigned char *)aInput;
  165067. if( aInput==0 ){
  165068. pCsr->nInput = 0;
  165069. }else if( nInput<0 ){
  165070. pCsr->nInput = (int)strlen(aInput);
  165071. }else{
  165072. pCsr->nInput = nInput;
  165073. }
  165074. *pp = &pCsr->base;
  165075. UNUSED_PARAMETER(p);
  165076. return SQLITE_OK;
  165077. }
  165078. /*
  165079. ** Close a tokenization cursor previously opened by a call to
  165080. ** simpleOpen() above.
  165081. */
  165082. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  165083. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  165084. sqlite3_free(pCsr->zToken);
  165085. sqlite3_free(pCsr);
  165086. return SQLITE_OK;
  165087. }
  165088. /*
  165089. ** Extract the next token from a tokenization cursor. The cursor must
  165090. ** have been opened by a prior call to simpleOpen().
  165091. */
  165092. static int unicodeNext(
  165093. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  165094. const char **paToken, /* OUT: Token text */
  165095. int *pnToken, /* OUT: Number of bytes at *paToken */
  165096. int *piStart, /* OUT: Starting offset of token */
  165097. int *piEnd, /* OUT: Ending offset of token */
  165098. int *piPos /* OUT: Position integer of token */
  165099. ){
  165100. unicode_cursor *pCsr = (unicode_cursor *)pC;
  165101. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  165102. unsigned int iCode = 0;
  165103. char *zOut;
  165104. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  165105. const unsigned char *zStart = z;
  165106. const unsigned char *zEnd;
  165107. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  165108. /* Scan past any delimiter characters before the start of the next token.
  165109. ** Return SQLITE_DONE early if this takes us all the way to the end of
  165110. ** the input. */
  165111. while( z<zTerm ){
  165112. READ_UTF8(z, zTerm, iCode);
  165113. if( unicodeIsAlnum(p, (int)iCode) ) break;
  165114. zStart = z;
  165115. }
  165116. if( zStart>=zTerm ) return SQLITE_DONE;
  165117. zOut = pCsr->zToken;
  165118. do {
  165119. int iOut;
  165120. /* Grow the output buffer if required. */
  165121. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  165122. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  165123. if( !zNew ) return SQLITE_NOMEM;
  165124. zOut = &zNew[zOut - pCsr->zToken];
  165125. pCsr->zToken = zNew;
  165126. pCsr->nAlloc += 64;
  165127. }
  165128. /* Write the folded case of the last character read to the output */
  165129. zEnd = z;
  165130. iOut = sqlite3FtsUnicodeFold((int)iCode, p->bRemoveDiacritic);
  165131. if( iOut ){
  165132. WRITE_UTF8(zOut, iOut);
  165133. }
  165134. /* If the cursor is not at EOF, read the next character */
  165135. if( z>=zTerm ) break;
  165136. READ_UTF8(z, zTerm, iCode);
  165137. }while( unicodeIsAlnum(p, (int)iCode)
  165138. || sqlite3FtsUnicodeIsdiacritic((int)iCode)
  165139. );
  165140. /* Set the output variables and return. */
  165141. pCsr->iOff = (int)(z - pCsr->aInput);
  165142. *paToken = pCsr->zToken;
  165143. *pnToken = (int)(zOut - pCsr->zToken);
  165144. *piStart = (int)(zStart - pCsr->aInput);
  165145. *piEnd = (int)(zEnd - pCsr->aInput);
  165146. *piPos = pCsr->iToken++;
  165147. return SQLITE_OK;
  165148. }
  165149. /*
  165150. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  165151. ** structure for the unicode tokenizer.
  165152. */
  165153. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  165154. static const sqlite3_tokenizer_module module = {
  165155. 0,
  165156. unicodeCreate,
  165157. unicodeDestroy,
  165158. unicodeOpen,
  165159. unicodeClose,
  165160. unicodeNext,
  165161. 0,
  165162. };
  165163. *ppModule = &module;
  165164. }
  165165. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  165166. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  165167. /************** End of fts3_unicode.c ****************************************/
  165168. /************** Begin file fts3_unicode2.c ***********************************/
  165169. /*
  165170. ** 2012 May 25
  165171. **
  165172. ** The author disclaims copyright to this source code. In place of
  165173. ** a legal notice, here is a blessing:
  165174. **
  165175. ** May you do good and not evil.
  165176. ** May you find forgiveness for yourself and forgive others.
  165177. ** May you share freely, never taking more than you give.
  165178. **
  165179. ******************************************************************************
  165180. */
  165181. /*
  165182. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  165183. */
  165184. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  165185. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  165186. /* #include <assert.h> */
  165187. /*
  165188. ** Return true if the argument corresponds to a unicode codepoint
  165189. ** classified as either a letter or a number. Otherwise false.
  165190. **
  165191. ** The results are undefined if the value passed to this function
  165192. ** is less than zero.
  165193. */
  165194. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  165195. /* Each unsigned integer in the following array corresponds to a contiguous
  165196. ** range of unicode codepoints that are not either letters or numbers (i.e.
  165197. ** codepoints for which this function should return 0).
  165198. **
  165199. ** The most significant 22 bits in each 32-bit value contain the first
  165200. ** codepoint in the range. The least significant 10 bits are used to store
  165201. ** the size of the range (always at least 1). In other words, the value
  165202. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  165203. ** C. It is not possible to represent a range larger than 1023 codepoints
  165204. ** using this format.
  165205. */
  165206. static const unsigned int aEntry[] = {
  165207. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  165208. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  165209. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  165210. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  165211. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  165212. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  165213. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  165214. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  165215. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  165216. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  165217. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  165218. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  165219. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  165220. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  165221. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  165222. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  165223. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  165224. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  165225. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  165226. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  165227. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  165228. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  165229. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  165230. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  165231. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  165232. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  165233. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  165234. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  165235. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  165236. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  165237. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  165238. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  165239. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  165240. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  165241. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  165242. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  165243. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  165244. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  165245. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  165246. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  165247. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  165248. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  165249. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  165250. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  165251. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  165252. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  165253. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  165254. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  165255. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  165256. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  165257. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  165258. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  165259. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  165260. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  165261. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  165262. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  165263. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  165264. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  165265. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  165266. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  165267. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  165268. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  165269. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  165270. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  165271. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  165272. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  165273. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  165274. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  165275. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  165276. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  165277. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  165278. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  165279. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  165280. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  165281. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  165282. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  165283. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  165284. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  165285. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  165286. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  165287. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  165288. 0x380400F0,
  165289. };
  165290. static const unsigned int aAscii[4] = {
  165291. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  165292. };
  165293. if( (unsigned int)c<128 ){
  165294. return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
  165295. }else if( (unsigned int)c<(1<<22) ){
  165296. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  165297. int iRes = 0;
  165298. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  165299. int iLo = 0;
  165300. while( iHi>=iLo ){
  165301. int iTest = (iHi + iLo) / 2;
  165302. if( key >= aEntry[iTest] ){
  165303. iRes = iTest;
  165304. iLo = iTest+1;
  165305. }else{
  165306. iHi = iTest-1;
  165307. }
  165308. }
  165309. assert( aEntry[0]<key );
  165310. assert( key>=aEntry[iRes] );
  165311. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  165312. }
  165313. return 1;
  165314. }
  165315. /*
  165316. ** If the argument is a codepoint corresponding to a lowercase letter
  165317. ** in the ASCII range with a diacritic added, return the codepoint
  165318. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  165319. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  165320. ** E"). The resuls of passing a codepoint that corresponds to an
  165321. ** uppercase letter are undefined.
  165322. */
  165323. static int remove_diacritic(int c){
  165324. unsigned short aDia[] = {
  165325. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  165326. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  165327. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  165328. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  165329. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  165330. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  165331. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  165332. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  165333. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  165334. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  165335. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  165336. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  165337. 62924, 63050, 63082, 63274, 63390,
  165338. };
  165339. char aChar[] = {
  165340. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  165341. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  165342. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  165343. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  165344. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  165345. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  165346. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  165347. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  165348. 'e', 'i', 'o', 'u', 'y',
  165349. };
  165350. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  165351. int iRes = 0;
  165352. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  165353. int iLo = 0;
  165354. while( iHi>=iLo ){
  165355. int iTest = (iHi + iLo) / 2;
  165356. if( key >= aDia[iTest] ){
  165357. iRes = iTest;
  165358. iLo = iTest+1;
  165359. }else{
  165360. iHi = iTest-1;
  165361. }
  165362. }
  165363. assert( key>=aDia[iRes] );
  165364. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  165365. }
  165366. /*
  165367. ** Return true if the argument interpreted as a unicode codepoint
  165368. ** is a diacritical modifier character.
  165369. */
  165370. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  165371. unsigned int mask0 = 0x08029FDF;
  165372. unsigned int mask1 = 0x000361F8;
  165373. if( c<768 || c>817 ) return 0;
  165374. return (c < 768+32) ?
  165375. (mask0 & (1 << (c-768))) :
  165376. (mask1 & (1 << (c-768-32)));
  165377. }
  165378. /*
  165379. ** Interpret the argument as a unicode codepoint. If the codepoint
  165380. ** is an upper case character that has a lower case equivalent,
  165381. ** return the codepoint corresponding to the lower case version.
  165382. ** Otherwise, return a copy of the argument.
  165383. **
  165384. ** The results are undefined if the value passed to this function
  165385. ** is less than zero.
  165386. */
  165387. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  165388. /* Each entry in the following array defines a rule for folding a range
  165389. ** of codepoints to lower case. The rule applies to a range of nRange
  165390. ** codepoints starting at codepoint iCode.
  165391. **
  165392. ** If the least significant bit in flags is clear, then the rule applies
  165393. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  165394. ** need to be folded). Or, if it is set, then the rule only applies to
  165395. ** every second codepoint in the range, starting with codepoint C.
  165396. **
  165397. ** The 7 most significant bits in flags are an index into the aiOff[]
  165398. ** array. If a specific codepoint C does require folding, then its lower
  165399. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  165400. **
  165401. ** The contents of this array are generated by parsing the CaseFolding.txt
  165402. ** file distributed as part of the "Unicode Character Database". See
  165403. ** http://www.unicode.org for details.
  165404. */
  165405. static const struct TableEntry {
  165406. unsigned short iCode;
  165407. unsigned char flags;
  165408. unsigned char nRange;
  165409. } aEntry[] = {
  165410. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  165411. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  165412. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  165413. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  165414. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  165415. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  165416. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  165417. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  165418. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  165419. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  165420. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  165421. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  165422. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  165423. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  165424. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  165425. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  165426. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  165427. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  165428. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  165429. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  165430. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  165431. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  165432. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  165433. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  165434. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  165435. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  165436. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  165437. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  165438. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  165439. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  165440. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  165441. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  165442. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  165443. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  165444. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  165445. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  165446. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  165447. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  165448. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  165449. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  165450. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  165451. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  165452. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  165453. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  165454. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  165455. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  165456. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  165457. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  165458. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  165459. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  165460. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  165461. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  165462. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  165463. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  165464. {65313, 14, 26},
  165465. };
  165466. static const unsigned short aiOff[] = {
  165467. 1, 2, 8, 15, 16, 26, 28, 32,
  165468. 37, 38, 40, 48, 63, 64, 69, 71,
  165469. 79, 80, 116, 202, 203, 205, 206, 207,
  165470. 209, 210, 211, 213, 214, 217, 218, 219,
  165471. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  165472. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  165473. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  165474. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  165475. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  165476. 65514, 65521, 65527, 65528, 65529,
  165477. };
  165478. int ret = c;
  165479. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  165480. if( c<128 ){
  165481. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  165482. }else if( c<65536 ){
  165483. const struct TableEntry *p;
  165484. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  165485. int iLo = 0;
  165486. int iRes = -1;
  165487. assert( c>aEntry[0].iCode );
  165488. while( iHi>=iLo ){
  165489. int iTest = (iHi + iLo) / 2;
  165490. int cmp = (c - aEntry[iTest].iCode);
  165491. if( cmp>=0 ){
  165492. iRes = iTest;
  165493. iLo = iTest+1;
  165494. }else{
  165495. iHi = iTest-1;
  165496. }
  165497. }
  165498. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  165499. p = &aEntry[iRes];
  165500. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  165501. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  165502. assert( ret>0 );
  165503. }
  165504. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  165505. }
  165506. else if( c>=66560 && c<66600 ){
  165507. ret = c + 40;
  165508. }
  165509. return ret;
  165510. }
  165511. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  165512. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  165513. /************** End of fts3_unicode2.c ***************************************/
  165514. /************** Begin file json1.c *******************************************/
  165515. /*
  165516. ** 2015-08-12
  165517. **
  165518. ** The author disclaims copyright to this source code. In place of
  165519. ** a legal notice, here is a blessing:
  165520. **
  165521. ** May you do good and not evil.
  165522. ** May you find forgiveness for yourself and forgive others.
  165523. ** May you share freely, never taking more than you give.
  165524. **
  165525. ******************************************************************************
  165526. **
  165527. ** This SQLite extension implements JSON functions. The interface is
  165528. ** modeled after MySQL JSON functions:
  165529. **
  165530. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  165531. **
  165532. ** For the time being, all JSON is stored as pure text. (We might add
  165533. ** a JSONB type in the future which stores a binary encoding of JSON in
  165534. ** a BLOB, but there is no support for JSONB in the current implementation.
  165535. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  165536. ** how JSONB might improve on that.)
  165537. */
  165538. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  165539. #if !defined(SQLITEINT_H)
  165540. /* #include "sqlite3ext.h" */
  165541. #endif
  165542. SQLITE_EXTENSION_INIT1
  165543. /* #include <assert.h> */
  165544. /* #include <string.h> */
  165545. /* #include <stdlib.h> */
  165546. /* #include <stdarg.h> */
  165547. /* Mark a function parameter as unused, to suppress nuisance compiler
  165548. ** warnings. */
  165549. #ifndef UNUSED_PARAM
  165550. # define UNUSED_PARAM(X) (void)(X)
  165551. #endif
  165552. #ifndef LARGEST_INT64
  165553. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  165554. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  165555. #endif
  165556. /*
  165557. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  165558. ** to pass signed char values.
  165559. */
  165560. #ifdef sqlite3Isdigit
  165561. /* Use the SQLite core versions if this routine is part of the
  165562. ** SQLite amalgamation */
  165563. # define safe_isdigit(x) sqlite3Isdigit(x)
  165564. # define safe_isalnum(x) sqlite3Isalnum(x)
  165565. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  165566. #else
  165567. /* Use the standard library for separate compilation */
  165568. #include <ctype.h> /* amalgamator: keep */
  165569. # define safe_isdigit(x) isdigit((unsigned char)(x))
  165570. # define safe_isalnum(x) isalnum((unsigned char)(x))
  165571. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  165572. #endif
  165573. /*
  165574. ** Growing our own isspace() routine this way is twice as fast as
  165575. ** the library isspace() function, resulting in a 7% overall performance
  165576. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  165577. */
  165578. static const char jsonIsSpace[] = {
  165579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  165580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165581. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  165595. };
  165596. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  165597. #ifndef SQLITE_AMALGAMATION
  165598. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  165599. ** but the definitions need to be repeated for separate compilation. */
  165600. typedef sqlite3_uint64 u64;
  165601. typedef unsigned int u32;
  165602. typedef unsigned short int u16;
  165603. typedef unsigned char u8;
  165604. #endif
  165605. /* Objects */
  165606. typedef struct JsonString JsonString;
  165607. typedef struct JsonNode JsonNode;
  165608. typedef struct JsonParse JsonParse;
  165609. /* An instance of this object represents a JSON string
  165610. ** under construction. Really, this is a generic string accumulator
  165611. ** that can be and is used to create strings other than JSON.
  165612. */
  165613. struct JsonString {
  165614. sqlite3_context *pCtx; /* Function context - put error messages here */
  165615. char *zBuf; /* Append JSON content here */
  165616. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  165617. u64 nUsed; /* Bytes of zBuf[] currently used */
  165618. u8 bStatic; /* True if zBuf is static space */
  165619. u8 bErr; /* True if an error has been encountered */
  165620. char zSpace[100]; /* Initial static space */
  165621. };
  165622. /* JSON type values
  165623. */
  165624. #define JSON_NULL 0
  165625. #define JSON_TRUE 1
  165626. #define JSON_FALSE 2
  165627. #define JSON_INT 3
  165628. #define JSON_REAL 4
  165629. #define JSON_STRING 5
  165630. #define JSON_ARRAY 6
  165631. #define JSON_OBJECT 7
  165632. /* The "subtype" set for JSON values */
  165633. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  165634. /*
  165635. ** Names of the various JSON types:
  165636. */
  165637. static const char * const jsonType[] = {
  165638. "null", "true", "false", "integer", "real", "text", "array", "object"
  165639. };
  165640. /* Bit values for the JsonNode.jnFlag field
  165641. */
  165642. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  165643. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  165644. #define JNODE_REMOVE 0x04 /* Do not output */
  165645. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
  165646. #define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
  165647. #define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
  165648. #define JNODE_LABEL 0x40 /* Is a label of an object */
  165649. /* A single node of parsed JSON
  165650. */
  165651. struct JsonNode {
  165652. u8 eType; /* One of the JSON_ type values */
  165653. u8 jnFlags; /* JNODE flags */
  165654. u32 n; /* Bytes of content, or number of sub-nodes */
  165655. union {
  165656. const char *zJContent; /* Content for INT, REAL, and STRING */
  165657. u32 iAppend; /* More terms for ARRAY and OBJECT */
  165658. u32 iKey; /* Key for ARRAY objects in json_tree() */
  165659. u32 iReplace; /* Replacement content for JNODE_REPLACE */
  165660. JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
  165661. } u;
  165662. };
  165663. /* A completely parsed JSON string
  165664. */
  165665. struct JsonParse {
  165666. u32 nNode; /* Number of slots of aNode[] used */
  165667. u32 nAlloc; /* Number of slots of aNode[] allocated */
  165668. JsonNode *aNode; /* Array of nodes containing the parse */
  165669. const char *zJson; /* Original JSON string */
  165670. u32 *aUp; /* Index of parent of each node */
  165671. u8 oom; /* Set to true if out of memory */
  165672. u8 nErr; /* Number of errors seen */
  165673. u16 iDepth; /* Nesting depth */
  165674. int nJson; /* Length of the zJson string in bytes */
  165675. u32 iHold; /* Replace cache line with the lowest iHold value */
  165676. };
  165677. /*
  165678. ** Maximum nesting depth of JSON for this implementation.
  165679. **
  165680. ** This limit is needed to avoid a stack overflow in the recursive
  165681. ** descent parser. A depth of 2000 is far deeper than any sane JSON
  165682. ** should go.
  165683. */
  165684. #define JSON_MAX_DEPTH 2000
  165685. /**************************************************************************
  165686. ** Utility routines for dealing with JsonString objects
  165687. **************************************************************************/
  165688. /* Set the JsonString object to an empty string
  165689. */
  165690. static void jsonZero(JsonString *p){
  165691. p->zBuf = p->zSpace;
  165692. p->nAlloc = sizeof(p->zSpace);
  165693. p->nUsed = 0;
  165694. p->bStatic = 1;
  165695. }
  165696. /* Initialize the JsonString object
  165697. */
  165698. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  165699. p->pCtx = pCtx;
  165700. p->bErr = 0;
  165701. jsonZero(p);
  165702. }
  165703. /* Free all allocated memory and reset the JsonString object back to its
  165704. ** initial state.
  165705. */
  165706. static void jsonReset(JsonString *p){
  165707. if( !p->bStatic ) sqlite3_free(p->zBuf);
  165708. jsonZero(p);
  165709. }
  165710. /* Report an out-of-memory (OOM) condition
  165711. */
  165712. static void jsonOom(JsonString *p){
  165713. p->bErr = 1;
  165714. sqlite3_result_error_nomem(p->pCtx);
  165715. jsonReset(p);
  165716. }
  165717. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  165718. ** Return zero on success. Return non-zero on an OOM error
  165719. */
  165720. static int jsonGrow(JsonString *p, u32 N){
  165721. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  165722. char *zNew;
  165723. if( p->bStatic ){
  165724. if( p->bErr ) return 1;
  165725. zNew = sqlite3_malloc64(nTotal);
  165726. if( zNew==0 ){
  165727. jsonOom(p);
  165728. return SQLITE_NOMEM;
  165729. }
  165730. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  165731. p->zBuf = zNew;
  165732. p->bStatic = 0;
  165733. }else{
  165734. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  165735. if( zNew==0 ){
  165736. jsonOom(p);
  165737. return SQLITE_NOMEM;
  165738. }
  165739. p->zBuf = zNew;
  165740. }
  165741. p->nAlloc = nTotal;
  165742. return SQLITE_OK;
  165743. }
  165744. /* Append N bytes from zIn onto the end of the JsonString string.
  165745. */
  165746. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  165747. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  165748. memcpy(p->zBuf+p->nUsed, zIn, N);
  165749. p->nUsed += N;
  165750. }
  165751. /* Append formatted text (not to exceed N bytes) to the JsonString.
  165752. */
  165753. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  165754. va_list ap;
  165755. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  165756. va_start(ap, zFormat);
  165757. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  165758. va_end(ap);
  165759. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  165760. }
  165761. /* Append a single character
  165762. */
  165763. static void jsonAppendChar(JsonString *p, char c){
  165764. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  165765. p->zBuf[p->nUsed++] = c;
  165766. }
  165767. /* Append a comma separator to the output buffer, if the previous
  165768. ** character is not '[' or '{'.
  165769. */
  165770. static void jsonAppendSeparator(JsonString *p){
  165771. char c;
  165772. if( p->nUsed==0 ) return;
  165773. c = p->zBuf[p->nUsed-1];
  165774. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  165775. }
  165776. /* Append the N-byte string in zIn to the end of the JsonString string
  165777. ** under construction. Enclose the string in "..." and escape
  165778. ** any double-quotes or backslash characters contained within the
  165779. ** string.
  165780. */
  165781. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  165782. u32 i;
  165783. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  165784. p->zBuf[p->nUsed++] = '"';
  165785. for(i=0; i<N; i++){
  165786. unsigned char c = ((unsigned const char*)zIn)[i];
  165787. if( c=='"' || c=='\\' ){
  165788. json_simple_escape:
  165789. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  165790. p->zBuf[p->nUsed++] = '\\';
  165791. }else if( c<=0x1f ){
  165792. static const char aSpecial[] = {
  165793. 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
  165794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  165795. };
  165796. assert( sizeof(aSpecial)==32 );
  165797. assert( aSpecial['\b']=='b' );
  165798. assert( aSpecial['\f']=='f' );
  165799. assert( aSpecial['\n']=='n' );
  165800. assert( aSpecial['\r']=='r' );
  165801. assert( aSpecial['\t']=='t' );
  165802. if( aSpecial[c] ){
  165803. c = aSpecial[c];
  165804. goto json_simple_escape;
  165805. }
  165806. if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
  165807. p->zBuf[p->nUsed++] = '\\';
  165808. p->zBuf[p->nUsed++] = 'u';
  165809. p->zBuf[p->nUsed++] = '0';
  165810. p->zBuf[p->nUsed++] = '0';
  165811. p->zBuf[p->nUsed++] = '0' + (c>>4);
  165812. c = "0123456789abcdef"[c&0xf];
  165813. }
  165814. p->zBuf[p->nUsed++] = c;
  165815. }
  165816. p->zBuf[p->nUsed++] = '"';
  165817. assert( p->nUsed<p->nAlloc );
  165818. }
  165819. /*
  165820. ** Append a function parameter value to the JSON string under
  165821. ** construction.
  165822. */
  165823. static void jsonAppendValue(
  165824. JsonString *p, /* Append to this JSON string */
  165825. sqlite3_value *pValue /* Value to append */
  165826. ){
  165827. switch( sqlite3_value_type(pValue) ){
  165828. case SQLITE_NULL: {
  165829. jsonAppendRaw(p, "null", 4);
  165830. break;
  165831. }
  165832. case SQLITE_INTEGER:
  165833. case SQLITE_FLOAT: {
  165834. const char *z = (const char*)sqlite3_value_text(pValue);
  165835. u32 n = (u32)sqlite3_value_bytes(pValue);
  165836. jsonAppendRaw(p, z, n);
  165837. break;
  165838. }
  165839. case SQLITE_TEXT: {
  165840. const char *z = (const char*)sqlite3_value_text(pValue);
  165841. u32 n = (u32)sqlite3_value_bytes(pValue);
  165842. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  165843. jsonAppendRaw(p, z, n);
  165844. }else{
  165845. jsonAppendString(p, z, n);
  165846. }
  165847. break;
  165848. }
  165849. default: {
  165850. if( p->bErr==0 ){
  165851. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  165852. p->bErr = 2;
  165853. jsonReset(p);
  165854. }
  165855. break;
  165856. }
  165857. }
  165858. }
  165859. /* Make the JSON in p the result of the SQL function.
  165860. */
  165861. static void jsonResult(JsonString *p){
  165862. if( p->bErr==0 ){
  165863. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  165864. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  165865. SQLITE_UTF8);
  165866. jsonZero(p);
  165867. }
  165868. assert( p->bStatic );
  165869. }
  165870. /**************************************************************************
  165871. ** Utility routines for dealing with JsonNode and JsonParse objects
  165872. **************************************************************************/
  165873. /*
  165874. ** Return the number of consecutive JsonNode slots need to represent
  165875. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  165876. ** OBJECT types, the number might be larger.
  165877. **
  165878. ** Appended elements are not counted. The value returned is the number
  165879. ** by which the JsonNode counter should increment in order to go to the
  165880. ** next peer value.
  165881. */
  165882. static u32 jsonNodeSize(JsonNode *pNode){
  165883. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  165884. }
  165885. /*
  165886. ** Reclaim all memory allocated by a JsonParse object. But do not
  165887. ** delete the JsonParse object itself.
  165888. */
  165889. static void jsonParseReset(JsonParse *pParse){
  165890. sqlite3_free(pParse->aNode);
  165891. pParse->aNode = 0;
  165892. pParse->nNode = 0;
  165893. pParse->nAlloc = 0;
  165894. sqlite3_free(pParse->aUp);
  165895. pParse->aUp = 0;
  165896. }
  165897. /*
  165898. ** Free a JsonParse object that was obtained from sqlite3_malloc().
  165899. */
  165900. static void jsonParseFree(JsonParse *pParse){
  165901. jsonParseReset(pParse);
  165902. sqlite3_free(pParse);
  165903. }
  165904. /*
  165905. ** Convert the JsonNode pNode into a pure JSON string and
  165906. ** append to pOut. Subsubstructure is also included. Return
  165907. ** the number of JsonNode objects that are encoded.
  165908. */
  165909. static void jsonRenderNode(
  165910. JsonNode *pNode, /* The node to render */
  165911. JsonString *pOut, /* Write JSON here */
  165912. sqlite3_value **aReplace /* Replacement values */
  165913. ){
  165914. if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
  165915. if( pNode->jnFlags & JNODE_REPLACE ){
  165916. jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
  165917. return;
  165918. }
  165919. pNode = pNode->u.pPatch;
  165920. }
  165921. switch( pNode->eType ){
  165922. default: {
  165923. assert( pNode->eType==JSON_NULL );
  165924. jsonAppendRaw(pOut, "null", 4);
  165925. break;
  165926. }
  165927. case JSON_TRUE: {
  165928. jsonAppendRaw(pOut, "true", 4);
  165929. break;
  165930. }
  165931. case JSON_FALSE: {
  165932. jsonAppendRaw(pOut, "false", 5);
  165933. break;
  165934. }
  165935. case JSON_STRING: {
  165936. if( pNode->jnFlags & JNODE_RAW ){
  165937. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  165938. break;
  165939. }
  165940. /* Fall through into the next case */
  165941. }
  165942. case JSON_REAL:
  165943. case JSON_INT: {
  165944. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  165945. break;
  165946. }
  165947. case JSON_ARRAY: {
  165948. u32 j = 1;
  165949. jsonAppendChar(pOut, '[');
  165950. for(;;){
  165951. while( j<=pNode->n ){
  165952. if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
  165953. jsonAppendSeparator(pOut);
  165954. jsonRenderNode(&pNode[j], pOut, aReplace);
  165955. }
  165956. j += jsonNodeSize(&pNode[j]);
  165957. }
  165958. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  165959. pNode = &pNode[pNode->u.iAppend];
  165960. j = 1;
  165961. }
  165962. jsonAppendChar(pOut, ']');
  165963. break;
  165964. }
  165965. case JSON_OBJECT: {
  165966. u32 j = 1;
  165967. jsonAppendChar(pOut, '{');
  165968. for(;;){
  165969. while( j<=pNode->n ){
  165970. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  165971. jsonAppendSeparator(pOut);
  165972. jsonRenderNode(&pNode[j], pOut, aReplace);
  165973. jsonAppendChar(pOut, ':');
  165974. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  165975. }
  165976. j += 1 + jsonNodeSize(&pNode[j+1]);
  165977. }
  165978. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  165979. pNode = &pNode[pNode->u.iAppend];
  165980. j = 1;
  165981. }
  165982. jsonAppendChar(pOut, '}');
  165983. break;
  165984. }
  165985. }
  165986. }
  165987. /*
  165988. ** Return a JsonNode and all its descendents as a JSON string.
  165989. */
  165990. static void jsonReturnJson(
  165991. JsonNode *pNode, /* Node to return */
  165992. sqlite3_context *pCtx, /* Return value for this function */
  165993. sqlite3_value **aReplace /* Array of replacement values */
  165994. ){
  165995. JsonString s;
  165996. jsonInit(&s, pCtx);
  165997. jsonRenderNode(pNode, &s, aReplace);
  165998. jsonResult(&s);
  165999. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  166000. }
  166001. /*
  166002. ** Make the JsonNode the return value of the function.
  166003. */
  166004. static void jsonReturn(
  166005. JsonNode *pNode, /* Node to return */
  166006. sqlite3_context *pCtx, /* Return value for this function */
  166007. sqlite3_value **aReplace /* Array of replacement values */
  166008. ){
  166009. switch( pNode->eType ){
  166010. default: {
  166011. assert( pNode->eType==JSON_NULL );
  166012. sqlite3_result_null(pCtx);
  166013. break;
  166014. }
  166015. case JSON_TRUE: {
  166016. sqlite3_result_int(pCtx, 1);
  166017. break;
  166018. }
  166019. case JSON_FALSE: {
  166020. sqlite3_result_int(pCtx, 0);
  166021. break;
  166022. }
  166023. case JSON_INT: {
  166024. sqlite3_int64 i = 0;
  166025. const char *z = pNode->u.zJContent;
  166026. if( z[0]=='-' ){ z++; }
  166027. while( z[0]>='0' && z[0]<='9' ){
  166028. unsigned v = *(z++) - '0';
  166029. if( i>=LARGEST_INT64/10 ){
  166030. if( i>LARGEST_INT64/10 ) goto int_as_real;
  166031. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  166032. if( v==9 ) goto int_as_real;
  166033. if( v==8 ){
  166034. if( pNode->u.zJContent[0]=='-' ){
  166035. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  166036. goto int_done;
  166037. }else{
  166038. goto int_as_real;
  166039. }
  166040. }
  166041. }
  166042. i = i*10 + v;
  166043. }
  166044. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  166045. sqlite3_result_int64(pCtx, i);
  166046. int_done:
  166047. break;
  166048. int_as_real: /* fall through to real */;
  166049. }
  166050. case JSON_REAL: {
  166051. double r;
  166052. #ifdef SQLITE_AMALGAMATION
  166053. const char *z = pNode->u.zJContent;
  166054. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  166055. #else
  166056. r = strtod(pNode->u.zJContent, 0);
  166057. #endif
  166058. sqlite3_result_double(pCtx, r);
  166059. break;
  166060. }
  166061. case JSON_STRING: {
  166062. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  166063. ** json_insert() and json_replace() and those routines do not
  166064. ** call jsonReturn() */
  166065. if( pNode->jnFlags & JNODE_RAW ){
  166066. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  166067. SQLITE_TRANSIENT);
  166068. }else
  166069. #endif
  166070. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  166071. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  166072. /* JSON formatted without any backslash-escapes */
  166073. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  166074. SQLITE_TRANSIENT);
  166075. }else{
  166076. /* Translate JSON formatted string into raw text */
  166077. u32 i;
  166078. u32 n = pNode->n;
  166079. const char *z = pNode->u.zJContent;
  166080. char *zOut;
  166081. u32 j;
  166082. zOut = sqlite3_malloc( n+1 );
  166083. if( zOut==0 ){
  166084. sqlite3_result_error_nomem(pCtx);
  166085. break;
  166086. }
  166087. for(i=1, j=0; i<n-1; i++){
  166088. char c = z[i];
  166089. if( c!='\\' ){
  166090. zOut[j++] = c;
  166091. }else{
  166092. c = z[++i];
  166093. if( c=='u' ){
  166094. u32 v = 0, k;
  166095. for(k=0; k<4; i++, k++){
  166096. assert( i<n-2 );
  166097. c = z[i+1];
  166098. assert( safe_isxdigit(c) );
  166099. if( c<='9' ) v = v*16 + c - '0';
  166100. else if( c<='F' ) v = v*16 + c - 'A' + 10;
  166101. else v = v*16 + c - 'a' + 10;
  166102. }
  166103. if( v==0 ) break;
  166104. if( v<=0x7f ){
  166105. zOut[j++] = (char)v;
  166106. }else if( v<=0x7ff ){
  166107. zOut[j++] = (char)(0xc0 | (v>>6));
  166108. zOut[j++] = 0x80 | (v&0x3f);
  166109. }else{
  166110. zOut[j++] = (char)(0xe0 | (v>>12));
  166111. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  166112. zOut[j++] = 0x80 | (v&0x3f);
  166113. }
  166114. }else{
  166115. if( c=='b' ){
  166116. c = '\b';
  166117. }else if( c=='f' ){
  166118. c = '\f';
  166119. }else if( c=='n' ){
  166120. c = '\n';
  166121. }else if( c=='r' ){
  166122. c = '\r';
  166123. }else if( c=='t' ){
  166124. c = '\t';
  166125. }
  166126. zOut[j++] = c;
  166127. }
  166128. }
  166129. }
  166130. zOut[j] = 0;
  166131. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  166132. }
  166133. break;
  166134. }
  166135. case JSON_ARRAY:
  166136. case JSON_OBJECT: {
  166137. jsonReturnJson(pNode, pCtx, aReplace);
  166138. break;
  166139. }
  166140. }
  166141. }
  166142. /* Forward reference */
  166143. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  166144. /*
  166145. ** A macro to hint to the compiler that a function should not be
  166146. ** inlined.
  166147. */
  166148. #if defined(__GNUC__)
  166149. # define JSON_NOINLINE __attribute__((noinline))
  166150. #elif defined(_MSC_VER) && _MSC_VER>=1310
  166151. # define JSON_NOINLINE __declspec(noinline)
  166152. #else
  166153. # define JSON_NOINLINE
  166154. #endif
  166155. static JSON_NOINLINE int jsonParseAddNodeExpand(
  166156. JsonParse *pParse, /* Append the node to this object */
  166157. u32 eType, /* Node type */
  166158. u32 n, /* Content size or sub-node count */
  166159. const char *zContent /* Content */
  166160. ){
  166161. u32 nNew;
  166162. JsonNode *pNew;
  166163. assert( pParse->nNode>=pParse->nAlloc );
  166164. if( pParse->oom ) return -1;
  166165. nNew = pParse->nAlloc*2 + 10;
  166166. pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
  166167. if( pNew==0 ){
  166168. pParse->oom = 1;
  166169. return -1;
  166170. }
  166171. pParse->nAlloc = nNew;
  166172. pParse->aNode = pNew;
  166173. assert( pParse->nNode<pParse->nAlloc );
  166174. return jsonParseAddNode(pParse, eType, n, zContent);
  166175. }
  166176. /*
  166177. ** Create a new JsonNode instance based on the arguments and append that
  166178. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  166179. ** new node, or -1 if a memory allocation fails.
  166180. */
  166181. static int jsonParseAddNode(
  166182. JsonParse *pParse, /* Append the node to this object */
  166183. u32 eType, /* Node type */
  166184. u32 n, /* Content size or sub-node count */
  166185. const char *zContent /* Content */
  166186. ){
  166187. JsonNode *p;
  166188. if( pParse->nNode>=pParse->nAlloc ){
  166189. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  166190. }
  166191. p = &pParse->aNode[pParse->nNode];
  166192. p->eType = (u8)eType;
  166193. p->jnFlags = 0;
  166194. p->n = n;
  166195. p->u.zJContent = zContent;
  166196. return pParse->nNode++;
  166197. }
  166198. /*
  166199. ** Return true if z[] begins with 4 (or more) hexadecimal digits
  166200. */
  166201. static int jsonIs4Hex(const char *z){
  166202. int i;
  166203. for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
  166204. return 1;
  166205. }
  166206. /*
  166207. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  166208. ** index of the first character past the end of the value parsed.
  166209. **
  166210. ** Return negative for a syntax error. Special cases: return -2 if the
  166211. ** first non-whitespace character is '}' and return -3 if the first
  166212. ** non-whitespace character is ']'.
  166213. */
  166214. static int jsonParseValue(JsonParse *pParse, u32 i){
  166215. char c;
  166216. u32 j;
  166217. int iThis;
  166218. int x;
  166219. JsonNode *pNode;
  166220. const char *z = pParse->zJson;
  166221. while( safe_isspace(z[i]) ){ i++; }
  166222. if( (c = z[i])=='{' ){
  166223. /* Parse object */
  166224. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  166225. if( iThis<0 ) return -1;
  166226. for(j=i+1;;j++){
  166227. while( safe_isspace(z[j]) ){ j++; }
  166228. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  166229. x = jsonParseValue(pParse, j);
  166230. if( x<0 ){
  166231. pParse->iDepth--;
  166232. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  166233. return -1;
  166234. }
  166235. if( pParse->oom ) return -1;
  166236. pNode = &pParse->aNode[pParse->nNode-1];
  166237. if( pNode->eType!=JSON_STRING ) return -1;
  166238. pNode->jnFlags |= JNODE_LABEL;
  166239. j = x;
  166240. while( safe_isspace(z[j]) ){ j++; }
  166241. if( z[j]!=':' ) return -1;
  166242. j++;
  166243. x = jsonParseValue(pParse, j);
  166244. pParse->iDepth--;
  166245. if( x<0 ) return -1;
  166246. j = x;
  166247. while( safe_isspace(z[j]) ){ j++; }
  166248. c = z[j];
  166249. if( c==',' ) continue;
  166250. if( c!='}' ) return -1;
  166251. break;
  166252. }
  166253. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  166254. return j+1;
  166255. }else if( c=='[' ){
  166256. /* Parse array */
  166257. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  166258. if( iThis<0 ) return -1;
  166259. for(j=i+1;;j++){
  166260. while( safe_isspace(z[j]) ){ j++; }
  166261. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  166262. x = jsonParseValue(pParse, j);
  166263. pParse->iDepth--;
  166264. if( x<0 ){
  166265. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  166266. return -1;
  166267. }
  166268. j = x;
  166269. while( safe_isspace(z[j]) ){ j++; }
  166270. c = z[j];
  166271. if( c==',' ) continue;
  166272. if( c!=']' ) return -1;
  166273. break;
  166274. }
  166275. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  166276. return j+1;
  166277. }else if( c=='"' ){
  166278. /* Parse string */
  166279. u8 jnFlags = 0;
  166280. j = i+1;
  166281. for(;;){
  166282. c = z[j];
  166283. if( (c & ~0x1f)==0 ){
  166284. /* Control characters are not allowed in strings */
  166285. return -1;
  166286. }
  166287. if( c=='\\' ){
  166288. c = z[++j];
  166289. if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
  166290. || c=='n' || c=='r' || c=='t'
  166291. || (c=='u' && jsonIs4Hex(z+j+1)) ){
  166292. jnFlags = JNODE_ESCAPE;
  166293. }else{
  166294. return -1;
  166295. }
  166296. }else if( c=='"' ){
  166297. break;
  166298. }
  166299. j++;
  166300. }
  166301. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
  166302. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  166303. return j+1;
  166304. }else if( c=='n'
  166305. && strncmp(z+i,"null",4)==0
  166306. && !safe_isalnum(z[i+4]) ){
  166307. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  166308. return i+4;
  166309. }else if( c=='t'
  166310. && strncmp(z+i,"true",4)==0
  166311. && !safe_isalnum(z[i+4]) ){
  166312. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  166313. return i+4;
  166314. }else if( c=='f'
  166315. && strncmp(z+i,"false",5)==0
  166316. && !safe_isalnum(z[i+5]) ){
  166317. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  166318. return i+5;
  166319. }else if( c=='-' || (c>='0' && c<='9') ){
  166320. /* Parse number */
  166321. u8 seenDP = 0;
  166322. u8 seenE = 0;
  166323. assert( '-' < '0' );
  166324. if( c<='0' ){
  166325. j = c=='-' ? i+1 : i;
  166326. if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
  166327. }
  166328. j = i+1;
  166329. for(;; j++){
  166330. c = z[j];
  166331. if( c>='0' && c<='9' ) continue;
  166332. if( c=='.' ){
  166333. if( z[j-1]=='-' ) return -1;
  166334. if( seenDP ) return -1;
  166335. seenDP = 1;
  166336. continue;
  166337. }
  166338. if( c=='e' || c=='E' ){
  166339. if( z[j-1]<'0' ) return -1;
  166340. if( seenE ) return -1;
  166341. seenDP = seenE = 1;
  166342. c = z[j+1];
  166343. if( c=='+' || c=='-' ){
  166344. j++;
  166345. c = z[j+1];
  166346. }
  166347. if( c<'0' || c>'9' ) return -1;
  166348. continue;
  166349. }
  166350. break;
  166351. }
  166352. if( z[j-1]<'0' ) return -1;
  166353. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  166354. j - i, &z[i]);
  166355. return j;
  166356. }else if( c=='}' ){
  166357. return -2; /* End of {...} */
  166358. }else if( c==']' ){
  166359. return -3; /* End of [...] */
  166360. }else if( c==0 ){
  166361. return 0; /* End of file */
  166362. }else{
  166363. return -1; /* Syntax error */
  166364. }
  166365. }
  166366. /*
  166367. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  166368. ** are any errors. If an error occurs, free all memory associated with
  166369. ** pParse.
  166370. **
  166371. ** pParse is uninitialized when this routine is called.
  166372. */
  166373. static int jsonParse(
  166374. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  166375. sqlite3_context *pCtx, /* Report errors here */
  166376. const char *zJson /* Input JSON text to be parsed */
  166377. ){
  166378. int i;
  166379. memset(pParse, 0, sizeof(*pParse));
  166380. if( zJson==0 ) return 1;
  166381. pParse->zJson = zJson;
  166382. i = jsonParseValue(pParse, 0);
  166383. if( pParse->oom ) i = -1;
  166384. if( i>0 ){
  166385. assert( pParse->iDepth==0 );
  166386. while( safe_isspace(zJson[i]) ) i++;
  166387. if( zJson[i] ) i = -1;
  166388. }
  166389. if( i<=0 ){
  166390. if( pCtx!=0 ){
  166391. if( pParse->oom ){
  166392. sqlite3_result_error_nomem(pCtx);
  166393. }else{
  166394. sqlite3_result_error(pCtx, "malformed JSON", -1);
  166395. }
  166396. }
  166397. jsonParseReset(pParse);
  166398. return 1;
  166399. }
  166400. return 0;
  166401. }
  166402. /* Mark node i of pParse as being a child of iParent. Call recursively
  166403. ** to fill in all the descendants of node i.
  166404. */
  166405. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  166406. JsonNode *pNode = &pParse->aNode[i];
  166407. u32 j;
  166408. pParse->aUp[i] = iParent;
  166409. switch( pNode->eType ){
  166410. case JSON_ARRAY: {
  166411. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  166412. jsonParseFillInParentage(pParse, i+j, i);
  166413. }
  166414. break;
  166415. }
  166416. case JSON_OBJECT: {
  166417. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  166418. pParse->aUp[i+j] = i;
  166419. jsonParseFillInParentage(pParse, i+j+1, i);
  166420. }
  166421. break;
  166422. }
  166423. default: {
  166424. break;
  166425. }
  166426. }
  166427. }
  166428. /*
  166429. ** Compute the parentage of all nodes in a completed parse.
  166430. */
  166431. static int jsonParseFindParents(JsonParse *pParse){
  166432. u32 *aUp;
  166433. assert( pParse->aUp==0 );
  166434. aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
  166435. if( aUp==0 ){
  166436. pParse->oom = 1;
  166437. return SQLITE_NOMEM;
  166438. }
  166439. jsonParseFillInParentage(pParse, 0, 0);
  166440. return SQLITE_OK;
  166441. }
  166442. /*
  166443. ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
  166444. */
  166445. #define JSON_CACHE_ID (-429938) /* First cache entry */
  166446. #define JSON_CACHE_SZ 4 /* Max number of cache entries */
  166447. /*
  166448. ** Obtain a complete parse of the JSON found in the first argument
  166449. ** of the argv array. Use the sqlite3_get_auxdata() cache for this
  166450. ** parse if it is available. If the cache is not available or if it
  166451. ** is no longer valid, parse the JSON again and return the new parse,
  166452. ** and also register the new parse so that it will be available for
  166453. ** future sqlite3_get_auxdata() calls.
  166454. */
  166455. static JsonParse *jsonParseCached(
  166456. sqlite3_context *pCtx,
  166457. sqlite3_value **argv,
  166458. sqlite3_context *pErrCtx
  166459. ){
  166460. const char *zJson = (const char*)sqlite3_value_text(argv[0]);
  166461. int nJson = sqlite3_value_bytes(argv[0]);
  166462. JsonParse *p;
  166463. JsonParse *pMatch = 0;
  166464. int iKey;
  166465. int iMinKey = 0;
  166466. u32 iMinHold = 0xffffffff;
  166467. u32 iMaxHold = 0;
  166468. if( zJson==0 ) return 0;
  166469. for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
  166470. p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
  166471. if( p==0 ){
  166472. iMinKey = iKey;
  166473. break;
  166474. }
  166475. if( pMatch==0
  166476. && p->nJson==nJson
  166477. && memcmp(p->zJson,zJson,nJson)==0
  166478. ){
  166479. p->nErr = 0;
  166480. pMatch = p;
  166481. }else if( p->iHold<iMinHold ){
  166482. iMinHold = p->iHold;
  166483. iMinKey = iKey;
  166484. }
  166485. if( p->iHold>iMaxHold ){
  166486. iMaxHold = p->iHold;
  166487. }
  166488. }
  166489. if( pMatch ){
  166490. pMatch->nErr = 0;
  166491. pMatch->iHold = iMaxHold+1;
  166492. return pMatch;
  166493. }
  166494. p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
  166495. if( p==0 ){
  166496. sqlite3_result_error_nomem(pCtx);
  166497. return 0;
  166498. }
  166499. memset(p, 0, sizeof(*p));
  166500. p->zJson = (char*)&p[1];
  166501. memcpy((char*)p->zJson, zJson, nJson+1);
  166502. if( jsonParse(p, pErrCtx, p->zJson) ){
  166503. sqlite3_free(p);
  166504. return 0;
  166505. }
  166506. p->nJson = nJson;
  166507. p->iHold = iMaxHold+1;
  166508. sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
  166509. (void(*)(void*))jsonParseFree);
  166510. return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
  166511. }
  166512. /*
  166513. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  166514. ** a match.
  166515. */
  166516. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  166517. if( pNode->jnFlags & JNODE_RAW ){
  166518. if( pNode->n!=nKey ) return 0;
  166519. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  166520. }else{
  166521. if( pNode->n!=nKey+2 ) return 0;
  166522. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  166523. }
  166524. }
  166525. /* forward declaration */
  166526. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  166527. /*
  166528. ** Search along zPath to find the node specified. Return a pointer
  166529. ** to that node, or NULL if zPath is malformed or if there is no such
  166530. ** node.
  166531. **
  166532. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  166533. ** possible to do so and if no existing node corresponds to zPath. If
  166534. ** new nodes are appended *pApnd is set to 1.
  166535. */
  166536. static JsonNode *jsonLookupStep(
  166537. JsonParse *pParse, /* The JSON to search */
  166538. u32 iRoot, /* Begin the search at this node */
  166539. const char *zPath, /* The path to search */
  166540. int *pApnd, /* Append nodes to complete path if not NULL */
  166541. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  166542. ){
  166543. u32 i, j, nKey;
  166544. const char *zKey;
  166545. JsonNode *pRoot = &pParse->aNode[iRoot];
  166546. if( zPath[0]==0 ) return pRoot;
  166547. if( zPath[0]=='.' ){
  166548. if( pRoot->eType!=JSON_OBJECT ) return 0;
  166549. zPath++;
  166550. if( zPath[0]=='"' ){
  166551. zKey = zPath + 1;
  166552. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  166553. nKey = i-1;
  166554. if( zPath[i] ){
  166555. i++;
  166556. }else{
  166557. *pzErr = zPath;
  166558. return 0;
  166559. }
  166560. }else{
  166561. zKey = zPath;
  166562. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  166563. nKey = i;
  166564. }
  166565. if( nKey==0 ){
  166566. *pzErr = zPath;
  166567. return 0;
  166568. }
  166569. j = 1;
  166570. for(;;){
  166571. while( j<=pRoot->n ){
  166572. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  166573. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  166574. }
  166575. j++;
  166576. j += jsonNodeSize(&pRoot[j]);
  166577. }
  166578. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  166579. iRoot += pRoot->u.iAppend;
  166580. pRoot = &pParse->aNode[iRoot];
  166581. j = 1;
  166582. }
  166583. if( pApnd ){
  166584. u32 iStart, iLabel;
  166585. JsonNode *pNode;
  166586. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  166587. iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
  166588. zPath += i;
  166589. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  166590. if( pParse->oom ) return 0;
  166591. if( pNode ){
  166592. pRoot = &pParse->aNode[iRoot];
  166593. pRoot->u.iAppend = iStart - iRoot;
  166594. pRoot->jnFlags |= JNODE_APPEND;
  166595. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  166596. }
  166597. return pNode;
  166598. }
  166599. }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  166600. if( pRoot->eType!=JSON_ARRAY ) return 0;
  166601. i = 0;
  166602. j = 1;
  166603. while( safe_isdigit(zPath[j]) ){
  166604. i = i*10 + zPath[j] - '0';
  166605. j++;
  166606. }
  166607. if( zPath[j]!=']' ){
  166608. *pzErr = zPath;
  166609. return 0;
  166610. }
  166611. zPath += j + 1;
  166612. j = 1;
  166613. for(;;){
  166614. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  166615. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  166616. j += jsonNodeSize(&pRoot[j]);
  166617. }
  166618. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  166619. iRoot += pRoot->u.iAppend;
  166620. pRoot = &pParse->aNode[iRoot];
  166621. j = 1;
  166622. }
  166623. if( j<=pRoot->n ){
  166624. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  166625. }
  166626. if( i==0 && pApnd ){
  166627. u32 iStart;
  166628. JsonNode *pNode;
  166629. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  166630. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  166631. if( pParse->oom ) return 0;
  166632. if( pNode ){
  166633. pRoot = &pParse->aNode[iRoot];
  166634. pRoot->u.iAppend = iStart - iRoot;
  166635. pRoot->jnFlags |= JNODE_APPEND;
  166636. }
  166637. return pNode;
  166638. }
  166639. }else{
  166640. *pzErr = zPath;
  166641. }
  166642. return 0;
  166643. }
  166644. /*
  166645. ** Append content to pParse that will complete zPath. Return a pointer
  166646. ** to the inserted node, or return NULL if the append fails.
  166647. */
  166648. static JsonNode *jsonLookupAppend(
  166649. JsonParse *pParse, /* Append content to the JSON parse */
  166650. const char *zPath, /* Description of content to append */
  166651. int *pApnd, /* Set this flag to 1 */
  166652. const char **pzErr /* Make this point to any syntax error */
  166653. ){
  166654. *pApnd = 1;
  166655. if( zPath[0]==0 ){
  166656. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  166657. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  166658. }
  166659. if( zPath[0]=='.' ){
  166660. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  166661. }else if( strncmp(zPath,"[0]",3)==0 ){
  166662. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  166663. }else{
  166664. return 0;
  166665. }
  166666. if( pParse->oom ) return 0;
  166667. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  166668. }
  166669. /*
  166670. ** Return the text of a syntax error message on a JSON path. Space is
  166671. ** obtained from sqlite3_malloc().
  166672. */
  166673. static char *jsonPathSyntaxError(const char *zErr){
  166674. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  166675. }
  166676. /*
  166677. ** Do a node lookup using zPath. Return a pointer to the node on success.
  166678. ** Return NULL if not found or if there is an error.
  166679. **
  166680. ** On an error, write an error message into pCtx and increment the
  166681. ** pParse->nErr counter.
  166682. **
  166683. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  166684. ** nodes are appended.
  166685. */
  166686. static JsonNode *jsonLookup(
  166687. JsonParse *pParse, /* The JSON to search */
  166688. const char *zPath, /* The path to search */
  166689. int *pApnd, /* Append nodes to complete path if not NULL */
  166690. sqlite3_context *pCtx /* Report errors here, if not NULL */
  166691. ){
  166692. const char *zErr = 0;
  166693. JsonNode *pNode = 0;
  166694. char *zMsg;
  166695. if( zPath==0 ) return 0;
  166696. if( zPath[0]!='$' ){
  166697. zErr = zPath;
  166698. goto lookup_err;
  166699. }
  166700. zPath++;
  166701. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  166702. if( zErr==0 ) return pNode;
  166703. lookup_err:
  166704. pParse->nErr++;
  166705. assert( zErr!=0 && pCtx!=0 );
  166706. zMsg = jsonPathSyntaxError(zErr);
  166707. if( zMsg ){
  166708. sqlite3_result_error(pCtx, zMsg, -1);
  166709. sqlite3_free(zMsg);
  166710. }else{
  166711. sqlite3_result_error_nomem(pCtx);
  166712. }
  166713. return 0;
  166714. }
  166715. /*
  166716. ** Report the wrong number of arguments for json_insert(), json_replace()
  166717. ** or json_set().
  166718. */
  166719. static void jsonWrongNumArgs(
  166720. sqlite3_context *pCtx,
  166721. const char *zFuncName
  166722. ){
  166723. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  166724. zFuncName);
  166725. sqlite3_result_error(pCtx, zMsg, -1);
  166726. sqlite3_free(zMsg);
  166727. }
  166728. /*
  166729. ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
  166730. */
  166731. static void jsonRemoveAllNulls(JsonNode *pNode){
  166732. int i, n;
  166733. assert( pNode->eType==JSON_OBJECT );
  166734. n = pNode->n;
  166735. for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
  166736. switch( pNode[i].eType ){
  166737. case JSON_NULL:
  166738. pNode[i].jnFlags |= JNODE_REMOVE;
  166739. break;
  166740. case JSON_OBJECT:
  166741. jsonRemoveAllNulls(&pNode[i]);
  166742. break;
  166743. }
  166744. }
  166745. }
  166746. /****************************************************************************
  166747. ** SQL functions used for testing and debugging
  166748. ****************************************************************************/
  166749. #ifdef SQLITE_DEBUG
  166750. /*
  166751. ** The json_parse(JSON) function returns a string which describes
  166752. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  166753. ** well-formed.
  166754. */
  166755. static void jsonParseFunc(
  166756. sqlite3_context *ctx,
  166757. int argc,
  166758. sqlite3_value **argv
  166759. ){
  166760. JsonString s; /* Output string - not real JSON */
  166761. JsonParse x; /* The parse */
  166762. u32 i;
  166763. assert( argc==1 );
  166764. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  166765. jsonParseFindParents(&x);
  166766. jsonInit(&s, ctx);
  166767. for(i=0; i<x.nNode; i++){
  166768. const char *zType;
  166769. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  166770. assert( x.aNode[i].eType==JSON_STRING );
  166771. zType = "label";
  166772. }else{
  166773. zType = jsonType[x.aNode[i].eType];
  166774. }
  166775. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  166776. i, zType, x.aNode[i].n, x.aUp[i]);
  166777. if( x.aNode[i].u.zJContent!=0 ){
  166778. jsonAppendRaw(&s, " ", 1);
  166779. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  166780. }
  166781. jsonAppendRaw(&s, "\n", 1);
  166782. }
  166783. jsonParseReset(&x);
  166784. jsonResult(&s);
  166785. }
  166786. /*
  166787. ** The json_test1(JSON) function return true (1) if the input is JSON
  166788. ** text generated by another json function. It returns (0) if the input
  166789. ** is not known to be JSON.
  166790. */
  166791. static void jsonTest1Func(
  166792. sqlite3_context *ctx,
  166793. int argc,
  166794. sqlite3_value **argv
  166795. ){
  166796. UNUSED_PARAM(argc);
  166797. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  166798. }
  166799. #endif /* SQLITE_DEBUG */
  166800. /****************************************************************************
  166801. ** Scalar SQL function implementations
  166802. ****************************************************************************/
  166803. /*
  166804. ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
  166805. ** corresponding to the SQL value input. Mostly this means putting
  166806. ** double-quotes around strings and returning the unquoted string "null"
  166807. ** when given a NULL input.
  166808. */
  166809. static void jsonQuoteFunc(
  166810. sqlite3_context *ctx,
  166811. int argc,
  166812. sqlite3_value **argv
  166813. ){
  166814. JsonString jx;
  166815. UNUSED_PARAM(argc);
  166816. jsonInit(&jx, ctx);
  166817. jsonAppendValue(&jx, argv[0]);
  166818. jsonResult(&jx);
  166819. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  166820. }
  166821. /*
  166822. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  166823. ** array that contains all values given in arguments. Or if any argument
  166824. ** is a BLOB, throw an error.
  166825. */
  166826. static void jsonArrayFunc(
  166827. sqlite3_context *ctx,
  166828. int argc,
  166829. sqlite3_value **argv
  166830. ){
  166831. int i;
  166832. JsonString jx;
  166833. jsonInit(&jx, ctx);
  166834. jsonAppendChar(&jx, '[');
  166835. for(i=0; i<argc; i++){
  166836. jsonAppendSeparator(&jx);
  166837. jsonAppendValue(&jx, argv[i]);
  166838. }
  166839. jsonAppendChar(&jx, ']');
  166840. jsonResult(&jx);
  166841. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  166842. }
  166843. /*
  166844. ** json_array_length(JSON)
  166845. ** json_array_length(JSON, PATH)
  166846. **
  166847. ** Return the number of elements in the top-level JSON array.
  166848. ** Return 0 if the input is not a well-formed JSON array.
  166849. */
  166850. static void jsonArrayLengthFunc(
  166851. sqlite3_context *ctx,
  166852. int argc,
  166853. sqlite3_value **argv
  166854. ){
  166855. JsonParse *p; /* The parse */
  166856. sqlite3_int64 n = 0;
  166857. u32 i;
  166858. JsonNode *pNode;
  166859. p = jsonParseCached(ctx, argv, ctx);
  166860. if( p==0 ) return;
  166861. assert( p->nNode );
  166862. if( argc==2 ){
  166863. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  166864. pNode = jsonLookup(p, zPath, 0, ctx);
  166865. }else{
  166866. pNode = p->aNode;
  166867. }
  166868. if( pNode==0 ){
  166869. return;
  166870. }
  166871. if( pNode->eType==JSON_ARRAY ){
  166872. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  166873. for(i=1; i<=pNode->n; n++){
  166874. i += jsonNodeSize(&pNode[i]);
  166875. }
  166876. }
  166877. sqlite3_result_int64(ctx, n);
  166878. }
  166879. /*
  166880. ** json_extract(JSON, PATH, ...)
  166881. **
  166882. ** Return the element described by PATH. Return NULL if there is no
  166883. ** PATH element. If there are multiple PATHs, then return a JSON array
  166884. ** with the result from each path. Throw an error if the JSON or any PATH
  166885. ** is malformed.
  166886. */
  166887. static void jsonExtractFunc(
  166888. sqlite3_context *ctx,
  166889. int argc,
  166890. sqlite3_value **argv
  166891. ){
  166892. JsonParse *p; /* The parse */
  166893. JsonNode *pNode;
  166894. const char *zPath;
  166895. JsonString jx;
  166896. int i;
  166897. if( argc<2 ) return;
  166898. p = jsonParseCached(ctx, argv, ctx);
  166899. if( p==0 ) return;
  166900. jsonInit(&jx, ctx);
  166901. jsonAppendChar(&jx, '[');
  166902. for(i=1; i<argc; i++){
  166903. zPath = (const char*)sqlite3_value_text(argv[i]);
  166904. pNode = jsonLookup(p, zPath, 0, ctx);
  166905. if( p->nErr ) break;
  166906. if( argc>2 ){
  166907. jsonAppendSeparator(&jx);
  166908. if( pNode ){
  166909. jsonRenderNode(pNode, &jx, 0);
  166910. }else{
  166911. jsonAppendRaw(&jx, "null", 4);
  166912. }
  166913. }else if( pNode ){
  166914. jsonReturn(pNode, ctx, 0);
  166915. }
  166916. }
  166917. if( argc>2 && i==argc ){
  166918. jsonAppendChar(&jx, ']');
  166919. jsonResult(&jx);
  166920. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  166921. }
  166922. jsonReset(&jx);
  166923. }
  166924. /* This is the RFC 7396 MergePatch algorithm.
  166925. */
  166926. static JsonNode *jsonMergePatch(
  166927. JsonParse *pParse, /* The JSON parser that contains the TARGET */
  166928. u32 iTarget, /* Node of the TARGET in pParse */
  166929. JsonNode *pPatch /* The PATCH */
  166930. ){
  166931. u32 i, j;
  166932. u32 iRoot;
  166933. JsonNode *pTarget;
  166934. if( pPatch->eType!=JSON_OBJECT ){
  166935. return pPatch;
  166936. }
  166937. assert( iTarget>=0 && iTarget<pParse->nNode );
  166938. pTarget = &pParse->aNode[iTarget];
  166939. assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
  166940. if( pTarget->eType!=JSON_OBJECT ){
  166941. jsonRemoveAllNulls(pPatch);
  166942. return pPatch;
  166943. }
  166944. iRoot = iTarget;
  166945. for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
  166946. u32 nKey;
  166947. const char *zKey;
  166948. assert( pPatch[i].eType==JSON_STRING );
  166949. assert( pPatch[i].jnFlags & JNODE_LABEL );
  166950. nKey = pPatch[i].n;
  166951. zKey = pPatch[i].u.zJContent;
  166952. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  166953. for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
  166954. assert( pTarget[j].eType==JSON_STRING );
  166955. assert( pTarget[j].jnFlags & JNODE_LABEL );
  166956. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  166957. if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
  166958. if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
  166959. if( pPatch[i+1].eType==JSON_NULL ){
  166960. pTarget[j+1].jnFlags |= JNODE_REMOVE;
  166961. }else{
  166962. JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
  166963. if( pNew==0 ) return 0;
  166964. pTarget = &pParse->aNode[iTarget];
  166965. if( pNew!=&pTarget[j+1] ){
  166966. pTarget[j+1].u.pPatch = pNew;
  166967. pTarget[j+1].jnFlags |= JNODE_PATCH;
  166968. }
  166969. }
  166970. break;
  166971. }
  166972. }
  166973. if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
  166974. int iStart, iPatch;
  166975. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  166976. jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  166977. iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  166978. if( pParse->oom ) return 0;
  166979. jsonRemoveAllNulls(pPatch);
  166980. pTarget = &pParse->aNode[iTarget];
  166981. pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
  166982. pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
  166983. iRoot = iStart;
  166984. pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
  166985. pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
  166986. }
  166987. }
  166988. return pTarget;
  166989. }
  166990. /*
  166991. ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
  166992. ** object that is the result of running the RFC 7396 MergePatch() algorithm
  166993. ** on the two arguments.
  166994. */
  166995. static void jsonPatchFunc(
  166996. sqlite3_context *ctx,
  166997. int argc,
  166998. sqlite3_value **argv
  166999. ){
  167000. JsonParse x; /* The JSON that is being patched */
  167001. JsonParse y; /* The patch */
  167002. JsonNode *pResult; /* The result of the merge */
  167003. UNUSED_PARAM(argc);
  167004. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  167005. if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
  167006. jsonParseReset(&x);
  167007. return;
  167008. }
  167009. pResult = jsonMergePatch(&x, 0, y.aNode);
  167010. assert( pResult!=0 || x.oom );
  167011. if( pResult ){
  167012. jsonReturnJson(pResult, ctx, 0);
  167013. }else{
  167014. sqlite3_result_error_nomem(ctx);
  167015. }
  167016. jsonParseReset(&x);
  167017. jsonParseReset(&y);
  167018. }
  167019. /*
  167020. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  167021. ** object that contains all name/value given in arguments. Or if any name
  167022. ** is not a string or if any value is a BLOB, throw an error.
  167023. */
  167024. static void jsonObjectFunc(
  167025. sqlite3_context *ctx,
  167026. int argc,
  167027. sqlite3_value **argv
  167028. ){
  167029. int i;
  167030. JsonString jx;
  167031. const char *z;
  167032. u32 n;
  167033. if( argc&1 ){
  167034. sqlite3_result_error(ctx, "json_object() requires an even number "
  167035. "of arguments", -1);
  167036. return;
  167037. }
  167038. jsonInit(&jx, ctx);
  167039. jsonAppendChar(&jx, '{');
  167040. for(i=0; i<argc; i+=2){
  167041. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  167042. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  167043. jsonReset(&jx);
  167044. return;
  167045. }
  167046. jsonAppendSeparator(&jx);
  167047. z = (const char*)sqlite3_value_text(argv[i]);
  167048. n = (u32)sqlite3_value_bytes(argv[i]);
  167049. jsonAppendString(&jx, z, n);
  167050. jsonAppendChar(&jx, ':');
  167051. jsonAppendValue(&jx, argv[i+1]);
  167052. }
  167053. jsonAppendChar(&jx, '}');
  167054. jsonResult(&jx);
  167055. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  167056. }
  167057. /*
  167058. ** json_remove(JSON, PATH, ...)
  167059. **
  167060. ** Remove the named elements from JSON and return the result. malformed
  167061. ** JSON or PATH arguments result in an error.
  167062. */
  167063. static void jsonRemoveFunc(
  167064. sqlite3_context *ctx,
  167065. int argc,
  167066. sqlite3_value **argv
  167067. ){
  167068. JsonParse x; /* The parse */
  167069. JsonNode *pNode;
  167070. const char *zPath;
  167071. u32 i;
  167072. if( argc<1 ) return;
  167073. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  167074. assert( x.nNode );
  167075. for(i=1; i<(u32)argc; i++){
  167076. zPath = (const char*)sqlite3_value_text(argv[i]);
  167077. if( zPath==0 ) goto remove_done;
  167078. pNode = jsonLookup(&x, zPath, 0, ctx);
  167079. if( x.nErr ) goto remove_done;
  167080. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  167081. }
  167082. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  167083. jsonReturnJson(x.aNode, ctx, 0);
  167084. }
  167085. remove_done:
  167086. jsonParseReset(&x);
  167087. }
  167088. /*
  167089. ** json_replace(JSON, PATH, VALUE, ...)
  167090. **
  167091. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  167092. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  167093. */
  167094. static void jsonReplaceFunc(
  167095. sqlite3_context *ctx,
  167096. int argc,
  167097. sqlite3_value **argv
  167098. ){
  167099. JsonParse x; /* The parse */
  167100. JsonNode *pNode;
  167101. const char *zPath;
  167102. u32 i;
  167103. if( argc<1 ) return;
  167104. if( (argc&1)==0 ) {
  167105. jsonWrongNumArgs(ctx, "replace");
  167106. return;
  167107. }
  167108. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  167109. assert( x.nNode );
  167110. for(i=1; i<(u32)argc; i+=2){
  167111. zPath = (const char*)sqlite3_value_text(argv[i]);
  167112. pNode = jsonLookup(&x, zPath, 0, ctx);
  167113. if( x.nErr ) goto replace_err;
  167114. if( pNode ){
  167115. pNode->jnFlags |= (u8)JNODE_REPLACE;
  167116. pNode->u.iReplace = i + 1;
  167117. }
  167118. }
  167119. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  167120. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  167121. }else{
  167122. jsonReturnJson(x.aNode, ctx, argv);
  167123. }
  167124. replace_err:
  167125. jsonParseReset(&x);
  167126. }
  167127. /*
  167128. ** json_set(JSON, PATH, VALUE, ...)
  167129. **
  167130. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  167131. ** exist. Overwrite existing values that do exist.
  167132. ** If JSON or PATH is malformed, throw an error.
  167133. **
  167134. ** json_insert(JSON, PATH, VALUE, ...)
  167135. **
  167136. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  167137. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  167138. */
  167139. static void jsonSetFunc(
  167140. sqlite3_context *ctx,
  167141. int argc,
  167142. sqlite3_value **argv
  167143. ){
  167144. JsonParse x; /* The parse */
  167145. JsonNode *pNode;
  167146. const char *zPath;
  167147. u32 i;
  167148. int bApnd;
  167149. int bIsSet = *(int*)sqlite3_user_data(ctx);
  167150. if( argc<1 ) return;
  167151. if( (argc&1)==0 ) {
  167152. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  167153. return;
  167154. }
  167155. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  167156. assert( x.nNode );
  167157. for(i=1; i<(u32)argc; i+=2){
  167158. zPath = (const char*)sqlite3_value_text(argv[i]);
  167159. bApnd = 0;
  167160. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  167161. if( x.oom ){
  167162. sqlite3_result_error_nomem(ctx);
  167163. goto jsonSetDone;
  167164. }else if( x.nErr ){
  167165. goto jsonSetDone;
  167166. }else if( pNode && (bApnd || bIsSet) ){
  167167. pNode->jnFlags |= (u8)JNODE_REPLACE;
  167168. pNode->u.iReplace = i + 1;
  167169. }
  167170. }
  167171. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  167172. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  167173. }else{
  167174. jsonReturnJson(x.aNode, ctx, argv);
  167175. }
  167176. jsonSetDone:
  167177. jsonParseReset(&x);
  167178. }
  167179. /*
  167180. ** json_type(JSON)
  167181. ** json_type(JSON, PATH)
  167182. **
  167183. ** Return the top-level "type" of a JSON string. Throw an error if
  167184. ** either the JSON or PATH inputs are not well-formed.
  167185. */
  167186. static void jsonTypeFunc(
  167187. sqlite3_context *ctx,
  167188. int argc,
  167189. sqlite3_value **argv
  167190. ){
  167191. JsonParse *p; /* The parse */
  167192. const char *zPath;
  167193. JsonNode *pNode;
  167194. p = jsonParseCached(ctx, argv, ctx);
  167195. if( p==0 ) return;
  167196. if( argc==2 ){
  167197. zPath = (const char*)sqlite3_value_text(argv[1]);
  167198. pNode = jsonLookup(p, zPath, 0, ctx);
  167199. }else{
  167200. pNode = p->aNode;
  167201. }
  167202. if( pNode ){
  167203. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  167204. }
  167205. }
  167206. /*
  167207. ** json_valid(JSON)
  167208. **
  167209. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  167210. ** Return 0 otherwise.
  167211. */
  167212. static void jsonValidFunc(
  167213. sqlite3_context *ctx,
  167214. int argc,
  167215. sqlite3_value **argv
  167216. ){
  167217. JsonParse *p; /* The parse */
  167218. UNUSED_PARAM(argc);
  167219. p = jsonParseCached(ctx, argv, 0);
  167220. sqlite3_result_int(ctx, p!=0);
  167221. }
  167222. /****************************************************************************
  167223. ** Aggregate SQL function implementations
  167224. ****************************************************************************/
  167225. /*
  167226. ** json_group_array(VALUE)
  167227. **
  167228. ** Return a JSON array composed of all values in the aggregate.
  167229. */
  167230. static void jsonArrayStep(
  167231. sqlite3_context *ctx,
  167232. int argc,
  167233. sqlite3_value **argv
  167234. ){
  167235. JsonString *pStr;
  167236. UNUSED_PARAM(argc);
  167237. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  167238. if( pStr ){
  167239. if( pStr->zBuf==0 ){
  167240. jsonInit(pStr, ctx);
  167241. jsonAppendChar(pStr, '[');
  167242. }else{
  167243. jsonAppendChar(pStr, ',');
  167244. pStr->pCtx = ctx;
  167245. }
  167246. jsonAppendValue(pStr, argv[0]);
  167247. }
  167248. }
  167249. static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
  167250. JsonString *pStr;
  167251. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  167252. if( pStr ){
  167253. pStr->pCtx = ctx;
  167254. jsonAppendChar(pStr, ']');
  167255. if( pStr->bErr ){
  167256. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  167257. assert( pStr->bStatic );
  167258. }else if( isFinal ){
  167259. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
  167260. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  167261. pStr->bStatic = 1;
  167262. }else{
  167263. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
  167264. pStr->nUsed--;
  167265. }
  167266. }else{
  167267. sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  167268. }
  167269. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  167270. }
  167271. static void jsonArrayValue(sqlite3_context *ctx){
  167272. jsonArrayCompute(ctx, 0);
  167273. }
  167274. static void jsonArrayFinal(sqlite3_context *ctx){
  167275. jsonArrayCompute(ctx, 1);
  167276. }
  167277. #ifndef SQLITE_OMIT_WINDOWFUNC
  167278. /*
  167279. ** This method works for both json_group_array() and json_group_object().
  167280. ** It works by removing the first element of the group by searching forward
  167281. ** to the first comma (",") that is not within a string and deleting all
  167282. ** text through that comma.
  167283. */
  167284. static void jsonGroupInverse(
  167285. sqlite3_context *ctx,
  167286. int argc,
  167287. sqlite3_value **argv
  167288. ){
  167289. int i;
  167290. int inStr = 0;
  167291. char *z;
  167292. JsonString *pStr;
  167293. UNUSED_PARAM(argc);
  167294. UNUSED_PARAM(argv);
  167295. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  167296. #ifdef NEVER
  167297. /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
  167298. ** always have been called to initalize it */
  167299. if( NEVER(!pStr) ) return;
  167300. #endif
  167301. z = pStr->zBuf;
  167302. for(i=1; z[i]!=',' || inStr; i++){
  167303. assert( i<pStr->nUsed );
  167304. if( z[i]=='"' ){
  167305. inStr = !inStr;
  167306. }else if( z[i]=='\\' ){
  167307. i++;
  167308. }
  167309. }
  167310. pStr->nUsed -= i;
  167311. memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
  167312. }
  167313. #else
  167314. # define jsonGroupInverse 0
  167315. #endif
  167316. /*
  167317. ** json_group_obj(NAME,VALUE)
  167318. **
  167319. ** Return a JSON object composed of all names and values in the aggregate.
  167320. */
  167321. static void jsonObjectStep(
  167322. sqlite3_context *ctx,
  167323. int argc,
  167324. sqlite3_value **argv
  167325. ){
  167326. JsonString *pStr;
  167327. const char *z;
  167328. u32 n;
  167329. UNUSED_PARAM(argc);
  167330. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  167331. if( pStr ){
  167332. if( pStr->zBuf==0 ){
  167333. jsonInit(pStr, ctx);
  167334. jsonAppendChar(pStr, '{');
  167335. }else{
  167336. jsonAppendChar(pStr, ',');
  167337. pStr->pCtx = ctx;
  167338. }
  167339. z = (const char*)sqlite3_value_text(argv[0]);
  167340. n = (u32)sqlite3_value_bytes(argv[0]);
  167341. jsonAppendString(pStr, z, n);
  167342. jsonAppendChar(pStr, ':');
  167343. jsonAppendValue(pStr, argv[1]);
  167344. }
  167345. }
  167346. static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
  167347. JsonString *pStr;
  167348. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  167349. if( pStr ){
  167350. jsonAppendChar(pStr, '}');
  167351. if( pStr->bErr ){
  167352. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  167353. assert( pStr->bStatic );
  167354. }else if( isFinal ){
  167355. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
  167356. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  167357. pStr->bStatic = 1;
  167358. }else{
  167359. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
  167360. pStr->nUsed--;
  167361. }
  167362. }else{
  167363. sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  167364. }
  167365. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  167366. }
  167367. static void jsonObjectValue(sqlite3_context *ctx){
  167368. jsonObjectCompute(ctx, 0);
  167369. }
  167370. static void jsonObjectFinal(sqlite3_context *ctx){
  167371. jsonObjectCompute(ctx, 1);
  167372. }
  167373. #ifndef SQLITE_OMIT_VIRTUALTABLE
  167374. /****************************************************************************
  167375. ** The json_each virtual table
  167376. ****************************************************************************/
  167377. typedef struct JsonEachCursor JsonEachCursor;
  167378. struct JsonEachCursor {
  167379. sqlite3_vtab_cursor base; /* Base class - must be first */
  167380. u32 iRowid; /* The rowid */
  167381. u32 iBegin; /* The first node of the scan */
  167382. u32 i; /* Index in sParse.aNode[] of current row */
  167383. u32 iEnd; /* EOF when i equals or exceeds this value */
  167384. u8 eType; /* Type of top-level element */
  167385. u8 bRecursive; /* True for json_tree(). False for json_each() */
  167386. char *zJson; /* Input JSON */
  167387. char *zRoot; /* Path by which to filter zJson */
  167388. JsonParse sParse; /* Parse of the input JSON */
  167389. };
  167390. /* Constructor for the json_each virtual table */
  167391. static int jsonEachConnect(
  167392. sqlite3 *db,
  167393. void *pAux,
  167394. int argc, const char *const*argv,
  167395. sqlite3_vtab **ppVtab,
  167396. char **pzErr
  167397. ){
  167398. sqlite3_vtab *pNew;
  167399. int rc;
  167400. /* Column numbers */
  167401. #define JEACH_KEY 0
  167402. #define JEACH_VALUE 1
  167403. #define JEACH_TYPE 2
  167404. #define JEACH_ATOM 3
  167405. #define JEACH_ID 4
  167406. #define JEACH_PARENT 5
  167407. #define JEACH_FULLKEY 6
  167408. #define JEACH_PATH 7
  167409. /* The xBestIndex method assumes that the JSON and ROOT columns are
  167410. ** the last two columns in the table. Should this ever changes, be
  167411. ** sure to update the xBestIndex method. */
  167412. #define JEACH_JSON 8
  167413. #define JEACH_ROOT 9
  167414. UNUSED_PARAM(pzErr);
  167415. UNUSED_PARAM(argv);
  167416. UNUSED_PARAM(argc);
  167417. UNUSED_PARAM(pAux);
  167418. rc = sqlite3_declare_vtab(db,
  167419. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  167420. "json HIDDEN,root HIDDEN)");
  167421. if( rc==SQLITE_OK ){
  167422. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  167423. if( pNew==0 ) return SQLITE_NOMEM;
  167424. memset(pNew, 0, sizeof(*pNew));
  167425. }
  167426. return rc;
  167427. }
  167428. /* destructor for json_each virtual table */
  167429. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  167430. sqlite3_free(pVtab);
  167431. return SQLITE_OK;
  167432. }
  167433. /* constructor for a JsonEachCursor object for json_each(). */
  167434. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  167435. JsonEachCursor *pCur;
  167436. UNUSED_PARAM(p);
  167437. pCur = sqlite3_malloc( sizeof(*pCur) );
  167438. if( pCur==0 ) return SQLITE_NOMEM;
  167439. memset(pCur, 0, sizeof(*pCur));
  167440. *ppCursor = &pCur->base;
  167441. return SQLITE_OK;
  167442. }
  167443. /* constructor for a JsonEachCursor object for json_tree(). */
  167444. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  167445. int rc = jsonEachOpenEach(p, ppCursor);
  167446. if( rc==SQLITE_OK ){
  167447. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  167448. pCur->bRecursive = 1;
  167449. }
  167450. return rc;
  167451. }
  167452. /* Reset a JsonEachCursor back to its original state. Free any memory
  167453. ** held. */
  167454. static void jsonEachCursorReset(JsonEachCursor *p){
  167455. sqlite3_free(p->zJson);
  167456. sqlite3_free(p->zRoot);
  167457. jsonParseReset(&p->sParse);
  167458. p->iRowid = 0;
  167459. p->i = 0;
  167460. p->iEnd = 0;
  167461. p->eType = 0;
  167462. p->zJson = 0;
  167463. p->zRoot = 0;
  167464. }
  167465. /* Destructor for a jsonEachCursor object */
  167466. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  167467. JsonEachCursor *p = (JsonEachCursor*)cur;
  167468. jsonEachCursorReset(p);
  167469. sqlite3_free(cur);
  167470. return SQLITE_OK;
  167471. }
  167472. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  167473. ** of the JSON object */
  167474. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  167475. JsonEachCursor *p = (JsonEachCursor*)cur;
  167476. return p->i >= p->iEnd;
  167477. }
  167478. /* Advance the cursor to the next element for json_tree() */
  167479. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  167480. JsonEachCursor *p = (JsonEachCursor*)cur;
  167481. if( p->bRecursive ){
  167482. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  167483. p->i++;
  167484. p->iRowid++;
  167485. if( p->i<p->iEnd ){
  167486. u32 iUp = p->sParse.aUp[p->i];
  167487. JsonNode *pUp = &p->sParse.aNode[iUp];
  167488. p->eType = pUp->eType;
  167489. if( pUp->eType==JSON_ARRAY ){
  167490. if( iUp==p->i-1 ){
  167491. pUp->u.iKey = 0;
  167492. }else{
  167493. pUp->u.iKey++;
  167494. }
  167495. }
  167496. }
  167497. }else{
  167498. switch( p->eType ){
  167499. case JSON_ARRAY: {
  167500. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  167501. p->iRowid++;
  167502. break;
  167503. }
  167504. case JSON_OBJECT: {
  167505. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  167506. p->iRowid++;
  167507. break;
  167508. }
  167509. default: {
  167510. p->i = p->iEnd;
  167511. break;
  167512. }
  167513. }
  167514. }
  167515. return SQLITE_OK;
  167516. }
  167517. /* Append the name of the path for element i to pStr
  167518. */
  167519. static void jsonEachComputePath(
  167520. JsonEachCursor *p, /* The cursor */
  167521. JsonString *pStr, /* Write the path here */
  167522. u32 i /* Path to this element */
  167523. ){
  167524. JsonNode *pNode, *pUp;
  167525. u32 iUp;
  167526. if( i==0 ){
  167527. jsonAppendChar(pStr, '$');
  167528. return;
  167529. }
  167530. iUp = p->sParse.aUp[i];
  167531. jsonEachComputePath(p, pStr, iUp);
  167532. pNode = &p->sParse.aNode[i];
  167533. pUp = &p->sParse.aNode[iUp];
  167534. if( pUp->eType==JSON_ARRAY ){
  167535. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  167536. }else{
  167537. assert( pUp->eType==JSON_OBJECT );
  167538. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  167539. assert( pNode->eType==JSON_STRING );
  167540. assert( pNode->jnFlags & JNODE_LABEL );
  167541. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  167542. }
  167543. }
  167544. /* Return the value of a column */
  167545. static int jsonEachColumn(
  167546. sqlite3_vtab_cursor *cur, /* The cursor */
  167547. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  167548. int i /* Which column to return */
  167549. ){
  167550. JsonEachCursor *p = (JsonEachCursor*)cur;
  167551. JsonNode *pThis = &p->sParse.aNode[p->i];
  167552. switch( i ){
  167553. case JEACH_KEY: {
  167554. if( p->i==0 ) break;
  167555. if( p->eType==JSON_OBJECT ){
  167556. jsonReturn(pThis, ctx, 0);
  167557. }else if( p->eType==JSON_ARRAY ){
  167558. u32 iKey;
  167559. if( p->bRecursive ){
  167560. if( p->iRowid==0 ) break;
  167561. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  167562. }else{
  167563. iKey = p->iRowid;
  167564. }
  167565. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  167566. }
  167567. break;
  167568. }
  167569. case JEACH_VALUE: {
  167570. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  167571. jsonReturn(pThis, ctx, 0);
  167572. break;
  167573. }
  167574. case JEACH_TYPE: {
  167575. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  167576. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  167577. break;
  167578. }
  167579. case JEACH_ATOM: {
  167580. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  167581. if( pThis->eType>=JSON_ARRAY ) break;
  167582. jsonReturn(pThis, ctx, 0);
  167583. break;
  167584. }
  167585. case JEACH_ID: {
  167586. sqlite3_result_int64(ctx,
  167587. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  167588. break;
  167589. }
  167590. case JEACH_PARENT: {
  167591. if( p->i>p->iBegin && p->bRecursive ){
  167592. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  167593. }
  167594. break;
  167595. }
  167596. case JEACH_FULLKEY: {
  167597. JsonString x;
  167598. jsonInit(&x, ctx);
  167599. if( p->bRecursive ){
  167600. jsonEachComputePath(p, &x, p->i);
  167601. }else{
  167602. if( p->zRoot ){
  167603. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  167604. }else{
  167605. jsonAppendChar(&x, '$');
  167606. }
  167607. if( p->eType==JSON_ARRAY ){
  167608. jsonPrintf(30, &x, "[%d]", p->iRowid);
  167609. }else if( p->eType==JSON_OBJECT ){
  167610. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  167611. }
  167612. }
  167613. jsonResult(&x);
  167614. break;
  167615. }
  167616. case JEACH_PATH: {
  167617. if( p->bRecursive ){
  167618. JsonString x;
  167619. jsonInit(&x, ctx);
  167620. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  167621. jsonResult(&x);
  167622. break;
  167623. }
  167624. /* For json_each() path and root are the same so fall through
  167625. ** into the root case */
  167626. }
  167627. default: {
  167628. const char *zRoot = p->zRoot;
  167629. if( zRoot==0 ) zRoot = "$";
  167630. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  167631. break;
  167632. }
  167633. case JEACH_JSON: {
  167634. assert( i==JEACH_JSON );
  167635. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  167636. break;
  167637. }
  167638. }
  167639. return SQLITE_OK;
  167640. }
  167641. /* Return the current rowid value */
  167642. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  167643. JsonEachCursor *p = (JsonEachCursor*)cur;
  167644. *pRowid = p->iRowid;
  167645. return SQLITE_OK;
  167646. }
  167647. /* The query strategy is to look for an equality constraint on the json
  167648. ** column. Without such a constraint, the table cannot operate. idxNum is
  167649. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  167650. ** and 0 otherwise.
  167651. */
  167652. static int jsonEachBestIndex(
  167653. sqlite3_vtab *tab,
  167654. sqlite3_index_info *pIdxInfo
  167655. ){
  167656. int i; /* Loop counter or computed array index */
  167657. int aIdx[2]; /* Index of constraints for JSON and ROOT */
  167658. int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */
  167659. int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */
  167660. const struct sqlite3_index_constraint *pConstraint;
  167661. /* This implementation assumes that JSON and ROOT are the last two
  167662. ** columns in the table */
  167663. assert( JEACH_ROOT == JEACH_JSON+1 );
  167664. UNUSED_PARAM(tab);
  167665. aIdx[0] = aIdx[1] = -1;
  167666. pConstraint = pIdxInfo->aConstraint;
  167667. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  167668. int iCol;
  167669. int iMask;
  167670. if( pConstraint->iColumn < JEACH_JSON ) continue;
  167671. iCol = pConstraint->iColumn - JEACH_JSON;
  167672. assert( iCol==0 || iCol==1 );
  167673. iMask = 1 << iCol;
  167674. if( pConstraint->usable==0 ){
  167675. unusableMask |= iMask;
  167676. }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  167677. aIdx[iCol] = i;
  167678. idxMask |= iMask;
  167679. }
  167680. }
  167681. if( (unusableMask & ~idxMask)!=0 ){
  167682. /* If there are any unusable constraints on JSON or ROOT, then reject
  167683. ** this entire plan */
  167684. return SQLITE_CONSTRAINT;
  167685. }
  167686. if( aIdx[0]<0 ){
  167687. /* No JSON input. Leave estimatedCost at the huge value that it was
  167688. ** initialized to to discourage the query planner from selecting this
  167689. ** plan. */
  167690. pIdxInfo->idxNum = 0;
  167691. }else{
  167692. pIdxInfo->estimatedCost = 1.0;
  167693. i = aIdx[0];
  167694. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  167695. pIdxInfo->aConstraintUsage[i].omit = 1;
  167696. if( aIdx[1]<0 ){
  167697. pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */
  167698. }else{
  167699. i = aIdx[1];
  167700. pIdxInfo->aConstraintUsage[i].argvIndex = 2;
  167701. pIdxInfo->aConstraintUsage[i].omit = 1;
  167702. pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */
  167703. }
  167704. }
  167705. return SQLITE_OK;
  167706. }
  167707. /* Start a search on a new JSON string */
  167708. static int jsonEachFilter(
  167709. sqlite3_vtab_cursor *cur,
  167710. int idxNum, const char *idxStr,
  167711. int argc, sqlite3_value **argv
  167712. ){
  167713. JsonEachCursor *p = (JsonEachCursor*)cur;
  167714. const char *z;
  167715. const char *zRoot = 0;
  167716. sqlite3_int64 n;
  167717. UNUSED_PARAM(idxStr);
  167718. UNUSED_PARAM(argc);
  167719. jsonEachCursorReset(p);
  167720. if( idxNum==0 ) return SQLITE_OK;
  167721. z = (const char*)sqlite3_value_text(argv[0]);
  167722. if( z==0 ) return SQLITE_OK;
  167723. n = sqlite3_value_bytes(argv[0]);
  167724. p->zJson = sqlite3_malloc64( n+1 );
  167725. if( p->zJson==0 ) return SQLITE_NOMEM;
  167726. memcpy(p->zJson, z, (size_t)n+1);
  167727. if( jsonParse(&p->sParse, 0, p->zJson) ){
  167728. int rc = SQLITE_NOMEM;
  167729. if( p->sParse.oom==0 ){
  167730. sqlite3_free(cur->pVtab->zErrMsg);
  167731. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  167732. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  167733. }
  167734. jsonEachCursorReset(p);
  167735. return rc;
  167736. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  167737. jsonEachCursorReset(p);
  167738. return SQLITE_NOMEM;
  167739. }else{
  167740. JsonNode *pNode = 0;
  167741. if( idxNum==3 ){
  167742. const char *zErr = 0;
  167743. zRoot = (const char*)sqlite3_value_text(argv[1]);
  167744. if( zRoot==0 ) return SQLITE_OK;
  167745. n = sqlite3_value_bytes(argv[1]);
  167746. p->zRoot = sqlite3_malloc64( n+1 );
  167747. if( p->zRoot==0 ) return SQLITE_NOMEM;
  167748. memcpy(p->zRoot, zRoot, (size_t)n+1);
  167749. if( zRoot[0]!='$' ){
  167750. zErr = zRoot;
  167751. }else{
  167752. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  167753. }
  167754. if( zErr ){
  167755. sqlite3_free(cur->pVtab->zErrMsg);
  167756. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  167757. jsonEachCursorReset(p);
  167758. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  167759. }else if( pNode==0 ){
  167760. return SQLITE_OK;
  167761. }
  167762. }else{
  167763. pNode = p->sParse.aNode;
  167764. }
  167765. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  167766. p->eType = pNode->eType;
  167767. if( p->eType>=JSON_ARRAY ){
  167768. pNode->u.iKey = 0;
  167769. p->iEnd = p->i + pNode->n + 1;
  167770. if( p->bRecursive ){
  167771. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  167772. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  167773. p->i--;
  167774. }
  167775. }else{
  167776. p->i++;
  167777. }
  167778. }else{
  167779. p->iEnd = p->i+1;
  167780. }
  167781. }
  167782. return SQLITE_OK;
  167783. }
  167784. /* The methods of the json_each virtual table */
  167785. static sqlite3_module jsonEachModule = {
  167786. 0, /* iVersion */
  167787. 0, /* xCreate */
  167788. jsonEachConnect, /* xConnect */
  167789. jsonEachBestIndex, /* xBestIndex */
  167790. jsonEachDisconnect, /* xDisconnect */
  167791. 0, /* xDestroy */
  167792. jsonEachOpenEach, /* xOpen - open a cursor */
  167793. jsonEachClose, /* xClose - close a cursor */
  167794. jsonEachFilter, /* xFilter - configure scan constraints */
  167795. jsonEachNext, /* xNext - advance a cursor */
  167796. jsonEachEof, /* xEof - check for end of scan */
  167797. jsonEachColumn, /* xColumn - read data */
  167798. jsonEachRowid, /* xRowid - read data */
  167799. 0, /* xUpdate */
  167800. 0, /* xBegin */
  167801. 0, /* xSync */
  167802. 0, /* xCommit */
  167803. 0, /* xRollback */
  167804. 0, /* xFindMethod */
  167805. 0, /* xRename */
  167806. 0, /* xSavepoint */
  167807. 0, /* xRelease */
  167808. 0, /* xRollbackTo */
  167809. 0 /* xShadowName */
  167810. };
  167811. /* The methods of the json_tree virtual table. */
  167812. static sqlite3_module jsonTreeModule = {
  167813. 0, /* iVersion */
  167814. 0, /* xCreate */
  167815. jsonEachConnect, /* xConnect */
  167816. jsonEachBestIndex, /* xBestIndex */
  167817. jsonEachDisconnect, /* xDisconnect */
  167818. 0, /* xDestroy */
  167819. jsonEachOpenTree, /* xOpen - open a cursor */
  167820. jsonEachClose, /* xClose - close a cursor */
  167821. jsonEachFilter, /* xFilter - configure scan constraints */
  167822. jsonEachNext, /* xNext - advance a cursor */
  167823. jsonEachEof, /* xEof - check for end of scan */
  167824. jsonEachColumn, /* xColumn - read data */
  167825. jsonEachRowid, /* xRowid - read data */
  167826. 0, /* xUpdate */
  167827. 0, /* xBegin */
  167828. 0, /* xSync */
  167829. 0, /* xCommit */
  167830. 0, /* xRollback */
  167831. 0, /* xFindMethod */
  167832. 0, /* xRename */
  167833. 0, /* xSavepoint */
  167834. 0, /* xRelease */
  167835. 0, /* xRollbackTo */
  167836. 0 /* xShadowName */
  167837. };
  167838. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  167839. /****************************************************************************
  167840. ** The following routines are the only publically visible identifiers in this
  167841. ** file. Call the following routines in order to register the various SQL
  167842. ** functions and the virtual table implemented by this file.
  167843. ****************************************************************************/
  167844. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  167845. int rc = SQLITE_OK;
  167846. unsigned int i;
  167847. static const struct {
  167848. const char *zName;
  167849. int nArg;
  167850. int flag;
  167851. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  167852. } aFunc[] = {
  167853. { "json", 1, 0, jsonRemoveFunc },
  167854. { "json_array", -1, 0, jsonArrayFunc },
  167855. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  167856. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  167857. { "json_extract", -1, 0, jsonExtractFunc },
  167858. { "json_insert", -1, 0, jsonSetFunc },
  167859. { "json_object", -1, 0, jsonObjectFunc },
  167860. { "json_patch", 2, 0, jsonPatchFunc },
  167861. { "json_quote", 1, 0, jsonQuoteFunc },
  167862. { "json_remove", -1, 0, jsonRemoveFunc },
  167863. { "json_replace", -1, 0, jsonReplaceFunc },
  167864. { "json_set", -1, 1, jsonSetFunc },
  167865. { "json_type", 1, 0, jsonTypeFunc },
  167866. { "json_type", 2, 0, jsonTypeFunc },
  167867. { "json_valid", 1, 0, jsonValidFunc },
  167868. #if SQLITE_DEBUG
  167869. /* DEBUG and TESTING functions */
  167870. { "json_parse", 1, 0, jsonParseFunc },
  167871. { "json_test1", 1, 0, jsonTest1Func },
  167872. #endif
  167873. };
  167874. static const struct {
  167875. const char *zName;
  167876. int nArg;
  167877. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  167878. void (*xFinal)(sqlite3_context*);
  167879. void (*xValue)(sqlite3_context*);
  167880. } aAgg[] = {
  167881. { "json_group_array", 1,
  167882. jsonArrayStep, jsonArrayFinal, jsonArrayValue },
  167883. { "json_group_object", 2,
  167884. jsonObjectStep, jsonObjectFinal, jsonObjectValue },
  167885. };
  167886. #ifndef SQLITE_OMIT_VIRTUALTABLE
  167887. static const struct {
  167888. const char *zName;
  167889. sqlite3_module *pModule;
  167890. } aMod[] = {
  167891. { "json_each", &jsonEachModule },
  167892. { "json_tree", &jsonTreeModule },
  167893. };
  167894. #endif
  167895. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  167896. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  167897. SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  167898. (void*)&aFunc[i].flag,
  167899. aFunc[i].xFunc, 0, 0);
  167900. }
  167901. #ifndef SQLITE_OMIT_WINDOWFUNC
  167902. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  167903. rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
  167904. SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
  167905. aAgg[i].xStep, aAgg[i].xFinal,
  167906. aAgg[i].xValue, jsonGroupInverse, 0);
  167907. }
  167908. #endif
  167909. #ifndef SQLITE_OMIT_VIRTUALTABLE
  167910. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  167911. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  167912. }
  167913. #endif
  167914. return rc;
  167915. }
  167916. #ifndef SQLITE_CORE
  167917. #ifdef _WIN32
  167918. __declspec(dllexport)
  167919. #endif
  167920. SQLITE_API int sqlite3_json_init(
  167921. sqlite3 *db,
  167922. char **pzErrMsg,
  167923. const sqlite3_api_routines *pApi
  167924. ){
  167925. SQLITE_EXTENSION_INIT2(pApi);
  167926. (void)pzErrMsg; /* Unused parameter */
  167927. return sqlite3Json1Init(db);
  167928. }
  167929. #endif
  167930. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  167931. /************** End of json1.c ***********************************************/
  167932. /************** Begin file rtree.c *******************************************/
  167933. /*
  167934. ** 2001 September 15
  167935. **
  167936. ** The author disclaims copyright to this source code. In place of
  167937. ** a legal notice, here is a blessing:
  167938. **
  167939. ** May you do good and not evil.
  167940. ** May you find forgiveness for yourself and forgive others.
  167941. ** May you share freely, never taking more than you give.
  167942. **
  167943. *************************************************************************
  167944. ** This file contains code for implementations of the r-tree and r*-tree
  167945. ** algorithms packaged as an SQLite virtual table module.
  167946. */
  167947. /*
  167948. ** Database Format of R-Tree Tables
  167949. ** --------------------------------
  167950. **
  167951. ** The data structure for a single virtual r-tree table is stored in three
  167952. ** native SQLite tables declared as follows. In each case, the '%' character
  167953. ** in the table name is replaced with the user-supplied name of the r-tree
  167954. ** table.
  167955. **
  167956. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  167957. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  167958. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
  167959. **
  167960. ** The data for each node of the r-tree structure is stored in the %_node
  167961. ** table. For each node that is not the root node of the r-tree, there is
  167962. ** an entry in the %_parent table associating the node with its parent.
  167963. ** And for each row of data in the table, there is an entry in the %_rowid
  167964. ** table that maps from the entries rowid to the id of the node that it
  167965. ** is stored on. If the r-tree contains auxiliary columns, those are stored
  167966. ** on the end of the %_rowid table.
  167967. **
  167968. ** The root node of an r-tree always exists, even if the r-tree table is
  167969. ** empty. The nodeno of the root node is always 1. All other nodes in the
  167970. ** table must be the same size as the root node. The content of each node
  167971. ** is formatted as follows:
  167972. **
  167973. ** 1. If the node is the root node (node 1), then the first 2 bytes
  167974. ** of the node contain the tree depth as a big-endian integer.
  167975. ** For non-root nodes, the first 2 bytes are left unused.
  167976. **
  167977. ** 2. The next 2 bytes contain the number of entries currently
  167978. ** stored in the node.
  167979. **
  167980. ** 3. The remainder of the node contains the node entries. Each entry
  167981. ** consists of a single 8-byte integer followed by an even number
  167982. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  167983. ** of a record. For internal nodes it is the node number of a
  167984. ** child page.
  167985. */
  167986. #if !defined(SQLITE_CORE) \
  167987. || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
  167988. #ifndef SQLITE_CORE
  167989. /* #include "sqlite3ext.h" */
  167990. SQLITE_EXTENSION_INIT1
  167991. #else
  167992. /* #include "sqlite3.h" */
  167993. #endif
  167994. /* #include <string.h> */
  167995. /* #include <assert.h> */
  167996. /* #include <stdio.h> */
  167997. #ifndef SQLITE_AMALGAMATION
  167998. #include "sqlite3rtree.h"
  167999. typedef sqlite3_int64 i64;
  168000. typedef sqlite3_uint64 u64;
  168001. typedef unsigned char u8;
  168002. typedef unsigned short u16;
  168003. typedef unsigned int u32;
  168004. #endif
  168005. /* The following macro is used to suppress compiler warnings.
  168006. */
  168007. #ifndef UNUSED_PARAMETER
  168008. # define UNUSED_PARAMETER(x) (void)(x)
  168009. #endif
  168010. typedef struct Rtree Rtree;
  168011. typedef struct RtreeCursor RtreeCursor;
  168012. typedef struct RtreeNode RtreeNode;
  168013. typedef struct RtreeCell RtreeCell;
  168014. typedef struct RtreeConstraint RtreeConstraint;
  168015. typedef struct RtreeMatchArg RtreeMatchArg;
  168016. typedef struct RtreeGeomCallback RtreeGeomCallback;
  168017. typedef union RtreeCoord RtreeCoord;
  168018. typedef struct RtreeSearchPoint RtreeSearchPoint;
  168019. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  168020. #define RTREE_MAX_DIMENSIONS 5
  168021. /* Maximum number of auxiliary columns */
  168022. #define RTREE_MAX_AUX_COLUMN 100
  168023. /* Size of hash table Rtree.aHash. This hash table is not expected to
  168024. ** ever contain very many entries, so a fixed number of buckets is
  168025. ** used.
  168026. */
  168027. #define HASHSIZE 97
  168028. /* The xBestIndex method of this virtual table requires an estimate of
  168029. ** the number of rows in the virtual table to calculate the costs of
  168030. ** various strategies. If possible, this estimate is loaded from the
  168031. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  168032. ** Otherwise, if no sqlite_stat1 entry is available, use
  168033. ** RTREE_DEFAULT_ROWEST.
  168034. */
  168035. #define RTREE_DEFAULT_ROWEST 1048576
  168036. #define RTREE_MIN_ROWEST 100
  168037. /*
  168038. ** An rtree virtual-table object.
  168039. */
  168040. struct Rtree {
  168041. sqlite3_vtab base; /* Base class. Must be first */
  168042. sqlite3 *db; /* Host database connection */
  168043. int iNodeSize; /* Size in bytes of each node in the node table */
  168044. u8 nDim; /* Number of dimensions */
  168045. u8 nDim2; /* Twice the number of dimensions */
  168046. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  168047. u8 nBytesPerCell; /* Bytes consumed per cell */
  168048. u8 inWrTrans; /* True if inside write transaction */
  168049. u8 nAux; /* # of auxiliary columns in %_rowid */
  168050. u8 nAuxNotNull; /* Number of initial not-null aux columns */
  168051. int iDepth; /* Current depth of the r-tree structure */
  168052. char *zDb; /* Name of database containing r-tree table */
  168053. char *zName; /* Name of r-tree table */
  168054. u32 nBusy; /* Current number of users of this structure */
  168055. i64 nRowEst; /* Estimated number of rows in this table */
  168056. u32 nCursor; /* Number of open cursors */
  168057. u32 nNodeRef; /* Number RtreeNodes with positive nRef */
  168058. char *zReadAuxSql; /* SQL for statement to read aux data */
  168059. /* List of nodes removed during a CondenseTree operation. List is
  168060. ** linked together via the pointer normally used for hash chains -
  168061. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  168062. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  168063. */
  168064. RtreeNode *pDeleted;
  168065. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  168066. /* Blob I/O on xxx_node */
  168067. sqlite3_blob *pNodeBlob;
  168068. /* Statements to read/write/delete a record from xxx_node */
  168069. sqlite3_stmt *pWriteNode;
  168070. sqlite3_stmt *pDeleteNode;
  168071. /* Statements to read/write/delete a record from xxx_rowid */
  168072. sqlite3_stmt *pReadRowid;
  168073. sqlite3_stmt *pWriteRowid;
  168074. sqlite3_stmt *pDeleteRowid;
  168075. /* Statements to read/write/delete a record from xxx_parent */
  168076. sqlite3_stmt *pReadParent;
  168077. sqlite3_stmt *pWriteParent;
  168078. sqlite3_stmt *pDeleteParent;
  168079. /* Statement for writing to the "aux:" fields, if there are any */
  168080. sqlite3_stmt *pWriteAux;
  168081. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  168082. };
  168083. /* Possible values for Rtree.eCoordType: */
  168084. #define RTREE_COORD_REAL32 0
  168085. #define RTREE_COORD_INT32 1
  168086. /*
  168087. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  168088. ** only deal with integer coordinates. No floating point operations
  168089. ** will be done.
  168090. */
  168091. #ifdef SQLITE_RTREE_INT_ONLY
  168092. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  168093. typedef int RtreeValue; /* Low accuracy coordinate */
  168094. # define RTREE_ZERO 0
  168095. #else
  168096. typedef double RtreeDValue; /* High accuracy coordinate */
  168097. typedef float RtreeValue; /* Low accuracy coordinate */
  168098. # define RTREE_ZERO 0.0
  168099. #endif
  168100. /*
  168101. ** When doing a search of an r-tree, instances of the following structure
  168102. ** record intermediate results from the tree walk.
  168103. **
  168104. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  168105. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  168106. ** the id is of the parent node and the cell that RtreeSearchPoint
  168107. ** represents is the iCell-th entry in the parent node.
  168108. */
  168109. struct RtreeSearchPoint {
  168110. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  168111. sqlite3_int64 id; /* Node ID */
  168112. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  168113. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  168114. u8 iCell; /* Cell index within the node */
  168115. };
  168116. /*
  168117. ** The minimum number of cells allowed for a node is a third of the
  168118. ** maximum. In Gutman's notation:
  168119. **
  168120. ** m = M/3
  168121. **
  168122. ** If an R*-tree "Reinsert" operation is required, the same number of
  168123. ** cells are removed from the overfull node and reinserted into the tree.
  168124. */
  168125. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  168126. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  168127. #define RTREE_MAXCELLS 51
  168128. /*
  168129. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  168130. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  168131. ** Therefore all non-root nodes must contain at least 3 entries. Since
  168132. ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
  168133. ** 40 or less.
  168134. */
  168135. #define RTREE_MAX_DEPTH 40
  168136. /*
  168137. ** Number of entries in the cursor RtreeNode cache. The first entry is
  168138. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  168139. ** entries cache the RtreeNode for the first elements of the priority queue.
  168140. */
  168141. #define RTREE_CACHE_SZ 5
  168142. /*
  168143. ** An rtree cursor object.
  168144. */
  168145. struct RtreeCursor {
  168146. sqlite3_vtab_cursor base; /* Base class. Must be first */
  168147. u8 atEOF; /* True if at end of search */
  168148. u8 bPoint; /* True if sPoint is valid */
  168149. u8 bAuxValid; /* True if pReadAux is valid */
  168150. int iStrategy; /* Copy of idxNum search parameter */
  168151. int nConstraint; /* Number of entries in aConstraint */
  168152. RtreeConstraint *aConstraint; /* Search constraints. */
  168153. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  168154. int nPoint; /* Number of slots used in aPoint[] */
  168155. int mxLevel; /* iLevel value for root of the tree */
  168156. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  168157. sqlite3_stmt *pReadAux; /* Statement to read aux-data */
  168158. RtreeSearchPoint sPoint; /* Cached next search point */
  168159. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  168160. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  168161. };
  168162. /* Return the Rtree of a RtreeCursor */
  168163. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  168164. /*
  168165. ** A coordinate can be either a floating point number or a integer. All
  168166. ** coordinates within a single R-Tree are always of the same time.
  168167. */
  168168. union RtreeCoord {
  168169. RtreeValue f; /* Floating point value */
  168170. int i; /* Integer value */
  168171. u32 u; /* Unsigned for byte-order conversions */
  168172. };
  168173. /*
  168174. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  168175. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  168176. ** variable pRtree points to the Rtree structure associated with the
  168177. ** RtreeCoord.
  168178. */
  168179. #ifdef SQLITE_RTREE_INT_ONLY
  168180. # define DCOORD(coord) ((RtreeDValue)coord.i)
  168181. #else
  168182. # define DCOORD(coord) ( \
  168183. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  168184. ((double)coord.f) : \
  168185. ((double)coord.i) \
  168186. )
  168187. #endif
  168188. /*
  168189. ** A search constraint.
  168190. */
  168191. struct RtreeConstraint {
  168192. int iCoord; /* Index of constrained coordinate */
  168193. int op; /* Constraining operation */
  168194. union {
  168195. RtreeDValue rValue; /* Constraint value. */
  168196. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  168197. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  168198. } u;
  168199. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  168200. };
  168201. /* Possible values for RtreeConstraint.op */
  168202. #define RTREE_EQ 0x41 /* A */
  168203. #define RTREE_LE 0x42 /* B */
  168204. #define RTREE_LT 0x43 /* C */
  168205. #define RTREE_GE 0x44 /* D */
  168206. #define RTREE_GT 0x45 /* E */
  168207. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  168208. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  168209. /*
  168210. ** An rtree structure node.
  168211. */
  168212. struct RtreeNode {
  168213. RtreeNode *pParent; /* Parent node */
  168214. i64 iNode; /* The node number */
  168215. int nRef; /* Number of references to this node */
  168216. int isDirty; /* True if the node needs to be written to disk */
  168217. u8 *zData; /* Content of the node, as should be on disk */
  168218. RtreeNode *pNext; /* Next node in this hash collision chain */
  168219. };
  168220. /* Return the number of cells in a node */
  168221. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  168222. /*
  168223. ** A single cell from a node, deserialized
  168224. */
  168225. struct RtreeCell {
  168226. i64 iRowid; /* Node or entry ID */
  168227. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  168228. };
  168229. /*
  168230. ** This object becomes the sqlite3_user_data() for the SQL functions
  168231. ** that are created by sqlite3_rtree_geometry_callback() and
  168232. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  168233. ** operators in order to constrain a search.
  168234. **
  168235. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  168236. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  168237. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  168238. ** sqlite3_rtree_query_callback().
  168239. **
  168240. ** This object is deleted automatically by the destructor mechanism in
  168241. ** sqlite3_create_function_v2().
  168242. */
  168243. struct RtreeGeomCallback {
  168244. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  168245. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  168246. void (*xDestructor)(void*);
  168247. void *pContext;
  168248. };
  168249. /*
  168250. ** An instance of this structure (in the form of a BLOB) is returned by
  168251. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  168252. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  168253. ** operand to the MATCH operator of an R-Tree.
  168254. */
  168255. struct RtreeMatchArg {
  168256. u32 iSize; /* Size of this object */
  168257. RtreeGeomCallback cb; /* Info about the callback functions */
  168258. int nParam; /* Number of parameters to the SQL function */
  168259. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  168260. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  168261. };
  168262. #ifndef MAX
  168263. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  168264. #endif
  168265. #ifndef MIN
  168266. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  168267. #endif
  168268. /* What version of GCC is being used. 0 means GCC is not being used .
  168269. ** Note that the GCC_VERSION macro will also be set correctly when using
  168270. ** clang, since clang works hard to be gcc compatible. So the gcc
  168271. ** optimizations will also work when compiling with clang.
  168272. */
  168273. #ifndef GCC_VERSION
  168274. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  168275. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  168276. #else
  168277. # define GCC_VERSION 0
  168278. #endif
  168279. #endif
  168280. /* The testcase() macro should already be defined in the amalgamation. If
  168281. ** it is not, make it a no-op.
  168282. */
  168283. #ifndef SQLITE_AMALGAMATION
  168284. # define testcase(X)
  168285. #endif
  168286. /*
  168287. ** Macros to determine whether the machine is big or little endian,
  168288. ** and whether or not that determination is run-time or compile-time.
  168289. **
  168290. ** For best performance, an attempt is made to guess at the byte-order
  168291. ** using C-preprocessor macros. If that is unsuccessful, or if
  168292. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  168293. ** at run-time.
  168294. */
  168295. #ifndef SQLITE_BYTEORDER
  168296. #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  168297. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  168298. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  168299. defined(__arm__)
  168300. # define SQLITE_BYTEORDER 1234
  168301. #elif defined(sparc) || defined(__ppc__)
  168302. # define SQLITE_BYTEORDER 4321
  168303. #else
  168304. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  168305. #endif
  168306. #endif
  168307. /* What version of MSVC is being used. 0 means MSVC is not being used */
  168308. #ifndef MSVC_VERSION
  168309. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  168310. # define MSVC_VERSION _MSC_VER
  168311. #else
  168312. # define MSVC_VERSION 0
  168313. #endif
  168314. #endif
  168315. /*
  168316. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  168317. ** 64 bit integer. The deserialized value is returned.
  168318. */
  168319. static int readInt16(u8 *p){
  168320. return (p[0]<<8) + p[1];
  168321. }
  168322. static void readCoord(u8 *p, RtreeCoord *pCoord){
  168323. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  168324. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  168325. pCoord->u = _byteswap_ulong(*(u32*)p);
  168326. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  168327. pCoord->u = __builtin_bswap32(*(u32*)p);
  168328. #elif SQLITE_BYTEORDER==4321
  168329. pCoord->u = *(u32*)p;
  168330. #else
  168331. pCoord->u = (
  168332. (((u32)p[0]) << 24) +
  168333. (((u32)p[1]) << 16) +
  168334. (((u32)p[2]) << 8) +
  168335. (((u32)p[3]) << 0)
  168336. );
  168337. #endif
  168338. }
  168339. static i64 readInt64(u8 *p){
  168340. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  168341. u64 x;
  168342. memcpy(&x, p, 8);
  168343. return (i64)_byteswap_uint64(x);
  168344. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  168345. u64 x;
  168346. memcpy(&x, p, 8);
  168347. return (i64)__builtin_bswap64(x);
  168348. #elif SQLITE_BYTEORDER==4321
  168349. i64 x;
  168350. memcpy(&x, p, 8);
  168351. return x;
  168352. #else
  168353. return (i64)(
  168354. (((u64)p[0]) << 56) +
  168355. (((u64)p[1]) << 48) +
  168356. (((u64)p[2]) << 40) +
  168357. (((u64)p[3]) << 32) +
  168358. (((u64)p[4]) << 24) +
  168359. (((u64)p[5]) << 16) +
  168360. (((u64)p[6]) << 8) +
  168361. (((u64)p[7]) << 0)
  168362. );
  168363. #endif
  168364. }
  168365. /*
  168366. ** Functions to serialize a 16 bit integer, 32 bit real number and
  168367. ** 64 bit integer. The value returned is the number of bytes written
  168368. ** to the argument buffer (always 2, 4 and 8 respectively).
  168369. */
  168370. static void writeInt16(u8 *p, int i){
  168371. p[0] = (i>> 8)&0xFF;
  168372. p[1] = (i>> 0)&0xFF;
  168373. }
  168374. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  168375. u32 i;
  168376. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  168377. assert( sizeof(RtreeCoord)==4 );
  168378. assert( sizeof(u32)==4 );
  168379. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  168380. i = __builtin_bswap32(pCoord->u);
  168381. memcpy(p, &i, 4);
  168382. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  168383. i = _byteswap_ulong(pCoord->u);
  168384. memcpy(p, &i, 4);
  168385. #elif SQLITE_BYTEORDER==4321
  168386. i = pCoord->u;
  168387. memcpy(p, &i, 4);
  168388. #else
  168389. i = pCoord->u;
  168390. p[0] = (i>>24)&0xFF;
  168391. p[1] = (i>>16)&0xFF;
  168392. p[2] = (i>> 8)&0xFF;
  168393. p[3] = (i>> 0)&0xFF;
  168394. #endif
  168395. return 4;
  168396. }
  168397. static int writeInt64(u8 *p, i64 i){
  168398. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  168399. i = (i64)__builtin_bswap64((u64)i);
  168400. memcpy(p, &i, 8);
  168401. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  168402. i = (i64)_byteswap_uint64((u64)i);
  168403. memcpy(p, &i, 8);
  168404. #elif SQLITE_BYTEORDER==4321
  168405. memcpy(p, &i, 8);
  168406. #else
  168407. p[0] = (i>>56)&0xFF;
  168408. p[1] = (i>>48)&0xFF;
  168409. p[2] = (i>>40)&0xFF;
  168410. p[3] = (i>>32)&0xFF;
  168411. p[4] = (i>>24)&0xFF;
  168412. p[5] = (i>>16)&0xFF;
  168413. p[6] = (i>> 8)&0xFF;
  168414. p[7] = (i>> 0)&0xFF;
  168415. #endif
  168416. return 8;
  168417. }
  168418. /*
  168419. ** Increment the reference count of node p.
  168420. */
  168421. static void nodeReference(RtreeNode *p){
  168422. if( p ){
  168423. assert( p->nRef>0 );
  168424. p->nRef++;
  168425. }
  168426. }
  168427. /*
  168428. ** Clear the content of node p (set all bytes to 0x00).
  168429. */
  168430. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  168431. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  168432. p->isDirty = 1;
  168433. }
  168434. /*
  168435. ** Given a node number iNode, return the corresponding key to use
  168436. ** in the Rtree.aHash table.
  168437. */
  168438. static int nodeHash(i64 iNode){
  168439. return iNode % HASHSIZE;
  168440. }
  168441. /*
  168442. ** Search the node hash table for node iNode. If found, return a pointer
  168443. ** to it. Otherwise, return 0.
  168444. */
  168445. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  168446. RtreeNode *p;
  168447. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  168448. return p;
  168449. }
  168450. /*
  168451. ** Add node pNode to the node hash table.
  168452. */
  168453. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  168454. int iHash;
  168455. assert( pNode->pNext==0 );
  168456. iHash = nodeHash(pNode->iNode);
  168457. pNode->pNext = pRtree->aHash[iHash];
  168458. pRtree->aHash[iHash] = pNode;
  168459. }
  168460. /*
  168461. ** Remove node pNode from the node hash table.
  168462. */
  168463. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  168464. RtreeNode **pp;
  168465. if( pNode->iNode!=0 ){
  168466. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  168467. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  168468. *pp = pNode->pNext;
  168469. pNode->pNext = 0;
  168470. }
  168471. }
  168472. /*
  168473. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  168474. ** indicating that node has not yet been assigned a node number. It is
  168475. ** assigned a node number when nodeWrite() is called to write the
  168476. ** node contents out to the database.
  168477. */
  168478. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  168479. RtreeNode *pNode;
  168480. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  168481. if( pNode ){
  168482. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  168483. pNode->zData = (u8 *)&pNode[1];
  168484. pNode->nRef = 1;
  168485. pRtree->nNodeRef++;
  168486. pNode->pParent = pParent;
  168487. pNode->isDirty = 1;
  168488. nodeReference(pParent);
  168489. }
  168490. return pNode;
  168491. }
  168492. /*
  168493. ** Clear the Rtree.pNodeBlob object
  168494. */
  168495. static void nodeBlobReset(Rtree *pRtree){
  168496. if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
  168497. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  168498. pRtree->pNodeBlob = 0;
  168499. sqlite3_blob_close(pBlob);
  168500. }
  168501. }
  168502. /*
  168503. ** Obtain a reference to an r-tree node.
  168504. */
  168505. static int nodeAcquire(
  168506. Rtree *pRtree, /* R-tree structure */
  168507. i64 iNode, /* Node number to load */
  168508. RtreeNode *pParent, /* Either the parent node or NULL */
  168509. RtreeNode **ppNode /* OUT: Acquired node */
  168510. ){
  168511. int rc = SQLITE_OK;
  168512. RtreeNode *pNode = 0;
  168513. /* Check if the requested node is already in the hash table. If so,
  168514. ** increase its reference count and return it.
  168515. */
  168516. if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
  168517. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  168518. if( pParent && !pNode->pParent ){
  168519. pParent->nRef++;
  168520. pNode->pParent = pParent;
  168521. }
  168522. pNode->nRef++;
  168523. *ppNode = pNode;
  168524. return SQLITE_OK;
  168525. }
  168526. if( pRtree->pNodeBlob ){
  168527. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  168528. pRtree->pNodeBlob = 0;
  168529. rc = sqlite3_blob_reopen(pBlob, iNode);
  168530. pRtree->pNodeBlob = pBlob;
  168531. if( rc ){
  168532. nodeBlobReset(pRtree);
  168533. if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
  168534. }
  168535. }
  168536. if( pRtree->pNodeBlob==0 ){
  168537. char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
  168538. if( zTab==0 ) return SQLITE_NOMEM;
  168539. rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
  168540. &pRtree->pNodeBlob);
  168541. sqlite3_free(zTab);
  168542. }
  168543. if( rc ){
  168544. nodeBlobReset(pRtree);
  168545. *ppNode = 0;
  168546. /* If unable to open an sqlite3_blob on the desired row, that can only
  168547. ** be because the shadow tables hold erroneous data. */
  168548. if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB;
  168549. }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
  168550. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  168551. if( !pNode ){
  168552. rc = SQLITE_NOMEM;
  168553. }else{
  168554. pNode->pParent = pParent;
  168555. pNode->zData = (u8 *)&pNode[1];
  168556. pNode->nRef = 1;
  168557. pRtree->nNodeRef++;
  168558. pNode->iNode = iNode;
  168559. pNode->isDirty = 0;
  168560. pNode->pNext = 0;
  168561. rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
  168562. pRtree->iNodeSize, 0);
  168563. nodeReference(pParent);
  168564. }
  168565. }
  168566. /* If the root node was just loaded, set pRtree->iDepth to the height
  168567. ** of the r-tree structure. A height of zero means all data is stored on
  168568. ** the root node. A height of one means the children of the root node
  168569. ** are the leaves, and so on. If the depth as specified on the root node
  168570. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  168571. */
  168572. if( pNode && iNode==1 ){
  168573. pRtree->iDepth = readInt16(pNode->zData);
  168574. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  168575. rc = SQLITE_CORRUPT_VTAB;
  168576. }
  168577. }
  168578. /* If no error has occurred so far, check if the "number of entries"
  168579. ** field on the node is too large. If so, set the return code to
  168580. ** SQLITE_CORRUPT_VTAB.
  168581. */
  168582. if( pNode && rc==SQLITE_OK ){
  168583. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  168584. rc = SQLITE_CORRUPT_VTAB;
  168585. }
  168586. }
  168587. if( rc==SQLITE_OK ){
  168588. if( pNode!=0 ){
  168589. nodeHashInsert(pRtree, pNode);
  168590. }else{
  168591. rc = SQLITE_CORRUPT_VTAB;
  168592. }
  168593. *ppNode = pNode;
  168594. }else{
  168595. if( pNode ){
  168596. pRtree->nNodeRef--;
  168597. sqlite3_free(pNode);
  168598. }
  168599. *ppNode = 0;
  168600. }
  168601. return rc;
  168602. }
  168603. /*
  168604. ** Overwrite cell iCell of node pNode with the contents of pCell.
  168605. */
  168606. static void nodeOverwriteCell(
  168607. Rtree *pRtree, /* The overall R-Tree */
  168608. RtreeNode *pNode, /* The node into which the cell is to be written */
  168609. RtreeCell *pCell, /* The cell to write */
  168610. int iCell /* Index into pNode into which pCell is written */
  168611. ){
  168612. int ii;
  168613. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  168614. p += writeInt64(p, pCell->iRowid);
  168615. for(ii=0; ii<pRtree->nDim2; ii++){
  168616. p += writeCoord(p, &pCell->aCoord[ii]);
  168617. }
  168618. pNode->isDirty = 1;
  168619. }
  168620. /*
  168621. ** Remove the cell with index iCell from node pNode.
  168622. */
  168623. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  168624. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  168625. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  168626. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  168627. memmove(pDst, pSrc, nByte);
  168628. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  168629. pNode->isDirty = 1;
  168630. }
  168631. /*
  168632. ** Insert the contents of cell pCell into node pNode. If the insert
  168633. ** is successful, return SQLITE_OK.
  168634. **
  168635. ** If there is not enough free space in pNode, return SQLITE_FULL.
  168636. */
  168637. static int nodeInsertCell(
  168638. Rtree *pRtree, /* The overall R-Tree */
  168639. RtreeNode *pNode, /* Write new cell into this node */
  168640. RtreeCell *pCell /* The cell to be inserted */
  168641. ){
  168642. int nCell; /* Current number of cells in pNode */
  168643. int nMaxCell; /* Maximum number of cells for pNode */
  168644. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  168645. nCell = NCELL(pNode);
  168646. assert( nCell<=nMaxCell );
  168647. if( nCell<nMaxCell ){
  168648. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  168649. writeInt16(&pNode->zData[2], nCell+1);
  168650. pNode->isDirty = 1;
  168651. }
  168652. return (nCell==nMaxCell);
  168653. }
  168654. /*
  168655. ** If the node is dirty, write it out to the database.
  168656. */
  168657. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  168658. int rc = SQLITE_OK;
  168659. if( pNode->isDirty ){
  168660. sqlite3_stmt *p = pRtree->pWriteNode;
  168661. if( pNode->iNode ){
  168662. sqlite3_bind_int64(p, 1, pNode->iNode);
  168663. }else{
  168664. sqlite3_bind_null(p, 1);
  168665. }
  168666. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  168667. sqlite3_step(p);
  168668. pNode->isDirty = 0;
  168669. rc = sqlite3_reset(p);
  168670. sqlite3_bind_null(p, 2);
  168671. if( pNode->iNode==0 && rc==SQLITE_OK ){
  168672. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  168673. nodeHashInsert(pRtree, pNode);
  168674. }
  168675. }
  168676. return rc;
  168677. }
  168678. /*
  168679. ** Release a reference to a node. If the node is dirty and the reference
  168680. ** count drops to zero, the node data is written to the database.
  168681. */
  168682. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  168683. int rc = SQLITE_OK;
  168684. if( pNode ){
  168685. assert( pNode->nRef>0 );
  168686. assert( pRtree->nNodeRef>0 );
  168687. pNode->nRef--;
  168688. if( pNode->nRef==0 ){
  168689. pRtree->nNodeRef--;
  168690. if( pNode->iNode==1 ){
  168691. pRtree->iDepth = -1;
  168692. }
  168693. if( pNode->pParent ){
  168694. rc = nodeRelease(pRtree, pNode->pParent);
  168695. }
  168696. if( rc==SQLITE_OK ){
  168697. rc = nodeWrite(pRtree, pNode);
  168698. }
  168699. nodeHashDelete(pRtree, pNode);
  168700. sqlite3_free(pNode);
  168701. }
  168702. }
  168703. return rc;
  168704. }
  168705. /*
  168706. ** Return the 64-bit integer value associated with cell iCell of
  168707. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  168708. ** an internal node, then the 64-bit integer is a child page number.
  168709. */
  168710. static i64 nodeGetRowid(
  168711. Rtree *pRtree, /* The overall R-Tree */
  168712. RtreeNode *pNode, /* The node from which to extract the ID */
  168713. int iCell /* The cell index from which to extract the ID */
  168714. ){
  168715. assert( iCell<NCELL(pNode) );
  168716. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  168717. }
  168718. /*
  168719. ** Return coordinate iCoord from cell iCell in node pNode.
  168720. */
  168721. static void nodeGetCoord(
  168722. Rtree *pRtree, /* The overall R-Tree */
  168723. RtreeNode *pNode, /* The node from which to extract a coordinate */
  168724. int iCell, /* The index of the cell within the node */
  168725. int iCoord, /* Which coordinate to extract */
  168726. RtreeCoord *pCoord /* OUT: Space to write result to */
  168727. ){
  168728. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  168729. }
  168730. /*
  168731. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  168732. ** to by pCell with the results.
  168733. */
  168734. static void nodeGetCell(
  168735. Rtree *pRtree, /* The overall R-Tree */
  168736. RtreeNode *pNode, /* The node containing the cell to be read */
  168737. int iCell, /* Index of the cell within the node */
  168738. RtreeCell *pCell /* OUT: Write the cell contents here */
  168739. ){
  168740. u8 *pData;
  168741. RtreeCoord *pCoord;
  168742. int ii = 0;
  168743. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  168744. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  168745. pCoord = pCell->aCoord;
  168746. do{
  168747. readCoord(pData, &pCoord[ii]);
  168748. readCoord(pData+4, &pCoord[ii+1]);
  168749. pData += 8;
  168750. ii += 2;
  168751. }while( ii<pRtree->nDim2 );
  168752. }
  168753. /* Forward declaration for the function that does the work of
  168754. ** the virtual table module xCreate() and xConnect() methods.
  168755. */
  168756. static int rtreeInit(
  168757. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  168758. );
  168759. /*
  168760. ** Rtree virtual table module xCreate method.
  168761. */
  168762. static int rtreeCreate(
  168763. sqlite3 *db,
  168764. void *pAux,
  168765. int argc, const char *const*argv,
  168766. sqlite3_vtab **ppVtab,
  168767. char **pzErr
  168768. ){
  168769. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  168770. }
  168771. /*
  168772. ** Rtree virtual table module xConnect method.
  168773. */
  168774. static int rtreeConnect(
  168775. sqlite3 *db,
  168776. void *pAux,
  168777. int argc, const char *const*argv,
  168778. sqlite3_vtab **ppVtab,
  168779. char **pzErr
  168780. ){
  168781. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  168782. }
  168783. /*
  168784. ** Increment the r-tree reference count.
  168785. */
  168786. static void rtreeReference(Rtree *pRtree){
  168787. pRtree->nBusy++;
  168788. }
  168789. /*
  168790. ** Decrement the r-tree reference count. When the reference count reaches
  168791. ** zero the structure is deleted.
  168792. */
  168793. static void rtreeRelease(Rtree *pRtree){
  168794. pRtree->nBusy--;
  168795. if( pRtree->nBusy==0 ){
  168796. pRtree->inWrTrans = 0;
  168797. assert( pRtree->nCursor==0 );
  168798. nodeBlobReset(pRtree);
  168799. assert( pRtree->nNodeRef==0 );
  168800. sqlite3_finalize(pRtree->pWriteNode);
  168801. sqlite3_finalize(pRtree->pDeleteNode);
  168802. sqlite3_finalize(pRtree->pReadRowid);
  168803. sqlite3_finalize(pRtree->pWriteRowid);
  168804. sqlite3_finalize(pRtree->pDeleteRowid);
  168805. sqlite3_finalize(pRtree->pReadParent);
  168806. sqlite3_finalize(pRtree->pWriteParent);
  168807. sqlite3_finalize(pRtree->pDeleteParent);
  168808. sqlite3_finalize(pRtree->pWriteAux);
  168809. sqlite3_free(pRtree->zReadAuxSql);
  168810. sqlite3_free(pRtree);
  168811. }
  168812. }
  168813. /*
  168814. ** Rtree virtual table module xDisconnect method.
  168815. */
  168816. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  168817. rtreeRelease((Rtree *)pVtab);
  168818. return SQLITE_OK;
  168819. }
  168820. /*
  168821. ** Rtree virtual table module xDestroy method.
  168822. */
  168823. static int rtreeDestroy(sqlite3_vtab *pVtab){
  168824. Rtree *pRtree = (Rtree *)pVtab;
  168825. int rc;
  168826. char *zCreate = sqlite3_mprintf(
  168827. "DROP TABLE '%q'.'%q_node';"
  168828. "DROP TABLE '%q'.'%q_rowid';"
  168829. "DROP TABLE '%q'.'%q_parent';",
  168830. pRtree->zDb, pRtree->zName,
  168831. pRtree->zDb, pRtree->zName,
  168832. pRtree->zDb, pRtree->zName
  168833. );
  168834. if( !zCreate ){
  168835. rc = SQLITE_NOMEM;
  168836. }else{
  168837. nodeBlobReset(pRtree);
  168838. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  168839. sqlite3_free(zCreate);
  168840. }
  168841. if( rc==SQLITE_OK ){
  168842. rtreeRelease(pRtree);
  168843. }
  168844. return rc;
  168845. }
  168846. /*
  168847. ** Rtree virtual table module xOpen method.
  168848. */
  168849. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  168850. int rc = SQLITE_NOMEM;
  168851. Rtree *pRtree = (Rtree *)pVTab;
  168852. RtreeCursor *pCsr;
  168853. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  168854. if( pCsr ){
  168855. memset(pCsr, 0, sizeof(RtreeCursor));
  168856. pCsr->base.pVtab = pVTab;
  168857. rc = SQLITE_OK;
  168858. pRtree->nCursor++;
  168859. }
  168860. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  168861. return rc;
  168862. }
  168863. /*
  168864. ** Free the RtreeCursor.aConstraint[] array and its contents.
  168865. */
  168866. static void freeCursorConstraints(RtreeCursor *pCsr){
  168867. if( pCsr->aConstraint ){
  168868. int i; /* Used to iterate through constraint array */
  168869. for(i=0; i<pCsr->nConstraint; i++){
  168870. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  168871. if( pInfo ){
  168872. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  168873. sqlite3_free(pInfo);
  168874. }
  168875. }
  168876. sqlite3_free(pCsr->aConstraint);
  168877. pCsr->aConstraint = 0;
  168878. }
  168879. }
  168880. /*
  168881. ** Rtree virtual table module xClose method.
  168882. */
  168883. static int rtreeClose(sqlite3_vtab_cursor *cur){
  168884. Rtree *pRtree = (Rtree *)(cur->pVtab);
  168885. int ii;
  168886. RtreeCursor *pCsr = (RtreeCursor *)cur;
  168887. assert( pRtree->nCursor>0 );
  168888. freeCursorConstraints(pCsr);
  168889. sqlite3_finalize(pCsr->pReadAux);
  168890. sqlite3_free(pCsr->aPoint);
  168891. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  168892. sqlite3_free(pCsr);
  168893. pRtree->nCursor--;
  168894. nodeBlobReset(pRtree);
  168895. return SQLITE_OK;
  168896. }
  168897. /*
  168898. ** Rtree virtual table module xEof method.
  168899. **
  168900. ** Return non-zero if the cursor does not currently point to a valid
  168901. ** record (i.e if the scan has finished), or zero otherwise.
  168902. */
  168903. static int rtreeEof(sqlite3_vtab_cursor *cur){
  168904. RtreeCursor *pCsr = (RtreeCursor *)cur;
  168905. return pCsr->atEOF;
  168906. }
  168907. /*
  168908. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  168909. ** The on-disk format is big-endian and needs to be converted for little-
  168910. ** endian platforms. The on-disk record stores integer coordinates if
  168911. ** eInt is true and it stores 32-bit floating point records if eInt is
  168912. ** false. a[] is the four bytes of the on-disk record to be decoded.
  168913. ** Store the results in "r".
  168914. **
  168915. ** There are five versions of this macro. The last one is generic. The
  168916. ** other four are various architectures-specific optimizations.
  168917. */
  168918. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  168919. #define RTREE_DECODE_COORD(eInt, a, r) { \
  168920. RtreeCoord c; /* Coordinate decoded */ \
  168921. c.u = _byteswap_ulong(*(u32*)a); \
  168922. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  168923. }
  168924. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  168925. #define RTREE_DECODE_COORD(eInt, a, r) { \
  168926. RtreeCoord c; /* Coordinate decoded */ \
  168927. c.u = __builtin_bswap32(*(u32*)a); \
  168928. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  168929. }
  168930. #elif SQLITE_BYTEORDER==1234
  168931. #define RTREE_DECODE_COORD(eInt, a, r) { \
  168932. RtreeCoord c; /* Coordinate decoded */ \
  168933. memcpy(&c.u,a,4); \
  168934. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  168935. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  168936. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  168937. }
  168938. #elif SQLITE_BYTEORDER==4321
  168939. #define RTREE_DECODE_COORD(eInt, a, r) { \
  168940. RtreeCoord c; /* Coordinate decoded */ \
  168941. memcpy(&c.u,a,4); \
  168942. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  168943. }
  168944. #else
  168945. #define RTREE_DECODE_COORD(eInt, a, r) { \
  168946. RtreeCoord c; /* Coordinate decoded */ \
  168947. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  168948. +((u32)a[2]<<8) + a[3]; \
  168949. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  168950. }
  168951. #endif
  168952. /*
  168953. ** Check the RTree node or entry given by pCellData and p against the MATCH
  168954. ** constraint pConstraint.
  168955. */
  168956. static int rtreeCallbackConstraint(
  168957. RtreeConstraint *pConstraint, /* The constraint to test */
  168958. int eInt, /* True if RTree holding integer coordinates */
  168959. u8 *pCellData, /* Raw cell content */
  168960. RtreeSearchPoint *pSearch, /* Container of this cell */
  168961. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  168962. int *peWithin /* OUT: visibility of the cell */
  168963. ){
  168964. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  168965. int nCoord = pInfo->nCoord; /* No. of coordinates */
  168966. int rc; /* Callback return code */
  168967. RtreeCoord c; /* Translator union */
  168968. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  168969. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  168970. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  168971. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  168972. pInfo->iRowid = readInt64(pCellData);
  168973. }
  168974. pCellData += 8;
  168975. #ifndef SQLITE_RTREE_INT_ONLY
  168976. if( eInt==0 ){
  168977. switch( nCoord ){
  168978. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
  168979. readCoord(pCellData+32, &c); aCoord[8] = c.f;
  168980. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
  168981. readCoord(pCellData+24, &c); aCoord[6] = c.f;
  168982. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
  168983. readCoord(pCellData+16, &c); aCoord[4] = c.f;
  168984. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
  168985. readCoord(pCellData+8, &c); aCoord[2] = c.f;
  168986. default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
  168987. readCoord(pCellData, &c); aCoord[0] = c.f;
  168988. }
  168989. }else
  168990. #endif
  168991. {
  168992. switch( nCoord ){
  168993. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
  168994. readCoord(pCellData+32, &c); aCoord[8] = c.i;
  168995. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
  168996. readCoord(pCellData+24, &c); aCoord[6] = c.i;
  168997. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
  168998. readCoord(pCellData+16, &c); aCoord[4] = c.i;
  168999. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
  169000. readCoord(pCellData+8, &c); aCoord[2] = c.i;
  169001. default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
  169002. readCoord(pCellData, &c); aCoord[0] = c.i;
  169003. }
  169004. }
  169005. if( pConstraint->op==RTREE_MATCH ){
  169006. int eWithin = 0;
  169007. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  169008. nCoord, aCoord, &eWithin);
  169009. if( eWithin==0 ) *peWithin = NOT_WITHIN;
  169010. *prScore = RTREE_ZERO;
  169011. }else{
  169012. pInfo->aCoord = aCoord;
  169013. pInfo->iLevel = pSearch->iLevel - 1;
  169014. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  169015. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  169016. rc = pConstraint->u.xQueryFunc(pInfo);
  169017. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  169018. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  169019. *prScore = pInfo->rScore;
  169020. }
  169021. }
  169022. return rc;
  169023. }
  169024. /*
  169025. ** Check the internal RTree node given by pCellData against constraint p.
  169026. ** If this constraint cannot be satisfied by any child within the node,
  169027. ** set *peWithin to NOT_WITHIN.
  169028. */
  169029. static void rtreeNonleafConstraint(
  169030. RtreeConstraint *p, /* The constraint to test */
  169031. int eInt, /* True if RTree holds integer coordinates */
  169032. u8 *pCellData, /* Raw cell content as appears on disk */
  169033. int *peWithin /* Adjust downward, as appropriate */
  169034. ){
  169035. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  169036. /* p->iCoord might point to either a lower or upper bound coordinate
  169037. ** in a coordinate pair. But make pCellData point to the lower bound.
  169038. */
  169039. pCellData += 8 + 4*(p->iCoord&0xfe);
  169040. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  169041. || p->op==RTREE_GT || p->op==RTREE_EQ );
  169042. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  169043. switch( p->op ){
  169044. case RTREE_LE:
  169045. case RTREE_LT:
  169046. case RTREE_EQ:
  169047. RTREE_DECODE_COORD(eInt, pCellData, val);
  169048. /* val now holds the lower bound of the coordinate pair */
  169049. if( p->u.rValue>=val ) return;
  169050. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  169051. /* Fall through for the RTREE_EQ case */
  169052. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  169053. pCellData += 4;
  169054. RTREE_DECODE_COORD(eInt, pCellData, val);
  169055. /* val now holds the upper bound of the coordinate pair */
  169056. if( p->u.rValue<=val ) return;
  169057. }
  169058. *peWithin = NOT_WITHIN;
  169059. }
  169060. /*
  169061. ** Check the leaf RTree cell given by pCellData against constraint p.
  169062. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  169063. ** If the constraint is satisfied, leave *peWithin unchanged.
  169064. **
  169065. ** The constraint is of the form: xN op $val
  169066. **
  169067. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  169068. ** pCellData. $val is given by p->u.rValue.
  169069. */
  169070. static void rtreeLeafConstraint(
  169071. RtreeConstraint *p, /* The constraint to test */
  169072. int eInt, /* True if RTree holds integer coordinates */
  169073. u8 *pCellData, /* Raw cell content as appears on disk */
  169074. int *peWithin /* Adjust downward, as appropriate */
  169075. ){
  169076. RtreeDValue xN; /* Coordinate value converted to a double */
  169077. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  169078. || p->op==RTREE_GT || p->op==RTREE_EQ );
  169079. pCellData += 8 + p->iCoord*4;
  169080. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  169081. RTREE_DECODE_COORD(eInt, pCellData, xN);
  169082. switch( p->op ){
  169083. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  169084. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  169085. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  169086. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  169087. default: if( xN == p->u.rValue ) return; break;
  169088. }
  169089. *peWithin = NOT_WITHIN;
  169090. }
  169091. /*
  169092. ** One of the cells in node pNode is guaranteed to have a 64-bit
  169093. ** integer value equal to iRowid. Return the index of this cell.
  169094. */
  169095. static int nodeRowidIndex(
  169096. Rtree *pRtree,
  169097. RtreeNode *pNode,
  169098. i64 iRowid,
  169099. int *piIndex
  169100. ){
  169101. int ii;
  169102. int nCell = NCELL(pNode);
  169103. assert( nCell<200 );
  169104. for(ii=0; ii<nCell; ii++){
  169105. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  169106. *piIndex = ii;
  169107. return SQLITE_OK;
  169108. }
  169109. }
  169110. return SQLITE_CORRUPT_VTAB;
  169111. }
  169112. /*
  169113. ** Return the index of the cell containing a pointer to node pNode
  169114. ** in its parent. If pNode is the root node, return -1.
  169115. */
  169116. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  169117. RtreeNode *pParent = pNode->pParent;
  169118. if( pParent ){
  169119. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  169120. }
  169121. *piIndex = -1;
  169122. return SQLITE_OK;
  169123. }
  169124. /*
  169125. ** Compare two search points. Return negative, zero, or positive if the first
  169126. ** is less than, equal to, or greater than the second.
  169127. **
  169128. ** The rScore is the primary key. Smaller rScore values come first.
  169129. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  169130. ** iLevel values coming first. In this way, if rScore is the same for all
  169131. ** SearchPoints, then iLevel becomes the deciding factor and the result
  169132. ** is a depth-first search, which is the desired default behavior.
  169133. */
  169134. static int rtreeSearchPointCompare(
  169135. const RtreeSearchPoint *pA,
  169136. const RtreeSearchPoint *pB
  169137. ){
  169138. if( pA->rScore<pB->rScore ) return -1;
  169139. if( pA->rScore>pB->rScore ) return +1;
  169140. if( pA->iLevel<pB->iLevel ) return -1;
  169141. if( pA->iLevel>pB->iLevel ) return +1;
  169142. return 0;
  169143. }
  169144. /*
  169145. ** Interchange two search points in a cursor.
  169146. */
  169147. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  169148. RtreeSearchPoint t = p->aPoint[i];
  169149. assert( i<j );
  169150. p->aPoint[i] = p->aPoint[j];
  169151. p->aPoint[j] = t;
  169152. i++; j++;
  169153. if( i<RTREE_CACHE_SZ ){
  169154. if( j>=RTREE_CACHE_SZ ){
  169155. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  169156. p->aNode[i] = 0;
  169157. }else{
  169158. RtreeNode *pTemp = p->aNode[i];
  169159. p->aNode[i] = p->aNode[j];
  169160. p->aNode[j] = pTemp;
  169161. }
  169162. }
  169163. }
  169164. /*
  169165. ** Return the search point with the lowest current score.
  169166. */
  169167. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  169168. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  169169. }
  169170. /*
  169171. ** Get the RtreeNode for the search point with the lowest score.
  169172. */
  169173. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  169174. sqlite3_int64 id;
  169175. int ii = 1 - pCur->bPoint;
  169176. assert( ii==0 || ii==1 );
  169177. assert( pCur->bPoint || pCur->nPoint );
  169178. if( pCur->aNode[ii]==0 ){
  169179. assert( pRC!=0 );
  169180. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  169181. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  169182. }
  169183. return pCur->aNode[ii];
  169184. }
  169185. /*
  169186. ** Push a new element onto the priority queue
  169187. */
  169188. static RtreeSearchPoint *rtreeEnqueue(
  169189. RtreeCursor *pCur, /* The cursor */
  169190. RtreeDValue rScore, /* Score for the new search point */
  169191. u8 iLevel /* Level for the new search point */
  169192. ){
  169193. int i, j;
  169194. RtreeSearchPoint *pNew;
  169195. if( pCur->nPoint>=pCur->nPointAlloc ){
  169196. int nNew = pCur->nPointAlloc*2 + 8;
  169197. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  169198. if( pNew==0 ) return 0;
  169199. pCur->aPoint = pNew;
  169200. pCur->nPointAlloc = nNew;
  169201. }
  169202. i = pCur->nPoint++;
  169203. pNew = pCur->aPoint + i;
  169204. pNew->rScore = rScore;
  169205. pNew->iLevel = iLevel;
  169206. assert( iLevel<=RTREE_MAX_DEPTH );
  169207. while( i>0 ){
  169208. RtreeSearchPoint *pParent;
  169209. j = (i-1)/2;
  169210. pParent = pCur->aPoint + j;
  169211. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  169212. rtreeSearchPointSwap(pCur, j, i);
  169213. i = j;
  169214. pNew = pParent;
  169215. }
  169216. return pNew;
  169217. }
  169218. /*
  169219. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  169220. ** NULL if malloc fails.
  169221. */
  169222. static RtreeSearchPoint *rtreeSearchPointNew(
  169223. RtreeCursor *pCur, /* The cursor */
  169224. RtreeDValue rScore, /* Score for the new search point */
  169225. u8 iLevel /* Level for the new search point */
  169226. ){
  169227. RtreeSearchPoint *pNew, *pFirst;
  169228. pFirst = rtreeSearchPointFirst(pCur);
  169229. pCur->anQueue[iLevel]++;
  169230. if( pFirst==0
  169231. || pFirst->rScore>rScore
  169232. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  169233. ){
  169234. if( pCur->bPoint ){
  169235. int ii;
  169236. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  169237. if( pNew==0 ) return 0;
  169238. ii = (int)(pNew - pCur->aPoint) + 1;
  169239. if( ii<RTREE_CACHE_SZ ){
  169240. assert( pCur->aNode[ii]==0 );
  169241. pCur->aNode[ii] = pCur->aNode[0];
  169242. }else{
  169243. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  169244. }
  169245. pCur->aNode[0] = 0;
  169246. *pNew = pCur->sPoint;
  169247. }
  169248. pCur->sPoint.rScore = rScore;
  169249. pCur->sPoint.iLevel = iLevel;
  169250. pCur->bPoint = 1;
  169251. return &pCur->sPoint;
  169252. }else{
  169253. return rtreeEnqueue(pCur, rScore, iLevel);
  169254. }
  169255. }
  169256. #if 0
  169257. /* Tracing routines for the RtreeSearchPoint queue */
  169258. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  169259. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  169260. printf(" %d.%05lld.%02d %g %d",
  169261. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  169262. );
  169263. idx++;
  169264. if( idx<RTREE_CACHE_SZ ){
  169265. printf(" %p\n", pCur->aNode[idx]);
  169266. }else{
  169267. printf("\n");
  169268. }
  169269. }
  169270. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  169271. int ii;
  169272. printf("=== %9s ", zPrefix);
  169273. if( pCur->bPoint ){
  169274. tracePoint(&pCur->sPoint, -1, pCur);
  169275. }
  169276. for(ii=0; ii<pCur->nPoint; ii++){
  169277. if( ii>0 || pCur->bPoint ) printf(" ");
  169278. tracePoint(&pCur->aPoint[ii], ii, pCur);
  169279. }
  169280. }
  169281. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  169282. #else
  169283. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  169284. #endif
  169285. /* Remove the search point with the lowest current score.
  169286. */
  169287. static void rtreeSearchPointPop(RtreeCursor *p){
  169288. int i, j, k, n;
  169289. i = 1 - p->bPoint;
  169290. assert( i==0 || i==1 );
  169291. if( p->aNode[i] ){
  169292. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  169293. p->aNode[i] = 0;
  169294. }
  169295. if( p->bPoint ){
  169296. p->anQueue[p->sPoint.iLevel]--;
  169297. p->bPoint = 0;
  169298. }else if( p->nPoint ){
  169299. p->anQueue[p->aPoint[0].iLevel]--;
  169300. n = --p->nPoint;
  169301. p->aPoint[0] = p->aPoint[n];
  169302. if( n<RTREE_CACHE_SZ-1 ){
  169303. p->aNode[1] = p->aNode[n+1];
  169304. p->aNode[n+1] = 0;
  169305. }
  169306. i = 0;
  169307. while( (j = i*2+1)<n ){
  169308. k = j+1;
  169309. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  169310. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  169311. rtreeSearchPointSwap(p, i, k);
  169312. i = k;
  169313. }else{
  169314. break;
  169315. }
  169316. }else{
  169317. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  169318. rtreeSearchPointSwap(p, i, j);
  169319. i = j;
  169320. }else{
  169321. break;
  169322. }
  169323. }
  169324. }
  169325. }
  169326. }
  169327. /*
  169328. ** Continue the search on cursor pCur until the front of the queue
  169329. ** contains an entry suitable for returning as a result-set row,
  169330. ** or until the RtreeSearchPoint queue is empty, indicating that the
  169331. ** query has completed.
  169332. */
  169333. static int rtreeStepToLeaf(RtreeCursor *pCur){
  169334. RtreeSearchPoint *p;
  169335. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  169336. RtreeNode *pNode;
  169337. int eWithin;
  169338. int rc = SQLITE_OK;
  169339. int nCell;
  169340. int nConstraint = pCur->nConstraint;
  169341. int ii;
  169342. int eInt;
  169343. RtreeSearchPoint x;
  169344. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  169345. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  169346. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  169347. if( rc ) return rc;
  169348. nCell = NCELL(pNode);
  169349. assert( nCell<200 );
  169350. while( p->iCell<nCell ){
  169351. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  169352. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  169353. eWithin = FULLY_WITHIN;
  169354. for(ii=0; ii<nConstraint; ii++){
  169355. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  169356. if( pConstraint->op>=RTREE_MATCH ){
  169357. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  169358. &rScore, &eWithin);
  169359. if( rc ) return rc;
  169360. }else if( p->iLevel==1 ){
  169361. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  169362. }else{
  169363. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  169364. }
  169365. if( eWithin==NOT_WITHIN ) break;
  169366. }
  169367. p->iCell++;
  169368. if( eWithin==NOT_WITHIN ) continue;
  169369. x.iLevel = p->iLevel - 1;
  169370. if( x.iLevel ){
  169371. x.id = readInt64(pCellData);
  169372. x.iCell = 0;
  169373. }else{
  169374. x.id = p->id;
  169375. x.iCell = p->iCell - 1;
  169376. }
  169377. if( p->iCell>=nCell ){
  169378. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  169379. rtreeSearchPointPop(pCur);
  169380. }
  169381. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  169382. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  169383. if( p==0 ) return SQLITE_NOMEM;
  169384. p->eWithin = (u8)eWithin;
  169385. p->id = x.id;
  169386. p->iCell = x.iCell;
  169387. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  169388. break;
  169389. }
  169390. if( p->iCell>=nCell ){
  169391. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  169392. rtreeSearchPointPop(pCur);
  169393. }
  169394. }
  169395. pCur->atEOF = p==0;
  169396. return SQLITE_OK;
  169397. }
  169398. /*
  169399. ** Rtree virtual table module xNext method.
  169400. */
  169401. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  169402. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  169403. int rc = SQLITE_OK;
  169404. /* Move to the next entry that matches the configured constraints. */
  169405. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  169406. if( pCsr->bAuxValid ){
  169407. pCsr->bAuxValid = 0;
  169408. sqlite3_reset(pCsr->pReadAux);
  169409. }
  169410. rtreeSearchPointPop(pCsr);
  169411. rc = rtreeStepToLeaf(pCsr);
  169412. return rc;
  169413. }
  169414. /*
  169415. ** Rtree virtual table module xRowid method.
  169416. */
  169417. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  169418. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  169419. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  169420. int rc = SQLITE_OK;
  169421. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  169422. if( rc==SQLITE_OK && p ){
  169423. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  169424. }
  169425. return rc;
  169426. }
  169427. /*
  169428. ** Rtree virtual table module xColumn method.
  169429. */
  169430. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  169431. Rtree *pRtree = (Rtree *)cur->pVtab;
  169432. RtreeCursor *pCsr = (RtreeCursor *)cur;
  169433. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  169434. RtreeCoord c;
  169435. int rc = SQLITE_OK;
  169436. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  169437. if( rc ) return rc;
  169438. if( p==0 ) return SQLITE_OK;
  169439. if( i==0 ){
  169440. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  169441. }else if( i<=pRtree->nDim2 ){
  169442. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  169443. #ifndef SQLITE_RTREE_INT_ONLY
  169444. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  169445. sqlite3_result_double(ctx, c.f);
  169446. }else
  169447. #endif
  169448. {
  169449. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  169450. sqlite3_result_int(ctx, c.i);
  169451. }
  169452. }else{
  169453. if( !pCsr->bAuxValid ){
  169454. if( pCsr->pReadAux==0 ){
  169455. rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
  169456. &pCsr->pReadAux, 0);
  169457. if( rc ) return rc;
  169458. }
  169459. sqlite3_bind_int64(pCsr->pReadAux, 1,
  169460. nodeGetRowid(pRtree, pNode, p->iCell));
  169461. rc = sqlite3_step(pCsr->pReadAux);
  169462. if( rc==SQLITE_ROW ){
  169463. pCsr->bAuxValid = 1;
  169464. }else{
  169465. sqlite3_reset(pCsr->pReadAux);
  169466. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  169467. return rc;
  169468. }
  169469. }
  169470. sqlite3_result_value(ctx,
  169471. sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
  169472. }
  169473. return SQLITE_OK;
  169474. }
  169475. /*
  169476. ** Use nodeAcquire() to obtain the leaf node containing the record with
  169477. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  169478. ** return SQLITE_OK. If there is no such record in the table, set
  169479. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  169480. ** to zero and return an SQLite error code.
  169481. */
  169482. static int findLeafNode(
  169483. Rtree *pRtree, /* RTree to search */
  169484. i64 iRowid, /* The rowid searching for */
  169485. RtreeNode **ppLeaf, /* Write the node here */
  169486. sqlite3_int64 *piNode /* Write the node-id here */
  169487. ){
  169488. int rc;
  169489. *ppLeaf = 0;
  169490. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  169491. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  169492. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  169493. if( piNode ) *piNode = iNode;
  169494. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  169495. sqlite3_reset(pRtree->pReadRowid);
  169496. }else{
  169497. rc = sqlite3_reset(pRtree->pReadRowid);
  169498. }
  169499. return rc;
  169500. }
  169501. /*
  169502. ** This function is called to configure the RtreeConstraint object passed
  169503. ** as the second argument for a MATCH constraint. The value passed as the
  169504. ** first argument to this function is the right-hand operand to the MATCH
  169505. ** operator.
  169506. */
  169507. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  169508. RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
  169509. sqlite3_rtree_query_info *pInfo; /* Callback information */
  169510. pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
  169511. if( pSrc==0 ) return SQLITE_ERROR;
  169512. pInfo = (sqlite3_rtree_query_info*)
  169513. sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
  169514. if( !pInfo ) return SQLITE_NOMEM;
  169515. memset(pInfo, 0, sizeof(*pInfo));
  169516. pBlob = (RtreeMatchArg*)&pInfo[1];
  169517. memcpy(pBlob, pSrc, pSrc->iSize);
  169518. pInfo->pContext = pBlob->cb.pContext;
  169519. pInfo->nParam = pBlob->nParam;
  169520. pInfo->aParam = pBlob->aParam;
  169521. pInfo->apSqlParam = pBlob->apSqlParam;
  169522. if( pBlob->cb.xGeom ){
  169523. pCons->u.xGeom = pBlob->cb.xGeom;
  169524. }else{
  169525. pCons->op = RTREE_QUERY;
  169526. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  169527. }
  169528. pCons->pInfo = pInfo;
  169529. return SQLITE_OK;
  169530. }
  169531. /*
  169532. ** Rtree virtual table module xFilter method.
  169533. */
  169534. static int rtreeFilter(
  169535. sqlite3_vtab_cursor *pVtabCursor,
  169536. int idxNum, const char *idxStr,
  169537. int argc, sqlite3_value **argv
  169538. ){
  169539. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  169540. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  169541. RtreeNode *pRoot = 0;
  169542. int ii;
  169543. int rc = SQLITE_OK;
  169544. int iCell = 0;
  169545. sqlite3_stmt *pStmt;
  169546. rtreeReference(pRtree);
  169547. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  169548. freeCursorConstraints(pCsr);
  169549. sqlite3_free(pCsr->aPoint);
  169550. pStmt = pCsr->pReadAux;
  169551. memset(pCsr, 0, sizeof(RtreeCursor));
  169552. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  169553. pCsr->pReadAux = pStmt;
  169554. pCsr->iStrategy = idxNum;
  169555. if( idxNum==1 ){
  169556. /* Special case - lookup by rowid. */
  169557. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  169558. RtreeSearchPoint *p; /* Search point for the leaf */
  169559. i64 iRowid = sqlite3_value_int64(argv[0]);
  169560. i64 iNode = 0;
  169561. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  169562. if( rc==SQLITE_OK && pLeaf!=0 ){
  169563. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  169564. assert( p!=0 ); /* Always returns pCsr->sPoint */
  169565. pCsr->aNode[0] = pLeaf;
  169566. p->id = iNode;
  169567. p->eWithin = PARTLY_WITHIN;
  169568. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  169569. p->iCell = (u8)iCell;
  169570. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  169571. }else{
  169572. pCsr->atEOF = 1;
  169573. }
  169574. }else{
  169575. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  169576. ** with the configured constraints.
  169577. */
  169578. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  169579. if( rc==SQLITE_OK && argc>0 ){
  169580. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  169581. pCsr->nConstraint = argc;
  169582. if( !pCsr->aConstraint ){
  169583. rc = SQLITE_NOMEM;
  169584. }else{
  169585. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  169586. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  169587. assert( (idxStr==0 && argc==0)
  169588. || (idxStr && (int)strlen(idxStr)==argc*2) );
  169589. for(ii=0; ii<argc; ii++){
  169590. RtreeConstraint *p = &pCsr->aConstraint[ii];
  169591. p->op = idxStr[ii*2];
  169592. p->iCoord = idxStr[ii*2+1]-'0';
  169593. if( p->op>=RTREE_MATCH ){
  169594. /* A MATCH operator. The right-hand-side must be a blob that
  169595. ** can be cast into an RtreeMatchArg object. One created using
  169596. ** an sqlite3_rtree_geometry_callback() SQL user function.
  169597. */
  169598. rc = deserializeGeometry(argv[ii], p);
  169599. if( rc!=SQLITE_OK ){
  169600. break;
  169601. }
  169602. p->pInfo->nCoord = pRtree->nDim2;
  169603. p->pInfo->anQueue = pCsr->anQueue;
  169604. p->pInfo->mxLevel = pRtree->iDepth + 1;
  169605. }else{
  169606. #ifdef SQLITE_RTREE_INT_ONLY
  169607. p->u.rValue = sqlite3_value_int64(argv[ii]);
  169608. #else
  169609. p->u.rValue = sqlite3_value_double(argv[ii]);
  169610. #endif
  169611. }
  169612. }
  169613. }
  169614. }
  169615. if( rc==SQLITE_OK ){
  169616. RtreeSearchPoint *pNew;
  169617. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  169618. if( pNew==0 ) return SQLITE_NOMEM;
  169619. pNew->id = 1;
  169620. pNew->iCell = 0;
  169621. pNew->eWithin = PARTLY_WITHIN;
  169622. assert( pCsr->bPoint==1 );
  169623. pCsr->aNode[0] = pRoot;
  169624. pRoot = 0;
  169625. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  169626. rc = rtreeStepToLeaf(pCsr);
  169627. }
  169628. }
  169629. nodeRelease(pRtree, pRoot);
  169630. rtreeRelease(pRtree);
  169631. return rc;
  169632. }
  169633. /*
  169634. ** Rtree virtual table module xBestIndex method. There are three
  169635. ** table scan strategies to choose from (in order from most to
  169636. ** least desirable):
  169637. **
  169638. ** idxNum idxStr Strategy
  169639. ** ------------------------------------------------
  169640. ** 1 Unused Direct lookup by rowid.
  169641. ** 2 See below R-tree query or full-table scan.
  169642. ** ------------------------------------------------
  169643. **
  169644. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  169645. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  169646. ** constraint used. The first two bytes of idxStr correspond to
  169647. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  169648. ** (argvIndex==1) etc.
  169649. **
  169650. ** The first of each pair of bytes in idxStr identifies the constraint
  169651. ** operator as follows:
  169652. **
  169653. ** Operator Byte Value
  169654. ** ----------------------
  169655. ** = 0x41 ('A')
  169656. ** <= 0x42 ('B')
  169657. ** < 0x43 ('C')
  169658. ** >= 0x44 ('D')
  169659. ** > 0x45 ('E')
  169660. ** MATCH 0x46 ('F')
  169661. ** ----------------------
  169662. **
  169663. ** The second of each pair of bytes identifies the coordinate column
  169664. ** to which the constraint applies. The leftmost coordinate column
  169665. ** is 'a', the second from the left 'b' etc.
  169666. */
  169667. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  169668. Rtree *pRtree = (Rtree*)tab;
  169669. int rc = SQLITE_OK;
  169670. int ii;
  169671. int bMatch = 0; /* True if there exists a MATCH constraint */
  169672. i64 nRow; /* Estimated rows returned by this scan */
  169673. int iIdx = 0;
  169674. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  169675. memset(zIdxStr, 0, sizeof(zIdxStr));
  169676. /* Check if there exists a MATCH constraint - even an unusable one. If there
  169677. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  169678. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  169679. ** possible. */
  169680. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  169681. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  169682. bMatch = 1;
  169683. }
  169684. }
  169685. assert( pIdxInfo->idxStr==0 );
  169686. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  169687. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  169688. if( bMatch==0 && p->usable
  169689. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  169690. ){
  169691. /* We have an equality constraint on the rowid. Use strategy 1. */
  169692. int jj;
  169693. for(jj=0; jj<ii; jj++){
  169694. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  169695. pIdxInfo->aConstraintUsage[jj].omit = 0;
  169696. }
  169697. pIdxInfo->idxNum = 1;
  169698. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  169699. pIdxInfo->aConstraintUsage[jj].omit = 1;
  169700. /* This strategy involves a two rowid lookups on an B-Tree structures
  169701. ** and then a linear search of an R-Tree node. This should be
  169702. ** considered almost as quick as a direct rowid lookup (for which
  169703. ** sqlite uses an internal cost of 0.0). It is expected to return
  169704. ** a single row.
  169705. */
  169706. pIdxInfo->estimatedCost = 30.0;
  169707. pIdxInfo->estimatedRows = 1;
  169708. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  169709. return SQLITE_OK;
  169710. }
  169711. if( p->usable
  169712. && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
  169713. || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
  169714. ){
  169715. u8 op;
  169716. switch( p->op ){
  169717. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  169718. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  169719. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  169720. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  169721. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  169722. default:
  169723. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  169724. op = RTREE_MATCH;
  169725. break;
  169726. }
  169727. zIdxStr[iIdx++] = op;
  169728. zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
  169729. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  169730. pIdxInfo->aConstraintUsage[ii].omit = 1;
  169731. }
  169732. }
  169733. pIdxInfo->idxNum = 2;
  169734. pIdxInfo->needToFreeIdxStr = 1;
  169735. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  169736. return SQLITE_NOMEM;
  169737. }
  169738. nRow = pRtree->nRowEst >> (iIdx/2);
  169739. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  169740. pIdxInfo->estimatedRows = nRow;
  169741. return rc;
  169742. }
  169743. /*
  169744. ** Return the N-dimensional volumn of the cell stored in *p.
  169745. */
  169746. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  169747. RtreeDValue area = (RtreeDValue)1;
  169748. assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
  169749. #ifndef SQLITE_RTREE_INT_ONLY
  169750. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  169751. switch( pRtree->nDim ){
  169752. case 5: area = p->aCoord[9].f - p->aCoord[8].f;
  169753. case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
  169754. case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
  169755. case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
  169756. default: area *= p->aCoord[1].f - p->aCoord[0].f;
  169757. }
  169758. }else
  169759. #endif
  169760. {
  169761. switch( pRtree->nDim ){
  169762. case 5: area = p->aCoord[9].i - p->aCoord[8].i;
  169763. case 4: area *= p->aCoord[7].i - p->aCoord[6].i;
  169764. case 3: area *= p->aCoord[5].i - p->aCoord[4].i;
  169765. case 2: area *= p->aCoord[3].i - p->aCoord[2].i;
  169766. default: area *= p->aCoord[1].i - p->aCoord[0].i;
  169767. }
  169768. }
  169769. return area;
  169770. }
  169771. /*
  169772. ** Return the margin length of cell p. The margin length is the sum
  169773. ** of the objects size in each dimension.
  169774. */
  169775. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  169776. RtreeDValue margin = 0;
  169777. int ii = pRtree->nDim2 - 2;
  169778. do{
  169779. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  169780. ii -= 2;
  169781. }while( ii>=0 );
  169782. return margin;
  169783. }
  169784. /*
  169785. ** Store the union of cells p1 and p2 in p1.
  169786. */
  169787. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  169788. int ii = 0;
  169789. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  169790. do{
  169791. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  169792. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  169793. ii += 2;
  169794. }while( ii<pRtree->nDim2 );
  169795. }else{
  169796. do{
  169797. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  169798. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  169799. ii += 2;
  169800. }while( ii<pRtree->nDim2 );
  169801. }
  169802. }
  169803. /*
  169804. ** Return true if the area covered by p2 is a subset of the area covered
  169805. ** by p1. False otherwise.
  169806. */
  169807. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  169808. int ii;
  169809. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  169810. for(ii=0; ii<pRtree->nDim2; ii+=2){
  169811. RtreeCoord *a1 = &p1->aCoord[ii];
  169812. RtreeCoord *a2 = &p2->aCoord[ii];
  169813. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  169814. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  169815. ){
  169816. return 0;
  169817. }
  169818. }
  169819. return 1;
  169820. }
  169821. /*
  169822. ** Return the amount cell p would grow by if it were unioned with pCell.
  169823. */
  169824. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  169825. RtreeDValue area;
  169826. RtreeCell cell;
  169827. memcpy(&cell, p, sizeof(RtreeCell));
  169828. area = cellArea(pRtree, &cell);
  169829. cellUnion(pRtree, &cell, pCell);
  169830. return (cellArea(pRtree, &cell)-area);
  169831. }
  169832. static RtreeDValue cellOverlap(
  169833. Rtree *pRtree,
  169834. RtreeCell *p,
  169835. RtreeCell *aCell,
  169836. int nCell
  169837. ){
  169838. int ii;
  169839. RtreeDValue overlap = RTREE_ZERO;
  169840. for(ii=0; ii<nCell; ii++){
  169841. int jj;
  169842. RtreeDValue o = (RtreeDValue)1;
  169843. for(jj=0; jj<pRtree->nDim2; jj+=2){
  169844. RtreeDValue x1, x2;
  169845. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  169846. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  169847. if( x2<x1 ){
  169848. o = (RtreeDValue)0;
  169849. break;
  169850. }else{
  169851. o = o * (x2-x1);
  169852. }
  169853. }
  169854. overlap += o;
  169855. }
  169856. return overlap;
  169857. }
  169858. /*
  169859. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  169860. ** ChooseSubTree in r*tree terminology.
  169861. */
  169862. static int ChooseLeaf(
  169863. Rtree *pRtree, /* Rtree table */
  169864. RtreeCell *pCell, /* Cell to insert into rtree */
  169865. int iHeight, /* Height of sub-tree rooted at pCell */
  169866. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  169867. ){
  169868. int rc;
  169869. int ii;
  169870. RtreeNode *pNode = 0;
  169871. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  169872. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  169873. int iCell;
  169874. sqlite3_int64 iBest = 0;
  169875. RtreeDValue fMinGrowth = RTREE_ZERO;
  169876. RtreeDValue fMinArea = RTREE_ZERO;
  169877. int nCell = NCELL(pNode);
  169878. RtreeCell cell;
  169879. RtreeNode *pChild;
  169880. RtreeCell *aCell = 0;
  169881. /* Select the child node which will be enlarged the least if pCell
  169882. ** is inserted into it. Resolve ties by choosing the entry with
  169883. ** the smallest area.
  169884. */
  169885. for(iCell=0; iCell<nCell; iCell++){
  169886. int bBest = 0;
  169887. RtreeDValue growth;
  169888. RtreeDValue area;
  169889. nodeGetCell(pRtree, pNode, iCell, &cell);
  169890. growth = cellGrowth(pRtree, &cell, pCell);
  169891. area = cellArea(pRtree, &cell);
  169892. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  169893. bBest = 1;
  169894. }
  169895. if( bBest ){
  169896. fMinGrowth = growth;
  169897. fMinArea = area;
  169898. iBest = cell.iRowid;
  169899. }
  169900. }
  169901. sqlite3_free(aCell);
  169902. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  169903. nodeRelease(pRtree, pNode);
  169904. pNode = pChild;
  169905. }
  169906. *ppLeaf = pNode;
  169907. return rc;
  169908. }
  169909. /*
  169910. ** A cell with the same content as pCell has just been inserted into
  169911. ** the node pNode. This function updates the bounding box cells in
  169912. ** all ancestor elements.
  169913. */
  169914. static int AdjustTree(
  169915. Rtree *pRtree, /* Rtree table */
  169916. RtreeNode *pNode, /* Adjust ancestry of this node. */
  169917. RtreeCell *pCell /* This cell was just inserted */
  169918. ){
  169919. RtreeNode *p = pNode;
  169920. while( p->pParent ){
  169921. RtreeNode *pParent = p->pParent;
  169922. RtreeCell cell;
  169923. int iCell;
  169924. if( nodeParentIndex(pRtree, p, &iCell) ){
  169925. return SQLITE_CORRUPT_VTAB;
  169926. }
  169927. nodeGetCell(pRtree, pParent, iCell, &cell);
  169928. if( !cellContains(pRtree, &cell, pCell) ){
  169929. cellUnion(pRtree, &cell, pCell);
  169930. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  169931. }
  169932. p = pParent;
  169933. }
  169934. return SQLITE_OK;
  169935. }
  169936. /*
  169937. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  169938. */
  169939. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  169940. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  169941. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  169942. sqlite3_step(pRtree->pWriteRowid);
  169943. return sqlite3_reset(pRtree->pWriteRowid);
  169944. }
  169945. /*
  169946. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  169947. */
  169948. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  169949. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  169950. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  169951. sqlite3_step(pRtree->pWriteParent);
  169952. return sqlite3_reset(pRtree->pWriteParent);
  169953. }
  169954. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  169955. /*
  169956. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  169957. ** nIdx. The aIdx array contains the set of integers from 0 to
  169958. ** (nIdx-1) in no particular order. This function sorts the values
  169959. ** in aIdx according to the indexed values in aDistance. For
  169960. ** example, assuming the inputs:
  169961. **
  169962. ** aIdx = { 0, 1, 2, 3 }
  169963. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  169964. **
  169965. ** this function sets the aIdx array to contain:
  169966. **
  169967. ** aIdx = { 0, 1, 2, 3 }
  169968. **
  169969. ** The aSpare array is used as temporary working space by the
  169970. ** sorting algorithm.
  169971. */
  169972. static void SortByDistance(
  169973. int *aIdx,
  169974. int nIdx,
  169975. RtreeDValue *aDistance,
  169976. int *aSpare
  169977. ){
  169978. if( nIdx>1 ){
  169979. int iLeft = 0;
  169980. int iRight = 0;
  169981. int nLeft = nIdx/2;
  169982. int nRight = nIdx-nLeft;
  169983. int *aLeft = aIdx;
  169984. int *aRight = &aIdx[nLeft];
  169985. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  169986. SortByDistance(aRight, nRight, aDistance, aSpare);
  169987. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  169988. aLeft = aSpare;
  169989. while( iLeft<nLeft || iRight<nRight ){
  169990. if( iLeft==nLeft ){
  169991. aIdx[iLeft+iRight] = aRight[iRight];
  169992. iRight++;
  169993. }else if( iRight==nRight ){
  169994. aIdx[iLeft+iRight] = aLeft[iLeft];
  169995. iLeft++;
  169996. }else{
  169997. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  169998. RtreeDValue fRight = aDistance[aRight[iRight]];
  169999. if( fLeft<fRight ){
  170000. aIdx[iLeft+iRight] = aLeft[iLeft];
  170001. iLeft++;
  170002. }else{
  170003. aIdx[iLeft+iRight] = aRight[iRight];
  170004. iRight++;
  170005. }
  170006. }
  170007. }
  170008. #if 0
  170009. /* Check that the sort worked */
  170010. {
  170011. int jj;
  170012. for(jj=1; jj<nIdx; jj++){
  170013. RtreeDValue left = aDistance[aIdx[jj-1]];
  170014. RtreeDValue right = aDistance[aIdx[jj]];
  170015. assert( left<=right );
  170016. }
  170017. }
  170018. #endif
  170019. }
  170020. }
  170021. /*
  170022. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  170023. ** nIdx. The aIdx array contains the set of integers from 0 to
  170024. ** (nIdx-1) in no particular order. This function sorts the values
  170025. ** in aIdx according to dimension iDim of the cells in aCell. The
  170026. ** minimum value of dimension iDim is considered first, the
  170027. ** maximum used to break ties.
  170028. **
  170029. ** The aSpare array is used as temporary working space by the
  170030. ** sorting algorithm.
  170031. */
  170032. static void SortByDimension(
  170033. Rtree *pRtree,
  170034. int *aIdx,
  170035. int nIdx,
  170036. int iDim,
  170037. RtreeCell *aCell,
  170038. int *aSpare
  170039. ){
  170040. if( nIdx>1 ){
  170041. int iLeft = 0;
  170042. int iRight = 0;
  170043. int nLeft = nIdx/2;
  170044. int nRight = nIdx-nLeft;
  170045. int *aLeft = aIdx;
  170046. int *aRight = &aIdx[nLeft];
  170047. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  170048. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  170049. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  170050. aLeft = aSpare;
  170051. while( iLeft<nLeft || iRight<nRight ){
  170052. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  170053. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  170054. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  170055. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  170056. if( (iLeft!=nLeft) && ((iRight==nRight)
  170057. || (xleft1<xright1)
  170058. || (xleft1==xright1 && xleft2<xright2)
  170059. )){
  170060. aIdx[iLeft+iRight] = aLeft[iLeft];
  170061. iLeft++;
  170062. }else{
  170063. aIdx[iLeft+iRight] = aRight[iRight];
  170064. iRight++;
  170065. }
  170066. }
  170067. #if 0
  170068. /* Check that the sort worked */
  170069. {
  170070. int jj;
  170071. for(jj=1; jj<nIdx; jj++){
  170072. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  170073. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  170074. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  170075. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  170076. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  170077. }
  170078. }
  170079. #endif
  170080. }
  170081. }
  170082. /*
  170083. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  170084. */
  170085. static int splitNodeStartree(
  170086. Rtree *pRtree,
  170087. RtreeCell *aCell,
  170088. int nCell,
  170089. RtreeNode *pLeft,
  170090. RtreeNode *pRight,
  170091. RtreeCell *pBboxLeft,
  170092. RtreeCell *pBboxRight
  170093. ){
  170094. int **aaSorted;
  170095. int *aSpare;
  170096. int ii;
  170097. int iBestDim = 0;
  170098. int iBestSplit = 0;
  170099. RtreeDValue fBestMargin = RTREE_ZERO;
  170100. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  170101. aaSorted = (int **)sqlite3_malloc(nByte);
  170102. if( !aaSorted ){
  170103. return SQLITE_NOMEM;
  170104. }
  170105. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  170106. memset(aaSorted, 0, nByte);
  170107. for(ii=0; ii<pRtree->nDim; ii++){
  170108. int jj;
  170109. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  170110. for(jj=0; jj<nCell; jj++){
  170111. aaSorted[ii][jj] = jj;
  170112. }
  170113. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  170114. }
  170115. for(ii=0; ii<pRtree->nDim; ii++){
  170116. RtreeDValue margin = RTREE_ZERO;
  170117. RtreeDValue fBestOverlap = RTREE_ZERO;
  170118. RtreeDValue fBestArea = RTREE_ZERO;
  170119. int iBestLeft = 0;
  170120. int nLeft;
  170121. for(
  170122. nLeft=RTREE_MINCELLS(pRtree);
  170123. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  170124. nLeft++
  170125. ){
  170126. RtreeCell left;
  170127. RtreeCell right;
  170128. int kk;
  170129. RtreeDValue overlap;
  170130. RtreeDValue area;
  170131. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  170132. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  170133. for(kk=1; kk<(nCell-1); kk++){
  170134. if( kk<nLeft ){
  170135. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  170136. }else{
  170137. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  170138. }
  170139. }
  170140. margin += cellMargin(pRtree, &left);
  170141. margin += cellMargin(pRtree, &right);
  170142. overlap = cellOverlap(pRtree, &left, &right, 1);
  170143. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  170144. if( (nLeft==RTREE_MINCELLS(pRtree))
  170145. || (overlap<fBestOverlap)
  170146. || (overlap==fBestOverlap && area<fBestArea)
  170147. ){
  170148. iBestLeft = nLeft;
  170149. fBestOverlap = overlap;
  170150. fBestArea = area;
  170151. }
  170152. }
  170153. if( ii==0 || margin<fBestMargin ){
  170154. iBestDim = ii;
  170155. fBestMargin = margin;
  170156. iBestSplit = iBestLeft;
  170157. }
  170158. }
  170159. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  170160. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  170161. for(ii=0; ii<nCell; ii++){
  170162. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  170163. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  170164. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  170165. nodeInsertCell(pRtree, pTarget, pCell);
  170166. cellUnion(pRtree, pBbox, pCell);
  170167. }
  170168. sqlite3_free(aaSorted);
  170169. return SQLITE_OK;
  170170. }
  170171. static int updateMapping(
  170172. Rtree *pRtree,
  170173. i64 iRowid,
  170174. RtreeNode *pNode,
  170175. int iHeight
  170176. ){
  170177. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  170178. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  170179. if( iHeight>0 ){
  170180. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  170181. if( pChild ){
  170182. nodeRelease(pRtree, pChild->pParent);
  170183. nodeReference(pNode);
  170184. pChild->pParent = pNode;
  170185. }
  170186. }
  170187. return xSetMapping(pRtree, iRowid, pNode->iNode);
  170188. }
  170189. static int SplitNode(
  170190. Rtree *pRtree,
  170191. RtreeNode *pNode,
  170192. RtreeCell *pCell,
  170193. int iHeight
  170194. ){
  170195. int i;
  170196. int newCellIsRight = 0;
  170197. int rc = SQLITE_OK;
  170198. int nCell = NCELL(pNode);
  170199. RtreeCell *aCell;
  170200. int *aiUsed;
  170201. RtreeNode *pLeft = 0;
  170202. RtreeNode *pRight = 0;
  170203. RtreeCell leftbbox;
  170204. RtreeCell rightbbox;
  170205. /* Allocate an array and populate it with a copy of pCell and
  170206. ** all cells from node pLeft. Then zero the original node.
  170207. */
  170208. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  170209. if( !aCell ){
  170210. rc = SQLITE_NOMEM;
  170211. goto splitnode_out;
  170212. }
  170213. aiUsed = (int *)&aCell[nCell+1];
  170214. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  170215. for(i=0; i<nCell; i++){
  170216. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  170217. }
  170218. nodeZero(pRtree, pNode);
  170219. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  170220. nCell++;
  170221. if( pNode->iNode==1 ){
  170222. pRight = nodeNew(pRtree, pNode);
  170223. pLeft = nodeNew(pRtree, pNode);
  170224. pRtree->iDepth++;
  170225. pNode->isDirty = 1;
  170226. writeInt16(pNode->zData, pRtree->iDepth);
  170227. }else{
  170228. pLeft = pNode;
  170229. pRight = nodeNew(pRtree, pLeft->pParent);
  170230. pLeft->nRef++;
  170231. }
  170232. if( !pLeft || !pRight ){
  170233. rc = SQLITE_NOMEM;
  170234. goto splitnode_out;
  170235. }
  170236. memset(pLeft->zData, 0, pRtree->iNodeSize);
  170237. memset(pRight->zData, 0, pRtree->iNodeSize);
  170238. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  170239. &leftbbox, &rightbbox);
  170240. if( rc!=SQLITE_OK ){
  170241. goto splitnode_out;
  170242. }
  170243. /* Ensure both child nodes have node numbers assigned to them by calling
  170244. ** nodeWrite(). Node pRight always needs a node number, as it was created
  170245. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  170246. ** In this case avoid the all to nodeWrite().
  170247. */
  170248. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  170249. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  170250. ){
  170251. goto splitnode_out;
  170252. }
  170253. rightbbox.iRowid = pRight->iNode;
  170254. leftbbox.iRowid = pLeft->iNode;
  170255. if( pNode->iNode==1 ){
  170256. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  170257. if( rc!=SQLITE_OK ){
  170258. goto splitnode_out;
  170259. }
  170260. }else{
  170261. RtreeNode *pParent = pLeft->pParent;
  170262. int iCell;
  170263. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  170264. if( rc==SQLITE_OK ){
  170265. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  170266. rc = AdjustTree(pRtree, pParent, &leftbbox);
  170267. }
  170268. if( rc!=SQLITE_OK ){
  170269. goto splitnode_out;
  170270. }
  170271. }
  170272. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  170273. goto splitnode_out;
  170274. }
  170275. for(i=0; i<NCELL(pRight); i++){
  170276. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  170277. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  170278. if( iRowid==pCell->iRowid ){
  170279. newCellIsRight = 1;
  170280. }
  170281. if( rc!=SQLITE_OK ){
  170282. goto splitnode_out;
  170283. }
  170284. }
  170285. if( pNode->iNode==1 ){
  170286. for(i=0; i<NCELL(pLeft); i++){
  170287. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  170288. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  170289. if( rc!=SQLITE_OK ){
  170290. goto splitnode_out;
  170291. }
  170292. }
  170293. }else if( newCellIsRight==0 ){
  170294. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  170295. }
  170296. if( rc==SQLITE_OK ){
  170297. rc = nodeRelease(pRtree, pRight);
  170298. pRight = 0;
  170299. }
  170300. if( rc==SQLITE_OK ){
  170301. rc = nodeRelease(pRtree, pLeft);
  170302. pLeft = 0;
  170303. }
  170304. splitnode_out:
  170305. nodeRelease(pRtree, pRight);
  170306. nodeRelease(pRtree, pLeft);
  170307. sqlite3_free(aCell);
  170308. return rc;
  170309. }
  170310. /*
  170311. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  170312. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  170313. ** the pLeaf->pParent chain all the way up to the root node.
  170314. **
  170315. ** This operation is required when a row is deleted (or updated - an update
  170316. ** is implemented as a delete followed by an insert). SQLite provides the
  170317. ** rowid of the row to delete, which can be used to find the leaf on which
  170318. ** the entry resides (argument pLeaf). Once the leaf is located, this
  170319. ** function is called to determine its ancestry.
  170320. */
  170321. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  170322. int rc = SQLITE_OK;
  170323. RtreeNode *pChild = pLeaf;
  170324. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  170325. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  170326. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  170327. rc = sqlite3_step(pRtree->pReadParent);
  170328. if( rc==SQLITE_ROW ){
  170329. RtreeNode *pTest; /* Used to test for reference loops */
  170330. i64 iNode; /* Node number of parent node */
  170331. /* Before setting pChild->pParent, test that we are not creating a
  170332. ** loop of references (as we would if, say, pChild==pParent). We don't
  170333. ** want to do this as it leads to a memory leak when trying to delete
  170334. ** the referenced counted node structures.
  170335. */
  170336. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  170337. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  170338. if( !pTest ){
  170339. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  170340. }
  170341. }
  170342. rc = sqlite3_reset(pRtree->pReadParent);
  170343. if( rc==SQLITE_OK ) rc = rc2;
  170344. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  170345. pChild = pChild->pParent;
  170346. }
  170347. return rc;
  170348. }
  170349. static int deleteCell(Rtree *, RtreeNode *, int, int);
  170350. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  170351. int rc;
  170352. int rc2;
  170353. RtreeNode *pParent = 0;
  170354. int iCell;
  170355. assert( pNode->nRef==1 );
  170356. /* Remove the entry in the parent cell. */
  170357. rc = nodeParentIndex(pRtree, pNode, &iCell);
  170358. if( rc==SQLITE_OK ){
  170359. pParent = pNode->pParent;
  170360. pNode->pParent = 0;
  170361. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  170362. }
  170363. rc2 = nodeRelease(pRtree, pParent);
  170364. if( rc==SQLITE_OK ){
  170365. rc = rc2;
  170366. }
  170367. if( rc!=SQLITE_OK ){
  170368. return rc;
  170369. }
  170370. /* Remove the xxx_node entry. */
  170371. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  170372. sqlite3_step(pRtree->pDeleteNode);
  170373. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  170374. return rc;
  170375. }
  170376. /* Remove the xxx_parent entry. */
  170377. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  170378. sqlite3_step(pRtree->pDeleteParent);
  170379. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  170380. return rc;
  170381. }
  170382. /* Remove the node from the in-memory hash table and link it into
  170383. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  170384. */
  170385. nodeHashDelete(pRtree, pNode);
  170386. pNode->iNode = iHeight;
  170387. pNode->pNext = pRtree->pDeleted;
  170388. pNode->nRef++;
  170389. pRtree->pDeleted = pNode;
  170390. return SQLITE_OK;
  170391. }
  170392. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  170393. RtreeNode *pParent = pNode->pParent;
  170394. int rc = SQLITE_OK;
  170395. if( pParent ){
  170396. int ii;
  170397. int nCell = NCELL(pNode);
  170398. RtreeCell box; /* Bounding box for pNode */
  170399. nodeGetCell(pRtree, pNode, 0, &box);
  170400. for(ii=1; ii<nCell; ii++){
  170401. RtreeCell cell;
  170402. nodeGetCell(pRtree, pNode, ii, &cell);
  170403. cellUnion(pRtree, &box, &cell);
  170404. }
  170405. box.iRowid = pNode->iNode;
  170406. rc = nodeParentIndex(pRtree, pNode, &ii);
  170407. if( rc==SQLITE_OK ){
  170408. nodeOverwriteCell(pRtree, pParent, &box, ii);
  170409. rc = fixBoundingBox(pRtree, pParent);
  170410. }
  170411. }
  170412. return rc;
  170413. }
  170414. /*
  170415. ** Delete the cell at index iCell of node pNode. After removing the
  170416. ** cell, adjust the r-tree data structure if required.
  170417. */
  170418. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  170419. RtreeNode *pParent;
  170420. int rc;
  170421. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  170422. return rc;
  170423. }
  170424. /* Remove the cell from the node. This call just moves bytes around
  170425. ** the in-memory node image, so it cannot fail.
  170426. */
  170427. nodeDeleteCell(pRtree, pNode, iCell);
  170428. /* If the node is not the tree root and now has less than the minimum
  170429. ** number of cells, remove it from the tree. Otherwise, update the
  170430. ** cell in the parent node so that it tightly contains the updated
  170431. ** node.
  170432. */
  170433. pParent = pNode->pParent;
  170434. assert( pParent || pNode->iNode==1 );
  170435. if( pParent ){
  170436. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  170437. rc = removeNode(pRtree, pNode, iHeight);
  170438. }else{
  170439. rc = fixBoundingBox(pRtree, pNode);
  170440. }
  170441. }
  170442. return rc;
  170443. }
  170444. static int Reinsert(
  170445. Rtree *pRtree,
  170446. RtreeNode *pNode,
  170447. RtreeCell *pCell,
  170448. int iHeight
  170449. ){
  170450. int *aOrder;
  170451. int *aSpare;
  170452. RtreeCell *aCell;
  170453. RtreeDValue *aDistance;
  170454. int nCell;
  170455. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  170456. int iDim;
  170457. int ii;
  170458. int rc = SQLITE_OK;
  170459. int n;
  170460. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  170461. nCell = NCELL(pNode)+1;
  170462. n = (nCell+1)&(~1);
  170463. /* Allocate the buffers used by this operation. The allocation is
  170464. ** relinquished before this function returns.
  170465. */
  170466. aCell = (RtreeCell *)sqlite3_malloc(n * (
  170467. sizeof(RtreeCell) + /* aCell array */
  170468. sizeof(int) + /* aOrder array */
  170469. sizeof(int) + /* aSpare array */
  170470. sizeof(RtreeDValue) /* aDistance array */
  170471. ));
  170472. if( !aCell ){
  170473. return SQLITE_NOMEM;
  170474. }
  170475. aOrder = (int *)&aCell[n];
  170476. aSpare = (int *)&aOrder[n];
  170477. aDistance = (RtreeDValue *)&aSpare[n];
  170478. for(ii=0; ii<nCell; ii++){
  170479. if( ii==(nCell-1) ){
  170480. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  170481. }else{
  170482. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  170483. }
  170484. aOrder[ii] = ii;
  170485. for(iDim=0; iDim<pRtree->nDim; iDim++){
  170486. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  170487. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  170488. }
  170489. }
  170490. for(iDim=0; iDim<pRtree->nDim; iDim++){
  170491. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  170492. }
  170493. for(ii=0; ii<nCell; ii++){
  170494. aDistance[ii] = RTREE_ZERO;
  170495. for(iDim=0; iDim<pRtree->nDim; iDim++){
  170496. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  170497. DCOORD(aCell[ii].aCoord[iDim*2]));
  170498. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  170499. }
  170500. }
  170501. SortByDistance(aOrder, nCell, aDistance, aSpare);
  170502. nodeZero(pRtree, pNode);
  170503. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  170504. RtreeCell *p = &aCell[aOrder[ii]];
  170505. nodeInsertCell(pRtree, pNode, p);
  170506. if( p->iRowid==pCell->iRowid ){
  170507. if( iHeight==0 ){
  170508. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  170509. }else{
  170510. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  170511. }
  170512. }
  170513. }
  170514. if( rc==SQLITE_OK ){
  170515. rc = fixBoundingBox(pRtree, pNode);
  170516. }
  170517. for(; rc==SQLITE_OK && ii<nCell; ii++){
  170518. /* Find a node to store this cell in. pNode->iNode currently contains
  170519. ** the height of the sub-tree headed by the cell.
  170520. */
  170521. RtreeNode *pInsert;
  170522. RtreeCell *p = &aCell[aOrder[ii]];
  170523. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  170524. if( rc==SQLITE_OK ){
  170525. int rc2;
  170526. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  170527. rc2 = nodeRelease(pRtree, pInsert);
  170528. if( rc==SQLITE_OK ){
  170529. rc = rc2;
  170530. }
  170531. }
  170532. }
  170533. sqlite3_free(aCell);
  170534. return rc;
  170535. }
  170536. /*
  170537. ** Insert cell pCell into node pNode. Node pNode is the head of a
  170538. ** subtree iHeight high (leaf nodes have iHeight==0).
  170539. */
  170540. static int rtreeInsertCell(
  170541. Rtree *pRtree,
  170542. RtreeNode *pNode,
  170543. RtreeCell *pCell,
  170544. int iHeight
  170545. ){
  170546. int rc = SQLITE_OK;
  170547. if( iHeight>0 ){
  170548. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  170549. if( pChild ){
  170550. nodeRelease(pRtree, pChild->pParent);
  170551. nodeReference(pNode);
  170552. pChild->pParent = pNode;
  170553. }
  170554. }
  170555. if( nodeInsertCell(pRtree, pNode, pCell) ){
  170556. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  170557. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  170558. }else{
  170559. pRtree->iReinsertHeight = iHeight;
  170560. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  170561. }
  170562. }else{
  170563. rc = AdjustTree(pRtree, pNode, pCell);
  170564. if( rc==SQLITE_OK ){
  170565. if( iHeight==0 ){
  170566. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  170567. }else{
  170568. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  170569. }
  170570. }
  170571. }
  170572. return rc;
  170573. }
  170574. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  170575. int ii;
  170576. int rc = SQLITE_OK;
  170577. int nCell = NCELL(pNode);
  170578. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  170579. RtreeNode *pInsert;
  170580. RtreeCell cell;
  170581. nodeGetCell(pRtree, pNode, ii, &cell);
  170582. /* Find a node to store this cell in. pNode->iNode currently contains
  170583. ** the height of the sub-tree headed by the cell.
  170584. */
  170585. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  170586. if( rc==SQLITE_OK ){
  170587. int rc2;
  170588. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  170589. rc2 = nodeRelease(pRtree, pInsert);
  170590. if( rc==SQLITE_OK ){
  170591. rc = rc2;
  170592. }
  170593. }
  170594. }
  170595. return rc;
  170596. }
  170597. /*
  170598. ** Select a currently unused rowid for a new r-tree record.
  170599. */
  170600. static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){
  170601. int rc;
  170602. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  170603. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  170604. sqlite3_step(pRtree->pWriteRowid);
  170605. rc = sqlite3_reset(pRtree->pWriteRowid);
  170606. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  170607. return rc;
  170608. }
  170609. /*
  170610. ** Remove the entry with rowid=iDelete from the r-tree structure.
  170611. */
  170612. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  170613. int rc; /* Return code */
  170614. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  170615. int iCell; /* Index of iDelete cell in pLeaf */
  170616. RtreeNode *pRoot = 0; /* Root node of rtree structure */
  170617. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  170618. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  170619. /* Obtain a reference to the leaf node that contains the entry
  170620. ** about to be deleted.
  170621. */
  170622. if( rc==SQLITE_OK ){
  170623. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  170624. }
  170625. /* Delete the cell in question from the leaf node. */
  170626. if( rc==SQLITE_OK ){
  170627. int rc2;
  170628. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  170629. if( rc==SQLITE_OK ){
  170630. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  170631. }
  170632. rc2 = nodeRelease(pRtree, pLeaf);
  170633. if( rc==SQLITE_OK ){
  170634. rc = rc2;
  170635. }
  170636. }
  170637. /* Delete the corresponding entry in the <rtree>_rowid table. */
  170638. if( rc==SQLITE_OK ){
  170639. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  170640. sqlite3_step(pRtree->pDeleteRowid);
  170641. rc = sqlite3_reset(pRtree->pDeleteRowid);
  170642. }
  170643. /* Check if the root node now has exactly one child. If so, remove
  170644. ** it, schedule the contents of the child for reinsertion and
  170645. ** reduce the tree height by one.
  170646. **
  170647. ** This is equivalent to copying the contents of the child into
  170648. ** the root node (the operation that Gutman's paper says to perform
  170649. ** in this scenario).
  170650. */
  170651. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  170652. int rc2;
  170653. RtreeNode *pChild = 0;
  170654. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  170655. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  170656. if( rc==SQLITE_OK ){
  170657. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  170658. }
  170659. rc2 = nodeRelease(pRtree, pChild);
  170660. if( rc==SQLITE_OK ) rc = rc2;
  170661. if( rc==SQLITE_OK ){
  170662. pRtree->iDepth--;
  170663. writeInt16(pRoot->zData, pRtree->iDepth);
  170664. pRoot->isDirty = 1;
  170665. }
  170666. }
  170667. /* Re-insert the contents of any underfull nodes removed from the tree. */
  170668. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  170669. if( rc==SQLITE_OK ){
  170670. rc = reinsertNodeContent(pRtree, pLeaf);
  170671. }
  170672. pRtree->pDeleted = pLeaf->pNext;
  170673. pRtree->nNodeRef--;
  170674. sqlite3_free(pLeaf);
  170675. }
  170676. /* Release the reference to the root node. */
  170677. if( rc==SQLITE_OK ){
  170678. rc = nodeRelease(pRtree, pRoot);
  170679. }else{
  170680. nodeRelease(pRtree, pRoot);
  170681. }
  170682. return rc;
  170683. }
  170684. /*
  170685. ** Rounding constants for float->double conversion.
  170686. */
  170687. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  170688. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  170689. #if !defined(SQLITE_RTREE_INT_ONLY)
  170690. /*
  170691. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  170692. ** while taking care to round toward negative or positive, respectively.
  170693. */
  170694. static RtreeValue rtreeValueDown(sqlite3_value *v){
  170695. double d = sqlite3_value_double(v);
  170696. float f = (float)d;
  170697. if( f>d ){
  170698. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  170699. }
  170700. return f;
  170701. }
  170702. static RtreeValue rtreeValueUp(sqlite3_value *v){
  170703. double d = sqlite3_value_double(v);
  170704. float f = (float)d;
  170705. if( f<d ){
  170706. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  170707. }
  170708. return f;
  170709. }
  170710. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  170711. /*
  170712. ** A constraint has failed while inserting a row into an rtree table.
  170713. ** Assuming no OOM error occurs, this function sets the error message
  170714. ** (at pRtree->base.zErrMsg) to an appropriate value and returns
  170715. ** SQLITE_CONSTRAINT.
  170716. **
  170717. ** Parameter iCol is the index of the leftmost column involved in the
  170718. ** constraint failure. If it is 0, then the constraint that failed is
  170719. ** the unique constraint on the id column. Otherwise, it is the rtree
  170720. ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
  170721. **
  170722. ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
  170723. */
  170724. static int rtreeConstraintError(Rtree *pRtree, int iCol){
  170725. sqlite3_stmt *pStmt = 0;
  170726. char *zSql;
  170727. int rc;
  170728. assert( iCol==0 || iCol%2 );
  170729. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
  170730. if( zSql ){
  170731. rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
  170732. }else{
  170733. rc = SQLITE_NOMEM;
  170734. }
  170735. sqlite3_free(zSql);
  170736. if( rc==SQLITE_OK ){
  170737. if( iCol==0 ){
  170738. const char *zCol = sqlite3_column_name(pStmt, 0);
  170739. pRtree->base.zErrMsg = sqlite3_mprintf(
  170740. "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
  170741. );
  170742. }else{
  170743. const char *zCol1 = sqlite3_column_name(pStmt, iCol);
  170744. const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
  170745. pRtree->base.zErrMsg = sqlite3_mprintf(
  170746. "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
  170747. );
  170748. }
  170749. }
  170750. sqlite3_finalize(pStmt);
  170751. return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
  170752. }
  170753. /*
  170754. ** The xUpdate method for rtree module virtual tables.
  170755. */
  170756. static int rtreeUpdate(
  170757. sqlite3_vtab *pVtab,
  170758. int nData,
  170759. sqlite3_value **aData,
  170760. sqlite_int64 *pRowid
  170761. ){
  170762. Rtree *pRtree = (Rtree *)pVtab;
  170763. int rc = SQLITE_OK;
  170764. RtreeCell cell; /* New cell to insert if nData>1 */
  170765. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  170766. if( pRtree->nNodeRef ){
  170767. /* Unable to write to the btree while another cursor is reading from it,
  170768. ** since the write might do a rebalance which would disrupt the read
  170769. ** cursor. */
  170770. return SQLITE_LOCKED_VTAB;
  170771. }
  170772. rtreeReference(pRtree);
  170773. assert(nData>=1);
  170774. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  170775. /* Constraint handling. A write operation on an r-tree table may return
  170776. ** SQLITE_CONSTRAINT for two reasons:
  170777. **
  170778. ** 1. A duplicate rowid value, or
  170779. ** 2. The supplied data violates the "x2>=x1" constraint.
  170780. **
  170781. ** In the first case, if the conflict-handling mode is REPLACE, then
  170782. ** the conflicting row can be removed before proceeding. In the second
  170783. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  170784. ** conflict-handling mode specified by the user.
  170785. */
  170786. if( nData>1 ){
  170787. int ii;
  170788. int nn = nData - 4;
  170789. if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
  170790. /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
  170791. **
  170792. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  170793. ** with "column" that are interpreted as table constraints.
  170794. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  170795. ** This problem was discovered after years of use, so we silently ignore
  170796. ** these kinds of misdeclared tables to avoid breaking any legacy.
  170797. */
  170798. #ifndef SQLITE_RTREE_INT_ONLY
  170799. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  170800. for(ii=0; ii<nn; ii+=2){
  170801. cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
  170802. cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
  170803. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  170804. rc = rtreeConstraintError(pRtree, ii+1);
  170805. goto constraint;
  170806. }
  170807. }
  170808. }else
  170809. #endif
  170810. {
  170811. for(ii=0; ii<nn; ii+=2){
  170812. cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
  170813. cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
  170814. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  170815. rc = rtreeConstraintError(pRtree, ii+1);
  170816. goto constraint;
  170817. }
  170818. }
  170819. }
  170820. /* If a rowid value was supplied, check if it is already present in
  170821. ** the table. If so, the constraint has failed. */
  170822. if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
  170823. cell.iRowid = sqlite3_value_int64(aData[2]);
  170824. if( sqlite3_value_type(aData[0])==SQLITE_NULL
  170825. || sqlite3_value_int64(aData[0])!=cell.iRowid
  170826. ){
  170827. int steprc;
  170828. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  170829. steprc = sqlite3_step(pRtree->pReadRowid);
  170830. rc = sqlite3_reset(pRtree->pReadRowid);
  170831. if( SQLITE_ROW==steprc ){
  170832. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  170833. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  170834. }else{
  170835. rc = rtreeConstraintError(pRtree, 0);
  170836. goto constraint;
  170837. }
  170838. }
  170839. }
  170840. bHaveRowid = 1;
  170841. }
  170842. }
  170843. /* If aData[0] is not an SQL NULL value, it is the rowid of a
  170844. ** record to delete from the r-tree table. The following block does
  170845. ** just that.
  170846. */
  170847. if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
  170848. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
  170849. }
  170850. /* If the aData[] array contains more than one element, elements
  170851. ** (aData[2]..aData[argc-1]) contain a new record to insert into
  170852. ** the r-tree structure.
  170853. */
  170854. if( rc==SQLITE_OK && nData>1 ){
  170855. /* Insert the new record into the r-tree */
  170856. RtreeNode *pLeaf = 0;
  170857. /* Figure out the rowid of the new row. */
  170858. if( bHaveRowid==0 ){
  170859. rc = rtreeNewRowid(pRtree, &cell.iRowid);
  170860. }
  170861. *pRowid = cell.iRowid;
  170862. if( rc==SQLITE_OK ){
  170863. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  170864. }
  170865. if( rc==SQLITE_OK ){
  170866. int rc2;
  170867. pRtree->iReinsertHeight = -1;
  170868. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  170869. rc2 = nodeRelease(pRtree, pLeaf);
  170870. if( rc==SQLITE_OK ){
  170871. rc = rc2;
  170872. }
  170873. }
  170874. if( pRtree->nAux ){
  170875. sqlite3_stmt *pUp = pRtree->pWriteAux;
  170876. int jj;
  170877. sqlite3_bind_int64(pUp, 1, *pRowid);
  170878. for(jj=0; jj<pRtree->nAux; jj++){
  170879. sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
  170880. }
  170881. sqlite3_step(pUp);
  170882. rc = sqlite3_reset(pUp);
  170883. }
  170884. }
  170885. constraint:
  170886. rtreeRelease(pRtree);
  170887. return rc;
  170888. }
  170889. /*
  170890. ** Called when a transaction starts.
  170891. */
  170892. static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
  170893. Rtree *pRtree = (Rtree *)pVtab;
  170894. assert( pRtree->inWrTrans==0 );
  170895. pRtree->inWrTrans++;
  170896. return SQLITE_OK;
  170897. }
  170898. /*
  170899. ** Called when a transaction completes (either by COMMIT or ROLLBACK).
  170900. ** The sqlite3_blob object should be released at this point.
  170901. */
  170902. static int rtreeEndTransaction(sqlite3_vtab *pVtab){
  170903. Rtree *pRtree = (Rtree *)pVtab;
  170904. pRtree->inWrTrans = 0;
  170905. nodeBlobReset(pRtree);
  170906. return SQLITE_OK;
  170907. }
  170908. /*
  170909. ** The xRename method for rtree module virtual tables.
  170910. */
  170911. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  170912. Rtree *pRtree = (Rtree *)pVtab;
  170913. int rc = SQLITE_NOMEM;
  170914. char *zSql = sqlite3_mprintf(
  170915. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  170916. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  170917. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  170918. , pRtree->zDb, pRtree->zName, zNewName
  170919. , pRtree->zDb, pRtree->zName, zNewName
  170920. , pRtree->zDb, pRtree->zName, zNewName
  170921. );
  170922. if( zSql ){
  170923. nodeBlobReset(pRtree);
  170924. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  170925. sqlite3_free(zSql);
  170926. }
  170927. return rc;
  170928. }
  170929. /*
  170930. ** The xSavepoint method.
  170931. **
  170932. ** This module does not need to do anything to support savepoints. However,
  170933. ** it uses this hook to close any open blob handle. This is done because a
  170934. ** DROP TABLE command - which fortunately always opens a savepoint - cannot
  170935. ** succeed if there are any open blob handles. i.e. if the blob handle were
  170936. ** not closed here, the following would fail:
  170937. **
  170938. ** BEGIN;
  170939. ** INSERT INTO rtree...
  170940. ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
  170941. ** COMMIT;
  170942. */
  170943. static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
  170944. Rtree *pRtree = (Rtree *)pVtab;
  170945. u8 iwt = pRtree->inWrTrans;
  170946. UNUSED_PARAMETER(iSavepoint);
  170947. pRtree->inWrTrans = 0;
  170948. nodeBlobReset(pRtree);
  170949. pRtree->inWrTrans = iwt;
  170950. return SQLITE_OK;
  170951. }
  170952. /*
  170953. ** This function populates the pRtree->nRowEst variable with an estimate
  170954. ** of the number of rows in the virtual table. If possible, this is based
  170955. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  170956. */
  170957. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  170958. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  170959. char *zSql;
  170960. sqlite3_stmt *p;
  170961. int rc;
  170962. i64 nRow = 0;
  170963. rc = sqlite3_table_column_metadata(
  170964. db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
  170965. );
  170966. if( rc!=SQLITE_OK ){
  170967. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  170968. return rc==SQLITE_ERROR ? SQLITE_OK : rc;
  170969. }
  170970. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  170971. if( zSql==0 ){
  170972. rc = SQLITE_NOMEM;
  170973. }else{
  170974. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  170975. if( rc==SQLITE_OK ){
  170976. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  170977. rc = sqlite3_finalize(p);
  170978. }else if( rc!=SQLITE_NOMEM ){
  170979. rc = SQLITE_OK;
  170980. }
  170981. if( rc==SQLITE_OK ){
  170982. if( nRow==0 ){
  170983. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  170984. }else{
  170985. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  170986. }
  170987. }
  170988. sqlite3_free(zSql);
  170989. }
  170990. return rc;
  170991. }
  170992. /*
  170993. ** Return true if zName is the extension on one of the shadow tables used
  170994. ** by this module.
  170995. */
  170996. static int rtreeShadowName(const char *zName){
  170997. static const char *azName[] = {
  170998. "node", "parent", "rowid"
  170999. };
  171000. unsigned int i;
  171001. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  171002. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  171003. }
  171004. return 0;
  171005. }
  171006. static sqlite3_module rtreeModule = {
  171007. 3, /* iVersion */
  171008. rtreeCreate, /* xCreate - create a table */
  171009. rtreeConnect, /* xConnect - connect to an existing table */
  171010. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  171011. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  171012. rtreeDestroy, /* xDestroy - Drop a table */
  171013. rtreeOpen, /* xOpen - open a cursor */
  171014. rtreeClose, /* xClose - close a cursor */
  171015. rtreeFilter, /* xFilter - configure scan constraints */
  171016. rtreeNext, /* xNext - advance a cursor */
  171017. rtreeEof, /* xEof */
  171018. rtreeColumn, /* xColumn - read data */
  171019. rtreeRowid, /* xRowid - read data */
  171020. rtreeUpdate, /* xUpdate - write data */
  171021. rtreeBeginTransaction, /* xBegin - begin transaction */
  171022. rtreeEndTransaction, /* xSync - sync transaction */
  171023. rtreeEndTransaction, /* xCommit - commit transaction */
  171024. rtreeEndTransaction, /* xRollback - rollback transaction */
  171025. 0, /* xFindFunction - function overloading */
  171026. rtreeRename, /* xRename - rename the table */
  171027. rtreeSavepoint, /* xSavepoint */
  171028. 0, /* xRelease */
  171029. 0, /* xRollbackTo */
  171030. rtreeShadowName /* xShadowName */
  171031. };
  171032. static int rtreeSqlInit(
  171033. Rtree *pRtree,
  171034. sqlite3 *db,
  171035. const char *zDb,
  171036. const char *zPrefix,
  171037. int isCreate
  171038. ){
  171039. int rc = SQLITE_OK;
  171040. #define N_STATEMENT 8
  171041. static const char *azSql[N_STATEMENT] = {
  171042. /* Write the xxx_node table */
  171043. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
  171044. "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
  171045. /* Read and write the xxx_rowid table */
  171046. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
  171047. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
  171048. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
  171049. /* Read and write the xxx_parent table */
  171050. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
  171051. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
  171052. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
  171053. };
  171054. sqlite3_stmt **appStmt[N_STATEMENT];
  171055. int i;
  171056. pRtree->db = db;
  171057. if( isCreate ){
  171058. char *zCreate;
  171059. sqlite3_str *p = sqlite3_str_new(db);
  171060. int ii;
  171061. sqlite3_str_appendf(p,
  171062. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
  171063. zDb, zPrefix);
  171064. for(ii=0; ii<pRtree->nAux; ii++){
  171065. sqlite3_str_appendf(p,",a%d",ii);
  171066. }
  171067. sqlite3_str_appendf(p,
  171068. ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
  171069. zDb, zPrefix);
  171070. sqlite3_str_appendf(p,
  171071. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
  171072. zDb, zPrefix);
  171073. sqlite3_str_appendf(p,
  171074. "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
  171075. zDb, zPrefix, pRtree->iNodeSize);
  171076. zCreate = sqlite3_str_finish(p);
  171077. if( !zCreate ){
  171078. return SQLITE_NOMEM;
  171079. }
  171080. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  171081. sqlite3_free(zCreate);
  171082. if( rc!=SQLITE_OK ){
  171083. return rc;
  171084. }
  171085. }
  171086. appStmt[0] = &pRtree->pWriteNode;
  171087. appStmt[1] = &pRtree->pDeleteNode;
  171088. appStmt[2] = &pRtree->pReadRowid;
  171089. appStmt[3] = &pRtree->pWriteRowid;
  171090. appStmt[4] = &pRtree->pDeleteRowid;
  171091. appStmt[5] = &pRtree->pReadParent;
  171092. appStmt[6] = &pRtree->pWriteParent;
  171093. appStmt[7] = &pRtree->pDeleteParent;
  171094. rc = rtreeQueryStat1(db, pRtree);
  171095. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  171096. char *zSql;
  171097. const char *zFormat;
  171098. if( i!=3 || pRtree->nAux==0 ){
  171099. zFormat = azSql[i];
  171100. }else {
  171101. /* An UPSERT is very slightly slower than REPLACE, but it is needed
  171102. ** if there are auxiliary columns */
  171103. zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
  171104. "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
  171105. }
  171106. zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
  171107. if( zSql ){
  171108. rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
  171109. appStmt[i], 0);
  171110. }else{
  171111. rc = SQLITE_NOMEM;
  171112. }
  171113. sqlite3_free(zSql);
  171114. }
  171115. if( pRtree->nAux ){
  171116. pRtree->zReadAuxSql = sqlite3_mprintf(
  171117. "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
  171118. zDb, zPrefix);
  171119. if( pRtree->zReadAuxSql==0 ){
  171120. rc = SQLITE_NOMEM;
  171121. }else{
  171122. sqlite3_str *p = sqlite3_str_new(db);
  171123. int ii;
  171124. char *zSql;
  171125. sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
  171126. for(ii=0; ii<pRtree->nAux; ii++){
  171127. if( ii ) sqlite3_str_append(p, ",", 1);
  171128. if( ii<pRtree->nAuxNotNull ){
  171129. sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
  171130. }else{
  171131. sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
  171132. }
  171133. }
  171134. sqlite3_str_appendf(p, " WHERE rowid=?1");
  171135. zSql = sqlite3_str_finish(p);
  171136. if( zSql==0 ){
  171137. rc = SQLITE_NOMEM;
  171138. }else{
  171139. rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
  171140. &pRtree->pWriteAux, 0);
  171141. sqlite3_free(zSql);
  171142. }
  171143. }
  171144. }
  171145. return rc;
  171146. }
  171147. /*
  171148. ** The second argument to this function contains the text of an SQL statement
  171149. ** that returns a single integer value. The statement is compiled and executed
  171150. ** using database connection db. If successful, the integer value returned
  171151. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  171152. ** code is returned and the value of *piVal after returning is not defined.
  171153. */
  171154. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  171155. int rc = SQLITE_NOMEM;
  171156. if( zSql ){
  171157. sqlite3_stmt *pStmt = 0;
  171158. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  171159. if( rc==SQLITE_OK ){
  171160. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  171161. *piVal = sqlite3_column_int(pStmt, 0);
  171162. }
  171163. rc = sqlite3_finalize(pStmt);
  171164. }
  171165. }
  171166. return rc;
  171167. }
  171168. /*
  171169. ** This function is called from within the xConnect() or xCreate() method to
  171170. ** determine the node-size used by the rtree table being created or connected
  171171. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  171172. ** Otherwise, an SQLite error code is returned.
  171173. **
  171174. ** If this function is being called as part of an xConnect(), then the rtree
  171175. ** table already exists. In this case the node-size is determined by inspecting
  171176. ** the root node of the tree.
  171177. **
  171178. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  171179. ** This ensures that each node is stored on a single database page. If the
  171180. ** database page-size is so large that more than RTREE_MAXCELLS entries
  171181. ** would fit in a single node, use a smaller node-size.
  171182. */
  171183. static int getNodeSize(
  171184. sqlite3 *db, /* Database handle */
  171185. Rtree *pRtree, /* Rtree handle */
  171186. int isCreate, /* True for xCreate, false for xConnect */
  171187. char **pzErr /* OUT: Error message, if any */
  171188. ){
  171189. int rc;
  171190. char *zSql;
  171191. if( isCreate ){
  171192. int iPageSize = 0;
  171193. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  171194. rc = getIntFromStmt(db, zSql, &iPageSize);
  171195. if( rc==SQLITE_OK ){
  171196. pRtree->iNodeSize = iPageSize-64;
  171197. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  171198. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  171199. }
  171200. }else{
  171201. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  171202. }
  171203. }else{
  171204. zSql = sqlite3_mprintf(
  171205. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  171206. pRtree->zDb, pRtree->zName
  171207. );
  171208. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  171209. if( rc!=SQLITE_OK ){
  171210. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  171211. }else if( pRtree->iNodeSize<(512-64) ){
  171212. rc = SQLITE_CORRUPT_VTAB;
  171213. *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
  171214. pRtree->zName);
  171215. }
  171216. }
  171217. sqlite3_free(zSql);
  171218. return rc;
  171219. }
  171220. /*
  171221. ** This function is the implementation of both the xConnect and xCreate
  171222. ** methods of the r-tree virtual table.
  171223. **
  171224. ** argv[0] -> module name
  171225. ** argv[1] -> database name
  171226. ** argv[2] -> table name
  171227. ** argv[...] -> column names...
  171228. */
  171229. static int rtreeInit(
  171230. sqlite3 *db, /* Database connection */
  171231. void *pAux, /* One of the RTREE_COORD_* constants */
  171232. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  171233. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  171234. char **pzErr, /* OUT: Error message, if any */
  171235. int isCreate /* True for xCreate, false for xConnect */
  171236. ){
  171237. int rc = SQLITE_OK;
  171238. Rtree *pRtree;
  171239. int nDb; /* Length of string argv[1] */
  171240. int nName; /* Length of string argv[2] */
  171241. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  171242. sqlite3_str *pSql;
  171243. char *zSql;
  171244. int ii = 4;
  171245. int iErr;
  171246. const char *aErrMsg[] = {
  171247. 0, /* 0 */
  171248. "Wrong number of columns for an rtree table", /* 1 */
  171249. "Too few columns for an rtree table", /* 2 */
  171250. "Too many columns for an rtree table", /* 3 */
  171251. "Auxiliary rtree columns must be last" /* 4 */
  171252. };
  171253. assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
  171254. if( argc>RTREE_MAX_AUX_COLUMN+3 ){
  171255. *pzErr = sqlite3_mprintf("%s", aErrMsg[3]);
  171256. return SQLITE_ERROR;
  171257. }
  171258. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  171259. /* Allocate the sqlite3_vtab structure */
  171260. nDb = (int)strlen(argv[1]);
  171261. nName = (int)strlen(argv[2]);
  171262. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  171263. if( !pRtree ){
  171264. return SQLITE_NOMEM;
  171265. }
  171266. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  171267. pRtree->nBusy = 1;
  171268. pRtree->base.pModule = &rtreeModule;
  171269. pRtree->zDb = (char *)&pRtree[1];
  171270. pRtree->zName = &pRtree->zDb[nDb+1];
  171271. pRtree->eCoordType = (u8)eCoordType;
  171272. memcpy(pRtree->zDb, argv[1], nDb);
  171273. memcpy(pRtree->zName, argv[2], nName);
  171274. /* Create/Connect to the underlying relational database schema. If
  171275. ** that is successful, call sqlite3_declare_vtab() to configure
  171276. ** the r-tree table schema.
  171277. */
  171278. pSql = sqlite3_str_new(db);
  171279. sqlite3_str_appendf(pSql, "CREATE TABLE x(%s", argv[3]);
  171280. for(ii=4; ii<argc; ii++){
  171281. if( argv[ii][0]=='+' ){
  171282. pRtree->nAux++;
  171283. sqlite3_str_appendf(pSql, ",%s", argv[ii]+1);
  171284. }else if( pRtree->nAux>0 ){
  171285. break;
  171286. }else{
  171287. pRtree->nDim2++;
  171288. sqlite3_str_appendf(pSql, ",%s", argv[ii]);
  171289. }
  171290. }
  171291. sqlite3_str_appendf(pSql, ");");
  171292. zSql = sqlite3_str_finish(pSql);
  171293. if( !zSql ){
  171294. rc = SQLITE_NOMEM;
  171295. }else if( ii<argc ){
  171296. *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
  171297. rc = SQLITE_ERROR;
  171298. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  171299. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  171300. }
  171301. sqlite3_free(zSql);
  171302. if( rc ) goto rtreeInit_fail;
  171303. pRtree->nDim = pRtree->nDim2/2;
  171304. if( pRtree->nDim<1 ){
  171305. iErr = 2;
  171306. }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
  171307. iErr = 3;
  171308. }else if( pRtree->nDim2 % 2 ){
  171309. iErr = 1;
  171310. }else{
  171311. iErr = 0;
  171312. }
  171313. if( iErr ){
  171314. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  171315. goto rtreeInit_fail;
  171316. }
  171317. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  171318. /* Figure out the node size to use. */
  171319. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  171320. if( rc ) goto rtreeInit_fail;
  171321. rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
  171322. if( rc ){
  171323. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  171324. goto rtreeInit_fail;
  171325. }
  171326. *ppVtab = (sqlite3_vtab *)pRtree;
  171327. return SQLITE_OK;
  171328. rtreeInit_fail:
  171329. if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
  171330. assert( *ppVtab==0 );
  171331. assert( pRtree->nBusy==1 );
  171332. rtreeRelease(pRtree);
  171333. return rc;
  171334. }
  171335. /*
  171336. ** Implementation of a scalar function that decodes r-tree nodes to
  171337. ** human readable strings. This can be used for debugging and analysis.
  171338. **
  171339. ** The scalar function takes two arguments: (1) the number of dimensions
  171340. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  171341. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  171342. ** deserialize all nodes, a statement like:
  171343. **
  171344. ** SELECT rtreenode(2, data) FROM rt_node;
  171345. **
  171346. ** The human readable string takes the form of a Tcl list with one
  171347. ** entry for each cell in the r-tree node. Each entry is itself a
  171348. ** list, containing the 8-byte rowid/pageno followed by the
  171349. ** <num-dimension>*2 coordinates.
  171350. */
  171351. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  171352. char *zText = 0;
  171353. RtreeNode node;
  171354. Rtree tree;
  171355. int ii;
  171356. UNUSED_PARAMETER(nArg);
  171357. memset(&node, 0, sizeof(RtreeNode));
  171358. memset(&tree, 0, sizeof(Rtree));
  171359. tree.nDim = (u8)sqlite3_value_int(apArg[0]);
  171360. tree.nDim2 = tree.nDim*2;
  171361. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  171362. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  171363. for(ii=0; ii<NCELL(&node); ii++){
  171364. char zCell[512];
  171365. int nCell = 0;
  171366. RtreeCell cell;
  171367. int jj;
  171368. nodeGetCell(&tree, &node, ii, &cell);
  171369. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  171370. nCell = (int)strlen(zCell);
  171371. for(jj=0; jj<tree.nDim2; jj++){
  171372. #ifndef SQLITE_RTREE_INT_ONLY
  171373. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  171374. (double)cell.aCoord[jj].f);
  171375. #else
  171376. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  171377. cell.aCoord[jj].i);
  171378. #endif
  171379. nCell = (int)strlen(zCell);
  171380. }
  171381. if( zText ){
  171382. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  171383. sqlite3_free(zText);
  171384. zText = zTextNew;
  171385. }else{
  171386. zText = sqlite3_mprintf("{%s}", zCell);
  171387. }
  171388. }
  171389. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  171390. }
  171391. /* This routine implements an SQL function that returns the "depth" parameter
  171392. ** from the front of a blob that is an r-tree node. For example:
  171393. **
  171394. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  171395. **
  171396. ** The depth value is 0 for all nodes other than the root node, and the root
  171397. ** node always has nodeno=1, so the example above is the primary use for this
  171398. ** routine. This routine is intended for testing and analysis only.
  171399. */
  171400. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  171401. UNUSED_PARAMETER(nArg);
  171402. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  171403. || sqlite3_value_bytes(apArg[0])<2
  171404. ){
  171405. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  171406. }else{
  171407. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  171408. sqlite3_result_int(ctx, readInt16(zBlob));
  171409. }
  171410. }
  171411. /*
  171412. ** Context object passed between the various routines that make up the
  171413. ** implementation of integrity-check function rtreecheck().
  171414. */
  171415. typedef struct RtreeCheck RtreeCheck;
  171416. struct RtreeCheck {
  171417. sqlite3 *db; /* Database handle */
  171418. const char *zDb; /* Database containing rtree table */
  171419. const char *zTab; /* Name of rtree table */
  171420. int bInt; /* True for rtree_i32 table */
  171421. int nDim; /* Number of dimensions for this rtree tbl */
  171422. sqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */
  171423. sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
  171424. int nLeaf; /* Number of leaf cells in table */
  171425. int nNonLeaf; /* Number of non-leaf cells in table */
  171426. int rc; /* Return code */
  171427. char *zReport; /* Message to report */
  171428. int nErr; /* Number of lines in zReport */
  171429. };
  171430. #define RTREE_CHECK_MAX_ERROR 100
  171431. /*
  171432. ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
  171433. ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
  171434. */
  171435. static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
  171436. int rc = sqlite3_reset(pStmt);
  171437. if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
  171438. }
  171439. /*
  171440. ** The second and subsequent arguments to this function are a format string
  171441. ** and printf style arguments. This function formats the string and attempts
  171442. ** to compile it as an SQL statement.
  171443. **
  171444. ** If successful, a pointer to the new SQL statement is returned. Otherwise,
  171445. ** NULL is returned and an error code left in RtreeCheck.rc.
  171446. */
  171447. static sqlite3_stmt *rtreeCheckPrepare(
  171448. RtreeCheck *pCheck, /* RtreeCheck object */
  171449. const char *zFmt, ... /* Format string and trailing args */
  171450. ){
  171451. va_list ap;
  171452. char *z;
  171453. sqlite3_stmt *pRet = 0;
  171454. va_start(ap, zFmt);
  171455. z = sqlite3_vmprintf(zFmt, ap);
  171456. if( pCheck->rc==SQLITE_OK ){
  171457. if( z==0 ){
  171458. pCheck->rc = SQLITE_NOMEM;
  171459. }else{
  171460. pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
  171461. }
  171462. }
  171463. sqlite3_free(z);
  171464. va_end(ap);
  171465. return pRet;
  171466. }
  171467. /*
  171468. ** The second and subsequent arguments to this function are a printf()
  171469. ** style format string and arguments. This function formats the string and
  171470. ** appends it to the report being accumuated in pCheck.
  171471. */
  171472. static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
  171473. va_list ap;
  171474. va_start(ap, zFmt);
  171475. if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
  171476. char *z = sqlite3_vmprintf(zFmt, ap);
  171477. if( z==0 ){
  171478. pCheck->rc = SQLITE_NOMEM;
  171479. }else{
  171480. pCheck->zReport = sqlite3_mprintf("%z%s%z",
  171481. pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
  171482. );
  171483. if( pCheck->zReport==0 ){
  171484. pCheck->rc = SQLITE_NOMEM;
  171485. }
  171486. }
  171487. pCheck->nErr++;
  171488. }
  171489. va_end(ap);
  171490. }
  171491. /*
  171492. ** This function is a no-op if there is already an error code stored
  171493. ** in the RtreeCheck object indicated by the first argument. NULL is
  171494. ** returned in this case.
  171495. **
  171496. ** Otherwise, the contents of rtree table node iNode are loaded from
  171497. ** the database and copied into a buffer obtained from sqlite3_malloc().
  171498. ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
  171499. ** is set to the size of the buffer in bytes.
  171500. **
  171501. ** Or, if an error does occur, NULL is returned and an error code left
  171502. ** in the RtreeCheck object. The final value of *pnNode is undefined in
  171503. ** this case.
  171504. */
  171505. static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
  171506. u8 *pRet = 0; /* Return value */
  171507. assert( pCheck->rc==SQLITE_OK );
  171508. if( pCheck->pGetNode==0 ){
  171509. pCheck->pGetNode = rtreeCheckPrepare(pCheck,
  171510. "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
  171511. pCheck->zDb, pCheck->zTab
  171512. );
  171513. }
  171514. if( pCheck->rc==SQLITE_OK ){
  171515. sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
  171516. if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
  171517. int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
  171518. const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
  171519. pRet = sqlite3_malloc(nNode);
  171520. if( pRet==0 ){
  171521. pCheck->rc = SQLITE_NOMEM;
  171522. }else{
  171523. memcpy(pRet, pNode, nNode);
  171524. *pnNode = nNode;
  171525. }
  171526. }
  171527. rtreeCheckReset(pCheck, pCheck->pGetNode);
  171528. if( pCheck->rc==SQLITE_OK && pRet==0 ){
  171529. rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
  171530. }
  171531. }
  171532. return pRet;
  171533. }
  171534. /*
  171535. ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
  171536. ** (if bLeaf==1) table contains a specified entry. The schemas of the
  171537. ** two tables are:
  171538. **
  171539. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  171540. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
  171541. **
  171542. ** In both cases, this function checks that there exists an entry with
  171543. ** IPK value iKey and the second column set to iVal.
  171544. **
  171545. */
  171546. static void rtreeCheckMapping(
  171547. RtreeCheck *pCheck, /* RtreeCheck object */
  171548. int bLeaf, /* True for a leaf cell, false for interior */
  171549. i64 iKey, /* Key for mapping */
  171550. i64 iVal /* Expected value for mapping */
  171551. ){
  171552. int rc;
  171553. sqlite3_stmt *pStmt;
  171554. const char *azSql[2] = {
  171555. "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
  171556. "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
  171557. };
  171558. assert( bLeaf==0 || bLeaf==1 );
  171559. if( pCheck->aCheckMapping[bLeaf]==0 ){
  171560. pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
  171561. azSql[bLeaf], pCheck->zDb, pCheck->zTab
  171562. );
  171563. }
  171564. if( pCheck->rc!=SQLITE_OK ) return;
  171565. pStmt = pCheck->aCheckMapping[bLeaf];
  171566. sqlite3_bind_int64(pStmt, 1, iKey);
  171567. rc = sqlite3_step(pStmt);
  171568. if( rc==SQLITE_DONE ){
  171569. rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
  171570. iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
  171571. );
  171572. }else if( rc==SQLITE_ROW ){
  171573. i64 ii = sqlite3_column_int64(pStmt, 0);
  171574. if( ii!=iVal ){
  171575. rtreeCheckAppendMsg(pCheck,
  171576. "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
  171577. iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
  171578. );
  171579. }
  171580. }
  171581. rtreeCheckReset(pCheck, pStmt);
  171582. }
  171583. /*
  171584. ** Argument pCell points to an array of coordinates stored on an rtree page.
  171585. ** This function checks that the coordinates are internally consistent (no
  171586. ** x1>x2 conditions) and adds an error message to the RtreeCheck object
  171587. ** if they are not.
  171588. **
  171589. ** Additionally, if pParent is not NULL, then it is assumed to point to
  171590. ** the array of coordinates on the parent page that bound the page
  171591. ** containing pCell. In this case it is also verified that the two
  171592. ** sets of coordinates are mutually consistent and an error message added
  171593. ** to the RtreeCheck object if they are not.
  171594. */
  171595. static void rtreeCheckCellCoord(
  171596. RtreeCheck *pCheck,
  171597. i64 iNode, /* Node id to use in error messages */
  171598. int iCell, /* Cell number to use in error messages */
  171599. u8 *pCell, /* Pointer to cell coordinates */
  171600. u8 *pParent /* Pointer to parent coordinates */
  171601. ){
  171602. RtreeCoord c1, c2;
  171603. RtreeCoord p1, p2;
  171604. int i;
  171605. for(i=0; i<pCheck->nDim; i++){
  171606. readCoord(&pCell[4*2*i], &c1);
  171607. readCoord(&pCell[4*(2*i + 1)], &c2);
  171608. /* printf("%e, %e\n", c1.u.f, c2.u.f); */
  171609. if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
  171610. rtreeCheckAppendMsg(pCheck,
  171611. "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
  171612. );
  171613. }
  171614. if( pParent ){
  171615. readCoord(&pParent[4*2*i], &p1);
  171616. readCoord(&pParent[4*(2*i + 1)], &p2);
  171617. if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
  171618. || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
  171619. ){
  171620. rtreeCheckAppendMsg(pCheck,
  171621. "Dimension %d of cell %d on node %lld is corrupt relative to parent"
  171622. , i, iCell, iNode
  171623. );
  171624. }
  171625. }
  171626. }
  171627. }
  171628. /*
  171629. ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
  171630. ** the r-tree structure. Argument aParent points to the array of coordinates
  171631. ** that bound node iNode on the parent node.
  171632. **
  171633. ** If any problems are discovered, an error message is appended to the
  171634. ** report accumulated in the RtreeCheck object.
  171635. */
  171636. static void rtreeCheckNode(
  171637. RtreeCheck *pCheck,
  171638. int iDepth, /* Depth of iNode (0==leaf) */
  171639. u8 *aParent, /* Buffer containing parent coords */
  171640. i64 iNode /* Node to check */
  171641. ){
  171642. u8 *aNode = 0;
  171643. int nNode = 0;
  171644. assert( iNode==1 || aParent!=0 );
  171645. assert( pCheck->nDim>0 );
  171646. aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
  171647. if( aNode ){
  171648. if( nNode<4 ){
  171649. rtreeCheckAppendMsg(pCheck,
  171650. "Node %lld is too small (%d bytes)", iNode, nNode
  171651. );
  171652. }else{
  171653. int nCell; /* Number of cells on page */
  171654. int i; /* Used to iterate through cells */
  171655. if( aParent==0 ){
  171656. iDepth = readInt16(aNode);
  171657. if( iDepth>RTREE_MAX_DEPTH ){
  171658. rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
  171659. sqlite3_free(aNode);
  171660. return;
  171661. }
  171662. }
  171663. nCell = readInt16(&aNode[2]);
  171664. if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
  171665. rtreeCheckAppendMsg(pCheck,
  171666. "Node %lld is too small for cell count of %d (%d bytes)",
  171667. iNode, nCell, nNode
  171668. );
  171669. }else{
  171670. for(i=0; i<nCell; i++){
  171671. u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
  171672. i64 iVal = readInt64(pCell);
  171673. rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
  171674. if( iDepth>0 ){
  171675. rtreeCheckMapping(pCheck, 0, iVal, iNode);
  171676. rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
  171677. pCheck->nNonLeaf++;
  171678. }else{
  171679. rtreeCheckMapping(pCheck, 1, iVal, iNode);
  171680. pCheck->nLeaf++;
  171681. }
  171682. }
  171683. }
  171684. }
  171685. sqlite3_free(aNode);
  171686. }
  171687. }
  171688. /*
  171689. ** The second argument to this function must be either "_rowid" or
  171690. ** "_parent". This function checks that the number of entries in the
  171691. ** %_rowid or %_parent table is exactly nExpect. If not, it adds
  171692. ** an error message to the report in the RtreeCheck object indicated
  171693. ** by the first argument.
  171694. */
  171695. static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
  171696. if( pCheck->rc==SQLITE_OK ){
  171697. sqlite3_stmt *pCount;
  171698. pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
  171699. pCheck->zDb, pCheck->zTab, zTbl
  171700. );
  171701. if( pCount ){
  171702. if( sqlite3_step(pCount)==SQLITE_ROW ){
  171703. i64 nActual = sqlite3_column_int64(pCount, 0);
  171704. if( nActual!=nExpect ){
  171705. rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
  171706. " - expected %lld, actual %lld" , zTbl, nExpect, nActual
  171707. );
  171708. }
  171709. }
  171710. pCheck->rc = sqlite3_finalize(pCount);
  171711. }
  171712. }
  171713. }
  171714. /*
  171715. ** This function does the bulk of the work for the rtree integrity-check.
  171716. ** It is called by rtreecheck(), which is the SQL function implementation.
  171717. */
  171718. static int rtreeCheckTable(
  171719. sqlite3 *db, /* Database handle to access db through */
  171720. const char *zDb, /* Name of db ("main", "temp" etc.) */
  171721. const char *zTab, /* Name of rtree table to check */
  171722. char **pzReport /* OUT: sqlite3_malloc'd report text */
  171723. ){
  171724. RtreeCheck check; /* Common context for various routines */
  171725. sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */
  171726. int bEnd = 0; /* True if transaction should be closed */
  171727. int nAux = 0; /* Number of extra columns. */
  171728. /* Initialize the context object */
  171729. memset(&check, 0, sizeof(check));
  171730. check.db = db;
  171731. check.zDb = zDb;
  171732. check.zTab = zTab;
  171733. /* If there is not already an open transaction, open one now. This is
  171734. ** to ensure that the queries run as part of this integrity-check operate
  171735. ** on a consistent snapshot. */
  171736. if( sqlite3_get_autocommit(db) ){
  171737. check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
  171738. bEnd = 1;
  171739. }
  171740. /* Find the number of auxiliary columns */
  171741. if( check.rc==SQLITE_OK ){
  171742. pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
  171743. if( pStmt ){
  171744. nAux = sqlite3_column_count(pStmt) - 2;
  171745. sqlite3_finalize(pStmt);
  171746. }
  171747. check.rc = SQLITE_OK;
  171748. }
  171749. /* Find number of dimensions in the rtree table. */
  171750. pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
  171751. if( pStmt ){
  171752. int rc;
  171753. check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
  171754. if( check.nDim<1 ){
  171755. rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
  171756. }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
  171757. check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
  171758. }
  171759. rc = sqlite3_finalize(pStmt);
  171760. if( rc!=SQLITE_CORRUPT ) check.rc = rc;
  171761. }
  171762. /* Do the actual integrity-check */
  171763. if( check.nDim>=1 ){
  171764. if( check.rc==SQLITE_OK ){
  171765. rtreeCheckNode(&check, 0, 0, 1);
  171766. }
  171767. rtreeCheckCount(&check, "_rowid", check.nLeaf);
  171768. rtreeCheckCount(&check, "_parent", check.nNonLeaf);
  171769. }
  171770. /* Finalize SQL statements used by the integrity-check */
  171771. sqlite3_finalize(check.pGetNode);
  171772. sqlite3_finalize(check.aCheckMapping[0]);
  171773. sqlite3_finalize(check.aCheckMapping[1]);
  171774. /* If one was opened, close the transaction */
  171775. if( bEnd ){
  171776. int rc = sqlite3_exec(db, "END", 0, 0, 0);
  171777. if( check.rc==SQLITE_OK ) check.rc = rc;
  171778. }
  171779. *pzReport = check.zReport;
  171780. return check.rc;
  171781. }
  171782. /*
  171783. ** Usage:
  171784. **
  171785. ** rtreecheck(<rtree-table>);
  171786. ** rtreecheck(<database>, <rtree-table>);
  171787. **
  171788. ** Invoking this SQL function runs an integrity-check on the named rtree
  171789. ** table. The integrity-check verifies the following:
  171790. **
  171791. ** 1. For each cell in the r-tree structure (%_node table), that:
  171792. **
  171793. ** a) for each dimension, (coord1 <= coord2).
  171794. **
  171795. ** b) unless the cell is on the root node, that the cell is bounded
  171796. ** by the parent cell on the parent node.
  171797. **
  171798. ** c) for leaf nodes, that there is an entry in the %_rowid
  171799. ** table corresponding to the cell's rowid value that
  171800. ** points to the correct node.
  171801. **
  171802. ** d) for cells on non-leaf nodes, that there is an entry in the
  171803. ** %_parent table mapping from the cell's child node to the
  171804. ** node that it resides on.
  171805. **
  171806. ** 2. That there are the same number of entries in the %_rowid table
  171807. ** as there are leaf cells in the r-tree structure, and that there
  171808. ** is a leaf cell that corresponds to each entry in the %_rowid table.
  171809. **
  171810. ** 3. That there are the same number of entries in the %_parent table
  171811. ** as there are non-leaf cells in the r-tree structure, and that
  171812. ** there is a non-leaf cell that corresponds to each entry in the
  171813. ** %_parent table.
  171814. */
  171815. static void rtreecheck(
  171816. sqlite3_context *ctx,
  171817. int nArg,
  171818. sqlite3_value **apArg
  171819. ){
  171820. if( nArg!=1 && nArg!=2 ){
  171821. sqlite3_result_error(ctx,
  171822. "wrong number of arguments to function rtreecheck()", -1
  171823. );
  171824. }else{
  171825. int rc;
  171826. char *zReport = 0;
  171827. const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
  171828. const char *zTab;
  171829. if( nArg==1 ){
  171830. zTab = zDb;
  171831. zDb = "main";
  171832. }else{
  171833. zTab = (const char*)sqlite3_value_text(apArg[1]);
  171834. }
  171835. rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
  171836. if( rc==SQLITE_OK ){
  171837. sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
  171838. }else{
  171839. sqlite3_result_error_code(ctx, rc);
  171840. }
  171841. sqlite3_free(zReport);
  171842. }
  171843. }
  171844. /* Conditionally include the geopoly code */
  171845. #ifdef SQLITE_ENABLE_GEOPOLY
  171846. /************** Include geopoly.c in the middle of rtree.c *******************/
  171847. /************** Begin file geopoly.c *****************************************/
  171848. /*
  171849. ** 2018-05-25
  171850. **
  171851. ** The author disclaims copyright to this source code. In place of
  171852. ** a legal notice, here is a blessing:
  171853. **
  171854. ** May you do good and not evil.
  171855. ** May you find forgiveness for yourself and forgive others.
  171856. ** May you share freely, never taking more than you give.
  171857. **
  171858. ******************************************************************************
  171859. **
  171860. ** This file implements an alternative R-Tree virtual table that
  171861. ** uses polygons to express the boundaries of 2-dimensional objects.
  171862. **
  171863. ** This file is #include-ed onto the end of "rtree.c" so that it has
  171864. ** access to all of the R-Tree internals.
  171865. */
  171866. /* #include <stdlib.h> */
  171867. /* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */
  171868. #ifdef GEOPOLY_ENABLE_DEBUG
  171869. static int geo_debug = 0;
  171870. # define GEODEBUG(X) if(geo_debug)printf X
  171871. #else
  171872. # define GEODEBUG(X)
  171873. #endif
  171874. #ifndef JSON_NULL /* The following stuff repeats things found in json1 */
  171875. /*
  171876. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  171877. ** to pass signed char values.
  171878. */
  171879. #ifdef sqlite3Isdigit
  171880. /* Use the SQLite core versions if this routine is part of the
  171881. ** SQLite amalgamation */
  171882. # define safe_isdigit(x) sqlite3Isdigit(x)
  171883. # define safe_isalnum(x) sqlite3Isalnum(x)
  171884. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  171885. #else
  171886. /* Use the standard library for separate compilation */
  171887. #include <ctype.h> /* amalgamator: keep */
  171888. # define safe_isdigit(x) isdigit((unsigned char)(x))
  171889. # define safe_isalnum(x) isalnum((unsigned char)(x))
  171890. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  171891. #endif
  171892. /*
  171893. ** Growing our own isspace() routine this way is twice as fast as
  171894. ** the library isspace() function.
  171895. */
  171896. static const char geopolyIsSpace[] = {
  171897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  171898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171899. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  171913. };
  171914. #define safe_isspace(x) (geopolyIsSpace[(unsigned char)x])
  171915. #endif /* JSON NULL - back to original code */
  171916. /* Compiler and version */
  171917. #ifndef GCC_VERSION
  171918. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  171919. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  171920. #else
  171921. # define GCC_VERSION 0
  171922. #endif
  171923. #endif
  171924. #ifndef MSVC_VERSION
  171925. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  171926. # define MSVC_VERSION _MSC_VER
  171927. #else
  171928. # define MSVC_VERSION 0
  171929. #endif
  171930. #endif
  171931. /* Datatype for coordinates
  171932. */
  171933. typedef float GeoCoord;
  171934. /*
  171935. ** Internal representation of a polygon.
  171936. **
  171937. ** The polygon consists of a sequence of vertexes. There is a line
  171938. ** segment between each pair of vertexes, and one final segment from
  171939. ** the last vertex back to the first. (This differs from the GeoJSON
  171940. ** standard in which the final vertex is a repeat of the first.)
  171941. **
  171942. ** The polygon follows the right-hand rule. The area to the right of
  171943. ** each segment is "outside" and the area to the left is "inside".
  171944. **
  171945. ** The on-disk representation consists of a 4-byte header followed by
  171946. ** the values. The 4-byte header is:
  171947. **
  171948. ** encoding (1 byte) 0=big-endian, 1=little-endian
  171949. ** nvertex (3 bytes) Number of vertexes as a big-endian integer
  171950. **
  171951. ** Enough space is allocated for 4 coordinates, to work around over-zealous
  171952. ** warnings coming from some compiler (notably, clang). In reality, the size
  171953. ** of each GeoPoly memory allocate is adjusted as necessary so that the
  171954. ** GeoPoly.a[] array at the end is the appropriate size.
  171955. */
  171956. typedef struct GeoPoly GeoPoly;
  171957. struct GeoPoly {
  171958. int nVertex; /* Number of vertexes */
  171959. unsigned char hdr[4]; /* Header for on-disk representation */
  171960. GeoCoord a[8]; /* 2*nVertex values. X (longitude) first, then Y */
  171961. };
  171962. /* The size of a memory allocation needed for a GeoPoly object sufficient
  171963. ** to hold N coordinate pairs.
  171964. */
  171965. #define GEOPOLY_SZ(N) (sizeof(GeoPoly) + sizeof(GeoCoord)*2*((N)-4))
  171966. /*
  171967. ** State of a parse of a GeoJSON input.
  171968. */
  171969. typedef struct GeoParse GeoParse;
  171970. struct GeoParse {
  171971. const unsigned char *z; /* Unparsed input */
  171972. int nVertex; /* Number of vertexes in a[] */
  171973. int nAlloc; /* Space allocated to a[] */
  171974. int nErr; /* Number of errors encountered */
  171975. GeoCoord *a; /* Array of vertexes. From sqlite3_malloc64() */
  171976. };
  171977. /* Do a 4-byte byte swap */
  171978. static void geopolySwab32(unsigned char *a){
  171979. unsigned char t = a[0];
  171980. a[0] = a[3];
  171981. a[3] = t;
  171982. t = a[1];
  171983. a[1] = a[2];
  171984. a[2] = t;
  171985. }
  171986. /* Skip whitespace. Return the next non-whitespace character. */
  171987. static char geopolySkipSpace(GeoParse *p){
  171988. while( safe_isspace(p->z[0]) ) p->z++;
  171989. return p->z[0];
  171990. }
  171991. /* Parse out a number. Write the value into *pVal if pVal!=0.
  171992. ** return non-zero on success and zero if the next token is not a number.
  171993. */
  171994. static int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){
  171995. char c = geopolySkipSpace(p);
  171996. const unsigned char *z = p->z;
  171997. int j = 0;
  171998. int seenDP = 0;
  171999. int seenE = 0;
  172000. if( c=='-' ){
  172001. j = 1;
  172002. c = z[j];
  172003. }
  172004. if( c=='0' && z[j+1]>='0' && z[j+1]<='9' ) return 0;
  172005. for(;; j++){
  172006. c = z[j];
  172007. if( safe_isdigit(c) ) continue;
  172008. if( c=='.' ){
  172009. if( z[j-1]=='-' ) return 0;
  172010. if( seenDP ) return 0;
  172011. seenDP = 1;
  172012. continue;
  172013. }
  172014. if( c=='e' || c=='E' ){
  172015. if( z[j-1]<'0' ) return 0;
  172016. if( seenE ) return -1;
  172017. seenDP = seenE = 1;
  172018. c = z[j+1];
  172019. if( c=='+' || c=='-' ){
  172020. j++;
  172021. c = z[j+1];
  172022. }
  172023. if( c<'0' || c>'9' ) return 0;
  172024. continue;
  172025. }
  172026. break;
  172027. }
  172028. if( z[j-1]<'0' ) return 0;
  172029. if( pVal ){
  172030. #ifdef SQLITE_AMALGAMATION
  172031. /* The sqlite3AtoF() routine is much much faster than atof(), if it
  172032. ** is available */
  172033. double r;
  172034. (void)sqlite3AtoF((const char*)p->z, &r, j, SQLITE_UTF8);
  172035. *pVal = r;
  172036. #else
  172037. *pVal = (GeoCoord)atof((const char*)p->z);
  172038. #endif
  172039. }
  172040. p->z += j;
  172041. return 1;
  172042. }
  172043. /*
  172044. ** If the input is a well-formed JSON array of coordinates with at least
  172045. ** four coordinates and where each coordinate is itself a two-value array,
  172046. ** then convert the JSON into a GeoPoly object and return a pointer to
  172047. ** that object.
  172048. **
  172049. ** If any error occurs, return NULL.
  172050. */
  172051. static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){
  172052. GeoParse s;
  172053. int rc = SQLITE_OK;
  172054. memset(&s, 0, sizeof(s));
  172055. s.z = z;
  172056. if( geopolySkipSpace(&s)=='[' ){
  172057. s.z++;
  172058. while( geopolySkipSpace(&s)=='[' ){
  172059. int ii = 0;
  172060. char c;
  172061. s.z++;
  172062. if( s.nVertex>=s.nAlloc ){
  172063. GeoCoord *aNew;
  172064. s.nAlloc = s.nAlloc*2 + 16;
  172065. aNew = sqlite3_realloc64(s.a, s.nAlloc*sizeof(GeoCoord)*2 );
  172066. if( aNew==0 ){
  172067. rc = SQLITE_NOMEM;
  172068. s.nErr++;
  172069. break;
  172070. }
  172071. s.a = aNew;
  172072. }
  172073. while( geopolyParseNumber(&s, ii<=1 ? &s.a[s.nVertex*2+ii] : 0) ){
  172074. ii++;
  172075. if( ii==2 ) s.nVertex++;
  172076. c = geopolySkipSpace(&s);
  172077. s.z++;
  172078. if( c==',' ) continue;
  172079. if( c==']' && ii>=2 ) break;
  172080. s.nErr++;
  172081. rc = SQLITE_ERROR;
  172082. goto parse_json_err;
  172083. }
  172084. if( geopolySkipSpace(&s)==',' ){
  172085. s.z++;
  172086. continue;
  172087. }
  172088. break;
  172089. }
  172090. if( geopolySkipSpace(&s)==']'
  172091. && s.nVertex>=4
  172092. && s.a[0]==s.a[s.nVertex*2-2]
  172093. && s.a[1]==s.a[s.nVertex*2-1]
  172094. && (s.z++, geopolySkipSpace(&s)==0)
  172095. ){
  172096. GeoPoly *pOut;
  172097. int x = 1;
  172098. s.nVertex--; /* Remove the redundant vertex at the end */
  172099. pOut = sqlite3_malloc64( GEOPOLY_SZ(s.nVertex) );
  172100. x = 1;
  172101. if( pOut==0 ) goto parse_json_err;
  172102. pOut->nVertex = s.nVertex;
  172103. memcpy(pOut->a, s.a, s.nVertex*2*sizeof(GeoCoord));
  172104. pOut->hdr[0] = *(unsigned char*)&x;
  172105. pOut->hdr[1] = (s.nVertex>>16)&0xff;
  172106. pOut->hdr[2] = (s.nVertex>>8)&0xff;
  172107. pOut->hdr[3] = s.nVertex&0xff;
  172108. sqlite3_free(s.a);
  172109. if( pRc ) *pRc = SQLITE_OK;
  172110. return pOut;
  172111. }else{
  172112. s.nErr++;
  172113. rc = SQLITE_ERROR;
  172114. }
  172115. }
  172116. parse_json_err:
  172117. if( pRc ) *pRc = rc;
  172118. sqlite3_free(s.a);
  172119. return 0;
  172120. }
  172121. /*
  172122. ** Given a function parameter, try to interpret it as a polygon, either
  172123. ** in the binary format or JSON text. Compute a GeoPoly object and
  172124. ** return a pointer to that object. Or if the input is not a well-formed
  172125. ** polygon, put an error message in sqlite3_context and return NULL.
  172126. */
  172127. static GeoPoly *geopolyFuncParam(
  172128. sqlite3_context *pCtx, /* Context for error messages */
  172129. sqlite3_value *pVal, /* The value to decode */
  172130. int *pRc /* Write error here */
  172131. ){
  172132. GeoPoly *p = 0;
  172133. int nByte;
  172134. if( sqlite3_value_type(pVal)==SQLITE_BLOB
  172135. && (nByte = sqlite3_value_bytes(pVal))>=(4+6*sizeof(GeoCoord))
  172136. ){
  172137. const unsigned char *a = sqlite3_value_blob(pVal);
  172138. int nVertex;
  172139. nVertex = (a[1]<<16) + (a[2]<<8) + a[3];
  172140. if( (a[0]==0 || a[0]==1)
  172141. && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte
  172142. ){
  172143. p = sqlite3_malloc64( sizeof(*p) + (nVertex-1)*2*sizeof(GeoCoord) );
  172144. if( p==0 ){
  172145. if( pRc ) *pRc = SQLITE_NOMEM;
  172146. if( pCtx ) sqlite3_result_error_nomem(pCtx);
  172147. }else{
  172148. int x = 1;
  172149. p->nVertex = nVertex;
  172150. memcpy(p->hdr, a, nByte);
  172151. if( a[0] != *(unsigned char*)&x ){
  172152. int ii;
  172153. for(ii=0; ii<nVertex*2; ii++){
  172154. geopolySwab32((unsigned char*)&p->a[ii]);
  172155. }
  172156. p->hdr[0] ^= 1;
  172157. }
  172158. }
  172159. }
  172160. if( pRc ) *pRc = SQLITE_OK;
  172161. return p;
  172162. }else if( sqlite3_value_type(pVal)==SQLITE_TEXT ){
  172163. const unsigned char *zJson = sqlite3_value_text(pVal);
  172164. if( zJson==0 ){
  172165. if( pRc ) *pRc = SQLITE_NOMEM;
  172166. return 0;
  172167. }
  172168. return geopolyParseJson(zJson, pRc);
  172169. }else{
  172170. if( pRc ) *pRc = SQLITE_ERROR;
  172171. return 0;
  172172. }
  172173. }
  172174. /*
  172175. ** Implementation of the geopoly_blob(X) function.
  172176. **
  172177. ** If the input is a well-formed Geopoly BLOB or JSON string
  172178. ** then return the BLOB representation of the polygon. Otherwise
  172179. ** return NULL.
  172180. */
  172181. static void geopolyBlobFunc(
  172182. sqlite3_context *context,
  172183. int argc,
  172184. sqlite3_value **argv
  172185. ){
  172186. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  172187. if( p ){
  172188. sqlite3_result_blob(context, p->hdr,
  172189. 4+8*p->nVertex, SQLITE_TRANSIENT);
  172190. sqlite3_free(p);
  172191. }
  172192. }
  172193. /*
  172194. ** SQL function: geopoly_json(X)
  172195. **
  172196. ** Interpret X as a polygon and render it as a JSON array
  172197. ** of coordinates. Or, if X is not a valid polygon, return NULL.
  172198. */
  172199. static void geopolyJsonFunc(
  172200. sqlite3_context *context,
  172201. int argc,
  172202. sqlite3_value **argv
  172203. ){
  172204. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  172205. if( p ){
  172206. sqlite3 *db = sqlite3_context_db_handle(context);
  172207. sqlite3_str *x = sqlite3_str_new(db);
  172208. int i;
  172209. sqlite3_str_append(x, "[", 1);
  172210. for(i=0; i<p->nVertex; i++){
  172211. sqlite3_str_appendf(x, "[%!g,%!g],", p->a[i*2], p->a[i*2+1]);
  172212. }
  172213. sqlite3_str_appendf(x, "[%!g,%!g]]", p->a[0], p->a[1]);
  172214. sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
  172215. sqlite3_free(p);
  172216. }
  172217. }
  172218. /*
  172219. ** SQL function: geopoly_svg(X, ....)
  172220. **
  172221. ** Interpret X as a polygon and render it as a SVG <polyline>.
  172222. ** Additional arguments are added as attributes to the <polyline>.
  172223. */
  172224. static void geopolySvgFunc(
  172225. sqlite3_context *context,
  172226. int argc,
  172227. sqlite3_value **argv
  172228. ){
  172229. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  172230. if( p ){
  172231. sqlite3 *db = sqlite3_context_db_handle(context);
  172232. sqlite3_str *x = sqlite3_str_new(db);
  172233. int i;
  172234. char cSep = '\'';
  172235. sqlite3_str_appendf(x, "<polyline points=");
  172236. for(i=0; i<p->nVertex; i++){
  172237. sqlite3_str_appendf(x, "%c%g,%g", cSep, p->a[i*2], p->a[i*2+1]);
  172238. cSep = ' ';
  172239. }
  172240. sqlite3_str_appendf(x, " %g,%g'", p->a[0], p->a[1]);
  172241. for(i=1; i<argc; i++){
  172242. const char *z = (const char*)sqlite3_value_text(argv[i]);
  172243. if( z && z[0] ){
  172244. sqlite3_str_appendf(x, " %s", z);
  172245. }
  172246. }
  172247. sqlite3_str_appendf(x, "></polyline>");
  172248. sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
  172249. sqlite3_free(p);
  172250. }
  172251. }
  172252. /*
  172253. ** SQL Function: geopoly_xform(poly, A, B, C, D, E, F)
  172254. **
  172255. ** Transform and/or translate a polygon as follows:
  172256. **
  172257. ** x1 = A*x0 + B*y0 + E
  172258. ** y1 = C*x0 + D*y0 + F
  172259. **
  172260. ** For a translation:
  172261. **
  172262. ** geopoly_xform(poly, 1, 0, 0, 1, x-offset, y-offset)
  172263. **
  172264. ** Rotate by R around the point (0,0):
  172265. **
  172266. ** geopoly_xform(poly, cos(R), sin(R), -sin(R), cos(R), 0, 0)
  172267. */
  172268. static void geopolyXformFunc(
  172269. sqlite3_context *context,
  172270. int argc,
  172271. sqlite3_value **argv
  172272. ){
  172273. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  172274. double A = sqlite3_value_double(argv[1]);
  172275. double B = sqlite3_value_double(argv[2]);
  172276. double C = sqlite3_value_double(argv[3]);
  172277. double D = sqlite3_value_double(argv[4]);
  172278. double E = sqlite3_value_double(argv[5]);
  172279. double F = sqlite3_value_double(argv[6]);
  172280. GeoCoord x1, y1, x0, y0;
  172281. int ii;
  172282. if( p ){
  172283. for(ii=0; ii<p->nVertex; ii++){
  172284. x0 = p->a[ii*2];
  172285. y0 = p->a[ii*2+1];
  172286. x1 = (GeoCoord)(A*x0 + B*y0 + E);
  172287. y1 = (GeoCoord)(C*x0 + D*y0 + F);
  172288. p->a[ii*2] = x1;
  172289. p->a[ii*2+1] = y1;
  172290. }
  172291. sqlite3_result_blob(context, p->hdr,
  172292. 4+8*p->nVertex, SQLITE_TRANSIENT);
  172293. sqlite3_free(p);
  172294. }
  172295. }
  172296. /*
  172297. ** Compute the area enclosed by the polygon.
  172298. **
  172299. ** This routine can also be used to detect polygons that rotate in
  172300. ** the wrong direction. Polygons are suppose to be counter-clockwise (CCW).
  172301. ** This routine returns a negative value for clockwise (CW) polygons.
  172302. */
  172303. static double geopolyArea(GeoPoly *p){
  172304. double rArea = 0.0;
  172305. int ii;
  172306. for(ii=0; ii<p->nVertex-1; ii++){
  172307. rArea += (p->a[ii*2] - p->a[ii*2+2]) /* (x0 - x1) */
  172308. * (p->a[ii*2+1] + p->a[ii*2+3]) /* (y0 + y1) */
  172309. * 0.5;
  172310. }
  172311. rArea += (p->a[ii*2] - p->a[0]) /* (xN - x0) */
  172312. * (p->a[ii*2+1] + p->a[1]) /* (yN + y0) */
  172313. * 0.5;
  172314. return rArea;
  172315. }
  172316. /*
  172317. ** Implementation of the geopoly_area(X) function.
  172318. **
  172319. ** If the input is a well-formed Geopoly BLOB then return the area
  172320. ** enclosed by the polygon. If the polygon circulates clockwise instead
  172321. ** of counterclockwise (as it should) then return the negative of the
  172322. ** enclosed area. Otherwise return NULL.
  172323. */
  172324. static void geopolyAreaFunc(
  172325. sqlite3_context *context,
  172326. int argc,
  172327. sqlite3_value **argv
  172328. ){
  172329. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  172330. if( p ){
  172331. sqlite3_result_double(context, geopolyArea(p));
  172332. sqlite3_free(p);
  172333. }
  172334. }
  172335. /*
  172336. ** Implementation of the geopoly_ccw(X) function.
  172337. **
  172338. ** If the rotation of polygon X is clockwise (incorrect) instead of
  172339. ** counter-clockwise (the correct winding order according to RFC7946)
  172340. ** then reverse the order of the vertexes in polygon X.
  172341. **
  172342. ** In other words, this routine returns a CCW polygon regardless of the
  172343. ** winding order of its input.
  172344. **
  172345. ** Use this routine to sanitize historical inputs that that sometimes
  172346. ** contain polygons that wind in the wrong direction.
  172347. */
  172348. static void geopolyCcwFunc(
  172349. sqlite3_context *context,
  172350. int argc,
  172351. sqlite3_value **argv
  172352. ){
  172353. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  172354. if( p ){
  172355. if( geopolyArea(p)<0.0 ){
  172356. int ii, jj;
  172357. for(ii=2, jj=p->nVertex*2 - 2; ii<jj; ii+=2, jj-=2){
  172358. GeoCoord t = p->a[ii];
  172359. p->a[ii] = p->a[jj];
  172360. p->a[jj] = t;
  172361. t = p->a[ii+1];
  172362. p->a[ii+1] = p->a[jj+1];
  172363. p->a[jj+1] = t;
  172364. }
  172365. }
  172366. sqlite3_result_blob(context, p->hdr,
  172367. 4+8*p->nVertex, SQLITE_TRANSIENT);
  172368. sqlite3_free(p);
  172369. }
  172370. }
  172371. #define GEOPOLY_PI 3.1415926535897932385
  172372. /* Fast approximation for sine(X) for X between -0.5*pi and 2*pi
  172373. */
  172374. static double geopolySine(double r){
  172375. assert( r>=-0.5*GEOPOLY_PI && r<=2.0*GEOPOLY_PI );
  172376. if( r>=1.5*GEOPOLY_PI ){
  172377. r -= 2.0*GEOPOLY_PI;
  172378. }
  172379. if( r>=0.5*GEOPOLY_PI ){
  172380. return -geopolySine(r-GEOPOLY_PI);
  172381. }else{
  172382. double r2 = r*r;
  172383. double r3 = r2*r;
  172384. double r5 = r3*r2;
  172385. return 0.9996949*r - 0.1656700*r3 + 0.0075134*r5;
  172386. }
  172387. }
  172388. /*
  172389. ** Function: geopoly_regular(X,Y,R,N)
  172390. **
  172391. ** Construct a simple, convex, regular polygon centered at X, Y
  172392. ** with circumradius R and with N sides.
  172393. */
  172394. static void geopolyRegularFunc(
  172395. sqlite3_context *context,
  172396. int argc,
  172397. sqlite3_value **argv
  172398. ){
  172399. double x = sqlite3_value_double(argv[0]);
  172400. double y = sqlite3_value_double(argv[1]);
  172401. double r = sqlite3_value_double(argv[2]);
  172402. int n = sqlite3_value_int(argv[3]);
  172403. int i;
  172404. GeoPoly *p;
  172405. if( n<3 || r<=0.0 ) return;
  172406. if( n>1000 ) n = 1000;
  172407. p = sqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) );
  172408. if( p==0 ){
  172409. sqlite3_result_error_nomem(context);
  172410. return;
  172411. }
  172412. i = 1;
  172413. p->hdr[0] = *(unsigned char*)&i;
  172414. p->hdr[1] = 0;
  172415. p->hdr[2] = (n>>8)&0xff;
  172416. p->hdr[3] = n&0xff;
  172417. for(i=0; i<n; i++){
  172418. double rAngle = 2.0*GEOPOLY_PI*i/n;
  172419. p->a[i*2] = x - r*geopolySine(rAngle-0.5*GEOPOLY_PI);
  172420. p->a[i*2+1] = y + r*geopolySine(rAngle);
  172421. }
  172422. sqlite3_result_blob(context, p->hdr, 4+8*n, SQLITE_TRANSIENT);
  172423. sqlite3_free(p);
  172424. }
  172425. /*
  172426. ** If pPoly is a polygon, compute its bounding box. Then:
  172427. **
  172428. ** (1) if aCoord!=0 store the bounding box in aCoord, returning NULL
  172429. ** (2) otherwise, compute a GeoPoly for the bounding box and return the
  172430. ** new GeoPoly
  172431. **
  172432. ** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from
  172433. ** the bounding box in aCoord and return a pointer to that GeoPoly.
  172434. */
  172435. static GeoPoly *geopolyBBox(
  172436. sqlite3_context *context, /* For recording the error */
  172437. sqlite3_value *pPoly, /* The polygon */
  172438. RtreeCoord *aCoord, /* Results here */
  172439. int *pRc /* Error code here */
  172440. ){
  172441. GeoPoly *pOut = 0;
  172442. GeoPoly *p;
  172443. float mnX, mxX, mnY, mxY;
  172444. if( pPoly==0 && aCoord!=0 ){
  172445. p = 0;
  172446. mnX = aCoord[0].f;
  172447. mxX = aCoord[1].f;
  172448. mnY = aCoord[2].f;
  172449. mxY = aCoord[3].f;
  172450. goto geopolyBboxFill;
  172451. }else{
  172452. p = geopolyFuncParam(context, pPoly, pRc);
  172453. }
  172454. if( p ){
  172455. int ii;
  172456. mnX = mxX = p->a[0];
  172457. mnY = mxY = p->a[1];
  172458. for(ii=1; ii<p->nVertex; ii++){
  172459. double r = p->a[ii*2];
  172460. if( r<mnX ) mnX = (float)r;
  172461. else if( r>mxX ) mxX = (float)r;
  172462. r = p->a[ii*2+1];
  172463. if( r<mnY ) mnY = (float)r;
  172464. else if( r>mxY ) mxY = (float)r;
  172465. }
  172466. if( pRc ) *pRc = SQLITE_OK;
  172467. if( aCoord==0 ){
  172468. geopolyBboxFill:
  172469. pOut = sqlite3_realloc(p, GEOPOLY_SZ(4));
  172470. if( pOut==0 ){
  172471. sqlite3_free(p);
  172472. if( context ) sqlite3_result_error_nomem(context);
  172473. if( pRc ) *pRc = SQLITE_NOMEM;
  172474. return 0;
  172475. }
  172476. pOut->nVertex = 4;
  172477. ii = 1;
  172478. pOut->hdr[0] = *(unsigned char*)&ii;
  172479. pOut->hdr[1] = 0;
  172480. pOut->hdr[2] = 0;
  172481. pOut->hdr[3] = 4;
  172482. pOut->a[0] = mnX;
  172483. pOut->a[1] = mnY;
  172484. pOut->a[2] = mxX;
  172485. pOut->a[3] = mnY;
  172486. pOut->a[4] = mxX;
  172487. pOut->a[5] = mxY;
  172488. pOut->a[6] = mnX;
  172489. pOut->a[7] = mxY;
  172490. }else{
  172491. sqlite3_free(p);
  172492. aCoord[0].f = mnX;
  172493. aCoord[1].f = mxX;
  172494. aCoord[2].f = mnY;
  172495. aCoord[3].f = mxY;
  172496. }
  172497. }
  172498. return pOut;
  172499. }
  172500. /*
  172501. ** Implementation of the geopoly_bbox(X) SQL function.
  172502. */
  172503. static void geopolyBBoxFunc(
  172504. sqlite3_context *context,
  172505. int argc,
  172506. sqlite3_value **argv
  172507. ){
  172508. GeoPoly *p = geopolyBBox(context, argv[0], 0, 0);
  172509. if( p ){
  172510. sqlite3_result_blob(context, p->hdr,
  172511. 4+8*p->nVertex, SQLITE_TRANSIENT);
  172512. sqlite3_free(p);
  172513. }
  172514. }
  172515. /*
  172516. ** State vector for the geopoly_group_bbox() aggregate function.
  172517. */
  172518. typedef struct GeoBBox GeoBBox;
  172519. struct GeoBBox {
  172520. int isInit;
  172521. RtreeCoord a[4];
  172522. };
  172523. /*
  172524. ** Implementation of the geopoly_group_bbox(X) aggregate SQL function.
  172525. */
  172526. static void geopolyBBoxStep(
  172527. sqlite3_context *context,
  172528. int argc,
  172529. sqlite3_value **argv
  172530. ){
  172531. RtreeCoord a[4];
  172532. int rc = SQLITE_OK;
  172533. (void)geopolyBBox(context, argv[0], a, &rc);
  172534. if( rc==SQLITE_OK ){
  172535. GeoBBox *pBBox;
  172536. pBBox = (GeoBBox*)sqlite3_aggregate_context(context, sizeof(*pBBox));
  172537. if( pBBox==0 ) return;
  172538. if( pBBox->isInit==0 ){
  172539. pBBox->isInit = 1;
  172540. memcpy(pBBox->a, a, sizeof(RtreeCoord)*4);
  172541. }else{
  172542. if( a[0].f < pBBox->a[0].f ) pBBox->a[0] = a[0];
  172543. if( a[1].f > pBBox->a[1].f ) pBBox->a[1] = a[1];
  172544. if( a[2].f < pBBox->a[2].f ) pBBox->a[2] = a[2];
  172545. if( a[3].f > pBBox->a[3].f ) pBBox->a[3] = a[3];
  172546. }
  172547. }
  172548. }
  172549. static void geopolyBBoxFinal(
  172550. sqlite3_context *context
  172551. ){
  172552. GeoPoly *p;
  172553. GeoBBox *pBBox;
  172554. pBBox = (GeoBBox*)sqlite3_aggregate_context(context, 0);
  172555. if( pBBox==0 ) return;
  172556. p = geopolyBBox(context, 0, pBBox->a, 0);
  172557. if( p ){
  172558. sqlite3_result_blob(context, p->hdr,
  172559. 4+8*p->nVertex, SQLITE_TRANSIENT);
  172560. sqlite3_free(p);
  172561. }
  172562. }
  172563. /*
  172564. ** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2).
  172565. ** Returns:
  172566. **
  172567. ** +2 x0,y0 is on the line segement
  172568. **
  172569. ** +1 x0,y0 is beneath line segment
  172570. **
  172571. ** 0 x0,y0 is not on or beneath the line segment or the line segment
  172572. ** is vertical and x0,y0 is not on the line segment
  172573. **
  172574. ** The left-most coordinate min(x1,x2) is not considered to be part of
  172575. ** the line segment for the purposes of this analysis.
  172576. */
  172577. static int pointBeneathLine(
  172578. double x0, double y0,
  172579. double x1, double y1,
  172580. double x2, double y2
  172581. ){
  172582. double y;
  172583. if( x0==x1 && y0==y1 ) return 2;
  172584. if( x1<x2 ){
  172585. if( x0<=x1 || x0>x2 ) return 0;
  172586. }else if( x1>x2 ){
  172587. if( x0<=x2 || x0>x1 ) return 0;
  172588. }else{
  172589. /* Vertical line segment */
  172590. if( x0!=x1 ) return 0;
  172591. if( y0<y1 && y0<y2 ) return 0;
  172592. if( y0>y1 && y0>y2 ) return 0;
  172593. return 2;
  172594. }
  172595. y = y1 + (y2-y1)*(x0-x1)/(x2-x1);
  172596. if( y0==y ) return 2;
  172597. if( y0<y ) return 1;
  172598. return 0;
  172599. }
  172600. /*
  172601. ** SQL function: geopoly_contains_point(P,X,Y)
  172602. **
  172603. ** Return +2 if point X,Y is within polygon P.
  172604. ** Return +1 if point X,Y is on the polygon boundary.
  172605. ** Return 0 if point X,Y is outside the polygon
  172606. */
  172607. static void geopolyContainsPointFunc(
  172608. sqlite3_context *context,
  172609. int argc,
  172610. sqlite3_value **argv
  172611. ){
  172612. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  172613. double x0 = sqlite3_value_double(argv[1]);
  172614. double y0 = sqlite3_value_double(argv[2]);
  172615. int v = 0;
  172616. int cnt = 0;
  172617. int ii;
  172618. if( p1==0 ) return;
  172619. for(ii=0; ii<p1->nVertex-1; ii++){
  172620. v = pointBeneathLine(x0,y0,p1->a[ii*2],p1->a[ii*2+1],
  172621. p1->a[ii*2+2],p1->a[ii*2+3]);
  172622. if( v==2 ) break;
  172623. cnt += v;
  172624. }
  172625. if( v!=2 ){
  172626. v = pointBeneathLine(x0,y0,p1->a[ii*2],p1->a[ii*2+1],
  172627. p1->a[0],p1->a[1]);
  172628. }
  172629. if( v==2 ){
  172630. sqlite3_result_int(context, 1);
  172631. }else if( ((v+cnt)&1)==0 ){
  172632. sqlite3_result_int(context, 0);
  172633. }else{
  172634. sqlite3_result_int(context, 2);
  172635. }
  172636. sqlite3_free(p1);
  172637. }
  172638. /* Forward declaration */
  172639. static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2);
  172640. /*
  172641. ** SQL function: geopoly_within(P1,P2)
  172642. **
  172643. ** Return +2 if P1 and P2 are the same polygon
  172644. ** Return +1 if P2 is contained within P1
  172645. ** Return 0 if any part of P2 is on the outside of P1
  172646. **
  172647. */
  172648. static void geopolyWithinFunc(
  172649. sqlite3_context *context,
  172650. int argc,
  172651. sqlite3_value **argv
  172652. ){
  172653. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  172654. GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
  172655. if( p1 && p2 ){
  172656. int x = geopolyOverlap(p1, p2);
  172657. if( x<0 ){
  172658. sqlite3_result_error_nomem(context);
  172659. }else{
  172660. sqlite3_result_int(context, x==2 ? 1 : x==4 ? 2 : 0);
  172661. }
  172662. }
  172663. sqlite3_free(p1);
  172664. sqlite3_free(p2);
  172665. }
  172666. /* Objects used by the overlap algorihm. */
  172667. typedef struct GeoEvent GeoEvent;
  172668. typedef struct GeoSegment GeoSegment;
  172669. typedef struct GeoOverlap GeoOverlap;
  172670. struct GeoEvent {
  172671. double x; /* X coordinate at which event occurs */
  172672. int eType; /* 0 for ADD, 1 for REMOVE */
  172673. GeoSegment *pSeg; /* The segment to be added or removed */
  172674. GeoEvent *pNext; /* Next event in the sorted list */
  172675. };
  172676. struct GeoSegment {
  172677. double C, B; /* y = C*x + B */
  172678. double y; /* Current y value */
  172679. float y0; /* Initial y value */
  172680. unsigned char side; /* 1 for p1, 2 for p2 */
  172681. unsigned int idx; /* Which segment within the side */
  172682. GeoSegment *pNext; /* Next segment in a list sorted by y */
  172683. };
  172684. struct GeoOverlap {
  172685. GeoEvent *aEvent; /* Array of all events */
  172686. GeoSegment *aSegment; /* Array of all segments */
  172687. int nEvent; /* Number of events */
  172688. int nSegment; /* Number of segments */
  172689. };
  172690. /*
  172691. ** Add a single segment and its associated events.
  172692. */
  172693. static void geopolyAddOneSegment(
  172694. GeoOverlap *p,
  172695. GeoCoord x0,
  172696. GeoCoord y0,
  172697. GeoCoord x1,
  172698. GeoCoord y1,
  172699. unsigned char side,
  172700. unsigned int idx
  172701. ){
  172702. GeoSegment *pSeg;
  172703. GeoEvent *pEvent;
  172704. if( x0==x1 ) return; /* Ignore vertical segments */
  172705. if( x0>x1 ){
  172706. GeoCoord t = x0;
  172707. x0 = x1;
  172708. x1 = t;
  172709. t = y0;
  172710. y0 = y1;
  172711. y1 = t;
  172712. }
  172713. pSeg = p->aSegment + p->nSegment;
  172714. p->nSegment++;
  172715. pSeg->C = (y1-y0)/(x1-x0);
  172716. pSeg->B = y1 - x1*pSeg->C;
  172717. pSeg->y0 = y0;
  172718. pSeg->side = side;
  172719. pSeg->idx = idx;
  172720. pEvent = p->aEvent + p->nEvent;
  172721. p->nEvent++;
  172722. pEvent->x = x0;
  172723. pEvent->eType = 0;
  172724. pEvent->pSeg = pSeg;
  172725. pEvent = p->aEvent + p->nEvent;
  172726. p->nEvent++;
  172727. pEvent->x = x1;
  172728. pEvent->eType = 1;
  172729. pEvent->pSeg = pSeg;
  172730. }
  172731. /*
  172732. ** Insert all segments and events for polygon pPoly.
  172733. */
  172734. static void geopolyAddSegments(
  172735. GeoOverlap *p, /* Add segments to this Overlap object */
  172736. GeoPoly *pPoly, /* Take all segments from this polygon */
  172737. unsigned char side /* The side of pPoly */
  172738. ){
  172739. unsigned int i;
  172740. GeoCoord *x;
  172741. for(i=0; i<(unsigned)pPoly->nVertex-1; i++){
  172742. x = pPoly->a + (i*2);
  172743. geopolyAddOneSegment(p, x[0], x[1], x[2], x[3], side, i);
  172744. }
  172745. x = pPoly->a + (i*2);
  172746. geopolyAddOneSegment(p, x[0], x[1], pPoly->a[0], pPoly->a[1], side, i);
  172747. }
  172748. /*
  172749. ** Merge two lists of sorted events by X coordinate
  172750. */
  172751. static GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){
  172752. GeoEvent head, *pLast;
  172753. head.pNext = 0;
  172754. pLast = &head;
  172755. while( pRight && pLeft ){
  172756. if( pRight->x <= pLeft->x ){
  172757. pLast->pNext = pRight;
  172758. pLast = pRight;
  172759. pRight = pRight->pNext;
  172760. }else{
  172761. pLast->pNext = pLeft;
  172762. pLast = pLeft;
  172763. pLeft = pLeft->pNext;
  172764. }
  172765. }
  172766. pLast->pNext = pRight ? pRight : pLeft;
  172767. return head.pNext;
  172768. }
  172769. /*
  172770. ** Sort an array of nEvent event objects into a list.
  172771. */
  172772. static GeoEvent *geopolySortEventsByX(GeoEvent *aEvent, int nEvent){
  172773. int mx = 0;
  172774. int i, j;
  172775. GeoEvent *p;
  172776. GeoEvent *a[50];
  172777. for(i=0; i<nEvent; i++){
  172778. p = &aEvent[i];
  172779. p->pNext = 0;
  172780. for(j=0; j<mx && a[j]; j++){
  172781. p = geopolyEventMerge(a[j], p);
  172782. a[j] = 0;
  172783. }
  172784. a[j] = p;
  172785. if( j>=mx ) mx = j+1;
  172786. }
  172787. p = 0;
  172788. for(i=0; i<mx; i++){
  172789. p = geopolyEventMerge(a[i], p);
  172790. }
  172791. return p;
  172792. }
  172793. /*
  172794. ** Merge two lists of sorted segments by Y, and then by C.
  172795. */
  172796. static GeoSegment *geopolySegmentMerge(GeoSegment *pLeft, GeoSegment *pRight){
  172797. GeoSegment head, *pLast;
  172798. head.pNext = 0;
  172799. pLast = &head;
  172800. while( pRight && pLeft ){
  172801. double r = pRight->y - pLeft->y;
  172802. if( r==0.0 ) r = pRight->C - pLeft->C;
  172803. if( r<0.0 ){
  172804. pLast->pNext = pRight;
  172805. pLast = pRight;
  172806. pRight = pRight->pNext;
  172807. }else{
  172808. pLast->pNext = pLeft;
  172809. pLast = pLeft;
  172810. pLeft = pLeft->pNext;
  172811. }
  172812. }
  172813. pLast->pNext = pRight ? pRight : pLeft;
  172814. return head.pNext;
  172815. }
  172816. /*
  172817. ** Sort a list of GeoSegments in order of increasing Y and in the event of
  172818. ** a tie, increasing C (slope).
  172819. */
  172820. static GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){
  172821. int mx = 0;
  172822. int i;
  172823. GeoSegment *p;
  172824. GeoSegment *a[50];
  172825. while( pList ){
  172826. p = pList;
  172827. pList = pList->pNext;
  172828. p->pNext = 0;
  172829. for(i=0; i<mx && a[i]; i++){
  172830. p = geopolySegmentMerge(a[i], p);
  172831. a[i] = 0;
  172832. }
  172833. a[i] = p;
  172834. if( i>=mx ) mx = i+1;
  172835. }
  172836. p = 0;
  172837. for(i=0; i<mx; i++){
  172838. p = geopolySegmentMerge(a[i], p);
  172839. }
  172840. return p;
  172841. }
  172842. /*
  172843. ** Determine the overlap between two polygons
  172844. */
  172845. static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){
  172846. int nVertex = p1->nVertex + p2->nVertex + 2;
  172847. GeoOverlap *p;
  172848. int nByte;
  172849. GeoEvent *pThisEvent;
  172850. double rX;
  172851. int rc = 0;
  172852. int needSort = 0;
  172853. GeoSegment *pActive = 0;
  172854. GeoSegment *pSeg;
  172855. unsigned char aOverlap[4];
  172856. nByte = sizeof(GeoEvent)*nVertex*2
  172857. + sizeof(GeoSegment)*nVertex
  172858. + sizeof(GeoOverlap);
  172859. p = sqlite3_malloc( nByte );
  172860. if( p==0 ) return -1;
  172861. p->aEvent = (GeoEvent*)&p[1];
  172862. p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2];
  172863. p->nEvent = p->nSegment = 0;
  172864. geopolyAddSegments(p, p1, 1);
  172865. geopolyAddSegments(p, p2, 2);
  172866. pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent);
  172867. rX = pThisEvent->x==0.0 ? -1.0 : 0.0;
  172868. memset(aOverlap, 0, sizeof(aOverlap));
  172869. while( pThisEvent ){
  172870. if( pThisEvent->x!=rX ){
  172871. GeoSegment *pPrev = 0;
  172872. int iMask = 0;
  172873. GEODEBUG(("Distinct X: %g\n", pThisEvent->x));
  172874. rX = pThisEvent->x;
  172875. if( needSort ){
  172876. GEODEBUG(("SORT\n"));
  172877. pActive = geopolySortSegmentsByYAndC(pActive);
  172878. needSort = 0;
  172879. }
  172880. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  172881. if( pPrev ){
  172882. if( pPrev->y!=pSeg->y ){
  172883. GEODEBUG(("MASK: %d\n", iMask));
  172884. aOverlap[iMask] = 1;
  172885. }
  172886. }
  172887. iMask ^= pSeg->side;
  172888. pPrev = pSeg;
  172889. }
  172890. pPrev = 0;
  172891. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  172892. double y = pSeg->C*rX + pSeg->B;
  172893. GEODEBUG(("Segment %d.%d %g->%g\n", pSeg->side, pSeg->idx, pSeg->y, y));
  172894. pSeg->y = y;
  172895. if( pPrev ){
  172896. if( pPrev->y>pSeg->y && pPrev->side!=pSeg->side ){
  172897. rc = 1;
  172898. GEODEBUG(("Crossing: %d.%d and %d.%d\n",
  172899. pPrev->side, pPrev->idx,
  172900. pSeg->side, pSeg->idx));
  172901. goto geopolyOverlapDone;
  172902. }else if( pPrev->y!=pSeg->y ){
  172903. GEODEBUG(("MASK: %d\n", iMask));
  172904. aOverlap[iMask] = 1;
  172905. }
  172906. }
  172907. iMask ^= pSeg->side;
  172908. pPrev = pSeg;
  172909. }
  172910. }
  172911. GEODEBUG(("%s %d.%d C=%g B=%g\n",
  172912. pThisEvent->eType ? "RM " : "ADD",
  172913. pThisEvent->pSeg->side, pThisEvent->pSeg->idx,
  172914. pThisEvent->pSeg->C,
  172915. pThisEvent->pSeg->B));
  172916. if( pThisEvent->eType==0 ){
  172917. /* Add a segment */
  172918. pSeg = pThisEvent->pSeg;
  172919. pSeg->y = pSeg->y0;
  172920. pSeg->pNext = pActive;
  172921. pActive = pSeg;
  172922. needSort = 1;
  172923. }else{
  172924. /* Remove a segment */
  172925. if( pActive==pThisEvent->pSeg ){
  172926. pActive = pActive->pNext;
  172927. }else{
  172928. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  172929. if( pSeg->pNext==pThisEvent->pSeg ){
  172930. pSeg->pNext = pSeg->pNext->pNext;
  172931. break;
  172932. }
  172933. }
  172934. }
  172935. }
  172936. pThisEvent = pThisEvent->pNext;
  172937. }
  172938. if( aOverlap[3]==0 ){
  172939. rc = 0;
  172940. }else if( aOverlap[1]!=0 && aOverlap[2]==0 ){
  172941. rc = 3;
  172942. }else if( aOverlap[1]==0 && aOverlap[2]!=0 ){
  172943. rc = 2;
  172944. }else if( aOverlap[1]==0 && aOverlap[2]==0 ){
  172945. rc = 4;
  172946. }else{
  172947. rc = 1;
  172948. }
  172949. geopolyOverlapDone:
  172950. sqlite3_free(p);
  172951. return rc;
  172952. }
  172953. /*
  172954. ** SQL function: geopoly_overlap(P1,P2)
  172955. **
  172956. ** Determine whether or not P1 and P2 overlap. Return value:
  172957. **
  172958. ** 0 The two polygons are disjoint
  172959. ** 1 They overlap
  172960. ** 2 P1 is completely contained within P2
  172961. ** 3 P2 is completely contained within P1
  172962. ** 4 P1 and P2 are the same polygon
  172963. ** NULL Either P1 or P2 or both are not valid polygons
  172964. */
  172965. static void geopolyOverlapFunc(
  172966. sqlite3_context *context,
  172967. int argc,
  172968. sqlite3_value **argv
  172969. ){
  172970. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  172971. GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
  172972. if( p1 && p2 ){
  172973. int x = geopolyOverlap(p1, p2);
  172974. if( x<0 ){
  172975. sqlite3_result_error_nomem(context);
  172976. }else{
  172977. sqlite3_result_int(context, x);
  172978. }
  172979. }
  172980. sqlite3_free(p1);
  172981. sqlite3_free(p2);
  172982. }
  172983. /*
  172984. ** Enable or disable debugging output
  172985. */
  172986. static void geopolyDebugFunc(
  172987. sqlite3_context *context,
  172988. int argc,
  172989. sqlite3_value **argv
  172990. ){
  172991. #ifdef GEOPOLY_ENABLE_DEBUG
  172992. geo_debug = sqlite3_value_int(argv[0]);
  172993. #endif
  172994. }
  172995. /*
  172996. ** This function is the implementation of both the xConnect and xCreate
  172997. ** methods of the geopoly virtual table.
  172998. **
  172999. ** argv[0] -> module name
  173000. ** argv[1] -> database name
  173001. ** argv[2] -> table name
  173002. ** argv[...] -> column names...
  173003. */
  173004. static int geopolyInit(
  173005. sqlite3 *db, /* Database connection */
  173006. void *pAux, /* One of the RTREE_COORD_* constants */
  173007. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  173008. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  173009. char **pzErr, /* OUT: Error message, if any */
  173010. int isCreate /* True for xCreate, false for xConnect */
  173011. ){
  173012. int rc = SQLITE_OK;
  173013. Rtree *pRtree;
  173014. int nDb; /* Length of string argv[1] */
  173015. int nName; /* Length of string argv[2] */
  173016. sqlite3_str *pSql;
  173017. char *zSql;
  173018. int ii;
  173019. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  173020. /* Allocate the sqlite3_vtab structure */
  173021. nDb = (int)strlen(argv[1]);
  173022. nName = (int)strlen(argv[2]);
  173023. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  173024. if( !pRtree ){
  173025. return SQLITE_NOMEM;
  173026. }
  173027. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  173028. pRtree->nBusy = 1;
  173029. pRtree->base.pModule = &rtreeModule;
  173030. pRtree->zDb = (char *)&pRtree[1];
  173031. pRtree->zName = &pRtree->zDb[nDb+1];
  173032. pRtree->eCoordType = RTREE_COORD_REAL32;
  173033. pRtree->nDim = 2;
  173034. pRtree->nDim2 = 4;
  173035. memcpy(pRtree->zDb, argv[1], nDb);
  173036. memcpy(pRtree->zName, argv[2], nName);
  173037. /* Create/Connect to the underlying relational database schema. If
  173038. ** that is successful, call sqlite3_declare_vtab() to configure
  173039. ** the r-tree table schema.
  173040. */
  173041. pSql = sqlite3_str_new(db);
  173042. sqlite3_str_appendf(pSql, "CREATE TABLE x(_shape");
  173043. pRtree->nAux = 1; /* Add one for _shape */
  173044. pRtree->nAuxNotNull = 1; /* The _shape column is always not-null */
  173045. for(ii=3; ii<argc; ii++){
  173046. pRtree->nAux++;
  173047. sqlite3_str_appendf(pSql, ",%s", argv[ii]);
  173048. }
  173049. sqlite3_str_appendf(pSql, ");");
  173050. zSql = sqlite3_str_finish(pSql);
  173051. if( !zSql ){
  173052. rc = SQLITE_NOMEM;
  173053. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  173054. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  173055. }
  173056. sqlite3_free(zSql);
  173057. if( rc ) goto geopolyInit_fail;
  173058. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  173059. /* Figure out the node size to use. */
  173060. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  173061. if( rc ) goto geopolyInit_fail;
  173062. rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
  173063. if( rc ){
  173064. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  173065. goto geopolyInit_fail;
  173066. }
  173067. *ppVtab = (sqlite3_vtab *)pRtree;
  173068. return SQLITE_OK;
  173069. geopolyInit_fail:
  173070. if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
  173071. assert( *ppVtab==0 );
  173072. assert( pRtree->nBusy==1 );
  173073. rtreeRelease(pRtree);
  173074. return rc;
  173075. }
  173076. /*
  173077. ** GEOPOLY virtual table module xCreate method.
  173078. */
  173079. static int geopolyCreate(
  173080. sqlite3 *db,
  173081. void *pAux,
  173082. int argc, const char *const*argv,
  173083. sqlite3_vtab **ppVtab,
  173084. char **pzErr
  173085. ){
  173086. return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  173087. }
  173088. /*
  173089. ** GEOPOLY virtual table module xConnect method.
  173090. */
  173091. static int geopolyConnect(
  173092. sqlite3 *db,
  173093. void *pAux,
  173094. int argc, const char *const*argv,
  173095. sqlite3_vtab **ppVtab,
  173096. char **pzErr
  173097. ){
  173098. return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  173099. }
  173100. /*
  173101. ** GEOPOLY virtual table module xFilter method.
  173102. **
  173103. ** Query plans:
  173104. **
  173105. ** 1 rowid lookup
  173106. ** 2 search for objects overlapping the same bounding box
  173107. ** that contains polygon argv[0]
  173108. ** 3 search for objects overlapping the same bounding box
  173109. ** that contains polygon argv[0]
  173110. ** 4 full table scan
  173111. */
  173112. static int geopolyFilter(
  173113. sqlite3_vtab_cursor *pVtabCursor, /* The cursor to initialize */
  173114. int idxNum, /* Query plan */
  173115. const char *idxStr, /* Not Used */
  173116. int argc, sqlite3_value **argv /* Parameters to the query plan */
  173117. ){
  173118. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  173119. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  173120. RtreeNode *pRoot = 0;
  173121. int rc = SQLITE_OK;
  173122. int iCell = 0;
  173123. sqlite3_stmt *pStmt;
  173124. rtreeReference(pRtree);
  173125. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  173126. freeCursorConstraints(pCsr);
  173127. sqlite3_free(pCsr->aPoint);
  173128. pStmt = pCsr->pReadAux;
  173129. memset(pCsr, 0, sizeof(RtreeCursor));
  173130. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  173131. pCsr->pReadAux = pStmt;
  173132. pCsr->iStrategy = idxNum;
  173133. if( idxNum==1 ){
  173134. /* Special case - lookup by rowid. */
  173135. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  173136. RtreeSearchPoint *p; /* Search point for the leaf */
  173137. i64 iRowid = sqlite3_value_int64(argv[0]);
  173138. i64 iNode = 0;
  173139. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  173140. if( rc==SQLITE_OK && pLeaf!=0 ){
  173141. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  173142. assert( p!=0 ); /* Always returns pCsr->sPoint */
  173143. pCsr->aNode[0] = pLeaf;
  173144. p->id = iNode;
  173145. p->eWithin = PARTLY_WITHIN;
  173146. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  173147. p->iCell = (u8)iCell;
  173148. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  173149. }else{
  173150. pCsr->atEOF = 1;
  173151. }
  173152. }else{
  173153. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  173154. ** with the configured constraints.
  173155. */
  173156. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  173157. if( rc==SQLITE_OK && idxNum<=3 ){
  173158. RtreeCoord bbox[4];
  173159. RtreeConstraint *p;
  173160. assert( argc==1 );
  173161. geopolyBBox(0, argv[0], bbox, &rc);
  173162. if( rc ){
  173163. goto geopoly_filter_end;
  173164. }
  173165. pCsr->aConstraint = p = sqlite3_malloc(sizeof(RtreeConstraint)*4);
  173166. pCsr->nConstraint = 4;
  173167. if( p==0 ){
  173168. rc = SQLITE_NOMEM;
  173169. }else{
  173170. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*4);
  173171. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  173172. if( idxNum==2 ){
  173173. /* Overlap query */
  173174. p->op = 'B';
  173175. p->iCoord = 0;
  173176. p->u.rValue = bbox[1].f;
  173177. p++;
  173178. p->op = 'D';
  173179. p->iCoord = 1;
  173180. p->u.rValue = bbox[0].f;
  173181. p++;
  173182. p->op = 'B';
  173183. p->iCoord = 2;
  173184. p->u.rValue = bbox[3].f;
  173185. p++;
  173186. p->op = 'D';
  173187. p->iCoord = 3;
  173188. p->u.rValue = bbox[2].f;
  173189. }else{
  173190. /* Within query */
  173191. p->op = 'D';
  173192. p->iCoord = 0;
  173193. p->u.rValue = bbox[0].f;
  173194. p++;
  173195. p->op = 'B';
  173196. p->iCoord = 1;
  173197. p->u.rValue = bbox[1].f;
  173198. p++;
  173199. p->op = 'D';
  173200. p->iCoord = 2;
  173201. p->u.rValue = bbox[2].f;
  173202. p++;
  173203. p->op = 'B';
  173204. p->iCoord = 3;
  173205. p->u.rValue = bbox[3].f;
  173206. }
  173207. }
  173208. }
  173209. if( rc==SQLITE_OK ){
  173210. RtreeSearchPoint *pNew;
  173211. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  173212. if( pNew==0 ){
  173213. rc = SQLITE_NOMEM;
  173214. goto geopoly_filter_end;
  173215. }
  173216. pNew->id = 1;
  173217. pNew->iCell = 0;
  173218. pNew->eWithin = PARTLY_WITHIN;
  173219. assert( pCsr->bPoint==1 );
  173220. pCsr->aNode[0] = pRoot;
  173221. pRoot = 0;
  173222. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  173223. rc = rtreeStepToLeaf(pCsr);
  173224. }
  173225. }
  173226. geopoly_filter_end:
  173227. nodeRelease(pRtree, pRoot);
  173228. rtreeRelease(pRtree);
  173229. return rc;
  173230. }
  173231. /*
  173232. ** Rtree virtual table module xBestIndex method. There are three
  173233. ** table scan strategies to choose from (in order from most to
  173234. ** least desirable):
  173235. **
  173236. ** idxNum idxStr Strategy
  173237. ** ------------------------------------------------
  173238. ** 1 "rowid" Direct lookup by rowid.
  173239. ** 2 "rtree" R-tree overlap query using geopoly_overlap()
  173240. ** 3 "rtree" R-tree within query using geopoly_within()
  173241. ** 4 "fullscan" full-table scan.
  173242. ** ------------------------------------------------
  173243. */
  173244. static int geopolyBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  173245. int ii;
  173246. int iRowidTerm = -1;
  173247. int iFuncTerm = -1;
  173248. int idxNum = 0;
  173249. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  173250. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  173251. if( !p->usable ) continue;
  173252. if( p->iColumn<0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  173253. iRowidTerm = ii;
  173254. break;
  173255. }
  173256. if( p->iColumn==0 && p->op>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
  173257. /* p->op==SQLITE_INDEX_CONSTRAINT_FUNCTION for geopoly_overlap()
  173258. ** p->op==(SQLITE_INDEX_CONTRAINT_FUNCTION+1) for geopoly_within().
  173259. ** See geopolyFindFunction() */
  173260. iFuncTerm = ii;
  173261. idxNum = p->op - SQLITE_INDEX_CONSTRAINT_FUNCTION + 2;
  173262. }
  173263. }
  173264. if( iRowidTerm>=0 ){
  173265. pIdxInfo->idxNum = 1;
  173266. pIdxInfo->idxStr = "rowid";
  173267. pIdxInfo->aConstraintUsage[iRowidTerm].argvIndex = 1;
  173268. pIdxInfo->aConstraintUsage[iRowidTerm].omit = 1;
  173269. pIdxInfo->estimatedCost = 30.0;
  173270. pIdxInfo->estimatedRows = 1;
  173271. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  173272. return SQLITE_OK;
  173273. }
  173274. if( iFuncTerm>=0 ){
  173275. pIdxInfo->idxNum = idxNum;
  173276. pIdxInfo->idxStr = "rtree";
  173277. pIdxInfo->aConstraintUsage[iFuncTerm].argvIndex = 1;
  173278. pIdxInfo->aConstraintUsage[iFuncTerm].omit = 0;
  173279. pIdxInfo->estimatedCost = 300.0;
  173280. pIdxInfo->estimatedRows = 10;
  173281. return SQLITE_OK;
  173282. }
  173283. pIdxInfo->idxNum = 4;
  173284. pIdxInfo->idxStr = "fullscan";
  173285. pIdxInfo->estimatedCost = 3000000.0;
  173286. pIdxInfo->estimatedRows = 100000;
  173287. return SQLITE_OK;
  173288. }
  173289. /*
  173290. ** GEOPOLY virtual table module xColumn method.
  173291. */
  173292. static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  173293. Rtree *pRtree = (Rtree *)cur->pVtab;
  173294. RtreeCursor *pCsr = (RtreeCursor *)cur;
  173295. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  173296. int rc = SQLITE_OK;
  173297. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  173298. if( rc ) return rc;
  173299. if( p==0 ) return SQLITE_OK;
  173300. if( i==0 && sqlite3_vtab_nochange(ctx) ) return SQLITE_OK;
  173301. if( i<=pRtree->nAux ){
  173302. if( !pCsr->bAuxValid ){
  173303. if( pCsr->pReadAux==0 ){
  173304. rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
  173305. &pCsr->pReadAux, 0);
  173306. if( rc ) return rc;
  173307. }
  173308. sqlite3_bind_int64(pCsr->pReadAux, 1,
  173309. nodeGetRowid(pRtree, pNode, p->iCell));
  173310. rc = sqlite3_step(pCsr->pReadAux);
  173311. if( rc==SQLITE_ROW ){
  173312. pCsr->bAuxValid = 1;
  173313. }else{
  173314. sqlite3_reset(pCsr->pReadAux);
  173315. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  173316. return rc;
  173317. }
  173318. }
  173319. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pReadAux, i+2));
  173320. }
  173321. return SQLITE_OK;
  173322. }
  173323. /*
  173324. ** The xUpdate method for GEOPOLY module virtual tables.
  173325. **
  173326. ** For DELETE:
  173327. **
  173328. ** argv[0] = the rowid to be deleted
  173329. **
  173330. ** For INSERT:
  173331. **
  173332. ** argv[0] = SQL NULL
  173333. ** argv[1] = rowid to insert, or an SQL NULL to select automatically
  173334. ** argv[2] = _shape column
  173335. ** argv[3] = first application-defined column....
  173336. **
  173337. ** For UPDATE:
  173338. **
  173339. ** argv[0] = rowid to modify. Never NULL
  173340. ** argv[1] = rowid after the change. Never NULL
  173341. ** argv[2] = new value for _shape
  173342. ** argv[3] = new value for first application-defined column....
  173343. */
  173344. static int geopolyUpdate(
  173345. sqlite3_vtab *pVtab,
  173346. int nData,
  173347. sqlite3_value **aData,
  173348. sqlite_int64 *pRowid
  173349. ){
  173350. Rtree *pRtree = (Rtree *)pVtab;
  173351. int rc = SQLITE_OK;
  173352. RtreeCell cell; /* New cell to insert if nData>1 */
  173353. i64 oldRowid; /* The old rowid */
  173354. int oldRowidValid; /* True if oldRowid is valid */
  173355. i64 newRowid; /* The new rowid */
  173356. int newRowidValid; /* True if newRowid is valid */
  173357. int coordChange = 0; /* Change in coordinates */
  173358. if( pRtree->nNodeRef ){
  173359. /* Unable to write to the btree while another cursor is reading from it,
  173360. ** since the write might do a rebalance which would disrupt the read
  173361. ** cursor. */
  173362. return SQLITE_LOCKED_VTAB;
  173363. }
  173364. rtreeReference(pRtree);
  173365. assert(nData>=1);
  173366. oldRowidValid = sqlite3_value_type(aData[0])!=SQLITE_NULL;;
  173367. oldRowid = oldRowidValid ? sqlite3_value_int64(aData[0]) : 0;
  173368. newRowidValid = nData>1 && sqlite3_value_type(aData[1])!=SQLITE_NULL;
  173369. newRowid = newRowidValid ? sqlite3_value_int64(aData[1]) : 0;
  173370. cell.iRowid = newRowid;
  173371. if( nData>1 /* not a DELETE */
  173372. && (!oldRowidValid /* INSERT */
  173373. || !sqlite3_value_nochange(aData[2]) /* UPDATE _shape */
  173374. || oldRowid!=newRowid) /* Rowid change */
  173375. ){
  173376. geopolyBBox(0, aData[2], cell.aCoord, &rc);
  173377. if( rc ){
  173378. if( rc==SQLITE_ERROR ){
  173379. pVtab->zErrMsg =
  173380. sqlite3_mprintf("_shape does not contain a valid polygon");
  173381. }
  173382. goto geopoly_update_end;
  173383. }
  173384. coordChange = 1;
  173385. /* If a rowid value was supplied, check if it is already present in
  173386. ** the table. If so, the constraint has failed. */
  173387. if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){
  173388. int steprc;
  173389. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  173390. steprc = sqlite3_step(pRtree->pReadRowid);
  173391. rc = sqlite3_reset(pRtree->pReadRowid);
  173392. if( SQLITE_ROW==steprc ){
  173393. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  173394. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  173395. }else{
  173396. rc = rtreeConstraintError(pRtree, 0);
  173397. }
  173398. }
  173399. }
  173400. }
  173401. /* If aData[0] is not an SQL NULL value, it is the rowid of a
  173402. ** record to delete from the r-tree table. The following block does
  173403. ** just that.
  173404. */
  173405. if( rc==SQLITE_OK && (nData==1 || (coordChange && oldRowidValid)) ){
  173406. rc = rtreeDeleteRowid(pRtree, oldRowid);
  173407. }
  173408. /* If the aData[] array contains more than one element, elements
  173409. ** (aData[2]..aData[argc-1]) contain a new record to insert into
  173410. ** the r-tree structure.
  173411. */
  173412. if( rc==SQLITE_OK && nData>1 && coordChange ){
  173413. /* Insert the new record into the r-tree */
  173414. RtreeNode *pLeaf = 0;
  173415. if( !newRowidValid ){
  173416. rc = rtreeNewRowid(pRtree, &cell.iRowid);
  173417. }
  173418. *pRowid = cell.iRowid;
  173419. if( rc==SQLITE_OK ){
  173420. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  173421. }
  173422. if( rc==SQLITE_OK ){
  173423. int rc2;
  173424. pRtree->iReinsertHeight = -1;
  173425. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  173426. rc2 = nodeRelease(pRtree, pLeaf);
  173427. if( rc==SQLITE_OK ){
  173428. rc = rc2;
  173429. }
  173430. }
  173431. }
  173432. /* Change the data */
  173433. if( rc==SQLITE_OK && nData>1 ){
  173434. sqlite3_stmt *pUp = pRtree->pWriteAux;
  173435. int jj;
  173436. int nChange = 0;
  173437. sqlite3_bind_int64(pUp, 1, cell.iRowid);
  173438. assert( pRtree->nAux>=1 );
  173439. if( sqlite3_value_nochange(aData[2]) ){
  173440. sqlite3_bind_null(pUp, 2);
  173441. }else{
  173442. GeoPoly *p = 0;
  173443. if( sqlite3_value_type(aData[2])==SQLITE_TEXT
  173444. && (p = geopolyFuncParam(0, aData[2], &rc))!=0
  173445. && rc==SQLITE_OK
  173446. ){
  173447. sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT);
  173448. }else{
  173449. sqlite3_bind_value(pUp, 2, aData[2]);
  173450. }
  173451. sqlite3_free(p);
  173452. nChange = 1;
  173453. }
  173454. for(jj=1; jj<pRtree->nAux; jj++){
  173455. nChange++;
  173456. sqlite3_bind_value(pUp, jj+2, aData[jj+2]);
  173457. }
  173458. if( nChange ){
  173459. sqlite3_step(pUp);
  173460. rc = sqlite3_reset(pUp);
  173461. }
  173462. }
  173463. geopoly_update_end:
  173464. rtreeRelease(pRtree);
  173465. return rc;
  173466. }
  173467. /*
  173468. ** Report that geopoly_overlap() is an overloaded function suitable
  173469. ** for use in xBestIndex.
  173470. */
  173471. static int geopolyFindFunction(
  173472. sqlite3_vtab *pVtab,
  173473. int nArg,
  173474. const char *zName,
  173475. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  173476. void **ppArg
  173477. ){
  173478. if( sqlite3_stricmp(zName, "geopoly_overlap")==0 ){
  173479. *pxFunc = geopolyOverlapFunc;
  173480. *ppArg = 0;
  173481. return SQLITE_INDEX_CONSTRAINT_FUNCTION;
  173482. }
  173483. if( sqlite3_stricmp(zName, "geopoly_within")==0 ){
  173484. *pxFunc = geopolyWithinFunc;
  173485. *ppArg = 0;
  173486. return SQLITE_INDEX_CONSTRAINT_FUNCTION+1;
  173487. }
  173488. return 0;
  173489. }
  173490. static sqlite3_module geopolyModule = {
  173491. 3, /* iVersion */
  173492. geopolyCreate, /* xCreate - create a table */
  173493. geopolyConnect, /* xConnect - connect to an existing table */
  173494. geopolyBestIndex, /* xBestIndex - Determine search strategy */
  173495. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  173496. rtreeDestroy, /* xDestroy - Drop a table */
  173497. rtreeOpen, /* xOpen - open a cursor */
  173498. rtreeClose, /* xClose - close a cursor */
  173499. geopolyFilter, /* xFilter - configure scan constraints */
  173500. rtreeNext, /* xNext - advance a cursor */
  173501. rtreeEof, /* xEof */
  173502. geopolyColumn, /* xColumn - read data */
  173503. rtreeRowid, /* xRowid - read data */
  173504. geopolyUpdate, /* xUpdate - write data */
  173505. rtreeBeginTransaction, /* xBegin - begin transaction */
  173506. rtreeEndTransaction, /* xSync - sync transaction */
  173507. rtreeEndTransaction, /* xCommit - commit transaction */
  173508. rtreeEndTransaction, /* xRollback - rollback transaction */
  173509. geopolyFindFunction, /* xFindFunction - function overloading */
  173510. rtreeRename, /* xRename - rename the table */
  173511. rtreeSavepoint, /* xSavepoint */
  173512. 0, /* xRelease */
  173513. 0, /* xRollbackTo */
  173514. rtreeShadowName /* xShadowName */
  173515. };
  173516. static int sqlite3_geopoly_init(sqlite3 *db){
  173517. int rc = SQLITE_OK;
  173518. static const struct {
  173519. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  173520. signed char nArg;
  173521. unsigned char bPure;
  173522. const char *zName;
  173523. } aFunc[] = {
  173524. { geopolyAreaFunc, 1, 1, "geopoly_area" },
  173525. { geopolyBlobFunc, 1, 1, "geopoly_blob" },
  173526. { geopolyJsonFunc, 1, 1, "geopoly_json" },
  173527. { geopolySvgFunc, -1, 1, "geopoly_svg" },
  173528. { geopolyWithinFunc, 2, 1, "geopoly_within" },
  173529. { geopolyContainsPointFunc, 3, 1, "geopoly_contains_point" },
  173530. { geopolyOverlapFunc, 2, 1, "geopoly_overlap" },
  173531. { geopolyDebugFunc, 1, 0, "geopoly_debug" },
  173532. { geopolyBBoxFunc, 1, 1, "geopoly_bbox" },
  173533. { geopolyXformFunc, 7, 1, "geopoly_xform" },
  173534. { geopolyRegularFunc, 4, 1, "geopoly_regular" },
  173535. { geopolyCcwFunc, 1, 1, "geopoly_ccw" },
  173536. };
  173537. static const struct {
  173538. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  173539. void (*xFinal)(sqlite3_context*);
  173540. const char *zName;
  173541. } aAgg[] = {
  173542. { geopolyBBoxStep, geopolyBBoxFinal, "geopoly_group_bbox" },
  173543. };
  173544. int i;
  173545. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  173546. int enc = aFunc[i].bPure ? SQLITE_UTF8|SQLITE_DETERMINISTIC : SQLITE_UTF8;
  173547. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  173548. enc, 0,
  173549. aFunc[i].xFunc, 0, 0);
  173550. }
  173551. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  173552. rc = sqlite3_create_function(db, aAgg[i].zName, 1, SQLITE_UTF8, 0,
  173553. 0, aAgg[i].xStep, aAgg[i].xFinal);
  173554. }
  173555. if( rc==SQLITE_OK ){
  173556. rc = sqlite3_create_module_v2(db, "geopoly", &geopolyModule, 0, 0);
  173557. }
  173558. return rc;
  173559. }
  173560. /************** End of geopoly.c *********************************************/
  173561. /************** Continuing where we left off in rtree.c **********************/
  173562. #endif
  173563. /*
  173564. ** Register the r-tree module with database handle db. This creates the
  173565. ** virtual table module "rtree" and the debugging/analysis scalar
  173566. ** function "rtreenode".
  173567. */
  173568. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  173569. const int utf8 = SQLITE_UTF8;
  173570. int rc;
  173571. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  173572. if( rc==SQLITE_OK ){
  173573. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  173574. }
  173575. if( rc==SQLITE_OK ){
  173576. rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
  173577. }
  173578. if( rc==SQLITE_OK ){
  173579. #ifdef SQLITE_RTREE_INT_ONLY
  173580. void *c = (void *)RTREE_COORD_INT32;
  173581. #else
  173582. void *c = (void *)RTREE_COORD_REAL32;
  173583. #endif
  173584. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  173585. }
  173586. if( rc==SQLITE_OK ){
  173587. void *c = (void *)RTREE_COORD_INT32;
  173588. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  173589. }
  173590. #ifdef SQLITE_ENABLE_GEOPOLY
  173591. if( rc==SQLITE_OK ){
  173592. rc = sqlite3_geopoly_init(db);
  173593. }
  173594. #endif
  173595. return rc;
  173596. }
  173597. /*
  173598. ** This routine deletes the RtreeGeomCallback object that was attached
  173599. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  173600. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  173601. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  173602. ** the corresponding SQL function is deleted.
  173603. */
  173604. static void rtreeFreeCallback(void *p){
  173605. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  173606. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  173607. sqlite3_free(p);
  173608. }
  173609. /*
  173610. ** This routine frees the BLOB that is returned by geomCallback().
  173611. */
  173612. static void rtreeMatchArgFree(void *pArg){
  173613. int i;
  173614. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  173615. for(i=0; i<p->nParam; i++){
  173616. sqlite3_value_free(p->apSqlParam[i]);
  173617. }
  173618. sqlite3_free(p);
  173619. }
  173620. /*
  173621. ** Each call to sqlite3_rtree_geometry_callback() or
  173622. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  173623. ** scalar function that is implemented by this routine.
  173624. **
  173625. ** All this function does is construct an RtreeMatchArg object that
  173626. ** contains the geometry-checking callback routines and a list of
  173627. ** parameters to this function, then return that RtreeMatchArg object
  173628. ** as a BLOB.
  173629. **
  173630. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  173631. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  173632. ** out which elements of the R-Tree should be returned by the query.
  173633. */
  173634. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  173635. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  173636. RtreeMatchArg *pBlob;
  173637. int nBlob;
  173638. int memErr = 0;
  173639. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  173640. + nArg*sizeof(sqlite3_value*);
  173641. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  173642. if( !pBlob ){
  173643. sqlite3_result_error_nomem(ctx);
  173644. }else{
  173645. int i;
  173646. pBlob->iSize = nBlob;
  173647. pBlob->cb = pGeomCtx[0];
  173648. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  173649. pBlob->nParam = nArg;
  173650. for(i=0; i<nArg; i++){
  173651. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  173652. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  173653. #ifdef SQLITE_RTREE_INT_ONLY
  173654. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  173655. #else
  173656. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  173657. #endif
  173658. }
  173659. if( memErr ){
  173660. sqlite3_result_error_nomem(ctx);
  173661. rtreeMatchArgFree(pBlob);
  173662. }else{
  173663. sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
  173664. }
  173665. }
  173666. }
  173667. /*
  173668. ** Register a new geometry function for use with the r-tree MATCH operator.
  173669. */
  173670. SQLITE_API int sqlite3_rtree_geometry_callback(
  173671. sqlite3 *db, /* Register SQL function on this connection */
  173672. const char *zGeom, /* Name of the new SQL function */
  173673. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  173674. void *pContext /* Extra data associated with the callback */
  173675. ){
  173676. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  173677. /* Allocate and populate the context object. */
  173678. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  173679. if( !pGeomCtx ) return SQLITE_NOMEM;
  173680. pGeomCtx->xGeom = xGeom;
  173681. pGeomCtx->xQueryFunc = 0;
  173682. pGeomCtx->xDestructor = 0;
  173683. pGeomCtx->pContext = pContext;
  173684. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  173685. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  173686. );
  173687. }
  173688. /*
  173689. ** Register a new 2nd-generation geometry function for use with the
  173690. ** r-tree MATCH operator.
  173691. */
  173692. SQLITE_API int sqlite3_rtree_query_callback(
  173693. sqlite3 *db, /* Register SQL function on this connection */
  173694. const char *zQueryFunc, /* Name of new SQL function */
  173695. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  173696. void *pContext, /* Extra data passed into the callback */
  173697. void (*xDestructor)(void*) /* Destructor for the extra data */
  173698. ){
  173699. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  173700. /* Allocate and populate the context object. */
  173701. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  173702. if( !pGeomCtx ) return SQLITE_NOMEM;
  173703. pGeomCtx->xGeom = 0;
  173704. pGeomCtx->xQueryFunc = xQueryFunc;
  173705. pGeomCtx->xDestructor = xDestructor;
  173706. pGeomCtx->pContext = pContext;
  173707. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  173708. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  173709. );
  173710. }
  173711. #if !SQLITE_CORE
  173712. #ifdef _WIN32
  173713. __declspec(dllexport)
  173714. #endif
  173715. SQLITE_API int sqlite3_rtree_init(
  173716. sqlite3 *db,
  173717. char **pzErrMsg,
  173718. const sqlite3_api_routines *pApi
  173719. ){
  173720. SQLITE_EXTENSION_INIT2(pApi)
  173721. return sqlite3RtreeInit(db);
  173722. }
  173723. #endif
  173724. #endif
  173725. /************** End of rtree.c ***********************************************/
  173726. /************** Begin file icu.c *********************************************/
  173727. /*
  173728. ** 2007 May 6
  173729. **
  173730. ** The author disclaims copyright to this source code. In place of
  173731. ** a legal notice, here is a blessing:
  173732. **
  173733. ** May you do good and not evil.
  173734. ** May you find forgiveness for yourself and forgive others.
  173735. ** May you share freely, never taking more than you give.
  173736. **
  173737. *************************************************************************
  173738. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  173739. **
  173740. ** This file implements an integration between the ICU library
  173741. ** ("International Components for Unicode", an open-source library
  173742. ** for handling unicode data) and SQLite. The integration uses
  173743. ** ICU to provide the following to SQLite:
  173744. **
  173745. ** * An implementation of the SQL regexp() function (and hence REGEXP
  173746. ** operator) using the ICU uregex_XX() APIs.
  173747. **
  173748. ** * Implementations of the SQL scalar upper() and lower() functions
  173749. ** for case mapping.
  173750. **
  173751. ** * Integration of ICU and SQLite collation sequences.
  173752. **
  173753. ** * An implementation of the LIKE operator that uses ICU to
  173754. ** provide case-independent matching.
  173755. */
  173756. #if !defined(SQLITE_CORE) \
  173757. || defined(SQLITE_ENABLE_ICU) \
  173758. || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  173759. /* Include ICU headers */
  173760. #include <unicode/utypes.h>
  173761. #include <unicode/uregex.h>
  173762. #include <unicode/ustring.h>
  173763. #include <unicode/ucol.h>
  173764. /* #include <assert.h> */
  173765. #ifndef SQLITE_CORE
  173766. /* #include "sqlite3ext.h" */
  173767. SQLITE_EXTENSION_INIT1
  173768. #else
  173769. /* #include "sqlite3.h" */
  173770. #endif
  173771. /*
  173772. ** This function is called when an ICU function called from within
  173773. ** the implementation of an SQL scalar function returns an error.
  173774. **
  173775. ** The scalar function context passed as the first argument is
  173776. ** loaded with an error message based on the following two args.
  173777. */
  173778. static void icuFunctionError(
  173779. sqlite3_context *pCtx, /* SQLite scalar function context */
  173780. const char *zName, /* Name of ICU function that failed */
  173781. UErrorCode e /* Error code returned by ICU function */
  173782. ){
  173783. char zBuf[128];
  173784. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  173785. zBuf[127] = '\0';
  173786. sqlite3_result_error(pCtx, zBuf, -1);
  173787. }
  173788. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  173789. /*
  173790. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  173791. ** operator.
  173792. */
  173793. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  173794. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  173795. #endif
  173796. /*
  173797. ** Version of sqlite3_free() that is always a function, never a macro.
  173798. */
  173799. static void xFree(void *p){
  173800. sqlite3_free(p);
  173801. }
  173802. /*
  173803. ** This lookup table is used to help decode the first byte of
  173804. ** a multi-byte UTF8 character. It is copied here from SQLite source
  173805. ** code file utf8.c.
  173806. */
  173807. static const unsigned char icuUtf8Trans1[] = {
  173808. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  173809. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  173810. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  173811. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  173812. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  173813. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  173814. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  173815. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  173816. };
  173817. #define SQLITE_ICU_READ_UTF8(zIn, c) \
  173818. c = *(zIn++); \
  173819. if( c>=0xc0 ){ \
  173820. c = icuUtf8Trans1[c-0xc0]; \
  173821. while( (*zIn & 0xc0)==0x80 ){ \
  173822. c = (c<<6) + (0x3f & *(zIn++)); \
  173823. } \
  173824. }
  173825. #define SQLITE_ICU_SKIP_UTF8(zIn) \
  173826. assert( *zIn ); \
  173827. if( *(zIn++)>=0xc0 ){ \
  173828. while( (*zIn & 0xc0)==0x80 ){zIn++;} \
  173829. }
  173830. /*
  173831. ** Compare two UTF-8 strings for equality where the first string is
  173832. ** a "LIKE" expression. Return true (1) if they are the same and
  173833. ** false (0) if they are different.
  173834. */
  173835. static int icuLikeCompare(
  173836. const uint8_t *zPattern, /* LIKE pattern */
  173837. const uint8_t *zString, /* The UTF-8 string to compare against */
  173838. const UChar32 uEsc /* The escape character */
  173839. ){
  173840. static const uint32_t MATCH_ONE = (uint32_t)'_';
  173841. static const uint32_t MATCH_ALL = (uint32_t)'%';
  173842. int prevEscape = 0; /* True if the previous character was uEsc */
  173843. while( 1 ){
  173844. /* Read (and consume) the next character from the input pattern. */
  173845. uint32_t uPattern;
  173846. SQLITE_ICU_READ_UTF8(zPattern, uPattern);
  173847. if( uPattern==0 ) break;
  173848. /* There are now 4 possibilities:
  173849. **
  173850. ** 1. uPattern is an unescaped match-all character "%",
  173851. ** 2. uPattern is an unescaped match-one character "_",
  173852. ** 3. uPattern is an unescaped escape character, or
  173853. ** 4. uPattern is to be handled as an ordinary character
  173854. */
  173855. if( !prevEscape && uPattern==MATCH_ALL ){
  173856. /* Case 1. */
  173857. uint8_t c;
  173858. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  173859. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  173860. ** test string.
  173861. */
  173862. while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
  173863. if( c==MATCH_ONE ){
  173864. if( *zString==0 ) return 0;
  173865. SQLITE_ICU_SKIP_UTF8(zString);
  173866. }
  173867. zPattern++;
  173868. }
  173869. if( *zPattern==0 ) return 1;
  173870. while( *zString ){
  173871. if( icuLikeCompare(zPattern, zString, uEsc) ){
  173872. return 1;
  173873. }
  173874. SQLITE_ICU_SKIP_UTF8(zString);
  173875. }
  173876. return 0;
  173877. }else if( !prevEscape && uPattern==MATCH_ONE ){
  173878. /* Case 2. */
  173879. if( *zString==0 ) return 0;
  173880. SQLITE_ICU_SKIP_UTF8(zString);
  173881. }else if( !prevEscape && uPattern==(uint32_t)uEsc){
  173882. /* Case 3. */
  173883. prevEscape = 1;
  173884. }else{
  173885. /* Case 4. */
  173886. uint32_t uString;
  173887. SQLITE_ICU_READ_UTF8(zString, uString);
  173888. uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
  173889. uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
  173890. if( uString!=uPattern ){
  173891. return 0;
  173892. }
  173893. prevEscape = 0;
  173894. }
  173895. }
  173896. return *zString==0;
  173897. }
  173898. /*
  173899. ** Implementation of the like() SQL function. This function implements
  173900. ** the build-in LIKE operator. The first argument to the function is the
  173901. ** pattern and the second argument is the string. So, the SQL statements:
  173902. **
  173903. ** A LIKE B
  173904. **
  173905. ** is implemented as like(B, A). If there is an escape character E,
  173906. **
  173907. ** A LIKE B ESCAPE E
  173908. **
  173909. ** is mapped to like(B, A, E).
  173910. */
  173911. static void icuLikeFunc(
  173912. sqlite3_context *context,
  173913. int argc,
  173914. sqlite3_value **argv
  173915. ){
  173916. const unsigned char *zA = sqlite3_value_text(argv[0]);
  173917. const unsigned char *zB = sqlite3_value_text(argv[1]);
  173918. UChar32 uEsc = 0;
  173919. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  173920. ** of deep recursion and N*N behavior in patternCompare().
  173921. */
  173922. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  173923. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  173924. return;
  173925. }
  173926. if( argc==3 ){
  173927. /* The escape character string must consist of a single UTF-8 character.
  173928. ** Otherwise, return an error.
  173929. */
  173930. int nE= sqlite3_value_bytes(argv[2]);
  173931. const unsigned char *zE = sqlite3_value_text(argv[2]);
  173932. int i = 0;
  173933. if( zE==0 ) return;
  173934. U8_NEXT(zE, i, nE, uEsc);
  173935. if( i!=nE){
  173936. sqlite3_result_error(context,
  173937. "ESCAPE expression must be a single character", -1);
  173938. return;
  173939. }
  173940. }
  173941. if( zA && zB ){
  173942. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  173943. }
  173944. }
  173945. /*
  173946. ** Function to delete compiled regexp objects. Registered as
  173947. ** a destructor function with sqlite3_set_auxdata().
  173948. */
  173949. static void icuRegexpDelete(void *p){
  173950. URegularExpression *pExpr = (URegularExpression *)p;
  173951. uregex_close(pExpr);
  173952. }
  173953. /*
  173954. ** Implementation of SQLite REGEXP operator. This scalar function takes
  173955. ** two arguments. The first is a regular expression pattern to compile
  173956. ** the second is a string to match against that pattern. If either
  173957. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  173958. ** is 1 if the string matches the pattern, or 0 otherwise.
  173959. **
  173960. ** SQLite maps the regexp() function to the regexp() operator such
  173961. ** that the following two are equivalent:
  173962. **
  173963. ** zString REGEXP zPattern
  173964. ** regexp(zPattern, zString)
  173965. **
  173966. ** Uses the following ICU regexp APIs:
  173967. **
  173968. ** uregex_open()
  173969. ** uregex_matches()
  173970. ** uregex_close()
  173971. */
  173972. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  173973. UErrorCode status = U_ZERO_ERROR;
  173974. URegularExpression *pExpr;
  173975. UBool res;
  173976. const UChar *zString = sqlite3_value_text16(apArg[1]);
  173977. (void)nArg; /* Unused parameter */
  173978. /* If the left hand side of the regexp operator is NULL,
  173979. ** then the result is also NULL.
  173980. */
  173981. if( !zString ){
  173982. return;
  173983. }
  173984. pExpr = sqlite3_get_auxdata(p, 0);
  173985. if( !pExpr ){
  173986. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  173987. if( !zPattern ){
  173988. return;
  173989. }
  173990. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  173991. if( U_SUCCESS(status) ){
  173992. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  173993. }else{
  173994. assert(!pExpr);
  173995. icuFunctionError(p, "uregex_open", status);
  173996. return;
  173997. }
  173998. }
  173999. /* Configure the text that the regular expression operates on. */
  174000. uregex_setText(pExpr, zString, -1, &status);
  174001. if( !U_SUCCESS(status) ){
  174002. icuFunctionError(p, "uregex_setText", status);
  174003. return;
  174004. }
  174005. /* Attempt the match */
  174006. res = uregex_matches(pExpr, 0, &status);
  174007. if( !U_SUCCESS(status) ){
  174008. icuFunctionError(p, "uregex_matches", status);
  174009. return;
  174010. }
  174011. /* Set the text that the regular expression operates on to a NULL
  174012. ** pointer. This is not really necessary, but it is tidier than
  174013. ** leaving the regular expression object configured with an invalid
  174014. ** pointer after this function returns.
  174015. */
  174016. uregex_setText(pExpr, 0, 0, &status);
  174017. /* Return 1 or 0. */
  174018. sqlite3_result_int(p, res ? 1 : 0);
  174019. }
  174020. /*
  174021. ** Implementations of scalar functions for case mapping - upper() and
  174022. ** lower(). Function upper() converts its input to upper-case (ABC).
  174023. ** Function lower() converts to lower-case (abc).
  174024. **
  174025. ** ICU provides two types of case mapping, "general" case mapping and
  174026. ** "language specific". Refer to ICU documentation for the differences
  174027. ** between the two.
  174028. **
  174029. ** To utilise "general" case mapping, the upper() or lower() scalar
  174030. ** functions are invoked with one argument:
  174031. **
  174032. ** upper('ABC') -> 'abc'
  174033. ** lower('abc') -> 'ABC'
  174034. **
  174035. ** To access ICU "language specific" case mapping, upper() or lower()
  174036. ** should be invoked with two arguments. The second argument is the name
  174037. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  174038. ** as the second argument is the same as invoking the 1 argument version
  174039. ** of upper() or lower().
  174040. **
  174041. ** lower('I', 'en_us') -> 'i'
  174042. ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
  174043. **
  174044. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  174045. */
  174046. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  174047. const UChar *zInput; /* Pointer to input string */
  174048. UChar *zOutput = 0; /* Pointer to output buffer */
  174049. int nInput; /* Size of utf-16 input string in bytes */
  174050. int nOut; /* Size of output buffer in bytes */
  174051. int cnt;
  174052. int bToUpper; /* True for toupper(), false for tolower() */
  174053. UErrorCode status;
  174054. const char *zLocale = 0;
  174055. assert(nArg==1 || nArg==2);
  174056. bToUpper = (sqlite3_user_data(p)!=0);
  174057. if( nArg==2 ){
  174058. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  174059. }
  174060. zInput = sqlite3_value_text16(apArg[0]);
  174061. if( !zInput ){
  174062. return;
  174063. }
  174064. nOut = nInput = sqlite3_value_bytes16(apArg[0]);
  174065. if( nOut==0 ){
  174066. sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
  174067. return;
  174068. }
  174069. for(cnt=0; cnt<2; cnt++){
  174070. UChar *zNew = sqlite3_realloc(zOutput, nOut);
  174071. if( zNew==0 ){
  174072. sqlite3_free(zOutput);
  174073. sqlite3_result_error_nomem(p);
  174074. return;
  174075. }
  174076. zOutput = zNew;
  174077. status = U_ZERO_ERROR;
  174078. if( bToUpper ){
  174079. nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  174080. }else{
  174081. nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  174082. }
  174083. if( U_SUCCESS(status) ){
  174084. sqlite3_result_text16(p, zOutput, nOut, xFree);
  174085. }else if( status==U_BUFFER_OVERFLOW_ERROR ){
  174086. assert( cnt==0 );
  174087. continue;
  174088. }else{
  174089. icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
  174090. }
  174091. return;
  174092. }
  174093. assert( 0 ); /* Unreachable */
  174094. }
  174095. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  174096. /*
  174097. ** Collation sequence destructor function. The pCtx argument points to
  174098. ** a UCollator structure previously allocated using ucol_open().
  174099. */
  174100. static void icuCollationDel(void *pCtx){
  174101. UCollator *p = (UCollator *)pCtx;
  174102. ucol_close(p);
  174103. }
  174104. /*
  174105. ** Collation sequence comparison function. The pCtx argument points to
  174106. ** a UCollator structure previously allocated using ucol_open().
  174107. */
  174108. static int icuCollationColl(
  174109. void *pCtx,
  174110. int nLeft,
  174111. const void *zLeft,
  174112. int nRight,
  174113. const void *zRight
  174114. ){
  174115. UCollationResult res;
  174116. UCollator *p = (UCollator *)pCtx;
  174117. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  174118. switch( res ){
  174119. case UCOL_LESS: return -1;
  174120. case UCOL_GREATER: return +1;
  174121. case UCOL_EQUAL: return 0;
  174122. }
  174123. assert(!"Unexpected return value from ucol_strcoll()");
  174124. return 0;
  174125. }
  174126. /*
  174127. ** Implementation of the scalar function icu_load_collation().
  174128. **
  174129. ** This scalar function is used to add ICU collation based collation
  174130. ** types to an SQLite database connection. It is intended to be called
  174131. ** as follows:
  174132. **
  174133. ** SELECT icu_load_collation(<locale>, <collation-name>);
  174134. **
  174135. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  174136. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  174137. ** collation sequence to create.
  174138. */
  174139. static void icuLoadCollation(
  174140. sqlite3_context *p,
  174141. int nArg,
  174142. sqlite3_value **apArg
  174143. ){
  174144. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  174145. UErrorCode status = U_ZERO_ERROR;
  174146. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  174147. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  174148. UCollator *pUCollator; /* ICU library collation object */
  174149. int rc; /* Return code from sqlite3_create_collation_x() */
  174150. assert(nArg==2);
  174151. (void)nArg; /* Unused parameter */
  174152. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  174153. zName = (const char *)sqlite3_value_text(apArg[1]);
  174154. if( !zLocale || !zName ){
  174155. return;
  174156. }
  174157. pUCollator = ucol_open(zLocale, &status);
  174158. if( !U_SUCCESS(status) ){
  174159. icuFunctionError(p, "ucol_open", status);
  174160. return;
  174161. }
  174162. assert(p);
  174163. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  174164. icuCollationColl, icuCollationDel
  174165. );
  174166. if( rc!=SQLITE_OK ){
  174167. ucol_close(pUCollator);
  174168. sqlite3_result_error(p, "Error registering collation function", -1);
  174169. }
  174170. }
  174171. /*
  174172. ** Register the ICU extension functions with database db.
  174173. */
  174174. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  174175. static const struct IcuScalar {
  174176. const char *zName; /* Function name */
  174177. unsigned char nArg; /* Number of arguments */
  174178. unsigned short enc; /* Optimal text encoding */
  174179. unsigned char iContext; /* sqlite3_user_data() context */
  174180. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  174181. } scalars[] = {
  174182. {"icu_load_collation", 2, SQLITE_UTF8, 1, icuLoadCollation},
  174183. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  174184. {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc},
  174185. {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  174186. {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  174187. {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  174188. {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  174189. {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  174190. {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  174191. {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  174192. {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  174193. {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  174194. {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  174195. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  174196. };
  174197. int rc = SQLITE_OK;
  174198. int i;
  174199. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  174200. const struct IcuScalar *p = &scalars[i];
  174201. rc = sqlite3_create_function(
  174202. db, p->zName, p->nArg, p->enc,
  174203. p->iContext ? (void*)db : (void*)0,
  174204. p->xFunc, 0, 0
  174205. );
  174206. }
  174207. return rc;
  174208. }
  174209. #if !SQLITE_CORE
  174210. #ifdef _WIN32
  174211. __declspec(dllexport)
  174212. #endif
  174213. SQLITE_API int sqlite3_icu_init(
  174214. sqlite3 *db,
  174215. char **pzErrMsg,
  174216. const sqlite3_api_routines *pApi
  174217. ){
  174218. SQLITE_EXTENSION_INIT2(pApi)
  174219. return sqlite3IcuInit(db);
  174220. }
  174221. #endif
  174222. #endif
  174223. /************** End of icu.c *************************************************/
  174224. /************** Begin file fts3_icu.c ****************************************/
  174225. /*
  174226. ** 2007 June 22
  174227. **
  174228. ** The author disclaims copyright to this source code. In place of
  174229. ** a legal notice, here is a blessing:
  174230. **
  174231. ** May you do good and not evil.
  174232. ** May you find forgiveness for yourself and forgive others.
  174233. ** May you share freely, never taking more than you give.
  174234. **
  174235. *************************************************************************
  174236. ** This file implements a tokenizer for fts3 based on the ICU library.
  174237. */
  174238. /* #include "fts3Int.h" */
  174239. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  174240. #ifdef SQLITE_ENABLE_ICU
  174241. /* #include <assert.h> */
  174242. /* #include <string.h> */
  174243. /* #include "fts3_tokenizer.h" */
  174244. #include <unicode/ubrk.h>
  174245. /* #include <unicode/ucol.h> */
  174246. /* #include <unicode/ustring.h> */
  174247. #include <unicode/utf16.h>
  174248. typedef struct IcuTokenizer IcuTokenizer;
  174249. typedef struct IcuCursor IcuCursor;
  174250. struct IcuTokenizer {
  174251. sqlite3_tokenizer base;
  174252. char *zLocale;
  174253. };
  174254. struct IcuCursor {
  174255. sqlite3_tokenizer_cursor base;
  174256. UBreakIterator *pIter; /* ICU break-iterator object */
  174257. int nChar; /* Number of UChar elements in pInput */
  174258. UChar *aChar; /* Copy of input using utf-16 encoding */
  174259. int *aOffset; /* Offsets of each character in utf-8 input */
  174260. int nBuffer;
  174261. char *zBuffer;
  174262. int iToken;
  174263. };
  174264. /*
  174265. ** Create a new tokenizer instance.
  174266. */
  174267. static int icuCreate(
  174268. int argc, /* Number of entries in argv[] */
  174269. const char * const *argv, /* Tokenizer creation arguments */
  174270. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  174271. ){
  174272. IcuTokenizer *p;
  174273. int n = 0;
  174274. if( argc>0 ){
  174275. n = strlen(argv[0])+1;
  174276. }
  174277. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  174278. if( !p ){
  174279. return SQLITE_NOMEM;
  174280. }
  174281. memset(p, 0, sizeof(IcuTokenizer));
  174282. if( n ){
  174283. p->zLocale = (char *)&p[1];
  174284. memcpy(p->zLocale, argv[0], n);
  174285. }
  174286. *ppTokenizer = (sqlite3_tokenizer *)p;
  174287. return SQLITE_OK;
  174288. }
  174289. /*
  174290. ** Destroy a tokenizer
  174291. */
  174292. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  174293. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  174294. sqlite3_free(p);
  174295. return SQLITE_OK;
  174296. }
  174297. /*
  174298. ** Prepare to begin tokenizing a particular string. The input
  174299. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  174300. ** used to incrementally tokenize this string is returned in
  174301. ** *ppCursor.
  174302. */
  174303. static int icuOpen(
  174304. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  174305. const char *zInput, /* Input string */
  174306. int nInput, /* Length of zInput in bytes */
  174307. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  174308. ){
  174309. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  174310. IcuCursor *pCsr;
  174311. const int32_t opt = U_FOLD_CASE_DEFAULT;
  174312. UErrorCode status = U_ZERO_ERROR;
  174313. int nChar;
  174314. UChar32 c;
  174315. int iInput = 0;
  174316. int iOut = 0;
  174317. *ppCursor = 0;
  174318. if( zInput==0 ){
  174319. nInput = 0;
  174320. zInput = "";
  174321. }else if( nInput<0 ){
  174322. nInput = strlen(zInput);
  174323. }
  174324. nChar = nInput+1;
  174325. pCsr = (IcuCursor *)sqlite3_malloc(
  174326. sizeof(IcuCursor) + /* IcuCursor */
  174327. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  174328. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  174329. );
  174330. if( !pCsr ){
  174331. return SQLITE_NOMEM;
  174332. }
  174333. memset(pCsr, 0, sizeof(IcuCursor));
  174334. pCsr->aChar = (UChar *)&pCsr[1];
  174335. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  174336. pCsr->aOffset[iOut] = iInput;
  174337. U8_NEXT(zInput, iInput, nInput, c);
  174338. while( c>0 ){
  174339. int isError = 0;
  174340. c = u_foldCase(c, opt);
  174341. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  174342. if( isError ){
  174343. sqlite3_free(pCsr);
  174344. return SQLITE_ERROR;
  174345. }
  174346. pCsr->aOffset[iOut] = iInput;
  174347. if( iInput<nInput ){
  174348. U8_NEXT(zInput, iInput, nInput, c);
  174349. }else{
  174350. c = 0;
  174351. }
  174352. }
  174353. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  174354. if( !U_SUCCESS(status) ){
  174355. sqlite3_free(pCsr);
  174356. return SQLITE_ERROR;
  174357. }
  174358. pCsr->nChar = iOut;
  174359. ubrk_first(pCsr->pIter);
  174360. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  174361. return SQLITE_OK;
  174362. }
  174363. /*
  174364. ** Close a tokenization cursor previously opened by a call to icuOpen().
  174365. */
  174366. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  174367. IcuCursor *pCsr = (IcuCursor *)pCursor;
  174368. ubrk_close(pCsr->pIter);
  174369. sqlite3_free(pCsr->zBuffer);
  174370. sqlite3_free(pCsr);
  174371. return SQLITE_OK;
  174372. }
  174373. /*
  174374. ** Extract the next token from a tokenization cursor.
  174375. */
  174376. static int icuNext(
  174377. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  174378. const char **ppToken, /* OUT: *ppToken is the token text */
  174379. int *pnBytes, /* OUT: Number of bytes in token */
  174380. int *piStartOffset, /* OUT: Starting offset of token */
  174381. int *piEndOffset, /* OUT: Ending offset of token */
  174382. int *piPosition /* OUT: Position integer of token */
  174383. ){
  174384. IcuCursor *pCsr = (IcuCursor *)pCursor;
  174385. int iStart = 0;
  174386. int iEnd = 0;
  174387. int nByte = 0;
  174388. while( iStart==iEnd ){
  174389. UChar32 c;
  174390. iStart = ubrk_current(pCsr->pIter);
  174391. iEnd = ubrk_next(pCsr->pIter);
  174392. if( iEnd==UBRK_DONE ){
  174393. return SQLITE_DONE;
  174394. }
  174395. while( iStart<iEnd ){
  174396. int iWhite = iStart;
  174397. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  174398. if( u_isspace(c) ){
  174399. iStart = iWhite;
  174400. }else{
  174401. break;
  174402. }
  174403. }
  174404. assert(iStart<=iEnd);
  174405. }
  174406. do {
  174407. UErrorCode status = U_ZERO_ERROR;
  174408. if( nByte ){
  174409. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  174410. if( !zNew ){
  174411. return SQLITE_NOMEM;
  174412. }
  174413. pCsr->zBuffer = zNew;
  174414. pCsr->nBuffer = nByte;
  174415. }
  174416. u_strToUTF8(
  174417. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  174418. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  174419. &status /* Output success/failure */
  174420. );
  174421. } while( nByte>pCsr->nBuffer );
  174422. *ppToken = pCsr->zBuffer;
  174423. *pnBytes = nByte;
  174424. *piStartOffset = pCsr->aOffset[iStart];
  174425. *piEndOffset = pCsr->aOffset[iEnd];
  174426. *piPosition = pCsr->iToken++;
  174427. return SQLITE_OK;
  174428. }
  174429. /*
  174430. ** The set of routines that implement the simple tokenizer
  174431. */
  174432. static const sqlite3_tokenizer_module icuTokenizerModule = {
  174433. 0, /* iVersion */
  174434. icuCreate, /* xCreate */
  174435. icuDestroy, /* xCreate */
  174436. icuOpen, /* xOpen */
  174437. icuClose, /* xClose */
  174438. icuNext, /* xNext */
  174439. 0, /* xLanguageid */
  174440. };
  174441. /*
  174442. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  174443. */
  174444. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  174445. sqlite3_tokenizer_module const**ppModule
  174446. ){
  174447. *ppModule = &icuTokenizerModule;
  174448. }
  174449. #endif /* defined(SQLITE_ENABLE_ICU) */
  174450. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  174451. /************** End of fts3_icu.c ********************************************/
  174452. /************** Begin file sqlite3rbu.c **************************************/
  174453. /*
  174454. ** 2014 August 30
  174455. **
  174456. ** The author disclaims copyright to this source code. In place of
  174457. ** a legal notice, here is a blessing:
  174458. **
  174459. ** May you do good and not evil.
  174460. ** May you find forgiveness for yourself and forgive others.
  174461. ** May you share freely, never taking more than you give.
  174462. **
  174463. *************************************************************************
  174464. **
  174465. **
  174466. ** OVERVIEW
  174467. **
  174468. ** The RBU extension requires that the RBU update be packaged as an
  174469. ** SQLite database. The tables it expects to find are described in
  174470. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  174471. ** that the user wishes to write to, a corresponding data_xyz table is
  174472. ** created in the RBU database and populated with one row for each row to
  174473. ** update, insert or delete from the target table.
  174474. **
  174475. ** The update proceeds in three stages:
  174476. **
  174477. ** 1) The database is updated. The modified database pages are written
  174478. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  174479. ** that it is named "<database>-oal" instead of "<database>-wal".
  174480. ** Because regular SQLite clients do not look for file named
  174481. ** "<database>-oal", they go on using the original database in
  174482. ** rollback mode while the *-oal file is being generated.
  174483. **
  174484. ** During this stage RBU does not update the database by writing
  174485. ** directly to the target tables. Instead it creates "imposter"
  174486. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  174487. ** to update each b-tree individually. All updates required by each
  174488. ** b-tree are completed before moving on to the next, and all
  174489. ** updates are done in sorted key order.
  174490. **
  174491. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  174492. ** location using a call to rename(2). Before doing this the RBU
  174493. ** module takes an EXCLUSIVE lock on the database file, ensuring
  174494. ** that there are no other active readers.
  174495. **
  174496. ** Once the EXCLUSIVE lock is released, any other database readers
  174497. ** detect the new *-wal file and read the database in wal mode. At
  174498. ** this point they see the new version of the database - including
  174499. ** the updates made as part of the RBU update.
  174500. **
  174501. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  174502. ** as a regular database checkpoint, except that a single frame is
  174503. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  174504. ** handle is closed before the entire *-wal file is checkpointed,
  174505. ** the checkpoint progress is saved in the RBU database and the
  174506. ** checkpoint can be resumed by another RBU client at some point in
  174507. ** the future.
  174508. **
  174509. ** POTENTIAL PROBLEMS
  174510. **
  174511. ** The rename() call might not be portable. And RBU is not currently
  174512. ** syncing the directory after renaming the file.
  174513. **
  174514. ** When state is saved, any commit to the *-oal file and the commit to
  174515. ** the RBU update database are not atomic. So if the power fails at the
  174516. ** wrong moment they might get out of sync. As the main database will be
  174517. ** committed before the RBU update database this will likely either just
  174518. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  174519. ** constraint violations).
  174520. **
  174521. ** If some client does modify the target database mid RBU update, or some
  174522. ** other error occurs, the RBU extension will keep throwing errors. It's
  174523. ** not really clear how to get out of this state. The system could just
  174524. ** by delete the RBU update database and *-oal file and have the device
  174525. ** download the update again and start over.
  174526. **
  174527. ** At present, for an UPDATE, both the new.* and old.* records are
  174528. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  174529. ** fields are collected. This means we're probably writing a lot more
  174530. ** data to disk when saving the state of an ongoing update to the RBU
  174531. ** update database than is strictly necessary.
  174532. **
  174533. */
  174534. /* #include <assert.h> */
  174535. /* #include <string.h> */
  174536. /* #include <stdio.h> */
  174537. /* #include "sqlite3.h" */
  174538. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  174539. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  174540. /************** Begin file sqlite3rbu.h **************************************/
  174541. /*
  174542. ** 2014 August 30
  174543. **
  174544. ** The author disclaims copyright to this source code. In place of
  174545. ** a legal notice, here is a blessing:
  174546. **
  174547. ** May you do good and not evil.
  174548. ** May you find forgiveness for yourself and forgive others.
  174549. ** May you share freely, never taking more than you give.
  174550. **
  174551. *************************************************************************
  174552. **
  174553. ** This file contains the public interface for the RBU extension.
  174554. */
  174555. /*
  174556. ** SUMMARY
  174557. **
  174558. ** Writing a transaction containing a large number of operations on
  174559. ** b-tree indexes that are collectively larger than the available cache
  174560. ** memory can be very inefficient.
  174561. **
  174562. ** The problem is that in order to update a b-tree, the leaf page (at least)
  174563. ** containing the entry being inserted or deleted must be modified. If the
  174564. ** working set of leaves is larger than the available cache memory, then a
  174565. ** single leaf that is modified more than once as part of the transaction
  174566. ** may be loaded from or written to the persistent media multiple times.
  174567. ** Additionally, because the index updates are likely to be applied in
  174568. ** random order, access to pages within the database is also likely to be in
  174569. ** random order, which is itself quite inefficient.
  174570. **
  174571. ** One way to improve the situation is to sort the operations on each index
  174572. ** by index key before applying them to the b-tree. This leads to an IO
  174573. ** pattern that resembles a single linear scan through the index b-tree,
  174574. ** and all but guarantees each modified leaf page is loaded and stored
  174575. ** exactly once. SQLite uses this trick to improve the performance of
  174576. ** CREATE INDEX commands. This extension allows it to be used to improve
  174577. ** the performance of large transactions on existing databases.
  174578. **
  174579. ** Additionally, this extension allows the work involved in writing the
  174580. ** large transaction to be broken down into sub-transactions performed
  174581. ** sequentially by separate processes. This is useful if the system cannot
  174582. ** guarantee that a single update process will run for long enough to apply
  174583. ** the entire update, for example because the update is being applied on a
  174584. ** mobile device that is frequently rebooted. Even after the writer process
  174585. ** has committed one or more sub-transactions, other database clients continue
  174586. ** to read from the original database snapshot. In other words, partially
  174587. ** applied transactions are not visible to other clients.
  174588. **
  174589. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  174590. ** transmitted via a wireless network to a mobile device. A transaction
  174591. ** applied using this extension is hence refered to as an "RBU update".
  174592. **
  174593. **
  174594. ** LIMITATIONS
  174595. **
  174596. ** An "RBU update" transaction is subject to the following limitations:
  174597. **
  174598. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  174599. ** only.
  174600. **
  174601. ** * INSERT statements may not use any default values.
  174602. **
  174603. ** * UPDATE and DELETE statements must identify their target rows by
  174604. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  174605. ** KEY fields may not be updated or deleted. If the table being written
  174606. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  174607. **
  174608. ** * UPDATE statements may not modify PRIMARY KEY columns.
  174609. **
  174610. ** * No triggers will be fired.
  174611. **
  174612. ** * No foreign key violations are detected or reported.
  174613. **
  174614. ** * CHECK constraints are not enforced.
  174615. **
  174616. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  174617. **
  174618. **
  174619. ** PREPARATION
  174620. **
  174621. ** An "RBU update" is stored as a separate SQLite database. A database
  174622. ** containing an RBU update is an "RBU database". For each table in the
  174623. ** target database to be updated, the RBU database should contain a table
  174624. ** named "data_<target name>" containing the same set of columns as the
  174625. ** target table, and one more - "rbu_control". The data_% table should
  174626. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  174627. ** the same type as the corresponding column in the target database.
  174628. ** The "rbu_control" column should have no type at all. For example, if
  174629. ** the target database contains:
  174630. **
  174631. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  174632. **
  174633. ** Then the RBU database should contain:
  174634. **
  174635. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  174636. **
  174637. ** The order of the columns in the data_% table does not matter.
  174638. **
  174639. ** Instead of a regular table, the RBU database may also contain virtual
  174640. ** tables or view named using the data_<target> naming scheme.
  174641. **
  174642. ** Instead of the plain data_<target> naming scheme, RBU database tables
  174643. ** may also be named data<integer>_<target>, where <integer> is any sequence
  174644. ** of zero or more numeric characters (0-9). This can be significant because
  174645. ** tables within the RBU database are always processed in order sorted by
  174646. ** name. By judicious selection of the <integer> portion of the names
  174647. ** of the RBU tables the user can therefore control the order in which they
  174648. ** are processed. This can be useful, for example, to ensure that "external
  174649. ** content" FTS4 tables are updated before their underlying content tables.
  174650. **
  174651. ** If the target database table is a virtual table or a table that has no
  174652. ** PRIMARY KEY declaration, the data_% table must also contain a column
  174653. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  174654. ** key column - "rowid". Virtual tables for which the "rowid" column does
  174655. ** not function like a primary key value cannot be updated using RBU. For
  174656. ** example, if the target db contains either of the following:
  174657. **
  174658. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  174659. ** CREATE TABLE x1(a, b)
  174660. **
  174661. ** then the RBU database should contain:
  174662. **
  174663. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  174664. **
  174665. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  174666. ** target table must be present in the input table. For virtual tables,
  174667. ** hidden columns are optional - they are updated by RBU if present in
  174668. ** the input table, or not otherwise. For example, to write to an fts4
  174669. ** table with a hidden languageid column such as:
  174670. **
  174671. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  174672. **
  174673. ** Either of the following input table schemas may be used:
  174674. **
  174675. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  174676. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  174677. **
  174678. ** For each row to INSERT into the target database as part of the RBU
  174679. ** update, the corresponding data_% table should contain a single record
  174680. ** with the "rbu_control" column set to contain integer value 0. The
  174681. ** other columns should be set to the values that make up the new record
  174682. ** to insert.
  174683. **
  174684. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  174685. ** possible to insert a NULL value into the IPK column. Attempting to
  174686. ** do so results in an SQLITE_MISMATCH error.
  174687. **
  174688. ** For each row to DELETE from the target database as part of the RBU
  174689. ** update, the corresponding data_% table should contain a single record
  174690. ** with the "rbu_control" column set to contain integer value 1. The
  174691. ** real primary key values of the row to delete should be stored in the
  174692. ** corresponding columns of the data_% table. The values stored in the
  174693. ** other columns are not used.
  174694. **
  174695. ** For each row to UPDATE from the target database as part of the RBU
  174696. ** update, the corresponding data_% table should contain a single record
  174697. ** with the "rbu_control" column set to contain a value of type text.
  174698. ** The real primary key values identifying the row to update should be
  174699. ** stored in the corresponding columns of the data_% table row, as should
  174700. ** the new values of all columns being update. The text value in the
  174701. ** "rbu_control" column must contain the same number of characters as
  174702. ** there are columns in the target database table, and must consist entirely
  174703. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  174704. ** each column that is being updated, the corresponding character is set to
  174705. ** 'x'. For those that remain as they are, the corresponding character of the
  174706. ** rbu_control value should be set to '.'. For example, given the tables
  174707. ** above, the update statement:
  174708. **
  174709. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  174710. **
  174711. ** is represented by the data_t1 row created by:
  174712. **
  174713. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  174714. **
  174715. ** Instead of an 'x' character, characters of the rbu_control value specified
  174716. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  174717. ** target table with the value stored in the corresponding data_% column, the
  174718. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  174719. ** the target table column. rbu_delta() is invoked with two arguments - the
  174720. ** original value currently stored in the target table column and the
  174721. ** value specified in the data_xxx table.
  174722. **
  174723. ** For example, this row:
  174724. **
  174725. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  174726. **
  174727. ** is similar to an UPDATE statement such as:
  174728. **
  174729. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  174730. **
  174731. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  174732. ** ota_control string, the contents of the data_xxx table column is assumed
  174733. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  174734. ** format used by the fossil source-code management system. In this case
  174735. ** the existing value within the target database table must be of type BLOB.
  174736. ** It is replaced by the result of applying the specified fossil delta to
  174737. ** itself.
  174738. **
  174739. ** If the target database table is a virtual table or a table with no PRIMARY
  174740. ** KEY, the rbu_control value should not include a character corresponding
  174741. ** to the rbu_rowid value. For example, this:
  174742. **
  174743. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  174744. ** VALUES(NULL, 'usa', 12, '.x');
  174745. **
  174746. ** causes a result similar to:
  174747. **
  174748. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  174749. **
  174750. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  174751. ** However, RBU is more efficient if reading the rows in from each data_xxx
  174752. ** table in "rowid" order is roughly the same as reading them sorted by
  174753. ** the PRIMARY KEY of the corresponding target database table. In other
  174754. ** words, rows should be sorted using the destination table PRIMARY KEY
  174755. ** fields before they are inserted into the data_xxx tables.
  174756. **
  174757. ** USAGE
  174758. **
  174759. ** The API declared below allows an application to apply an RBU update
  174760. ** stored on disk to an existing target database. Essentially, the
  174761. ** application:
  174762. **
  174763. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  174764. **
  174765. ** 2) Registers any required virtual table modules with the database
  174766. ** handle returned by sqlite3rbu_db(). Also, if required, register
  174767. ** the rbu_delta() implementation.
  174768. **
  174769. ** 3) Calls the sqlite3rbu_step() function one or more times on
  174770. ** the new handle. Each call to sqlite3rbu_step() performs a single
  174771. ** b-tree operation, so thousands of calls may be required to apply
  174772. ** a complete update.
  174773. **
  174774. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  174775. ** sqlite3rbu_step() has been called enough times to completely
  174776. ** apply the update to the target database, then the RBU database
  174777. ** is marked as fully applied. Otherwise, the state of the RBU
  174778. ** update application is saved in the RBU database for later
  174779. ** resumption.
  174780. **
  174781. ** See comments below for more detail on APIs.
  174782. **
  174783. ** If an update is only partially applied to the target database by the
  174784. ** time sqlite3rbu_close() is called, various state information is saved
  174785. ** within the RBU database. This allows subsequent processes to automatically
  174786. ** resume the RBU update from where it left off.
  174787. **
  174788. ** To remove all RBU extension state information, returning an RBU database
  174789. ** to its original contents, it is sufficient to drop all tables that begin
  174790. ** with the prefix "rbu_"
  174791. **
  174792. ** DATABASE LOCKING
  174793. **
  174794. ** An RBU update may not be applied to a database in WAL mode. Attempting
  174795. ** to do so is an error (SQLITE_ERROR).
  174796. **
  174797. ** While an RBU handle is open, a SHARED lock may be held on the target
  174798. ** database file. This means it is possible for other clients to read the
  174799. ** database, but not to write it.
  174800. **
  174801. ** If an RBU update is started and then suspended before it is completed,
  174802. ** then an external client writes to the database, then attempting to resume
  174803. ** the suspended RBU update is also an error (SQLITE_BUSY).
  174804. */
  174805. #ifndef _SQLITE3RBU_H
  174806. #define _SQLITE3RBU_H
  174807. /* #include "sqlite3.h" ** Required for error code definitions ** */
  174808. #if 0
  174809. extern "C" {
  174810. #endif
  174811. typedef struct sqlite3rbu sqlite3rbu;
  174812. /*
  174813. ** Open an RBU handle.
  174814. **
  174815. ** Argument zTarget is the path to the target database. Argument zRbu is
  174816. ** the path to the RBU database. Each call to this function must be matched
  174817. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  174818. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  174819. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  174820. ** database URI, not a regular file name.
  174821. **
  174822. ** If the zState argument is passed a NULL value, the RBU extension stores
  174823. ** the current state of the update (how many rows have been updated, which
  174824. ** indexes are yet to be updated etc.) within the RBU database itself. This
  174825. ** can be convenient, as it means that the RBU application does not need to
  174826. ** organize removing a separate state file after the update is concluded.
  174827. ** Or, if zState is non-NULL, it must be a path to a database file in which
  174828. ** the RBU extension can store the state of the update.
  174829. **
  174830. ** When resuming an RBU update, the zState argument must be passed the same
  174831. ** value as when the RBU update was started.
  174832. **
  174833. ** Once the RBU update is finished, the RBU extension does not
  174834. ** automatically remove any zState database file, even if it created it.
  174835. **
  174836. ** By default, RBU uses the default VFS to access the files on disk. To
  174837. ** use a VFS other than the default, an SQLite "file:" URI containing a
  174838. ** "vfs=..." option may be passed as the zTarget option.
  174839. **
  174840. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  174841. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  174842. ** not work out of the box with zipvfs. Refer to the comment describing
  174843. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  174844. */
  174845. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  174846. const char *zTarget,
  174847. const char *zRbu,
  174848. const char *zState
  174849. );
  174850. /*
  174851. ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
  174852. ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
  174853. ** that it can be suspended and resumed like an RBU update.
  174854. **
  174855. ** The second argument to this function identifies a database in which
  174856. ** to store the state of the RBU vacuum operation if it is suspended. The
  174857. ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
  174858. ** operation, the state database should either not exist or be empty
  174859. ** (contain no tables). If an RBU vacuum is suspended by calling
  174860. ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
  174861. ** returned SQLITE_DONE, the vacuum state is stored in the state database.
  174862. ** The vacuum can be resumed by calling this function to open a new RBU
  174863. ** handle specifying the same target and state databases.
  174864. **
  174865. ** If the second argument passed to this function is NULL, then the
  174866. ** name of the state database is "<database>-vacuum", where <database>
  174867. ** is the name of the target database file. In this case, on UNIX, if the
  174868. ** state database is not already present in the file-system, it is created
  174869. ** with the same permissions as the target db is made.
  174870. **
  174871. ** This function does not delete the state database after an RBU vacuum
  174872. ** is completed, even if it created it. However, if the call to
  174873. ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
  174874. ** of the state tables within the state database are zeroed. This way,
  174875. ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
  174876. ** new RBU vacuum operation.
  174877. **
  174878. ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
  174879. ** describing the sqlite3rbu_create_vfs() API function below for
  174880. ** a description of the complications associated with using RBU with
  174881. ** zipvfs databases.
  174882. */
  174883. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  174884. const char *zTarget,
  174885. const char *zState
  174886. );
  174887. /*
  174888. ** Configure a limit for the amount of temp space that may be used by
  174889. ** the RBU handle passed as the first argument. The new limit is specified
  174890. ** in bytes by the second parameter. If it is positive, the limit is updated.
  174891. ** If the second parameter to this function is passed zero, then the limit
  174892. ** is removed entirely. If the second parameter is negative, the limit is
  174893. ** not modified (this is useful for querying the current limit).
  174894. **
  174895. ** In all cases the returned value is the current limit in bytes (zero
  174896. ** indicates unlimited).
  174897. **
  174898. ** If the temp space limit is exceeded during operation, an SQLITE_FULL
  174899. ** error is returned.
  174900. */
  174901. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
  174902. /*
  174903. ** Return the current amount of temp file space, in bytes, currently used by
  174904. ** the RBU handle passed as the only argument.
  174905. */
  174906. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
  174907. /*
  174908. ** Internally, each RBU connection uses a separate SQLite database
  174909. ** connection to access the target and rbu update databases. This
  174910. ** API allows the application direct access to these database handles.
  174911. **
  174912. ** The first argument passed to this function must be a valid, open, RBU
  174913. ** handle. The second argument should be passed zero to access the target
  174914. ** database handle, or non-zero to access the rbu update database handle.
  174915. ** Accessing the underlying database handles may be useful in the
  174916. ** following scenarios:
  174917. **
  174918. ** * If any target tables are virtual tables, it may be necessary to
  174919. ** call sqlite3_create_module() on the target database handle to
  174920. ** register the required virtual table implementations.
  174921. **
  174922. ** * If the data_xxx tables in the RBU source database are virtual
  174923. ** tables, the application may need to call sqlite3_create_module() on
  174924. ** the rbu update db handle to any required virtual table
  174925. ** implementations.
  174926. **
  174927. ** * If the application uses the "rbu_delta()" feature described above,
  174928. ** it must use sqlite3_create_function() or similar to register the
  174929. ** rbu_delta() implementation with the target database handle.
  174930. **
  174931. ** If an error has occurred, either while opening or stepping the RBU object,
  174932. ** this function may return NULL. The error code and message may be collected
  174933. ** when sqlite3rbu_close() is called.
  174934. **
  174935. ** Database handles returned by this function remain valid until the next
  174936. ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
  174937. */
  174938. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
  174939. /*
  174940. ** Do some work towards applying the RBU update to the target db.
  174941. **
  174942. ** Return SQLITE_DONE if the update has been completely applied, or
  174943. ** SQLITE_OK if no error occurs but there remains work to do to apply
  174944. ** the RBU update. If an error does occur, some other error code is
  174945. ** returned.
  174946. **
  174947. ** Once a call to sqlite3rbu_step() has returned a value other than
  174948. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  174949. ** that immediately return the same value.
  174950. */
  174951. SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
  174952. /*
  174953. ** Force RBU to save its state to disk.
  174954. **
  174955. ** If a power failure or application crash occurs during an update, following
  174956. ** system recovery RBU may resume the update from the point at which the state
  174957. ** was last saved. In other words, from the most recent successful call to
  174958. ** sqlite3rbu_close() or this function.
  174959. **
  174960. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  174961. */
  174962. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
  174963. /*
  174964. ** Close an RBU handle.
  174965. **
  174966. ** If the RBU update has been completely applied, mark the RBU database
  174967. ** as fully applied. Otherwise, assuming no error has occurred, save the
  174968. ** current state of the RBU update appliation to the RBU database.
  174969. **
  174970. ** If an error has already occurred as part of an sqlite3rbu_step()
  174971. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  174972. ** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
  174973. ** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
  174974. ** English language error message. It is the responsibility of the caller to
  174975. ** eventually free any such buffer using sqlite3_free().
  174976. **
  174977. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  174978. ** update has been partially applied, or SQLITE_DONE if it has been
  174979. ** completely applied.
  174980. */
  174981. SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  174982. /*
  174983. ** Return the total number of key-value operations (inserts, deletes or
  174984. ** updates) that have been performed on the target database since the
  174985. ** current RBU update was started.
  174986. */
  174987. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
  174988. /*
  174989. ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
  174990. ** progress indications for the two stages of an RBU update. This API may
  174991. ** be useful for driving GUI progress indicators and similar.
  174992. **
  174993. ** An RBU update is divided into two stages:
  174994. **
  174995. ** * Stage 1, in which changes are accumulated in an oal/wal file, and
  174996. ** * Stage 2, in which the contents of the wal file are copied into the
  174997. ** main database.
  174998. **
  174999. ** The update is visible to non-RBU clients during stage 2. During stage 1
  175000. ** non-RBU reader clients may see the original database.
  175001. **
  175002. ** If this API is called during stage 2 of the update, output variable
  175003. ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
  175004. ** to a value between 0 and 10000 to indicate the permyriadage progress of
  175005. ** stage 2. A value of 5000 indicates that stage 2 is half finished,
  175006. ** 9000 indicates that it is 90% finished, and so on.
  175007. **
  175008. ** If this API is called during stage 1 of the update, output variable
  175009. ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
  175010. ** value to which (*pnOne) is set depends on whether or not the RBU
  175011. ** database contains an "rbu_count" table. The rbu_count table, if it
  175012. ** exists, must contain the same columns as the following:
  175013. **
  175014. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  175015. **
  175016. ** There must be one row in the table for each source (data_xxx) table within
  175017. ** the RBU database. The 'tbl' column should contain the name of the source
  175018. ** table. The 'cnt' column should contain the number of rows within the
  175019. ** source table.
  175020. **
  175021. ** If the rbu_count table is present and populated correctly and this
  175022. ** API is called during stage 1, the *pnOne output variable is set to the
  175023. ** permyriadage progress of the same stage. If the rbu_count table does
  175024. ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
  175025. ** table exists but is not correctly populated, the value of the *pnOne
  175026. ** output variable during stage 1 is undefined.
  175027. */
  175028. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
  175029. /*
  175030. ** Obtain an indication as to the current stage of an RBU update or vacuum.
  175031. ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
  175032. ** defined in this file. Return values should be interpreted as follows:
  175033. **
  175034. ** SQLITE_RBU_STATE_OAL:
  175035. ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
  175036. ** may either add further data to the *-oal file, or compute data that will
  175037. ** be added by a subsequent call.
  175038. **
  175039. ** SQLITE_RBU_STATE_MOVE:
  175040. ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
  175041. ** will move the *-oal file to the equivalent *-wal path. If the current
  175042. ** operation is an RBU update, then the updated version of the database
  175043. ** file will become visible to ordinary SQLite clients following the next
  175044. ** call to sqlite3rbu_step().
  175045. **
  175046. ** SQLITE_RBU_STATE_CHECKPOINT:
  175047. ** RBU is currently performing an incremental checkpoint. The next call to
  175048. ** sqlite3rbu_step() will copy a page of data from the *-wal file into
  175049. ** the target database file.
  175050. **
  175051. ** SQLITE_RBU_STATE_DONE:
  175052. ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
  175053. ** will immediately return SQLITE_DONE.
  175054. **
  175055. ** SQLITE_RBU_STATE_ERROR:
  175056. ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
  175057. ** immediately return the SQLite error code associated with the error.
  175058. */
  175059. #define SQLITE_RBU_STATE_OAL 1
  175060. #define SQLITE_RBU_STATE_MOVE 2
  175061. #define SQLITE_RBU_STATE_CHECKPOINT 3
  175062. #define SQLITE_RBU_STATE_DONE 4
  175063. #define SQLITE_RBU_STATE_ERROR 5
  175064. SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
  175065. /*
  175066. ** Create an RBU VFS named zName that accesses the underlying file-system
  175067. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  175068. ** then the new RBU VFS uses the default system VFS to access the file-system.
  175069. ** The new object is registered as a non-default VFS with SQLite before
  175070. ** returning.
  175071. **
  175072. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  175073. ** object is created and deleted automatically by RBU.
  175074. **
  175075. ** The exception is for applications that also use zipvfs. In this case,
  175076. ** the custom VFS must be explicitly created by the user before the RBU
  175077. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  175078. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  175079. ** (for example multiplexor) to access the file-system. For example,
  175080. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  175081. ** multiplexor (error checking omitted):
  175082. **
  175083. ** // Create a VFS named "multiplex" (not the default).
  175084. ** sqlite3_multiplex_initialize(0, 0);
  175085. **
  175086. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  175087. ** // second argument were replaced with NULL, the "rbu" VFS would
  175088. ** // access the file-system via the system default VFS, bypassing the
  175089. ** // multiplexor.
  175090. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  175091. **
  175092. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  175093. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  175094. **
  175095. ** // Make zipvfs the default VFS.
  175096. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  175097. **
  175098. ** Because the default VFS created above includes a RBU functionality, it
  175099. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  175100. ** that does not include the RBU layer results in an error.
  175101. **
  175102. ** The overhead of adding the "rbu" VFS to the system is negligible for
  175103. ** non-RBU users. There is no harm in an application accessing the
  175104. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  175105. ** occasionally.
  175106. */
  175107. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  175108. /*
  175109. ** Deregister and destroy an RBU vfs created by an earlier call to
  175110. ** sqlite3rbu_create_vfs().
  175111. **
  175112. ** VFS objects are not reference counted. If a VFS object is destroyed
  175113. ** before all database handles that use it have been closed, the results
  175114. ** are undefined.
  175115. */
  175116. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
  175117. #if 0
  175118. } /* end of the 'extern "C"' block */
  175119. #endif
  175120. #endif /* _SQLITE3RBU_H */
  175121. /************** End of sqlite3rbu.h ******************************************/
  175122. /************** Continuing where we left off in sqlite3rbu.c *****************/
  175123. #if defined(_WIN32_WCE)
  175124. /* #include "windows.h" */
  175125. #endif
  175126. /* Maximum number of prepared UPDATE statements held by this module */
  175127. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  175128. /* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM
  175129. ** to enable checksum verification.
  175130. */
  175131. #ifndef RBU_ENABLE_DELTA_CKSUM
  175132. # define RBU_ENABLE_DELTA_CKSUM 0
  175133. #endif
  175134. /*
  175135. ** Swap two objects of type TYPE.
  175136. */
  175137. #if !defined(SQLITE_AMALGAMATION)
  175138. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  175139. #endif
  175140. /*
  175141. ** The rbu_state table is used to save the state of a partially applied
  175142. ** update so that it can be resumed later. The table consists of integer
  175143. ** keys mapped to values as follows:
  175144. **
  175145. ** RBU_STATE_STAGE:
  175146. ** May be set to integer values 1, 2, 4 or 5. As follows:
  175147. ** 1: the *-rbu file is currently under construction.
  175148. ** 2: the *-rbu file has been constructed, but not yet moved
  175149. ** to the *-wal path.
  175150. ** 4: the checkpoint is underway.
  175151. ** 5: the rbu update has been checkpointed.
  175152. **
  175153. ** RBU_STATE_TBL:
  175154. ** Only valid if STAGE==1. The target database name of the table
  175155. ** currently being written.
  175156. **
  175157. ** RBU_STATE_IDX:
  175158. ** Only valid if STAGE==1. The target database name of the index
  175159. ** currently being written, or NULL if the main table is currently being
  175160. ** updated.
  175161. **
  175162. ** RBU_STATE_ROW:
  175163. ** Only valid if STAGE==1. Number of rows already processed for the current
  175164. ** table/index.
  175165. **
  175166. ** RBU_STATE_PROGRESS:
  175167. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  175168. ** rbu update.
  175169. **
  175170. ** RBU_STATE_CKPT:
  175171. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  175172. ** header created by recovering the *-wal file. This is used to detect
  175173. ** cases when another client appends frames to the *-wal file in the
  175174. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  175175. ** be continued if this happens).
  175176. **
  175177. ** RBU_STATE_COOKIE:
  175178. ** Valid if STAGE==1. The current change-counter cookie value in the
  175179. ** target db file.
  175180. **
  175181. ** RBU_STATE_OALSZ:
  175182. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  175183. **
  175184. ** RBU_STATE_DATATBL:
  175185. ** Only valid if STAGE==1. The RBU database name of the table
  175186. ** currently being read.
  175187. */
  175188. #define RBU_STATE_STAGE 1
  175189. #define RBU_STATE_TBL 2
  175190. #define RBU_STATE_IDX 3
  175191. #define RBU_STATE_ROW 4
  175192. #define RBU_STATE_PROGRESS 5
  175193. #define RBU_STATE_CKPT 6
  175194. #define RBU_STATE_COOKIE 7
  175195. #define RBU_STATE_OALSZ 8
  175196. #define RBU_STATE_PHASEONESTEP 9
  175197. #define RBU_STATE_DATATBL 10
  175198. #define RBU_STAGE_OAL 1
  175199. #define RBU_STAGE_MOVE 2
  175200. #define RBU_STAGE_CAPTURE 3
  175201. #define RBU_STAGE_CKPT 4
  175202. #define RBU_STAGE_DONE 5
  175203. #define RBU_CREATE_STATE \
  175204. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  175205. typedef struct RbuFrame RbuFrame;
  175206. typedef struct RbuObjIter RbuObjIter;
  175207. typedef struct RbuState RbuState;
  175208. typedef struct rbu_vfs rbu_vfs;
  175209. typedef struct rbu_file rbu_file;
  175210. typedef struct RbuUpdateStmt RbuUpdateStmt;
  175211. #if !defined(SQLITE_AMALGAMATION)
  175212. typedef unsigned int u32;
  175213. typedef unsigned short u16;
  175214. typedef unsigned char u8;
  175215. typedef sqlite3_int64 i64;
  175216. #endif
  175217. /*
  175218. ** These values must match the values defined in wal.c for the equivalent
  175219. ** locks. These are not magic numbers as they are part of the SQLite file
  175220. ** format.
  175221. */
  175222. #define WAL_LOCK_WRITE 0
  175223. #define WAL_LOCK_CKPT 1
  175224. #define WAL_LOCK_READ0 3
  175225. #define SQLITE_FCNTL_RBUCNT 5149216
  175226. /*
  175227. ** A structure to store values read from the rbu_state table in memory.
  175228. */
  175229. struct RbuState {
  175230. int eStage;
  175231. char *zTbl;
  175232. char *zDataTbl;
  175233. char *zIdx;
  175234. i64 iWalCksum;
  175235. int nRow;
  175236. i64 nProgress;
  175237. u32 iCookie;
  175238. i64 iOalSz;
  175239. i64 nPhaseOneStep;
  175240. };
  175241. struct RbuUpdateStmt {
  175242. char *zMask; /* Copy of update mask used with pUpdate */
  175243. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  175244. RbuUpdateStmt *pNext;
  175245. };
  175246. /*
  175247. ** An iterator of this type is used to iterate through all objects in
  175248. ** the target database that require updating. For each such table, the
  175249. ** iterator visits, in order:
  175250. **
  175251. ** * the table itself,
  175252. ** * each index of the table (zero or more points to visit), and
  175253. ** * a special "cleanup table" state.
  175254. **
  175255. ** abIndexed:
  175256. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  175257. ** it points to an array of flags nTblCol elements in size. The flag is
  175258. ** set for each column that is either a part of the PK or a part of an
  175259. ** index. Or clear otherwise.
  175260. **
  175261. */
  175262. struct RbuObjIter {
  175263. sqlite3_stmt *pTblIter; /* Iterate through tables */
  175264. sqlite3_stmt *pIdxIter; /* Index iterator */
  175265. int nTblCol; /* Size of azTblCol[] array */
  175266. char **azTblCol; /* Array of unquoted target column names */
  175267. char **azTblType; /* Array of target column types */
  175268. int *aiSrcOrder; /* src table col -> target table col */
  175269. u8 *abTblPk; /* Array of flags, set on target PK columns */
  175270. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  175271. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  175272. int eType; /* Table type - an RBU_PK_XXX value */
  175273. /* Output variables. zTbl==0 implies EOF. */
  175274. int bCleanup; /* True in "cleanup" state */
  175275. const char *zTbl; /* Name of target db table */
  175276. const char *zDataTbl; /* Name of rbu db table (or null) */
  175277. const char *zIdx; /* Name of target db index (or null) */
  175278. int iTnum; /* Root page of current object */
  175279. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  175280. int bUnique; /* Current index is unique */
  175281. int nIndex; /* Number of aux. indexes on table zTbl */
  175282. /* Statements created by rbuObjIterPrepareAll() */
  175283. int nCol; /* Number of columns in current object */
  175284. sqlite3_stmt *pSelect; /* Source data */
  175285. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  175286. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  175287. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  175288. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  175289. RbuUpdateStmt *pRbuUpdate;
  175290. };
  175291. /*
  175292. ** Values for RbuObjIter.eType
  175293. **
  175294. ** 0: Table does not exist (error)
  175295. ** 1: Table has an implicit rowid.
  175296. ** 2: Table has an explicit IPK column.
  175297. ** 3: Table has an external PK index.
  175298. ** 4: Table is WITHOUT ROWID.
  175299. ** 5: Table is a virtual table.
  175300. */
  175301. #define RBU_PK_NOTABLE 0
  175302. #define RBU_PK_NONE 1
  175303. #define RBU_PK_IPK 2
  175304. #define RBU_PK_EXTERNAL 3
  175305. #define RBU_PK_WITHOUT_ROWID 4
  175306. #define RBU_PK_VTAB 5
  175307. /*
  175308. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  175309. ** one of the following operations.
  175310. */
  175311. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  175312. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  175313. #define RBU_REPLACE 3 /* Delete and then insert a row */
  175314. #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
  175315. #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
  175316. #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
  175317. /*
  175318. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  175319. ** file should be copied to page iDbPage of the database file.
  175320. */
  175321. struct RbuFrame {
  175322. u32 iDbPage;
  175323. u32 iWalFrame;
  175324. };
  175325. /*
  175326. ** RBU handle.
  175327. **
  175328. ** nPhaseOneStep:
  175329. ** If the RBU database contains an rbu_count table, this value is set to
  175330. ** a running estimate of the number of b-tree operations required to
  175331. ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
  175332. ** API to calculate the permyriadage progress of populating the *-oal file
  175333. ** using the formula:
  175334. **
  175335. ** permyriadage = (10000 * nProgress) / nPhaseOneStep
  175336. **
  175337. ** nPhaseOneStep is initialized to the sum of:
  175338. **
  175339. ** nRow * (nIndex + 1)
  175340. **
  175341. ** for all source tables in the RBU database, where nRow is the number
  175342. ** of rows in the source table and nIndex the number of indexes on the
  175343. ** corresponding target database table.
  175344. **
  175345. ** This estimate is accurate if the RBU update consists entirely of
  175346. ** INSERT operations. However, it is inaccurate if:
  175347. **
  175348. ** * the RBU update contains any UPDATE operations. If the PK specified
  175349. ** for an UPDATE operation does not exist in the target table, then
  175350. ** no b-tree operations are required on index b-trees. Or if the
  175351. ** specified PK does exist, then (nIndex*2) such operations are
  175352. ** required (one delete and one insert on each index b-tree).
  175353. **
  175354. ** * the RBU update contains any DELETE operations for which the specified
  175355. ** PK does not exist. In this case no operations are required on index
  175356. ** b-trees.
  175357. **
  175358. ** * the RBU update contains REPLACE operations. These are similar to
  175359. ** UPDATE operations.
  175360. **
  175361. ** nPhaseOneStep is updated to account for the conditions above during the
  175362. ** first pass of each source table. The updated nPhaseOneStep value is
  175363. ** stored in the rbu_state table if the RBU update is suspended.
  175364. */
  175365. struct sqlite3rbu {
  175366. int eStage; /* Value of RBU_STATE_STAGE field */
  175367. sqlite3 *dbMain; /* target database handle */
  175368. sqlite3 *dbRbu; /* rbu database handle */
  175369. char *zTarget; /* Path to target db */
  175370. char *zRbu; /* Path to rbu db */
  175371. char *zState; /* Path to state db (or NULL if zRbu) */
  175372. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  175373. int rc; /* Value returned by last rbu_step() call */
  175374. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  175375. int nStep; /* Rows processed for current object */
  175376. int nProgress; /* Rows processed for all objects */
  175377. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  175378. const char *zVfsName; /* Name of automatically created rbu vfs */
  175379. rbu_file *pTargetFd; /* File handle open on target db */
  175380. int nPagePerSector; /* Pages per sector for pTargetFd */
  175381. i64 iOalSz;
  175382. i64 nPhaseOneStep;
  175383. /* The following state variables are used as part of the incremental
  175384. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  175385. ** function rbuSetupCheckpoint() for details. */
  175386. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  175387. u32 mLock;
  175388. int nFrame; /* Entries in aFrame[] array */
  175389. int nFrameAlloc; /* Allocated size of aFrame[] array */
  175390. RbuFrame *aFrame;
  175391. int pgsz;
  175392. u8 *aBuf;
  175393. i64 iWalCksum;
  175394. i64 szTemp; /* Current size of all temp files in use */
  175395. i64 szTempLimit; /* Total size limit for temp files */
  175396. /* Used in RBU vacuum mode only */
  175397. int nRbu; /* Number of RBU VFS in the stack */
  175398. rbu_file *pRbuFd; /* Fd for main db of dbRbu */
  175399. };
  175400. /*
  175401. ** An rbu VFS is implemented using an instance of this structure.
  175402. **
  175403. ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
  175404. ** It is NULL for RBU VFS objects created explicitly using
  175405. ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
  175406. ** space used by the RBU handle.
  175407. */
  175408. struct rbu_vfs {
  175409. sqlite3_vfs base; /* rbu VFS shim methods */
  175410. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  175411. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  175412. sqlite3rbu *pRbu; /* Owner RBU object */
  175413. rbu_file *pMain; /* List of main db files */
  175414. rbu_file *pMainRbu; /* List of main db files with pRbu!=0 */
  175415. };
  175416. /*
  175417. ** Each file opened by an rbu VFS is represented by an instance of
  175418. ** the following structure.
  175419. **
  175420. ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
  175421. ** "sz" is set to the current size of the database file.
  175422. */
  175423. struct rbu_file {
  175424. sqlite3_file base; /* sqlite3_file methods */
  175425. sqlite3_file *pReal; /* Underlying file handle */
  175426. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  175427. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  175428. i64 sz; /* Size of file in bytes (temp only) */
  175429. int openFlags; /* Flags this file was opened with */
  175430. u32 iCookie; /* Cookie value for main db files */
  175431. u8 iWriteVer; /* "write-version" value for main db files */
  175432. u8 bNolock; /* True to fail EXCLUSIVE locks */
  175433. int nShm; /* Number of entries in apShm[] array */
  175434. char **apShm; /* Array of mmap'd *-shm regions */
  175435. char *zDel; /* Delete this when closing file */
  175436. const char *zWal; /* Wal filename for this main db file */
  175437. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  175438. rbu_file *pMainNext; /* Next MAIN_DB file */
  175439. rbu_file *pMainRbuNext; /* Next MAIN_DB file with pRbu!=0 */
  175440. };
  175441. /*
  175442. ** True for an RBU vacuum handle, or false otherwise.
  175443. */
  175444. #define rbuIsVacuum(p) ((p)->zTarget==0)
  175445. /*************************************************************************
  175446. ** The following three functions, found below:
  175447. **
  175448. ** rbuDeltaGetInt()
  175449. ** rbuDeltaChecksum()
  175450. ** rbuDeltaApply()
  175451. **
  175452. ** are lifted from the fossil source code (http://fossil-scm.org). They
  175453. ** are used to implement the scalar SQL function rbu_fossil_delta().
  175454. */
  175455. /*
  175456. ** Read bytes from *pz and convert them into a positive integer. When
  175457. ** finished, leave *pz pointing to the first character past the end of
  175458. ** the integer. The *pLen parameter holds the length of the string
  175459. ** in *pz and is decremented once for each character in the integer.
  175460. */
  175461. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  175462. static const signed char zValue[] = {
  175463. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  175464. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  175465. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  175466. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  175467. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  175468. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  175469. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  175470. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  175471. };
  175472. unsigned int v = 0;
  175473. int c;
  175474. unsigned char *z = (unsigned char*)*pz;
  175475. unsigned char *zStart = z;
  175476. while( (c = zValue[0x7f&*(z++)])>=0 ){
  175477. v = (v<<6) + c;
  175478. }
  175479. z--;
  175480. *pLen -= z - zStart;
  175481. *pz = (char*)z;
  175482. return v;
  175483. }
  175484. #if RBU_ENABLE_DELTA_CKSUM
  175485. /*
  175486. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  175487. */
  175488. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  175489. const unsigned char *z = (const unsigned char *)zIn;
  175490. unsigned sum0 = 0;
  175491. unsigned sum1 = 0;
  175492. unsigned sum2 = 0;
  175493. unsigned sum3 = 0;
  175494. while(N >= 16){
  175495. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  175496. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  175497. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  175498. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  175499. z += 16;
  175500. N -= 16;
  175501. }
  175502. while(N >= 4){
  175503. sum0 += z[0];
  175504. sum1 += z[1];
  175505. sum2 += z[2];
  175506. sum3 += z[3];
  175507. z += 4;
  175508. N -= 4;
  175509. }
  175510. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  175511. switch(N){
  175512. case 3: sum3 += (z[2] << 8);
  175513. case 2: sum3 += (z[1] << 16);
  175514. case 1: sum3 += (z[0] << 24);
  175515. default: ;
  175516. }
  175517. return sum3;
  175518. }
  175519. #endif
  175520. /*
  175521. ** Apply a delta.
  175522. **
  175523. ** The output buffer should be big enough to hold the whole output
  175524. ** file and a NUL terminator at the end. The delta_output_size()
  175525. ** routine will determine this size for you.
  175526. **
  175527. ** The delta string should be null-terminated. But the delta string
  175528. ** may contain embedded NUL characters (if the input and output are
  175529. ** binary files) so we also have to pass in the length of the delta in
  175530. ** the lenDelta parameter.
  175531. **
  175532. ** This function returns the size of the output file in bytes (excluding
  175533. ** the final NUL terminator character). Except, if the delta string is
  175534. ** malformed or intended for use with a source file other than zSrc,
  175535. ** then this routine returns -1.
  175536. **
  175537. ** Refer to the delta_create() documentation above for a description
  175538. ** of the delta file format.
  175539. */
  175540. static int rbuDeltaApply(
  175541. const char *zSrc, /* The source or pattern file */
  175542. int lenSrc, /* Length of the source file */
  175543. const char *zDelta, /* Delta to apply to the pattern */
  175544. int lenDelta, /* Length of the delta */
  175545. char *zOut /* Write the output into this preallocated buffer */
  175546. ){
  175547. unsigned int limit;
  175548. unsigned int total = 0;
  175549. #if RBU_ENABLE_DELTA_CKSUM
  175550. char *zOrigOut = zOut;
  175551. #endif
  175552. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  175553. if( *zDelta!='\n' ){
  175554. /* ERROR: size integer not terminated by "\n" */
  175555. return -1;
  175556. }
  175557. zDelta++; lenDelta--;
  175558. while( *zDelta && lenDelta>0 ){
  175559. unsigned int cnt, ofst;
  175560. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  175561. switch( zDelta[0] ){
  175562. case '@': {
  175563. zDelta++; lenDelta--;
  175564. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  175565. if( lenDelta>0 && zDelta[0]!=',' ){
  175566. /* ERROR: copy command not terminated by ',' */
  175567. return -1;
  175568. }
  175569. zDelta++; lenDelta--;
  175570. total += cnt;
  175571. if( total>limit ){
  175572. /* ERROR: copy exceeds output file size */
  175573. return -1;
  175574. }
  175575. if( (int)(ofst+cnt) > lenSrc ){
  175576. /* ERROR: copy extends past end of input */
  175577. return -1;
  175578. }
  175579. memcpy(zOut, &zSrc[ofst], cnt);
  175580. zOut += cnt;
  175581. break;
  175582. }
  175583. case ':': {
  175584. zDelta++; lenDelta--;
  175585. total += cnt;
  175586. if( total>limit ){
  175587. /* ERROR: insert command gives an output larger than predicted */
  175588. return -1;
  175589. }
  175590. if( (int)cnt>lenDelta ){
  175591. /* ERROR: insert count exceeds size of delta */
  175592. return -1;
  175593. }
  175594. memcpy(zOut, zDelta, cnt);
  175595. zOut += cnt;
  175596. zDelta += cnt;
  175597. lenDelta -= cnt;
  175598. break;
  175599. }
  175600. case ';': {
  175601. zDelta++; lenDelta--;
  175602. zOut[0] = 0;
  175603. #if RBU_ENABLE_DELTA_CKSUM
  175604. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  175605. /* ERROR: bad checksum */
  175606. return -1;
  175607. }
  175608. #endif
  175609. if( total!=limit ){
  175610. /* ERROR: generated size does not match predicted size */
  175611. return -1;
  175612. }
  175613. return total;
  175614. }
  175615. default: {
  175616. /* ERROR: unknown delta operator */
  175617. return -1;
  175618. }
  175619. }
  175620. }
  175621. /* ERROR: unterminated delta */
  175622. return -1;
  175623. }
  175624. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  175625. int size;
  175626. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  175627. if( *zDelta!='\n' ){
  175628. /* ERROR: size integer not terminated by "\n" */
  175629. return -1;
  175630. }
  175631. return size;
  175632. }
  175633. /*
  175634. ** End of code taken from fossil.
  175635. *************************************************************************/
  175636. /*
  175637. ** Implementation of SQL scalar function rbu_fossil_delta().
  175638. **
  175639. ** This function applies a fossil delta patch to a blob. Exactly two
  175640. ** arguments must be passed to this function. The first is the blob to
  175641. ** patch and the second the patch to apply. If no error occurs, this
  175642. ** function returns the patched blob.
  175643. */
  175644. static void rbuFossilDeltaFunc(
  175645. sqlite3_context *context,
  175646. int argc,
  175647. sqlite3_value **argv
  175648. ){
  175649. const char *aDelta;
  175650. int nDelta;
  175651. const char *aOrig;
  175652. int nOrig;
  175653. int nOut;
  175654. int nOut2;
  175655. char *aOut;
  175656. assert( argc==2 );
  175657. nOrig = sqlite3_value_bytes(argv[0]);
  175658. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  175659. nDelta = sqlite3_value_bytes(argv[1]);
  175660. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  175661. /* Figure out the size of the output */
  175662. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  175663. if( nOut<0 ){
  175664. sqlite3_result_error(context, "corrupt fossil delta", -1);
  175665. return;
  175666. }
  175667. aOut = sqlite3_malloc(nOut+1);
  175668. if( aOut==0 ){
  175669. sqlite3_result_error_nomem(context);
  175670. }else{
  175671. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  175672. if( nOut2!=nOut ){
  175673. sqlite3_result_error(context, "corrupt fossil delta", -1);
  175674. }else{
  175675. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  175676. }
  175677. }
  175678. }
  175679. /*
  175680. ** Prepare the SQL statement in buffer zSql against database handle db.
  175681. ** If successful, set *ppStmt to point to the new statement and return
  175682. ** SQLITE_OK.
  175683. **
  175684. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  175685. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  175686. ** point to a buffer containing an error message. It is the responsibility
  175687. ** of the caller to (eventually) free this buffer using sqlite3_free().
  175688. */
  175689. static int prepareAndCollectError(
  175690. sqlite3 *db,
  175691. sqlite3_stmt **ppStmt,
  175692. char **pzErrmsg,
  175693. const char *zSql
  175694. ){
  175695. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  175696. if( rc!=SQLITE_OK ){
  175697. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  175698. *ppStmt = 0;
  175699. }
  175700. return rc;
  175701. }
  175702. /*
  175703. ** Reset the SQL statement passed as the first argument. Return a copy
  175704. ** of the value returned by sqlite3_reset().
  175705. **
  175706. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  175707. ** containing an error message. It is the responsibility of the caller
  175708. ** to eventually free this buffer using sqlite3_free().
  175709. */
  175710. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  175711. int rc = sqlite3_reset(pStmt);
  175712. if( rc!=SQLITE_OK ){
  175713. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  175714. }
  175715. return rc;
  175716. }
  175717. /*
  175718. ** Unless it is NULL, argument zSql points to a buffer allocated using
  175719. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  175720. ** statement against database db and frees the buffer. If statement
  175721. ** compilation is successful, *ppStmt is set to point to the new statement
  175722. ** handle and SQLITE_OK is returned.
  175723. **
  175724. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  175725. ** returned. In this case, *pzErrmsg may also be set to point to an error
  175726. ** message. It is the responsibility of the caller to free this error message
  175727. ** buffer using sqlite3_free().
  175728. **
  175729. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  175730. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  175731. */
  175732. static int prepareFreeAndCollectError(
  175733. sqlite3 *db,
  175734. sqlite3_stmt **ppStmt,
  175735. char **pzErrmsg,
  175736. char *zSql
  175737. ){
  175738. int rc;
  175739. assert( *pzErrmsg==0 );
  175740. if( zSql==0 ){
  175741. rc = SQLITE_NOMEM;
  175742. *ppStmt = 0;
  175743. }else{
  175744. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  175745. sqlite3_free(zSql);
  175746. }
  175747. return rc;
  175748. }
  175749. /*
  175750. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  175751. ** by an earlier call to rbuObjIterCacheTableInfo().
  175752. */
  175753. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  175754. int i;
  175755. for(i=0; i<pIter->nTblCol; i++){
  175756. sqlite3_free(pIter->azTblCol[i]);
  175757. sqlite3_free(pIter->azTblType[i]);
  175758. }
  175759. sqlite3_free(pIter->azTblCol);
  175760. pIter->azTblCol = 0;
  175761. pIter->azTblType = 0;
  175762. pIter->aiSrcOrder = 0;
  175763. pIter->abTblPk = 0;
  175764. pIter->abNotNull = 0;
  175765. pIter->nTblCol = 0;
  175766. pIter->eType = 0; /* Invalid value */
  175767. }
  175768. /*
  175769. ** Finalize all statements and free all allocations that are specific to
  175770. ** the current object (table/index pair).
  175771. */
  175772. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  175773. RbuUpdateStmt *pUp;
  175774. sqlite3_finalize(pIter->pSelect);
  175775. sqlite3_finalize(pIter->pInsert);
  175776. sqlite3_finalize(pIter->pDelete);
  175777. sqlite3_finalize(pIter->pTmpInsert);
  175778. pUp = pIter->pRbuUpdate;
  175779. while( pUp ){
  175780. RbuUpdateStmt *pTmp = pUp->pNext;
  175781. sqlite3_finalize(pUp->pUpdate);
  175782. sqlite3_free(pUp);
  175783. pUp = pTmp;
  175784. }
  175785. pIter->pSelect = 0;
  175786. pIter->pInsert = 0;
  175787. pIter->pDelete = 0;
  175788. pIter->pRbuUpdate = 0;
  175789. pIter->pTmpInsert = 0;
  175790. pIter->nCol = 0;
  175791. }
  175792. /*
  175793. ** Clean up any resources allocated as part of the iterator object passed
  175794. ** as the only argument.
  175795. */
  175796. static void rbuObjIterFinalize(RbuObjIter *pIter){
  175797. rbuObjIterClearStatements(pIter);
  175798. sqlite3_finalize(pIter->pTblIter);
  175799. sqlite3_finalize(pIter->pIdxIter);
  175800. rbuObjIterFreeCols(pIter);
  175801. memset(pIter, 0, sizeof(RbuObjIter));
  175802. }
  175803. /*
  175804. ** Advance the iterator to the next position.
  175805. **
  175806. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  175807. ** pointing to the next entry. Otherwise, an error code and message is
  175808. ** left in the RBU handle passed as the first argument. A copy of the
  175809. ** error code is returned.
  175810. */
  175811. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  175812. int rc = p->rc;
  175813. if( rc==SQLITE_OK ){
  175814. /* Free any SQLite statements used while processing the previous object */
  175815. rbuObjIterClearStatements(pIter);
  175816. if( pIter->zIdx==0 ){
  175817. rc = sqlite3_exec(p->dbMain,
  175818. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  175819. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  175820. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  175821. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  175822. , 0, 0, &p->zErrmsg
  175823. );
  175824. }
  175825. if( rc==SQLITE_OK ){
  175826. if( pIter->bCleanup ){
  175827. rbuObjIterFreeCols(pIter);
  175828. pIter->bCleanup = 0;
  175829. rc = sqlite3_step(pIter->pTblIter);
  175830. if( rc!=SQLITE_ROW ){
  175831. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  175832. pIter->zTbl = 0;
  175833. }else{
  175834. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  175835. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  175836. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  175837. }
  175838. }else{
  175839. if( pIter->zIdx==0 ){
  175840. sqlite3_stmt *pIdx = pIter->pIdxIter;
  175841. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  175842. }
  175843. if( rc==SQLITE_OK ){
  175844. rc = sqlite3_step(pIter->pIdxIter);
  175845. if( rc!=SQLITE_ROW ){
  175846. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  175847. pIter->bCleanup = 1;
  175848. pIter->zIdx = 0;
  175849. }else{
  175850. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  175851. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  175852. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  175853. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  175854. }
  175855. }
  175856. }
  175857. }
  175858. }
  175859. if( rc!=SQLITE_OK ){
  175860. rbuObjIterFinalize(pIter);
  175861. p->rc = rc;
  175862. }
  175863. return rc;
  175864. }
  175865. /*
  175866. ** The implementation of the rbu_target_name() SQL function. This function
  175867. ** accepts one or two arguments. The first argument is the name of a table -
  175868. ** the name of a table in the RBU database. The second, if it is present, is 1
  175869. ** for a view or 0 for a table.
  175870. **
  175871. ** For a non-vacuum RBU handle, if the table name matches the pattern:
  175872. **
  175873. ** data[0-9]_<name>
  175874. **
  175875. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  175876. ** Otherwise, if the only argument does not match the above pattern, an SQL
  175877. ** NULL is returned.
  175878. **
  175879. ** "data_t1" -> "t1"
  175880. ** "data0123_t2" -> "t2"
  175881. ** "dataAB_t3" -> NULL
  175882. **
  175883. ** For an rbu vacuum handle, a copy of the first argument is returned if
  175884. ** the second argument is either missing or 0 (not a view).
  175885. */
  175886. static void rbuTargetNameFunc(
  175887. sqlite3_context *pCtx,
  175888. int argc,
  175889. sqlite3_value **argv
  175890. ){
  175891. sqlite3rbu *p = sqlite3_user_data(pCtx);
  175892. const char *zIn;
  175893. assert( argc==1 || argc==2 );
  175894. zIn = (const char*)sqlite3_value_text(argv[0]);
  175895. if( zIn ){
  175896. if( rbuIsVacuum(p) ){
  175897. if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
  175898. sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
  175899. }
  175900. }else{
  175901. if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  175902. int i;
  175903. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  175904. if( zIn[i]=='_' && zIn[i+1] ){
  175905. sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
  175906. }
  175907. }
  175908. }
  175909. }
  175910. }
  175911. /*
  175912. ** Initialize the iterator structure passed as the second argument.
  175913. **
  175914. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  175915. ** pointing to the first entry. Otherwise, an error code and message is
  175916. ** left in the RBU handle passed as the first argument. A copy of the
  175917. ** error code is returned.
  175918. */
  175919. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  175920. int rc;
  175921. memset(pIter, 0, sizeof(RbuObjIter));
  175922. rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  175923. sqlite3_mprintf(
  175924. "SELECT rbu_target_name(name, type='view') AS target, name "
  175925. "FROM sqlite_master "
  175926. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  175927. " %s "
  175928. "ORDER BY name"
  175929. , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
  175930. if( rc==SQLITE_OK ){
  175931. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  175932. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  175933. " FROM main.sqlite_master "
  175934. " WHERE type='index' AND tbl_name = ?"
  175935. );
  175936. }
  175937. pIter->bCleanup = 1;
  175938. p->rc = rc;
  175939. return rbuObjIterNext(p, pIter);
  175940. }
  175941. /*
  175942. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  175943. ** an error code is stored in the RBU handle passed as the first argument.
  175944. **
  175945. ** If an error has already occurred (p->rc is already set to something other
  175946. ** than SQLITE_OK), then this function returns NULL without modifying the
  175947. ** stored error code. In this case it still calls sqlite3_free() on any
  175948. ** printf() parameters associated with %z conversions.
  175949. */
  175950. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  175951. char *zSql = 0;
  175952. va_list ap;
  175953. va_start(ap, zFmt);
  175954. zSql = sqlite3_vmprintf(zFmt, ap);
  175955. if( p->rc==SQLITE_OK ){
  175956. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  175957. }else{
  175958. sqlite3_free(zSql);
  175959. zSql = 0;
  175960. }
  175961. va_end(ap);
  175962. return zSql;
  175963. }
  175964. /*
  175965. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  175966. ** arguments are the usual subsitution values. This function performs
  175967. ** the printf() style substitutions and executes the result as an SQL
  175968. ** statement on the RBU handles database.
  175969. **
  175970. ** If an error occurs, an error code and error message is stored in the
  175971. ** RBU handle. If an error has already occurred when this function is
  175972. ** called, it is a no-op.
  175973. */
  175974. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  175975. va_list ap;
  175976. char *zSql;
  175977. va_start(ap, zFmt);
  175978. zSql = sqlite3_vmprintf(zFmt, ap);
  175979. if( p->rc==SQLITE_OK ){
  175980. if( zSql==0 ){
  175981. p->rc = SQLITE_NOMEM;
  175982. }else{
  175983. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  175984. }
  175985. }
  175986. sqlite3_free(zSql);
  175987. va_end(ap);
  175988. return p->rc;
  175989. }
  175990. /*
  175991. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  175992. ** bytes.
  175993. **
  175994. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  175995. ** error code in the rbu handle passed as the first argument. Or, if an
  175996. ** error has already occurred when this function is called, return NULL
  175997. ** immediately without attempting the allocation or modifying the stored
  175998. ** error code.
  175999. */
  176000. static void *rbuMalloc(sqlite3rbu *p, int nByte){
  176001. void *pRet = 0;
  176002. if( p->rc==SQLITE_OK ){
  176003. assert( nByte>0 );
  176004. pRet = sqlite3_malloc64(nByte);
  176005. if( pRet==0 ){
  176006. p->rc = SQLITE_NOMEM;
  176007. }else{
  176008. memset(pRet, 0, nByte);
  176009. }
  176010. }
  176011. return pRet;
  176012. }
  176013. /*
  176014. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  176015. ** there is room for at least nCol elements. If an OOM occurs, store an
  176016. ** error code in the RBU handle passed as the first argument.
  176017. */
  176018. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  176019. int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  176020. char **azNew;
  176021. azNew = (char**)rbuMalloc(p, nByte);
  176022. if( azNew ){
  176023. pIter->azTblCol = azNew;
  176024. pIter->azTblType = &azNew[nCol];
  176025. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  176026. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  176027. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  176028. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  176029. }
  176030. }
  176031. /*
  176032. ** The first argument must be a nul-terminated string. This function
  176033. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  176034. ** It is the responsibility of the caller to eventually free this memory
  176035. ** using sqlite3_free().
  176036. **
  176037. ** If an OOM condition is encountered when attempting to allocate memory,
  176038. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  176039. ** if the allocation succeeds, (*pRc) is left unchanged.
  176040. */
  176041. static char *rbuStrndup(const char *zStr, int *pRc){
  176042. char *zRet = 0;
  176043. assert( *pRc==SQLITE_OK );
  176044. if( zStr ){
  176045. size_t nCopy = strlen(zStr) + 1;
  176046. zRet = (char*)sqlite3_malloc64(nCopy);
  176047. if( zRet ){
  176048. memcpy(zRet, zStr, nCopy);
  176049. }else{
  176050. *pRc = SQLITE_NOMEM;
  176051. }
  176052. }
  176053. return zRet;
  176054. }
  176055. /*
  176056. ** Finalize the statement passed as the second argument.
  176057. **
  176058. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  176059. ** rbu handle error code is not already set, set the error code and error
  176060. ** message accordingly.
  176061. */
  176062. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  176063. sqlite3 *db = sqlite3_db_handle(pStmt);
  176064. int rc = sqlite3_finalize(pStmt);
  176065. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  176066. p->rc = rc;
  176067. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  176068. }
  176069. }
  176070. /* Determine the type of a table.
  176071. **
  176072. ** peType is of type (int*), a pointer to an output parameter of type
  176073. ** (int). This call sets the output parameter as follows, depending
  176074. ** on the type of the table specified by parameters dbName and zTbl.
  176075. **
  176076. ** RBU_PK_NOTABLE: No such table.
  176077. ** RBU_PK_NONE: Table has an implicit rowid.
  176078. ** RBU_PK_IPK: Table has an explicit IPK column.
  176079. ** RBU_PK_EXTERNAL: Table has an external PK index.
  176080. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  176081. ** RBU_PK_VTAB: Table is a virtual table.
  176082. **
  176083. ** Argument *piPk is also of type (int*), and also points to an output
  176084. ** parameter. Unless the table has an external primary key index
  176085. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  176086. ** if the table does have an external primary key index, then *piPk
  176087. ** is set to the root page number of the primary key index before
  176088. ** returning.
  176089. **
  176090. ** ALGORITHM:
  176091. **
  176092. ** if( no entry exists in sqlite_master ){
  176093. ** return RBU_PK_NOTABLE
  176094. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  176095. ** return RBU_PK_VTAB
  176096. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  176097. ** if( the index that is the pk exists in sqlite_master ){
  176098. ** *piPK = rootpage of that index.
  176099. ** return RBU_PK_EXTERNAL
  176100. ** }else{
  176101. ** return RBU_PK_WITHOUT_ROWID
  176102. ** }
  176103. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  176104. ** return RBU_PK_IPK
  176105. ** }else{
  176106. ** return RBU_PK_NONE
  176107. ** }
  176108. */
  176109. static void rbuTableType(
  176110. sqlite3rbu *p,
  176111. const char *zTab,
  176112. int *peType,
  176113. int *piTnum,
  176114. int *piPk
  176115. ){
  176116. /*
  176117. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  176118. ** 1) PRAGMA index_list = ?
  176119. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  176120. ** 3) PRAGMA table_info = ?
  176121. */
  176122. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  176123. *peType = RBU_PK_NOTABLE;
  176124. *piPk = 0;
  176125. assert( p->rc==SQLITE_OK );
  176126. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  176127. sqlite3_mprintf(
  176128. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  176129. " FROM sqlite_master"
  176130. " WHERE name=%Q", zTab
  176131. ));
  176132. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  176133. /* Either an error, or no such table. */
  176134. goto rbuTableType_end;
  176135. }
  176136. if( sqlite3_column_int(aStmt[0], 0) ){
  176137. *peType = RBU_PK_VTAB; /* virtual table */
  176138. goto rbuTableType_end;
  176139. }
  176140. *piTnum = sqlite3_column_int(aStmt[0], 1);
  176141. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  176142. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  176143. );
  176144. if( p->rc ) goto rbuTableType_end;
  176145. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  176146. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  176147. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  176148. if( zOrig && zIdx && zOrig[0]=='p' ){
  176149. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  176150. sqlite3_mprintf(
  176151. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  176152. ));
  176153. if( p->rc==SQLITE_OK ){
  176154. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  176155. *piPk = sqlite3_column_int(aStmt[2], 0);
  176156. *peType = RBU_PK_EXTERNAL;
  176157. }else{
  176158. *peType = RBU_PK_WITHOUT_ROWID;
  176159. }
  176160. }
  176161. goto rbuTableType_end;
  176162. }
  176163. }
  176164. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  176165. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  176166. );
  176167. if( p->rc==SQLITE_OK ){
  176168. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  176169. if( sqlite3_column_int(aStmt[3],5)>0 ){
  176170. *peType = RBU_PK_IPK; /* explicit IPK column */
  176171. goto rbuTableType_end;
  176172. }
  176173. }
  176174. *peType = RBU_PK_NONE;
  176175. }
  176176. rbuTableType_end: {
  176177. unsigned int i;
  176178. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  176179. rbuFinalize(p, aStmt[i]);
  176180. }
  176181. }
  176182. }
  176183. /*
  176184. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  176185. ** the pIter->abIndexed[] array.
  176186. */
  176187. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  176188. sqlite3_stmt *pList = 0;
  176189. int bIndex = 0;
  176190. if( p->rc==SQLITE_OK ){
  176191. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  176192. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  176193. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  176194. );
  176195. }
  176196. pIter->nIndex = 0;
  176197. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  176198. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  176199. sqlite3_stmt *pXInfo = 0;
  176200. if( zIdx==0 ) break;
  176201. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  176202. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  176203. );
  176204. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  176205. int iCid = sqlite3_column_int(pXInfo, 1);
  176206. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  176207. }
  176208. rbuFinalize(p, pXInfo);
  176209. bIndex = 1;
  176210. pIter->nIndex++;
  176211. }
  176212. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  176213. /* "PRAGMA index_list" includes the main PK b-tree */
  176214. pIter->nIndex--;
  176215. }
  176216. rbuFinalize(p, pList);
  176217. if( bIndex==0 ) pIter->abIndexed = 0;
  176218. }
  176219. /*
  176220. ** If they are not already populated, populate the pIter->azTblCol[],
  176221. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  176222. ** the table (not index) that the iterator currently points to.
  176223. **
  176224. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  176225. ** an error does occur, an error code and error message are also left in
  176226. ** the RBU handle.
  176227. */
  176228. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  176229. if( pIter->azTblCol==0 ){
  176230. sqlite3_stmt *pStmt = 0;
  176231. int nCol = 0;
  176232. int i; /* for() loop iterator variable */
  176233. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  176234. int iOrder = 0;
  176235. int iTnum = 0;
  176236. /* Figure out the type of table this step will deal with. */
  176237. assert( pIter->eType==0 );
  176238. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  176239. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  176240. p->rc = SQLITE_ERROR;
  176241. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  176242. }
  176243. if( p->rc ) return p->rc;
  176244. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  176245. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  176246. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  176247. || pIter->eType==RBU_PK_VTAB
  176248. );
  176249. /* Populate the azTblCol[] and nTblCol variables based on the columns
  176250. ** of the input table. Ignore any input table columns that begin with
  176251. ** "rbu_". */
  176252. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  176253. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  176254. );
  176255. if( p->rc==SQLITE_OK ){
  176256. nCol = sqlite3_column_count(pStmt);
  176257. rbuAllocateIterArrays(p, pIter, nCol);
  176258. }
  176259. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  176260. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  176261. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  176262. char *zCopy = rbuStrndup(zName, &p->rc);
  176263. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  176264. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  176265. }
  176266. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  176267. bRbuRowid = 1;
  176268. }
  176269. }
  176270. sqlite3_finalize(pStmt);
  176271. pStmt = 0;
  176272. if( p->rc==SQLITE_OK
  176273. && rbuIsVacuum(p)==0
  176274. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  176275. ){
  176276. p->rc = SQLITE_ERROR;
  176277. p->zErrmsg = sqlite3_mprintf(
  176278. "table %q %s rbu_rowid column", pIter->zDataTbl,
  176279. (bRbuRowid ? "may not have" : "requires")
  176280. );
  176281. }
  176282. /* Check that all non-HIDDEN columns in the destination table are also
  176283. ** present in the input table. Populate the abTblPk[], azTblType[] and
  176284. ** aiTblOrder[] arrays at the same time. */
  176285. if( p->rc==SQLITE_OK ){
  176286. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  176287. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  176288. );
  176289. }
  176290. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  176291. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  176292. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  176293. for(i=iOrder; i<pIter->nTblCol; i++){
  176294. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  176295. }
  176296. if( i==pIter->nTblCol ){
  176297. p->rc = SQLITE_ERROR;
  176298. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  176299. pIter->zDataTbl, zName
  176300. );
  176301. }else{
  176302. int iPk = sqlite3_column_int(pStmt, 5);
  176303. int bNotNull = sqlite3_column_int(pStmt, 3);
  176304. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  176305. if( i!=iOrder ){
  176306. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  176307. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  176308. }
  176309. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  176310. pIter->abTblPk[iOrder] = (iPk!=0);
  176311. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  176312. iOrder++;
  176313. }
  176314. }
  176315. rbuFinalize(p, pStmt);
  176316. rbuObjIterCacheIndexedCols(p, pIter);
  176317. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  176318. assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
  176319. }
  176320. return p->rc;
  176321. }
  176322. /*
  176323. ** This function constructs and returns a pointer to a nul-terminated
  176324. ** string containing some SQL clause or list based on one or more of the
  176325. ** column names currently stored in the pIter->azTblCol[] array.
  176326. */
  176327. static char *rbuObjIterGetCollist(
  176328. sqlite3rbu *p, /* RBU object */
  176329. RbuObjIter *pIter /* Object iterator for column names */
  176330. ){
  176331. char *zList = 0;
  176332. const char *zSep = "";
  176333. int i;
  176334. for(i=0; i<pIter->nTblCol; i++){
  176335. const char *z = pIter->azTblCol[i];
  176336. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  176337. zSep = ", ";
  176338. }
  176339. return zList;
  176340. }
  176341. /*
  176342. ** This function is used to create a SELECT list (the list of SQL
  176343. ** expressions that follows a SELECT keyword) for a SELECT statement
  176344. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  176345. ** index object currently indicated by the iterator object passed as the
  176346. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  176347. ** to obtain the required information.
  176348. **
  176349. ** If the index is of the following form:
  176350. **
  176351. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  176352. **
  176353. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  176354. ** "ipk", the returned string is:
  176355. **
  176356. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  176357. **
  176358. ** As well as the returned string, three other malloc'd strings are
  176359. ** returned via output parameters. As follows:
  176360. **
  176361. ** pzImposterCols: ...
  176362. ** pzImposterPk: ...
  176363. ** pzWhere: ...
  176364. */
  176365. static char *rbuObjIterGetIndexCols(
  176366. sqlite3rbu *p, /* RBU object */
  176367. RbuObjIter *pIter, /* Object iterator for column names */
  176368. char **pzImposterCols, /* OUT: Columns for imposter table */
  176369. char **pzImposterPk, /* OUT: Imposter PK clause */
  176370. char **pzWhere, /* OUT: WHERE clause */
  176371. int *pnBind /* OUT: Trbul number of columns */
  176372. ){
  176373. int rc = p->rc; /* Error code */
  176374. int rc2; /* sqlite3_finalize() return code */
  176375. char *zRet = 0; /* String to return */
  176376. char *zImpCols = 0; /* String to return via *pzImposterCols */
  176377. char *zImpPK = 0; /* String to return via *pzImposterPK */
  176378. char *zWhere = 0; /* String to return via *pzWhere */
  176379. int nBind = 0; /* Value to return via *pnBind */
  176380. const char *zCom = ""; /* Set to ", " later on */
  176381. const char *zAnd = ""; /* Set to " AND " later on */
  176382. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  176383. if( rc==SQLITE_OK ){
  176384. assert( p->zErrmsg==0 );
  176385. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  176386. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  176387. );
  176388. }
  176389. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  176390. int iCid = sqlite3_column_int(pXInfo, 1);
  176391. int bDesc = sqlite3_column_int(pXInfo, 3);
  176392. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  176393. const char *zCol;
  176394. const char *zType;
  176395. if( iCid<0 ){
  176396. /* An integer primary key. If the table has an explicit IPK, use
  176397. ** its name. Otherwise, use "rbu_rowid". */
  176398. if( pIter->eType==RBU_PK_IPK ){
  176399. int i;
  176400. for(i=0; pIter->abTblPk[i]==0; i++);
  176401. assert( i<pIter->nTblCol );
  176402. zCol = pIter->azTblCol[i];
  176403. }else if( rbuIsVacuum(p) ){
  176404. zCol = "_rowid_";
  176405. }else{
  176406. zCol = "rbu_rowid";
  176407. }
  176408. zType = "INTEGER";
  176409. }else{
  176410. zCol = pIter->azTblCol[iCid];
  176411. zType = pIter->azTblType[iCid];
  176412. }
  176413. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  176414. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  176415. const char *zOrder = (bDesc ? " DESC" : "");
  176416. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  176417. zImpPK, zCom, nBind, zCol, zOrder
  176418. );
  176419. }
  176420. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  176421. zImpCols, zCom, nBind, zCol, zType, zCollate
  176422. );
  176423. zWhere = sqlite3_mprintf(
  176424. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  176425. );
  176426. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  176427. zCom = ", ";
  176428. zAnd = " AND ";
  176429. nBind++;
  176430. }
  176431. rc2 = sqlite3_finalize(pXInfo);
  176432. if( rc==SQLITE_OK ) rc = rc2;
  176433. if( rc!=SQLITE_OK ){
  176434. sqlite3_free(zRet);
  176435. sqlite3_free(zImpCols);
  176436. sqlite3_free(zImpPK);
  176437. sqlite3_free(zWhere);
  176438. zRet = 0;
  176439. zImpCols = 0;
  176440. zImpPK = 0;
  176441. zWhere = 0;
  176442. p->rc = rc;
  176443. }
  176444. *pzImposterCols = zImpCols;
  176445. *pzImposterPk = zImpPK;
  176446. *pzWhere = zWhere;
  176447. *pnBind = nBind;
  176448. return zRet;
  176449. }
  176450. /*
  176451. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  176452. ** paramter is passed "old", return a string of the form:
  176453. **
  176454. ** "old.a, old.b, old.b"
  176455. **
  176456. ** With the column names escaped.
  176457. **
  176458. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  176459. ** the text ", old._rowid_" to the returned value.
  176460. */
  176461. static char *rbuObjIterGetOldlist(
  176462. sqlite3rbu *p,
  176463. RbuObjIter *pIter,
  176464. const char *zObj
  176465. ){
  176466. char *zList = 0;
  176467. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  176468. const char *zS = "";
  176469. int i;
  176470. for(i=0; i<pIter->nTblCol; i++){
  176471. if( pIter->abIndexed[i] ){
  176472. const char *zCol = pIter->azTblCol[i];
  176473. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  176474. }else{
  176475. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  176476. }
  176477. zS = ", ";
  176478. if( zList==0 ){
  176479. p->rc = SQLITE_NOMEM;
  176480. break;
  176481. }
  176482. }
  176483. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  176484. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  176485. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  176486. }
  176487. }
  176488. return zList;
  176489. }
  176490. /*
  176491. ** Return an expression that can be used in a WHERE clause to match the
  176492. ** primary key of the current table. For example, if the table is:
  176493. **
  176494. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  176495. **
  176496. ** Return the string:
  176497. **
  176498. ** "b = ?1 AND c = ?2"
  176499. */
  176500. static char *rbuObjIterGetWhere(
  176501. sqlite3rbu *p,
  176502. RbuObjIter *pIter
  176503. ){
  176504. char *zList = 0;
  176505. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  176506. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  176507. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  176508. const char *zSep = "";
  176509. int i;
  176510. for(i=0; i<pIter->nTblCol; i++){
  176511. if( pIter->abTblPk[i] ){
  176512. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  176513. zSep = " AND ";
  176514. }
  176515. }
  176516. zList = rbuMPrintf(p,
  176517. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  176518. );
  176519. }else{
  176520. const char *zSep = "";
  176521. int i;
  176522. for(i=0; i<pIter->nTblCol; i++){
  176523. if( pIter->abTblPk[i] ){
  176524. const char *zCol = pIter->azTblCol[i];
  176525. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  176526. zSep = " AND ";
  176527. }
  176528. }
  176529. }
  176530. return zList;
  176531. }
  176532. /*
  176533. ** The SELECT statement iterating through the keys for the current object
  176534. ** (p->objiter.pSelect) currently points to a valid row. However, there
  176535. ** is something wrong with the rbu_control value in the rbu_control value
  176536. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  176537. ** of the RBU handle to something reflecting this.
  176538. */
  176539. static void rbuBadControlError(sqlite3rbu *p){
  176540. p->rc = SQLITE_ERROR;
  176541. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  176542. }
  176543. /*
  176544. ** Return a nul-terminated string containing the comma separated list of
  176545. ** assignments that should be included following the "SET" keyword of
  176546. ** an UPDATE statement used to update the table object that the iterator
  176547. ** passed as the second argument currently points to if the rbu_control
  176548. ** column of the data_xxx table entry is set to zMask.
  176549. **
  176550. ** The memory for the returned string is obtained from sqlite3_malloc().
  176551. ** It is the responsibility of the caller to eventually free it using
  176552. ** sqlite3_free().
  176553. **
  176554. ** If an OOM error is encountered when allocating space for the new
  176555. ** string, an error code is left in the rbu handle passed as the first
  176556. ** argument and NULL is returned. Or, if an error has already occurred
  176557. ** when this function is called, NULL is returned immediately, without
  176558. ** attempting the allocation or modifying the stored error code.
  176559. */
  176560. static char *rbuObjIterGetSetlist(
  176561. sqlite3rbu *p,
  176562. RbuObjIter *pIter,
  176563. const char *zMask
  176564. ){
  176565. char *zList = 0;
  176566. if( p->rc==SQLITE_OK ){
  176567. int i;
  176568. if( (int)strlen(zMask)!=pIter->nTblCol ){
  176569. rbuBadControlError(p);
  176570. }else{
  176571. const char *zSep = "";
  176572. for(i=0; i<pIter->nTblCol; i++){
  176573. char c = zMask[pIter->aiSrcOrder[i]];
  176574. if( c=='x' ){
  176575. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  176576. zList, zSep, pIter->azTblCol[i], i+1
  176577. );
  176578. zSep = ", ";
  176579. }
  176580. else if( c=='d' ){
  176581. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  176582. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  176583. );
  176584. zSep = ", ";
  176585. }
  176586. else if( c=='f' ){
  176587. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  176588. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  176589. );
  176590. zSep = ", ";
  176591. }
  176592. }
  176593. }
  176594. }
  176595. return zList;
  176596. }
  176597. /*
  176598. ** Return a nul-terminated string consisting of nByte comma separated
  176599. ** "?" expressions. For example, if nByte is 3, return a pointer to
  176600. ** a buffer containing the string "?,?,?".
  176601. **
  176602. ** The memory for the returned string is obtained from sqlite3_malloc().
  176603. ** It is the responsibility of the caller to eventually free it using
  176604. ** sqlite3_free().
  176605. **
  176606. ** If an OOM error is encountered when allocating space for the new
  176607. ** string, an error code is left in the rbu handle passed as the first
  176608. ** argument and NULL is returned. Or, if an error has already occurred
  176609. ** when this function is called, NULL is returned immediately, without
  176610. ** attempting the allocation or modifying the stored error code.
  176611. */
  176612. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  176613. char *zRet = 0;
  176614. int nByte = nBind*2 + 1;
  176615. zRet = (char*)rbuMalloc(p, nByte);
  176616. if( zRet ){
  176617. int i;
  176618. for(i=0; i<nBind; i++){
  176619. zRet[i*2] = '?';
  176620. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  176621. }
  176622. }
  176623. return zRet;
  176624. }
  176625. /*
  176626. ** The iterator currently points to a table (not index) of type
  176627. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  176628. ** declaration for the corresponding imposter table. For example,
  176629. ** if the iterator points to a table created as:
  176630. **
  176631. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  176632. **
  176633. ** this function returns:
  176634. **
  176635. ** PRIMARY KEY("b", "a" DESC)
  176636. */
  176637. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  176638. char *z = 0;
  176639. assert( pIter->zIdx==0 );
  176640. if( p->rc==SQLITE_OK ){
  176641. const char *zSep = "PRIMARY KEY(";
  176642. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  176643. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  176644. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  176645. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  176646. );
  176647. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  176648. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  176649. if( zOrig && strcmp(zOrig, "pk")==0 ){
  176650. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  176651. if( zIdx ){
  176652. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  176653. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  176654. );
  176655. }
  176656. break;
  176657. }
  176658. }
  176659. rbuFinalize(p, pXList);
  176660. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  176661. if( sqlite3_column_int(pXInfo, 5) ){
  176662. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  176663. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  176664. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  176665. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  176666. zSep = ", ";
  176667. }
  176668. }
  176669. z = rbuMPrintf(p, "%z)", z);
  176670. rbuFinalize(p, pXInfo);
  176671. }
  176672. return z;
  176673. }
  176674. /*
  176675. ** This function creates the second imposter table used when writing to
  176676. ** a table b-tree where the table has an external primary key. If the
  176677. ** iterator passed as the second argument does not currently point to
  176678. ** a table (not index) with an external primary key, this function is a
  176679. ** no-op.
  176680. **
  176681. ** Assuming the iterator does point to a table with an external PK, this
  176682. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  176683. ** used to access that PK index. For example, if the target table is
  176684. ** declared as follows:
  176685. **
  176686. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  176687. **
  176688. ** then the imposter table schema is:
  176689. **
  176690. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  176691. **
  176692. */
  176693. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  176694. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  176695. int tnum = pIter->iPkTnum; /* Root page of PK index */
  176696. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  176697. const char *zIdx = 0; /* Name of PK index */
  176698. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  176699. const char *zComma = "";
  176700. char *zCols = 0; /* Used to build up list of table cols */
  176701. char *zPk = 0; /* Used to build up table PK declaration */
  176702. /* Figure out the name of the primary key index for the current table.
  176703. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  176704. ** zIdx to point to a nul-terminated string containing this name. */
  176705. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  176706. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  176707. );
  176708. if( p->rc==SQLITE_OK ){
  176709. sqlite3_bind_int(pQuery, 1, tnum);
  176710. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  176711. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  176712. }
  176713. }
  176714. if( zIdx ){
  176715. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  176716. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  176717. );
  176718. }
  176719. rbuFinalize(p, pQuery);
  176720. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  176721. int bKey = sqlite3_column_int(pXInfo, 5);
  176722. if( bKey ){
  176723. int iCid = sqlite3_column_int(pXInfo, 1);
  176724. int bDesc = sqlite3_column_int(pXInfo, 3);
  176725. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  176726. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma,
  176727. iCid, pIter->azTblType[iCid], zCollate
  176728. );
  176729. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  176730. zComma = ", ";
  176731. }
  176732. }
  176733. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  176734. rbuFinalize(p, pXInfo);
  176735. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  176736. rbuMPrintfExec(p, p->dbMain,
  176737. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  176738. zCols, zPk
  176739. );
  176740. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  176741. }
  176742. }
  176743. /*
  176744. ** If an error has already occurred when this function is called, it
  176745. ** immediately returns zero (without doing any work). Or, if an error
  176746. ** occurs during the execution of this function, it sets the error code
  176747. ** in the sqlite3rbu object indicated by the first argument and returns
  176748. ** zero.
  176749. **
  176750. ** The iterator passed as the second argument is guaranteed to point to
  176751. ** a table (not an index) when this function is called. This function
  176752. ** attempts to create any imposter table required to write to the main
  176753. ** table b-tree of the table before returning. Non-zero is returned if
  176754. ** an imposter table are created, or zero otherwise.
  176755. **
  176756. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  176757. ** virtual tables are written to directly. The imposter table has the
  176758. ** same schema as the actual target table (less any UNIQUE constraints).
  176759. ** More precisely, the "same schema" means the same columns, types,
  176760. ** collation sequences. For tables that do not have an external PRIMARY
  176761. ** KEY, it also means the same PRIMARY KEY declaration.
  176762. */
  176763. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  176764. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  176765. int tnum = pIter->iTnum;
  176766. const char *zComma = "";
  176767. char *zSql = 0;
  176768. int iCol;
  176769. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  176770. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  176771. const char *zPk = "";
  176772. const char *zCol = pIter->azTblCol[iCol];
  176773. const char *zColl = 0;
  176774. p->rc = sqlite3_table_column_metadata(
  176775. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  176776. );
  176777. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  176778. /* If the target table column is an "INTEGER PRIMARY KEY", add
  176779. ** "PRIMARY KEY" to the imposter table column declaration. */
  176780. zPk = "PRIMARY KEY ";
  176781. }
  176782. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
  176783. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  176784. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  176785. );
  176786. zComma = ", ";
  176787. }
  176788. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  176789. char *zPk = rbuWithoutRowidPK(p, pIter);
  176790. if( zPk ){
  176791. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  176792. }
  176793. }
  176794. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  176795. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  176796. pIter->zTbl, zSql,
  176797. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  176798. );
  176799. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  176800. }
  176801. }
  176802. /*
  176803. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  176804. ** Specifically a statement of the form:
  176805. **
  176806. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  176807. **
  176808. ** The number of bound variables is equal to the number of columns in
  176809. ** the target table, plus one (for the rbu_control column), plus one more
  176810. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  176811. ** virtual table.
  176812. */
  176813. static void rbuObjIterPrepareTmpInsert(
  176814. sqlite3rbu *p,
  176815. RbuObjIter *pIter,
  176816. const char *zCollist,
  176817. const char *zRbuRowid
  176818. ){
  176819. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  176820. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  176821. if( zBind ){
  176822. assert( pIter->pTmpInsert==0 );
  176823. p->rc = prepareFreeAndCollectError(
  176824. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  176825. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  176826. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  176827. ));
  176828. }
  176829. }
  176830. static void rbuTmpInsertFunc(
  176831. sqlite3_context *pCtx,
  176832. int nVal,
  176833. sqlite3_value **apVal
  176834. ){
  176835. sqlite3rbu *p = sqlite3_user_data(pCtx);
  176836. int rc = SQLITE_OK;
  176837. int i;
  176838. assert( sqlite3_value_int(apVal[0])!=0
  176839. || p->objiter.eType==RBU_PK_EXTERNAL
  176840. || p->objiter.eType==RBU_PK_NONE
  176841. );
  176842. if( sqlite3_value_int(apVal[0])!=0 ){
  176843. p->nPhaseOneStep += p->objiter.nIndex;
  176844. }
  176845. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  176846. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  176847. }
  176848. if( rc==SQLITE_OK ){
  176849. sqlite3_step(p->objiter.pTmpInsert);
  176850. rc = sqlite3_reset(p->objiter.pTmpInsert);
  176851. }
  176852. if( rc!=SQLITE_OK ){
  176853. sqlite3_result_error_code(pCtx, rc);
  176854. }
  176855. }
  176856. /*
  176857. ** Ensure that the SQLite statement handles required to update the
  176858. ** target database object currently indicated by the iterator passed
  176859. ** as the second argument are available.
  176860. */
  176861. static int rbuObjIterPrepareAll(
  176862. sqlite3rbu *p,
  176863. RbuObjIter *pIter,
  176864. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  176865. ){
  176866. assert( pIter->bCleanup==0 );
  176867. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  176868. const int tnum = pIter->iTnum;
  176869. char *zCollist = 0; /* List of indexed columns */
  176870. char **pz = &p->zErrmsg;
  176871. const char *zIdx = pIter->zIdx;
  176872. char *zLimit = 0;
  176873. if( nOffset ){
  176874. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  176875. if( !zLimit ) p->rc = SQLITE_NOMEM;
  176876. }
  176877. if( zIdx ){
  176878. const char *zTbl = pIter->zTbl;
  176879. char *zImposterCols = 0; /* Columns for imposter table */
  176880. char *zImposterPK = 0; /* Primary key declaration for imposter */
  176881. char *zWhere = 0; /* WHERE clause on PK columns */
  176882. char *zBind = 0;
  176883. int nBind = 0;
  176884. assert( pIter->eType!=RBU_PK_VTAB );
  176885. zCollist = rbuObjIterGetIndexCols(
  176886. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  176887. );
  176888. zBind = rbuObjIterGetBindlist(p, nBind);
  176889. /* Create the imposter table used to write to this index. */
  176890. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  176891. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  176892. rbuMPrintfExec(p, p->dbMain,
  176893. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  176894. zTbl, zImposterCols, zImposterPK
  176895. );
  176896. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  176897. /* Create the statement to insert index entries */
  176898. pIter->nCol = nBind;
  176899. if( p->rc==SQLITE_OK ){
  176900. p->rc = prepareFreeAndCollectError(
  176901. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  176902. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  176903. );
  176904. }
  176905. /* And to delete index entries */
  176906. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  176907. p->rc = prepareFreeAndCollectError(
  176908. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  176909. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  176910. );
  176911. }
  176912. /* Create the SELECT statement to read keys in sorted order */
  176913. if( p->rc==SQLITE_OK ){
  176914. char *zSql;
  176915. if( rbuIsVacuum(p) ){
  176916. zSql = sqlite3_mprintf(
  176917. "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
  176918. zCollist,
  176919. pIter->zDataTbl,
  176920. zCollist, zLimit
  176921. );
  176922. }else
  176923. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  176924. zSql = sqlite3_mprintf(
  176925. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
  176926. zCollist, p->zStateDb, pIter->zDataTbl,
  176927. zCollist, zLimit
  176928. );
  176929. }else{
  176930. zSql = sqlite3_mprintf(
  176931. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
  176932. "UNION ALL "
  176933. "SELECT %s, rbu_control FROM '%q' "
  176934. "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
  176935. "ORDER BY %s%s",
  176936. zCollist, p->zStateDb, pIter->zDataTbl,
  176937. zCollist, pIter->zDataTbl,
  176938. zCollist, zLimit
  176939. );
  176940. }
  176941. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
  176942. }
  176943. sqlite3_free(zImposterCols);
  176944. sqlite3_free(zImposterPK);
  176945. sqlite3_free(zWhere);
  176946. sqlite3_free(zBind);
  176947. }else{
  176948. int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
  176949. ||(pIter->eType==RBU_PK_NONE)
  176950. ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
  176951. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  176952. const char *zWrite; /* Imposter table name */
  176953. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  176954. char *zWhere = rbuObjIterGetWhere(p, pIter);
  176955. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  176956. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  176957. zCollist = rbuObjIterGetCollist(p, pIter);
  176958. pIter->nCol = pIter->nTblCol;
  176959. /* Create the imposter table or tables (if required). */
  176960. rbuCreateImposterTable(p, pIter);
  176961. rbuCreateImposterTable2(p, pIter);
  176962. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  176963. /* Create the INSERT statement to write to the target PK b-tree */
  176964. if( p->rc==SQLITE_OK ){
  176965. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  176966. sqlite3_mprintf(
  176967. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  176968. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  176969. )
  176970. );
  176971. }
  176972. /* Create the DELETE statement to write to the target PK b-tree.
  176973. ** Because it only performs INSERT operations, this is not required for
  176974. ** an rbu vacuum handle. */
  176975. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  176976. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  176977. sqlite3_mprintf(
  176978. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  176979. )
  176980. );
  176981. }
  176982. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  176983. const char *zRbuRowid = "";
  176984. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  176985. zRbuRowid = ", rbu_rowid";
  176986. }
  176987. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  176988. rbuMPrintfExec(p, p->dbRbu,
  176989. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  176990. "SELECT *%s FROM '%q' WHERE 0;"
  176991. , p->zStateDb, pIter->zDataTbl
  176992. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  176993. , pIter->zDataTbl
  176994. );
  176995. rbuMPrintfExec(p, p->dbMain,
  176996. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  176997. "BEGIN "
  176998. " SELECT rbu_tmp_insert(3, %s);"
  176999. "END;"
  177000. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  177001. "BEGIN "
  177002. " SELECT rbu_tmp_insert(3, %s);"
  177003. "END;"
  177004. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  177005. "BEGIN "
  177006. " SELECT rbu_tmp_insert(4, %s);"
  177007. "END;",
  177008. zWrite, zTbl, zOldlist,
  177009. zWrite, zTbl, zOldlist,
  177010. zWrite, zTbl, zNewlist
  177011. );
  177012. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  177013. rbuMPrintfExec(p, p->dbMain,
  177014. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  177015. "BEGIN "
  177016. " SELECT rbu_tmp_insert(0, %s);"
  177017. "END;",
  177018. zWrite, zTbl, zNewlist
  177019. );
  177020. }
  177021. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  177022. }
  177023. /* Create the SELECT statement to read keys from data_xxx */
  177024. if( p->rc==SQLITE_OK ){
  177025. const char *zRbuRowid = "";
  177026. if( bRbuRowid ){
  177027. zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
  177028. }
  177029. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  177030. sqlite3_mprintf(
  177031. "SELECT %s,%s rbu_control%s FROM '%q'%s",
  177032. zCollist,
  177033. (rbuIsVacuum(p) ? "0 AS " : ""),
  177034. zRbuRowid,
  177035. pIter->zDataTbl, zLimit
  177036. )
  177037. );
  177038. }
  177039. sqlite3_free(zWhere);
  177040. sqlite3_free(zOldlist);
  177041. sqlite3_free(zNewlist);
  177042. sqlite3_free(zBindings);
  177043. }
  177044. sqlite3_free(zCollist);
  177045. sqlite3_free(zLimit);
  177046. }
  177047. return p->rc;
  177048. }
  177049. /*
  177050. ** Set output variable *ppStmt to point to an UPDATE statement that may
  177051. ** be used to update the imposter table for the main table b-tree of the
  177052. ** table object that pIter currently points to, assuming that the
  177053. ** rbu_control column of the data_xyz table contains zMask.
  177054. **
  177055. ** If the zMask string does not specify any columns to update, then this
  177056. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  177057. */
  177058. static int rbuGetUpdateStmt(
  177059. sqlite3rbu *p, /* RBU handle */
  177060. RbuObjIter *pIter, /* Object iterator */
  177061. const char *zMask, /* rbu_control value ('x.x.') */
  177062. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  177063. ){
  177064. RbuUpdateStmt **pp;
  177065. RbuUpdateStmt *pUp = 0;
  177066. int nUp = 0;
  177067. /* In case an error occurs */
  177068. *ppStmt = 0;
  177069. /* Search for an existing statement. If one is found, shift it to the front
  177070. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  177071. ** to the number of statements currently in the cache and pUp to the
  177072. ** last object in the list. */
  177073. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  177074. pUp = *pp;
  177075. if( strcmp(pUp->zMask, zMask)==0 ){
  177076. *pp = pUp->pNext;
  177077. pUp->pNext = pIter->pRbuUpdate;
  177078. pIter->pRbuUpdate = pUp;
  177079. *ppStmt = pUp->pUpdate;
  177080. return SQLITE_OK;
  177081. }
  177082. nUp++;
  177083. }
  177084. assert( pUp==0 || pUp->pNext==0 );
  177085. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  177086. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  177087. *pp = 0;
  177088. sqlite3_finalize(pUp->pUpdate);
  177089. pUp->pUpdate = 0;
  177090. }else{
  177091. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  177092. }
  177093. if( pUp ){
  177094. char *zWhere = rbuObjIterGetWhere(p, pIter);
  177095. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  177096. char *zUpdate = 0;
  177097. pUp->zMask = (char*)&pUp[1];
  177098. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  177099. pUp->pNext = pIter->pRbuUpdate;
  177100. pIter->pRbuUpdate = pUp;
  177101. if( zSet ){
  177102. const char *zPrefix = "";
  177103. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  177104. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  177105. zPrefix, pIter->zTbl, zSet, zWhere
  177106. );
  177107. p->rc = prepareFreeAndCollectError(
  177108. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  177109. );
  177110. *ppStmt = pUp->pUpdate;
  177111. }
  177112. sqlite3_free(zWhere);
  177113. sqlite3_free(zSet);
  177114. }
  177115. return p->rc;
  177116. }
  177117. static sqlite3 *rbuOpenDbhandle(
  177118. sqlite3rbu *p,
  177119. const char *zName,
  177120. int bUseVfs
  177121. ){
  177122. sqlite3 *db = 0;
  177123. if( p->rc==SQLITE_OK ){
  177124. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  177125. p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
  177126. if( p->rc ){
  177127. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  177128. sqlite3_close(db);
  177129. db = 0;
  177130. }
  177131. }
  177132. return db;
  177133. }
  177134. /*
  177135. ** Free an RbuState object allocated by rbuLoadState().
  177136. */
  177137. static void rbuFreeState(RbuState *p){
  177138. if( p ){
  177139. sqlite3_free(p->zTbl);
  177140. sqlite3_free(p->zDataTbl);
  177141. sqlite3_free(p->zIdx);
  177142. sqlite3_free(p);
  177143. }
  177144. }
  177145. /*
  177146. ** Allocate an RbuState object and load the contents of the rbu_state
  177147. ** table into it. Return a pointer to the new object. It is the
  177148. ** responsibility of the caller to eventually free the object using
  177149. ** sqlite3_free().
  177150. **
  177151. ** If an error occurs, leave an error code and message in the rbu handle
  177152. ** and return NULL.
  177153. */
  177154. static RbuState *rbuLoadState(sqlite3rbu *p){
  177155. RbuState *pRet = 0;
  177156. sqlite3_stmt *pStmt = 0;
  177157. int rc;
  177158. int rc2;
  177159. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  177160. if( pRet==0 ) return 0;
  177161. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  177162. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  177163. );
  177164. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  177165. switch( sqlite3_column_int(pStmt, 0) ){
  177166. case RBU_STATE_STAGE:
  177167. pRet->eStage = sqlite3_column_int(pStmt, 1);
  177168. if( pRet->eStage!=RBU_STAGE_OAL
  177169. && pRet->eStage!=RBU_STAGE_MOVE
  177170. && pRet->eStage!=RBU_STAGE_CKPT
  177171. ){
  177172. p->rc = SQLITE_CORRUPT;
  177173. }
  177174. break;
  177175. case RBU_STATE_TBL:
  177176. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  177177. break;
  177178. case RBU_STATE_IDX:
  177179. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  177180. break;
  177181. case RBU_STATE_ROW:
  177182. pRet->nRow = sqlite3_column_int(pStmt, 1);
  177183. break;
  177184. case RBU_STATE_PROGRESS:
  177185. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  177186. break;
  177187. case RBU_STATE_CKPT:
  177188. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  177189. break;
  177190. case RBU_STATE_COOKIE:
  177191. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  177192. break;
  177193. case RBU_STATE_OALSZ:
  177194. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  177195. break;
  177196. case RBU_STATE_PHASEONESTEP:
  177197. pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
  177198. break;
  177199. case RBU_STATE_DATATBL:
  177200. pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  177201. break;
  177202. default:
  177203. rc = SQLITE_CORRUPT;
  177204. break;
  177205. }
  177206. }
  177207. rc2 = sqlite3_finalize(pStmt);
  177208. if( rc==SQLITE_OK ) rc = rc2;
  177209. p->rc = rc;
  177210. return pRet;
  177211. }
  177212. /*
  177213. ** Open the database handle and attach the RBU database as "rbu". If an
  177214. ** error occurs, leave an error code and message in the RBU handle.
  177215. */
  177216. static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
  177217. assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
  177218. assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
  177219. /* Open the RBU database */
  177220. p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
  177221. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  177222. sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  177223. if( p->zState==0 ){
  177224. const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
  177225. p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
  177226. }
  177227. }
  177228. /* If using separate RBU and state databases, attach the state database to
  177229. ** the RBU db handle now. */
  177230. if( p->zState ){
  177231. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  177232. memcpy(p->zStateDb, "stat", 4);
  177233. }else{
  177234. memcpy(p->zStateDb, "main", 4);
  177235. }
  177236. #if 0
  177237. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  177238. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
  177239. }
  177240. #endif
  177241. /* If it has not already been created, create the rbu_state table */
  177242. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  177243. #if 0
  177244. if( rbuIsVacuum(p) ){
  177245. if( p->rc==SQLITE_OK ){
  177246. int rc2;
  177247. int bOk = 0;
  177248. sqlite3_stmt *pCnt = 0;
  177249. p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
  177250. "SELECT count(*) FROM stat.sqlite_master"
  177251. );
  177252. if( p->rc==SQLITE_OK
  177253. && sqlite3_step(pCnt)==SQLITE_ROW
  177254. && 1==sqlite3_column_int(pCnt, 0)
  177255. ){
  177256. bOk = 1;
  177257. }
  177258. rc2 = sqlite3_finalize(pCnt);
  177259. if( p->rc==SQLITE_OK ) p->rc = rc2;
  177260. if( p->rc==SQLITE_OK && bOk==0 ){
  177261. p->rc = SQLITE_ERROR;
  177262. p->zErrmsg = sqlite3_mprintf("invalid state database");
  177263. }
  177264. if( p->rc==SQLITE_OK ){
  177265. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  177266. }
  177267. }
  177268. }
  177269. #endif
  177270. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  177271. int bOpen = 0;
  177272. int rc;
  177273. p->nRbu = 0;
  177274. p->pRbuFd = 0;
  177275. rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  177276. if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
  177277. if( p->eStage>=RBU_STAGE_MOVE ){
  177278. bOpen = 1;
  177279. }else{
  177280. RbuState *pState = rbuLoadState(p);
  177281. if( pState ){
  177282. bOpen = (pState->eStage>=RBU_STAGE_MOVE);
  177283. rbuFreeState(pState);
  177284. }
  177285. }
  177286. if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
  177287. }
  177288. p->eStage = 0;
  177289. if( p->rc==SQLITE_OK && p->dbMain==0 ){
  177290. if( !rbuIsVacuum(p) ){
  177291. p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
  177292. }else if( p->pRbuFd->pWalFd ){
  177293. if( pbRetry ){
  177294. p->pRbuFd->bNolock = 0;
  177295. sqlite3_close(p->dbRbu);
  177296. sqlite3_close(p->dbMain);
  177297. p->dbMain = 0;
  177298. p->dbRbu = 0;
  177299. *pbRetry = 1;
  177300. return;
  177301. }
  177302. p->rc = SQLITE_ERROR;
  177303. p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
  177304. }else{
  177305. char *zTarget;
  177306. char *zExtra = 0;
  177307. if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
  177308. zExtra = &p->zRbu[5];
  177309. while( *zExtra ){
  177310. if( *zExtra++=='?' ) break;
  177311. }
  177312. if( *zExtra=='\0' ) zExtra = 0;
  177313. }
  177314. zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
  177315. sqlite3_db_filename(p->dbRbu, "main"),
  177316. (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
  177317. );
  177318. if( zTarget==0 ){
  177319. p->rc = SQLITE_NOMEM;
  177320. return;
  177321. }
  177322. p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
  177323. sqlite3_free(zTarget);
  177324. }
  177325. }
  177326. if( p->rc==SQLITE_OK ){
  177327. p->rc = sqlite3_create_function(p->dbMain,
  177328. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  177329. );
  177330. }
  177331. if( p->rc==SQLITE_OK ){
  177332. p->rc = sqlite3_create_function(p->dbMain,
  177333. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  177334. );
  177335. }
  177336. if( p->rc==SQLITE_OK ){
  177337. p->rc = sqlite3_create_function(p->dbRbu,
  177338. "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  177339. );
  177340. }
  177341. if( p->rc==SQLITE_OK ){
  177342. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  177343. }
  177344. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  177345. /* Mark the database file just opened as an RBU target database. If
  177346. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  177347. ** This is an error. */
  177348. if( p->rc==SQLITE_OK ){
  177349. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  177350. }
  177351. if( p->rc==SQLITE_NOTFOUND ){
  177352. p->rc = SQLITE_ERROR;
  177353. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  177354. }
  177355. }
  177356. /*
  177357. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  177358. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  177359. **
  177360. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  177361. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  177362. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  177363. ** three characters, then shorten the suffix on z[] to be the last three
  177364. ** characters of the original suffix.
  177365. **
  177366. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  177367. ** do the suffix shortening regardless of URI parameter.
  177368. **
  177369. ** Examples:
  177370. **
  177371. ** test.db-journal => test.nal
  177372. ** test.db-wal => test.wal
  177373. ** test.db-shm => test.shm
  177374. ** test.db-mj7f3319fa => test.9fa
  177375. */
  177376. static void rbuFileSuffix3(const char *zBase, char *z){
  177377. #ifdef SQLITE_ENABLE_8_3_NAMES
  177378. #if SQLITE_ENABLE_8_3_NAMES<2
  177379. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  177380. #endif
  177381. {
  177382. int i, sz;
  177383. sz = (int)strlen(z)&0xffffff;
  177384. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  177385. if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
  177386. }
  177387. #endif
  177388. }
  177389. /*
  177390. ** Return the current wal-index header checksum for the target database
  177391. ** as a 64-bit integer.
  177392. **
  177393. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  177394. ** blob starting at byte offset 40.
  177395. */
  177396. static i64 rbuShmChecksum(sqlite3rbu *p){
  177397. i64 iRet = 0;
  177398. if( p->rc==SQLITE_OK ){
  177399. sqlite3_file *pDb = p->pTargetFd->pReal;
  177400. u32 volatile *ptr;
  177401. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  177402. if( p->rc==SQLITE_OK ){
  177403. iRet = ((i64)ptr[10] << 32) + ptr[11];
  177404. }
  177405. }
  177406. return iRet;
  177407. }
  177408. /*
  177409. ** This function is called as part of initializing or reinitializing an
  177410. ** incremental checkpoint.
  177411. **
  177412. ** It populates the sqlite3rbu.aFrame[] array with the set of
  177413. ** (wal frame -> db page) copy operations required to checkpoint the
  177414. ** current wal file, and obtains the set of shm locks required to safely
  177415. ** perform the copy operations directly on the file-system.
  177416. **
  177417. ** If argument pState is not NULL, then the incremental checkpoint is
  177418. ** being resumed. In this case, if the checksum of the wal-index-header
  177419. ** following recovery is not the same as the checksum saved in the RbuState
  177420. ** object, then the rbu handle is set to DONE state. This occurs if some
  177421. ** other client appends a transaction to the wal file in the middle of
  177422. ** an incremental checkpoint.
  177423. */
  177424. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  177425. /* If pState is NULL, then the wal file may not have been opened and
  177426. ** recovered. Running a read-statement here to ensure that doing so
  177427. ** does not interfere with the "capture" process below. */
  177428. if( pState==0 ){
  177429. p->eStage = 0;
  177430. if( p->rc==SQLITE_OK ){
  177431. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  177432. }
  177433. }
  177434. /* Assuming no error has occurred, run a "restart" checkpoint with the
  177435. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  177436. ** special behaviour in the rbu VFS:
  177437. **
  177438. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  177439. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  177440. ** proceed with running a passive checkpoint instead of failing).
  177441. **
  177442. ** * Attempts to read from the *-wal file or write to the database file
  177443. ** do not perform any IO. Instead, the frame/page combinations that
  177444. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  177445. ** array.
  177446. **
  177447. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  177448. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  177449. ** no-ops. These locks will not be released until the connection
  177450. ** is closed.
  177451. **
  177452. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  177453. ** error.
  177454. **
  177455. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  177456. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  177457. ** array populated with a set of (frame -> page) mappings. Because the
  177458. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  177459. ** data from the wal file into the database file according to the
  177460. ** contents of aFrame[].
  177461. */
  177462. if( p->rc==SQLITE_OK ){
  177463. int rc2;
  177464. p->eStage = RBU_STAGE_CAPTURE;
  177465. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  177466. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  177467. }
  177468. if( p->rc==SQLITE_OK && p->nFrame>0 ){
  177469. p->eStage = RBU_STAGE_CKPT;
  177470. p->nStep = (pState ? pState->nRow : 0);
  177471. p->aBuf = rbuMalloc(p, p->pgsz);
  177472. p->iWalCksum = rbuShmChecksum(p);
  177473. }
  177474. if( p->rc==SQLITE_OK ){
  177475. if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
  177476. p->rc = SQLITE_DONE;
  177477. p->eStage = RBU_STAGE_DONE;
  177478. }else{
  177479. int nSectorSize;
  177480. sqlite3_file *pDb = p->pTargetFd->pReal;
  177481. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  177482. assert( p->nPagePerSector==0 );
  177483. nSectorSize = pDb->pMethods->xSectorSize(pDb);
  177484. if( nSectorSize>p->pgsz ){
  177485. p->nPagePerSector = nSectorSize / p->pgsz;
  177486. }else{
  177487. p->nPagePerSector = 1;
  177488. }
  177489. /* Call xSync() on the wal file. This causes SQLite to sync the
  177490. ** directory in which the target database and the wal file reside, in
  177491. ** case it has not been synced since the rename() call in
  177492. ** rbuMoveOalFile(). */
  177493. p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
  177494. }
  177495. }
  177496. }
  177497. /*
  177498. ** Called when iAmt bytes are read from offset iOff of the wal file while
  177499. ** the rbu object is in capture mode. Record the frame number of the frame
  177500. ** being read in the aFrame[] array.
  177501. */
  177502. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  177503. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  177504. u32 iFrame;
  177505. if( pRbu->mLock!=mReq ){
  177506. pRbu->rc = SQLITE_BUSY;
  177507. return SQLITE_INTERNAL;
  177508. }
  177509. pRbu->pgsz = iAmt;
  177510. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  177511. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  177512. RbuFrame *aNew;
  177513. aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
  177514. if( aNew==0 ) return SQLITE_NOMEM;
  177515. pRbu->aFrame = aNew;
  177516. pRbu->nFrameAlloc = nNew;
  177517. }
  177518. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  177519. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  177520. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  177521. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  177522. pRbu->nFrame++;
  177523. return SQLITE_OK;
  177524. }
  177525. /*
  177526. ** Called when a page of data is written to offset iOff of the database
  177527. ** file while the rbu handle is in capture mode. Record the page number
  177528. ** of the page being written in the aFrame[] array.
  177529. */
  177530. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  177531. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  177532. return SQLITE_OK;
  177533. }
  177534. /*
  177535. ** This is called as part of an incremental checkpoint operation. Copy
  177536. ** a single frame of data from the wal file into the database file, as
  177537. ** indicated by the RbuFrame object.
  177538. */
  177539. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  177540. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  177541. sqlite3_file *pDb = p->pTargetFd->pReal;
  177542. i64 iOff;
  177543. assert( p->rc==SQLITE_OK );
  177544. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  177545. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  177546. if( p->rc ) return;
  177547. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  177548. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  177549. }
  177550. /*
  177551. ** Take an EXCLUSIVE lock on the database file.
  177552. */
  177553. static void rbuLockDatabase(sqlite3rbu *p){
  177554. sqlite3_file *pReal = p->pTargetFd->pReal;
  177555. assert( p->rc==SQLITE_OK );
  177556. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  177557. if( p->rc==SQLITE_OK ){
  177558. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  177559. }
  177560. }
  177561. #if defined(_WIN32_WCE)
  177562. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  177563. int nChar;
  177564. LPWSTR zWideFilename;
  177565. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  177566. if( nChar==0 ){
  177567. return 0;
  177568. }
  177569. zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
  177570. if( zWideFilename==0 ){
  177571. return 0;
  177572. }
  177573. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  177574. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  177575. nChar);
  177576. if( nChar==0 ){
  177577. sqlite3_free(zWideFilename);
  177578. zWideFilename = 0;
  177579. }
  177580. return zWideFilename;
  177581. }
  177582. #endif
  177583. /*
  177584. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  177585. ** on the database file. This proc moves the *-oal file to the *-wal path,
  177586. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  177587. ** If an error occurs, leave an error code and error message in the rbu
  177588. ** handle.
  177589. */
  177590. static void rbuMoveOalFile(sqlite3rbu *p){
  177591. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  177592. const char *zMove = zBase;
  177593. char *zOal;
  177594. char *zWal;
  177595. if( rbuIsVacuum(p) ){
  177596. zMove = sqlite3_db_filename(p->dbRbu, "main");
  177597. }
  177598. zOal = sqlite3_mprintf("%s-oal", zMove);
  177599. zWal = sqlite3_mprintf("%s-wal", zMove);
  177600. assert( p->eStage==RBU_STAGE_MOVE );
  177601. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  177602. if( zWal==0 || zOal==0 ){
  177603. p->rc = SQLITE_NOMEM;
  177604. }else{
  177605. /* Move the *-oal file to *-wal. At this point connection p->db is
  177606. ** holding a SHARED lock on the target database file (because it is
  177607. ** in WAL mode). So no other connection may be writing the db.
  177608. **
  177609. ** In order to ensure that there are no database readers, an EXCLUSIVE
  177610. ** lock is obtained here before the *-oal is moved to *-wal.
  177611. */
  177612. rbuLockDatabase(p);
  177613. if( p->rc==SQLITE_OK ){
  177614. rbuFileSuffix3(zBase, zWal);
  177615. rbuFileSuffix3(zBase, zOal);
  177616. /* Re-open the databases. */
  177617. rbuObjIterFinalize(&p->objiter);
  177618. sqlite3_close(p->dbRbu);
  177619. sqlite3_close(p->dbMain);
  177620. p->dbMain = 0;
  177621. p->dbRbu = 0;
  177622. #if defined(_WIN32_WCE)
  177623. {
  177624. LPWSTR zWideOal;
  177625. LPWSTR zWideWal;
  177626. zWideOal = rbuWinUtf8ToUnicode(zOal);
  177627. if( zWideOal ){
  177628. zWideWal = rbuWinUtf8ToUnicode(zWal);
  177629. if( zWideWal ){
  177630. if( MoveFileW(zWideOal, zWideWal) ){
  177631. p->rc = SQLITE_OK;
  177632. }else{
  177633. p->rc = SQLITE_IOERR;
  177634. }
  177635. sqlite3_free(zWideWal);
  177636. }else{
  177637. p->rc = SQLITE_IOERR_NOMEM;
  177638. }
  177639. sqlite3_free(zWideOal);
  177640. }else{
  177641. p->rc = SQLITE_IOERR_NOMEM;
  177642. }
  177643. }
  177644. #else
  177645. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  177646. #endif
  177647. if( p->rc==SQLITE_OK ){
  177648. rbuOpenDatabase(p, 0);
  177649. rbuSetupCheckpoint(p, 0);
  177650. }
  177651. }
  177652. }
  177653. sqlite3_free(zWal);
  177654. sqlite3_free(zOal);
  177655. }
  177656. /*
  177657. ** The SELECT statement iterating through the keys for the current object
  177658. ** (p->objiter.pSelect) currently points to a valid row. This function
  177659. ** determines the type of operation requested by this row and returns
  177660. ** one of the following values to indicate the result:
  177661. **
  177662. ** * RBU_INSERT
  177663. ** * RBU_DELETE
  177664. ** * RBU_IDX_DELETE
  177665. ** * RBU_UPDATE
  177666. **
  177667. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  177668. ** point to the text value indicating the columns to update.
  177669. **
  177670. ** If the rbu_control field contains an invalid value, an error code and
  177671. ** message are left in the RBU handle and zero returned.
  177672. */
  177673. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  177674. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  177675. int res = 0; /* Return value */
  177676. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  177677. case SQLITE_INTEGER: {
  177678. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  177679. switch( iVal ){
  177680. case 0: res = RBU_INSERT; break;
  177681. case 1: res = RBU_DELETE; break;
  177682. case 2: res = RBU_REPLACE; break;
  177683. case 3: res = RBU_IDX_DELETE; break;
  177684. case 4: res = RBU_IDX_INSERT; break;
  177685. }
  177686. break;
  177687. }
  177688. case SQLITE_TEXT: {
  177689. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  177690. if( z==0 ){
  177691. p->rc = SQLITE_NOMEM;
  177692. }else{
  177693. *pzMask = (const char*)z;
  177694. }
  177695. res = RBU_UPDATE;
  177696. break;
  177697. }
  177698. default:
  177699. break;
  177700. }
  177701. if( res==0 ){
  177702. rbuBadControlError(p);
  177703. }
  177704. return res;
  177705. }
  177706. #ifdef SQLITE_DEBUG
  177707. /*
  177708. ** Assert that column iCol of statement pStmt is named zName.
  177709. */
  177710. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  177711. const char *zCol = sqlite3_column_name(pStmt, iCol);
  177712. assert( 0==sqlite3_stricmp(zName, zCol) );
  177713. }
  177714. #else
  177715. # define assertColumnName(x,y,z)
  177716. #endif
  177717. /*
  177718. ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
  177719. ** RBU_IDX_DELETE. This function performs the work of a single
  177720. ** sqlite3rbu_step() call for the type of operation specified by eType.
  177721. */
  177722. static void rbuStepOneOp(sqlite3rbu *p, int eType){
  177723. RbuObjIter *pIter = &p->objiter;
  177724. sqlite3_value *pVal;
  177725. sqlite3_stmt *pWriter;
  177726. int i;
  177727. assert( p->rc==SQLITE_OK );
  177728. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  177729. assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
  177730. || eType==RBU_INSERT || eType==RBU_IDX_INSERT
  177731. );
  177732. /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
  177733. ** statement below does actually delete a row, nPhaseOneStep will be
  177734. ** incremented by the same amount when SQL function rbu_tmp_insert()
  177735. ** is invoked by the trigger. */
  177736. if( eType==RBU_DELETE ){
  177737. p->nPhaseOneStep -= p->objiter.nIndex;
  177738. }
  177739. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  177740. pWriter = pIter->pDelete;
  177741. }else{
  177742. pWriter = pIter->pInsert;
  177743. }
  177744. for(i=0; i<pIter->nCol; i++){
  177745. /* If this is an INSERT into a table b-tree and the table has an
  177746. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  177747. ** to write a NULL into the IPK column. That is not permitted. */
  177748. if( eType==RBU_INSERT
  177749. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  177750. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  177751. ){
  177752. p->rc = SQLITE_MISMATCH;
  177753. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  177754. return;
  177755. }
  177756. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  177757. continue;
  177758. }
  177759. pVal = sqlite3_column_value(pIter->pSelect, i);
  177760. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  177761. if( p->rc ) return;
  177762. }
  177763. if( pIter->zIdx==0 ){
  177764. if( pIter->eType==RBU_PK_VTAB
  177765. || pIter->eType==RBU_PK_NONE
  177766. || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
  177767. ){
  177768. /* For a virtual table, or a table with no primary key, the
  177769. ** SELECT statement is:
  177770. **
  177771. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  177772. **
  177773. ** Hence column_value(pIter->nCol+1).
  177774. */
  177775. assertColumnName(pIter->pSelect, pIter->nCol+1,
  177776. rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
  177777. );
  177778. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  177779. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  177780. }
  177781. }
  177782. if( p->rc==SQLITE_OK ){
  177783. sqlite3_step(pWriter);
  177784. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  177785. }
  177786. }
  177787. /*
  177788. ** This function does the work for an sqlite3rbu_step() call.
  177789. **
  177790. ** The object-iterator (p->objiter) currently points to a valid object,
  177791. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  177792. ** input row. Perform whatever processing is required and return.
  177793. **
  177794. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  177795. ** and message is left in the RBU handle and a copy of the error code
  177796. ** returned.
  177797. */
  177798. static int rbuStep(sqlite3rbu *p){
  177799. RbuObjIter *pIter = &p->objiter;
  177800. const char *zMask = 0;
  177801. int eType = rbuStepType(p, &zMask);
  177802. if( eType ){
  177803. assert( eType==RBU_INSERT || eType==RBU_DELETE
  177804. || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
  177805. || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
  177806. );
  177807. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  177808. if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
  177809. rbuBadControlError(p);
  177810. }
  177811. else if( eType==RBU_REPLACE ){
  177812. if( pIter->zIdx==0 ){
  177813. p->nPhaseOneStep += p->objiter.nIndex;
  177814. rbuStepOneOp(p, RBU_DELETE);
  177815. }
  177816. if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
  177817. }
  177818. else if( eType!=RBU_UPDATE ){
  177819. rbuStepOneOp(p, eType);
  177820. }
  177821. else{
  177822. sqlite3_value *pVal;
  177823. sqlite3_stmt *pUpdate = 0;
  177824. assert( eType==RBU_UPDATE );
  177825. p->nPhaseOneStep -= p->objiter.nIndex;
  177826. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  177827. if( pUpdate ){
  177828. int i;
  177829. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  177830. char c = zMask[pIter->aiSrcOrder[i]];
  177831. pVal = sqlite3_column_value(pIter->pSelect, i);
  177832. if( pIter->abTblPk[i] || c!='.' ){
  177833. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  177834. }
  177835. }
  177836. if( p->rc==SQLITE_OK
  177837. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  177838. ){
  177839. /* Bind the rbu_rowid value to column _rowid_ */
  177840. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  177841. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  177842. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  177843. }
  177844. if( p->rc==SQLITE_OK ){
  177845. sqlite3_step(pUpdate);
  177846. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  177847. }
  177848. }
  177849. }
  177850. }
  177851. return p->rc;
  177852. }
  177853. /*
  177854. ** Increment the schema cookie of the main database opened by p->dbMain.
  177855. **
  177856. ** Or, if this is an RBU vacuum, set the schema cookie of the main db
  177857. ** opened by p->dbMain to one more than the schema cookie of the main
  177858. ** db opened by p->dbRbu.
  177859. */
  177860. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  177861. if( p->rc==SQLITE_OK ){
  177862. sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  177863. int iCookie = 1000000;
  177864. sqlite3_stmt *pStmt;
  177865. p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
  177866. "PRAGMA schema_version"
  177867. );
  177868. if( p->rc==SQLITE_OK ){
  177869. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  177870. ** is already a transaction open, so the prepared statement cannot
  177871. ** throw an SQLITE_SCHEMA exception. The only database page the
  177872. ** statement reads is page 1, which is guaranteed to be in the cache.
  177873. ** And no memory allocations are required. */
  177874. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  177875. iCookie = sqlite3_column_int(pStmt, 0);
  177876. }
  177877. rbuFinalize(p, pStmt);
  177878. }
  177879. if( p->rc==SQLITE_OK ){
  177880. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  177881. }
  177882. }
  177883. }
  177884. /*
  177885. ** Update the contents of the rbu_state table within the rbu database. The
  177886. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  177887. ** are determined by inspecting the rbu handle passed as the first argument.
  177888. */
  177889. static void rbuSaveState(sqlite3rbu *p, int eStage){
  177890. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  177891. sqlite3_stmt *pInsert = 0;
  177892. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  177893. int rc;
  177894. assert( p->zErrmsg==0 );
  177895. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  177896. sqlite3_mprintf(
  177897. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  177898. "(%d, %d), "
  177899. "(%d, %Q), "
  177900. "(%d, %Q), "
  177901. "(%d, %d), "
  177902. "(%d, %d), "
  177903. "(%d, %lld), "
  177904. "(%d, %lld), "
  177905. "(%d, %lld), "
  177906. "(%d, %lld), "
  177907. "(%d, %Q) ",
  177908. p->zStateDb,
  177909. RBU_STATE_STAGE, eStage,
  177910. RBU_STATE_TBL, p->objiter.zTbl,
  177911. RBU_STATE_IDX, p->objiter.zIdx,
  177912. RBU_STATE_ROW, p->nStep,
  177913. RBU_STATE_PROGRESS, p->nProgress,
  177914. RBU_STATE_CKPT, p->iWalCksum,
  177915. RBU_STATE_COOKIE, (i64)pFd->iCookie,
  177916. RBU_STATE_OALSZ, p->iOalSz,
  177917. RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,
  177918. RBU_STATE_DATATBL, p->objiter.zDataTbl
  177919. )
  177920. );
  177921. assert( pInsert==0 || rc==SQLITE_OK );
  177922. if( rc==SQLITE_OK ){
  177923. sqlite3_step(pInsert);
  177924. rc = sqlite3_finalize(pInsert);
  177925. }
  177926. if( rc!=SQLITE_OK ) p->rc = rc;
  177927. }
  177928. }
  177929. /*
  177930. ** The second argument passed to this function is the name of a PRAGMA
  177931. ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
  177932. ** This function executes the following on sqlite3rbu.dbRbu:
  177933. **
  177934. ** "PRAGMA main.$zPragma"
  177935. **
  177936. ** where $zPragma is the string passed as the second argument, then
  177937. ** on sqlite3rbu.dbMain:
  177938. **
  177939. ** "PRAGMA main.$zPragma = $val"
  177940. **
  177941. ** where $val is the value returned by the first PRAGMA invocation.
  177942. **
  177943. ** In short, it copies the value of the specified PRAGMA setting from
  177944. ** dbRbu to dbMain.
  177945. */
  177946. static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
  177947. if( p->rc==SQLITE_OK ){
  177948. sqlite3_stmt *pPragma = 0;
  177949. p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
  177950. sqlite3_mprintf("PRAGMA main.%s", zPragma)
  177951. );
  177952. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
  177953. p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
  177954. zPragma, sqlite3_column_int(pPragma, 0)
  177955. );
  177956. }
  177957. rbuFinalize(p, pPragma);
  177958. }
  177959. }
  177960. /*
  177961. ** The RBU handle passed as the only argument has just been opened and
  177962. ** the state database is empty. If this RBU handle was opened for an
  177963. ** RBU vacuum operation, create the schema in the target db.
  177964. */
  177965. static void rbuCreateTargetSchema(sqlite3rbu *p){
  177966. sqlite3_stmt *pSql = 0;
  177967. sqlite3_stmt *pInsert = 0;
  177968. assert( rbuIsVacuum(p) );
  177969. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
  177970. if( p->rc==SQLITE_OK ){
  177971. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  177972. "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
  177973. " AND name!='sqlite_sequence' "
  177974. " ORDER BY type DESC"
  177975. );
  177976. }
  177977. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  177978. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  177979. p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
  177980. }
  177981. rbuFinalize(p, pSql);
  177982. if( p->rc!=SQLITE_OK ) return;
  177983. if( p->rc==SQLITE_OK ){
  177984. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  177985. "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
  177986. );
  177987. }
  177988. if( p->rc==SQLITE_OK ){
  177989. p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
  177990. "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
  177991. );
  177992. }
  177993. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  177994. int i;
  177995. for(i=0; i<5; i++){
  177996. sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
  177997. }
  177998. sqlite3_step(pInsert);
  177999. p->rc = sqlite3_reset(pInsert);
  178000. }
  178001. if( p->rc==SQLITE_OK ){
  178002. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
  178003. }
  178004. rbuFinalize(p, pSql);
  178005. rbuFinalize(p, pInsert);
  178006. }
  178007. /*
  178008. ** Step the RBU object.
  178009. */
  178010. SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
  178011. if( p ){
  178012. switch( p->eStage ){
  178013. case RBU_STAGE_OAL: {
  178014. RbuObjIter *pIter = &p->objiter;
  178015. /* If this is an RBU vacuum operation and the state table was empty
  178016. ** when this handle was opened, create the target database schema. */
  178017. if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
  178018. rbuCreateTargetSchema(p);
  178019. rbuCopyPragma(p, "user_version");
  178020. rbuCopyPragma(p, "application_id");
  178021. }
  178022. while( p->rc==SQLITE_OK && pIter->zTbl ){
  178023. if( pIter->bCleanup ){
  178024. /* Clean up the rbu_tmp_xxx table for the previous table. It
  178025. ** cannot be dropped as there are currently active SQL statements.
  178026. ** But the contents can be deleted. */
  178027. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  178028. rbuMPrintfExec(p, p->dbRbu,
  178029. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  178030. );
  178031. }
  178032. }else{
  178033. rbuObjIterPrepareAll(p, pIter, 0);
  178034. /* Advance to the next row to process. */
  178035. if( p->rc==SQLITE_OK ){
  178036. int rc = sqlite3_step(pIter->pSelect);
  178037. if( rc==SQLITE_ROW ){
  178038. p->nProgress++;
  178039. p->nStep++;
  178040. return rbuStep(p);
  178041. }
  178042. p->rc = sqlite3_reset(pIter->pSelect);
  178043. p->nStep = 0;
  178044. }
  178045. }
  178046. rbuObjIterNext(p, pIter);
  178047. }
  178048. if( p->rc==SQLITE_OK ){
  178049. assert( pIter->zTbl==0 );
  178050. rbuSaveState(p, RBU_STAGE_MOVE);
  178051. rbuIncrSchemaCookie(p);
  178052. if( p->rc==SQLITE_OK ){
  178053. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  178054. }
  178055. if( p->rc==SQLITE_OK ){
  178056. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  178057. }
  178058. p->eStage = RBU_STAGE_MOVE;
  178059. }
  178060. break;
  178061. }
  178062. case RBU_STAGE_MOVE: {
  178063. if( p->rc==SQLITE_OK ){
  178064. rbuMoveOalFile(p);
  178065. p->nProgress++;
  178066. }
  178067. break;
  178068. }
  178069. case RBU_STAGE_CKPT: {
  178070. if( p->rc==SQLITE_OK ){
  178071. if( p->nStep>=p->nFrame ){
  178072. sqlite3_file *pDb = p->pTargetFd->pReal;
  178073. /* Sync the db file */
  178074. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  178075. /* Update nBackfill */
  178076. if( p->rc==SQLITE_OK ){
  178077. void volatile *ptr;
  178078. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  178079. if( p->rc==SQLITE_OK ){
  178080. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  178081. }
  178082. }
  178083. if( p->rc==SQLITE_OK ){
  178084. p->eStage = RBU_STAGE_DONE;
  178085. p->rc = SQLITE_DONE;
  178086. }
  178087. }else{
  178088. /* At one point the following block copied a single frame from the
  178089. ** wal file to the database file. So that one call to sqlite3rbu_step()
  178090. ** checkpointed a single frame.
  178091. **
  178092. ** However, if the sector-size is larger than the page-size, and the
  178093. ** application calls sqlite3rbu_savestate() or close() immediately
  178094. ** after this step, then rbu_step() again, then a power failure occurs,
  178095. ** then the database page written here may be damaged. Work around
  178096. ** this by checkpointing frames until the next page in the aFrame[]
  178097. ** lies on a different disk sector to the current one. */
  178098. u32 iSector;
  178099. do{
  178100. RbuFrame *pFrame = &p->aFrame[p->nStep];
  178101. iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
  178102. rbuCheckpointFrame(p, pFrame);
  178103. p->nStep++;
  178104. }while( p->nStep<p->nFrame
  178105. && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
  178106. && p->rc==SQLITE_OK
  178107. );
  178108. }
  178109. p->nProgress++;
  178110. }
  178111. break;
  178112. }
  178113. default:
  178114. break;
  178115. }
  178116. return p->rc;
  178117. }else{
  178118. return SQLITE_NOMEM;
  178119. }
  178120. }
  178121. /*
  178122. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  178123. ** otherwise. Either or both argument may be NULL. Two NULL values are
  178124. ** considered equal, and NULL is considered distinct from all other values.
  178125. */
  178126. static int rbuStrCompare(const char *z1, const char *z2){
  178127. if( z1==0 && z2==0 ) return 0;
  178128. if( z1==0 || z2==0 ) return 1;
  178129. return (sqlite3_stricmp(z1, z2)!=0);
  178130. }
  178131. /*
  178132. ** This function is called as part of sqlite3rbu_open() when initializing
  178133. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  178134. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  178135. ** things so that the next call to sqlite3rbu_step() continues on from
  178136. ** where the previous rbu handle left off.
  178137. **
  178138. ** If an error occurs, an error code and error message are left in the
  178139. ** rbu handle passed as the first argument.
  178140. */
  178141. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  178142. assert( p->rc==SQLITE_OK );
  178143. if( pState->zTbl ){
  178144. RbuObjIter *pIter = &p->objiter;
  178145. int rc = SQLITE_OK;
  178146. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  178147. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  178148. || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
  178149. || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
  178150. )){
  178151. rc = rbuObjIterNext(p, pIter);
  178152. }
  178153. if( rc==SQLITE_OK && !pIter->zTbl ){
  178154. rc = SQLITE_ERROR;
  178155. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  178156. }
  178157. if( rc==SQLITE_OK ){
  178158. p->nStep = pState->nRow;
  178159. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  178160. }
  178161. p->rc = rc;
  178162. }
  178163. }
  178164. /*
  178165. ** If there is a "*-oal" file in the file-system corresponding to the
  178166. ** target database in the file-system, delete it. If an error occurs,
  178167. ** leave an error code and error message in the rbu handle.
  178168. */
  178169. static void rbuDeleteOalFile(sqlite3rbu *p){
  178170. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  178171. if( zOal ){
  178172. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  178173. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  178174. pVfs->xDelete(pVfs, zOal, 0);
  178175. sqlite3_free(zOal);
  178176. }
  178177. }
  178178. /*
  178179. ** Allocate a private rbu VFS for the rbu handle passed as the only
  178180. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  178181. ** specified a URI with a vfs=? option in place of a target database
  178182. ** file name.
  178183. */
  178184. static void rbuCreateVfs(sqlite3rbu *p){
  178185. int rnd;
  178186. char zRnd[64];
  178187. assert( p->rc==SQLITE_OK );
  178188. sqlite3_randomness(sizeof(int), (void*)&rnd);
  178189. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  178190. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  178191. if( p->rc==SQLITE_OK ){
  178192. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  178193. assert( pVfs );
  178194. p->zVfsName = pVfs->zName;
  178195. ((rbu_vfs*)pVfs)->pRbu = p;
  178196. }
  178197. }
  178198. /*
  178199. ** Destroy the private VFS created for the rbu handle passed as the only
  178200. ** argument by an earlier call to rbuCreateVfs().
  178201. */
  178202. static void rbuDeleteVfs(sqlite3rbu *p){
  178203. if( p->zVfsName ){
  178204. sqlite3rbu_destroy_vfs(p->zVfsName);
  178205. p->zVfsName = 0;
  178206. }
  178207. }
  178208. /*
  178209. ** This user-defined SQL function is invoked with a single argument - the
  178210. ** name of a table expected to appear in the target database. It returns
  178211. ** the number of auxilliary indexes on the table.
  178212. */
  178213. static void rbuIndexCntFunc(
  178214. sqlite3_context *pCtx,
  178215. int nVal,
  178216. sqlite3_value **apVal
  178217. ){
  178218. sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
  178219. sqlite3_stmt *pStmt = 0;
  178220. char *zErrmsg = 0;
  178221. int rc;
  178222. assert( nVal==1 );
  178223. rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
  178224. sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
  178225. "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
  178226. );
  178227. if( rc!=SQLITE_OK ){
  178228. sqlite3_result_error(pCtx, zErrmsg, -1);
  178229. }else{
  178230. int nIndex = 0;
  178231. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  178232. nIndex = sqlite3_column_int(pStmt, 0);
  178233. }
  178234. rc = sqlite3_finalize(pStmt);
  178235. if( rc==SQLITE_OK ){
  178236. sqlite3_result_int(pCtx, nIndex);
  178237. }else{
  178238. sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
  178239. }
  178240. }
  178241. sqlite3_free(zErrmsg);
  178242. }
  178243. /*
  178244. ** If the RBU database contains the rbu_count table, use it to initialize
  178245. ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
  178246. ** is assumed to contain the same columns as:
  178247. **
  178248. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  178249. **
  178250. ** There should be one row in the table for each data_xxx table in the
  178251. ** database. The 'tbl' column should contain the name of a data_xxx table,
  178252. ** and the cnt column the number of rows it contains.
  178253. **
  178254. ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
  178255. ** for all rows in the rbu_count table, where nIndex is the number of
  178256. ** indexes on the corresponding target database table.
  178257. */
  178258. static void rbuInitPhaseOneSteps(sqlite3rbu *p){
  178259. if( p->rc==SQLITE_OK ){
  178260. sqlite3_stmt *pStmt = 0;
  178261. int bExists = 0; /* True if rbu_count exists */
  178262. p->nPhaseOneStep = -1;
  178263. p->rc = sqlite3_create_function(p->dbRbu,
  178264. "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
  178265. );
  178266. /* Check for the rbu_count table. If it does not exist, or if an error
  178267. ** occurs, nPhaseOneStep will be left set to -1. */
  178268. if( p->rc==SQLITE_OK ){
  178269. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  178270. "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
  178271. );
  178272. }
  178273. if( p->rc==SQLITE_OK ){
  178274. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  178275. bExists = 1;
  178276. }
  178277. p->rc = sqlite3_finalize(pStmt);
  178278. }
  178279. if( p->rc==SQLITE_OK && bExists ){
  178280. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  178281. "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
  178282. "FROM rbu_count"
  178283. );
  178284. if( p->rc==SQLITE_OK ){
  178285. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  178286. p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
  178287. }
  178288. p->rc = sqlite3_finalize(pStmt);
  178289. }
  178290. }
  178291. }
  178292. }
  178293. static sqlite3rbu *openRbuHandle(
  178294. const char *zTarget,
  178295. const char *zRbu,
  178296. const char *zState
  178297. ){
  178298. sqlite3rbu *p;
  178299. size_t nTarget = zTarget ? strlen(zTarget) : 0;
  178300. size_t nRbu = strlen(zRbu);
  178301. size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
  178302. p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  178303. if( p ){
  178304. RbuState *pState = 0;
  178305. /* Create the custom VFS. */
  178306. memset(p, 0, sizeof(sqlite3rbu));
  178307. rbuCreateVfs(p);
  178308. /* Open the target, RBU and state databases */
  178309. if( p->rc==SQLITE_OK ){
  178310. char *pCsr = (char*)&p[1];
  178311. int bRetry = 0;
  178312. if( zTarget ){
  178313. p->zTarget = pCsr;
  178314. memcpy(p->zTarget, zTarget, nTarget+1);
  178315. pCsr += nTarget+1;
  178316. }
  178317. p->zRbu = pCsr;
  178318. memcpy(p->zRbu, zRbu, nRbu+1);
  178319. pCsr += nRbu+1;
  178320. if( zState ){
  178321. p->zState = rbuMPrintf(p, "%s", zState);
  178322. }
  178323. /* If the first attempt to open the database file fails and the bRetry
  178324. ** flag it set, this means that the db was not opened because it seemed
  178325. ** to be a wal-mode db. But, this may have happened due to an earlier
  178326. ** RBU vacuum operation leaving an old wal file in the directory.
  178327. ** If this is the case, it will have been checkpointed and deleted
  178328. ** when the handle was closed and a second attempt to open the
  178329. ** database may succeed. */
  178330. rbuOpenDatabase(p, &bRetry);
  178331. if( bRetry ){
  178332. rbuOpenDatabase(p, 0);
  178333. }
  178334. }
  178335. if( p->rc==SQLITE_OK ){
  178336. pState = rbuLoadState(p);
  178337. assert( pState || p->rc!=SQLITE_OK );
  178338. if( p->rc==SQLITE_OK ){
  178339. if( pState->eStage==0 ){
  178340. rbuDeleteOalFile(p);
  178341. rbuInitPhaseOneSteps(p);
  178342. p->eStage = RBU_STAGE_OAL;
  178343. }else{
  178344. p->eStage = pState->eStage;
  178345. p->nPhaseOneStep = pState->nPhaseOneStep;
  178346. }
  178347. p->nProgress = pState->nProgress;
  178348. p->iOalSz = pState->iOalSz;
  178349. }
  178350. }
  178351. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  178352. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  178353. if( p->eStage==RBU_STAGE_OAL ){
  178354. p->rc = SQLITE_ERROR;
  178355. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  178356. }else if( p->eStage==RBU_STAGE_MOVE ){
  178357. p->eStage = RBU_STAGE_CKPT;
  178358. p->nStep = 0;
  178359. }
  178360. }
  178361. if( p->rc==SQLITE_OK
  178362. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  178363. && pState->eStage!=0
  178364. ){
  178365. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  178366. if( pFd->iCookie!=pState->iCookie ){
  178367. /* At this point (pTargetFd->iCookie) contains the value of the
  178368. ** change-counter cookie (the thing that gets incremented when a
  178369. ** transaction is committed in rollback mode) currently stored on
  178370. ** page 1 of the database file. */
  178371. p->rc = SQLITE_BUSY;
  178372. p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
  178373. (rbuIsVacuum(p) ? "vacuum" : "update")
  178374. );
  178375. }
  178376. }
  178377. if( p->rc==SQLITE_OK ){
  178378. if( p->eStage==RBU_STAGE_OAL ){
  178379. sqlite3 *db = p->dbMain;
  178380. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
  178381. /* Point the object iterator at the first object */
  178382. if( p->rc==SQLITE_OK ){
  178383. p->rc = rbuObjIterFirst(p, &p->objiter);
  178384. }
  178385. /* If the RBU database contains no data_xxx tables, declare the RBU
  178386. ** update finished. */
  178387. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  178388. p->rc = SQLITE_DONE;
  178389. p->eStage = RBU_STAGE_DONE;
  178390. }else{
  178391. if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
  178392. rbuCopyPragma(p, "page_size");
  178393. rbuCopyPragma(p, "auto_vacuum");
  178394. }
  178395. /* Open transactions both databases. The *-oal file is opened or
  178396. ** created at this point. */
  178397. if( p->rc==SQLITE_OK ){
  178398. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  178399. }
  178400. /* Check if the main database is a zipvfs db. If it is, set the upper
  178401. ** level pager to use "journal_mode=off". This prevents it from
  178402. ** generating a large journal using a temp file. */
  178403. if( p->rc==SQLITE_OK ){
  178404. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  178405. if( frc==SQLITE_OK ){
  178406. p->rc = sqlite3_exec(
  178407. db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  178408. }
  178409. }
  178410. if( p->rc==SQLITE_OK ){
  178411. rbuSetupOal(p, pState);
  178412. }
  178413. }
  178414. }else if( p->eStage==RBU_STAGE_MOVE ){
  178415. /* no-op */
  178416. }else if( p->eStage==RBU_STAGE_CKPT ){
  178417. rbuSetupCheckpoint(p, pState);
  178418. }else if( p->eStage==RBU_STAGE_DONE ){
  178419. p->rc = SQLITE_DONE;
  178420. }else{
  178421. p->rc = SQLITE_CORRUPT;
  178422. }
  178423. }
  178424. rbuFreeState(pState);
  178425. }
  178426. return p;
  178427. }
  178428. /*
  178429. ** Allocate and return an RBU handle with all fields zeroed except for the
  178430. ** error code, which is set to SQLITE_MISUSE.
  178431. */
  178432. static sqlite3rbu *rbuMisuseError(void){
  178433. sqlite3rbu *pRet;
  178434. pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
  178435. if( pRet ){
  178436. memset(pRet, 0, sizeof(sqlite3rbu));
  178437. pRet->rc = SQLITE_MISUSE;
  178438. }
  178439. return pRet;
  178440. }
  178441. /*
  178442. ** Open and return a new RBU handle.
  178443. */
  178444. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  178445. const char *zTarget,
  178446. const char *zRbu,
  178447. const char *zState
  178448. ){
  178449. if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
  178450. /* TODO: Check that zTarget and zRbu are non-NULL */
  178451. return openRbuHandle(zTarget, zRbu, zState);
  178452. }
  178453. /*
  178454. ** Open a handle to begin or resume an RBU VACUUM operation.
  178455. */
  178456. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  178457. const char *zTarget,
  178458. const char *zState
  178459. ){
  178460. if( zTarget==0 ){ return rbuMisuseError(); }
  178461. /* TODO: Check that both arguments are non-NULL */
  178462. return openRbuHandle(0, zTarget, zState);
  178463. }
  178464. /*
  178465. ** Return the database handle used by pRbu.
  178466. */
  178467. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  178468. sqlite3 *db = 0;
  178469. if( pRbu ){
  178470. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  178471. }
  178472. return db;
  178473. }
  178474. /*
  178475. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  178476. ** then edit any error message string so as to remove all occurrences of
  178477. ** the pattern "rbu_imp_[0-9]*".
  178478. */
  178479. static void rbuEditErrmsg(sqlite3rbu *p){
  178480. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  178481. unsigned int i;
  178482. size_t nErrmsg = strlen(p->zErrmsg);
  178483. for(i=0; i<(nErrmsg-8); i++){
  178484. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  178485. int nDel = 8;
  178486. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  178487. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  178488. nErrmsg -= nDel;
  178489. }
  178490. }
  178491. }
  178492. }
  178493. /*
  178494. ** Close the RBU handle.
  178495. */
  178496. SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  178497. int rc;
  178498. if( p ){
  178499. /* Commit the transaction to the *-oal file. */
  178500. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  178501. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  178502. }
  178503. /* Sync the db file if currently doing an incremental checkpoint */
  178504. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  178505. sqlite3_file *pDb = p->pTargetFd->pReal;
  178506. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  178507. }
  178508. rbuSaveState(p, p->eStage);
  178509. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  178510. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  178511. }
  178512. /* Close any open statement handles. */
  178513. rbuObjIterFinalize(&p->objiter);
  178514. /* If this is an RBU vacuum handle and the vacuum has either finished
  178515. ** successfully or encountered an error, delete the contents of the
  178516. ** state table. This causes the next call to sqlite3rbu_vacuum()
  178517. ** specifying the current target and state databases to start a new
  178518. ** vacuum from scratch. */
  178519. if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
  178520. int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
  178521. if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
  178522. }
  178523. /* Close the open database handle and VFS object. */
  178524. sqlite3_close(p->dbRbu);
  178525. sqlite3_close(p->dbMain);
  178526. assert( p->szTemp==0 );
  178527. rbuDeleteVfs(p);
  178528. sqlite3_free(p->aBuf);
  178529. sqlite3_free(p->aFrame);
  178530. rbuEditErrmsg(p);
  178531. rc = p->rc;
  178532. if( pzErrmsg ){
  178533. *pzErrmsg = p->zErrmsg;
  178534. }else{
  178535. sqlite3_free(p->zErrmsg);
  178536. }
  178537. sqlite3_free(p->zState);
  178538. sqlite3_free(p);
  178539. }else{
  178540. rc = SQLITE_NOMEM;
  178541. *pzErrmsg = 0;
  178542. }
  178543. return rc;
  178544. }
  178545. /*
  178546. ** Return the total number of key-value operations (inserts, deletes or
  178547. ** updates) that have been performed on the target database since the
  178548. ** current RBU update was started.
  178549. */
  178550. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
  178551. return pRbu->nProgress;
  178552. }
  178553. /*
  178554. ** Return permyriadage progress indications for the two main stages of
  178555. ** an RBU update.
  178556. */
  178557. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
  178558. const int MAX_PROGRESS = 10000;
  178559. switch( p->eStage ){
  178560. case RBU_STAGE_OAL:
  178561. if( p->nPhaseOneStep>0 ){
  178562. *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
  178563. }else{
  178564. *pnOne = -1;
  178565. }
  178566. *pnTwo = 0;
  178567. break;
  178568. case RBU_STAGE_MOVE:
  178569. *pnOne = MAX_PROGRESS;
  178570. *pnTwo = 0;
  178571. break;
  178572. case RBU_STAGE_CKPT:
  178573. *pnOne = MAX_PROGRESS;
  178574. *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
  178575. break;
  178576. case RBU_STAGE_DONE:
  178577. *pnOne = MAX_PROGRESS;
  178578. *pnTwo = MAX_PROGRESS;
  178579. break;
  178580. default:
  178581. assert( 0 );
  178582. }
  178583. }
  178584. /*
  178585. ** Return the current state of the RBU vacuum or update operation.
  178586. */
  178587. SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
  178588. int aRes[] = {
  178589. 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
  178590. 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
  178591. };
  178592. assert( RBU_STAGE_OAL==1 );
  178593. assert( RBU_STAGE_MOVE==2 );
  178594. assert( RBU_STAGE_CKPT==4 );
  178595. assert( RBU_STAGE_DONE==5 );
  178596. assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
  178597. assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
  178598. assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
  178599. assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
  178600. if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
  178601. return SQLITE_RBU_STATE_ERROR;
  178602. }else{
  178603. assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
  178604. assert( p->eStage==RBU_STAGE_OAL
  178605. || p->eStage==RBU_STAGE_MOVE
  178606. || p->eStage==RBU_STAGE_CKPT
  178607. || p->eStage==RBU_STAGE_DONE
  178608. );
  178609. return aRes[p->eStage];
  178610. }
  178611. }
  178612. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
  178613. int rc = p->rc;
  178614. if( rc==SQLITE_DONE ) return SQLITE_OK;
  178615. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  178616. if( p->eStage==RBU_STAGE_OAL ){
  178617. assert( rc!=SQLITE_DONE );
  178618. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  178619. }
  178620. /* Sync the db file */
  178621. if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  178622. sqlite3_file *pDb = p->pTargetFd->pReal;
  178623. rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  178624. }
  178625. p->rc = rc;
  178626. rbuSaveState(p, p->eStage);
  178627. rc = p->rc;
  178628. if( p->eStage==RBU_STAGE_OAL ){
  178629. assert( rc!=SQLITE_DONE );
  178630. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  178631. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
  178632. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  178633. }
  178634. p->rc = rc;
  178635. return rc;
  178636. }
  178637. /**************************************************************************
  178638. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  178639. ** of a standard VFS in the following ways:
  178640. **
  178641. ** 1. Whenever the first page of a main database file is read or
  178642. ** written, the value of the change-counter cookie is stored in
  178643. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  178644. ** database header field is stored in rbu_file.iWriteVer. This ensures
  178645. ** that the values are always trustworthy within an open transaction.
  178646. **
  178647. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  178648. ** member variable of the associated database file descriptor is set
  178649. ** to point to the new file. A mutex protected linked list of all main
  178650. ** db fds opened using a particular RBU VFS is maintained at
  178651. ** rbu_vfs.pMain to facilitate this.
  178652. **
  178653. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  178654. ** object can be marked as the target database of an RBU update. This
  178655. ** turns on the following extra special behaviour:
  178656. **
  178657. ** 3a. If xAccess() is called to check if there exists a *-wal file
  178658. ** associated with an RBU target database currently in RBU_STAGE_OAL
  178659. ** stage (preparing the *-oal file), the following special handling
  178660. ** applies:
  178661. **
  178662. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  178663. ** target database may not be in wal mode already.
  178664. **
  178665. ** * if the *-wal file does not exist, set the output parameter to
  178666. ** non-zero (to tell SQLite that it does exist) anyway.
  178667. **
  178668. ** Then, when xOpen() is called to open the *-wal file associated with
  178669. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  178670. ** file, the rbu vfs opens the corresponding *-oal file instead.
  178671. **
  178672. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  178673. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  178674. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  178675. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  178676. ** because assert() statements in some VFS implementations fail if
  178677. ** xShmLock() is called before xShmMap().
  178678. **
  178679. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  178680. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  178681. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  178682. ** from automatically checkpointing a *-wal (or *-oal) file from within
  178683. ** sqlite3_close().
  178684. **
  178685. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  178686. ** all xWrite() calls on the target database file perform no IO.
  178687. ** Instead the frame and page numbers that would be read and written
  178688. ** are recorded. Additionally, successful attempts to obtain exclusive
  178689. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  178690. ** database file are recorded. xShmLock() calls to unlock the same
  178691. ** locks are no-ops (so that once obtained, these locks are never
  178692. ** relinquished). Finally, calls to xSync() on the target database
  178693. ** file fail with SQLITE_INTERNAL errors.
  178694. */
  178695. static void rbuUnlockShm(rbu_file *p){
  178696. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  178697. if( p->pRbu ){
  178698. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  178699. int i;
  178700. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  178701. if( (1<<i) & p->pRbu->mLock ){
  178702. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  178703. }
  178704. }
  178705. p->pRbu->mLock = 0;
  178706. }
  178707. }
  178708. /*
  178709. */
  178710. static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
  178711. sqlite3rbu *pRbu = pFd->pRbu;
  178712. i64 nDiff = nNew - pFd->sz;
  178713. pRbu->szTemp += nDiff;
  178714. pFd->sz = nNew;
  178715. assert( pRbu->szTemp>=0 );
  178716. if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
  178717. return SQLITE_OK;
  178718. }
  178719. /*
  178720. ** Add an item to the main-db lists, if it is not already present.
  178721. **
  178722. ** There are two main-db lists. One for all file descriptors, and one
  178723. ** for all file descriptors with rbu_file.pDb!=0. If the argument has
  178724. ** rbu_file.pDb!=0, then it is assumed to already be present on the
  178725. ** main list and is only added to the pDb!=0 list.
  178726. */
  178727. static void rbuMainlistAdd(rbu_file *p){
  178728. rbu_vfs *pRbuVfs = p->pRbuVfs;
  178729. rbu_file *pIter;
  178730. assert( (p->openFlags & SQLITE_OPEN_MAIN_DB) );
  178731. sqlite3_mutex_enter(pRbuVfs->mutex);
  178732. if( p->pRbu==0 ){
  178733. for(pIter=pRbuVfs->pMain; pIter; pIter=pIter->pMainNext);
  178734. p->pMainNext = pRbuVfs->pMain;
  178735. pRbuVfs->pMain = p;
  178736. }else{
  178737. for(pIter=pRbuVfs->pMainRbu; pIter && pIter!=p; pIter=pIter->pMainRbuNext){}
  178738. if( pIter==0 ){
  178739. p->pMainRbuNext = pRbuVfs->pMainRbu;
  178740. pRbuVfs->pMainRbu = p;
  178741. }
  178742. }
  178743. sqlite3_mutex_leave(pRbuVfs->mutex);
  178744. }
  178745. /*
  178746. ** Remove an item from the main-db lists.
  178747. */
  178748. static void rbuMainlistRemove(rbu_file *p){
  178749. rbu_file **pp;
  178750. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  178751. for(pp=&p->pRbuVfs->pMain; *pp && *pp!=p; pp=&((*pp)->pMainNext)){}
  178752. if( *pp ) *pp = p->pMainNext;
  178753. p->pMainNext = 0;
  178754. for(pp=&p->pRbuVfs->pMainRbu; *pp && *pp!=p; pp=&((*pp)->pMainRbuNext)){}
  178755. if( *pp ) *pp = p->pMainRbuNext;
  178756. p->pMainRbuNext = 0;
  178757. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  178758. }
  178759. /*
  178760. ** Given that zWal points to a buffer containing a wal file name passed to
  178761. ** either the xOpen() or xAccess() VFS method, search the main-db list for
  178762. ** a file-handle opened by the same database connection on the corresponding
  178763. ** database file.
  178764. **
  178765. ** If parameter bRbu is true, only search for file-descriptors with
  178766. ** rbu_file.pDb!=0.
  178767. */
  178768. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal, int bRbu){
  178769. rbu_file *pDb;
  178770. sqlite3_mutex_enter(pRbuVfs->mutex);
  178771. if( bRbu ){
  178772. for(pDb=pRbuVfs->pMainRbu; pDb && pDb->zWal!=zWal; pDb=pDb->pMainRbuNext){}
  178773. }else{
  178774. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
  178775. }
  178776. sqlite3_mutex_leave(pRbuVfs->mutex);
  178777. return pDb;
  178778. }
  178779. /*
  178780. ** Close an rbu file.
  178781. */
  178782. static int rbuVfsClose(sqlite3_file *pFile){
  178783. rbu_file *p = (rbu_file*)pFile;
  178784. int rc;
  178785. int i;
  178786. /* Free the contents of the apShm[] array. And the array itself. */
  178787. for(i=0; i<p->nShm; i++){
  178788. sqlite3_free(p->apShm[i]);
  178789. }
  178790. sqlite3_free(p->apShm);
  178791. p->apShm = 0;
  178792. sqlite3_free(p->zDel);
  178793. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  178794. rbuMainlistRemove(p);
  178795. rbuUnlockShm(p);
  178796. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  178797. }
  178798. else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  178799. rbuUpdateTempSize(p, 0);
  178800. }
  178801. assert( p->pMainNext==0 && p->pRbuVfs->pMain!=p );
  178802. /* Close the underlying file handle */
  178803. rc = p->pReal->pMethods->xClose(p->pReal);
  178804. return rc;
  178805. }
  178806. /*
  178807. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  178808. ** passed as the only argument.
  178809. */
  178810. static u32 rbuGetU32(u8 *aBuf){
  178811. return ((u32)aBuf[0] << 24)
  178812. + ((u32)aBuf[1] << 16)
  178813. + ((u32)aBuf[2] << 8)
  178814. + ((u32)aBuf[3]);
  178815. }
  178816. /*
  178817. ** Write an unsigned 32-bit value in big-endian format to the supplied
  178818. ** buffer.
  178819. */
  178820. static void rbuPutU32(u8 *aBuf, u32 iVal){
  178821. aBuf[0] = (iVal >> 24) & 0xFF;
  178822. aBuf[1] = (iVal >> 16) & 0xFF;
  178823. aBuf[2] = (iVal >> 8) & 0xFF;
  178824. aBuf[3] = (iVal >> 0) & 0xFF;
  178825. }
  178826. static void rbuPutU16(u8 *aBuf, u16 iVal){
  178827. aBuf[0] = (iVal >> 8) & 0xFF;
  178828. aBuf[1] = (iVal >> 0) & 0xFF;
  178829. }
  178830. /*
  178831. ** Read data from an rbuVfs-file.
  178832. */
  178833. static int rbuVfsRead(
  178834. sqlite3_file *pFile,
  178835. void *zBuf,
  178836. int iAmt,
  178837. sqlite_int64 iOfst
  178838. ){
  178839. rbu_file *p = (rbu_file*)pFile;
  178840. sqlite3rbu *pRbu = p->pRbu;
  178841. int rc;
  178842. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  178843. assert( p->openFlags & SQLITE_OPEN_WAL );
  178844. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  178845. }else{
  178846. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  178847. && (p->openFlags & SQLITE_OPEN_WAL)
  178848. && iOfst>=pRbu->iOalSz
  178849. ){
  178850. rc = SQLITE_OK;
  178851. memset(zBuf, 0, iAmt);
  178852. }else{
  178853. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  178854. #if 1
  178855. /* If this is being called to read the first page of the target
  178856. ** database as part of an rbu vacuum operation, synthesize the
  178857. ** contents of the first page if it does not yet exist. Otherwise,
  178858. ** SQLite will not check for a *-wal file. */
  178859. if( pRbu && rbuIsVacuum(pRbu)
  178860. && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
  178861. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  178862. && pRbu->rc==SQLITE_OK
  178863. ){
  178864. sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
  178865. rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
  178866. if( rc==SQLITE_OK ){
  178867. u8 *aBuf = (u8*)zBuf;
  178868. u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
  178869. rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
  178870. rbuPutU32(&aBuf[36], 0); /* number of free pages */
  178871. rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
  178872. rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
  178873. rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
  178874. if( iAmt>100 ){
  178875. memset(&aBuf[100], 0, iAmt-100);
  178876. rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
  178877. aBuf[100] = 0x0D;
  178878. }
  178879. }
  178880. }
  178881. #endif
  178882. }
  178883. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  178884. /* These look like magic numbers. But they are stable, as they are part
  178885. ** of the definition of the SQLite file format, which may not change. */
  178886. u8 *pBuf = (u8*)zBuf;
  178887. p->iCookie = rbuGetU32(&pBuf[24]);
  178888. p->iWriteVer = pBuf[19];
  178889. }
  178890. }
  178891. return rc;
  178892. }
  178893. /*
  178894. ** Write data to an rbuVfs-file.
  178895. */
  178896. static int rbuVfsWrite(
  178897. sqlite3_file *pFile,
  178898. const void *zBuf,
  178899. int iAmt,
  178900. sqlite_int64 iOfst
  178901. ){
  178902. rbu_file *p = (rbu_file*)pFile;
  178903. sqlite3rbu *pRbu = p->pRbu;
  178904. int rc;
  178905. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  178906. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  178907. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  178908. }else{
  178909. if( pRbu ){
  178910. if( pRbu->eStage==RBU_STAGE_OAL
  178911. && (p->openFlags & SQLITE_OPEN_WAL)
  178912. && iOfst>=pRbu->iOalSz
  178913. ){
  178914. pRbu->iOalSz = iAmt + iOfst;
  178915. }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
  178916. i64 szNew = iAmt+iOfst;
  178917. if( szNew>p->sz ){
  178918. rc = rbuUpdateTempSize(p, szNew);
  178919. if( rc!=SQLITE_OK ) return rc;
  178920. }
  178921. }
  178922. }
  178923. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  178924. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  178925. /* These look like magic numbers. But they are stable, as they are part
  178926. ** of the definition of the SQLite file format, which may not change. */
  178927. u8 *pBuf = (u8*)zBuf;
  178928. p->iCookie = rbuGetU32(&pBuf[24]);
  178929. p->iWriteVer = pBuf[19];
  178930. }
  178931. }
  178932. return rc;
  178933. }
  178934. /*
  178935. ** Truncate an rbuVfs-file.
  178936. */
  178937. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  178938. rbu_file *p = (rbu_file*)pFile;
  178939. if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  178940. int rc = rbuUpdateTempSize(p, size);
  178941. if( rc!=SQLITE_OK ) return rc;
  178942. }
  178943. return p->pReal->pMethods->xTruncate(p->pReal, size);
  178944. }
  178945. /*
  178946. ** Sync an rbuVfs-file.
  178947. */
  178948. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  178949. rbu_file *p = (rbu_file *)pFile;
  178950. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  178951. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  178952. return SQLITE_INTERNAL;
  178953. }
  178954. return SQLITE_OK;
  178955. }
  178956. return p->pReal->pMethods->xSync(p->pReal, flags);
  178957. }
  178958. /*
  178959. ** Return the current file-size of an rbuVfs-file.
  178960. */
  178961. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  178962. rbu_file *p = (rbu_file *)pFile;
  178963. int rc;
  178964. rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
  178965. /* If this is an RBU vacuum operation and this is the target database,
  178966. ** pretend that it has at least one page. Otherwise, SQLite will not
  178967. ** check for the existance of a *-wal file. rbuVfsRead() contains
  178968. ** similar logic. */
  178969. if( rc==SQLITE_OK && *pSize==0
  178970. && p->pRbu && rbuIsVacuum(p->pRbu)
  178971. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  178972. ){
  178973. *pSize = 1024;
  178974. }
  178975. return rc;
  178976. }
  178977. /*
  178978. ** Lock an rbuVfs-file.
  178979. */
  178980. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  178981. rbu_file *p = (rbu_file*)pFile;
  178982. sqlite3rbu *pRbu = p->pRbu;
  178983. int rc = SQLITE_OK;
  178984. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  178985. if( eLock==SQLITE_LOCK_EXCLUSIVE
  178986. && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
  178987. ){
  178988. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  178989. ** prevents it from checkpointing the database from sqlite3_close(). */
  178990. rc = SQLITE_BUSY;
  178991. }else{
  178992. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  178993. }
  178994. return rc;
  178995. }
  178996. /*
  178997. ** Unlock an rbuVfs-file.
  178998. */
  178999. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  179000. rbu_file *p = (rbu_file *)pFile;
  179001. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  179002. }
  179003. /*
  179004. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  179005. */
  179006. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  179007. rbu_file *p = (rbu_file *)pFile;
  179008. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  179009. }
  179010. /*
  179011. ** File control method. For custom operations on an rbuVfs-file.
  179012. */
  179013. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  179014. rbu_file *p = (rbu_file *)pFile;
  179015. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  179016. int rc;
  179017. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  179018. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  179019. );
  179020. if( op==SQLITE_FCNTL_RBU ){
  179021. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  179022. /* First try to find another RBU vfs lower down in the vfs stack. If
  179023. ** one is found, this vfs will operate in pass-through mode. The lower
  179024. ** level vfs will do the special RBU handling. */
  179025. rc = xControl(p->pReal, op, pArg);
  179026. if( rc==SQLITE_NOTFOUND ){
  179027. /* Now search for a zipvfs instance lower down in the VFS stack. If
  179028. ** one is found, this is an error. */
  179029. void *dummy = 0;
  179030. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  179031. if( rc==SQLITE_OK ){
  179032. rc = SQLITE_ERROR;
  179033. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  179034. }else if( rc==SQLITE_NOTFOUND ){
  179035. pRbu->pTargetFd = p;
  179036. p->pRbu = pRbu;
  179037. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  179038. rbuMainlistAdd(p);
  179039. }
  179040. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  179041. rc = SQLITE_OK;
  179042. }
  179043. }
  179044. return rc;
  179045. }
  179046. else if( op==SQLITE_FCNTL_RBUCNT ){
  179047. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  179048. pRbu->nRbu++;
  179049. pRbu->pRbuFd = p;
  179050. p->bNolock = 1;
  179051. }
  179052. rc = xControl(p->pReal, op, pArg);
  179053. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  179054. rbu_vfs *pRbuVfs = p->pRbuVfs;
  179055. char *zIn = *(char**)pArg;
  179056. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  179057. *(char**)pArg = zOut;
  179058. if( zOut==0 ) rc = SQLITE_NOMEM;
  179059. }
  179060. return rc;
  179061. }
  179062. /*
  179063. ** Return the sector-size in bytes for an rbuVfs-file.
  179064. */
  179065. static int rbuVfsSectorSize(sqlite3_file *pFile){
  179066. rbu_file *p = (rbu_file *)pFile;
  179067. return p->pReal->pMethods->xSectorSize(p->pReal);
  179068. }
  179069. /*
  179070. ** Return the device characteristic flags supported by an rbuVfs-file.
  179071. */
  179072. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  179073. rbu_file *p = (rbu_file *)pFile;
  179074. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  179075. }
  179076. /*
  179077. ** Take or release a shared-memory lock.
  179078. */
  179079. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  179080. rbu_file *p = (rbu_file*)pFile;
  179081. sqlite3rbu *pRbu = p->pRbu;
  179082. int rc = SQLITE_OK;
  179083. #ifdef SQLITE_AMALGAMATION
  179084. assert( WAL_CKPT_LOCK==1 );
  179085. #endif
  179086. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  179087. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  179088. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  179089. ** taking this lock also prevents any checkpoints from occurring.
  179090. ** todo: really, it's not clear why this might occur, as
  179091. ** wal_autocheckpoint ought to be turned off. */
  179092. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  179093. }else{
  179094. int bCapture = 0;
  179095. if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
  179096. && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
  179097. && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
  179098. ){
  179099. bCapture = 1;
  179100. }
  179101. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  179102. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  179103. if( bCapture && rc==SQLITE_OK ){
  179104. pRbu->mLock |= (1 << ofst);
  179105. }
  179106. }
  179107. }
  179108. return rc;
  179109. }
  179110. /*
  179111. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  179112. */
  179113. static int rbuVfsShmMap(
  179114. sqlite3_file *pFile,
  179115. int iRegion,
  179116. int szRegion,
  179117. int isWrite,
  179118. void volatile **pp
  179119. ){
  179120. rbu_file *p = (rbu_file*)pFile;
  179121. int rc = SQLITE_OK;
  179122. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  179123. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  179124. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  179125. ** instead of a file on disk. */
  179126. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  179127. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  179128. if( iRegion<=p->nShm ){
  179129. int nByte = (iRegion+1) * sizeof(char*);
  179130. char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
  179131. if( apNew==0 ){
  179132. rc = SQLITE_NOMEM;
  179133. }else{
  179134. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  179135. p->apShm = apNew;
  179136. p->nShm = iRegion+1;
  179137. }
  179138. }
  179139. if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
  179140. char *pNew = (char*)sqlite3_malloc64(szRegion);
  179141. if( pNew==0 ){
  179142. rc = SQLITE_NOMEM;
  179143. }else{
  179144. memset(pNew, 0, szRegion);
  179145. p->apShm[iRegion] = pNew;
  179146. }
  179147. }
  179148. if( rc==SQLITE_OK ){
  179149. *pp = p->apShm[iRegion];
  179150. }else{
  179151. *pp = 0;
  179152. }
  179153. }else{
  179154. assert( p->apShm==0 );
  179155. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  179156. }
  179157. return rc;
  179158. }
  179159. /*
  179160. ** Memory barrier.
  179161. */
  179162. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  179163. rbu_file *p = (rbu_file *)pFile;
  179164. p->pReal->pMethods->xShmBarrier(p->pReal);
  179165. }
  179166. /*
  179167. ** The xShmUnmap method.
  179168. */
  179169. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  179170. rbu_file *p = (rbu_file*)pFile;
  179171. int rc = SQLITE_OK;
  179172. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  179173. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  179174. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  179175. /* no-op */
  179176. }else{
  179177. /* Release the checkpointer and writer locks */
  179178. rbuUnlockShm(p);
  179179. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  179180. }
  179181. return rc;
  179182. }
  179183. /*
  179184. ** A main database named zName has just been opened. The following
  179185. ** function returns a pointer to a buffer owned by SQLite that contains
  179186. ** the name of the *-wal file this db connection will use. SQLite
  179187. ** happens to pass a pointer to this buffer when using xAccess()
  179188. ** or xOpen() to operate on the *-wal file.
  179189. */
  179190. static const char *rbuMainToWal(const char *zName, int flags){
  179191. int n = (int)strlen(zName);
  179192. const char *z = &zName[n];
  179193. if( flags & SQLITE_OPEN_URI ){
  179194. int odd = 0;
  179195. while( 1 ){
  179196. if( z[0]==0 ){
  179197. odd = 1 - odd;
  179198. if( odd && z[1]==0 ) break;
  179199. }
  179200. z++;
  179201. }
  179202. z += 2;
  179203. }else{
  179204. while( *z==0 ) z++;
  179205. }
  179206. z += (n + 8 + 1);
  179207. return z;
  179208. }
  179209. /*
  179210. ** Open an rbu file handle.
  179211. */
  179212. static int rbuVfsOpen(
  179213. sqlite3_vfs *pVfs,
  179214. const char *zName,
  179215. sqlite3_file *pFile,
  179216. int flags,
  179217. int *pOutFlags
  179218. ){
  179219. static sqlite3_io_methods rbuvfs_io_methods = {
  179220. 2, /* iVersion */
  179221. rbuVfsClose, /* xClose */
  179222. rbuVfsRead, /* xRead */
  179223. rbuVfsWrite, /* xWrite */
  179224. rbuVfsTruncate, /* xTruncate */
  179225. rbuVfsSync, /* xSync */
  179226. rbuVfsFileSize, /* xFileSize */
  179227. rbuVfsLock, /* xLock */
  179228. rbuVfsUnlock, /* xUnlock */
  179229. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  179230. rbuVfsFileControl, /* xFileControl */
  179231. rbuVfsSectorSize, /* xSectorSize */
  179232. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  179233. rbuVfsShmMap, /* xShmMap */
  179234. rbuVfsShmLock, /* xShmLock */
  179235. rbuVfsShmBarrier, /* xShmBarrier */
  179236. rbuVfsShmUnmap, /* xShmUnmap */
  179237. 0, 0 /* xFetch, xUnfetch */
  179238. };
  179239. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  179240. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  179241. rbu_file *pFd = (rbu_file *)pFile;
  179242. int rc = SQLITE_OK;
  179243. const char *zOpen = zName;
  179244. int oflags = flags;
  179245. memset(pFd, 0, sizeof(rbu_file));
  179246. pFd->pReal = (sqlite3_file*)&pFd[1];
  179247. pFd->pRbuVfs = pRbuVfs;
  179248. pFd->openFlags = flags;
  179249. if( zName ){
  179250. if( flags & SQLITE_OPEN_MAIN_DB ){
  179251. /* A main database has just been opened. The following block sets
  179252. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  179253. ** the name of the *-wal file this db connection will use. SQLite
  179254. ** happens to pass a pointer to this buffer when using xAccess()
  179255. ** or xOpen() to operate on the *-wal file. */
  179256. pFd->zWal = rbuMainToWal(zName, flags);
  179257. }
  179258. else if( flags & SQLITE_OPEN_WAL ){
  179259. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);
  179260. if( pDb ){
  179261. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  179262. /* This call is to open a *-wal file. Intead, open the *-oal. This
  179263. ** code ensures that the string passed to xOpen() is terminated by a
  179264. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  179265. ** parameter from it. */
  179266. const char *zBase = zName;
  179267. size_t nCopy;
  179268. char *zCopy;
  179269. if( rbuIsVacuum(pDb->pRbu) ){
  179270. zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
  179271. zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
  179272. }
  179273. nCopy = strlen(zBase);
  179274. zCopy = sqlite3_malloc64(nCopy+2);
  179275. if( zCopy ){
  179276. memcpy(zCopy, zBase, nCopy);
  179277. zCopy[nCopy-3] = 'o';
  179278. zCopy[nCopy] = '\0';
  179279. zCopy[nCopy+1] = '\0';
  179280. zOpen = (const char*)(pFd->zDel = zCopy);
  179281. }else{
  179282. rc = SQLITE_NOMEM;
  179283. }
  179284. pFd->pRbu = pDb->pRbu;
  179285. }
  179286. pDb->pWalFd = pFd;
  179287. }
  179288. }
  179289. }else{
  179290. pFd->pRbu = pRbuVfs->pRbu;
  179291. }
  179292. if( oflags & SQLITE_OPEN_MAIN_DB
  179293. && sqlite3_uri_boolean(zName, "rbu_memory", 0)
  179294. ){
  179295. assert( oflags & SQLITE_OPEN_MAIN_DB );
  179296. oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  179297. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  179298. zOpen = 0;
  179299. }
  179300. if( rc==SQLITE_OK ){
  179301. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
  179302. }
  179303. if( pFd->pReal->pMethods ){
  179304. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  179305. ** pointer and, if the file is a main database file, link it into the
  179306. ** mutex protected linked list of all such files. */
  179307. pFile->pMethods = &rbuvfs_io_methods;
  179308. if( flags & SQLITE_OPEN_MAIN_DB ){
  179309. rbuMainlistAdd(pFd);
  179310. }
  179311. }else{
  179312. sqlite3_free(pFd->zDel);
  179313. }
  179314. return rc;
  179315. }
  179316. /*
  179317. ** Delete the file located at zPath.
  179318. */
  179319. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  179320. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  179321. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  179322. }
  179323. /*
  179324. ** Test for access permissions. Return true if the requested permission
  179325. ** is available, or false otherwise.
  179326. */
  179327. static int rbuVfsAccess(
  179328. sqlite3_vfs *pVfs,
  179329. const char *zPath,
  179330. int flags,
  179331. int *pResOut
  179332. ){
  179333. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  179334. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  179335. int rc;
  179336. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  179337. /* If this call is to check if a *-wal file associated with an RBU target
  179338. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  179339. ** the following special handling is activated:
  179340. **
  179341. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  179342. ** ensures that the RBU extension never tries to update a database
  179343. ** in wal mode, even if the first page of the database file has
  179344. ** been damaged.
  179345. **
  179346. ** b) if the *-wal file does not exist, claim that it does anyway,
  179347. ** causing SQLite to call xOpen() to open it. This call will also
  179348. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  179349. ** file opened instead.
  179350. */
  179351. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  179352. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath, 1);
  179353. if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  179354. if( *pResOut ){
  179355. rc = SQLITE_CANTOPEN;
  179356. }else{
  179357. sqlite3_int64 sz = 0;
  179358. rc = rbuVfsFileSize(&pDb->base, &sz);
  179359. *pResOut = (sz>0);
  179360. }
  179361. }
  179362. }
  179363. return rc;
  179364. }
  179365. /*
  179366. ** Populate buffer zOut with the full canonical pathname corresponding
  179367. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  179368. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  179369. */
  179370. static int rbuVfsFullPathname(
  179371. sqlite3_vfs *pVfs,
  179372. const char *zPath,
  179373. int nOut,
  179374. char *zOut
  179375. ){
  179376. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  179377. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  179378. }
  179379. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  179380. /*
  179381. ** Open the dynamic library located at zPath and return a handle.
  179382. */
  179383. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  179384. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  179385. return pRealVfs->xDlOpen(pRealVfs, zPath);
  179386. }
  179387. /*
  179388. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  179389. ** utf-8 string describing the most recent error encountered associated
  179390. ** with dynamic libraries.
  179391. */
  179392. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  179393. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  179394. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  179395. }
  179396. /*
  179397. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  179398. */
  179399. static void (*rbuVfsDlSym(
  179400. sqlite3_vfs *pVfs,
  179401. void *pArg,
  179402. const char *zSym
  179403. ))(void){
  179404. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  179405. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  179406. }
  179407. /*
  179408. ** Close the dynamic library handle pHandle.
  179409. */
  179410. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  179411. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  179412. pRealVfs->xDlClose(pRealVfs, pHandle);
  179413. }
  179414. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  179415. /*
  179416. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  179417. ** random data.
  179418. */
  179419. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  179420. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  179421. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  179422. }
  179423. /*
  179424. ** Sleep for nMicro microseconds. Return the number of microseconds
  179425. ** actually slept.
  179426. */
  179427. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  179428. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  179429. return pRealVfs->xSleep(pRealVfs, nMicro);
  179430. }
  179431. /*
  179432. ** Return the current time as a Julian Day number in *pTimeOut.
  179433. */
  179434. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  179435. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  179436. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  179437. }
  179438. /*
  179439. ** No-op.
  179440. */
  179441. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  179442. return 0;
  179443. }
  179444. /*
  179445. ** Deregister and destroy an RBU vfs created by an earlier call to
  179446. ** sqlite3rbu_create_vfs().
  179447. */
  179448. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
  179449. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  179450. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  179451. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  179452. sqlite3_vfs_unregister(pVfs);
  179453. sqlite3_free(pVfs);
  179454. }
  179455. }
  179456. /*
  179457. ** Create an RBU VFS named zName that accesses the underlying file-system
  179458. ** via existing VFS zParent. The new object is registered as a non-default
  179459. ** VFS with SQLite before returning.
  179460. */
  179461. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  179462. /* Template for VFS */
  179463. static sqlite3_vfs vfs_template = {
  179464. 1, /* iVersion */
  179465. 0, /* szOsFile */
  179466. 0, /* mxPathname */
  179467. 0, /* pNext */
  179468. 0, /* zName */
  179469. 0, /* pAppData */
  179470. rbuVfsOpen, /* xOpen */
  179471. rbuVfsDelete, /* xDelete */
  179472. rbuVfsAccess, /* xAccess */
  179473. rbuVfsFullPathname, /* xFullPathname */
  179474. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  179475. rbuVfsDlOpen, /* xDlOpen */
  179476. rbuVfsDlError, /* xDlError */
  179477. rbuVfsDlSym, /* xDlSym */
  179478. rbuVfsDlClose, /* xDlClose */
  179479. #else
  179480. 0, 0, 0, 0,
  179481. #endif
  179482. rbuVfsRandomness, /* xRandomness */
  179483. rbuVfsSleep, /* xSleep */
  179484. rbuVfsCurrentTime, /* xCurrentTime */
  179485. rbuVfsGetLastError, /* xGetLastError */
  179486. 0, /* xCurrentTimeInt64 (version 2) */
  179487. 0, 0, 0 /* Unimplemented version 3 methods */
  179488. };
  179489. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  179490. int rc = SQLITE_OK;
  179491. size_t nName;
  179492. size_t nByte;
  179493. nName = strlen(zName);
  179494. nByte = sizeof(rbu_vfs) + nName + 1;
  179495. pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
  179496. if( pNew==0 ){
  179497. rc = SQLITE_NOMEM;
  179498. }else{
  179499. sqlite3_vfs *pParent; /* Parent VFS */
  179500. memset(pNew, 0, nByte);
  179501. pParent = sqlite3_vfs_find(zParent);
  179502. if( pParent==0 ){
  179503. rc = SQLITE_NOTFOUND;
  179504. }else{
  179505. char *zSpace;
  179506. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  179507. pNew->base.mxPathname = pParent->mxPathname;
  179508. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  179509. pNew->pRealVfs = pParent;
  179510. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  179511. memcpy(zSpace, zName, nName);
  179512. /* Allocate the mutex and register the new VFS (not as the default) */
  179513. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  179514. if( pNew->mutex==0 ){
  179515. rc = SQLITE_NOMEM;
  179516. }else{
  179517. rc = sqlite3_vfs_register(&pNew->base, 0);
  179518. }
  179519. }
  179520. if( rc!=SQLITE_OK ){
  179521. sqlite3_mutex_free(pNew->mutex);
  179522. sqlite3_free(pNew);
  179523. }
  179524. }
  179525. return rc;
  179526. }
  179527. /*
  179528. ** Configure the aggregate temp file size limit for this RBU handle.
  179529. */
  179530. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
  179531. if( n>=0 ){
  179532. pRbu->szTempLimit = n;
  179533. }
  179534. return pRbu->szTempLimit;
  179535. }
  179536. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
  179537. return pRbu->szTemp;
  179538. }
  179539. /**************************************************************************/
  179540. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  179541. /************** End of sqlite3rbu.c ******************************************/
  179542. /************** Begin file dbstat.c ******************************************/
  179543. /*
  179544. ** 2010 July 12
  179545. **
  179546. ** The author disclaims copyright to this source code. In place of
  179547. ** a legal notice, here is a blessing:
  179548. **
  179549. ** May you do good and not evil.
  179550. ** May you find forgiveness for yourself and forgive others.
  179551. ** May you share freely, never taking more than you give.
  179552. **
  179553. ******************************************************************************
  179554. **
  179555. ** This file contains an implementation of the "dbstat" virtual table.
  179556. **
  179557. ** The dbstat virtual table is used to extract low-level formatting
  179558. ** information from an SQLite database in order to implement the
  179559. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  179560. ** for an example implementation.
  179561. **
  179562. ** Additional information is available on the "dbstat.html" page of the
  179563. ** official SQLite documentation.
  179564. */
  179565. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  179566. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  179567. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  179568. /*
  179569. ** Page paths:
  179570. **
  179571. ** The value of the 'path' column describes the path taken from the
  179572. ** root-node of the b-tree structure to each page. The value of the
  179573. ** root-node path is '/'.
  179574. **
  179575. ** The value of the path for the left-most child page of the root of
  179576. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  179577. ** so the pages to the left have smaller keys than the pages to the right.)
  179578. ** The next to left-most child of the root page is
  179579. ** '/001', and so on, each sibling page identified by a 3-digit hex
  179580. ** value. The children of the 451st left-most sibling have paths such
  179581. ** as '/1c2/000/, '/1c2/001/' etc.
  179582. **
  179583. ** Overflow pages are specified by appending a '+' character and a
  179584. ** six-digit hexadecimal value to the path to the cell they are linked
  179585. ** from. For example, the three overflow pages in a chain linked from
  179586. ** the left-most cell of the 450th child of the root page are identified
  179587. ** by the paths:
  179588. **
  179589. ** '/1c2/000+000000' // First page in overflow chain
  179590. ** '/1c2/000+000001' // Second page in overflow chain
  179591. ** '/1c2/000+000002' // Third page in overflow chain
  179592. **
  179593. ** If the paths are sorted using the BINARY collation sequence, then
  179594. ** the overflow pages associated with a cell will appear earlier in the
  179595. ** sort-order than its child page:
  179596. **
  179597. ** '/1c2/000/' // Left-most child of 451st child of root
  179598. */
  179599. #define VTAB_SCHEMA \
  179600. "CREATE TABLE xx( " \
  179601. " name TEXT, /* Name of table or index */" \
  179602. " path TEXT, /* Path to page from root */" \
  179603. " pageno INTEGER, /* Page number */" \
  179604. " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \
  179605. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  179606. " payload INTEGER, /* Bytes of payload on this page */" \
  179607. " unused INTEGER, /* Bytes of unused space on this page */" \
  179608. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  179609. " pgoffset INTEGER, /* Offset of page in file */" \
  179610. " pgsize INTEGER, /* Size of the page */" \
  179611. " schema TEXT HIDDEN /* Database schema being analyzed */" \
  179612. ");"
  179613. typedef struct StatTable StatTable;
  179614. typedef struct StatCursor StatCursor;
  179615. typedef struct StatPage StatPage;
  179616. typedef struct StatCell StatCell;
  179617. struct StatCell {
  179618. int nLocal; /* Bytes of local payload */
  179619. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  179620. int nOvfl; /* Entries in aOvfl[] */
  179621. u32 *aOvfl; /* Array of overflow page numbers */
  179622. int nLastOvfl; /* Bytes of payload on final overflow page */
  179623. int iOvfl; /* Iterates through aOvfl[] */
  179624. };
  179625. struct StatPage {
  179626. u32 iPgno;
  179627. DbPage *pPg;
  179628. int iCell;
  179629. char *zPath; /* Path to this page */
  179630. /* Variables populated by statDecodePage(): */
  179631. u8 flags; /* Copy of flags byte */
  179632. int nCell; /* Number of cells on page */
  179633. int nUnused; /* Number of unused bytes on page */
  179634. StatCell *aCell; /* Array of parsed cells */
  179635. u32 iRightChildPg; /* Right-child page number (or 0) */
  179636. int nMxPayload; /* Largest payload of any cell on this page */
  179637. };
  179638. struct StatCursor {
  179639. sqlite3_vtab_cursor base;
  179640. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  179641. int isEof; /* After pStmt has returned SQLITE_DONE */
  179642. int iDb; /* Schema used for this query */
  179643. StatPage aPage[32];
  179644. int iPage; /* Current entry in aPage[] */
  179645. /* Values to return. */
  179646. char *zName; /* Value of 'name' column */
  179647. char *zPath; /* Value of 'path' column */
  179648. u32 iPageno; /* Value of 'pageno' column */
  179649. char *zPagetype; /* Value of 'pagetype' column */
  179650. int nCell; /* Value of 'ncell' column */
  179651. int nPayload; /* Value of 'payload' column */
  179652. int nUnused; /* Value of 'unused' column */
  179653. int nMxPayload; /* Value of 'mx_payload' column */
  179654. i64 iOffset; /* Value of 'pgOffset' column */
  179655. int szPage; /* Value of 'pgSize' column */
  179656. };
  179657. struct StatTable {
  179658. sqlite3_vtab base;
  179659. sqlite3 *db;
  179660. int iDb; /* Index of database to analyze */
  179661. };
  179662. #ifndef get2byte
  179663. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  179664. #endif
  179665. /*
  179666. ** Connect to or create a statvfs virtual table.
  179667. */
  179668. static int statConnect(
  179669. sqlite3 *db,
  179670. void *pAux,
  179671. int argc, const char *const*argv,
  179672. sqlite3_vtab **ppVtab,
  179673. char **pzErr
  179674. ){
  179675. StatTable *pTab = 0;
  179676. int rc = SQLITE_OK;
  179677. int iDb;
  179678. if( argc>=4 ){
  179679. Token nm;
  179680. sqlite3TokenInit(&nm, (char*)argv[3]);
  179681. iDb = sqlite3FindDb(db, &nm);
  179682. if( iDb<0 ){
  179683. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  179684. return SQLITE_ERROR;
  179685. }
  179686. }else{
  179687. iDb = 0;
  179688. }
  179689. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  179690. if( rc==SQLITE_OK ){
  179691. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  179692. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  179693. }
  179694. assert( rc==SQLITE_OK || pTab==0 );
  179695. if( rc==SQLITE_OK ){
  179696. memset(pTab, 0, sizeof(StatTable));
  179697. pTab->db = db;
  179698. pTab->iDb = iDb;
  179699. }
  179700. *ppVtab = (sqlite3_vtab*)pTab;
  179701. return rc;
  179702. }
  179703. /*
  179704. ** Disconnect from or destroy a statvfs virtual table.
  179705. */
  179706. static int statDisconnect(sqlite3_vtab *pVtab){
  179707. sqlite3_free(pVtab);
  179708. return SQLITE_OK;
  179709. }
  179710. /*
  179711. ** There is no "best-index". This virtual table always does a linear
  179712. ** scan. However, a schema=? constraint should cause this table to
  179713. ** operate on a different database schema, so check for it.
  179714. **
  179715. ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
  179716. */
  179717. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  179718. int i;
  179719. /* Look for a valid schema=? constraint. If found, change the idxNum to
  179720. ** 1 and request the value of that constraint be sent to xFilter. And
  179721. ** lower the cost estimate to encourage the constrained version to be
  179722. ** used.
  179723. */
  179724. for(i=0; i<pIdxInfo->nConstraint; i++){
  179725. if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
  179726. if( pIdxInfo->aConstraint[i].usable==0 ) return SQLITE_CONSTRAINT;
  179727. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  179728. pIdxInfo->idxNum = 1;
  179729. pIdxInfo->estimatedCost = 1.0;
  179730. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  179731. pIdxInfo->aConstraintUsage[i].omit = 1;
  179732. break;
  179733. }
  179734. /* Records are always returned in ascending order of (name, path).
  179735. ** If this will satisfy the client, set the orderByConsumed flag so that
  179736. ** SQLite does not do an external sort.
  179737. */
  179738. if( ( pIdxInfo->nOrderBy==1
  179739. && pIdxInfo->aOrderBy[0].iColumn==0
  179740. && pIdxInfo->aOrderBy[0].desc==0
  179741. ) ||
  179742. ( pIdxInfo->nOrderBy==2
  179743. && pIdxInfo->aOrderBy[0].iColumn==0
  179744. && pIdxInfo->aOrderBy[0].desc==0
  179745. && pIdxInfo->aOrderBy[1].iColumn==1
  179746. && pIdxInfo->aOrderBy[1].desc==0
  179747. )
  179748. ){
  179749. pIdxInfo->orderByConsumed = 1;
  179750. }
  179751. return SQLITE_OK;
  179752. }
  179753. /*
  179754. ** Open a new statvfs cursor.
  179755. */
  179756. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  179757. StatTable *pTab = (StatTable *)pVTab;
  179758. StatCursor *pCsr;
  179759. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  179760. if( pCsr==0 ){
  179761. return SQLITE_NOMEM_BKPT;
  179762. }else{
  179763. memset(pCsr, 0, sizeof(StatCursor));
  179764. pCsr->base.pVtab = pVTab;
  179765. pCsr->iDb = pTab->iDb;
  179766. }
  179767. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  179768. return SQLITE_OK;
  179769. }
  179770. static void statClearCells(StatPage *p){
  179771. int i;
  179772. if( p->aCell ){
  179773. for(i=0; i<p->nCell; i++){
  179774. sqlite3_free(p->aCell[i].aOvfl);
  179775. }
  179776. sqlite3_free(p->aCell);
  179777. }
  179778. p->nCell = 0;
  179779. p->aCell = 0;
  179780. }
  179781. static void statClearPage(StatPage *p){
  179782. statClearCells(p);
  179783. sqlite3PagerUnref(p->pPg);
  179784. sqlite3_free(p->zPath);
  179785. memset(p, 0, sizeof(StatPage));
  179786. }
  179787. static void statResetCsr(StatCursor *pCsr){
  179788. int i;
  179789. sqlite3_reset(pCsr->pStmt);
  179790. for(i=0; i<ArraySize(pCsr->aPage); i++){
  179791. statClearPage(&pCsr->aPage[i]);
  179792. }
  179793. pCsr->iPage = 0;
  179794. sqlite3_free(pCsr->zPath);
  179795. pCsr->zPath = 0;
  179796. pCsr->isEof = 0;
  179797. }
  179798. /*
  179799. ** Close a statvfs cursor.
  179800. */
  179801. static int statClose(sqlite3_vtab_cursor *pCursor){
  179802. StatCursor *pCsr = (StatCursor *)pCursor;
  179803. statResetCsr(pCsr);
  179804. sqlite3_finalize(pCsr->pStmt);
  179805. sqlite3_free(pCsr);
  179806. return SQLITE_OK;
  179807. }
  179808. static void getLocalPayload(
  179809. int nUsable, /* Usable bytes per page */
  179810. u8 flags, /* Page flags */
  179811. int nTotal, /* Total record (payload) size */
  179812. int *pnLocal /* OUT: Bytes stored locally */
  179813. ){
  179814. int nLocal;
  179815. int nMinLocal;
  179816. int nMaxLocal;
  179817. if( flags==0x0D ){ /* Table leaf node */
  179818. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  179819. nMaxLocal = nUsable - 35;
  179820. }else{ /* Index interior and leaf nodes */
  179821. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  179822. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  179823. }
  179824. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  179825. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  179826. *pnLocal = nLocal;
  179827. }
  179828. static int statDecodePage(Btree *pBt, StatPage *p){
  179829. int nUnused;
  179830. int iOff;
  179831. int nHdr;
  179832. int isLeaf;
  179833. int szPage;
  179834. u8 *aData = sqlite3PagerGetData(p->pPg);
  179835. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  179836. p->flags = aHdr[0];
  179837. if( p->flags==0x0A || p->flags==0x0D ){
  179838. isLeaf = 1;
  179839. nHdr = 8;
  179840. }else if( p->flags==0x05 || p->flags==0x02 ){
  179841. isLeaf = 0;
  179842. nHdr = 12;
  179843. }else{
  179844. goto statPageIsCorrupt;
  179845. }
  179846. if( p->iPgno==1 ) nHdr += 100;
  179847. p->nCell = get2byte(&aHdr[3]);
  179848. p->nMxPayload = 0;
  179849. szPage = sqlite3BtreeGetPageSize(pBt);
  179850. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  179851. nUnused += (int)aHdr[7];
  179852. iOff = get2byte(&aHdr[1]);
  179853. while( iOff ){
  179854. int iNext;
  179855. if( iOff>=szPage ) goto statPageIsCorrupt;
  179856. nUnused += get2byte(&aData[iOff+2]);
  179857. iNext = get2byte(&aData[iOff]);
  179858. if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt;
  179859. iOff = iNext;
  179860. }
  179861. p->nUnused = nUnused;
  179862. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  179863. if( p->nCell ){
  179864. int i; /* Used to iterate through cells */
  179865. int nUsable; /* Usable bytes per page */
  179866. sqlite3BtreeEnter(pBt);
  179867. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  179868. sqlite3BtreeLeave(pBt);
  179869. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  179870. if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
  179871. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  179872. for(i=0; i<p->nCell; i++){
  179873. StatCell *pCell = &p->aCell[i];
  179874. iOff = get2byte(&aData[nHdr+i*2]);
  179875. if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt;
  179876. if( !isLeaf ){
  179877. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  179878. iOff += 4;
  179879. }
  179880. if( p->flags==0x05 ){
  179881. /* A table interior node. nPayload==0. */
  179882. }else{
  179883. u32 nPayload; /* Bytes of payload total (local+overflow) */
  179884. int nLocal; /* Bytes of payload stored locally */
  179885. iOff += getVarint32(&aData[iOff], nPayload);
  179886. if( p->flags==0x0D ){
  179887. u64 dummy;
  179888. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  179889. }
  179890. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  179891. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  179892. if( nLocal<0 ) goto statPageIsCorrupt;
  179893. pCell->nLocal = nLocal;
  179894. assert( nPayload>=(u32)nLocal );
  179895. assert( nLocal<=(nUsable-35) );
  179896. if( nPayload>(u32)nLocal ){
  179897. int j;
  179898. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  179899. if( iOff+nLocal>nUsable ) goto statPageIsCorrupt;
  179900. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  179901. pCell->nOvfl = nOvfl;
  179902. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  179903. if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
  179904. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  179905. for(j=1; j<nOvfl; j++){
  179906. int rc;
  179907. u32 iPrev = pCell->aOvfl[j-1];
  179908. DbPage *pPg = 0;
  179909. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
  179910. if( rc!=SQLITE_OK ){
  179911. assert( pPg==0 );
  179912. return rc;
  179913. }
  179914. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  179915. sqlite3PagerUnref(pPg);
  179916. }
  179917. }
  179918. }
  179919. }
  179920. }
  179921. return SQLITE_OK;
  179922. statPageIsCorrupt:
  179923. p->flags = 0;
  179924. statClearCells(p);
  179925. return SQLITE_OK;
  179926. }
  179927. /*
  179928. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  179929. ** the current value of pCsr->iPageno.
  179930. */
  179931. static void statSizeAndOffset(StatCursor *pCsr){
  179932. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  179933. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  179934. Pager *pPager = sqlite3BtreePager(pBt);
  179935. sqlite3_file *fd;
  179936. sqlite3_int64 x[2];
  179937. /* The default page size and offset */
  179938. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  179939. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  179940. /* If connected to a ZIPVFS backend, override the page size and
  179941. ** offset with actual values obtained from ZIPVFS.
  179942. */
  179943. fd = sqlite3PagerFile(pPager);
  179944. x[0] = pCsr->iPageno;
  179945. if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  179946. pCsr->iOffset = x[0];
  179947. pCsr->szPage = (int)x[1];
  179948. }
  179949. }
  179950. /*
  179951. ** Move a statvfs cursor to the next entry in the file.
  179952. */
  179953. static int statNext(sqlite3_vtab_cursor *pCursor){
  179954. int rc;
  179955. int nPayload;
  179956. char *z;
  179957. StatCursor *pCsr = (StatCursor *)pCursor;
  179958. StatTable *pTab = (StatTable *)pCursor->pVtab;
  179959. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  179960. Pager *pPager = sqlite3BtreePager(pBt);
  179961. sqlite3_free(pCsr->zPath);
  179962. pCsr->zPath = 0;
  179963. statNextRestart:
  179964. if( pCsr->aPage[0].pPg==0 ){
  179965. rc = sqlite3_step(pCsr->pStmt);
  179966. if( rc==SQLITE_ROW ){
  179967. int nPage;
  179968. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  179969. sqlite3PagerPagecount(pPager, &nPage);
  179970. if( nPage==0 ){
  179971. pCsr->isEof = 1;
  179972. return sqlite3_reset(pCsr->pStmt);
  179973. }
  179974. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
  179975. pCsr->aPage[0].iPgno = iRoot;
  179976. pCsr->aPage[0].iCell = 0;
  179977. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  179978. pCsr->iPage = 0;
  179979. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  179980. }else{
  179981. pCsr->isEof = 1;
  179982. return sqlite3_reset(pCsr->pStmt);
  179983. }
  179984. }else{
  179985. /* Page p itself has already been visited. */
  179986. StatPage *p = &pCsr->aPage[pCsr->iPage];
  179987. while( p->iCell<p->nCell ){
  179988. StatCell *pCell = &p->aCell[p->iCell];
  179989. if( pCell->iOvfl<pCell->nOvfl ){
  179990. int nUsable;
  179991. sqlite3BtreeEnter(pBt);
  179992. nUsable = sqlite3BtreeGetPageSize(pBt) -
  179993. sqlite3BtreeGetReserveNoMutex(pBt);
  179994. sqlite3BtreeLeave(pBt);
  179995. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  179996. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  179997. pCsr->zPagetype = "overflow";
  179998. pCsr->nCell = 0;
  179999. pCsr->nMxPayload = 0;
  180000. pCsr->zPath = z = sqlite3_mprintf(
  180001. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  180002. );
  180003. if( pCell->iOvfl<pCell->nOvfl-1 ){
  180004. pCsr->nUnused = 0;
  180005. pCsr->nPayload = nUsable - 4;
  180006. }else{
  180007. pCsr->nPayload = pCell->nLastOvfl;
  180008. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  180009. }
  180010. pCell->iOvfl++;
  180011. statSizeAndOffset(pCsr);
  180012. return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  180013. }
  180014. if( p->iRightChildPg ) break;
  180015. p->iCell++;
  180016. }
  180017. if( !p->iRightChildPg || p->iCell>p->nCell ){
  180018. statClearPage(p);
  180019. if( pCsr->iPage==0 ) return statNext(pCursor);
  180020. pCsr->iPage--;
  180021. goto statNextRestart; /* Tail recursion */
  180022. }
  180023. pCsr->iPage++;
  180024. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  180025. if( p->iCell==p->nCell ){
  180026. p[1].iPgno = p->iRightChildPg;
  180027. }else{
  180028. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  180029. }
  180030. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
  180031. p[1].iCell = 0;
  180032. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  180033. p->iCell++;
  180034. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  180035. }
  180036. /* Populate the StatCursor fields with the values to be returned
  180037. ** by the xColumn() and xRowid() methods.
  180038. */
  180039. if( rc==SQLITE_OK ){
  180040. int i;
  180041. StatPage *p = &pCsr->aPage[pCsr->iPage];
  180042. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  180043. pCsr->iPageno = p->iPgno;
  180044. rc = statDecodePage(pBt, p);
  180045. if( rc==SQLITE_OK ){
  180046. statSizeAndOffset(pCsr);
  180047. switch( p->flags ){
  180048. case 0x05: /* table internal */
  180049. case 0x02: /* index internal */
  180050. pCsr->zPagetype = "internal";
  180051. break;
  180052. case 0x0D: /* table leaf */
  180053. case 0x0A: /* index leaf */
  180054. pCsr->zPagetype = "leaf";
  180055. break;
  180056. default:
  180057. pCsr->zPagetype = "corrupted";
  180058. break;
  180059. }
  180060. pCsr->nCell = p->nCell;
  180061. pCsr->nUnused = p->nUnused;
  180062. pCsr->nMxPayload = p->nMxPayload;
  180063. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  180064. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  180065. nPayload = 0;
  180066. for(i=0; i<p->nCell; i++){
  180067. nPayload += p->aCell[i].nLocal;
  180068. }
  180069. pCsr->nPayload = nPayload;
  180070. }
  180071. }
  180072. return rc;
  180073. }
  180074. static int statEof(sqlite3_vtab_cursor *pCursor){
  180075. StatCursor *pCsr = (StatCursor *)pCursor;
  180076. return pCsr->isEof;
  180077. }
  180078. static int statFilter(
  180079. sqlite3_vtab_cursor *pCursor,
  180080. int idxNum, const char *idxStr,
  180081. int argc, sqlite3_value **argv
  180082. ){
  180083. StatCursor *pCsr = (StatCursor *)pCursor;
  180084. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  180085. char *zSql;
  180086. int rc = SQLITE_OK;
  180087. char *zMaster;
  180088. if( idxNum==1 ){
  180089. const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
  180090. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  180091. if( pCsr->iDb<0 ){
  180092. sqlite3_free(pCursor->pVtab->zErrMsg);
  180093. pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
  180094. return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
  180095. }
  180096. }else{
  180097. pCsr->iDb = pTab->iDb;
  180098. }
  180099. statResetCsr(pCsr);
  180100. sqlite3_finalize(pCsr->pStmt);
  180101. pCsr->pStmt = 0;
  180102. zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
  180103. zSql = sqlite3_mprintf(
  180104. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  180105. " UNION ALL "
  180106. "SELECT name, rootpage, type"
  180107. " FROM \"%w\".%s WHERE rootpage!=0"
  180108. " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
  180109. if( zSql==0 ){
  180110. return SQLITE_NOMEM_BKPT;
  180111. }else{
  180112. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  180113. sqlite3_free(zSql);
  180114. }
  180115. if( rc==SQLITE_OK ){
  180116. rc = statNext(pCursor);
  180117. }
  180118. return rc;
  180119. }
  180120. static int statColumn(
  180121. sqlite3_vtab_cursor *pCursor,
  180122. sqlite3_context *ctx,
  180123. int i
  180124. ){
  180125. StatCursor *pCsr = (StatCursor *)pCursor;
  180126. switch( i ){
  180127. case 0: /* name */
  180128. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  180129. break;
  180130. case 1: /* path */
  180131. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  180132. break;
  180133. case 2: /* pageno */
  180134. sqlite3_result_int64(ctx, pCsr->iPageno);
  180135. break;
  180136. case 3: /* pagetype */
  180137. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  180138. break;
  180139. case 4: /* ncell */
  180140. sqlite3_result_int(ctx, pCsr->nCell);
  180141. break;
  180142. case 5: /* payload */
  180143. sqlite3_result_int(ctx, pCsr->nPayload);
  180144. break;
  180145. case 6: /* unused */
  180146. sqlite3_result_int(ctx, pCsr->nUnused);
  180147. break;
  180148. case 7: /* mx_payload */
  180149. sqlite3_result_int(ctx, pCsr->nMxPayload);
  180150. break;
  180151. case 8: /* pgoffset */
  180152. sqlite3_result_int64(ctx, pCsr->iOffset);
  180153. break;
  180154. case 9: /* pgsize */
  180155. sqlite3_result_int(ctx, pCsr->szPage);
  180156. break;
  180157. default: { /* schema */
  180158. sqlite3 *db = sqlite3_context_db_handle(ctx);
  180159. int iDb = pCsr->iDb;
  180160. sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
  180161. break;
  180162. }
  180163. }
  180164. return SQLITE_OK;
  180165. }
  180166. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  180167. StatCursor *pCsr = (StatCursor *)pCursor;
  180168. *pRowid = pCsr->iPageno;
  180169. return SQLITE_OK;
  180170. }
  180171. /*
  180172. ** Invoke this routine to register the "dbstat" virtual table module
  180173. */
  180174. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  180175. static sqlite3_module dbstat_module = {
  180176. 0, /* iVersion */
  180177. statConnect, /* xCreate */
  180178. statConnect, /* xConnect */
  180179. statBestIndex, /* xBestIndex */
  180180. statDisconnect, /* xDisconnect */
  180181. statDisconnect, /* xDestroy */
  180182. statOpen, /* xOpen - open a cursor */
  180183. statClose, /* xClose - close a cursor */
  180184. statFilter, /* xFilter - configure scan constraints */
  180185. statNext, /* xNext - advance a cursor */
  180186. statEof, /* xEof - check for end of scan */
  180187. statColumn, /* xColumn - read data */
  180188. statRowid, /* xRowid - read data */
  180189. 0, /* xUpdate */
  180190. 0, /* xBegin */
  180191. 0, /* xSync */
  180192. 0, /* xCommit */
  180193. 0, /* xRollback */
  180194. 0, /* xFindMethod */
  180195. 0, /* xRename */
  180196. 0, /* xSavepoint */
  180197. 0, /* xRelease */
  180198. 0, /* xRollbackTo */
  180199. 0 /* xShadowName */
  180200. };
  180201. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  180202. }
  180203. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  180204. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  180205. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  180206. /************** End of dbstat.c **********************************************/
  180207. /************** Begin file dbpage.c ******************************************/
  180208. /*
  180209. ** 2017-10-11
  180210. **
  180211. ** The author disclaims copyright to this source code. In place of
  180212. ** a legal notice, here is a blessing:
  180213. **
  180214. ** May you do good and not evil.
  180215. ** May you find forgiveness for yourself and forgive others.
  180216. ** May you share freely, never taking more than you give.
  180217. **
  180218. ******************************************************************************
  180219. **
  180220. ** This file contains an implementation of the "sqlite_dbpage" virtual table.
  180221. **
  180222. ** The sqlite_dbpage virtual table is used to read or write whole raw
  180223. ** pages of the database file. The pager interface is used so that
  180224. ** uncommitted changes and changes recorded in the WAL file are correctly
  180225. ** retrieved.
  180226. **
  180227. ** Usage example:
  180228. **
  180229. ** SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
  180230. **
  180231. ** This is an eponymous virtual table so it does not need to be created before
  180232. ** use. The optional argument to the sqlite_dbpage() table name is the
  180233. ** schema for the database file that is to be read. The default schema is
  180234. ** "main".
  180235. **
  180236. ** The data field of sqlite_dbpage table can be updated. The new
  180237. ** value must be a BLOB which is the correct page size, otherwise the
  180238. ** update fails. Rows may not be deleted or inserted.
  180239. */
  180240. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  180241. #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
  180242. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  180243. typedef struct DbpageTable DbpageTable;
  180244. typedef struct DbpageCursor DbpageCursor;
  180245. struct DbpageCursor {
  180246. sqlite3_vtab_cursor base; /* Base class. Must be first */
  180247. int pgno; /* Current page number */
  180248. int mxPgno; /* Last page to visit on this scan */
  180249. Pager *pPager; /* Pager being read/written */
  180250. DbPage *pPage1; /* Page 1 of the database */
  180251. int iDb; /* Index of database to analyze */
  180252. int szPage; /* Size of each page in bytes */
  180253. };
  180254. struct DbpageTable {
  180255. sqlite3_vtab base; /* Base class. Must be first */
  180256. sqlite3 *db; /* The database */
  180257. };
  180258. /* Columns */
  180259. #define DBPAGE_COLUMN_PGNO 0
  180260. #define DBPAGE_COLUMN_DATA 1
  180261. #define DBPAGE_COLUMN_SCHEMA 2
  180262. /*
  180263. ** Connect to or create a dbpagevfs virtual table.
  180264. */
  180265. static int dbpageConnect(
  180266. sqlite3 *db,
  180267. void *pAux,
  180268. int argc, const char *const*argv,
  180269. sqlite3_vtab **ppVtab,
  180270. char **pzErr
  180271. ){
  180272. DbpageTable *pTab = 0;
  180273. int rc = SQLITE_OK;
  180274. rc = sqlite3_declare_vtab(db,
  180275. "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
  180276. if( rc==SQLITE_OK ){
  180277. pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
  180278. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  180279. }
  180280. assert( rc==SQLITE_OK || pTab==0 );
  180281. if( rc==SQLITE_OK ){
  180282. memset(pTab, 0, sizeof(DbpageTable));
  180283. pTab->db = db;
  180284. }
  180285. *ppVtab = (sqlite3_vtab*)pTab;
  180286. return rc;
  180287. }
  180288. /*
  180289. ** Disconnect from or destroy a dbpagevfs virtual table.
  180290. */
  180291. static int dbpageDisconnect(sqlite3_vtab *pVtab){
  180292. sqlite3_free(pVtab);
  180293. return SQLITE_OK;
  180294. }
  180295. /*
  180296. ** idxNum:
  180297. **
  180298. ** 0 schema=main, full table scan
  180299. ** 1 schema=main, pgno=?1
  180300. ** 2 schema=?1, full table scan
  180301. ** 3 schema=?1, pgno=?2
  180302. */
  180303. static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  180304. int i;
  180305. int iPlan = 0;
  180306. /* If there is a schema= constraint, it must be honored. Report a
  180307. ** ridiculously large estimated cost if the schema= constraint is
  180308. ** unavailable
  180309. */
  180310. for(i=0; i<pIdxInfo->nConstraint; i++){
  180311. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  180312. if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue;
  180313. if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  180314. if( !p->usable ){
  180315. /* No solution. */
  180316. return SQLITE_CONSTRAINT;
  180317. }
  180318. iPlan = 2;
  180319. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  180320. pIdxInfo->aConstraintUsage[i].omit = 1;
  180321. break;
  180322. }
  180323. /* If we reach this point, it means that either there is no schema=
  180324. ** constraint (in which case we use the "main" schema) or else the
  180325. ** schema constraint was accepted. Lower the estimated cost accordingly
  180326. */
  180327. pIdxInfo->estimatedCost = 1.0e6;
  180328. /* Check for constraints against pgno */
  180329. for(i=0; i<pIdxInfo->nConstraint; i++){
  180330. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  180331. if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  180332. pIdxInfo->estimatedRows = 1;
  180333. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  180334. pIdxInfo->estimatedCost = 1.0;
  180335. pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1;
  180336. pIdxInfo->aConstraintUsage[i].omit = 1;
  180337. iPlan |= 1;
  180338. break;
  180339. }
  180340. }
  180341. pIdxInfo->idxNum = iPlan;
  180342. if( pIdxInfo->nOrderBy>=1
  180343. && pIdxInfo->aOrderBy[0].iColumn<=0
  180344. && pIdxInfo->aOrderBy[0].desc==0
  180345. ){
  180346. pIdxInfo->orderByConsumed = 1;
  180347. }
  180348. return SQLITE_OK;
  180349. }
  180350. /*
  180351. ** Open a new dbpagevfs cursor.
  180352. */
  180353. static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  180354. DbpageCursor *pCsr;
  180355. pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
  180356. if( pCsr==0 ){
  180357. return SQLITE_NOMEM_BKPT;
  180358. }else{
  180359. memset(pCsr, 0, sizeof(DbpageCursor));
  180360. pCsr->base.pVtab = pVTab;
  180361. pCsr->pgno = -1;
  180362. }
  180363. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  180364. return SQLITE_OK;
  180365. }
  180366. /*
  180367. ** Close a dbpagevfs cursor.
  180368. */
  180369. static int dbpageClose(sqlite3_vtab_cursor *pCursor){
  180370. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  180371. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  180372. sqlite3_free(pCsr);
  180373. return SQLITE_OK;
  180374. }
  180375. /*
  180376. ** Move a dbpagevfs cursor to the next entry in the file.
  180377. */
  180378. static int dbpageNext(sqlite3_vtab_cursor *pCursor){
  180379. int rc = SQLITE_OK;
  180380. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  180381. pCsr->pgno++;
  180382. return rc;
  180383. }
  180384. static int dbpageEof(sqlite3_vtab_cursor *pCursor){
  180385. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  180386. return pCsr->pgno > pCsr->mxPgno;
  180387. }
  180388. /*
  180389. ** idxNum:
  180390. **
  180391. ** 0 schema=main, full table scan
  180392. ** 1 schema=main, pgno=?1
  180393. ** 2 schema=?1, full table scan
  180394. ** 3 schema=?1, pgno=?2
  180395. **
  180396. ** idxStr is not used
  180397. */
  180398. static int dbpageFilter(
  180399. sqlite3_vtab_cursor *pCursor,
  180400. int idxNum, const char *idxStr,
  180401. int argc, sqlite3_value **argv
  180402. ){
  180403. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  180404. DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
  180405. int rc;
  180406. sqlite3 *db = pTab->db;
  180407. Btree *pBt;
  180408. /* Default setting is no rows of result */
  180409. pCsr->pgno = 1;
  180410. pCsr->mxPgno = 0;
  180411. if( idxNum & 2 ){
  180412. const char *zSchema;
  180413. assert( argc>=1 );
  180414. zSchema = (const char*)sqlite3_value_text(argv[0]);
  180415. pCsr->iDb = sqlite3FindDbName(db, zSchema);
  180416. if( pCsr->iDb<0 ) return SQLITE_OK;
  180417. }else{
  180418. pCsr->iDb = 0;
  180419. }
  180420. pBt = db->aDb[pCsr->iDb].pBt;
  180421. if( pBt==0 ) return SQLITE_OK;
  180422. pCsr->pPager = sqlite3BtreePager(pBt);
  180423. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  180424. pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
  180425. if( idxNum & 1 ){
  180426. assert( argc>(idxNum>>1) );
  180427. pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]);
  180428. if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){
  180429. pCsr->pgno = 1;
  180430. pCsr->mxPgno = 0;
  180431. }else{
  180432. pCsr->mxPgno = pCsr->pgno;
  180433. }
  180434. }else{
  180435. assert( pCsr->pgno==1 );
  180436. }
  180437. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  180438. rc = sqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0);
  180439. return rc;
  180440. }
  180441. static int dbpageColumn(
  180442. sqlite3_vtab_cursor *pCursor,
  180443. sqlite3_context *ctx,
  180444. int i
  180445. ){
  180446. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  180447. int rc = SQLITE_OK;
  180448. switch( i ){
  180449. case 0: { /* pgno */
  180450. sqlite3_result_int(ctx, pCsr->pgno);
  180451. break;
  180452. }
  180453. case 1: { /* data */
  180454. DbPage *pDbPage = 0;
  180455. rc = sqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
  180456. if( rc==SQLITE_OK ){
  180457. sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pCsr->szPage,
  180458. SQLITE_TRANSIENT);
  180459. }
  180460. sqlite3PagerUnref(pDbPage);
  180461. break;
  180462. }
  180463. default: { /* schema */
  180464. sqlite3 *db = sqlite3_context_db_handle(ctx);
  180465. sqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC);
  180466. break;
  180467. }
  180468. }
  180469. return SQLITE_OK;
  180470. }
  180471. static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  180472. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  180473. *pRowid = pCsr->pgno;
  180474. return SQLITE_OK;
  180475. }
  180476. static int dbpageUpdate(
  180477. sqlite3_vtab *pVtab,
  180478. int argc,
  180479. sqlite3_value **argv,
  180480. sqlite_int64 *pRowid
  180481. ){
  180482. DbpageTable *pTab = (DbpageTable *)pVtab;
  180483. Pgno pgno;
  180484. DbPage *pDbPage = 0;
  180485. int rc = SQLITE_OK;
  180486. char *zErr = 0;
  180487. const char *zSchema;
  180488. int iDb;
  180489. Btree *pBt;
  180490. Pager *pPager;
  180491. int szPage;
  180492. if( pTab->db->flags & SQLITE_Defensive ){
  180493. zErr = "read-only";
  180494. goto update_fail;
  180495. }
  180496. if( argc==1 ){
  180497. zErr = "cannot delete";
  180498. goto update_fail;
  180499. }
  180500. pgno = sqlite3_value_int(argv[0]);
  180501. if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){
  180502. zErr = "cannot insert";
  180503. goto update_fail;
  180504. }
  180505. zSchema = (const char*)sqlite3_value_text(argv[4]);
  180506. iDb = zSchema ? sqlite3FindDbName(pTab->db, zSchema) : -1;
  180507. if( iDb<0 ){
  180508. zErr = "no such schema";
  180509. goto update_fail;
  180510. }
  180511. pBt = pTab->db->aDb[iDb].pBt;
  180512. if( pgno<1 || pBt==0 || pgno>(int)sqlite3BtreeLastPage(pBt) ){
  180513. zErr = "bad page number";
  180514. goto update_fail;
  180515. }
  180516. szPage = sqlite3BtreeGetPageSize(pBt);
  180517. if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
  180518. || sqlite3_value_bytes(argv[3])!=szPage
  180519. ){
  180520. zErr = "bad page value";
  180521. goto update_fail;
  180522. }
  180523. pPager = sqlite3BtreePager(pBt);
  180524. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
  180525. if( rc==SQLITE_OK ){
  180526. rc = sqlite3PagerWrite(pDbPage);
  180527. if( rc==SQLITE_OK ){
  180528. memcpy(sqlite3PagerGetData(pDbPage),
  180529. sqlite3_value_blob(argv[3]),
  180530. szPage);
  180531. }
  180532. }
  180533. sqlite3PagerUnref(pDbPage);
  180534. return rc;
  180535. update_fail:
  180536. sqlite3_free(pVtab->zErrMsg);
  180537. pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
  180538. return SQLITE_ERROR;
  180539. }
  180540. /* Since we do not know in advance which database files will be
  180541. ** written by the sqlite_dbpage virtual table, start a write transaction
  180542. ** on them all.
  180543. */
  180544. static int dbpageBegin(sqlite3_vtab *pVtab){
  180545. DbpageTable *pTab = (DbpageTable *)pVtab;
  180546. sqlite3 *db = pTab->db;
  180547. int i;
  180548. for(i=0; i<db->nDb; i++){
  180549. Btree *pBt = db->aDb[i].pBt;
  180550. if( pBt ) sqlite3BtreeBeginTrans(pBt, 1, 0);
  180551. }
  180552. return SQLITE_OK;
  180553. }
  180554. /*
  180555. ** Invoke this routine to register the "dbpage" virtual table module
  180556. */
  180557. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
  180558. static sqlite3_module dbpage_module = {
  180559. 0, /* iVersion */
  180560. dbpageConnect, /* xCreate */
  180561. dbpageConnect, /* xConnect */
  180562. dbpageBestIndex, /* xBestIndex */
  180563. dbpageDisconnect, /* xDisconnect */
  180564. dbpageDisconnect, /* xDestroy */
  180565. dbpageOpen, /* xOpen - open a cursor */
  180566. dbpageClose, /* xClose - close a cursor */
  180567. dbpageFilter, /* xFilter - configure scan constraints */
  180568. dbpageNext, /* xNext - advance a cursor */
  180569. dbpageEof, /* xEof - check for end of scan */
  180570. dbpageColumn, /* xColumn - read data */
  180571. dbpageRowid, /* xRowid - read data */
  180572. dbpageUpdate, /* xUpdate */
  180573. dbpageBegin, /* xBegin */
  180574. 0, /* xSync */
  180575. 0, /* xCommit */
  180576. 0, /* xRollback */
  180577. 0, /* xFindMethod */
  180578. 0, /* xRename */
  180579. 0, /* xSavepoint */
  180580. 0, /* xRelease */
  180581. 0, /* xRollbackTo */
  180582. 0 /* xShadowName */
  180583. };
  180584. return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
  180585. }
  180586. #elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
  180587. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
  180588. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  180589. /************** End of dbpage.c **********************************************/
  180590. /************** Begin file sqlite3session.c **********************************/
  180591. #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  180592. /* #include "sqlite3session.h" */
  180593. /* #include <assert.h> */
  180594. /* #include <string.h> */
  180595. #ifndef SQLITE_AMALGAMATION
  180596. /* # include "sqliteInt.h" */
  180597. /* # include "vdbeInt.h" */
  180598. #endif
  180599. typedef struct SessionTable SessionTable;
  180600. typedef struct SessionChange SessionChange;
  180601. typedef struct SessionBuffer SessionBuffer;
  180602. typedef struct SessionInput SessionInput;
  180603. /*
  180604. ** Minimum chunk size used by streaming versions of functions.
  180605. */
  180606. #ifndef SESSIONS_STRM_CHUNK_SIZE
  180607. # ifdef SQLITE_TEST
  180608. # define SESSIONS_STRM_CHUNK_SIZE 64
  180609. # else
  180610. # define SESSIONS_STRM_CHUNK_SIZE 1024
  180611. # endif
  180612. #endif
  180613. static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;
  180614. typedef struct SessionHook SessionHook;
  180615. struct SessionHook {
  180616. void *pCtx;
  180617. int (*xOld)(void*,int,sqlite3_value**);
  180618. int (*xNew)(void*,int,sqlite3_value**);
  180619. int (*xCount)(void*);
  180620. int (*xDepth)(void*);
  180621. };
  180622. /*
  180623. ** Session handle structure.
  180624. */
  180625. struct sqlite3_session {
  180626. sqlite3 *db; /* Database handle session is attached to */
  180627. char *zDb; /* Name of database session is attached to */
  180628. int bEnable; /* True if currently recording */
  180629. int bIndirect; /* True if all changes are indirect */
  180630. int bAutoAttach; /* True to auto-attach tables */
  180631. int rc; /* Non-zero if an error has occurred */
  180632. void *pFilterCtx; /* First argument to pass to xTableFilter */
  180633. int (*xTableFilter)(void *pCtx, const char *zTab);
  180634. sqlite3_value *pZeroBlob; /* Value containing X'' */
  180635. sqlite3_session *pNext; /* Next session object on same db. */
  180636. SessionTable *pTable; /* List of attached tables */
  180637. SessionHook hook; /* APIs to grab new and old data with */
  180638. };
  180639. /*
  180640. ** Instances of this structure are used to build strings or binary records.
  180641. */
  180642. struct SessionBuffer {
  180643. u8 *aBuf; /* Pointer to changeset buffer */
  180644. int nBuf; /* Size of buffer aBuf */
  180645. int nAlloc; /* Size of allocation containing aBuf */
  180646. };
  180647. /*
  180648. ** An object of this type is used internally as an abstraction for
  180649. ** input data. Input data may be supplied either as a single large buffer
  180650. ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
  180651. ** sqlite3changeset_start_strm()).
  180652. */
  180653. struct SessionInput {
  180654. int bNoDiscard; /* If true, do not discard in InputBuffer() */
  180655. int iCurrent; /* Offset in aData[] of current change */
  180656. int iNext; /* Offset in aData[] of next change */
  180657. u8 *aData; /* Pointer to buffer containing changeset */
  180658. int nData; /* Number of bytes in aData */
  180659. SessionBuffer buf; /* Current read buffer */
  180660. int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
  180661. void *pIn; /* First argument to xInput */
  180662. int bEof; /* Set to true after xInput finished */
  180663. };
  180664. /*
  180665. ** Structure for changeset iterators.
  180666. */
  180667. struct sqlite3_changeset_iter {
  180668. SessionInput in; /* Input buffer or stream */
  180669. SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
  180670. int bPatchset; /* True if this is a patchset */
  180671. int bInvert; /* True to invert changeset */
  180672. int rc; /* Iterator error code */
  180673. sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
  180674. char *zTab; /* Current table */
  180675. int nCol; /* Number of columns in zTab */
  180676. int op; /* Current operation */
  180677. int bIndirect; /* True if current change was indirect */
  180678. u8 *abPK; /* Primary key array */
  180679. sqlite3_value **apValue; /* old.* and new.* values */
  180680. };
  180681. /*
  180682. ** Each session object maintains a set of the following structures, one
  180683. ** for each table the session object is monitoring. The structures are
  180684. ** stored in a linked list starting at sqlite3_session.pTable.
  180685. **
  180686. ** The keys of the SessionTable.aChange[] hash table are all rows that have
  180687. ** been modified in any way since the session object was attached to the
  180688. ** table.
  180689. **
  180690. ** The data associated with each hash-table entry is a structure containing
  180691. ** a subset of the initial values that the modified row contained at the
  180692. ** start of the session. Or no initial values if the row was inserted.
  180693. */
  180694. struct SessionTable {
  180695. SessionTable *pNext;
  180696. char *zName; /* Local name of table */
  180697. int nCol; /* Number of columns in table zName */
  180698. int bStat1; /* True if this is sqlite_stat1 */
  180699. const char **azCol; /* Column names */
  180700. u8 *abPK; /* Array of primary key flags */
  180701. int nEntry; /* Total number of entries in hash table */
  180702. int nChange; /* Size of apChange[] array */
  180703. SessionChange **apChange; /* Hash table buckets */
  180704. };
  180705. /*
  180706. ** RECORD FORMAT:
  180707. **
  180708. ** The following record format is similar to (but not compatible with) that
  180709. ** used in SQLite database files. This format is used as part of the
  180710. ** change-set binary format, and so must be architecture independent.
  180711. **
  180712. ** Unlike the SQLite database record format, each field is self-contained -
  180713. ** there is no separation of header and data. Each field begins with a
  180714. ** single byte describing its type, as follows:
  180715. **
  180716. ** 0x00: Undefined value.
  180717. ** 0x01: Integer value.
  180718. ** 0x02: Real value.
  180719. ** 0x03: Text value.
  180720. ** 0x04: Blob value.
  180721. ** 0x05: SQL NULL value.
  180722. **
  180723. ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
  180724. ** and so on in sqlite3.h. For undefined and NULL values, the field consists
  180725. ** only of the single type byte. For other types of values, the type byte
  180726. ** is followed by:
  180727. **
  180728. ** Text values:
  180729. ** A varint containing the number of bytes in the value (encoded using
  180730. ** UTF-8). Followed by a buffer containing the UTF-8 representation
  180731. ** of the text value. There is no nul terminator.
  180732. **
  180733. ** Blob values:
  180734. ** A varint containing the number of bytes in the value, followed by
  180735. ** a buffer containing the value itself.
  180736. **
  180737. ** Integer values:
  180738. ** An 8-byte big-endian integer value.
  180739. **
  180740. ** Real values:
  180741. ** An 8-byte big-endian IEEE 754-2008 real value.
  180742. **
  180743. ** Varint values are encoded in the same way as varints in the SQLite
  180744. ** record format.
  180745. **
  180746. ** CHANGESET FORMAT:
  180747. **
  180748. ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
  180749. ** one or more tables. Operations on a single table are grouped together,
  180750. ** but may occur in any order (i.e. deletes, updates and inserts are all
  180751. ** mixed together).
  180752. **
  180753. ** Each group of changes begins with a table header:
  180754. **
  180755. ** 1 byte: Constant 0x54 (capital 'T')
  180756. ** Varint: Number of columns in the table.
  180757. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  180758. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  180759. **
  180760. ** Followed by one or more changes to the table.
  180761. **
  180762. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  180763. ** 1 byte: The "indirect-change" flag.
  180764. ** old.* record: (delete and update only)
  180765. ** new.* record: (insert and update only)
  180766. **
  180767. ** The "old.*" and "new.*" records, if present, are N field records in the
  180768. ** format described above under "RECORD FORMAT", where N is the number of
  180769. ** columns in the table. The i'th field of each record is associated with
  180770. ** the i'th column of the table, counting from left to right in the order
  180771. ** in which columns were declared in the CREATE TABLE statement.
  180772. **
  180773. ** The new.* record that is part of each INSERT change contains the values
  180774. ** that make up the new row. Similarly, the old.* record that is part of each
  180775. ** DELETE change contains the values that made up the row that was deleted
  180776. ** from the database. In the changeset format, the records that are part
  180777. ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
  180778. ** fields.
  180779. **
  180780. ** Within the old.* record associated with an UPDATE change, all fields
  180781. ** associated with table columns that are not PRIMARY KEY columns and are
  180782. ** not modified by the UPDATE change are set to "undefined". Other fields
  180783. ** are set to the values that made up the row before the UPDATE that the
  180784. ** change records took place. Within the new.* record, fields associated
  180785. ** with table columns modified by the UPDATE change contain the new
  180786. ** values. Fields associated with table columns that are not modified
  180787. ** are set to "undefined".
  180788. **
  180789. ** PATCHSET FORMAT:
  180790. **
  180791. ** A patchset is also a collection of changes. It is similar to a changeset,
  180792. ** but leaves undefined those fields that are not useful if no conflict
  180793. ** resolution is required when applying the changeset.
  180794. **
  180795. ** Each group of changes begins with a table header:
  180796. **
  180797. ** 1 byte: Constant 0x50 (capital 'P')
  180798. ** Varint: Number of columns in the table.
  180799. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  180800. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  180801. **
  180802. ** Followed by one or more changes to the table.
  180803. **
  180804. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  180805. ** 1 byte: The "indirect-change" flag.
  180806. ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
  180807. ** full record for INSERT).
  180808. **
  180809. ** As in the changeset format, each field of the single record that is part
  180810. ** of a patchset change is associated with the correspondingly positioned
  180811. ** table column, counting from left to right within the CREATE TABLE
  180812. ** statement.
  180813. **
  180814. ** For a DELETE change, all fields within the record except those associated
  180815. ** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the
  180816. ** values identifying the row to delete.
  180817. **
  180818. ** For an UPDATE change, all fields except those associated with PRIMARY KEY
  180819. ** columns and columns that are modified by the UPDATE are set to "undefined".
  180820. ** PRIMARY KEY fields contain the values identifying the table row to update,
  180821. ** and fields associated with modified columns contain the new column values.
  180822. **
  180823. ** The records associated with INSERT changes are in the same format as for
  180824. ** changesets. It is not possible for a record associated with an INSERT
  180825. ** change to contain a field set to "undefined".
  180826. **
  180827. ** REBASE BLOB FORMAT:
  180828. **
  180829. ** A rebase blob may be output by sqlite3changeset_apply_v2() and its
  180830. ** streaming equivalent for use with the sqlite3_rebaser APIs to rebase
  180831. ** existing changesets. A rebase blob contains one entry for each conflict
  180832. ** resolved using either the OMIT or REPLACE strategies within the apply_v2()
  180833. ** call.
  180834. **
  180835. ** The format used for a rebase blob is very similar to that used for
  180836. ** changesets. All entries related to a single table are grouped together.
  180837. **
  180838. ** Each group of entries begins with a table header in changeset format:
  180839. **
  180840. ** 1 byte: Constant 0x54 (capital 'T')
  180841. ** Varint: Number of columns in the table.
  180842. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  180843. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  180844. **
  180845. ** Followed by one or more entries associated with the table.
  180846. **
  180847. ** 1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09).
  180848. ** 1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT.
  180849. ** record: (in the record format defined above).
  180850. **
  180851. ** In a rebase blob, the first field is set to SQLITE_INSERT if the change
  180852. ** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if
  180853. ** it was a DELETE. The second field is set to 0x01 if the conflict
  180854. ** resolution strategy was REPLACE, or 0x00 if it was OMIT.
  180855. **
  180856. ** If the change that caused the conflict was a DELETE, then the single
  180857. ** record is a copy of the old.* record from the original changeset. If it
  180858. ** was an INSERT, then the single record is a copy of the new.* record. If
  180859. ** the conflicting change was an UPDATE, then the single record is a copy
  180860. ** of the new.* record with the PK fields filled in based on the original
  180861. ** old.* record.
  180862. */
  180863. /*
  180864. ** For each row modified during a session, there exists a single instance of
  180865. ** this structure stored in a SessionTable.aChange[] hash table.
  180866. */
  180867. struct SessionChange {
  180868. int op; /* One of UPDATE, DELETE, INSERT */
  180869. int bIndirect; /* True if this change is "indirect" */
  180870. int nRecord; /* Number of bytes in buffer aRecord[] */
  180871. u8 *aRecord; /* Buffer containing old.* record */
  180872. SessionChange *pNext; /* For hash-table collisions */
  180873. };
  180874. /*
  180875. ** Write a varint with value iVal into the buffer at aBuf. Return the
  180876. ** number of bytes written.
  180877. */
  180878. static int sessionVarintPut(u8 *aBuf, int iVal){
  180879. return putVarint32(aBuf, iVal);
  180880. }
  180881. /*
  180882. ** Return the number of bytes required to store value iVal as a varint.
  180883. */
  180884. static int sessionVarintLen(int iVal){
  180885. return sqlite3VarintLen(iVal);
  180886. }
  180887. /*
  180888. ** Read a varint value from aBuf[] into *piVal. Return the number of
  180889. ** bytes read.
  180890. */
  180891. static int sessionVarintGet(u8 *aBuf, int *piVal){
  180892. return getVarint32(aBuf, *piVal);
  180893. }
  180894. /* Load an unaligned and unsigned 32-bit integer */
  180895. #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  180896. /*
  180897. ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
  180898. ** the value read.
  180899. */
  180900. static sqlite3_int64 sessionGetI64(u8 *aRec){
  180901. u64 x = SESSION_UINT32(aRec);
  180902. u32 y = SESSION_UINT32(aRec+4);
  180903. x = (x<<32) + y;
  180904. return (sqlite3_int64)x;
  180905. }
  180906. /*
  180907. ** Write a 64-bit big-endian integer value to the buffer aBuf[].
  180908. */
  180909. static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
  180910. aBuf[0] = (i>>56) & 0xFF;
  180911. aBuf[1] = (i>>48) & 0xFF;
  180912. aBuf[2] = (i>>40) & 0xFF;
  180913. aBuf[3] = (i>>32) & 0xFF;
  180914. aBuf[4] = (i>>24) & 0xFF;
  180915. aBuf[5] = (i>>16) & 0xFF;
  180916. aBuf[6] = (i>> 8) & 0xFF;
  180917. aBuf[7] = (i>> 0) & 0xFF;
  180918. }
  180919. /*
  180920. ** This function is used to serialize the contents of value pValue (see
  180921. ** comment titled "RECORD FORMAT" above).
  180922. **
  180923. ** If it is non-NULL, the serialized form of the value is written to
  180924. ** buffer aBuf. *pnWrite is set to the number of bytes written before
  180925. ** returning. Or, if aBuf is NULL, the only thing this function does is
  180926. ** set *pnWrite.
  180927. **
  180928. ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
  180929. ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
  180930. ** SQLITE_NOMEM is returned.
  180931. */
  180932. static int sessionSerializeValue(
  180933. u8 *aBuf, /* If non-NULL, write serialized value here */
  180934. sqlite3_value *pValue, /* Value to serialize */
  180935. int *pnWrite /* IN/OUT: Increment by bytes written */
  180936. ){
  180937. int nByte; /* Size of serialized value in bytes */
  180938. if( pValue ){
  180939. int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
  180940. eType = sqlite3_value_type(pValue);
  180941. if( aBuf ) aBuf[0] = eType;
  180942. switch( eType ){
  180943. case SQLITE_NULL:
  180944. nByte = 1;
  180945. break;
  180946. case SQLITE_INTEGER:
  180947. case SQLITE_FLOAT:
  180948. if( aBuf ){
  180949. /* TODO: SQLite does something special to deal with mixed-endian
  180950. ** floating point values (e.g. ARM7). This code probably should
  180951. ** too. */
  180952. u64 i;
  180953. if( eType==SQLITE_INTEGER ){
  180954. i = (u64)sqlite3_value_int64(pValue);
  180955. }else{
  180956. double r;
  180957. assert( sizeof(double)==8 && sizeof(u64)==8 );
  180958. r = sqlite3_value_double(pValue);
  180959. memcpy(&i, &r, 8);
  180960. }
  180961. sessionPutI64(&aBuf[1], i);
  180962. }
  180963. nByte = 9;
  180964. break;
  180965. default: {
  180966. u8 *z;
  180967. int n;
  180968. int nVarint;
  180969. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  180970. if( eType==SQLITE_TEXT ){
  180971. z = (u8 *)sqlite3_value_text(pValue);
  180972. }else{
  180973. z = (u8 *)sqlite3_value_blob(pValue);
  180974. }
  180975. n = sqlite3_value_bytes(pValue);
  180976. if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  180977. nVarint = sessionVarintLen(n);
  180978. if( aBuf ){
  180979. sessionVarintPut(&aBuf[1], n);
  180980. if( n ) memcpy(&aBuf[nVarint + 1], z, n);
  180981. }
  180982. nByte = 1 + nVarint + n;
  180983. break;
  180984. }
  180985. }
  180986. }else{
  180987. nByte = 1;
  180988. if( aBuf ) aBuf[0] = '\0';
  180989. }
  180990. if( pnWrite ) *pnWrite += nByte;
  180991. return SQLITE_OK;
  180992. }
  180993. /*
  180994. ** This macro is used to calculate hash key values for data structures. In
  180995. ** order to use this macro, the entire data structure must be represented
  180996. ** as a series of unsigned integers. In order to calculate a hash-key value
  180997. ** for a data structure represented as three such integers, the macro may
  180998. ** then be used as follows:
  180999. **
  181000. ** int hash_key_value;
  181001. ** hash_key_value = HASH_APPEND(0, <value 1>);
  181002. ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
  181003. ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
  181004. **
  181005. ** In practice, the data structures this macro is used for are the primary
  181006. ** key values of modified rows.
  181007. */
  181008. #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
  181009. /*
  181010. ** Append the hash of the 64-bit integer passed as the second argument to the
  181011. ** hash-key value passed as the first. Return the new hash-key value.
  181012. */
  181013. static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
  181014. h = HASH_APPEND(h, i & 0xFFFFFFFF);
  181015. return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
  181016. }
  181017. /*
  181018. ** Append the hash of the blob passed via the second and third arguments to
  181019. ** the hash-key value passed as the first. Return the new hash-key value.
  181020. */
  181021. static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
  181022. int i;
  181023. for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
  181024. return h;
  181025. }
  181026. /*
  181027. ** Append the hash of the data type passed as the second argument to the
  181028. ** hash-key value passed as the first. Return the new hash-key value.
  181029. */
  181030. static unsigned int sessionHashAppendType(unsigned int h, int eType){
  181031. return HASH_APPEND(h, eType);
  181032. }
  181033. /*
  181034. ** This function may only be called from within a pre-update callback.
  181035. ** It calculates a hash based on the primary key values of the old.* or
  181036. ** new.* row currently available and, assuming no error occurs, writes it to
  181037. ** *piHash before returning. If the primary key contains one or more NULL
  181038. ** values, *pbNullPK is set to true before returning.
  181039. **
  181040. ** If an error occurs, an SQLite error code is returned and the final values
  181041. ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
  181042. ** and the output variables are set as described above.
  181043. */
  181044. static int sessionPreupdateHash(
  181045. sqlite3_session *pSession, /* Session object that owns pTab */
  181046. SessionTable *pTab, /* Session table handle */
  181047. int bNew, /* True to hash the new.* PK */
  181048. int *piHash, /* OUT: Hash value */
  181049. int *pbNullPK /* OUT: True if there are NULL values in PK */
  181050. ){
  181051. unsigned int h = 0; /* Hash value to return */
  181052. int i; /* Used to iterate through columns */
  181053. assert( *pbNullPK==0 );
  181054. assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
  181055. for(i=0; i<pTab->nCol; i++){
  181056. if( pTab->abPK[i] ){
  181057. int rc;
  181058. int eType;
  181059. sqlite3_value *pVal;
  181060. if( bNew ){
  181061. rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
  181062. }else{
  181063. rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
  181064. }
  181065. if( rc!=SQLITE_OK ) return rc;
  181066. eType = sqlite3_value_type(pVal);
  181067. h = sessionHashAppendType(h, eType);
  181068. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  181069. i64 iVal;
  181070. if( eType==SQLITE_INTEGER ){
  181071. iVal = sqlite3_value_int64(pVal);
  181072. }else{
  181073. double rVal = sqlite3_value_double(pVal);
  181074. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  181075. memcpy(&iVal, &rVal, 8);
  181076. }
  181077. h = sessionHashAppendI64(h, iVal);
  181078. }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  181079. const u8 *z;
  181080. int n;
  181081. if( eType==SQLITE_TEXT ){
  181082. z = (const u8 *)sqlite3_value_text(pVal);
  181083. }else{
  181084. z = (const u8 *)sqlite3_value_blob(pVal);
  181085. }
  181086. n = sqlite3_value_bytes(pVal);
  181087. if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  181088. h = sessionHashAppendBlob(h, n, z);
  181089. }else{
  181090. assert( eType==SQLITE_NULL );
  181091. assert( pTab->bStat1==0 || i!=1 );
  181092. *pbNullPK = 1;
  181093. }
  181094. }
  181095. }
  181096. *piHash = (h % pTab->nChange);
  181097. return SQLITE_OK;
  181098. }
  181099. /*
  181100. ** The buffer that the argument points to contains a serialized SQL value.
  181101. ** Return the number of bytes of space occupied by the value (including
  181102. ** the type byte).
  181103. */
  181104. static int sessionSerialLen(u8 *a){
  181105. int e = *a;
  181106. int n;
  181107. if( e==0 || e==0xFF ) return 1;
  181108. if( e==SQLITE_NULL ) return 1;
  181109. if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
  181110. return sessionVarintGet(&a[1], &n) + 1 + n;
  181111. }
  181112. /*
  181113. ** Based on the primary key values stored in change aRecord, calculate a
  181114. ** hash key. Assume the has table has nBucket buckets. The hash keys
  181115. ** calculated by this function are compatible with those calculated by
  181116. ** sessionPreupdateHash().
  181117. **
  181118. ** The bPkOnly argument is non-zero if the record at aRecord[] is from
  181119. ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
  181120. */
  181121. static unsigned int sessionChangeHash(
  181122. SessionTable *pTab, /* Table handle */
  181123. int bPkOnly, /* Record consists of PK fields only */
  181124. u8 *aRecord, /* Change record */
  181125. int nBucket /* Assume this many buckets in hash table */
  181126. ){
  181127. unsigned int h = 0; /* Value to return */
  181128. int i; /* Used to iterate through columns */
  181129. u8 *a = aRecord; /* Used to iterate through change record */
  181130. for(i=0; i<pTab->nCol; i++){
  181131. int eType = *a;
  181132. int isPK = pTab->abPK[i];
  181133. if( bPkOnly && isPK==0 ) continue;
  181134. /* It is not possible for eType to be SQLITE_NULL here. The session
  181135. ** module does not record changes for rows with NULL values stored in
  181136. ** primary key columns. */
  181137. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  181138. || eType==SQLITE_TEXT || eType==SQLITE_BLOB
  181139. || eType==SQLITE_NULL || eType==0
  181140. );
  181141. assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
  181142. if( isPK ){
  181143. a++;
  181144. h = sessionHashAppendType(h, eType);
  181145. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  181146. h = sessionHashAppendI64(h, sessionGetI64(a));
  181147. a += 8;
  181148. }else{
  181149. int n;
  181150. a += sessionVarintGet(a, &n);
  181151. h = sessionHashAppendBlob(h, n, a);
  181152. a += n;
  181153. }
  181154. }else{
  181155. a += sessionSerialLen(a);
  181156. }
  181157. }
  181158. return (h % nBucket);
  181159. }
  181160. /*
  181161. ** Arguments aLeft and aRight are pointers to change records for table pTab.
  181162. ** This function returns true if the two records apply to the same row (i.e.
  181163. ** have the same values stored in the primary key columns), or false
  181164. ** otherwise.
  181165. */
  181166. static int sessionChangeEqual(
  181167. SessionTable *pTab, /* Table used for PK definition */
  181168. int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
  181169. u8 *aLeft, /* Change record */
  181170. int bRightPkOnly, /* True if aRight[] contains PK fields only */
  181171. u8 *aRight /* Change record */
  181172. ){
  181173. u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
  181174. u8 *a2 = aRight; /* Cursor to iterate through aRight */
  181175. int iCol; /* Used to iterate through table columns */
  181176. for(iCol=0; iCol<pTab->nCol; iCol++){
  181177. if( pTab->abPK[iCol] ){
  181178. int n1 = sessionSerialLen(a1);
  181179. int n2 = sessionSerialLen(a2);
  181180. if( n1!=n2 || memcmp(a1, a2, n1) ){
  181181. return 0;
  181182. }
  181183. a1 += n1;
  181184. a2 += n2;
  181185. }else{
  181186. if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
  181187. if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
  181188. }
  181189. }
  181190. return 1;
  181191. }
  181192. /*
  181193. ** Arguments aLeft and aRight both point to buffers containing change
  181194. ** records with nCol columns. This function "merges" the two records into
  181195. ** a single records which is written to the buffer at *paOut. *paOut is
  181196. ** then set to point to one byte after the last byte written before
  181197. ** returning.
  181198. **
  181199. ** The merging of records is done as follows: For each column, if the
  181200. ** aRight record contains a value for the column, copy the value from
  181201. ** their. Otherwise, if aLeft contains a value, copy it. If neither
  181202. ** record contains a value for a given column, then neither does the
  181203. ** output record.
  181204. */
  181205. static void sessionMergeRecord(
  181206. u8 **paOut,
  181207. int nCol,
  181208. u8 *aLeft,
  181209. u8 *aRight
  181210. ){
  181211. u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
  181212. u8 *a2 = aRight; /* Cursor used to iterate through aRight */
  181213. u8 *aOut = *paOut; /* Output cursor */
  181214. int iCol; /* Used to iterate from 0 to nCol */
  181215. for(iCol=0; iCol<nCol; iCol++){
  181216. int n1 = sessionSerialLen(a1);
  181217. int n2 = sessionSerialLen(a2);
  181218. if( *a2 ){
  181219. memcpy(aOut, a2, n2);
  181220. aOut += n2;
  181221. }else{
  181222. memcpy(aOut, a1, n1);
  181223. aOut += n1;
  181224. }
  181225. a1 += n1;
  181226. a2 += n2;
  181227. }
  181228. *paOut = aOut;
  181229. }
  181230. /*
  181231. ** This is a helper function used by sessionMergeUpdate().
  181232. **
  181233. ** When this function is called, both *paOne and *paTwo point to a value
  181234. ** within a change record. Before it returns, both have been advanced so
  181235. ** as to point to the next value in the record.
  181236. **
  181237. ** If, when this function is called, *paTwo points to a valid value (i.e.
  181238. ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
  181239. ** pointer is returned and *pnVal is set to the number of bytes in the
  181240. ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
  181241. ** set to the number of bytes in the value at *paOne. If *paOne points
  181242. ** to the "no value" placeholder, *pnVal is set to 1. In other words:
  181243. **
  181244. ** if( *paTwo is valid ) return *paTwo;
  181245. ** return *paOne;
  181246. **
  181247. */
  181248. static u8 *sessionMergeValue(
  181249. u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
  181250. u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
  181251. int *pnVal /* OUT: Bytes in returned value */
  181252. ){
  181253. u8 *a1 = *paOne;
  181254. u8 *a2 = *paTwo;
  181255. u8 *pRet = 0;
  181256. int n1;
  181257. assert( a1 );
  181258. if( a2 ){
  181259. int n2 = sessionSerialLen(a2);
  181260. if( *a2 ){
  181261. *pnVal = n2;
  181262. pRet = a2;
  181263. }
  181264. *paTwo = &a2[n2];
  181265. }
  181266. n1 = sessionSerialLen(a1);
  181267. if( pRet==0 ){
  181268. *pnVal = n1;
  181269. pRet = a1;
  181270. }
  181271. *paOne = &a1[n1];
  181272. return pRet;
  181273. }
  181274. /*
  181275. ** This function is used by changeset_concat() to merge two UPDATE changes
  181276. ** on the same row.
  181277. */
  181278. static int sessionMergeUpdate(
  181279. u8 **paOut, /* IN/OUT: Pointer to output buffer */
  181280. SessionTable *pTab, /* Table change pertains to */
  181281. int bPatchset, /* True if records are patchset records */
  181282. u8 *aOldRecord1, /* old.* record for first change */
  181283. u8 *aOldRecord2, /* old.* record for second change */
  181284. u8 *aNewRecord1, /* new.* record for first change */
  181285. u8 *aNewRecord2 /* new.* record for second change */
  181286. ){
  181287. u8 *aOld1 = aOldRecord1;
  181288. u8 *aOld2 = aOldRecord2;
  181289. u8 *aNew1 = aNewRecord1;
  181290. u8 *aNew2 = aNewRecord2;
  181291. u8 *aOut = *paOut;
  181292. int i;
  181293. if( bPatchset==0 ){
  181294. int bRequired = 0;
  181295. assert( aOldRecord1 && aNewRecord1 );
  181296. /* Write the old.* vector first. */
  181297. for(i=0; i<pTab->nCol; i++){
  181298. int nOld;
  181299. u8 *aOld;
  181300. int nNew;
  181301. u8 *aNew;
  181302. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  181303. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  181304. if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
  181305. if( pTab->abPK[i]==0 ) bRequired = 1;
  181306. memcpy(aOut, aOld, nOld);
  181307. aOut += nOld;
  181308. }else{
  181309. *(aOut++) = '\0';
  181310. }
  181311. }
  181312. if( !bRequired ) return 0;
  181313. }
  181314. /* Write the new.* vector */
  181315. aOld1 = aOldRecord1;
  181316. aOld2 = aOldRecord2;
  181317. aNew1 = aNewRecord1;
  181318. aNew2 = aNewRecord2;
  181319. for(i=0; i<pTab->nCol; i++){
  181320. int nOld;
  181321. u8 *aOld;
  181322. int nNew;
  181323. u8 *aNew;
  181324. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  181325. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  181326. if( bPatchset==0
  181327. && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
  181328. ){
  181329. *(aOut++) = '\0';
  181330. }else{
  181331. memcpy(aOut, aNew, nNew);
  181332. aOut += nNew;
  181333. }
  181334. }
  181335. *paOut = aOut;
  181336. return 1;
  181337. }
  181338. /*
  181339. ** This function is only called from within a pre-update-hook callback.
  181340. ** It determines if the current pre-update-hook change affects the same row
  181341. ** as the change stored in argument pChange. If so, it returns true. Otherwise
  181342. ** if the pre-update-hook does not affect the same row as pChange, it returns
  181343. ** false.
  181344. */
  181345. static int sessionPreupdateEqual(
  181346. sqlite3_session *pSession, /* Session object that owns SessionTable */
  181347. SessionTable *pTab, /* Table associated with change */
  181348. SessionChange *pChange, /* Change to compare to */
  181349. int op /* Current pre-update operation */
  181350. ){
  181351. int iCol; /* Used to iterate through columns */
  181352. u8 *a = pChange->aRecord; /* Cursor used to scan change record */
  181353. assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  181354. for(iCol=0; iCol<pTab->nCol; iCol++){
  181355. if( !pTab->abPK[iCol] ){
  181356. a += sessionSerialLen(a);
  181357. }else{
  181358. sqlite3_value *pVal; /* Value returned by preupdate_new/old */
  181359. int rc; /* Error code from preupdate_new/old */
  181360. int eType = *a++; /* Type of value from change record */
  181361. /* The following calls to preupdate_new() and preupdate_old() can not
  181362. ** fail. This is because they cache their return values, and by the
  181363. ** time control flows to here they have already been called once from
  181364. ** within sessionPreupdateHash(). The first two asserts below verify
  181365. ** this (that the method has already been called). */
  181366. if( op==SQLITE_INSERT ){
  181367. /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
  181368. rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
  181369. }else{
  181370. /* assert( db->pPreUpdate->pUnpacked ); */
  181371. rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
  181372. }
  181373. assert( rc==SQLITE_OK );
  181374. if( sqlite3_value_type(pVal)!=eType ) return 0;
  181375. /* A SessionChange object never has a NULL value in a PK column */
  181376. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  181377. || eType==SQLITE_BLOB || eType==SQLITE_TEXT
  181378. );
  181379. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  181380. i64 iVal = sessionGetI64(a);
  181381. a += 8;
  181382. if( eType==SQLITE_INTEGER ){
  181383. if( sqlite3_value_int64(pVal)!=iVal ) return 0;
  181384. }else{
  181385. double rVal;
  181386. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  181387. memcpy(&rVal, &iVal, 8);
  181388. if( sqlite3_value_double(pVal)!=rVal ) return 0;
  181389. }
  181390. }else{
  181391. int n;
  181392. const u8 *z;
  181393. a += sessionVarintGet(a, &n);
  181394. if( sqlite3_value_bytes(pVal)!=n ) return 0;
  181395. if( eType==SQLITE_TEXT ){
  181396. z = sqlite3_value_text(pVal);
  181397. }else{
  181398. z = sqlite3_value_blob(pVal);
  181399. }
  181400. if( n>0 && memcmp(a, z, n) ) return 0;
  181401. a += n;
  181402. }
  181403. }
  181404. }
  181405. return 1;
  181406. }
  181407. /*
  181408. ** If required, grow the hash table used to store changes on table pTab
  181409. ** (part of the session pSession). If a fatal OOM error occurs, set the
  181410. ** session object to failed and return SQLITE_ERROR. Otherwise, return
  181411. ** SQLITE_OK.
  181412. **
  181413. ** It is possible that a non-fatal OOM error occurs in this function. In
  181414. ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
  181415. ** Growing the hash table in this case is a performance optimization only,
  181416. ** it is not required for correct operation.
  181417. */
  181418. static int sessionGrowHash(int bPatchset, SessionTable *pTab){
  181419. if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
  181420. int i;
  181421. SessionChange **apNew;
  181422. int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
  181423. apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
  181424. if( apNew==0 ){
  181425. if( pTab->nChange==0 ){
  181426. return SQLITE_ERROR;
  181427. }
  181428. return SQLITE_OK;
  181429. }
  181430. memset(apNew, 0, sizeof(SessionChange *) * nNew);
  181431. for(i=0; i<pTab->nChange; i++){
  181432. SessionChange *p;
  181433. SessionChange *pNext;
  181434. for(p=pTab->apChange[i]; p; p=pNext){
  181435. int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
  181436. int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
  181437. pNext = p->pNext;
  181438. p->pNext = apNew[iHash];
  181439. apNew[iHash] = p;
  181440. }
  181441. }
  181442. sqlite3_free(pTab->apChange);
  181443. pTab->nChange = nNew;
  181444. pTab->apChange = apNew;
  181445. }
  181446. return SQLITE_OK;
  181447. }
  181448. /*
  181449. ** This function queries the database for the names of the columns of table
  181450. ** zThis, in schema zDb.
  181451. **
  181452. ** Otherwise, if they are not NULL, variable *pnCol is set to the number
  181453. ** of columns in the database table and variable *pzTab is set to point to a
  181454. ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
  181455. ** point to an array of pointers to column names. And *pabPK (again, if not
  181456. ** NULL) is set to point to an array of booleans - true if the corresponding
  181457. ** column is part of the primary key.
  181458. **
  181459. ** For example, if the table is declared as:
  181460. **
  181461. ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
  181462. **
  181463. ** Then the four output variables are populated as follows:
  181464. **
  181465. ** *pnCol = 4
  181466. ** *pzTab = "tbl1"
  181467. ** *pazCol = {"w", "x", "y", "z"}
  181468. ** *pabPK = {1, 0, 0, 1}
  181469. **
  181470. ** All returned buffers are part of the same single allocation, which must
  181471. ** be freed using sqlite3_free() by the caller
  181472. */
  181473. static int sessionTableInfo(
  181474. sqlite3 *db, /* Database connection */
  181475. const char *zDb, /* Name of attached database (e.g. "main") */
  181476. const char *zThis, /* Table name */
  181477. int *pnCol, /* OUT: number of columns */
  181478. const char **pzTab, /* OUT: Copy of zThis */
  181479. const char ***pazCol, /* OUT: Array of column names for table */
  181480. u8 **pabPK /* OUT: Array of booleans - true for PK col */
  181481. ){
  181482. char *zPragma;
  181483. sqlite3_stmt *pStmt;
  181484. int rc;
  181485. int nByte;
  181486. int nDbCol = 0;
  181487. int nThis;
  181488. int i;
  181489. u8 *pAlloc = 0;
  181490. char **azCol = 0;
  181491. u8 *abPK = 0;
  181492. assert( pazCol && pabPK );
  181493. nThis = sqlite3Strlen30(zThis);
  181494. if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
  181495. rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
  181496. if( rc==SQLITE_OK ){
  181497. /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
  181498. zPragma = sqlite3_mprintf(
  181499. "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL "
  181500. "SELECT 1, 'idx', '', 0, '', 2 UNION ALL "
  181501. "SELECT 2, 'stat', '', 0, '', 0"
  181502. );
  181503. }else if( rc==SQLITE_ERROR ){
  181504. zPragma = sqlite3_mprintf("");
  181505. }else{
  181506. return rc;
  181507. }
  181508. }else{
  181509. zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
  181510. }
  181511. if( !zPragma ) return SQLITE_NOMEM;
  181512. rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
  181513. sqlite3_free(zPragma);
  181514. if( rc!=SQLITE_OK ) return rc;
  181515. nByte = nThis + 1;
  181516. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  181517. nByte += sqlite3_column_bytes(pStmt, 1);
  181518. nDbCol++;
  181519. }
  181520. rc = sqlite3_reset(pStmt);
  181521. if( rc==SQLITE_OK ){
  181522. nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
  181523. pAlloc = sqlite3_malloc(nByte);
  181524. if( pAlloc==0 ){
  181525. rc = SQLITE_NOMEM;
  181526. }
  181527. }
  181528. if( rc==SQLITE_OK ){
  181529. azCol = (char **)pAlloc;
  181530. pAlloc = (u8 *)&azCol[nDbCol];
  181531. abPK = (u8 *)pAlloc;
  181532. pAlloc = &abPK[nDbCol];
  181533. if( pzTab ){
  181534. memcpy(pAlloc, zThis, nThis+1);
  181535. *pzTab = (char *)pAlloc;
  181536. pAlloc += nThis+1;
  181537. }
  181538. i = 0;
  181539. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  181540. int nName = sqlite3_column_bytes(pStmt, 1);
  181541. const unsigned char *zName = sqlite3_column_text(pStmt, 1);
  181542. if( zName==0 ) break;
  181543. memcpy(pAlloc, zName, nName+1);
  181544. azCol[i] = (char *)pAlloc;
  181545. pAlloc += nName+1;
  181546. abPK[i] = sqlite3_column_int(pStmt, 5);
  181547. i++;
  181548. }
  181549. rc = sqlite3_reset(pStmt);
  181550. }
  181551. /* If successful, populate the output variables. Otherwise, zero them and
  181552. ** free any allocation made. An error code will be returned in this case.
  181553. */
  181554. if( rc==SQLITE_OK ){
  181555. *pazCol = (const char **)azCol;
  181556. *pabPK = abPK;
  181557. *pnCol = nDbCol;
  181558. }else{
  181559. *pazCol = 0;
  181560. *pabPK = 0;
  181561. *pnCol = 0;
  181562. if( pzTab ) *pzTab = 0;
  181563. sqlite3_free(azCol);
  181564. }
  181565. sqlite3_finalize(pStmt);
  181566. return rc;
  181567. }
  181568. /*
  181569. ** This function is only called from within a pre-update handler for a
  181570. ** write to table pTab, part of session pSession. If this is the first
  181571. ** write to this table, initalize the SessionTable.nCol, azCol[] and
  181572. ** abPK[] arrays accordingly.
  181573. **
  181574. ** If an error occurs, an error code is stored in sqlite3_session.rc and
  181575. ** non-zero returned. Or, if no error occurs but the table has no primary
  181576. ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
  181577. ** indicate that updates on this table should be ignored. SessionTable.abPK
  181578. ** is set to NULL in this case.
  181579. */
  181580. static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  181581. if( pTab->nCol==0 ){
  181582. u8 *abPK;
  181583. assert( pTab->azCol==0 || pTab->abPK==0 );
  181584. pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
  181585. pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
  181586. );
  181587. if( pSession->rc==SQLITE_OK ){
  181588. int i;
  181589. for(i=0; i<pTab->nCol; i++){
  181590. if( abPK[i] ){
  181591. pTab->abPK = abPK;
  181592. break;
  181593. }
  181594. }
  181595. if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
  181596. pTab->bStat1 = 1;
  181597. }
  181598. }
  181599. }
  181600. return (pSession->rc || pTab->abPK==0);
  181601. }
  181602. /*
  181603. ** Versions of the four methods in object SessionHook for use with the
  181604. ** sqlite_stat1 table. The purpose of this is to substitute a zero-length
  181605. ** blob each time a NULL value is read from the "idx" column of the
  181606. ** sqlite_stat1 table.
  181607. */
  181608. typedef struct SessionStat1Ctx SessionStat1Ctx;
  181609. struct SessionStat1Ctx {
  181610. SessionHook hook;
  181611. sqlite3_session *pSession;
  181612. };
  181613. static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
  181614. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  181615. sqlite3_value *pVal = 0;
  181616. int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
  181617. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  181618. pVal = p->pSession->pZeroBlob;
  181619. }
  181620. *ppVal = pVal;
  181621. return rc;
  181622. }
  181623. static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
  181624. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  181625. sqlite3_value *pVal = 0;
  181626. int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
  181627. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  181628. pVal = p->pSession->pZeroBlob;
  181629. }
  181630. *ppVal = pVal;
  181631. return rc;
  181632. }
  181633. static int sessionStat1Count(void *pCtx){
  181634. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  181635. return p->hook.xCount(p->hook.pCtx);
  181636. }
  181637. static int sessionStat1Depth(void *pCtx){
  181638. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  181639. return p->hook.xDepth(p->hook.pCtx);
  181640. }
  181641. /*
  181642. ** This function is only called from with a pre-update-hook reporting a
  181643. ** change on table pTab (attached to session pSession). The type of change
  181644. ** (UPDATE, INSERT, DELETE) is specified by the first argument.
  181645. **
  181646. ** Unless one is already present or an error occurs, an entry is added
  181647. ** to the changed-rows hash table associated with table pTab.
  181648. */
  181649. static void sessionPreupdateOneChange(
  181650. int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
  181651. sqlite3_session *pSession, /* Session object pTab is attached to */
  181652. SessionTable *pTab /* Table that change applies to */
  181653. ){
  181654. int iHash;
  181655. int bNull = 0;
  181656. int rc = SQLITE_OK;
  181657. SessionStat1Ctx stat1 = {0};
  181658. if( pSession->rc ) return;
  181659. /* Load table details if required */
  181660. if( sessionInitTable(pSession, pTab) ) return;
  181661. /* Check the number of columns in this xPreUpdate call matches the
  181662. ** number of columns in the table. */
  181663. if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
  181664. pSession->rc = SQLITE_SCHEMA;
  181665. return;
  181666. }
  181667. /* Grow the hash table if required */
  181668. if( sessionGrowHash(0, pTab) ){
  181669. pSession->rc = SQLITE_NOMEM;
  181670. return;
  181671. }
  181672. if( pTab->bStat1 ){
  181673. stat1.hook = pSession->hook;
  181674. stat1.pSession = pSession;
  181675. pSession->hook.pCtx = (void*)&stat1;
  181676. pSession->hook.xNew = sessionStat1New;
  181677. pSession->hook.xOld = sessionStat1Old;
  181678. pSession->hook.xCount = sessionStat1Count;
  181679. pSession->hook.xDepth = sessionStat1Depth;
  181680. if( pSession->pZeroBlob==0 ){
  181681. sqlite3_value *p = sqlite3ValueNew(0);
  181682. if( p==0 ){
  181683. rc = SQLITE_NOMEM;
  181684. goto error_out;
  181685. }
  181686. sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
  181687. pSession->pZeroBlob = p;
  181688. }
  181689. }
  181690. /* Calculate the hash-key for this change. If the primary key of the row
  181691. ** includes a NULL value, exit early. Such changes are ignored by the
  181692. ** session module. */
  181693. rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
  181694. if( rc!=SQLITE_OK ) goto error_out;
  181695. if( bNull==0 ){
  181696. /* Search the hash table for an existing record for this row. */
  181697. SessionChange *pC;
  181698. for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
  181699. if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
  181700. }
  181701. if( pC==0 ){
  181702. /* Create a new change object containing all the old values (if
  181703. ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
  181704. ** values (if this is an INSERT). */
  181705. SessionChange *pChange; /* New change object */
  181706. int nByte; /* Number of bytes to allocate */
  181707. int i; /* Used to iterate through columns */
  181708. assert( rc==SQLITE_OK );
  181709. pTab->nEntry++;
  181710. /* Figure out how large an allocation is required */
  181711. nByte = sizeof(SessionChange);
  181712. for(i=0; i<pTab->nCol; i++){
  181713. sqlite3_value *p = 0;
  181714. if( op!=SQLITE_INSERT ){
  181715. TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  181716. assert( trc==SQLITE_OK );
  181717. }else if( pTab->abPK[i] ){
  181718. TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  181719. assert( trc==SQLITE_OK );
  181720. }
  181721. /* This may fail if SQLite value p contains a utf-16 string that must
  181722. ** be converted to utf-8 and an OOM error occurs while doing so. */
  181723. rc = sessionSerializeValue(0, p, &nByte);
  181724. if( rc!=SQLITE_OK ) goto error_out;
  181725. }
  181726. /* Allocate the change object */
  181727. pChange = (SessionChange *)sqlite3_malloc(nByte);
  181728. if( !pChange ){
  181729. rc = SQLITE_NOMEM;
  181730. goto error_out;
  181731. }else{
  181732. memset(pChange, 0, sizeof(SessionChange));
  181733. pChange->aRecord = (u8 *)&pChange[1];
  181734. }
  181735. /* Populate the change object. None of the preupdate_old(),
  181736. ** preupdate_new() or SerializeValue() calls below may fail as all
  181737. ** required values and encodings have already been cached in memory.
  181738. ** It is not possible for an OOM to occur in this block. */
  181739. nByte = 0;
  181740. for(i=0; i<pTab->nCol; i++){
  181741. sqlite3_value *p = 0;
  181742. if( op!=SQLITE_INSERT ){
  181743. pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  181744. }else if( pTab->abPK[i] ){
  181745. pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  181746. }
  181747. sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
  181748. }
  181749. /* Add the change to the hash-table */
  181750. if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
  181751. pChange->bIndirect = 1;
  181752. }
  181753. pChange->nRecord = nByte;
  181754. pChange->op = op;
  181755. pChange->pNext = pTab->apChange[iHash];
  181756. pTab->apChange[iHash] = pChange;
  181757. }else if( pC->bIndirect ){
  181758. /* If the existing change is considered "indirect", but this current
  181759. ** change is "direct", mark the change object as direct. */
  181760. if( pSession->hook.xDepth(pSession->hook.pCtx)==0
  181761. && pSession->bIndirect==0
  181762. ){
  181763. pC->bIndirect = 0;
  181764. }
  181765. }
  181766. }
  181767. /* If an error has occurred, mark the session object as failed. */
  181768. error_out:
  181769. if( pTab->bStat1 ){
  181770. pSession->hook = stat1.hook;
  181771. }
  181772. if( rc!=SQLITE_OK ){
  181773. pSession->rc = rc;
  181774. }
  181775. }
  181776. static int sessionFindTable(
  181777. sqlite3_session *pSession,
  181778. const char *zName,
  181779. SessionTable **ppTab
  181780. ){
  181781. int rc = SQLITE_OK;
  181782. int nName = sqlite3Strlen30(zName);
  181783. SessionTable *pRet;
  181784. /* Search for an existing table */
  181785. for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
  181786. if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
  181787. }
  181788. if( pRet==0 && pSession->bAutoAttach ){
  181789. /* If there is a table-filter configured, invoke it. If it returns 0,
  181790. ** do not automatically add the new table. */
  181791. if( pSession->xTableFilter==0
  181792. || pSession->xTableFilter(pSession->pFilterCtx, zName)
  181793. ){
  181794. rc = sqlite3session_attach(pSession, zName);
  181795. if( rc==SQLITE_OK ){
  181796. for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
  181797. assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
  181798. }
  181799. }
  181800. }
  181801. assert( rc==SQLITE_OK || pRet==0 );
  181802. *ppTab = pRet;
  181803. return rc;
  181804. }
  181805. /*
  181806. ** The 'pre-update' hook registered by this module with SQLite databases.
  181807. */
  181808. static void xPreUpdate(
  181809. void *pCtx, /* Copy of third arg to preupdate_hook() */
  181810. sqlite3 *db, /* Database handle */
  181811. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  181812. char const *zDb, /* Database name */
  181813. char const *zName, /* Table name */
  181814. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  181815. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  181816. ){
  181817. sqlite3_session *pSession;
  181818. int nDb = sqlite3Strlen30(zDb);
  181819. assert( sqlite3_mutex_held(db->mutex) );
  181820. for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
  181821. SessionTable *pTab;
  181822. /* If this session is attached to a different database ("main", "temp"
  181823. ** etc.), or if it is not currently enabled, there is nothing to do. Skip
  181824. ** to the next session object attached to this database. */
  181825. if( pSession->bEnable==0 ) continue;
  181826. if( pSession->rc ) continue;
  181827. if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
  181828. pSession->rc = sessionFindTable(pSession, zName, &pTab);
  181829. if( pTab ){
  181830. assert( pSession->rc==SQLITE_OK );
  181831. sessionPreupdateOneChange(op, pSession, pTab);
  181832. if( op==SQLITE_UPDATE ){
  181833. sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
  181834. }
  181835. }
  181836. }
  181837. }
  181838. /*
  181839. ** The pre-update hook implementations.
  181840. */
  181841. static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  181842. return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
  181843. }
  181844. static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  181845. return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
  181846. }
  181847. static int sessionPreupdateCount(void *pCtx){
  181848. return sqlite3_preupdate_count((sqlite3*)pCtx);
  181849. }
  181850. static int sessionPreupdateDepth(void *pCtx){
  181851. return sqlite3_preupdate_depth((sqlite3*)pCtx);
  181852. }
  181853. /*
  181854. ** Install the pre-update hooks on the session object passed as the only
  181855. ** argument.
  181856. */
  181857. static void sessionPreupdateHooks(
  181858. sqlite3_session *pSession
  181859. ){
  181860. pSession->hook.pCtx = (void*)pSession->db;
  181861. pSession->hook.xOld = sessionPreupdateOld;
  181862. pSession->hook.xNew = sessionPreupdateNew;
  181863. pSession->hook.xCount = sessionPreupdateCount;
  181864. pSession->hook.xDepth = sessionPreupdateDepth;
  181865. }
  181866. typedef struct SessionDiffCtx SessionDiffCtx;
  181867. struct SessionDiffCtx {
  181868. sqlite3_stmt *pStmt;
  181869. int nOldOff;
  181870. };
  181871. /*
  181872. ** The diff hook implementations.
  181873. */
  181874. static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  181875. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  181876. *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
  181877. return SQLITE_OK;
  181878. }
  181879. static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  181880. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  181881. *ppVal = sqlite3_column_value(p->pStmt, iVal);
  181882. return SQLITE_OK;
  181883. }
  181884. static int sessionDiffCount(void *pCtx){
  181885. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  181886. return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
  181887. }
  181888. static int sessionDiffDepth(void *pCtx){
  181889. return 0;
  181890. }
  181891. /*
  181892. ** Install the diff hooks on the session object passed as the only
  181893. ** argument.
  181894. */
  181895. static void sessionDiffHooks(
  181896. sqlite3_session *pSession,
  181897. SessionDiffCtx *pDiffCtx
  181898. ){
  181899. pSession->hook.pCtx = (void*)pDiffCtx;
  181900. pSession->hook.xOld = sessionDiffOld;
  181901. pSession->hook.xNew = sessionDiffNew;
  181902. pSession->hook.xCount = sessionDiffCount;
  181903. pSession->hook.xDepth = sessionDiffDepth;
  181904. }
  181905. static char *sessionExprComparePK(
  181906. int nCol,
  181907. const char *zDb1, const char *zDb2,
  181908. const char *zTab,
  181909. const char **azCol, u8 *abPK
  181910. ){
  181911. int i;
  181912. const char *zSep = "";
  181913. char *zRet = 0;
  181914. for(i=0; i<nCol; i++){
  181915. if( abPK[i] ){
  181916. zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
  181917. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  181918. );
  181919. zSep = " AND ";
  181920. if( zRet==0 ) break;
  181921. }
  181922. }
  181923. return zRet;
  181924. }
  181925. static char *sessionExprCompareOther(
  181926. int nCol,
  181927. const char *zDb1, const char *zDb2,
  181928. const char *zTab,
  181929. const char **azCol, u8 *abPK
  181930. ){
  181931. int i;
  181932. const char *zSep = "";
  181933. char *zRet = 0;
  181934. int bHave = 0;
  181935. for(i=0; i<nCol; i++){
  181936. if( abPK[i]==0 ){
  181937. bHave = 1;
  181938. zRet = sqlite3_mprintf(
  181939. "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
  181940. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  181941. );
  181942. zSep = " OR ";
  181943. if( zRet==0 ) break;
  181944. }
  181945. }
  181946. if( bHave==0 ){
  181947. assert( zRet==0 );
  181948. zRet = sqlite3_mprintf("0");
  181949. }
  181950. return zRet;
  181951. }
  181952. static char *sessionSelectFindNew(
  181953. int nCol,
  181954. const char *zDb1, /* Pick rows in this db only */
  181955. const char *zDb2, /* But not in this one */
  181956. const char *zTbl, /* Table name */
  181957. const char *zExpr
  181958. ){
  181959. char *zRet = sqlite3_mprintf(
  181960. "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
  181961. " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
  181962. ")",
  181963. zDb1, zTbl, zDb2, zTbl, zExpr
  181964. );
  181965. return zRet;
  181966. }
  181967. static int sessionDiffFindNew(
  181968. int op,
  181969. sqlite3_session *pSession,
  181970. SessionTable *pTab,
  181971. const char *zDb1,
  181972. const char *zDb2,
  181973. char *zExpr
  181974. ){
  181975. int rc = SQLITE_OK;
  181976. char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
  181977. if( zStmt==0 ){
  181978. rc = SQLITE_NOMEM;
  181979. }else{
  181980. sqlite3_stmt *pStmt;
  181981. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  181982. if( rc==SQLITE_OK ){
  181983. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  181984. pDiffCtx->pStmt = pStmt;
  181985. pDiffCtx->nOldOff = 0;
  181986. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  181987. sessionPreupdateOneChange(op, pSession, pTab);
  181988. }
  181989. rc = sqlite3_finalize(pStmt);
  181990. }
  181991. sqlite3_free(zStmt);
  181992. }
  181993. return rc;
  181994. }
  181995. static int sessionDiffFindModified(
  181996. sqlite3_session *pSession,
  181997. SessionTable *pTab,
  181998. const char *zFrom,
  181999. const char *zExpr
  182000. ){
  182001. int rc = SQLITE_OK;
  182002. char *zExpr2 = sessionExprCompareOther(pTab->nCol,
  182003. pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
  182004. );
  182005. if( zExpr2==0 ){
  182006. rc = SQLITE_NOMEM;
  182007. }else{
  182008. char *zStmt = sqlite3_mprintf(
  182009. "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
  182010. pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
  182011. );
  182012. if( zStmt==0 ){
  182013. rc = SQLITE_NOMEM;
  182014. }else{
  182015. sqlite3_stmt *pStmt;
  182016. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  182017. if( rc==SQLITE_OK ){
  182018. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  182019. pDiffCtx->pStmt = pStmt;
  182020. pDiffCtx->nOldOff = pTab->nCol;
  182021. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  182022. sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
  182023. }
  182024. rc = sqlite3_finalize(pStmt);
  182025. }
  182026. sqlite3_free(zStmt);
  182027. }
  182028. }
  182029. return rc;
  182030. }
  182031. SQLITE_API int sqlite3session_diff(
  182032. sqlite3_session *pSession,
  182033. const char *zFrom,
  182034. const char *zTbl,
  182035. char **pzErrMsg
  182036. ){
  182037. const char *zDb = pSession->zDb;
  182038. int rc = pSession->rc;
  182039. SessionDiffCtx d;
  182040. memset(&d, 0, sizeof(d));
  182041. sessionDiffHooks(pSession, &d);
  182042. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  182043. if( pzErrMsg ) *pzErrMsg = 0;
  182044. if( rc==SQLITE_OK ){
  182045. char *zExpr = 0;
  182046. sqlite3 *db = pSession->db;
  182047. SessionTable *pTo; /* Table zTbl */
  182048. /* Locate and if necessary initialize the target table object */
  182049. rc = sessionFindTable(pSession, zTbl, &pTo);
  182050. if( pTo==0 ) goto diff_out;
  182051. if( sessionInitTable(pSession, pTo) ){
  182052. rc = pSession->rc;
  182053. goto diff_out;
  182054. }
  182055. /* Check the table schemas match */
  182056. if( rc==SQLITE_OK ){
  182057. int bHasPk = 0;
  182058. int bMismatch = 0;
  182059. int nCol; /* Columns in zFrom.zTbl */
  182060. u8 *abPK;
  182061. const char **azCol = 0;
  182062. rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
  182063. if( rc==SQLITE_OK ){
  182064. if( pTo->nCol!=nCol ){
  182065. bMismatch = 1;
  182066. }else{
  182067. int i;
  182068. for(i=0; i<nCol; i++){
  182069. if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
  182070. if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
  182071. if( abPK[i] ) bHasPk = 1;
  182072. }
  182073. }
  182074. }
  182075. sqlite3_free((char*)azCol);
  182076. if( bMismatch ){
  182077. *pzErrMsg = sqlite3_mprintf("table schemas do not match");
  182078. rc = SQLITE_SCHEMA;
  182079. }
  182080. if( bHasPk==0 ){
  182081. /* Ignore tables with no primary keys */
  182082. goto diff_out;
  182083. }
  182084. }
  182085. if( rc==SQLITE_OK ){
  182086. zExpr = sessionExprComparePK(pTo->nCol,
  182087. zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
  182088. );
  182089. }
  182090. /* Find new rows */
  182091. if( rc==SQLITE_OK ){
  182092. rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
  182093. }
  182094. /* Find old rows */
  182095. if( rc==SQLITE_OK ){
  182096. rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
  182097. }
  182098. /* Find modified rows */
  182099. if( rc==SQLITE_OK ){
  182100. rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
  182101. }
  182102. sqlite3_free(zExpr);
  182103. }
  182104. diff_out:
  182105. sessionPreupdateHooks(pSession);
  182106. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  182107. return rc;
  182108. }
  182109. /*
  182110. ** Create a session object. This session object will record changes to
  182111. ** database zDb attached to connection db.
  182112. */
  182113. SQLITE_API int sqlite3session_create(
  182114. sqlite3 *db, /* Database handle */
  182115. const char *zDb, /* Name of db (e.g. "main") */
  182116. sqlite3_session **ppSession /* OUT: New session object */
  182117. ){
  182118. sqlite3_session *pNew; /* Newly allocated session object */
  182119. sqlite3_session *pOld; /* Session object already attached to db */
  182120. int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
  182121. /* Zero the output value in case an error occurs. */
  182122. *ppSession = 0;
  182123. /* Allocate and populate the new session object. */
  182124. pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
  182125. if( !pNew ) return SQLITE_NOMEM;
  182126. memset(pNew, 0, sizeof(sqlite3_session));
  182127. pNew->db = db;
  182128. pNew->zDb = (char *)&pNew[1];
  182129. pNew->bEnable = 1;
  182130. memcpy(pNew->zDb, zDb, nDb+1);
  182131. sessionPreupdateHooks(pNew);
  182132. /* Add the new session object to the linked list of session objects
  182133. ** attached to database handle $db. Do this under the cover of the db
  182134. ** handle mutex. */
  182135. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  182136. pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
  182137. pNew->pNext = pOld;
  182138. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  182139. *ppSession = pNew;
  182140. return SQLITE_OK;
  182141. }
  182142. /*
  182143. ** Free the list of table objects passed as the first argument. The contents
  182144. ** of the changed-rows hash tables are also deleted.
  182145. */
  182146. static void sessionDeleteTable(SessionTable *pList){
  182147. SessionTable *pNext;
  182148. SessionTable *pTab;
  182149. for(pTab=pList; pTab; pTab=pNext){
  182150. int i;
  182151. pNext = pTab->pNext;
  182152. for(i=0; i<pTab->nChange; i++){
  182153. SessionChange *p;
  182154. SessionChange *pNextChange;
  182155. for(p=pTab->apChange[i]; p; p=pNextChange){
  182156. pNextChange = p->pNext;
  182157. sqlite3_free(p);
  182158. }
  182159. }
  182160. sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
  182161. sqlite3_free(pTab->apChange);
  182162. sqlite3_free(pTab);
  182163. }
  182164. }
  182165. /*
  182166. ** Delete a session object previously allocated using sqlite3session_create().
  182167. */
  182168. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
  182169. sqlite3 *db = pSession->db;
  182170. sqlite3_session *pHead;
  182171. sqlite3_session **pp;
  182172. /* Unlink the session from the linked list of sessions attached to the
  182173. ** database handle. Hold the db mutex while doing so. */
  182174. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  182175. pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
  182176. for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
  182177. if( (*pp)==pSession ){
  182178. *pp = (*pp)->pNext;
  182179. if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
  182180. break;
  182181. }
  182182. }
  182183. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  182184. sqlite3ValueFree(pSession->pZeroBlob);
  182185. /* Delete all attached table objects. And the contents of their
  182186. ** associated hash-tables. */
  182187. sessionDeleteTable(pSession->pTable);
  182188. /* Free the session object itself. */
  182189. sqlite3_free(pSession);
  182190. }
  182191. /*
  182192. ** Set a table filter on a Session Object.
  182193. */
  182194. SQLITE_API void sqlite3session_table_filter(
  182195. sqlite3_session *pSession,
  182196. int(*xFilter)(void*, const char*),
  182197. void *pCtx /* First argument passed to xFilter */
  182198. ){
  182199. pSession->bAutoAttach = 1;
  182200. pSession->pFilterCtx = pCtx;
  182201. pSession->xTableFilter = xFilter;
  182202. }
  182203. /*
  182204. ** Attach a table to a session. All subsequent changes made to the table
  182205. ** while the session object is enabled will be recorded.
  182206. **
  182207. ** Only tables that have a PRIMARY KEY defined may be attached. It does
  182208. ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
  182209. ** or not.
  182210. */
  182211. SQLITE_API int sqlite3session_attach(
  182212. sqlite3_session *pSession, /* Session object */
  182213. const char *zName /* Table name */
  182214. ){
  182215. int rc = SQLITE_OK;
  182216. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  182217. if( !zName ){
  182218. pSession->bAutoAttach = 1;
  182219. }else{
  182220. SessionTable *pTab; /* New table object (if required) */
  182221. int nName; /* Number of bytes in string zName */
  182222. /* First search for an existing entry. If one is found, this call is
  182223. ** a no-op. Return early. */
  182224. nName = sqlite3Strlen30(zName);
  182225. for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
  182226. if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
  182227. }
  182228. if( !pTab ){
  182229. /* Allocate new SessionTable object. */
  182230. pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
  182231. if( !pTab ){
  182232. rc = SQLITE_NOMEM;
  182233. }else{
  182234. /* Populate the new SessionTable object and link it into the list.
  182235. ** The new object must be linked onto the end of the list, not
  182236. ** simply added to the start of it in order to ensure that tables
  182237. ** appear in the correct order when a changeset or patchset is
  182238. ** eventually generated. */
  182239. SessionTable **ppTab;
  182240. memset(pTab, 0, sizeof(SessionTable));
  182241. pTab->zName = (char *)&pTab[1];
  182242. memcpy(pTab->zName, zName, nName+1);
  182243. for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
  182244. *ppTab = pTab;
  182245. }
  182246. }
  182247. }
  182248. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  182249. return rc;
  182250. }
  182251. /*
  182252. ** Ensure that there is room in the buffer to append nByte bytes of data.
  182253. ** If not, use sqlite3_realloc() to grow the buffer so that there is.
  182254. **
  182255. ** If successful, return zero. Otherwise, if an OOM condition is encountered,
  182256. ** set *pRc to SQLITE_NOMEM and return non-zero.
  182257. */
  182258. static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
  182259. if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
  182260. u8 *aNew;
  182261. i64 nNew = p->nAlloc ? p->nAlloc : 128;
  182262. do {
  182263. nNew = nNew*2;
  182264. }while( (nNew-p->nBuf)<nByte );
  182265. aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew);
  182266. if( 0==aNew ){
  182267. *pRc = SQLITE_NOMEM;
  182268. }else{
  182269. p->aBuf = aNew;
  182270. p->nAlloc = nNew;
  182271. }
  182272. }
  182273. return (*pRc!=SQLITE_OK);
  182274. }
  182275. /*
  182276. ** Append the value passed as the second argument to the buffer passed
  182277. ** as the first.
  182278. **
  182279. ** This function is a no-op if *pRc is non-zero when it is called.
  182280. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
  182281. ** before returning.
  182282. */
  182283. static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
  182284. int rc = *pRc;
  182285. if( rc==SQLITE_OK ){
  182286. int nByte = 0;
  182287. rc = sessionSerializeValue(0, pVal, &nByte);
  182288. sessionBufferGrow(p, nByte, &rc);
  182289. if( rc==SQLITE_OK ){
  182290. rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
  182291. p->nBuf += nByte;
  182292. }else{
  182293. *pRc = rc;
  182294. }
  182295. }
  182296. }
  182297. /*
  182298. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  182299. ** called. Otherwise, append a single byte to the buffer.
  182300. **
  182301. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  182302. ** returning.
  182303. */
  182304. static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
  182305. if( 0==sessionBufferGrow(p, 1, pRc) ){
  182306. p->aBuf[p->nBuf++] = v;
  182307. }
  182308. }
  182309. /*
  182310. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  182311. ** called. Otherwise, append a single varint to the buffer.
  182312. **
  182313. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  182314. ** returning.
  182315. */
  182316. static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
  182317. if( 0==sessionBufferGrow(p, 9, pRc) ){
  182318. p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
  182319. }
  182320. }
  182321. /*
  182322. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  182323. ** called. Otherwise, append a blob of data to the buffer.
  182324. **
  182325. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  182326. ** returning.
  182327. */
  182328. static void sessionAppendBlob(
  182329. SessionBuffer *p,
  182330. const u8 *aBlob,
  182331. int nBlob,
  182332. int *pRc
  182333. ){
  182334. if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
  182335. memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
  182336. p->nBuf += nBlob;
  182337. }
  182338. }
  182339. /*
  182340. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  182341. ** called. Otherwise, append a string to the buffer. All bytes in the string
  182342. ** up to (but not including) the nul-terminator are written to the buffer.
  182343. **
  182344. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  182345. ** returning.
  182346. */
  182347. static void sessionAppendStr(
  182348. SessionBuffer *p,
  182349. const char *zStr,
  182350. int *pRc
  182351. ){
  182352. int nStr = sqlite3Strlen30(zStr);
  182353. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  182354. memcpy(&p->aBuf[p->nBuf], zStr, nStr);
  182355. p->nBuf += nStr;
  182356. }
  182357. }
  182358. /*
  182359. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  182360. ** called. Otherwise, append the string representation of integer iVal
  182361. ** to the buffer. No nul-terminator is written.
  182362. **
  182363. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  182364. ** returning.
  182365. */
  182366. static void sessionAppendInteger(
  182367. SessionBuffer *p, /* Buffer to append to */
  182368. int iVal, /* Value to write the string rep. of */
  182369. int *pRc /* IN/OUT: Error code */
  182370. ){
  182371. char aBuf[24];
  182372. sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  182373. sessionAppendStr(p, aBuf, pRc);
  182374. }
  182375. /*
  182376. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  182377. ** called. Otherwise, append the string zStr enclosed in quotes (") and
  182378. ** with any embedded quote characters escaped to the buffer. No
  182379. ** nul-terminator byte is written.
  182380. **
  182381. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  182382. ** returning.
  182383. */
  182384. static void sessionAppendIdent(
  182385. SessionBuffer *p, /* Buffer to a append to */
  182386. const char *zStr, /* String to quote, escape and append */
  182387. int *pRc /* IN/OUT: Error code */
  182388. ){
  182389. int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
  182390. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  182391. char *zOut = (char *)&p->aBuf[p->nBuf];
  182392. const char *zIn = zStr;
  182393. *zOut++ = '"';
  182394. while( *zIn ){
  182395. if( *zIn=='"' ) *zOut++ = '"';
  182396. *zOut++ = *(zIn++);
  182397. }
  182398. *zOut++ = '"';
  182399. p->nBuf = (int)((u8 *)zOut - p->aBuf);
  182400. }
  182401. }
  182402. /*
  182403. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  182404. ** called. Otherwse, it appends the serialized version of the value stored
  182405. ** in column iCol of the row that SQL statement pStmt currently points
  182406. ** to to the buffer.
  182407. */
  182408. static void sessionAppendCol(
  182409. SessionBuffer *p, /* Buffer to append to */
  182410. sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
  182411. int iCol, /* Column to read value from */
  182412. int *pRc /* IN/OUT: Error code */
  182413. ){
  182414. if( *pRc==SQLITE_OK ){
  182415. int eType = sqlite3_column_type(pStmt, iCol);
  182416. sessionAppendByte(p, (u8)eType, pRc);
  182417. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  182418. sqlite3_int64 i;
  182419. u8 aBuf[8];
  182420. if( eType==SQLITE_INTEGER ){
  182421. i = sqlite3_column_int64(pStmt, iCol);
  182422. }else{
  182423. double r = sqlite3_column_double(pStmt, iCol);
  182424. memcpy(&i, &r, 8);
  182425. }
  182426. sessionPutI64(aBuf, i);
  182427. sessionAppendBlob(p, aBuf, 8, pRc);
  182428. }
  182429. if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
  182430. u8 *z;
  182431. int nByte;
  182432. if( eType==SQLITE_BLOB ){
  182433. z = (u8 *)sqlite3_column_blob(pStmt, iCol);
  182434. }else{
  182435. z = (u8 *)sqlite3_column_text(pStmt, iCol);
  182436. }
  182437. nByte = sqlite3_column_bytes(pStmt, iCol);
  182438. if( z || (eType==SQLITE_BLOB && nByte==0) ){
  182439. sessionAppendVarint(p, nByte, pRc);
  182440. sessionAppendBlob(p, z, nByte, pRc);
  182441. }else{
  182442. *pRc = SQLITE_NOMEM;
  182443. }
  182444. }
  182445. }
  182446. }
  182447. /*
  182448. **
  182449. ** This function appends an update change to the buffer (see the comments
  182450. ** under "CHANGESET FORMAT" at the top of the file). An update change
  182451. ** consists of:
  182452. **
  182453. ** 1 byte: SQLITE_UPDATE (0x17)
  182454. ** n bytes: old.* record (see RECORD FORMAT)
  182455. ** m bytes: new.* record (see RECORD FORMAT)
  182456. **
  182457. ** The SessionChange object passed as the third argument contains the
  182458. ** values that were stored in the row when the session began (the old.*
  182459. ** values). The statement handle passed as the second argument points
  182460. ** at the current version of the row (the new.* values).
  182461. **
  182462. ** If all of the old.* values are equal to their corresponding new.* value
  182463. ** (i.e. nothing has changed), then no data at all is appended to the buffer.
  182464. **
  182465. ** Otherwise, the old.* record contains all primary key values and the
  182466. ** original values of any fields that have been modified. The new.* record
  182467. ** contains the new values of only those fields that have been modified.
  182468. */
  182469. static int sessionAppendUpdate(
  182470. SessionBuffer *pBuf, /* Buffer to append to */
  182471. int bPatchset, /* True for "patchset", 0 for "changeset" */
  182472. sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
  182473. SessionChange *p, /* Object containing old values */
  182474. u8 *abPK /* Boolean array - true for PK columns */
  182475. ){
  182476. int rc = SQLITE_OK;
  182477. SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
  182478. int bNoop = 1; /* Set to zero if any values are modified */
  182479. int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
  182480. int i; /* Used to iterate through columns */
  182481. u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
  182482. sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
  182483. sessionAppendByte(pBuf, p->bIndirect, &rc);
  182484. for(i=0; i<sqlite3_column_count(pStmt); i++){
  182485. int bChanged = 0;
  182486. int nAdvance;
  182487. int eType = *pCsr;
  182488. switch( eType ){
  182489. case SQLITE_NULL:
  182490. nAdvance = 1;
  182491. if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  182492. bChanged = 1;
  182493. }
  182494. break;
  182495. case SQLITE_FLOAT:
  182496. case SQLITE_INTEGER: {
  182497. nAdvance = 9;
  182498. if( eType==sqlite3_column_type(pStmt, i) ){
  182499. sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
  182500. if( eType==SQLITE_INTEGER ){
  182501. if( iVal==sqlite3_column_int64(pStmt, i) ) break;
  182502. }else{
  182503. double dVal;
  182504. memcpy(&dVal, &iVal, 8);
  182505. if( dVal==sqlite3_column_double(pStmt, i) ) break;
  182506. }
  182507. }
  182508. bChanged = 1;
  182509. break;
  182510. }
  182511. default: {
  182512. int n;
  182513. int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
  182514. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  182515. nAdvance = nHdr + n;
  182516. if( eType==sqlite3_column_type(pStmt, i)
  182517. && n==sqlite3_column_bytes(pStmt, i)
  182518. && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
  182519. ){
  182520. break;
  182521. }
  182522. bChanged = 1;
  182523. }
  182524. }
  182525. /* If at least one field has been modified, this is not a no-op. */
  182526. if( bChanged ) bNoop = 0;
  182527. /* Add a field to the old.* record. This is omitted if this modules is
  182528. ** currently generating a patchset. */
  182529. if( bPatchset==0 ){
  182530. if( bChanged || abPK[i] ){
  182531. sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
  182532. }else{
  182533. sessionAppendByte(pBuf, 0, &rc);
  182534. }
  182535. }
  182536. /* Add a field to the new.* record. Or the only record if currently
  182537. ** generating a patchset. */
  182538. if( bChanged || (bPatchset && abPK[i]) ){
  182539. sessionAppendCol(&buf2, pStmt, i, &rc);
  182540. }else{
  182541. sessionAppendByte(&buf2, 0, &rc);
  182542. }
  182543. pCsr += nAdvance;
  182544. }
  182545. if( bNoop ){
  182546. pBuf->nBuf = nRewind;
  182547. }else{
  182548. sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
  182549. }
  182550. sqlite3_free(buf2.aBuf);
  182551. return rc;
  182552. }
  182553. /*
  182554. ** Append a DELETE change to the buffer passed as the first argument. Use
  182555. ** the changeset format if argument bPatchset is zero, or the patchset
  182556. ** format otherwise.
  182557. */
  182558. static int sessionAppendDelete(
  182559. SessionBuffer *pBuf, /* Buffer to append to */
  182560. int bPatchset, /* True for "patchset", 0 for "changeset" */
  182561. SessionChange *p, /* Object containing old values */
  182562. int nCol, /* Number of columns in table */
  182563. u8 *abPK /* Boolean array - true for PK columns */
  182564. ){
  182565. int rc = SQLITE_OK;
  182566. sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
  182567. sessionAppendByte(pBuf, p->bIndirect, &rc);
  182568. if( bPatchset==0 ){
  182569. sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
  182570. }else{
  182571. int i;
  182572. u8 *a = p->aRecord;
  182573. for(i=0; i<nCol; i++){
  182574. u8 *pStart = a;
  182575. int eType = *a++;
  182576. switch( eType ){
  182577. case 0:
  182578. case SQLITE_NULL:
  182579. assert( abPK[i]==0 );
  182580. break;
  182581. case SQLITE_FLOAT:
  182582. case SQLITE_INTEGER:
  182583. a += 8;
  182584. break;
  182585. default: {
  182586. int n;
  182587. a += sessionVarintGet(a, &n);
  182588. a += n;
  182589. break;
  182590. }
  182591. }
  182592. if( abPK[i] ){
  182593. sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
  182594. }
  182595. }
  182596. assert( (a - p->aRecord)==p->nRecord );
  182597. }
  182598. return rc;
  182599. }
  182600. /*
  182601. ** Formulate and prepare a SELECT statement to retrieve a row from table
  182602. ** zTab in database zDb based on its primary key. i.e.
  182603. **
  182604. ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
  182605. */
  182606. static int sessionSelectStmt(
  182607. sqlite3 *db, /* Database handle */
  182608. const char *zDb, /* Database name */
  182609. const char *zTab, /* Table name */
  182610. int nCol, /* Number of columns in table */
  182611. const char **azCol, /* Names of table columns */
  182612. u8 *abPK, /* PRIMARY KEY array */
  182613. sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
  182614. ){
  182615. int rc = SQLITE_OK;
  182616. char *zSql = 0;
  182617. int nSql = -1;
  182618. if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
  182619. zSql = sqlite3_mprintf(
  182620. "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
  182621. "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
  182622. );
  182623. if( zSql==0 ) rc = SQLITE_NOMEM;
  182624. }else{
  182625. int i;
  182626. const char *zSep = "";
  182627. SessionBuffer buf = {0, 0, 0};
  182628. sessionAppendStr(&buf, "SELECT * FROM ", &rc);
  182629. sessionAppendIdent(&buf, zDb, &rc);
  182630. sessionAppendStr(&buf, ".", &rc);
  182631. sessionAppendIdent(&buf, zTab, &rc);
  182632. sessionAppendStr(&buf, " WHERE ", &rc);
  182633. for(i=0; i<nCol; i++){
  182634. if( abPK[i] ){
  182635. sessionAppendStr(&buf, zSep, &rc);
  182636. sessionAppendIdent(&buf, azCol[i], &rc);
  182637. sessionAppendStr(&buf, " IS ?", &rc);
  182638. sessionAppendInteger(&buf, i+1, &rc);
  182639. zSep = " AND ";
  182640. }
  182641. }
  182642. zSql = (char*)buf.aBuf;
  182643. nSql = buf.nBuf;
  182644. }
  182645. if( rc==SQLITE_OK ){
  182646. rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
  182647. }
  182648. sqlite3_free(zSql);
  182649. return rc;
  182650. }
  182651. /*
  182652. ** Bind the PRIMARY KEY values from the change passed in argument pChange
  182653. ** to the SELECT statement passed as the first argument. The SELECT statement
  182654. ** is as prepared by function sessionSelectStmt().
  182655. **
  182656. ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
  182657. ** error code (e.g. SQLITE_NOMEM) otherwise.
  182658. */
  182659. static int sessionSelectBind(
  182660. sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
  182661. int nCol, /* Number of columns in table */
  182662. u8 *abPK, /* PRIMARY KEY array */
  182663. SessionChange *pChange /* Change structure */
  182664. ){
  182665. int i;
  182666. int rc = SQLITE_OK;
  182667. u8 *a = pChange->aRecord;
  182668. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  182669. int eType = *a++;
  182670. switch( eType ){
  182671. case 0:
  182672. case SQLITE_NULL:
  182673. assert( abPK[i]==0 );
  182674. break;
  182675. case SQLITE_INTEGER: {
  182676. if( abPK[i] ){
  182677. i64 iVal = sessionGetI64(a);
  182678. rc = sqlite3_bind_int64(pSelect, i+1, iVal);
  182679. }
  182680. a += 8;
  182681. break;
  182682. }
  182683. case SQLITE_FLOAT: {
  182684. if( abPK[i] ){
  182685. double rVal;
  182686. i64 iVal = sessionGetI64(a);
  182687. memcpy(&rVal, &iVal, 8);
  182688. rc = sqlite3_bind_double(pSelect, i+1, rVal);
  182689. }
  182690. a += 8;
  182691. break;
  182692. }
  182693. case SQLITE_TEXT: {
  182694. int n;
  182695. a += sessionVarintGet(a, &n);
  182696. if( abPK[i] ){
  182697. rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
  182698. }
  182699. a += n;
  182700. break;
  182701. }
  182702. default: {
  182703. int n;
  182704. assert( eType==SQLITE_BLOB );
  182705. a += sessionVarintGet(a, &n);
  182706. if( abPK[i] ){
  182707. rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
  182708. }
  182709. a += n;
  182710. break;
  182711. }
  182712. }
  182713. }
  182714. return rc;
  182715. }
  182716. /*
  182717. ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
  182718. ** is called. Otherwise, append a serialized table header (part of the binary
  182719. ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
  182720. ** SQLite error code before returning.
  182721. */
  182722. static void sessionAppendTableHdr(
  182723. SessionBuffer *pBuf, /* Append header to this buffer */
  182724. int bPatchset, /* Use the patchset format if true */
  182725. SessionTable *pTab, /* Table object to append header for */
  182726. int *pRc /* IN/OUT: Error code */
  182727. ){
  182728. /* Write a table header */
  182729. sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
  182730. sessionAppendVarint(pBuf, pTab->nCol, pRc);
  182731. sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
  182732. sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
  182733. }
  182734. /*
  182735. ** Generate either a changeset (if argument bPatchset is zero) or a patchset
  182736. ** (if it is non-zero) based on the current contents of the session object
  182737. ** passed as the first argument.
  182738. **
  182739. ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
  182740. ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
  182741. ** occurs, an SQLite error code is returned and both output variables set
  182742. ** to 0.
  182743. */
  182744. static int sessionGenerateChangeset(
  182745. sqlite3_session *pSession, /* Session object */
  182746. int bPatchset, /* True for patchset, false for changeset */
  182747. int (*xOutput)(void *pOut, const void *pData, int nData),
  182748. void *pOut, /* First argument for xOutput */
  182749. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  182750. void **ppChangeset /* OUT: Buffer containing changeset */
  182751. ){
  182752. sqlite3 *db = pSession->db; /* Source database handle */
  182753. SessionTable *pTab; /* Used to iterate through attached tables */
  182754. SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
  182755. int rc; /* Return code */
  182756. assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
  182757. /* Zero the output variables in case an error occurs. If this session
  182758. ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
  182759. ** this call will be a no-op. */
  182760. if( xOutput==0 ){
  182761. *pnChangeset = 0;
  182762. *ppChangeset = 0;
  182763. }
  182764. if( pSession->rc ) return pSession->rc;
  182765. rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
  182766. if( rc!=SQLITE_OK ) return rc;
  182767. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  182768. for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  182769. if( pTab->nEntry ){
  182770. const char *zName = pTab->zName;
  182771. int nCol; /* Number of columns in table */
  182772. u8 *abPK; /* Primary key array */
  182773. const char **azCol = 0; /* Table columns */
  182774. int i; /* Used to iterate through hash buckets */
  182775. sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
  182776. int nRewind = buf.nBuf; /* Initial size of write buffer */
  182777. int nNoop; /* Size of buffer after writing tbl header */
  182778. /* Check the table schema is still Ok. */
  182779. rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
  182780. if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
  182781. rc = SQLITE_SCHEMA;
  182782. }
  182783. /* Write a table header */
  182784. sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
  182785. /* Build and compile a statement to execute: */
  182786. if( rc==SQLITE_OK ){
  182787. rc = sessionSelectStmt(
  182788. db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
  182789. }
  182790. nNoop = buf.nBuf;
  182791. for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
  182792. SessionChange *p; /* Used to iterate through changes */
  182793. for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
  182794. rc = sessionSelectBind(pSel, nCol, abPK, p);
  182795. if( rc!=SQLITE_OK ) continue;
  182796. if( sqlite3_step(pSel)==SQLITE_ROW ){
  182797. if( p->op==SQLITE_INSERT ){
  182798. int iCol;
  182799. sessionAppendByte(&buf, SQLITE_INSERT, &rc);
  182800. sessionAppendByte(&buf, p->bIndirect, &rc);
  182801. for(iCol=0; iCol<nCol; iCol++){
  182802. sessionAppendCol(&buf, pSel, iCol, &rc);
  182803. }
  182804. }else{
  182805. rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
  182806. }
  182807. }else if( p->op!=SQLITE_INSERT ){
  182808. rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
  182809. }
  182810. if( rc==SQLITE_OK ){
  182811. rc = sqlite3_reset(pSel);
  182812. }
  182813. /* If the buffer is now larger than sessions_strm_chunk_size, pass
  182814. ** its contents to the xOutput() callback. */
  182815. if( xOutput
  182816. && rc==SQLITE_OK
  182817. && buf.nBuf>nNoop
  182818. && buf.nBuf>sessions_strm_chunk_size
  182819. ){
  182820. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  182821. nNoop = -1;
  182822. buf.nBuf = 0;
  182823. }
  182824. }
  182825. }
  182826. sqlite3_finalize(pSel);
  182827. if( buf.nBuf==nNoop ){
  182828. buf.nBuf = nRewind;
  182829. }
  182830. sqlite3_free((char*)azCol); /* cast works around VC++ bug */
  182831. }
  182832. }
  182833. if( rc==SQLITE_OK ){
  182834. if( xOutput==0 ){
  182835. *pnChangeset = buf.nBuf;
  182836. *ppChangeset = buf.aBuf;
  182837. buf.aBuf = 0;
  182838. }else if( buf.nBuf>0 ){
  182839. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  182840. }
  182841. }
  182842. sqlite3_free(buf.aBuf);
  182843. sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
  182844. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  182845. return rc;
  182846. }
  182847. /*
  182848. ** Obtain a changeset object containing all changes recorded by the
  182849. ** session object passed as the first argument.
  182850. **
  182851. ** It is the responsibility of the caller to eventually free the buffer
  182852. ** using sqlite3_free().
  182853. */
  182854. SQLITE_API int sqlite3session_changeset(
  182855. sqlite3_session *pSession, /* Session object */
  182856. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  182857. void **ppChangeset /* OUT: Buffer containing changeset */
  182858. ){
  182859. return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
  182860. }
  182861. /*
  182862. ** Streaming version of sqlite3session_changeset().
  182863. */
  182864. SQLITE_API int sqlite3session_changeset_strm(
  182865. sqlite3_session *pSession,
  182866. int (*xOutput)(void *pOut, const void *pData, int nData),
  182867. void *pOut
  182868. ){
  182869. return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
  182870. }
  182871. /*
  182872. ** Streaming version of sqlite3session_patchset().
  182873. */
  182874. SQLITE_API int sqlite3session_patchset_strm(
  182875. sqlite3_session *pSession,
  182876. int (*xOutput)(void *pOut, const void *pData, int nData),
  182877. void *pOut
  182878. ){
  182879. return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
  182880. }
  182881. /*
  182882. ** Obtain a patchset object containing all changes recorded by the
  182883. ** session object passed as the first argument.
  182884. **
  182885. ** It is the responsibility of the caller to eventually free the buffer
  182886. ** using sqlite3_free().
  182887. */
  182888. SQLITE_API int sqlite3session_patchset(
  182889. sqlite3_session *pSession, /* Session object */
  182890. int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
  182891. void **ppPatchset /* OUT: Buffer containing changeset */
  182892. ){
  182893. return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
  182894. }
  182895. /*
  182896. ** Enable or disable the session object passed as the first argument.
  182897. */
  182898. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
  182899. int ret;
  182900. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  182901. if( bEnable>=0 ){
  182902. pSession->bEnable = bEnable;
  182903. }
  182904. ret = pSession->bEnable;
  182905. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  182906. return ret;
  182907. }
  182908. /*
  182909. ** Enable or disable the session object passed as the first argument.
  182910. */
  182911. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
  182912. int ret;
  182913. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  182914. if( bIndirect>=0 ){
  182915. pSession->bIndirect = bIndirect;
  182916. }
  182917. ret = pSession->bIndirect;
  182918. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  182919. return ret;
  182920. }
  182921. /*
  182922. ** Return true if there have been no changes to monitored tables recorded
  182923. ** by the session object passed as the only argument.
  182924. */
  182925. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
  182926. int ret = 0;
  182927. SessionTable *pTab;
  182928. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  182929. for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
  182930. ret = (pTab->nEntry>0);
  182931. }
  182932. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  182933. return (ret==0);
  182934. }
  182935. /*
  182936. ** Do the work for either sqlite3changeset_start() or start_strm().
  182937. */
  182938. static int sessionChangesetStart(
  182939. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  182940. int (*xInput)(void *pIn, void *pData, int *pnData),
  182941. void *pIn,
  182942. int nChangeset, /* Size of buffer pChangeset in bytes */
  182943. void *pChangeset, /* Pointer to buffer containing changeset */
  182944. int bInvert /* True to invert changeset */
  182945. ){
  182946. sqlite3_changeset_iter *pRet; /* Iterator to return */
  182947. int nByte; /* Number of bytes to allocate for iterator */
  182948. assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
  182949. /* Zero the output variable in case an error occurs. */
  182950. *pp = 0;
  182951. /* Allocate and initialize the iterator structure. */
  182952. nByte = sizeof(sqlite3_changeset_iter);
  182953. pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
  182954. if( !pRet ) return SQLITE_NOMEM;
  182955. memset(pRet, 0, sizeof(sqlite3_changeset_iter));
  182956. pRet->in.aData = (u8 *)pChangeset;
  182957. pRet->in.nData = nChangeset;
  182958. pRet->in.xInput = xInput;
  182959. pRet->in.pIn = pIn;
  182960. pRet->in.bEof = (xInput ? 0 : 1);
  182961. pRet->bInvert = bInvert;
  182962. /* Populate the output variable and return success. */
  182963. *pp = pRet;
  182964. return SQLITE_OK;
  182965. }
  182966. /*
  182967. ** Create an iterator used to iterate through the contents of a changeset.
  182968. */
  182969. SQLITE_API int sqlite3changeset_start(
  182970. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  182971. int nChangeset, /* Size of buffer pChangeset in bytes */
  182972. void *pChangeset /* Pointer to buffer containing changeset */
  182973. ){
  182974. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0);
  182975. }
  182976. SQLITE_API int sqlite3changeset_start_v2(
  182977. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  182978. int nChangeset, /* Size of buffer pChangeset in bytes */
  182979. void *pChangeset, /* Pointer to buffer containing changeset */
  182980. int flags
  182981. ){
  182982. int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
  182983. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert);
  182984. }
  182985. /*
  182986. ** Streaming version of sqlite3changeset_start().
  182987. */
  182988. SQLITE_API int sqlite3changeset_start_strm(
  182989. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  182990. int (*xInput)(void *pIn, void *pData, int *pnData),
  182991. void *pIn
  182992. ){
  182993. return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0);
  182994. }
  182995. SQLITE_API int sqlite3changeset_start_v2_strm(
  182996. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  182997. int (*xInput)(void *pIn, void *pData, int *pnData),
  182998. void *pIn,
  182999. int flags
  183000. ){
  183001. int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
  183002. return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert);
  183003. }
  183004. /*
  183005. ** If the SessionInput object passed as the only argument is a streaming
  183006. ** object and the buffer is full, discard some data to free up space.
  183007. */
  183008. static void sessionDiscardData(SessionInput *pIn){
  183009. if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){
  183010. int nMove = pIn->buf.nBuf - pIn->iNext;
  183011. assert( nMove>=0 );
  183012. if( nMove>0 ){
  183013. memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
  183014. }
  183015. pIn->buf.nBuf -= pIn->iNext;
  183016. pIn->iNext = 0;
  183017. pIn->nData = pIn->buf.nBuf;
  183018. }
  183019. }
  183020. /*
  183021. ** Ensure that there are at least nByte bytes available in the buffer. Or,
  183022. ** if there are not nByte bytes remaining in the input, that all available
  183023. ** data is in the buffer.
  183024. **
  183025. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  183026. */
  183027. static int sessionInputBuffer(SessionInput *pIn, int nByte){
  183028. int rc = SQLITE_OK;
  183029. if( pIn->xInput ){
  183030. while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
  183031. int nNew = sessions_strm_chunk_size;
  183032. if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
  183033. if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
  183034. rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
  183035. if( nNew==0 ){
  183036. pIn->bEof = 1;
  183037. }else{
  183038. pIn->buf.nBuf += nNew;
  183039. }
  183040. }
  183041. pIn->aData = pIn->buf.aBuf;
  183042. pIn->nData = pIn->buf.nBuf;
  183043. }
  183044. }
  183045. return rc;
  183046. }
  183047. /*
  183048. ** When this function is called, *ppRec points to the start of a record
  183049. ** that contains nCol values. This function advances the pointer *ppRec
  183050. ** until it points to the byte immediately following that record.
  183051. */
  183052. static void sessionSkipRecord(
  183053. u8 **ppRec, /* IN/OUT: Record pointer */
  183054. int nCol /* Number of values in record */
  183055. ){
  183056. u8 *aRec = *ppRec;
  183057. int i;
  183058. for(i=0; i<nCol; i++){
  183059. int eType = *aRec++;
  183060. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  183061. int nByte;
  183062. aRec += sessionVarintGet((u8*)aRec, &nByte);
  183063. aRec += nByte;
  183064. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  183065. aRec += 8;
  183066. }
  183067. }
  183068. *ppRec = aRec;
  183069. }
  183070. /*
  183071. ** This function sets the value of the sqlite3_value object passed as the
  183072. ** first argument to a copy of the string or blob held in the aData[]
  183073. ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
  183074. ** error occurs.
  183075. */
  183076. static int sessionValueSetStr(
  183077. sqlite3_value *pVal, /* Set the value of this object */
  183078. u8 *aData, /* Buffer containing string or blob data */
  183079. int nData, /* Size of buffer aData[] in bytes */
  183080. u8 enc /* String encoding (0 for blobs) */
  183081. ){
  183082. /* In theory this code could just pass SQLITE_TRANSIENT as the final
  183083. ** argument to sqlite3ValueSetStr() and have the copy created
  183084. ** automatically. But doing so makes it difficult to detect any OOM
  183085. ** error. Hence the code to create the copy externally. */
  183086. u8 *aCopy = sqlite3_malloc(nData+1);
  183087. if( aCopy==0 ) return SQLITE_NOMEM;
  183088. memcpy(aCopy, aData, nData);
  183089. sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
  183090. return SQLITE_OK;
  183091. }
  183092. /*
  183093. ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
  183094. ** for details.
  183095. **
  183096. ** When this function is called, *paChange points to the start of the record
  183097. ** to deserialize. Assuming no error occurs, *paChange is set to point to
  183098. ** one byte after the end of the same record before this function returns.
  183099. ** If the argument abPK is NULL, then the record contains nCol values. Or,
  183100. ** if abPK is other than NULL, then the record contains only the PK fields
  183101. ** (in other words, it is a patchset DELETE record).
  183102. **
  183103. ** If successful, each element of the apOut[] array (allocated by the caller)
  183104. ** is set to point to an sqlite3_value object containing the value read
  183105. ** from the corresponding position in the record. If that value is not
  183106. ** included in the record (i.e. because the record is part of an UPDATE change
  183107. ** and the field was not modified), the corresponding element of apOut[] is
  183108. ** set to NULL.
  183109. **
  183110. ** It is the responsibility of the caller to free all sqlite_value structures
  183111. ** using sqlite3_free().
  183112. **
  183113. ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  183114. ** The apOut[] array may have been partially populated in this case.
  183115. */
  183116. static int sessionReadRecord(
  183117. SessionInput *pIn, /* Input data */
  183118. int nCol, /* Number of values in record */
  183119. u8 *abPK, /* Array of primary key flags, or NULL */
  183120. sqlite3_value **apOut /* Write values to this array */
  183121. ){
  183122. int i; /* Used to iterate through columns */
  183123. int rc = SQLITE_OK;
  183124. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  183125. int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
  183126. if( abPK && abPK[i]==0 ) continue;
  183127. rc = sessionInputBuffer(pIn, 9);
  183128. if( rc==SQLITE_OK ){
  183129. if( pIn->iNext>=pIn->nData ){
  183130. rc = SQLITE_CORRUPT_BKPT;
  183131. }else{
  183132. eType = pIn->aData[pIn->iNext++];
  183133. assert( apOut[i]==0 );
  183134. if( eType ){
  183135. apOut[i] = sqlite3ValueNew(0);
  183136. if( !apOut[i] ) rc = SQLITE_NOMEM;
  183137. }
  183138. }
  183139. }
  183140. if( rc==SQLITE_OK ){
  183141. u8 *aVal = &pIn->aData[pIn->iNext];
  183142. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  183143. int nByte;
  183144. pIn->iNext += sessionVarintGet(aVal, &nByte);
  183145. rc = sessionInputBuffer(pIn, nByte);
  183146. if( rc==SQLITE_OK ){
  183147. if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
  183148. rc = SQLITE_CORRUPT_BKPT;
  183149. }else{
  183150. u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
  183151. rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
  183152. pIn->iNext += nByte;
  183153. }
  183154. }
  183155. }
  183156. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  183157. sqlite3_int64 v = sessionGetI64(aVal);
  183158. if( eType==SQLITE_INTEGER ){
  183159. sqlite3VdbeMemSetInt64(apOut[i], v);
  183160. }else{
  183161. double d;
  183162. memcpy(&d, &v, 8);
  183163. sqlite3VdbeMemSetDouble(apOut[i], d);
  183164. }
  183165. pIn->iNext += 8;
  183166. }
  183167. }
  183168. }
  183169. return rc;
  183170. }
  183171. /*
  183172. ** The input pointer currently points to the second byte of a table-header.
  183173. ** Specifically, to the following:
  183174. **
  183175. ** + number of columns in table (varint)
  183176. ** + array of PK flags (1 byte per column),
  183177. ** + table name (nul terminated).
  183178. **
  183179. ** This function ensures that all of the above is present in the input
  183180. ** buffer (i.e. that it can be accessed without any calls to xInput()).
  183181. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  183182. ** The input pointer is not moved.
  183183. */
  183184. static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
  183185. int rc = SQLITE_OK;
  183186. int nCol = 0;
  183187. int nRead = 0;
  183188. rc = sessionInputBuffer(pIn, 9);
  183189. if( rc==SQLITE_OK ){
  183190. nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
  183191. /* The hard upper limit for the number of columns in an SQLite
  183192. ** database table is, according to sqliteLimit.h, 32676. So
  183193. ** consider any table-header that purports to have more than 65536
  183194. ** columns to be corrupt. This is convenient because otherwise,
  183195. ** if the (nCol>65536) condition below were omitted, a sufficiently
  183196. ** large value for nCol may cause nRead to wrap around and become
  183197. ** negative. Leading to a crash. */
  183198. if( nCol<0 || nCol>65536 ){
  183199. rc = SQLITE_CORRUPT_BKPT;
  183200. }else{
  183201. rc = sessionInputBuffer(pIn, nRead+nCol+100);
  183202. nRead += nCol;
  183203. }
  183204. }
  183205. while( rc==SQLITE_OK ){
  183206. while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
  183207. nRead++;
  183208. }
  183209. if( (pIn->iNext + nRead)<pIn->nData ) break;
  183210. rc = sessionInputBuffer(pIn, nRead + 100);
  183211. }
  183212. *pnByte = nRead+1;
  183213. return rc;
  183214. }
  183215. /*
  183216. ** The input pointer currently points to the first byte of the first field
  183217. ** of a record consisting of nCol columns. This function ensures the entire
  183218. ** record is buffered. It does not move the input pointer.
  183219. **
  183220. ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
  183221. ** the record in bytes. Otherwise, an SQLite error code is returned. The
  183222. ** final value of *pnByte is undefined in this case.
  183223. */
  183224. static int sessionChangesetBufferRecord(
  183225. SessionInput *pIn, /* Input data */
  183226. int nCol, /* Number of columns in record */
  183227. int *pnByte /* OUT: Size of record in bytes */
  183228. ){
  183229. int rc = SQLITE_OK;
  183230. int nByte = 0;
  183231. int i;
  183232. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  183233. int eType;
  183234. rc = sessionInputBuffer(pIn, nByte + 10);
  183235. if( rc==SQLITE_OK ){
  183236. eType = pIn->aData[pIn->iNext + nByte++];
  183237. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  183238. int n;
  183239. nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
  183240. nByte += n;
  183241. rc = sessionInputBuffer(pIn, nByte);
  183242. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  183243. nByte += 8;
  183244. }
  183245. }
  183246. }
  183247. *pnByte = nByte;
  183248. return rc;
  183249. }
  183250. /*
  183251. ** The input pointer currently points to the second byte of a table-header.
  183252. ** Specifically, to the following:
  183253. **
  183254. ** + number of columns in table (varint)
  183255. ** + array of PK flags (1 byte per column),
  183256. ** + table name (nul terminated).
  183257. **
  183258. ** This function decodes the table-header and populates the p->nCol,
  183259. ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
  183260. ** also allocated or resized according to the new value of p->nCol. The
  183261. ** input pointer is left pointing to the byte following the table header.
  183262. **
  183263. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
  183264. ** is returned and the final values of the various fields enumerated above
  183265. ** are undefined.
  183266. */
  183267. static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
  183268. int rc;
  183269. int nCopy;
  183270. assert( p->rc==SQLITE_OK );
  183271. rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
  183272. if( rc==SQLITE_OK ){
  183273. int nByte;
  183274. int nVarint;
  183275. nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
  183276. if( p->nCol>0 ){
  183277. nCopy -= nVarint;
  183278. p->in.iNext += nVarint;
  183279. nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
  183280. p->tblhdr.nBuf = 0;
  183281. sessionBufferGrow(&p->tblhdr, nByte, &rc);
  183282. }else{
  183283. rc = SQLITE_CORRUPT_BKPT;
  183284. }
  183285. }
  183286. if( rc==SQLITE_OK ){
  183287. int iPK = sizeof(sqlite3_value*)*p->nCol*2;
  183288. memset(p->tblhdr.aBuf, 0, iPK);
  183289. memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
  183290. p->in.iNext += nCopy;
  183291. }
  183292. p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
  183293. p->abPK = (u8*)&p->apValue[p->nCol*2];
  183294. p->zTab = (char*)&p->abPK[p->nCol];
  183295. return (p->rc = rc);
  183296. }
  183297. /*
  183298. ** Advance the changeset iterator to the next change.
  183299. **
  183300. ** If both paRec and pnRec are NULL, then this function works like the public
  183301. ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
  183302. ** sqlite3changeset_new() and old() APIs may be used to query for values.
  183303. **
  183304. ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
  183305. ** record is written to *paRec before returning and the number of bytes in
  183306. ** the record to *pnRec.
  183307. **
  183308. ** Either way, this function returns SQLITE_ROW if the iterator is
  183309. ** successfully advanced to the next change in the changeset, an SQLite
  183310. ** error code if an error occurs, or SQLITE_DONE if there are no further
  183311. ** changes in the changeset.
  183312. */
  183313. static int sessionChangesetNext(
  183314. sqlite3_changeset_iter *p, /* Changeset iterator */
  183315. u8 **paRec, /* If non-NULL, store record pointer here */
  183316. int *pnRec, /* If non-NULL, store size of record here */
  183317. int *pbNew /* If non-NULL, true if new table */
  183318. ){
  183319. int i;
  183320. u8 op;
  183321. assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
  183322. /* If the iterator is in the error-state, return immediately. */
  183323. if( p->rc!=SQLITE_OK ) return p->rc;
  183324. /* Free the current contents of p->apValue[], if any. */
  183325. if( p->apValue ){
  183326. for(i=0; i<p->nCol*2; i++){
  183327. sqlite3ValueFree(p->apValue[i]);
  183328. }
  183329. memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
  183330. }
  183331. /* Make sure the buffer contains at least 10 bytes of input data, or all
  183332. ** remaining data if there are less than 10 bytes available. This is
  183333. ** sufficient either for the 'T' or 'P' byte and the varint that follows
  183334. ** it, or for the two single byte values otherwise. */
  183335. p->rc = sessionInputBuffer(&p->in, 2);
  183336. if( p->rc!=SQLITE_OK ) return p->rc;
  183337. /* If the iterator is already at the end of the changeset, return DONE. */
  183338. if( p->in.iNext>=p->in.nData ){
  183339. return SQLITE_DONE;
  183340. }
  183341. sessionDiscardData(&p->in);
  183342. p->in.iCurrent = p->in.iNext;
  183343. op = p->in.aData[p->in.iNext++];
  183344. while( op=='T' || op=='P' ){
  183345. if( pbNew ) *pbNew = 1;
  183346. p->bPatchset = (op=='P');
  183347. if( sessionChangesetReadTblhdr(p) ) return p->rc;
  183348. if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
  183349. p->in.iCurrent = p->in.iNext;
  183350. if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
  183351. op = p->in.aData[p->in.iNext++];
  183352. }
  183353. if( p->zTab==0 || (p->bPatchset && p->bInvert) ){
  183354. /* The first record in the changeset is not a table header. Must be a
  183355. ** corrupt changeset. */
  183356. assert( p->in.iNext==1 || p->zTab );
  183357. return (p->rc = SQLITE_CORRUPT_BKPT);
  183358. }
  183359. p->op = op;
  183360. p->bIndirect = p->in.aData[p->in.iNext++];
  183361. if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
  183362. return (p->rc = SQLITE_CORRUPT_BKPT);
  183363. }
  183364. if( paRec ){
  183365. int nVal; /* Number of values to buffer */
  183366. if( p->bPatchset==0 && op==SQLITE_UPDATE ){
  183367. nVal = p->nCol * 2;
  183368. }else if( p->bPatchset && op==SQLITE_DELETE ){
  183369. nVal = 0;
  183370. for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
  183371. }else{
  183372. nVal = p->nCol;
  183373. }
  183374. p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
  183375. if( p->rc!=SQLITE_OK ) return p->rc;
  183376. *paRec = &p->in.aData[p->in.iNext];
  183377. p->in.iNext += *pnRec;
  183378. }else{
  183379. sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue);
  183380. sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]);
  183381. /* If this is an UPDATE or DELETE, read the old.* record. */
  183382. if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
  183383. u8 *abPK = p->bPatchset ? p->abPK : 0;
  183384. p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld);
  183385. if( p->rc!=SQLITE_OK ) return p->rc;
  183386. }
  183387. /* If this is an INSERT or UPDATE, read the new.* record. */
  183388. if( p->op!=SQLITE_DELETE ){
  183389. p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew);
  183390. if( p->rc!=SQLITE_OK ) return p->rc;
  183391. }
  183392. if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){
  183393. /* If this is an UPDATE that is part of a patchset, then all PK and
  183394. ** modified fields are present in the new.* record. The old.* record
  183395. ** is currently completely empty. This block shifts the PK fields from
  183396. ** new.* to old.*, to accommodate the code that reads these arrays. */
  183397. for(i=0; i<p->nCol; i++){
  183398. assert( p->bPatchset==0 || p->apValue[i]==0 );
  183399. if( p->abPK[i] ){
  183400. assert( p->apValue[i]==0 );
  183401. p->apValue[i] = p->apValue[i+p->nCol];
  183402. if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
  183403. p->apValue[i+p->nCol] = 0;
  183404. }
  183405. }
  183406. }else if( p->bInvert ){
  183407. if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE;
  183408. else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT;
  183409. }
  183410. }
  183411. return SQLITE_ROW;
  183412. }
  183413. /*
  183414. ** Advance an iterator created by sqlite3changeset_start() to the next
  183415. ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
  183416. ** or SQLITE_CORRUPT.
  183417. **
  183418. ** This function may not be called on iterators passed to a conflict handler
  183419. ** callback by changeset_apply().
  183420. */
  183421. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
  183422. return sessionChangesetNext(p, 0, 0, 0);
  183423. }
  183424. /*
  183425. ** The following function extracts information on the current change
  183426. ** from a changeset iterator. It may only be called after changeset_next()
  183427. ** has returned SQLITE_ROW.
  183428. */
  183429. SQLITE_API int sqlite3changeset_op(
  183430. sqlite3_changeset_iter *pIter, /* Iterator handle */
  183431. const char **pzTab, /* OUT: Pointer to table name */
  183432. int *pnCol, /* OUT: Number of columns in table */
  183433. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  183434. int *pbIndirect /* OUT: True if change is indirect */
  183435. ){
  183436. *pOp = pIter->op;
  183437. *pnCol = pIter->nCol;
  183438. *pzTab = pIter->zTab;
  183439. if( pbIndirect ) *pbIndirect = pIter->bIndirect;
  183440. return SQLITE_OK;
  183441. }
  183442. /*
  183443. ** Return information regarding the PRIMARY KEY and number of columns in
  183444. ** the database table affected by the change that pIter currently points
  183445. ** to. This function may only be called after changeset_next() returns
  183446. ** SQLITE_ROW.
  183447. */
  183448. SQLITE_API int sqlite3changeset_pk(
  183449. sqlite3_changeset_iter *pIter, /* Iterator object */
  183450. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  183451. int *pnCol /* OUT: Number of entries in output array */
  183452. ){
  183453. *pabPK = pIter->abPK;
  183454. if( pnCol ) *pnCol = pIter->nCol;
  183455. return SQLITE_OK;
  183456. }
  183457. /*
  183458. ** This function may only be called while the iterator is pointing to an
  183459. ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
  183460. ** Otherwise, SQLITE_MISUSE is returned.
  183461. **
  183462. ** It sets *ppValue to point to an sqlite3_value structure containing the
  183463. ** iVal'th value in the old.* record. Or, if that particular value is not
  183464. ** included in the record (because the change is an UPDATE and the field
  183465. ** was not modified and is not a PK column), set *ppValue to NULL.
  183466. **
  183467. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  183468. ** not modified. Otherwise, SQLITE_OK.
  183469. */
  183470. SQLITE_API int sqlite3changeset_old(
  183471. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  183472. int iVal, /* Index of old.* value to retrieve */
  183473. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  183474. ){
  183475. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
  183476. return SQLITE_MISUSE;
  183477. }
  183478. if( iVal<0 || iVal>=pIter->nCol ){
  183479. return SQLITE_RANGE;
  183480. }
  183481. *ppValue = pIter->apValue[iVal];
  183482. return SQLITE_OK;
  183483. }
  183484. /*
  183485. ** This function may only be called while the iterator is pointing to an
  183486. ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
  183487. ** Otherwise, SQLITE_MISUSE is returned.
  183488. **
  183489. ** It sets *ppValue to point to an sqlite3_value structure containing the
  183490. ** iVal'th value in the new.* record. Or, if that particular value is not
  183491. ** included in the record (because the change is an UPDATE and the field
  183492. ** was not modified), set *ppValue to NULL.
  183493. **
  183494. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  183495. ** not modified. Otherwise, SQLITE_OK.
  183496. */
  183497. SQLITE_API int sqlite3changeset_new(
  183498. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  183499. int iVal, /* Index of new.* value to retrieve */
  183500. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  183501. ){
  183502. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
  183503. return SQLITE_MISUSE;
  183504. }
  183505. if( iVal<0 || iVal>=pIter->nCol ){
  183506. return SQLITE_RANGE;
  183507. }
  183508. *ppValue = pIter->apValue[pIter->nCol+iVal];
  183509. return SQLITE_OK;
  183510. }
  183511. /*
  183512. ** The following two macros are used internally. They are similar to the
  183513. ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
  183514. ** they omit all error checking and return a pointer to the requested value.
  183515. */
  183516. #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
  183517. #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
  183518. /*
  183519. ** This function may only be called with a changeset iterator that has been
  183520. ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
  183521. ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
  183522. **
  183523. ** If successful, *ppValue is set to point to an sqlite3_value structure
  183524. ** containing the iVal'th value of the conflicting record.
  183525. **
  183526. ** If value iVal is out-of-range or some other error occurs, an SQLite error
  183527. ** code is returned. Otherwise, SQLITE_OK.
  183528. */
  183529. SQLITE_API int sqlite3changeset_conflict(
  183530. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  183531. int iVal, /* Index of conflict record value to fetch */
  183532. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  183533. ){
  183534. if( !pIter->pConflict ){
  183535. return SQLITE_MISUSE;
  183536. }
  183537. if( iVal<0 || iVal>=pIter->nCol ){
  183538. return SQLITE_RANGE;
  183539. }
  183540. *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
  183541. return SQLITE_OK;
  183542. }
  183543. /*
  183544. ** This function may only be called with an iterator passed to an
  183545. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  183546. ** it sets the output variable to the total number of known foreign key
  183547. ** violations in the destination database and returns SQLITE_OK.
  183548. **
  183549. ** In all other cases this function returns SQLITE_MISUSE.
  183550. */
  183551. SQLITE_API int sqlite3changeset_fk_conflicts(
  183552. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  183553. int *pnOut /* OUT: Number of FK violations */
  183554. ){
  183555. if( pIter->pConflict || pIter->apValue ){
  183556. return SQLITE_MISUSE;
  183557. }
  183558. *pnOut = pIter->nCol;
  183559. return SQLITE_OK;
  183560. }
  183561. /*
  183562. ** Finalize an iterator allocated with sqlite3changeset_start().
  183563. **
  183564. ** This function may not be called on iterators passed to a conflict handler
  183565. ** callback by changeset_apply().
  183566. */
  183567. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
  183568. int rc = SQLITE_OK;
  183569. if( p ){
  183570. int i; /* Used to iterate through p->apValue[] */
  183571. rc = p->rc;
  183572. if( p->apValue ){
  183573. for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
  183574. }
  183575. sqlite3_free(p->tblhdr.aBuf);
  183576. sqlite3_free(p->in.buf.aBuf);
  183577. sqlite3_free(p);
  183578. }
  183579. return rc;
  183580. }
  183581. static int sessionChangesetInvert(
  183582. SessionInput *pInput, /* Input changeset */
  183583. int (*xOutput)(void *pOut, const void *pData, int nData),
  183584. void *pOut,
  183585. int *pnInverted, /* OUT: Number of bytes in output changeset */
  183586. void **ppInverted /* OUT: Inverse of pChangeset */
  183587. ){
  183588. int rc = SQLITE_OK; /* Return value */
  183589. SessionBuffer sOut; /* Output buffer */
  183590. int nCol = 0; /* Number of cols in current table */
  183591. u8 *abPK = 0; /* PK array for current table */
  183592. sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
  183593. SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
  183594. /* Initialize the output buffer */
  183595. memset(&sOut, 0, sizeof(SessionBuffer));
  183596. /* Zero the output variables in case an error occurs. */
  183597. if( ppInverted ){
  183598. *ppInverted = 0;
  183599. *pnInverted = 0;
  183600. }
  183601. while( 1 ){
  183602. u8 eType;
  183603. /* Test for EOF. */
  183604. if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
  183605. if( pInput->iNext>=pInput->nData ) break;
  183606. eType = pInput->aData[pInput->iNext];
  183607. switch( eType ){
  183608. case 'T': {
  183609. /* A 'table' record consists of:
  183610. **
  183611. ** * A constant 'T' character,
  183612. ** * Number of columns in said table (a varint),
  183613. ** * An array of nCol bytes (sPK),
  183614. ** * A nul-terminated table name.
  183615. */
  183616. int nByte;
  183617. int nVar;
  183618. pInput->iNext++;
  183619. if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
  183620. goto finished_invert;
  183621. }
  183622. nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
  183623. sPK.nBuf = 0;
  183624. sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
  183625. sessionAppendByte(&sOut, eType, &rc);
  183626. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  183627. if( rc ) goto finished_invert;
  183628. pInput->iNext += nByte;
  183629. sqlite3_free(apVal);
  183630. apVal = 0;
  183631. abPK = sPK.aBuf;
  183632. break;
  183633. }
  183634. case SQLITE_INSERT:
  183635. case SQLITE_DELETE: {
  183636. int nByte;
  183637. int bIndirect = pInput->aData[pInput->iNext+1];
  183638. int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
  183639. pInput->iNext += 2;
  183640. assert( rc==SQLITE_OK );
  183641. rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
  183642. sessionAppendByte(&sOut, eType2, &rc);
  183643. sessionAppendByte(&sOut, bIndirect, &rc);
  183644. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  183645. pInput->iNext += nByte;
  183646. if( rc ) goto finished_invert;
  183647. break;
  183648. }
  183649. case SQLITE_UPDATE: {
  183650. int iCol;
  183651. if( 0==apVal ){
  183652. apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
  183653. if( 0==apVal ){
  183654. rc = SQLITE_NOMEM;
  183655. goto finished_invert;
  183656. }
  183657. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  183658. }
  183659. /* Write the header for the new UPDATE change. Same as the original. */
  183660. sessionAppendByte(&sOut, eType, &rc);
  183661. sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
  183662. /* Read the old.* and new.* records for the update change. */
  183663. pInput->iNext += 2;
  183664. rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
  183665. if( rc==SQLITE_OK ){
  183666. rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
  183667. }
  183668. /* Write the new old.* record. Consists of the PK columns from the
  183669. ** original old.* record, and the other values from the original
  183670. ** new.* record. */
  183671. for(iCol=0; iCol<nCol; iCol++){
  183672. sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
  183673. sessionAppendValue(&sOut, pVal, &rc);
  183674. }
  183675. /* Write the new new.* record. Consists of a copy of all values
  183676. ** from the original old.* record, except for the PK columns, which
  183677. ** are set to "undefined". */
  183678. for(iCol=0; iCol<nCol; iCol++){
  183679. sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
  183680. sessionAppendValue(&sOut, pVal, &rc);
  183681. }
  183682. for(iCol=0; iCol<nCol*2; iCol++){
  183683. sqlite3ValueFree(apVal[iCol]);
  183684. }
  183685. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  183686. if( rc!=SQLITE_OK ){
  183687. goto finished_invert;
  183688. }
  183689. break;
  183690. }
  183691. default:
  183692. rc = SQLITE_CORRUPT_BKPT;
  183693. goto finished_invert;
  183694. }
  183695. assert( rc==SQLITE_OK );
  183696. if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){
  183697. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  183698. sOut.nBuf = 0;
  183699. if( rc!=SQLITE_OK ) goto finished_invert;
  183700. }
  183701. }
  183702. assert( rc==SQLITE_OK );
  183703. if( pnInverted ){
  183704. *pnInverted = sOut.nBuf;
  183705. *ppInverted = sOut.aBuf;
  183706. sOut.aBuf = 0;
  183707. }else if( sOut.nBuf>0 ){
  183708. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  183709. }
  183710. finished_invert:
  183711. sqlite3_free(sOut.aBuf);
  183712. sqlite3_free(apVal);
  183713. sqlite3_free(sPK.aBuf);
  183714. return rc;
  183715. }
  183716. /*
  183717. ** Invert a changeset object.
  183718. */
  183719. SQLITE_API int sqlite3changeset_invert(
  183720. int nChangeset, /* Number of bytes in input */
  183721. const void *pChangeset, /* Input changeset */
  183722. int *pnInverted, /* OUT: Number of bytes in output changeset */
  183723. void **ppInverted /* OUT: Inverse of pChangeset */
  183724. ){
  183725. SessionInput sInput;
  183726. /* Set up the input stream */
  183727. memset(&sInput, 0, sizeof(SessionInput));
  183728. sInput.nData = nChangeset;
  183729. sInput.aData = (u8*)pChangeset;
  183730. return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
  183731. }
  183732. /*
  183733. ** Streaming version of sqlite3changeset_invert().
  183734. */
  183735. SQLITE_API int sqlite3changeset_invert_strm(
  183736. int (*xInput)(void *pIn, void *pData, int *pnData),
  183737. void *pIn,
  183738. int (*xOutput)(void *pOut, const void *pData, int nData),
  183739. void *pOut
  183740. ){
  183741. SessionInput sInput;
  183742. int rc;
  183743. /* Set up the input stream */
  183744. memset(&sInput, 0, sizeof(SessionInput));
  183745. sInput.xInput = xInput;
  183746. sInput.pIn = pIn;
  183747. rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
  183748. sqlite3_free(sInput.buf.aBuf);
  183749. return rc;
  183750. }
  183751. typedef struct SessionApplyCtx SessionApplyCtx;
  183752. struct SessionApplyCtx {
  183753. sqlite3 *db;
  183754. sqlite3_stmt *pDelete; /* DELETE statement */
  183755. sqlite3_stmt *pUpdate; /* UPDATE statement */
  183756. sqlite3_stmt *pInsert; /* INSERT statement */
  183757. sqlite3_stmt *pSelect; /* SELECT statement */
  183758. int nCol; /* Size of azCol[] and abPK[] arrays */
  183759. const char **azCol; /* Array of column names */
  183760. u8 *abPK; /* Boolean array - true if column is in PK */
  183761. int bStat1; /* True if table is sqlite_stat1 */
  183762. int bDeferConstraints; /* True to defer constraints */
  183763. SessionBuffer constraints; /* Deferred constraints are stored here */
  183764. SessionBuffer rebase; /* Rebase information (if any) here */
  183765. u8 bRebaseStarted; /* If table header is already in rebase */
  183766. u8 bRebase; /* True to collect rebase information */
  183767. };
  183768. /*
  183769. ** Formulate a statement to DELETE a row from database db. Assuming a table
  183770. ** structure like this:
  183771. **
  183772. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  183773. **
  183774. ** The DELETE statement looks like this:
  183775. **
  183776. ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
  183777. **
  183778. ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
  183779. ** matching b and d values, or 1 otherwise. The second case comes up if the
  183780. ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
  183781. **
  183782. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
  183783. ** pointing to the prepared version of the SQL statement.
  183784. */
  183785. static int sessionDeleteRow(
  183786. sqlite3 *db, /* Database handle */
  183787. const char *zTab, /* Table name */
  183788. SessionApplyCtx *p /* Session changeset-apply context */
  183789. ){
  183790. int i;
  183791. const char *zSep = "";
  183792. int rc = SQLITE_OK;
  183793. SessionBuffer buf = {0, 0, 0};
  183794. int nPk = 0;
  183795. sessionAppendStr(&buf, "DELETE FROM ", &rc);
  183796. sessionAppendIdent(&buf, zTab, &rc);
  183797. sessionAppendStr(&buf, " WHERE ", &rc);
  183798. for(i=0; i<p->nCol; i++){
  183799. if( p->abPK[i] ){
  183800. nPk++;
  183801. sessionAppendStr(&buf, zSep, &rc);
  183802. sessionAppendIdent(&buf, p->azCol[i], &rc);
  183803. sessionAppendStr(&buf, " = ?", &rc);
  183804. sessionAppendInteger(&buf, i+1, &rc);
  183805. zSep = " AND ";
  183806. }
  183807. }
  183808. if( nPk<p->nCol ){
  183809. sessionAppendStr(&buf, " AND (?", &rc);
  183810. sessionAppendInteger(&buf, p->nCol+1, &rc);
  183811. sessionAppendStr(&buf, " OR ", &rc);
  183812. zSep = "";
  183813. for(i=0; i<p->nCol; i++){
  183814. if( !p->abPK[i] ){
  183815. sessionAppendStr(&buf, zSep, &rc);
  183816. sessionAppendIdent(&buf, p->azCol[i], &rc);
  183817. sessionAppendStr(&buf, " IS ?", &rc);
  183818. sessionAppendInteger(&buf, i+1, &rc);
  183819. zSep = "AND ";
  183820. }
  183821. }
  183822. sessionAppendStr(&buf, ")", &rc);
  183823. }
  183824. if( rc==SQLITE_OK ){
  183825. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
  183826. }
  183827. sqlite3_free(buf.aBuf);
  183828. return rc;
  183829. }
  183830. /*
  183831. ** Formulate and prepare a statement to UPDATE a row from database db.
  183832. ** Assuming a table structure like this:
  183833. **
  183834. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  183835. **
  183836. ** The UPDATE statement looks like this:
  183837. **
  183838. ** UPDATE x SET
  183839. ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
  183840. ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
  183841. ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
  183842. ** d = CASE WHEN ?11 THEN ?12 ELSE d END
  183843. ** WHERE a = ?1 AND c = ?7 AND (?13 OR
  183844. ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
  183845. ** )
  183846. **
  183847. ** For each column in the table, there are three variables to bind:
  183848. **
  183849. ** ?(i*3+1) The old.* value of the column, if any.
  183850. ** ?(i*3+2) A boolean flag indicating that the value is being modified.
  183851. ** ?(i*3+3) The new.* value of the column, if any.
  183852. **
  183853. ** Also, a boolean flag that, if set to true, causes the statement to update
  183854. ** a row even if the non-PK values do not match. This is required if the
  183855. ** conflict-handler is invoked with CHANGESET_DATA and returns
  183856. ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
  183857. **
  183858. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
  183859. ** pointing to the prepared version of the SQL statement.
  183860. */
  183861. static int sessionUpdateRow(
  183862. sqlite3 *db, /* Database handle */
  183863. const char *zTab, /* Table name */
  183864. SessionApplyCtx *p /* Session changeset-apply context */
  183865. ){
  183866. int rc = SQLITE_OK;
  183867. int i;
  183868. const char *zSep = "";
  183869. SessionBuffer buf = {0, 0, 0};
  183870. /* Append "UPDATE tbl SET " */
  183871. sessionAppendStr(&buf, "UPDATE ", &rc);
  183872. sessionAppendIdent(&buf, zTab, &rc);
  183873. sessionAppendStr(&buf, " SET ", &rc);
  183874. /* Append the assignments */
  183875. for(i=0; i<p->nCol; i++){
  183876. sessionAppendStr(&buf, zSep, &rc);
  183877. sessionAppendIdent(&buf, p->azCol[i], &rc);
  183878. sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
  183879. sessionAppendInteger(&buf, i*3+2, &rc);
  183880. sessionAppendStr(&buf, " THEN ?", &rc);
  183881. sessionAppendInteger(&buf, i*3+3, &rc);
  183882. sessionAppendStr(&buf, " ELSE ", &rc);
  183883. sessionAppendIdent(&buf, p->azCol[i], &rc);
  183884. sessionAppendStr(&buf, " END", &rc);
  183885. zSep = ", ";
  183886. }
  183887. /* Append the PK part of the WHERE clause */
  183888. sessionAppendStr(&buf, " WHERE ", &rc);
  183889. for(i=0; i<p->nCol; i++){
  183890. if( p->abPK[i] ){
  183891. sessionAppendIdent(&buf, p->azCol[i], &rc);
  183892. sessionAppendStr(&buf, " = ?", &rc);
  183893. sessionAppendInteger(&buf, i*3+1, &rc);
  183894. sessionAppendStr(&buf, " AND ", &rc);
  183895. }
  183896. }
  183897. /* Append the non-PK part of the WHERE clause */
  183898. sessionAppendStr(&buf, " (?", &rc);
  183899. sessionAppendInteger(&buf, p->nCol*3+1, &rc);
  183900. sessionAppendStr(&buf, " OR 1", &rc);
  183901. for(i=0; i<p->nCol; i++){
  183902. if( !p->abPK[i] ){
  183903. sessionAppendStr(&buf, " AND (?", &rc);
  183904. sessionAppendInteger(&buf, i*3+2, &rc);
  183905. sessionAppendStr(&buf, "=0 OR ", &rc);
  183906. sessionAppendIdent(&buf, p->azCol[i], &rc);
  183907. sessionAppendStr(&buf, " IS ?", &rc);
  183908. sessionAppendInteger(&buf, i*3+1, &rc);
  183909. sessionAppendStr(&buf, ")", &rc);
  183910. }
  183911. }
  183912. sessionAppendStr(&buf, ")", &rc);
  183913. if( rc==SQLITE_OK ){
  183914. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
  183915. }
  183916. sqlite3_free(buf.aBuf);
  183917. return rc;
  183918. }
  183919. /*
  183920. ** Formulate and prepare an SQL statement to query table zTab by primary
  183921. ** key. Assuming the following table structure:
  183922. **
  183923. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  183924. **
  183925. ** The SELECT statement looks like this:
  183926. **
  183927. ** SELECT * FROM x WHERE a = ?1 AND c = ?3
  183928. **
  183929. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
  183930. ** pointing to the prepared version of the SQL statement.
  183931. */
  183932. static int sessionSelectRow(
  183933. sqlite3 *db, /* Database handle */
  183934. const char *zTab, /* Table name */
  183935. SessionApplyCtx *p /* Session changeset-apply context */
  183936. ){
  183937. return sessionSelectStmt(
  183938. db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
  183939. }
  183940. /*
  183941. ** Formulate and prepare an INSERT statement to add a record to table zTab.
  183942. ** For example:
  183943. **
  183944. ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
  183945. **
  183946. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
  183947. ** pointing to the prepared version of the SQL statement.
  183948. */
  183949. static int sessionInsertRow(
  183950. sqlite3 *db, /* Database handle */
  183951. const char *zTab, /* Table name */
  183952. SessionApplyCtx *p /* Session changeset-apply context */
  183953. ){
  183954. int rc = SQLITE_OK;
  183955. int i;
  183956. SessionBuffer buf = {0, 0, 0};
  183957. sessionAppendStr(&buf, "INSERT INTO main.", &rc);
  183958. sessionAppendIdent(&buf, zTab, &rc);
  183959. sessionAppendStr(&buf, "(", &rc);
  183960. for(i=0; i<p->nCol; i++){
  183961. if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
  183962. sessionAppendIdent(&buf, p->azCol[i], &rc);
  183963. }
  183964. sessionAppendStr(&buf, ") VALUES(?", &rc);
  183965. for(i=1; i<p->nCol; i++){
  183966. sessionAppendStr(&buf, ", ?", &rc);
  183967. }
  183968. sessionAppendStr(&buf, ")", &rc);
  183969. if( rc==SQLITE_OK ){
  183970. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
  183971. }
  183972. sqlite3_free(buf.aBuf);
  183973. return rc;
  183974. }
  183975. static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
  183976. return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
  183977. }
  183978. /*
  183979. ** Prepare statements for applying changes to the sqlite_stat1 table.
  183980. ** These are similar to those created by sessionSelectRow(),
  183981. ** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
  183982. ** other tables.
  183983. */
  183984. static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
  183985. int rc = sessionSelectRow(db, "sqlite_stat1", p);
  183986. if( rc==SQLITE_OK ){
  183987. rc = sessionPrepare(db, &p->pInsert,
  183988. "INSERT INTO main.sqlite_stat1 VALUES(?1, "
  183989. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
  183990. "?3)"
  183991. );
  183992. }
  183993. if( rc==SQLITE_OK ){
  183994. rc = sessionPrepare(db, &p->pUpdate,
  183995. "UPDATE main.sqlite_stat1 SET "
  183996. "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, "
  183997. "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, "
  183998. "stat = CASE WHEN ?8 THEN ?9 ELSE stat END "
  183999. "WHERE tbl=?1 AND idx IS "
  184000. "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END "
  184001. "AND (?10 OR ?8=0 OR stat IS ?7)"
  184002. );
  184003. }
  184004. if( rc==SQLITE_OK ){
  184005. rc = sessionPrepare(db, &p->pDelete,
  184006. "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
  184007. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
  184008. "AND (?4 OR stat IS ?3)"
  184009. );
  184010. }
  184011. return rc;
  184012. }
  184013. /*
  184014. ** A wrapper around sqlite3_bind_value() that detects an extra problem.
  184015. ** See comments in the body of this function for details.
  184016. */
  184017. static int sessionBindValue(
  184018. sqlite3_stmt *pStmt, /* Statement to bind value to */
  184019. int i, /* Parameter number to bind to */
  184020. sqlite3_value *pVal /* Value to bind */
  184021. ){
  184022. int eType = sqlite3_value_type(pVal);
  184023. /* COVERAGE: The (pVal->z==0) branch is never true using current versions
  184024. ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
  184025. ** the (pVal->z) variable remains as it was or the type of the value is
  184026. ** set to SQLITE_NULL. */
  184027. if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
  184028. /* This condition occurs when an earlier OOM in a call to
  184029. ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
  184030. ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
  184031. return SQLITE_NOMEM;
  184032. }
  184033. return sqlite3_bind_value(pStmt, i, pVal);
  184034. }
  184035. /*
  184036. ** Iterator pIter must point to an SQLITE_INSERT entry. This function
  184037. ** transfers new.* values from the current iterator entry to statement
  184038. ** pStmt. The table being inserted into has nCol columns.
  184039. **
  184040. ** New.* value $i from the iterator is bound to variable ($i+1) of
  184041. ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
  184042. ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
  184043. ** to an array nCol elements in size. In this case only those values for
  184044. ** which abPK[$i] is true are read from the iterator and bound to the
  184045. ** statement.
  184046. **
  184047. ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
  184048. */
  184049. static int sessionBindRow(
  184050. sqlite3_changeset_iter *pIter, /* Iterator to read values from */
  184051. int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
  184052. int nCol, /* Number of columns */
  184053. u8 *abPK, /* If not NULL, bind only if true */
  184054. sqlite3_stmt *pStmt /* Bind values to this statement */
  184055. ){
  184056. int i;
  184057. int rc = SQLITE_OK;
  184058. /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
  184059. ** argument iterator points to a suitable entry. Make sure that xValue
  184060. ** is one of these to guarantee that it is safe to ignore the return
  184061. ** in the code below. */
  184062. assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
  184063. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  184064. if( !abPK || abPK[i] ){
  184065. sqlite3_value *pVal;
  184066. (void)xValue(pIter, i, &pVal);
  184067. if( pVal==0 ){
  184068. /* The value in the changeset was "undefined". This indicates a
  184069. ** corrupt changeset blob. */
  184070. rc = SQLITE_CORRUPT_BKPT;
  184071. }else{
  184072. rc = sessionBindValue(pStmt, i+1, pVal);
  184073. }
  184074. }
  184075. }
  184076. return rc;
  184077. }
  184078. /*
  184079. ** SQL statement pSelect is as generated by the sessionSelectRow() function.
  184080. ** This function binds the primary key values from the change that changeset
  184081. ** iterator pIter points to to the SELECT and attempts to seek to the table
  184082. ** entry. If a row is found, the SELECT statement left pointing at the row
  184083. ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
  184084. ** has occured, the statement is reset and SQLITE_OK is returned. If an
  184085. ** error occurs, the statement is reset and an SQLite error code is returned.
  184086. **
  184087. ** If this function returns SQLITE_ROW, the caller must eventually reset()
  184088. ** statement pSelect. If any other value is returned, the statement does
  184089. ** not require a reset().
  184090. **
  184091. ** If the iterator currently points to an INSERT record, bind values from the
  184092. ** new.* record to the SELECT statement. Or, if it points to a DELETE or
  184093. ** UPDATE, bind values from the old.* record.
  184094. */
  184095. static int sessionSeekToRow(
  184096. sqlite3 *db, /* Database handle */
  184097. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  184098. u8 *abPK, /* Primary key flags array */
  184099. sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
  184100. ){
  184101. int rc; /* Return code */
  184102. int nCol; /* Number of columns in table */
  184103. int op; /* Changset operation (SQLITE_UPDATE etc.) */
  184104. const char *zDummy; /* Unused */
  184105. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  184106. rc = sessionBindRow(pIter,
  184107. op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
  184108. nCol, abPK, pSelect
  184109. );
  184110. if( rc==SQLITE_OK ){
  184111. rc = sqlite3_step(pSelect);
  184112. if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
  184113. }
  184114. return rc;
  184115. }
  184116. /*
  184117. ** This function is called from within sqlite3changset_apply_v2() when
  184118. ** a conflict is encountered and resolved using conflict resolution
  184119. ** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
  184120. ** It adds a conflict resolution record to the buffer in
  184121. ** SessionApplyCtx.rebase, which will eventually be returned to the caller
  184122. ** of apply_v2() as the "rebase" buffer.
  184123. **
  184124. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  184125. */
  184126. static int sessionRebaseAdd(
  184127. SessionApplyCtx *p, /* Apply context */
  184128. int eType, /* Conflict resolution (OMIT or REPLACE) */
  184129. sqlite3_changeset_iter *pIter /* Iterator pointing at current change */
  184130. ){
  184131. int rc = SQLITE_OK;
  184132. if( p->bRebase ){
  184133. int i;
  184134. int eOp = pIter->op;
  184135. if( p->bRebaseStarted==0 ){
  184136. /* Append a table-header to the rebase buffer */
  184137. const char *zTab = pIter->zTab;
  184138. sessionAppendByte(&p->rebase, 'T', &rc);
  184139. sessionAppendVarint(&p->rebase, p->nCol, &rc);
  184140. sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);
  184141. sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);
  184142. p->bRebaseStarted = 1;
  184143. }
  184144. assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
  184145. assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
  184146. sessionAppendByte(&p->rebase,
  184147. (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
  184148. );
  184149. sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
  184150. for(i=0; i<p->nCol; i++){
  184151. sqlite3_value *pVal = 0;
  184152. if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){
  184153. sqlite3changeset_old(pIter, i, &pVal);
  184154. }else{
  184155. sqlite3changeset_new(pIter, i, &pVal);
  184156. }
  184157. sessionAppendValue(&p->rebase, pVal, &rc);
  184158. }
  184159. }
  184160. return rc;
  184161. }
  184162. /*
  184163. ** Invoke the conflict handler for the change that the changeset iterator
  184164. ** currently points to.
  184165. **
  184166. ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
  184167. ** If argument pbReplace is NULL, then the type of conflict handler invoked
  184168. ** depends solely on eType, as follows:
  184169. **
  184170. ** eType value Value passed to xConflict
  184171. ** -------------------------------------------------
  184172. ** CHANGESET_DATA CHANGESET_NOTFOUND
  184173. ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
  184174. **
  184175. ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
  184176. ** record with the same primary key as the record about to be deleted, updated
  184177. ** or inserted. If such a record can be found, it is available to the conflict
  184178. ** handler as the "conflicting" record. In this case the type of conflict
  184179. ** handler invoked is as follows:
  184180. **
  184181. ** eType value PK Record found? Value passed to xConflict
  184182. ** ----------------------------------------------------------------
  184183. ** CHANGESET_DATA Yes CHANGESET_DATA
  184184. ** CHANGESET_DATA No CHANGESET_NOTFOUND
  184185. ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
  184186. ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
  184187. **
  184188. ** If pbReplace is not NULL, and a record with a matching PK is found, and
  184189. ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
  184190. ** is set to non-zero before returning SQLITE_OK.
  184191. **
  184192. ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
  184193. ** returned. Or, if the conflict handler returns an invalid value,
  184194. ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
  184195. ** this function returns SQLITE_OK.
  184196. */
  184197. static int sessionConflictHandler(
  184198. int eType, /* Either CHANGESET_DATA or CONFLICT */
  184199. SessionApplyCtx *p, /* changeset_apply() context */
  184200. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  184201. int(*xConflict)(void *, int, sqlite3_changeset_iter*),
  184202. void *pCtx, /* First argument for conflict handler */
  184203. int *pbReplace /* OUT: Set to true if PK row is found */
  184204. ){
  184205. int res = 0; /* Value returned by conflict handler */
  184206. int rc;
  184207. int nCol;
  184208. int op;
  184209. const char *zDummy;
  184210. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  184211. assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
  184212. assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
  184213. assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
  184214. /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
  184215. if( pbReplace ){
  184216. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  184217. }else{
  184218. rc = SQLITE_OK;
  184219. }
  184220. if( rc==SQLITE_ROW ){
  184221. /* There exists another row with the new.* primary key. */
  184222. pIter->pConflict = p->pSelect;
  184223. res = xConflict(pCtx, eType, pIter);
  184224. pIter->pConflict = 0;
  184225. rc = sqlite3_reset(p->pSelect);
  184226. }else if( rc==SQLITE_OK ){
  184227. if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
  184228. /* Instead of invoking the conflict handler, append the change blob
  184229. ** to the SessionApplyCtx.constraints buffer. */
  184230. u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
  184231. int nBlob = pIter->in.iNext - pIter->in.iCurrent;
  184232. sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
  184233. return SQLITE_OK;
  184234. }else{
  184235. /* No other row with the new.* primary key. */
  184236. res = xConflict(pCtx, eType+1, pIter);
  184237. if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
  184238. }
  184239. }
  184240. if( rc==SQLITE_OK ){
  184241. switch( res ){
  184242. case SQLITE_CHANGESET_REPLACE:
  184243. assert( pbReplace );
  184244. *pbReplace = 1;
  184245. break;
  184246. case SQLITE_CHANGESET_OMIT:
  184247. break;
  184248. case SQLITE_CHANGESET_ABORT:
  184249. rc = SQLITE_ABORT;
  184250. break;
  184251. default:
  184252. rc = SQLITE_MISUSE;
  184253. break;
  184254. }
  184255. if( rc==SQLITE_OK ){
  184256. rc = sessionRebaseAdd(p, res, pIter);
  184257. }
  184258. }
  184259. return rc;
  184260. }
  184261. /*
  184262. ** Attempt to apply the change that the iterator passed as the first argument
  184263. ** currently points to to the database. If a conflict is encountered, invoke
  184264. ** the conflict handler callback.
  184265. **
  184266. ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
  184267. ** one is encountered, update or delete the row with the matching primary key
  184268. ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
  184269. ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
  184270. ** to true before returning. In this case the caller will invoke this function
  184271. ** again, this time with pbRetry set to NULL.
  184272. **
  184273. ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
  184274. ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
  184275. ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
  184276. ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
  184277. ** before retrying. In this case the caller attempts to remove the conflicting
  184278. ** row before invoking this function again, this time with pbReplace set
  184279. ** to NULL.
  184280. **
  184281. ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
  184282. ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
  184283. ** returned.
  184284. */
  184285. static int sessionApplyOneOp(
  184286. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  184287. SessionApplyCtx *p, /* changeset_apply() context */
  184288. int(*xConflict)(void *, int, sqlite3_changeset_iter *),
  184289. void *pCtx, /* First argument for the conflict handler */
  184290. int *pbReplace, /* OUT: True to remove PK row and retry */
  184291. int *pbRetry /* OUT: True to retry. */
  184292. ){
  184293. const char *zDummy;
  184294. int op;
  184295. int nCol;
  184296. int rc = SQLITE_OK;
  184297. assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
  184298. assert( p->azCol && p->abPK );
  184299. assert( !pbReplace || *pbReplace==0 );
  184300. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  184301. if( op==SQLITE_DELETE ){
  184302. /* Bind values to the DELETE statement. If conflict handling is required,
  184303. ** bind values for all columns and set bound variable (nCol+1) to true.
  184304. ** Or, if conflict handling is not required, bind just the PK column
  184305. ** values and, if it exists, set (nCol+1) to false. Conflict handling
  184306. ** is not required if:
  184307. **
  184308. ** * this is a patchset, or
  184309. ** * (pbRetry==0), or
  184310. ** * all columns of the table are PK columns (in this case there is
  184311. ** no (nCol+1) variable to bind to).
  184312. */
  184313. u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
  184314. rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
  184315. if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
  184316. rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
  184317. }
  184318. if( rc!=SQLITE_OK ) return rc;
  184319. sqlite3_step(p->pDelete);
  184320. rc = sqlite3_reset(p->pDelete);
  184321. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  184322. rc = sessionConflictHandler(
  184323. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  184324. );
  184325. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  184326. rc = sessionConflictHandler(
  184327. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  184328. );
  184329. }
  184330. }else if( op==SQLITE_UPDATE ){
  184331. int i;
  184332. /* Bind values to the UPDATE statement. */
  184333. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  184334. sqlite3_value *pOld = sessionChangesetOld(pIter, i);
  184335. sqlite3_value *pNew = sessionChangesetNew(pIter, i);
  184336. sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
  184337. if( pOld ){
  184338. rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
  184339. }
  184340. if( rc==SQLITE_OK && pNew ){
  184341. rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
  184342. }
  184343. }
  184344. if( rc==SQLITE_OK ){
  184345. sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
  184346. }
  184347. if( rc!=SQLITE_OK ) return rc;
  184348. /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
  184349. ** the result will be SQLITE_OK with 0 rows modified. */
  184350. sqlite3_step(p->pUpdate);
  184351. rc = sqlite3_reset(p->pUpdate);
  184352. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  184353. /* A NOTFOUND or DATA error. Search the table to see if it contains
  184354. ** a row with a matching primary key. If so, this is a DATA conflict.
  184355. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
  184356. rc = sessionConflictHandler(
  184357. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  184358. );
  184359. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  184360. /* This is always a CONSTRAINT conflict. */
  184361. rc = sessionConflictHandler(
  184362. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  184363. );
  184364. }
  184365. }else{
  184366. assert( op==SQLITE_INSERT );
  184367. if( p->bStat1 ){
  184368. /* Check if there is a conflicting row. For sqlite_stat1, this needs
  184369. ** to be done using a SELECT, as there is no PRIMARY KEY in the
  184370. ** database schema to throw an exception if a duplicate is inserted. */
  184371. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  184372. if( rc==SQLITE_ROW ){
  184373. rc = SQLITE_CONSTRAINT;
  184374. sqlite3_reset(p->pSelect);
  184375. }
  184376. }
  184377. if( rc==SQLITE_OK ){
  184378. rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
  184379. if( rc!=SQLITE_OK ) return rc;
  184380. sqlite3_step(p->pInsert);
  184381. rc = sqlite3_reset(p->pInsert);
  184382. }
  184383. if( (rc&0xff)==SQLITE_CONSTRAINT ){
  184384. rc = sessionConflictHandler(
  184385. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
  184386. );
  184387. }
  184388. }
  184389. return rc;
  184390. }
  184391. /*
  184392. ** Attempt to apply the change that the iterator passed as the first argument
  184393. ** currently points to to the database. If a conflict is encountered, invoke
  184394. ** the conflict handler callback.
  184395. **
  184396. ** The difference between this function and sessionApplyOne() is that this
  184397. ** function handles the case where the conflict-handler is invoked and
  184398. ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
  184399. ** retried in some manner.
  184400. */
  184401. static int sessionApplyOneWithRetry(
  184402. sqlite3 *db, /* Apply change to "main" db of this handle */
  184403. sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
  184404. SessionApplyCtx *pApply, /* Apply context */
  184405. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  184406. void *pCtx /* First argument passed to xConflict */
  184407. ){
  184408. int bReplace = 0;
  184409. int bRetry = 0;
  184410. int rc;
  184411. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
  184412. if( rc==SQLITE_OK ){
  184413. /* If the bRetry flag is set, the change has not been applied due to an
  184414. ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
  184415. ** a row with the correct PK is present in the db, but one or more other
  184416. ** fields do not contain the expected values) and the conflict handler
  184417. ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
  184418. ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
  184419. ** the SQLITE_CHANGESET_DATA problem. */
  184420. if( bRetry ){
  184421. assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
  184422. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  184423. }
  184424. /* If the bReplace flag is set, the change is an INSERT that has not
  184425. ** been performed because the database already contains a row with the
  184426. ** specified primary key and the conflict handler returned
  184427. ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
  184428. ** before reattempting the INSERT. */
  184429. else if( bReplace ){
  184430. assert( pIter->op==SQLITE_INSERT );
  184431. rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
  184432. if( rc==SQLITE_OK ){
  184433. rc = sessionBindRow(pIter,
  184434. sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
  184435. sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
  184436. }
  184437. if( rc==SQLITE_OK ){
  184438. sqlite3_step(pApply->pDelete);
  184439. rc = sqlite3_reset(pApply->pDelete);
  184440. }
  184441. if( rc==SQLITE_OK ){
  184442. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  184443. }
  184444. if( rc==SQLITE_OK ){
  184445. rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
  184446. }
  184447. }
  184448. }
  184449. return rc;
  184450. }
  184451. /*
  184452. ** Retry the changes accumulated in the pApply->constraints buffer.
  184453. */
  184454. static int sessionRetryConstraints(
  184455. sqlite3 *db,
  184456. int bPatchset,
  184457. const char *zTab,
  184458. SessionApplyCtx *pApply,
  184459. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  184460. void *pCtx /* First argument passed to xConflict */
  184461. ){
  184462. int rc = SQLITE_OK;
  184463. while( pApply->constraints.nBuf ){
  184464. sqlite3_changeset_iter *pIter2 = 0;
  184465. SessionBuffer cons = pApply->constraints;
  184466. memset(&pApply->constraints, 0, sizeof(SessionBuffer));
  184467. rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf, 0);
  184468. if( rc==SQLITE_OK ){
  184469. int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
  184470. int rc2;
  184471. pIter2->bPatchset = bPatchset;
  184472. pIter2->zTab = (char*)zTab;
  184473. pIter2->nCol = pApply->nCol;
  184474. pIter2->abPK = pApply->abPK;
  184475. sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
  184476. pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
  184477. if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
  184478. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
  184479. rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
  184480. }
  184481. rc2 = sqlite3changeset_finalize(pIter2);
  184482. if( rc==SQLITE_OK ) rc = rc2;
  184483. }
  184484. assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
  184485. sqlite3_free(cons.aBuf);
  184486. if( rc!=SQLITE_OK ) break;
  184487. if( pApply->constraints.nBuf>=cons.nBuf ){
  184488. /* No progress was made on the last round. */
  184489. pApply->bDeferConstraints = 0;
  184490. }
  184491. }
  184492. return rc;
  184493. }
  184494. /*
  184495. ** Argument pIter is a changeset iterator that has been initialized, but
  184496. ** not yet passed to sqlite3changeset_next(). This function applies the
  184497. ** changeset to the main database attached to handle "db". The supplied
  184498. ** conflict handler callback is invoked to resolve any conflicts encountered
  184499. ** while applying the change.
  184500. */
  184501. static int sessionChangesetApply(
  184502. sqlite3 *db, /* Apply change to "main" db of this handle */
  184503. sqlite3_changeset_iter *pIter, /* Changeset to apply */
  184504. int(*xFilter)(
  184505. void *pCtx, /* Copy of sixth arg to _apply() */
  184506. const char *zTab /* Table name */
  184507. ),
  184508. int(*xConflict)(
  184509. void *pCtx, /* Copy of fifth arg to _apply() */
  184510. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  184511. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  184512. ),
  184513. void *pCtx, /* First argument passed to xConflict */
  184514. void **ppRebase, int *pnRebase, /* OUT: Rebase information */
  184515. int flags /* SESSION_APPLY_XXX flags */
  184516. ){
  184517. int schemaMismatch = 0;
  184518. int rc = SQLITE_OK; /* Return code */
  184519. const char *zTab = 0; /* Name of current table */
  184520. int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
  184521. SessionApplyCtx sApply; /* changeset_apply() context object */
  184522. int bPatchset;
  184523. assert( xConflict!=0 );
  184524. pIter->in.bNoDiscard = 1;
  184525. memset(&sApply, 0, sizeof(sApply));
  184526. sApply.bRebase = (ppRebase && pnRebase);
  184527. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  184528. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  184529. rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  184530. }
  184531. if( rc==SQLITE_OK ){
  184532. rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
  184533. }
  184534. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
  184535. int nCol;
  184536. int op;
  184537. const char *zNew;
  184538. sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
  184539. if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
  184540. u8 *abPK;
  184541. rc = sessionRetryConstraints(
  184542. db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
  184543. );
  184544. if( rc!=SQLITE_OK ) break;
  184545. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  184546. sqlite3_finalize(sApply.pDelete);
  184547. sqlite3_finalize(sApply.pUpdate);
  184548. sqlite3_finalize(sApply.pInsert);
  184549. sqlite3_finalize(sApply.pSelect);
  184550. sApply.db = db;
  184551. sApply.pDelete = 0;
  184552. sApply.pUpdate = 0;
  184553. sApply.pInsert = 0;
  184554. sApply.pSelect = 0;
  184555. sApply.nCol = 0;
  184556. sApply.azCol = 0;
  184557. sApply.abPK = 0;
  184558. sApply.bStat1 = 0;
  184559. sApply.bDeferConstraints = 1;
  184560. sApply.bRebaseStarted = 0;
  184561. memset(&sApply.constraints, 0, sizeof(SessionBuffer));
  184562. /* If an xFilter() callback was specified, invoke it now. If the
  184563. ** xFilter callback returns zero, skip this table. If it returns
  184564. ** non-zero, proceed. */
  184565. schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
  184566. if( schemaMismatch ){
  184567. zTab = sqlite3_mprintf("%s", zNew);
  184568. if( zTab==0 ){
  184569. rc = SQLITE_NOMEM;
  184570. break;
  184571. }
  184572. nTab = (int)strlen(zTab);
  184573. sApply.azCol = (const char **)zTab;
  184574. }else{
  184575. int nMinCol = 0;
  184576. int i;
  184577. sqlite3changeset_pk(pIter, &abPK, 0);
  184578. rc = sessionTableInfo(
  184579. db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
  184580. );
  184581. if( rc!=SQLITE_OK ) break;
  184582. for(i=0; i<sApply.nCol; i++){
  184583. if( sApply.abPK[i] ) nMinCol = i+1;
  184584. }
  184585. if( sApply.nCol==0 ){
  184586. schemaMismatch = 1;
  184587. sqlite3_log(SQLITE_SCHEMA,
  184588. "sqlite3changeset_apply(): no such table: %s", zTab
  184589. );
  184590. }
  184591. else if( sApply.nCol<nCol ){
  184592. schemaMismatch = 1;
  184593. sqlite3_log(SQLITE_SCHEMA,
  184594. "sqlite3changeset_apply(): table %s has %d columns, "
  184595. "expected %d or more",
  184596. zTab, sApply.nCol, nCol
  184597. );
  184598. }
  184599. else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
  184600. schemaMismatch = 1;
  184601. sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
  184602. "primary key mismatch for table %s", zTab
  184603. );
  184604. }
  184605. else{
  184606. sApply.nCol = nCol;
  184607. if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
  184608. if( (rc = sessionStat1Sql(db, &sApply) ) ){
  184609. break;
  184610. }
  184611. sApply.bStat1 = 1;
  184612. }else{
  184613. if((rc = sessionSelectRow(db, zTab, &sApply))
  184614. || (rc = sessionUpdateRow(db, zTab, &sApply))
  184615. || (rc = sessionDeleteRow(db, zTab, &sApply))
  184616. || (rc = sessionInsertRow(db, zTab, &sApply))
  184617. ){
  184618. break;
  184619. }
  184620. sApply.bStat1 = 0;
  184621. }
  184622. }
  184623. nTab = sqlite3Strlen30(zTab);
  184624. }
  184625. }
  184626. /* If there is a schema mismatch on the current table, proceed to the
  184627. ** next change. A log message has already been issued. */
  184628. if( schemaMismatch ) continue;
  184629. rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
  184630. }
  184631. bPatchset = pIter->bPatchset;
  184632. if( rc==SQLITE_OK ){
  184633. rc = sqlite3changeset_finalize(pIter);
  184634. }else{
  184635. sqlite3changeset_finalize(pIter);
  184636. }
  184637. if( rc==SQLITE_OK ){
  184638. rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
  184639. }
  184640. if( rc==SQLITE_OK ){
  184641. int nFk, notUsed;
  184642. sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
  184643. if( nFk!=0 ){
  184644. int res = SQLITE_CHANGESET_ABORT;
  184645. sqlite3_changeset_iter sIter;
  184646. memset(&sIter, 0, sizeof(sIter));
  184647. sIter.nCol = nFk;
  184648. res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
  184649. if( res!=SQLITE_CHANGESET_OMIT ){
  184650. rc = SQLITE_CONSTRAINT;
  184651. }
  184652. }
  184653. }
  184654. sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
  184655. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  184656. if( rc==SQLITE_OK ){
  184657. rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  184658. }else{
  184659. sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
  184660. sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  184661. }
  184662. }
  184663. assert( sApply.bRebase || sApply.rebase.nBuf==0 );
  184664. if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){
  184665. *ppRebase = (void*)sApply.rebase.aBuf;
  184666. *pnRebase = sApply.rebase.nBuf;
  184667. sApply.rebase.aBuf = 0;
  184668. }
  184669. sqlite3_finalize(sApply.pInsert);
  184670. sqlite3_finalize(sApply.pDelete);
  184671. sqlite3_finalize(sApply.pUpdate);
  184672. sqlite3_finalize(sApply.pSelect);
  184673. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  184674. sqlite3_free((char*)sApply.constraints.aBuf);
  184675. sqlite3_free((char*)sApply.rebase.aBuf);
  184676. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  184677. return rc;
  184678. }
  184679. /*
  184680. ** Apply the changeset passed via pChangeset/nChangeset to the main
  184681. ** database attached to handle "db".
  184682. */
  184683. SQLITE_API int sqlite3changeset_apply_v2(
  184684. sqlite3 *db, /* Apply change to "main" db of this handle */
  184685. int nChangeset, /* Size of changeset in bytes */
  184686. void *pChangeset, /* Changeset blob */
  184687. int(*xFilter)(
  184688. void *pCtx, /* Copy of sixth arg to _apply() */
  184689. const char *zTab /* Table name */
  184690. ),
  184691. int(*xConflict)(
  184692. void *pCtx, /* Copy of sixth arg to _apply() */
  184693. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  184694. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  184695. ),
  184696. void *pCtx, /* First argument passed to xConflict */
  184697. void **ppRebase, int *pnRebase,
  184698. int flags
  184699. ){
  184700. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  184701. int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
  184702. int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset,bInverse);
  184703. if( rc==SQLITE_OK ){
  184704. rc = sessionChangesetApply(
  184705. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  184706. );
  184707. }
  184708. return rc;
  184709. }
  184710. /*
  184711. ** Apply the changeset passed via pChangeset/nChangeset to the main database
  184712. ** attached to handle "db". Invoke the supplied conflict handler callback
  184713. ** to resolve any conflicts encountered while applying the change.
  184714. */
  184715. SQLITE_API int sqlite3changeset_apply(
  184716. sqlite3 *db, /* Apply change to "main" db of this handle */
  184717. int nChangeset, /* Size of changeset in bytes */
  184718. void *pChangeset, /* Changeset blob */
  184719. int(*xFilter)(
  184720. void *pCtx, /* Copy of sixth arg to _apply() */
  184721. const char *zTab /* Table name */
  184722. ),
  184723. int(*xConflict)(
  184724. void *pCtx, /* Copy of fifth arg to _apply() */
  184725. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  184726. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  184727. ),
  184728. void *pCtx /* First argument passed to xConflict */
  184729. ){
  184730. return sqlite3changeset_apply_v2(
  184731. db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0
  184732. );
  184733. }
  184734. /*
  184735. ** Apply the changeset passed via xInput/pIn to the main database
  184736. ** attached to handle "db". Invoke the supplied conflict handler callback
  184737. ** to resolve any conflicts encountered while applying the change.
  184738. */
  184739. SQLITE_API int sqlite3changeset_apply_v2_strm(
  184740. sqlite3 *db, /* Apply change to "main" db of this handle */
  184741. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  184742. void *pIn, /* First arg for xInput */
  184743. int(*xFilter)(
  184744. void *pCtx, /* Copy of sixth arg to _apply() */
  184745. const char *zTab /* Table name */
  184746. ),
  184747. int(*xConflict)(
  184748. void *pCtx, /* Copy of sixth arg to _apply() */
  184749. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  184750. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  184751. ),
  184752. void *pCtx, /* First argument passed to xConflict */
  184753. void **ppRebase, int *pnRebase,
  184754. int flags
  184755. ){
  184756. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  184757. int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
  184758. int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse);
  184759. if( rc==SQLITE_OK ){
  184760. rc = sessionChangesetApply(
  184761. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  184762. );
  184763. }
  184764. return rc;
  184765. }
  184766. SQLITE_API int sqlite3changeset_apply_strm(
  184767. sqlite3 *db, /* Apply change to "main" db of this handle */
  184768. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  184769. void *pIn, /* First arg for xInput */
  184770. int(*xFilter)(
  184771. void *pCtx, /* Copy of sixth arg to _apply() */
  184772. const char *zTab /* Table name */
  184773. ),
  184774. int(*xConflict)(
  184775. void *pCtx, /* Copy of sixth arg to _apply() */
  184776. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  184777. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  184778. ),
  184779. void *pCtx /* First argument passed to xConflict */
  184780. ){
  184781. return sqlite3changeset_apply_v2_strm(
  184782. db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0
  184783. );
  184784. }
  184785. /*
  184786. ** sqlite3_changegroup handle.
  184787. */
  184788. struct sqlite3_changegroup {
  184789. int rc; /* Error code */
  184790. int bPatch; /* True to accumulate patchsets */
  184791. SessionTable *pList; /* List of tables in current patch */
  184792. };
  184793. /*
  184794. ** This function is called to merge two changes to the same row together as
  184795. ** part of an sqlite3changeset_concat() operation. A new change object is
  184796. ** allocated and a pointer to it stored in *ppNew.
  184797. */
  184798. static int sessionChangeMerge(
  184799. SessionTable *pTab, /* Table structure */
  184800. int bRebase, /* True for a rebase hash-table */
  184801. int bPatchset, /* True for patchsets */
  184802. SessionChange *pExist, /* Existing change */
  184803. int op2, /* Second change operation */
  184804. int bIndirect, /* True if second change is indirect */
  184805. u8 *aRec, /* Second change record */
  184806. int nRec, /* Number of bytes in aRec */
  184807. SessionChange **ppNew /* OUT: Merged change */
  184808. ){
  184809. SessionChange *pNew = 0;
  184810. int rc = SQLITE_OK;
  184811. if( !pExist ){
  184812. pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
  184813. if( !pNew ){
  184814. return SQLITE_NOMEM;
  184815. }
  184816. memset(pNew, 0, sizeof(SessionChange));
  184817. pNew->op = op2;
  184818. pNew->bIndirect = bIndirect;
  184819. pNew->aRecord = (u8*)&pNew[1];
  184820. if( bIndirect==0 || bRebase==0 ){
  184821. pNew->nRecord = nRec;
  184822. memcpy(pNew->aRecord, aRec, nRec);
  184823. }else{
  184824. int i;
  184825. u8 *pIn = aRec;
  184826. u8 *pOut = pNew->aRecord;
  184827. for(i=0; i<pTab->nCol; i++){
  184828. int nIn = sessionSerialLen(pIn);
  184829. if( *pIn==0 ){
  184830. *pOut++ = 0;
  184831. }else if( pTab->abPK[i]==0 ){
  184832. *pOut++ = 0xFF;
  184833. }else{
  184834. memcpy(pOut, pIn, nIn);
  184835. pOut += nIn;
  184836. }
  184837. pIn += nIn;
  184838. }
  184839. pNew->nRecord = pOut - pNew->aRecord;
  184840. }
  184841. }else if( bRebase ){
  184842. if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){
  184843. *ppNew = pExist;
  184844. }else{
  184845. int nByte = nRec + pExist->nRecord + sizeof(SessionChange);
  184846. pNew = (SessionChange*)sqlite3_malloc(nByte);
  184847. if( pNew==0 ){
  184848. rc = SQLITE_NOMEM;
  184849. }else{
  184850. int i;
  184851. u8 *a1 = pExist->aRecord;
  184852. u8 *a2 = aRec;
  184853. u8 *pOut;
  184854. memset(pNew, 0, nByte);
  184855. pNew->bIndirect = bIndirect || pExist->bIndirect;
  184856. pNew->op = op2;
  184857. pOut = pNew->aRecord = (u8*)&pNew[1];
  184858. for(i=0; i<pTab->nCol; i++){
  184859. int n1 = sessionSerialLen(a1);
  184860. int n2 = sessionSerialLen(a2);
  184861. if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){
  184862. *pOut++ = 0xFF;
  184863. }else if( *a2==0 ){
  184864. memcpy(pOut, a1, n1);
  184865. pOut += n1;
  184866. }else{
  184867. memcpy(pOut, a2, n2);
  184868. pOut += n2;
  184869. }
  184870. a1 += n1;
  184871. a2 += n2;
  184872. }
  184873. pNew->nRecord = pOut - pNew->aRecord;
  184874. }
  184875. sqlite3_free(pExist);
  184876. }
  184877. }else{
  184878. int op1 = pExist->op;
  184879. /*
  184880. ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
  184881. ** op1=INSERT, op2=UPDATE -> INSERT.
  184882. ** op1=INSERT, op2=DELETE -> (none)
  184883. **
  184884. ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
  184885. ** op1=UPDATE, op2=UPDATE -> UPDATE.
  184886. ** op1=UPDATE, op2=DELETE -> DELETE.
  184887. **
  184888. ** op1=DELETE, op2=INSERT -> UPDATE.
  184889. ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
  184890. ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
  184891. */
  184892. if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
  184893. || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
  184894. || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
  184895. || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
  184896. ){
  184897. pNew = pExist;
  184898. }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
  184899. sqlite3_free(pExist);
  184900. assert( pNew==0 );
  184901. }else{
  184902. u8 *aExist = pExist->aRecord;
  184903. int nByte;
  184904. u8 *aCsr;
  184905. /* Allocate a new SessionChange object. Ensure that the aRecord[]
  184906. ** buffer of the new object is large enough to hold any record that
  184907. ** may be generated by combining the input records. */
  184908. nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
  184909. pNew = (SessionChange *)sqlite3_malloc(nByte);
  184910. if( !pNew ){
  184911. sqlite3_free(pExist);
  184912. return SQLITE_NOMEM;
  184913. }
  184914. memset(pNew, 0, sizeof(SessionChange));
  184915. pNew->bIndirect = (bIndirect && pExist->bIndirect);
  184916. aCsr = pNew->aRecord = (u8 *)&pNew[1];
  184917. if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
  184918. u8 *a1 = aRec;
  184919. assert( op2==SQLITE_UPDATE );
  184920. pNew->op = SQLITE_INSERT;
  184921. if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
  184922. sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
  184923. }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
  184924. assert( op2==SQLITE_INSERT );
  184925. pNew->op = SQLITE_UPDATE;
  184926. if( bPatchset ){
  184927. memcpy(aCsr, aRec, nRec);
  184928. aCsr += nRec;
  184929. }else{
  184930. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
  184931. sqlite3_free(pNew);
  184932. pNew = 0;
  184933. }
  184934. }
  184935. }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
  184936. u8 *a1 = aExist;
  184937. u8 *a2 = aRec;
  184938. assert( op1==SQLITE_UPDATE );
  184939. if( bPatchset==0 ){
  184940. sessionSkipRecord(&a1, pTab->nCol);
  184941. sessionSkipRecord(&a2, pTab->nCol);
  184942. }
  184943. pNew->op = SQLITE_UPDATE;
  184944. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
  184945. sqlite3_free(pNew);
  184946. pNew = 0;
  184947. }
  184948. }else{ /* UPDATE + DELETE */
  184949. assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
  184950. pNew->op = SQLITE_DELETE;
  184951. if( bPatchset ){
  184952. memcpy(aCsr, aRec, nRec);
  184953. aCsr += nRec;
  184954. }else{
  184955. sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
  184956. }
  184957. }
  184958. if( pNew ){
  184959. pNew->nRecord = (int)(aCsr - pNew->aRecord);
  184960. }
  184961. sqlite3_free(pExist);
  184962. }
  184963. }
  184964. *ppNew = pNew;
  184965. return rc;
  184966. }
  184967. /*
  184968. ** Add all changes in the changeset traversed by the iterator passed as
  184969. ** the first argument to the changegroup hash tables.
  184970. */
  184971. static int sessionChangesetToHash(
  184972. sqlite3_changeset_iter *pIter, /* Iterator to read from */
  184973. sqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */
  184974. int bRebase /* True if hash table is for rebasing */
  184975. ){
  184976. u8 *aRec;
  184977. int nRec;
  184978. int rc = SQLITE_OK;
  184979. SessionTable *pTab = 0;
  184980. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){
  184981. const char *zNew;
  184982. int nCol;
  184983. int op;
  184984. int iHash;
  184985. int bIndirect;
  184986. SessionChange *pChange;
  184987. SessionChange *pExist = 0;
  184988. SessionChange **pp;
  184989. if( pGrp->pList==0 ){
  184990. pGrp->bPatch = pIter->bPatchset;
  184991. }else if( pIter->bPatchset!=pGrp->bPatch ){
  184992. rc = SQLITE_ERROR;
  184993. break;
  184994. }
  184995. sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
  184996. if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
  184997. /* Search the list for a matching table */
  184998. int nNew = (int)strlen(zNew);
  184999. u8 *abPK;
  185000. sqlite3changeset_pk(pIter, &abPK, 0);
  185001. for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
  185002. if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
  185003. }
  185004. if( !pTab ){
  185005. SessionTable **ppTab;
  185006. pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
  185007. if( !pTab ){
  185008. rc = SQLITE_NOMEM;
  185009. break;
  185010. }
  185011. memset(pTab, 0, sizeof(SessionTable));
  185012. pTab->nCol = nCol;
  185013. pTab->abPK = (u8*)&pTab[1];
  185014. memcpy(pTab->abPK, abPK, nCol);
  185015. pTab->zName = (char*)&pTab->abPK[nCol];
  185016. memcpy(pTab->zName, zNew, nNew+1);
  185017. /* The new object must be linked on to the end of the list, not
  185018. ** simply added to the start of it. This is to ensure that the
  185019. ** tables within the output of sqlite3changegroup_output() are in
  185020. ** the right order. */
  185021. for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
  185022. *ppTab = pTab;
  185023. }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
  185024. rc = SQLITE_SCHEMA;
  185025. break;
  185026. }
  185027. }
  185028. if( sessionGrowHash(pIter->bPatchset, pTab) ){
  185029. rc = SQLITE_NOMEM;
  185030. break;
  185031. }
  185032. iHash = sessionChangeHash(
  185033. pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
  185034. );
  185035. /* Search for existing entry. If found, remove it from the hash table.
  185036. ** Code below may link it back in.
  185037. */
  185038. for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
  185039. int bPkOnly1 = 0;
  185040. int bPkOnly2 = 0;
  185041. if( pIter->bPatchset ){
  185042. bPkOnly1 = (*pp)->op==SQLITE_DELETE;
  185043. bPkOnly2 = op==SQLITE_DELETE;
  185044. }
  185045. if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
  185046. pExist = *pp;
  185047. *pp = (*pp)->pNext;
  185048. pTab->nEntry--;
  185049. break;
  185050. }
  185051. }
  185052. rc = sessionChangeMerge(pTab, bRebase,
  185053. pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
  185054. );
  185055. if( rc ) break;
  185056. if( pChange ){
  185057. pChange->pNext = pTab->apChange[iHash];
  185058. pTab->apChange[iHash] = pChange;
  185059. pTab->nEntry++;
  185060. }
  185061. }
  185062. if( rc==SQLITE_OK ) rc = pIter->rc;
  185063. return rc;
  185064. }
  185065. /*
  185066. ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
  185067. ** added to the changegroup object passed as the first argument.
  185068. **
  185069. ** If xOutput is not NULL, then the changeset/patchset is returned to the
  185070. ** user via one or more calls to xOutput, as with the other streaming
  185071. ** interfaces.
  185072. **
  185073. ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
  185074. ** buffer containing the output changeset before this function returns. In
  185075. ** this case (*pnOut) is set to the size of the output buffer in bytes. It
  185076. ** is the responsibility of the caller to free the output buffer using
  185077. ** sqlite3_free() when it is no longer required.
  185078. **
  185079. ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
  185080. ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
  185081. ** are both set to 0 before returning.
  185082. */
  185083. static int sessionChangegroupOutput(
  185084. sqlite3_changegroup *pGrp,
  185085. int (*xOutput)(void *pOut, const void *pData, int nData),
  185086. void *pOut,
  185087. int *pnOut,
  185088. void **ppOut
  185089. ){
  185090. int rc = SQLITE_OK;
  185091. SessionBuffer buf = {0, 0, 0};
  185092. SessionTable *pTab;
  185093. assert( xOutput==0 || (ppOut==0 && pnOut==0) );
  185094. /* Create the serialized output changeset based on the contents of the
  185095. ** hash tables attached to the SessionTable objects in list p->pList.
  185096. */
  185097. for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  185098. int i;
  185099. if( pTab->nEntry==0 ) continue;
  185100. sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
  185101. for(i=0; i<pTab->nChange; i++){
  185102. SessionChange *p;
  185103. for(p=pTab->apChange[i]; p; p=p->pNext){
  185104. sessionAppendByte(&buf, p->op, &rc);
  185105. sessionAppendByte(&buf, p->bIndirect, &rc);
  185106. sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
  185107. if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){
  185108. rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  185109. buf.nBuf = 0;
  185110. }
  185111. }
  185112. }
  185113. }
  185114. if( rc==SQLITE_OK ){
  185115. if( xOutput ){
  185116. if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  185117. }else{
  185118. *ppOut = buf.aBuf;
  185119. *pnOut = buf.nBuf;
  185120. buf.aBuf = 0;
  185121. }
  185122. }
  185123. sqlite3_free(buf.aBuf);
  185124. return rc;
  185125. }
  185126. /*
  185127. ** Allocate a new, empty, sqlite3_changegroup.
  185128. */
  185129. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
  185130. int rc = SQLITE_OK; /* Return code */
  185131. sqlite3_changegroup *p; /* New object */
  185132. p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
  185133. if( p==0 ){
  185134. rc = SQLITE_NOMEM;
  185135. }else{
  185136. memset(p, 0, sizeof(sqlite3_changegroup));
  185137. }
  185138. *pp = p;
  185139. return rc;
  185140. }
  185141. /*
  185142. ** Add the changeset currently stored in buffer pData, size nData bytes,
  185143. ** to changeset-group p.
  185144. */
  185145. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
  185146. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  185147. int rc; /* Return code */
  185148. rc = sqlite3changeset_start(&pIter, nData, pData);
  185149. if( rc==SQLITE_OK ){
  185150. rc = sessionChangesetToHash(pIter, pGrp, 0);
  185151. }
  185152. sqlite3changeset_finalize(pIter);
  185153. return rc;
  185154. }
  185155. /*
  185156. ** Obtain a buffer containing a changeset representing the concatenation
  185157. ** of all changesets added to the group so far.
  185158. */
  185159. SQLITE_API int sqlite3changegroup_output(
  185160. sqlite3_changegroup *pGrp,
  185161. int *pnData,
  185162. void **ppData
  185163. ){
  185164. return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
  185165. }
  185166. /*
  185167. ** Streaming versions of changegroup_add().
  185168. */
  185169. SQLITE_API int sqlite3changegroup_add_strm(
  185170. sqlite3_changegroup *pGrp,
  185171. int (*xInput)(void *pIn, void *pData, int *pnData),
  185172. void *pIn
  185173. ){
  185174. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  185175. int rc; /* Return code */
  185176. rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  185177. if( rc==SQLITE_OK ){
  185178. rc = sessionChangesetToHash(pIter, pGrp, 0);
  185179. }
  185180. sqlite3changeset_finalize(pIter);
  185181. return rc;
  185182. }
  185183. /*
  185184. ** Streaming versions of changegroup_output().
  185185. */
  185186. SQLITE_API int sqlite3changegroup_output_strm(
  185187. sqlite3_changegroup *pGrp,
  185188. int (*xOutput)(void *pOut, const void *pData, int nData),
  185189. void *pOut
  185190. ){
  185191. return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
  185192. }
  185193. /*
  185194. ** Delete a changegroup object.
  185195. */
  185196. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
  185197. if( pGrp ){
  185198. sessionDeleteTable(pGrp->pList);
  185199. sqlite3_free(pGrp);
  185200. }
  185201. }
  185202. /*
  185203. ** Combine two changesets together.
  185204. */
  185205. SQLITE_API int sqlite3changeset_concat(
  185206. int nLeft, /* Number of bytes in lhs input */
  185207. void *pLeft, /* Lhs input changeset */
  185208. int nRight /* Number of bytes in rhs input */,
  185209. void *pRight, /* Rhs input changeset */
  185210. int *pnOut, /* OUT: Number of bytes in output changeset */
  185211. void **ppOut /* OUT: changeset (left <concat> right) */
  185212. ){
  185213. sqlite3_changegroup *pGrp;
  185214. int rc;
  185215. rc = sqlite3changegroup_new(&pGrp);
  185216. if( rc==SQLITE_OK ){
  185217. rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
  185218. }
  185219. if( rc==SQLITE_OK ){
  185220. rc = sqlite3changegroup_add(pGrp, nRight, pRight);
  185221. }
  185222. if( rc==SQLITE_OK ){
  185223. rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  185224. }
  185225. sqlite3changegroup_delete(pGrp);
  185226. return rc;
  185227. }
  185228. /*
  185229. ** Streaming version of sqlite3changeset_concat().
  185230. */
  185231. SQLITE_API int sqlite3changeset_concat_strm(
  185232. int (*xInputA)(void *pIn, void *pData, int *pnData),
  185233. void *pInA,
  185234. int (*xInputB)(void *pIn, void *pData, int *pnData),
  185235. void *pInB,
  185236. int (*xOutput)(void *pOut, const void *pData, int nData),
  185237. void *pOut
  185238. ){
  185239. sqlite3_changegroup *pGrp;
  185240. int rc;
  185241. rc = sqlite3changegroup_new(&pGrp);
  185242. if( rc==SQLITE_OK ){
  185243. rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
  185244. }
  185245. if( rc==SQLITE_OK ){
  185246. rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
  185247. }
  185248. if( rc==SQLITE_OK ){
  185249. rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
  185250. }
  185251. sqlite3changegroup_delete(pGrp);
  185252. return rc;
  185253. }
  185254. /*
  185255. ** Changeset rebaser handle.
  185256. */
  185257. struct sqlite3_rebaser {
  185258. sqlite3_changegroup grp; /* Hash table */
  185259. };
  185260. /*
  185261. ** Buffers a1 and a2 must both contain a sessions module record nCol
  185262. ** fields in size. This function appends an nCol sessions module
  185263. ** record to buffer pBuf that is a copy of a1, except that for
  185264. ** each field that is undefined in a1[], swap in the field from a2[].
  185265. */
  185266. static void sessionAppendRecordMerge(
  185267. SessionBuffer *pBuf, /* Buffer to append to */
  185268. int nCol, /* Number of columns in each record */
  185269. u8 *a1, int n1, /* Record 1 */
  185270. u8 *a2, int n2, /* Record 2 */
  185271. int *pRc /* IN/OUT: error code */
  185272. ){
  185273. sessionBufferGrow(pBuf, n1+n2, pRc);
  185274. if( *pRc==SQLITE_OK ){
  185275. int i;
  185276. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  185277. for(i=0; i<nCol; i++){
  185278. int nn1 = sessionSerialLen(a1);
  185279. int nn2 = sessionSerialLen(a2);
  185280. if( *a1==0 || *a1==0xFF ){
  185281. memcpy(pOut, a2, nn2);
  185282. pOut += nn2;
  185283. }else{
  185284. memcpy(pOut, a1, nn1);
  185285. pOut += nn1;
  185286. }
  185287. a1 += nn1;
  185288. a2 += nn2;
  185289. }
  185290. pBuf->nBuf = pOut-pBuf->aBuf;
  185291. assert( pBuf->nBuf<=pBuf->nAlloc );
  185292. }
  185293. }
  185294. /*
  185295. ** This function is called when rebasing a local UPDATE change against one
  185296. ** or more remote UPDATE changes. The aRec/nRec buffer contains the current
  185297. ** old.* and new.* records for the change. The rebase buffer (a single
  185298. ** record) is in aChange/nChange. The rebased change is appended to buffer
  185299. ** pBuf.
  185300. **
  185301. ** Rebasing the UPDATE involves:
  185302. **
  185303. ** * Removing any changes to fields for which the corresponding field
  185304. ** in the rebase buffer is set to "replaced" (type 0xFF). If this
  185305. ** means the UPDATE change updates no fields, nothing is appended
  185306. ** to the output buffer.
  185307. **
  185308. ** * For each field modified by the local change for which the
  185309. ** corresponding field in the rebase buffer is not "undefined" (0x00)
  185310. ** or "replaced" (0xFF), the old.* value is replaced by the value
  185311. ** in the rebase buffer.
  185312. */
  185313. static void sessionAppendPartialUpdate(
  185314. SessionBuffer *pBuf, /* Append record here */
  185315. sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */
  185316. u8 *aRec, int nRec, /* Local change */
  185317. u8 *aChange, int nChange, /* Record to rebase against */
  185318. int *pRc /* IN/OUT: Return Code */
  185319. ){
  185320. sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
  185321. if( *pRc==SQLITE_OK ){
  185322. int bData = 0;
  185323. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  185324. int i;
  185325. u8 *a1 = aRec;
  185326. u8 *a2 = aChange;
  185327. *pOut++ = SQLITE_UPDATE;
  185328. *pOut++ = pIter->bIndirect;
  185329. for(i=0; i<pIter->nCol; i++){
  185330. int n1 = sessionSerialLen(a1);
  185331. int n2 = sessionSerialLen(a2);
  185332. if( pIter->abPK[i] || a2[0]==0 ){
  185333. if( !pIter->abPK[i] ) bData = 1;
  185334. memcpy(pOut, a1, n1);
  185335. pOut += n1;
  185336. }else if( a2[0]!=0xFF ){
  185337. bData = 1;
  185338. memcpy(pOut, a2, n2);
  185339. pOut += n2;
  185340. }else{
  185341. *pOut++ = '\0';
  185342. }
  185343. a1 += n1;
  185344. a2 += n2;
  185345. }
  185346. if( bData ){
  185347. a2 = aChange;
  185348. for(i=0; i<pIter->nCol; i++){
  185349. int n1 = sessionSerialLen(a1);
  185350. int n2 = sessionSerialLen(a2);
  185351. if( pIter->abPK[i] || a2[0]!=0xFF ){
  185352. memcpy(pOut, a1, n1);
  185353. pOut += n1;
  185354. }else{
  185355. *pOut++ = '\0';
  185356. }
  185357. a1 += n1;
  185358. a2 += n2;
  185359. }
  185360. pBuf->nBuf = (pOut - pBuf->aBuf);
  185361. }
  185362. }
  185363. }
  185364. /*
  185365. ** pIter is configured to iterate through a changeset. This function rebases
  185366. ** that changeset according to the current configuration of the rebaser
  185367. ** object passed as the first argument. If no error occurs and argument xOutput
  185368. ** is not NULL, then the changeset is returned to the caller by invoking
  185369. ** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
  185370. ** then (*ppOut) is set to point to a buffer containing the rebased changeset
  185371. ** before this function returns. In this case (*pnOut) is set to the size of
  185372. ** the buffer in bytes. It is the responsibility of the caller to eventually
  185373. ** free the (*ppOut) buffer using sqlite3_free().
  185374. **
  185375. ** If an error occurs, an SQLite error code is returned. If ppOut and
  185376. ** pnOut are not NULL, then the two output parameters are set to 0 before
  185377. ** returning.
  185378. */
  185379. static int sessionRebase(
  185380. sqlite3_rebaser *p, /* Rebaser hash table */
  185381. sqlite3_changeset_iter *pIter, /* Input data */
  185382. int (*xOutput)(void *pOut, const void *pData, int nData),
  185383. void *pOut, /* Context for xOutput callback */
  185384. int *pnOut, /* OUT: Number of bytes in output changeset */
  185385. void **ppOut /* OUT: Inverse of pChangeset */
  185386. ){
  185387. int rc = SQLITE_OK;
  185388. u8 *aRec = 0;
  185389. int nRec = 0;
  185390. int bNew = 0;
  185391. SessionTable *pTab = 0;
  185392. SessionBuffer sOut = {0,0,0};
  185393. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){
  185394. SessionChange *pChange = 0;
  185395. int bDone = 0;
  185396. if( bNew ){
  185397. const char *zTab = pIter->zTab;
  185398. for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){
  185399. if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;
  185400. }
  185401. bNew = 0;
  185402. /* A patchset may not be rebased */
  185403. if( pIter->bPatchset ){
  185404. rc = SQLITE_ERROR;
  185405. }
  185406. /* Append a table header to the output for this new table */
  185407. sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);
  185408. sessionAppendVarint(&sOut, pIter->nCol, &rc);
  185409. sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);
  185410. sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);
  185411. }
  185412. if( pTab && rc==SQLITE_OK ){
  185413. int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);
  185414. for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){
  185415. if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){
  185416. break;
  185417. }
  185418. }
  185419. }
  185420. if( pChange ){
  185421. assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );
  185422. switch( pIter->op ){
  185423. case SQLITE_INSERT:
  185424. if( pChange->op==SQLITE_INSERT ){
  185425. bDone = 1;
  185426. if( pChange->bIndirect==0 ){
  185427. sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);
  185428. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  185429. sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);
  185430. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  185431. }
  185432. }
  185433. break;
  185434. case SQLITE_UPDATE:
  185435. bDone = 1;
  185436. if( pChange->op==SQLITE_DELETE ){
  185437. if( pChange->bIndirect==0 ){
  185438. u8 *pCsr = aRec;
  185439. sessionSkipRecord(&pCsr, pIter->nCol);
  185440. sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
  185441. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  185442. sessionAppendRecordMerge(&sOut, pIter->nCol,
  185443. pCsr, nRec-(pCsr-aRec),
  185444. pChange->aRecord, pChange->nRecord, &rc
  185445. );
  185446. }
  185447. }else{
  185448. sessionAppendPartialUpdate(&sOut, pIter,
  185449. aRec, nRec, pChange->aRecord, pChange->nRecord, &rc
  185450. );
  185451. }
  185452. break;
  185453. default:
  185454. assert( pIter->op==SQLITE_DELETE );
  185455. bDone = 1;
  185456. if( pChange->op==SQLITE_INSERT ){
  185457. sessionAppendByte(&sOut, SQLITE_DELETE, &rc);
  185458. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  185459. sessionAppendRecordMerge(&sOut, pIter->nCol,
  185460. pChange->aRecord, pChange->nRecord, aRec, nRec, &rc
  185461. );
  185462. }
  185463. break;
  185464. }
  185465. }
  185466. if( bDone==0 ){
  185467. sessionAppendByte(&sOut, pIter->op, &rc);
  185468. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  185469. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  185470. }
  185471. if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){
  185472. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  185473. sOut.nBuf = 0;
  185474. }
  185475. if( rc ) break;
  185476. }
  185477. if( rc!=SQLITE_OK ){
  185478. sqlite3_free(sOut.aBuf);
  185479. memset(&sOut, 0, sizeof(sOut));
  185480. }
  185481. if( rc==SQLITE_OK ){
  185482. if( xOutput ){
  185483. if( sOut.nBuf>0 ){
  185484. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  185485. }
  185486. }else{
  185487. *ppOut = (void*)sOut.aBuf;
  185488. *pnOut = sOut.nBuf;
  185489. sOut.aBuf = 0;
  185490. }
  185491. }
  185492. sqlite3_free(sOut.aBuf);
  185493. return rc;
  185494. }
  185495. /*
  185496. ** Create a new rebaser object.
  185497. */
  185498. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
  185499. int rc = SQLITE_OK;
  185500. sqlite3_rebaser *pNew;
  185501. pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));
  185502. if( pNew==0 ){
  185503. rc = SQLITE_NOMEM;
  185504. }else{
  185505. memset(pNew, 0, sizeof(sqlite3_rebaser));
  185506. }
  185507. *ppNew = pNew;
  185508. return rc;
  185509. }
  185510. /*
  185511. ** Call this one or more times to configure a rebaser.
  185512. */
  185513. SQLITE_API int sqlite3rebaser_configure(
  185514. sqlite3_rebaser *p,
  185515. int nRebase, const void *pRebase
  185516. ){
  185517. sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
  185518. int rc; /* Return code */
  185519. rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
  185520. if( rc==SQLITE_OK ){
  185521. rc = sessionChangesetToHash(pIter, &p->grp, 1);
  185522. }
  185523. sqlite3changeset_finalize(pIter);
  185524. return rc;
  185525. }
  185526. /*
  185527. ** Rebase a changeset according to current rebaser configuration
  185528. */
  185529. SQLITE_API int sqlite3rebaser_rebase(
  185530. sqlite3_rebaser *p,
  185531. int nIn, const void *pIn,
  185532. int *pnOut, void **ppOut
  185533. ){
  185534. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  185535. int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
  185536. if( rc==SQLITE_OK ){
  185537. rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);
  185538. sqlite3changeset_finalize(pIter);
  185539. }
  185540. return rc;
  185541. }
  185542. /*
  185543. ** Rebase a changeset according to current rebaser configuration
  185544. */
  185545. SQLITE_API int sqlite3rebaser_rebase_strm(
  185546. sqlite3_rebaser *p,
  185547. int (*xInput)(void *pIn, void *pData, int *pnData),
  185548. void *pIn,
  185549. int (*xOutput)(void *pOut, const void *pData, int nData),
  185550. void *pOut
  185551. ){
  185552. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  185553. int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  185554. if( rc==SQLITE_OK ){
  185555. rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);
  185556. sqlite3changeset_finalize(pIter);
  185557. }
  185558. return rc;
  185559. }
  185560. /*
  185561. ** Destroy a rebaser object
  185562. */
  185563. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){
  185564. if( p ){
  185565. sessionDeleteTable(p->grp.pList);
  185566. sqlite3_free(p);
  185567. }
  185568. }
  185569. /*
  185570. ** Global configuration
  185571. */
  185572. SQLITE_API int sqlite3session_config(int op, void *pArg){
  185573. int rc = SQLITE_OK;
  185574. switch( op ){
  185575. case SQLITE_SESSION_CONFIG_STRMSIZE: {
  185576. int *pInt = (int*)pArg;
  185577. if( *pInt>0 ){
  185578. sessions_strm_chunk_size = *pInt;
  185579. }
  185580. *pInt = sessions_strm_chunk_size;
  185581. break;
  185582. }
  185583. default:
  185584. rc = SQLITE_MISUSE;
  185585. break;
  185586. }
  185587. return rc;
  185588. }
  185589. #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
  185590. /************** End of sqlite3session.c **************************************/
  185591. /************** Begin file fts5.c ********************************************/
  185592. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  185593. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  185594. # define NDEBUG 1
  185595. #endif
  185596. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  185597. # undef NDEBUG
  185598. #endif
  185599. /*
  185600. ** 2014 May 31
  185601. **
  185602. ** The author disclaims copyright to this source code. In place of
  185603. ** a legal notice, here is a blessing:
  185604. **
  185605. ** May you do good and not evil.
  185606. ** May you find forgiveness for yourself and forgive others.
  185607. ** May you share freely, never taking more than you give.
  185608. **
  185609. ******************************************************************************
  185610. **
  185611. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  185612. ** FTS5 may be extended with:
  185613. **
  185614. ** * custom tokenizers, and
  185615. ** * custom auxiliary functions.
  185616. */
  185617. #ifndef _FTS5_H
  185618. #define _FTS5_H
  185619. /* #include "sqlite3.h" */
  185620. #if 0
  185621. extern "C" {
  185622. #endif
  185623. /*************************************************************************
  185624. ** CUSTOM AUXILIARY FUNCTIONS
  185625. **
  185626. ** Virtual table implementations may overload SQL functions by implementing
  185627. ** the sqlite3_module.xFindFunction() method.
  185628. */
  185629. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  185630. typedef struct Fts5Context Fts5Context;
  185631. typedef struct Fts5PhraseIter Fts5PhraseIter;
  185632. typedef void (*fts5_extension_function)(
  185633. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  185634. Fts5Context *pFts, /* First arg to pass to pApi functions */
  185635. sqlite3_context *pCtx, /* Context for returning result/error */
  185636. int nVal, /* Number of values in apVal[] array */
  185637. sqlite3_value **apVal /* Array of trailing arguments */
  185638. );
  185639. struct Fts5PhraseIter {
  185640. const unsigned char *a;
  185641. const unsigned char *b;
  185642. };
  185643. /*
  185644. ** EXTENSION API FUNCTIONS
  185645. **
  185646. ** xUserData(pFts):
  185647. ** Return a copy of the context pointer the extension function was
  185648. ** registered with.
  185649. **
  185650. ** xColumnTotalSize(pFts, iCol, pnToken):
  185651. ** If parameter iCol is less than zero, set output variable *pnToken
  185652. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  185653. ** non-negative but less than the number of columns in the table, return
  185654. ** the total number of tokens in column iCol, considering all rows in
  185655. ** the FTS5 table.
  185656. **
  185657. ** If parameter iCol is greater than or equal to the number of columns
  185658. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  185659. ** an OOM condition or IO error), an appropriate SQLite error code is
  185660. ** returned.
  185661. **
  185662. ** xColumnCount(pFts):
  185663. ** Return the number of columns in the table.
  185664. **
  185665. ** xColumnSize(pFts, iCol, pnToken):
  185666. ** If parameter iCol is less than zero, set output variable *pnToken
  185667. ** to the total number of tokens in the current row. Or, if iCol is
  185668. ** non-negative but less than the number of columns in the table, set
  185669. ** *pnToken to the number of tokens in column iCol of the current row.
  185670. **
  185671. ** If parameter iCol is greater than or equal to the number of columns
  185672. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  185673. ** an OOM condition or IO error), an appropriate SQLite error code is
  185674. ** returned.
  185675. **
  185676. ** This function may be quite inefficient if used with an FTS5 table
  185677. ** created with the "columnsize=0" option.
  185678. **
  185679. ** xColumnText:
  185680. ** This function attempts to retrieve the text of column iCol of the
  185681. ** current document. If successful, (*pz) is set to point to a buffer
  185682. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  185683. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  185684. ** if an error occurs, an SQLite error code is returned and the final values
  185685. ** of (*pz) and (*pn) are undefined.
  185686. **
  185687. ** xPhraseCount:
  185688. ** Returns the number of phrases in the current query expression.
  185689. **
  185690. ** xPhraseSize:
  185691. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  185692. ** are numbered starting from zero.
  185693. **
  185694. ** xInstCount:
  185695. ** Set *pnInst to the total number of occurrences of all phrases within
  185696. ** the query within the current row. Return SQLITE_OK if successful, or
  185697. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  185698. **
  185699. ** This API can be quite slow if used with an FTS5 table created with the
  185700. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  185701. ** with either "detail=none" or "detail=column" and "content=" option
  185702. ** (i.e. if it is a contentless table), then this API always returns 0.
  185703. **
  185704. ** xInst:
  185705. ** Query for the details of phrase match iIdx within the current row.
  185706. ** Phrase matches are numbered starting from zero, so the iIdx argument
  185707. ** should be greater than or equal to zero and smaller than the value
  185708. ** output by xInstCount().
  185709. **
  185710. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  185711. ** to the column in which it occurs and *piOff the token offset of the
  185712. ** first token of the phrase. The exception is if the table was created
  185713. ** with the offsets=0 option specified. In this case *piOff is always
  185714. ** set to -1.
  185715. **
  185716. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  185717. ** if an error occurs.
  185718. **
  185719. ** This API can be quite slow if used with an FTS5 table created with the
  185720. ** "detail=none" or "detail=column" option.
  185721. **
  185722. ** xRowid:
  185723. ** Returns the rowid of the current row.
  185724. **
  185725. ** xTokenize:
  185726. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  185727. **
  185728. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  185729. ** This API function is used to query the FTS table for phrase iPhrase
  185730. ** of the current query. Specifically, a query equivalent to:
  185731. **
  185732. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  185733. **
  185734. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  185735. ** current query is executed. Any column filter that applies to
  185736. ** phrase iPhrase of the current query is included in $p. For each
  185737. ** row visited, the callback function passed as the fourth argument
  185738. ** is invoked. The context and API objects passed to the callback
  185739. ** function may be used to access the properties of each matched row.
  185740. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  185741. ** the third argument to pUserData.
  185742. **
  185743. ** If the callback function returns any value other than SQLITE_OK, the
  185744. ** query is abandoned and the xQueryPhrase function returns immediately.
  185745. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  185746. ** Otherwise, the error code is propagated upwards.
  185747. **
  185748. ** If the query runs to completion without incident, SQLITE_OK is returned.
  185749. ** Or, if some error occurs before the query completes or is aborted by
  185750. ** the callback, an SQLite error code is returned.
  185751. **
  185752. **
  185753. ** xSetAuxdata(pFts5, pAux, xDelete)
  185754. **
  185755. ** Save the pointer passed as the second argument as the extension functions
  185756. ** "auxiliary data". The pointer may then be retrieved by the current or any
  185757. ** future invocation of the same fts5 extension function made as part of
  185758. ** of the same MATCH query using the xGetAuxdata() API.
  185759. **
  185760. ** Each extension function is allocated a single auxiliary data slot for
  185761. ** each FTS query (MATCH expression). If the extension function is invoked
  185762. ** more than once for a single FTS query, then all invocations share a
  185763. ** single auxiliary data context.
  185764. **
  185765. ** If there is already an auxiliary data pointer when this function is
  185766. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  185767. ** was specified along with the original pointer, it is invoked at this
  185768. ** point.
  185769. **
  185770. ** The xDelete callback, if one is specified, is also invoked on the
  185771. ** auxiliary data pointer after the FTS5 query has finished.
  185772. **
  185773. ** If an error (e.g. an OOM condition) occurs within this function, an
  185774. ** the auxiliary data is set to NULL and an error code returned. If the
  185775. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  185776. ** pointer before returning.
  185777. **
  185778. **
  185779. ** xGetAuxdata(pFts5, bClear)
  185780. **
  185781. ** Returns the current auxiliary data pointer for the fts5 extension
  185782. ** function. See the xSetAuxdata() method for details.
  185783. **
  185784. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  185785. ** (set to NULL) before this function returns. In this case the xDelete,
  185786. ** if any, is not invoked.
  185787. **
  185788. **
  185789. ** xRowCount(pFts5, pnRow)
  185790. **
  185791. ** This function is used to retrieve the total number of rows in the table.
  185792. ** In other words, the same value that would be returned by:
  185793. **
  185794. ** SELECT count(*) FROM ftstable;
  185795. **
  185796. ** xPhraseFirst()
  185797. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  185798. ** method, to iterate through all instances of a single query phrase within
  185799. ** the current row. This is the same information as is accessible via the
  185800. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  185801. ** to use, this API may be faster under some circumstances. To iterate
  185802. ** through instances of phrase iPhrase, use the following code:
  185803. **
  185804. ** Fts5PhraseIter iter;
  185805. ** int iCol, iOff;
  185806. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  185807. ** iCol>=0;
  185808. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  185809. ** ){
  185810. ** // An instance of phrase iPhrase at offset iOff of column iCol
  185811. ** }
  185812. **
  185813. ** The Fts5PhraseIter structure is defined above. Applications should not
  185814. ** modify this structure directly - it should only be used as shown above
  185815. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  185816. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  185817. **
  185818. ** This API can be quite slow if used with an FTS5 table created with the
  185819. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  185820. ** with either "detail=none" or "detail=column" and "content=" option
  185821. ** (i.e. if it is a contentless table), then this API always iterates
  185822. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  185823. **
  185824. ** xPhraseNext()
  185825. ** See xPhraseFirst above.
  185826. **
  185827. ** xPhraseFirstColumn()
  185828. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  185829. ** and xPhraseNext() APIs described above. The difference is that instead
  185830. ** of iterating through all instances of a phrase in the current row, these
  185831. ** APIs are used to iterate through the set of columns in the current row
  185832. ** that contain one or more instances of a specified phrase. For example:
  185833. **
  185834. ** Fts5PhraseIter iter;
  185835. ** int iCol;
  185836. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  185837. ** iCol>=0;
  185838. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  185839. ** ){
  185840. ** // Column iCol contains at least one instance of phrase iPhrase
  185841. ** }
  185842. **
  185843. ** This API can be quite slow if used with an FTS5 table created with the
  185844. ** "detail=none" option. If the FTS5 table is created with either
  185845. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  185846. ** then this API always iterates through an empty set (all calls to
  185847. ** xPhraseFirstColumn() set iCol to -1).
  185848. **
  185849. ** The information accessed using this API and its companion
  185850. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  185851. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  185852. ** significantly more efficient than those alternatives when used with
  185853. ** "detail=column" tables.
  185854. **
  185855. ** xPhraseNextColumn()
  185856. ** See xPhraseFirstColumn above.
  185857. */
  185858. struct Fts5ExtensionApi {
  185859. int iVersion; /* Currently always set to 3 */
  185860. void *(*xUserData)(Fts5Context*);
  185861. int (*xColumnCount)(Fts5Context*);
  185862. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  185863. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  185864. int (*xTokenize)(Fts5Context*,
  185865. const char *pText, int nText, /* Text to tokenize */
  185866. void *pCtx, /* Context passed to xToken() */
  185867. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  185868. );
  185869. int (*xPhraseCount)(Fts5Context*);
  185870. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  185871. int (*xInstCount)(Fts5Context*, int *pnInst);
  185872. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  185873. sqlite3_int64 (*xRowid)(Fts5Context*);
  185874. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  185875. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  185876. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  185877. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  185878. );
  185879. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  185880. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  185881. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  185882. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  185883. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  185884. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  185885. };
  185886. /*
  185887. ** CUSTOM AUXILIARY FUNCTIONS
  185888. *************************************************************************/
  185889. /*************************************************************************
  185890. ** CUSTOM TOKENIZERS
  185891. **
  185892. ** Applications may also register custom tokenizer types. A tokenizer
  185893. ** is registered by providing fts5 with a populated instance of the
  185894. ** following structure. All structure methods must be defined, setting
  185895. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  185896. ** behaviour. The structure methods are expected to function as follows:
  185897. **
  185898. ** xCreate:
  185899. ** This function is used to allocate and initialize a tokenizer instance.
  185900. ** A tokenizer instance is required to actually tokenize text.
  185901. **
  185902. ** The first argument passed to this function is a copy of the (void*)
  185903. ** pointer provided by the application when the fts5_tokenizer object
  185904. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  185905. ** The second and third arguments are an array of nul-terminated strings
  185906. ** containing the tokenizer arguments, if any, specified following the
  185907. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  185908. ** to create the FTS5 table.
  185909. **
  185910. ** The final argument is an output variable. If successful, (*ppOut)
  185911. ** should be set to point to the new tokenizer handle and SQLITE_OK
  185912. ** returned. If an error occurs, some value other than SQLITE_OK should
  185913. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  185914. ** is undefined.
  185915. **
  185916. ** xDelete:
  185917. ** This function is invoked to delete a tokenizer handle previously
  185918. ** allocated using xCreate(). Fts5 guarantees that this function will
  185919. ** be invoked exactly once for each successful call to xCreate().
  185920. **
  185921. ** xTokenize:
  185922. ** This function is expected to tokenize the nText byte string indicated
  185923. ** by argument pText. pText may or may not be nul-terminated. The first
  185924. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  185925. ** returned by an earlier call to xCreate().
  185926. **
  185927. ** The second argument indicates the reason that FTS5 is requesting
  185928. ** tokenization of the supplied text. This is always one of the following
  185929. ** four values:
  185930. **
  185931. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  185932. ** or removed from the FTS table. The tokenizer is being invoked to
  185933. ** determine the set of tokens to add to (or delete from) the
  185934. ** FTS index.
  185935. **
  185936. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  185937. ** against the FTS index. The tokenizer is being called to tokenize
  185938. ** a bareword or quoted string specified as part of the query.
  185939. **
  185940. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  185941. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  185942. ** followed by a "*" character, indicating that the last token
  185943. ** returned by the tokenizer will be treated as a token prefix.
  185944. **
  185945. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  185946. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  185947. ** function. Or an fts5_api.xColumnSize() request made by the same
  185948. ** on a columnsize=0 database.
  185949. ** </ul>
  185950. **
  185951. ** For each token in the input string, the supplied callback xToken() must
  185952. ** be invoked. The first argument to it should be a copy of the pointer
  185953. ** passed as the second argument to xTokenize(). The third and fourth
  185954. ** arguments are a pointer to a buffer containing the token text, and the
  185955. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  185956. ** of the first byte of and first byte immediately following the text from
  185957. ** which the token is derived within the input.
  185958. **
  185959. ** The second argument passed to the xToken() callback ("tflags") should
  185960. ** normally be set to 0. The exception is if the tokenizer supports
  185961. ** synonyms. In this case see the discussion below for details.
  185962. **
  185963. ** FTS5 assumes the xToken() callback is invoked for each token in the
  185964. ** order that they occur within the input text.
  185965. **
  185966. ** If an xToken() callback returns any value other than SQLITE_OK, then
  185967. ** the tokenization should be abandoned and the xTokenize() method should
  185968. ** immediately return a copy of the xToken() return value. Or, if the
  185969. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  185970. ** if an error occurs with the xTokenize() implementation itself, it
  185971. ** may abandon the tokenization and return any error code other than
  185972. ** SQLITE_OK or SQLITE_DONE.
  185973. **
  185974. ** SYNONYM SUPPORT
  185975. **
  185976. ** Custom tokenizers may also support synonyms. Consider a case in which a
  185977. ** user wishes to query for a phrase such as "first place". Using the
  185978. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  185979. ** of "first place" within the document set, but not alternative forms
  185980. ** such as "1st place". In some applications, it would be better to match
  185981. ** all instances of "first place" or "1st place" regardless of which form
  185982. ** the user specified in the MATCH query text.
  185983. **
  185984. ** There are several ways to approach this in FTS5:
  185985. **
  185986. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  185987. ** In the above example, this means that the tokenizer returns the
  185988. ** same token for inputs "first" and "1st". Say that token is in
  185989. ** fact "first", so that when the user inserts the document "I won
  185990. ** 1st place" entries are added to the index for tokens "i", "won",
  185991. ** "first" and "place". If the user then queries for '1st + place',
  185992. ** the tokenizer substitutes "first" for "1st" and the query works
  185993. ** as expected.
  185994. **
  185995. ** <li> By adding multiple synonyms for a single term to the FTS index.
  185996. ** In this case, when tokenizing query text, the tokenizer may
  185997. ** provide multiple synonyms for a single term within the document.
  185998. ** FTS5 then queries the index for each synonym individually. For
  185999. ** example, faced with the query:
  186000. **
  186001. ** <codeblock>
  186002. ** ... MATCH 'first place'</codeblock>
  186003. **
  186004. ** the tokenizer offers both "1st" and "first" as synonyms for the
  186005. ** first token in the MATCH query and FTS5 effectively runs a query
  186006. ** similar to:
  186007. **
  186008. ** <codeblock>
  186009. ** ... MATCH '(first OR 1st) place'</codeblock>
  186010. **
  186011. ** except that, for the purposes of auxiliary functions, the query
  186012. ** still appears to contain just two phrases - "(first OR 1st)"
  186013. ** being treated as a single phrase.
  186014. **
  186015. ** <li> By adding multiple synonyms for a single term to the FTS index.
  186016. ** Using this method, when tokenizing document text, the tokenizer
  186017. ** provides multiple synonyms for each token. So that when a
  186018. ** document such as "I won first place" is tokenized, entries are
  186019. ** added to the FTS index for "i", "won", "first", "1st" and
  186020. ** "place".
  186021. **
  186022. ** This way, even if the tokenizer does not provide synonyms
  186023. ** when tokenizing query text (it should not - to do would be
  186024. ** inefficient), it doesn't matter if the user queries for
  186025. ** 'first + place' or '1st + place', as there are entries in the
  186026. ** FTS index corresponding to both forms of the first token.
  186027. ** </ol>
  186028. **
  186029. ** Whether it is parsing document or query text, any call to xToken that
  186030. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  186031. ** is considered to supply a synonym for the previous token. For example,
  186032. ** when parsing the document "I won first place", a tokenizer that supports
  186033. ** synonyms would call xToken() 5 times, as follows:
  186034. **
  186035. ** <codeblock>
  186036. ** xToken(pCtx, 0, "i", 1, 0, 1);
  186037. ** xToken(pCtx, 0, "won", 3, 2, 5);
  186038. ** xToken(pCtx, 0, "first", 5, 6, 11);
  186039. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  186040. ** xToken(pCtx, 0, "place", 5, 12, 17);
  186041. **</codeblock>
  186042. **
  186043. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  186044. ** xToken() is called. Multiple synonyms may be specified for a single token
  186045. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  186046. ** There is no limit to the number of synonyms that may be provided for a
  186047. ** single token.
  186048. **
  186049. ** In many cases, method (1) above is the best approach. It does not add
  186050. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  186051. ** so it is efficient in terms of disk space and query speed. However, it
  186052. ** does not support prefix queries very well. If, as suggested above, the
  186053. ** token "first" is substituted for "1st" by the tokenizer, then the query:
  186054. **
  186055. ** <codeblock>
  186056. ** ... MATCH '1s*'</codeblock>
  186057. **
  186058. ** will not match documents that contain the token "1st" (as the tokenizer
  186059. ** will probably not map "1s" to any prefix of "first").
  186060. **
  186061. ** For full prefix support, method (3) may be preferred. In this case,
  186062. ** because the index contains entries for both "first" and "1st", prefix
  186063. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  186064. ** extra entries are added to the FTS index, this method uses more space
  186065. ** within the database.
  186066. **
  186067. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  186068. ** a query such as '1s*' will match documents that contain the literal
  186069. ** token "1st", but not "first" (assuming the tokenizer is not able to
  186070. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  186071. ** will match against "1st" and "first". This method does not require
  186072. ** extra disk space, as no extra entries are added to the FTS index.
  186073. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  186074. ** as separate queries of the FTS index are required for each synonym.
  186075. **
  186076. ** When using methods (2) or (3), it is important that the tokenizer only
  186077. ** provide synonyms when tokenizing document text (method (2)) or query
  186078. ** text (method (3)), not both. Doing so will not cause any errors, but is
  186079. ** inefficient.
  186080. */
  186081. typedef struct Fts5Tokenizer Fts5Tokenizer;
  186082. typedef struct fts5_tokenizer fts5_tokenizer;
  186083. struct fts5_tokenizer {
  186084. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  186085. void (*xDelete)(Fts5Tokenizer*);
  186086. int (*xTokenize)(Fts5Tokenizer*,
  186087. void *pCtx,
  186088. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  186089. const char *pText, int nText,
  186090. int (*xToken)(
  186091. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  186092. int tflags, /* Mask of FTS5_TOKEN_* flags */
  186093. const char *pToken, /* Pointer to buffer containing token */
  186094. int nToken, /* Size of token in bytes */
  186095. int iStart, /* Byte offset of token within input text */
  186096. int iEnd /* Byte offset of end of token within input text */
  186097. )
  186098. );
  186099. };
  186100. /* Flags that may be passed as the third argument to xTokenize() */
  186101. #define FTS5_TOKENIZE_QUERY 0x0001
  186102. #define FTS5_TOKENIZE_PREFIX 0x0002
  186103. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  186104. #define FTS5_TOKENIZE_AUX 0x0008
  186105. /* Flags that may be passed by the tokenizer implementation back to FTS5
  186106. ** as the third argument to the supplied xToken callback. */
  186107. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  186108. /*
  186109. ** END OF CUSTOM TOKENIZERS
  186110. *************************************************************************/
  186111. /*************************************************************************
  186112. ** FTS5 EXTENSION REGISTRATION API
  186113. */
  186114. typedef struct fts5_api fts5_api;
  186115. struct fts5_api {
  186116. int iVersion; /* Currently always set to 2 */
  186117. /* Create a new tokenizer */
  186118. int (*xCreateTokenizer)(
  186119. fts5_api *pApi,
  186120. const char *zName,
  186121. void *pContext,
  186122. fts5_tokenizer *pTokenizer,
  186123. void (*xDestroy)(void*)
  186124. );
  186125. /* Find an existing tokenizer */
  186126. int (*xFindTokenizer)(
  186127. fts5_api *pApi,
  186128. const char *zName,
  186129. void **ppContext,
  186130. fts5_tokenizer *pTokenizer
  186131. );
  186132. /* Create a new auxiliary function */
  186133. int (*xCreateFunction)(
  186134. fts5_api *pApi,
  186135. const char *zName,
  186136. void *pContext,
  186137. fts5_extension_function xFunction,
  186138. void (*xDestroy)(void*)
  186139. );
  186140. };
  186141. /*
  186142. ** END OF REGISTRATION API
  186143. *************************************************************************/
  186144. #if 0
  186145. } /* end of the 'extern "C"' block */
  186146. #endif
  186147. #endif /* _FTS5_H */
  186148. /*
  186149. ** 2014 May 31
  186150. **
  186151. ** The author disclaims copyright to this source code. In place of
  186152. ** a legal notice, here is a blessing:
  186153. **
  186154. ** May you do good and not evil.
  186155. ** May you find forgiveness for yourself and forgive others.
  186156. ** May you share freely, never taking more than you give.
  186157. **
  186158. ******************************************************************************
  186159. **
  186160. */
  186161. #ifndef _FTS5INT_H
  186162. #define _FTS5INT_H
  186163. /* #include "fts5.h" */
  186164. /* #include "sqlite3ext.h" */
  186165. SQLITE_EXTENSION_INIT1
  186166. /* #include <string.h> */
  186167. /* #include <assert.h> */
  186168. #ifndef SQLITE_AMALGAMATION
  186169. typedef unsigned char u8;
  186170. typedef unsigned int u32;
  186171. typedef unsigned short u16;
  186172. typedef short i16;
  186173. typedef sqlite3_int64 i64;
  186174. typedef sqlite3_uint64 u64;
  186175. #ifndef ArraySize
  186176. # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
  186177. #endif
  186178. #define testcase(x)
  186179. #define ALWAYS(x) 1
  186180. #define NEVER(x) 0
  186181. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  186182. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  186183. /*
  186184. ** Constants for the largest and smallest possible 64-bit signed integers.
  186185. */
  186186. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  186187. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  186188. #endif
  186189. /* Truncate very long tokens to this many bytes. Hard limit is
  186190. ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
  186191. ** field that occurs at the start of each leaf page (see fts5_index.c). */
  186192. #define FTS5_MAX_TOKEN_SIZE 32768
  186193. /*
  186194. ** Maximum number of prefix indexes on single FTS5 table. This must be
  186195. ** less than 32. If it is set to anything large than that, an #error
  186196. ** directive in fts5_index.c will cause the build to fail.
  186197. */
  186198. #define FTS5_MAX_PREFIX_INDEXES 31
  186199. #define FTS5_DEFAULT_NEARDIST 10
  186200. #define FTS5_DEFAULT_RANK "bm25"
  186201. /* Name of rank and rowid columns */
  186202. #define FTS5_RANK_NAME "rank"
  186203. #define FTS5_ROWID_NAME "rowid"
  186204. #ifdef SQLITE_DEBUG
  186205. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  186206. static int sqlite3Fts5Corrupt(void);
  186207. #else
  186208. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  186209. #endif
  186210. /*
  186211. ** The assert_nc() macro is similar to the assert() macro, except that it
  186212. ** is used for assert() conditions that are true only if it can be
  186213. ** guranteed that the database is not corrupt.
  186214. */
  186215. #ifdef SQLITE_DEBUG
  186216. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  186217. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  186218. #else
  186219. # define assert_nc(x) assert(x)
  186220. #endif
  186221. /* Mark a function parameter as unused, to suppress nuisance compiler
  186222. ** warnings. */
  186223. #ifndef UNUSED_PARAM
  186224. # define UNUSED_PARAM(X) (void)(X)
  186225. #endif
  186226. #ifndef UNUSED_PARAM2
  186227. # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
  186228. #endif
  186229. typedef struct Fts5Global Fts5Global;
  186230. typedef struct Fts5Colset Fts5Colset;
  186231. /* If a NEAR() clump or phrase may only match a specific set of columns,
  186232. ** then an object of the following type is used to record the set of columns.
  186233. ** Each entry in the aiCol[] array is a column that may be matched.
  186234. **
  186235. ** This object is used by fts5_expr.c and fts5_index.c.
  186236. */
  186237. struct Fts5Colset {
  186238. int nCol;
  186239. int aiCol[1];
  186240. };
  186241. /**************************************************************************
  186242. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  186243. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  186244. */
  186245. typedef struct Fts5Config Fts5Config;
  186246. /*
  186247. ** An instance of the following structure encodes all information that can
  186248. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  186249. **
  186250. ** And all information loaded from the %_config table.
  186251. **
  186252. ** nAutomerge:
  186253. ** The minimum number of segments that an auto-merge operation should
  186254. ** attempt to merge together. A value of 1 sets the object to use the
  186255. ** compile time default. Zero disables auto-merge altogether.
  186256. **
  186257. ** zContent:
  186258. **
  186259. ** zContentRowid:
  186260. ** The value of the content_rowid= option, if one was specified. Or
  186261. ** the string "rowid" otherwise. This text is not quoted - if it is
  186262. ** used as part of an SQL statement it needs to be quoted appropriately.
  186263. **
  186264. ** zContentExprlist:
  186265. **
  186266. ** pzErrmsg:
  186267. ** This exists in order to allow the fts5_index.c module to return a
  186268. ** decent error message if it encounters a file-format version it does
  186269. ** not understand.
  186270. **
  186271. ** bColumnsize:
  186272. ** True if the %_docsize table is created.
  186273. **
  186274. ** bPrefixIndex:
  186275. ** This is only used for debugging. If set to false, any prefix indexes
  186276. ** are ignored. This value is configured using:
  186277. **
  186278. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  186279. **
  186280. */
  186281. struct Fts5Config {
  186282. sqlite3 *db; /* Database handle */
  186283. char *zDb; /* Database holding FTS index (e.g. "main") */
  186284. char *zName; /* Name of FTS index */
  186285. int nCol; /* Number of columns */
  186286. char **azCol; /* Column names */
  186287. u8 *abUnindexed; /* True for unindexed columns */
  186288. int nPrefix; /* Number of prefix indexes */
  186289. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  186290. int eContent; /* An FTS5_CONTENT value */
  186291. char *zContent; /* content table */
  186292. char *zContentRowid; /* "content_rowid=" option value */
  186293. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  186294. int eDetail; /* FTS5_DETAIL_XXX value */
  186295. char *zContentExprlist;
  186296. Fts5Tokenizer *pTok;
  186297. fts5_tokenizer *pTokApi;
  186298. /* Values loaded from the %_config table */
  186299. int iCookie; /* Incremented when %_config is modified */
  186300. int pgsz; /* Approximate page size used in %_data */
  186301. int nAutomerge; /* 'automerge' setting */
  186302. int nCrisisMerge; /* Maximum allowed segments per level */
  186303. int nUsermerge; /* 'usermerge' setting */
  186304. int nHashSize; /* Bytes of memory for in-memory hash */
  186305. char *zRank; /* Name of rank function */
  186306. char *zRankArgs; /* Arguments to rank function */
  186307. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  186308. char **pzErrmsg;
  186309. #ifdef SQLITE_DEBUG
  186310. int bPrefixIndex; /* True to use prefix-indexes */
  186311. #endif
  186312. };
  186313. /* Current expected value of %_config table 'version' field */
  186314. #define FTS5_CURRENT_VERSION 4
  186315. #define FTS5_CONTENT_NORMAL 0
  186316. #define FTS5_CONTENT_NONE 1
  186317. #define FTS5_CONTENT_EXTERNAL 2
  186318. #define FTS5_DETAIL_FULL 0
  186319. #define FTS5_DETAIL_NONE 1
  186320. #define FTS5_DETAIL_COLUMNS 2
  186321. static int sqlite3Fts5ConfigParse(
  186322. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  186323. );
  186324. static void sqlite3Fts5ConfigFree(Fts5Config*);
  186325. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  186326. static int sqlite3Fts5Tokenize(
  186327. Fts5Config *pConfig, /* FTS5 Configuration object */
  186328. int flags, /* FTS5_TOKENIZE_* flags */
  186329. const char *pText, int nText, /* Text to tokenize */
  186330. void *pCtx, /* Context passed to xToken() */
  186331. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  186332. );
  186333. static void sqlite3Fts5Dequote(char *z);
  186334. /* Load the contents of the %_config table */
  186335. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  186336. /* Set the value of a single config attribute */
  186337. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  186338. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  186339. /*
  186340. ** End of interface to code in fts5_config.c.
  186341. **************************************************************************/
  186342. /**************************************************************************
  186343. ** Interface to code in fts5_buffer.c.
  186344. */
  186345. /*
  186346. ** Buffer object for the incremental building of string data.
  186347. */
  186348. typedef struct Fts5Buffer Fts5Buffer;
  186349. struct Fts5Buffer {
  186350. u8 *p;
  186351. int n;
  186352. int nSpace;
  186353. };
  186354. static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
  186355. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  186356. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
  186357. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  186358. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  186359. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  186360. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  186361. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  186362. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  186363. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  186364. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  186365. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  186366. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  186367. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  186368. #define fts5BufferGrow(pRc,pBuf,nn) ( \
  186369. (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
  186370. sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
  186371. )
  186372. /* Write and decode big-endian 32-bit integer values */
  186373. static void sqlite3Fts5Put32(u8*, int);
  186374. static int sqlite3Fts5Get32(const u8*);
  186375. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  186376. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
  186377. typedef struct Fts5PoslistReader Fts5PoslistReader;
  186378. struct Fts5PoslistReader {
  186379. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  186380. const u8 *a; /* Position list to iterate through */
  186381. int n; /* Size of buffer at a[] in bytes */
  186382. int i; /* Current offset in a[] */
  186383. u8 bFlag; /* For client use (any custom purpose) */
  186384. /* Output variables */
  186385. u8 bEof; /* Set to true at EOF */
  186386. i64 iPos; /* (iCol<<32) + iPos */
  186387. };
  186388. static int sqlite3Fts5PoslistReaderInit(
  186389. const u8 *a, int n, /* Poslist buffer to iterate through */
  186390. Fts5PoslistReader *pIter /* Iterator object to initialize */
  186391. );
  186392. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  186393. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  186394. struct Fts5PoslistWriter {
  186395. i64 iPrev;
  186396. };
  186397. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  186398. static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
  186399. static int sqlite3Fts5PoslistNext64(
  186400. const u8 *a, int n, /* Buffer containing poslist */
  186401. int *pi, /* IN/OUT: Offset within a[] */
  186402. i64 *piOff /* IN/OUT: Current offset */
  186403. );
  186404. /* Malloc utility */
  186405. static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
  186406. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  186407. /* Character set tests (like isspace(), isalpha() etc.) */
  186408. static int sqlite3Fts5IsBareword(char t);
  186409. /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
  186410. typedef struct Fts5Termset Fts5Termset;
  186411. static int sqlite3Fts5TermsetNew(Fts5Termset**);
  186412. static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
  186413. static void sqlite3Fts5TermsetFree(Fts5Termset*);
  186414. /*
  186415. ** End of interface to code in fts5_buffer.c.
  186416. **************************************************************************/
  186417. /**************************************************************************
  186418. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  186419. ** to access the data stored in the %_data table.
  186420. */
  186421. typedef struct Fts5Index Fts5Index;
  186422. typedef struct Fts5IndexIter Fts5IndexIter;
  186423. struct Fts5IndexIter {
  186424. i64 iRowid;
  186425. const u8 *pData;
  186426. int nData;
  186427. u8 bEof;
  186428. };
  186429. #define sqlite3Fts5IterEof(x) ((x)->bEof)
  186430. /*
  186431. ** Values used as part of the flags argument passed to IndexQuery().
  186432. */
  186433. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  186434. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  186435. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  186436. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  186437. /* The following are used internally by the fts5_index.c module. They are
  186438. ** defined here only to make it easier to avoid clashes with the flags
  186439. ** above. */
  186440. #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
  186441. #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
  186442. /*
  186443. ** Create/destroy an Fts5Index object.
  186444. */
  186445. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  186446. static int sqlite3Fts5IndexClose(Fts5Index *p);
  186447. /*
  186448. ** Return a simple checksum value based on the arguments.
  186449. */
  186450. static u64 sqlite3Fts5IndexEntryCksum(
  186451. i64 iRowid,
  186452. int iCol,
  186453. int iPos,
  186454. int iIdx,
  186455. const char *pTerm,
  186456. int nTerm
  186457. );
  186458. /*
  186459. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  186460. ** size. Return the number of bytes in the nChar character prefix of the
  186461. ** buffer, or 0 if there are less than nChar characters in total.
  186462. */
  186463. static int sqlite3Fts5IndexCharlenToBytelen(
  186464. const char *p,
  186465. int nByte,
  186466. int nChar
  186467. );
  186468. /*
  186469. ** Open a new iterator to iterate though all rowids that match the
  186470. ** specified token or token prefix.
  186471. */
  186472. static int sqlite3Fts5IndexQuery(
  186473. Fts5Index *p, /* FTS index to query */
  186474. const char *pToken, int nToken, /* Token (or prefix) to query for */
  186475. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  186476. Fts5Colset *pColset, /* Match these columns only */
  186477. Fts5IndexIter **ppIter /* OUT: New iterator object */
  186478. );
  186479. /*
  186480. ** The various operations on open token or token prefix iterators opened
  186481. ** using sqlite3Fts5IndexQuery().
  186482. */
  186483. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  186484. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  186485. /*
  186486. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  186487. */
  186488. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  186489. /*
  186490. ** This interface is used by the fts5vocab module.
  186491. */
  186492. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  186493. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  186494. /*
  186495. ** Insert or remove data to or from the index. Each time a document is
  186496. ** added to or removed from the index, this function is called one or more
  186497. ** times.
  186498. **
  186499. ** For an insert, it must be called once for each token in the new document.
  186500. ** If the operation is a delete, it must be called (at least) once for each
  186501. ** unique token in the document with an iCol value less than zero. The iPos
  186502. ** argument is ignored for a delete.
  186503. */
  186504. static int sqlite3Fts5IndexWrite(
  186505. Fts5Index *p, /* Index to write to */
  186506. int iCol, /* Column token appears in (-ve -> delete) */
  186507. int iPos, /* Position of token within column */
  186508. const char *pToken, int nToken /* Token to add or remove to or from index */
  186509. );
  186510. /*
  186511. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  186512. ** document iDocid.
  186513. */
  186514. static int sqlite3Fts5IndexBeginWrite(
  186515. Fts5Index *p, /* Index to write to */
  186516. int bDelete, /* True if current operation is a delete */
  186517. i64 iDocid /* Docid to add or remove data from */
  186518. );
  186519. /*
  186520. ** Flush any data stored in the in-memory hash tables to the database.
  186521. ** Also close any open blob handles.
  186522. */
  186523. static int sqlite3Fts5IndexSync(Fts5Index *p);
  186524. /*
  186525. ** Discard any data stored in the in-memory hash tables. Do not write it
  186526. ** to the database. Additionally, assume that the contents of the %_data
  186527. ** table may have changed on disk. So any in-memory caches of %_data
  186528. ** records must be invalidated.
  186529. */
  186530. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  186531. /*
  186532. ** Get or set the "averages" values.
  186533. */
  186534. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  186535. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  186536. /*
  186537. ** Functions called by the storage module as part of integrity-check.
  186538. */
  186539. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  186540. /*
  186541. ** Called during virtual module initialization to register UDF
  186542. ** fts5_decode() with SQLite
  186543. */
  186544. static int sqlite3Fts5IndexInit(sqlite3*);
  186545. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  186546. /*
  186547. ** Return the total number of entries read from the %_data table by
  186548. ** this connection since it was created.
  186549. */
  186550. static int sqlite3Fts5IndexReads(Fts5Index *p);
  186551. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  186552. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  186553. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  186554. static int sqlite3Fts5IndexReset(Fts5Index *p);
  186555. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  186556. /*
  186557. ** End of interface to code in fts5_index.c.
  186558. **************************************************************************/
  186559. /**************************************************************************
  186560. ** Interface to code in fts5_varint.c.
  186561. */
  186562. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  186563. static int sqlite3Fts5GetVarintLen(u32 iVal);
  186564. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  186565. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  186566. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  186567. #define fts5GetVarint sqlite3Fts5GetVarint
  186568. #define fts5FastGetVarint32(a, iOff, nVal) { \
  186569. nVal = (a)[iOff++]; \
  186570. if( nVal & 0x80 ){ \
  186571. iOff--; \
  186572. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  186573. } \
  186574. }
  186575. /*
  186576. ** End of interface to code in fts5_varint.c.
  186577. **************************************************************************/
  186578. /**************************************************************************
  186579. ** Interface to code in fts5.c.
  186580. */
  186581. static int sqlite3Fts5GetTokenizer(
  186582. Fts5Global*,
  186583. const char **azArg,
  186584. int nArg,
  186585. Fts5Tokenizer**,
  186586. fts5_tokenizer**,
  186587. char **pzErr
  186588. );
  186589. static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
  186590. /*
  186591. ** End of interface to code in fts5.c.
  186592. **************************************************************************/
  186593. /**************************************************************************
  186594. ** Interface to code in fts5_hash.c.
  186595. */
  186596. typedef struct Fts5Hash Fts5Hash;
  186597. /*
  186598. ** Create a hash table, free a hash table.
  186599. */
  186600. static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
  186601. static void sqlite3Fts5HashFree(Fts5Hash*);
  186602. static int sqlite3Fts5HashWrite(
  186603. Fts5Hash*,
  186604. i64 iRowid, /* Rowid for this entry */
  186605. int iCol, /* Column token appears in (-ve -> delete) */
  186606. int iPos, /* Position of token within column */
  186607. char bByte,
  186608. const char *pToken, int nToken /* Token to add or remove to or from index */
  186609. );
  186610. /*
  186611. ** Empty (but do not delete) a hash table.
  186612. */
  186613. static void sqlite3Fts5HashClear(Fts5Hash*);
  186614. static int sqlite3Fts5HashQuery(
  186615. Fts5Hash*, /* Hash table to query */
  186616. const char *pTerm, int nTerm, /* Query term */
  186617. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  186618. int *pnDoclist /* OUT: Size of doclist in bytes */
  186619. );
  186620. static int sqlite3Fts5HashScanInit(
  186621. Fts5Hash*, /* Hash table to query */
  186622. const char *pTerm, int nTerm /* Query prefix */
  186623. );
  186624. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  186625. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  186626. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  186627. const char **pzTerm, /* OUT: term (nul-terminated) */
  186628. const u8 **ppDoclist, /* OUT: pointer to doclist */
  186629. int *pnDoclist /* OUT: size of doclist in bytes */
  186630. );
  186631. /*
  186632. ** End of interface to code in fts5_hash.c.
  186633. **************************************************************************/
  186634. /**************************************************************************
  186635. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  186636. ** code to access the data stored in the %_content and %_docsize tables.
  186637. */
  186638. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  186639. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  186640. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  186641. typedef struct Fts5Storage Fts5Storage;
  186642. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  186643. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  186644. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  186645. static int sqlite3Fts5DropAll(Fts5Config*);
  186646. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  186647. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
  186648. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  186649. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  186650. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  186651. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  186652. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  186653. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  186654. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  186655. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  186656. static int sqlite3Fts5StorageSync(Fts5Storage *p);
  186657. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  186658. static int sqlite3Fts5StorageConfigValue(
  186659. Fts5Storage *p, const char*, sqlite3_value*, int
  186660. );
  186661. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  186662. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  186663. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  186664. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  186665. static int sqlite3Fts5StorageReset(Fts5Storage *p);
  186666. /*
  186667. ** End of interface to code in fts5_storage.c.
  186668. **************************************************************************/
  186669. /**************************************************************************
  186670. ** Interface to code in fts5_expr.c.
  186671. */
  186672. typedef struct Fts5Expr Fts5Expr;
  186673. typedef struct Fts5ExprNode Fts5ExprNode;
  186674. typedef struct Fts5Parse Fts5Parse;
  186675. typedef struct Fts5Token Fts5Token;
  186676. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  186677. typedef struct Fts5ExprNearset Fts5ExprNearset;
  186678. struct Fts5Token {
  186679. const char *p; /* Token text (not NULL terminated) */
  186680. int n; /* Size of buffer p in bytes */
  186681. };
  186682. /* Parse a MATCH expression. */
  186683. static int sqlite3Fts5ExprNew(
  186684. Fts5Config *pConfig,
  186685. int iCol, /* Column on LHS of MATCH operator */
  186686. const char *zExpr,
  186687. Fts5Expr **ppNew,
  186688. char **pzErr
  186689. );
  186690. /*
  186691. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  186692. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  186693. ** rc = sqlite3Fts5ExprNext(pExpr)
  186694. ** ){
  186695. ** // The document with rowid iRowid matches the expression!
  186696. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  186697. ** }
  186698. */
  186699. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  186700. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  186701. static int sqlite3Fts5ExprEof(Fts5Expr*);
  186702. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  186703. static void sqlite3Fts5ExprFree(Fts5Expr*);
  186704. /* Called during startup to register a UDF with SQLite */
  186705. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  186706. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  186707. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  186708. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  186709. typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
  186710. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
  186711. static int sqlite3Fts5ExprPopulatePoslists(
  186712. Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
  186713. );
  186714. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
  186715. static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
  186716. static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
  186717. /*******************************************
  186718. ** The fts5_expr.c API above this point is used by the other hand-written
  186719. ** C code in this module. The interfaces below this point are called by
  186720. ** the parser code in fts5parse.y. */
  186721. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  186722. static Fts5ExprNode *sqlite3Fts5ParseNode(
  186723. Fts5Parse *pParse,
  186724. int eType,
  186725. Fts5ExprNode *pLeft,
  186726. Fts5ExprNode *pRight,
  186727. Fts5ExprNearset *pNear
  186728. );
  186729. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  186730. Fts5Parse *pParse,
  186731. Fts5ExprNode *pLeft,
  186732. Fts5ExprNode *pRight
  186733. );
  186734. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  186735. Fts5Parse *pParse,
  186736. Fts5ExprPhrase *pPhrase,
  186737. Fts5Token *pToken,
  186738. int bPrefix
  186739. );
  186740. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);
  186741. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  186742. Fts5Parse*,
  186743. Fts5ExprNearset*,
  186744. Fts5ExprPhrase*
  186745. );
  186746. static Fts5Colset *sqlite3Fts5ParseColset(
  186747. Fts5Parse*,
  186748. Fts5Colset*,
  186749. Fts5Token *
  186750. );
  186751. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  186752. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  186753. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  186754. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  186755. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
  186756. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
  186757. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  186758. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  186759. /*
  186760. ** End of interface to code in fts5_expr.c.
  186761. **************************************************************************/
  186762. /**************************************************************************
  186763. ** Interface to code in fts5_aux.c.
  186764. */
  186765. static int sqlite3Fts5AuxInit(fts5_api*);
  186766. /*
  186767. ** End of interface to code in fts5_aux.c.
  186768. **************************************************************************/
  186769. /**************************************************************************
  186770. ** Interface to code in fts5_tokenizer.c.
  186771. */
  186772. static int sqlite3Fts5TokenizerInit(fts5_api*);
  186773. /*
  186774. ** End of interface to code in fts5_tokenizer.c.
  186775. **************************************************************************/
  186776. /**************************************************************************
  186777. ** Interface to code in fts5_vocab.c.
  186778. */
  186779. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  186780. /*
  186781. ** End of interface to code in fts5_vocab.c.
  186782. **************************************************************************/
  186783. /**************************************************************************
  186784. ** Interface to automatically generated code in fts5_unicode2.c.
  186785. */
  186786. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  186787. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  186788. static int sqlite3Fts5UnicodeCatParse(const char*, u8*);
  186789. static int sqlite3Fts5UnicodeCategory(int iCode);
  186790. static void sqlite3Fts5UnicodeAscii(u8*, u8*);
  186791. /*
  186792. ** End of interface to code in fts5_unicode2.c.
  186793. **************************************************************************/
  186794. #endif
  186795. #define FTS5_OR 1
  186796. #define FTS5_AND 2
  186797. #define FTS5_NOT 3
  186798. #define FTS5_TERM 4
  186799. #define FTS5_COLON 5
  186800. #define FTS5_MINUS 6
  186801. #define FTS5_LCP 7
  186802. #define FTS5_RCP 8
  186803. #define FTS5_STRING 9
  186804. #define FTS5_LP 10
  186805. #define FTS5_RP 11
  186806. #define FTS5_CARET 12
  186807. #define FTS5_COMMA 13
  186808. #define FTS5_PLUS 14
  186809. #define FTS5_STAR 15
  186810. /*
  186811. ** 2000-05-29
  186812. **
  186813. ** The author disclaims copyright to this source code. In place of
  186814. ** a legal notice, here is a blessing:
  186815. **
  186816. ** May you do good and not evil.
  186817. ** May you find forgiveness for yourself and forgive others.
  186818. ** May you share freely, never taking more than you give.
  186819. **
  186820. *************************************************************************
  186821. ** Driver template for the LEMON parser generator.
  186822. **
  186823. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  186824. ** this template to construct a parser. The "lemon" program inserts text
  186825. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  186826. ** interstitial "-" characters) contained in this template is changed into
  186827. ** the value of the %name directive from the grammar. Otherwise, the content
  186828. ** of this template is copied straight through into the generate parser
  186829. ** source file.
  186830. **
  186831. ** The following is the concatenation of all %include directives from the
  186832. ** input grammar file:
  186833. */
  186834. /* #include <stdio.h> */
  186835. /* #include <assert.h> */
  186836. /************ Begin %include sections from the grammar ************************/
  186837. /* #include "fts5Int.h" */
  186838. /* #include "fts5parse.h" */
  186839. /*
  186840. ** Disable all error recovery processing in the parser push-down
  186841. ** automaton.
  186842. */
  186843. #define fts5YYNOERRORRECOVERY 1
  186844. /*
  186845. ** Make fts5yytestcase() the same as testcase()
  186846. */
  186847. #define fts5yytestcase(X) testcase(X)
  186848. /*
  186849. ** Indicate that sqlite3ParserFree() will never be called with a null
  186850. ** pointer.
  186851. */
  186852. #define fts5YYPARSEFREENOTNULL 1
  186853. /*
  186854. ** Alternative datatype for the argument to the malloc() routine passed
  186855. ** into sqlite3ParserAlloc(). The default is size_t.
  186856. */
  186857. #define fts5YYMALLOCARGTYPE u64
  186858. /**************** End of %include directives **********************************/
  186859. /* These constants specify the various numeric values for terminal symbols
  186860. ** in a format understandable to "makeheaders". This section is blank unless
  186861. ** "lemon" is run with the "-m" command-line option.
  186862. ***************** Begin makeheaders token definitions *************************/
  186863. /**************** End makeheaders token definitions ***************************/
  186864. /* The next sections is a series of control #defines.
  186865. ** various aspects of the generated parser.
  186866. ** fts5YYCODETYPE is the data type used to store the integer codes
  186867. ** that represent terminal and non-terminal symbols.
  186868. ** "unsigned char" is used if there are fewer than
  186869. ** 256 symbols. Larger types otherwise.
  186870. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
  186871. ** any terminal or nonterminal symbol.
  186872. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  186873. ** (also known as: "terminal symbols") have fall-back
  186874. ** values which should be used if the original symbol
  186875. ** would not parse. This permits keywords to sometimes
  186876. ** be used as identifiers, for example.
  186877. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
  186878. ** that indicate what to do in response to the next
  186879. ** token.
  186880. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
  186881. ** symbols. Background: A "minor type" is a semantic
  186882. ** value associated with a terminal or non-terminal
  186883. ** symbols. For example, for an "ID" terminal symbol,
  186884. ** the minor type might be the name of the identifier.
  186885. ** Each non-terminal can have a different minor type.
  186886. ** Terminal symbols all have the same minor type, though.
  186887. ** This macros defines the minor type for terminal
  186888. ** symbols.
  186889. ** fts5YYMINORTYPE is the data type used for all minor types.
  186890. ** This is typically a union of many types, one of
  186891. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  186892. ** for terminal symbols is called "fts5yy0".
  186893. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  186894. ** zero the stack is dynamically sized using realloc()
  186895. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  186896. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  186897. ** sqlite3Fts5ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
  186898. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  186899. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  186900. ** sqlite3Fts5ParserCTX_* As sqlite3Fts5ParserARG_ except for %extra_context
  186901. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  186902. ** defined, then do no error processing.
  186903. ** fts5YYNSTATE the combined number of states.
  186904. ** fts5YYNRULE the number of rules in the grammar
  186905. ** fts5YYNFTS5TOKEN Number of terminal symbols
  186906. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  186907. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  186908. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  186909. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  186910. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  186911. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  186912. ** fts5YY_MIN_REDUCE Minimum value for reduce actions
  186913. ** fts5YY_MAX_REDUCE Maximum value for reduce actions
  186914. */
  186915. #ifndef INTERFACE
  186916. # define INTERFACE 1
  186917. #endif
  186918. /************* Begin control #defines *****************************************/
  186919. #define fts5YYCODETYPE unsigned char
  186920. #define fts5YYNOCODE 27
  186921. #define fts5YYACTIONTYPE unsigned char
  186922. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  186923. typedef union {
  186924. int fts5yyinit;
  186925. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  186926. int fts5yy4;
  186927. Fts5Colset* fts5yy11;
  186928. Fts5ExprNode* fts5yy24;
  186929. Fts5ExprNearset* fts5yy46;
  186930. Fts5ExprPhrase* fts5yy53;
  186931. } fts5YYMINORTYPE;
  186932. #ifndef fts5YYSTACKDEPTH
  186933. #define fts5YYSTACKDEPTH 100
  186934. #endif
  186935. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  186936. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  186937. #define sqlite3Fts5ParserARG_PARAM ,pParse
  186938. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse=fts5yypParser->pParse;
  186939. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse=pParse;
  186940. #define sqlite3Fts5ParserCTX_SDECL
  186941. #define sqlite3Fts5ParserCTX_PDECL
  186942. #define sqlite3Fts5ParserCTX_PARAM
  186943. #define sqlite3Fts5ParserCTX_FETCH
  186944. #define sqlite3Fts5ParserCTX_STORE
  186945. #define fts5YYNSTATE 35
  186946. #define fts5YYNRULE 28
  186947. #define fts5YYNFTS5TOKEN 16
  186948. #define fts5YY_MAX_SHIFT 34
  186949. #define fts5YY_MIN_SHIFTREDUCE 52
  186950. #define fts5YY_MAX_SHIFTREDUCE 79
  186951. #define fts5YY_ERROR_ACTION 80
  186952. #define fts5YY_ACCEPT_ACTION 81
  186953. #define fts5YY_NO_ACTION 82
  186954. #define fts5YY_MIN_REDUCE 83
  186955. #define fts5YY_MAX_REDUCE 110
  186956. /************* End control #defines *******************************************/
  186957. #define fts5YY_NLOOKAHEAD ((int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])))
  186958. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  186959. ** otherwise.
  186960. **
  186961. ** Applications can choose to define fts5yytestcase() in the %include section
  186962. ** to a macro that can assist in verifying code coverage. For production
  186963. ** code the fts5yytestcase() macro should be turned off. But it is useful
  186964. ** for testing.
  186965. */
  186966. #ifndef fts5yytestcase
  186967. # define fts5yytestcase(X)
  186968. #endif
  186969. /* Next are the tables used to determine what action to take based on the
  186970. ** current state and lookahead token. These tables are used to implement
  186971. ** functions that take a state number and lookahead value and return an
  186972. ** action integer.
  186973. **
  186974. ** Suppose the action integer is N. Then the action is determined as
  186975. ** follows
  186976. **
  186977. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  186978. ** token onto the stack and goto state N.
  186979. **
  186980. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  186981. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  186982. **
  186983. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  186984. **
  186985. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  186986. **
  186987. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  186988. ** slots in the fts5yy_action[] table.
  186989. **
  186990. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  186991. ** and fts5YY_MAX_REDUCE
  186992. **
  186993. ** The action table is constructed as a single large table named fts5yy_action[].
  186994. ** Given state S and lookahead X, the action is computed as either:
  186995. **
  186996. ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  186997. ** (B) N = fts5yy_default[S]
  186998. **
  186999. ** The (A) formula is preferred. The B formula is used instead if
  187000. ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X.
  187001. **
  187002. ** The formulas above are for computing the action when the lookahead is
  187003. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  187004. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  187005. ** the fts5yy_shift_ofst[] array.
  187006. **
  187007. ** The following are the tables generated in this section:
  187008. **
  187009. ** fts5yy_action[] A single table containing all actions.
  187010. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  187011. ** fts5yy_action. Used to detect hash collisions.
  187012. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  187013. ** shifting terminals.
  187014. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  187015. ** shifting non-terminals after a reduce.
  187016. ** fts5yy_default[] Default action for each state.
  187017. **
  187018. *********** Begin parsing tables **********************************************/
  187019. #define fts5YY_ACTTAB_COUNT (105)
  187020. static const fts5YYACTIONTYPE fts5yy_action[] = {
  187021. /* 0 */ 81, 20, 96, 6, 28, 99, 98, 26, 26, 18,
  187022. /* 10 */ 96, 6, 28, 17, 98, 56, 26, 19, 96, 6,
  187023. /* 20 */ 28, 14, 98, 14, 26, 31, 92, 96, 6, 28,
  187024. /* 30 */ 108, 98, 25, 26, 21, 96, 6, 28, 78, 98,
  187025. /* 40 */ 58, 26, 29, 96, 6, 28, 107, 98, 22, 26,
  187026. /* 50 */ 24, 16, 12, 11, 1, 13, 13, 24, 16, 23,
  187027. /* 60 */ 11, 33, 34, 13, 97, 8, 27, 32, 98, 7,
  187028. /* 70 */ 26, 3, 4, 5, 3, 4, 5, 3, 83, 4,
  187029. /* 80 */ 5, 3, 63, 5, 3, 62, 12, 2, 86, 13,
  187030. /* 90 */ 9, 30, 10, 10, 54, 57, 75, 78, 78, 53,
  187031. /* 100 */ 57, 15, 82, 82, 71,
  187032. };
  187033. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  187034. /* 0 */ 16, 17, 18, 19, 20, 22, 22, 24, 24, 17,
  187035. /* 10 */ 18, 19, 20, 7, 22, 9, 24, 17, 18, 19,
  187036. /* 20 */ 20, 9, 22, 9, 24, 13, 17, 18, 19, 20,
  187037. /* 30 */ 26, 22, 24, 24, 17, 18, 19, 20, 15, 22,
  187038. /* 40 */ 9, 24, 17, 18, 19, 20, 26, 22, 21, 24,
  187039. /* 50 */ 6, 7, 9, 9, 10, 12, 12, 6, 7, 21,
  187040. /* 60 */ 9, 24, 25, 12, 18, 5, 20, 14, 22, 5,
  187041. /* 70 */ 24, 3, 1, 2, 3, 1, 2, 3, 0, 1,
  187042. /* 80 */ 2, 3, 11, 2, 3, 11, 9, 10, 5, 12,
  187043. /* 90 */ 23, 24, 10, 10, 8, 9, 9, 15, 15, 8,
  187044. /* 100 */ 9, 9, 27, 27, 11, 27, 27, 27, 27, 27,
  187045. /* 110 */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  187046. /* 120 */ 27,
  187047. };
  187048. #define fts5YY_SHIFT_COUNT (34)
  187049. #define fts5YY_SHIFT_MIN (0)
  187050. #define fts5YY_SHIFT_MAX (93)
  187051. static const unsigned char fts5yy_shift_ofst[] = {
  187052. /* 0 */ 44, 44, 44, 44, 44, 44, 51, 77, 43, 12,
  187053. /* 10 */ 14, 83, 82, 14, 23, 23, 31, 31, 71, 74,
  187054. /* 20 */ 78, 81, 86, 91, 6, 53, 53, 60, 64, 68,
  187055. /* 30 */ 53, 87, 92, 53, 93,
  187056. };
  187057. #define fts5YY_REDUCE_COUNT (17)
  187058. #define fts5YY_REDUCE_MIN (-17)
  187059. #define fts5YY_REDUCE_MAX (67)
  187060. static const signed char fts5yy_reduce_ofst[] = {
  187061. /* 0 */ -16, -8, 0, 9, 17, 25, 46, -17, -17, 37,
  187062. /* 10 */ 67, 4, 4, 8, 4, 20, 27, 38,
  187063. };
  187064. static const fts5YYACTIONTYPE fts5yy_default[] = {
  187065. /* 0 */ 80, 80, 80, 80, 80, 80, 95, 80, 80, 105,
  187066. /* 10 */ 80, 110, 110, 80, 110, 110, 80, 80, 80, 80,
  187067. /* 20 */ 80, 91, 80, 80, 80, 101, 100, 80, 80, 90,
  187068. /* 30 */ 103, 80, 80, 104, 80,
  187069. };
  187070. /********** End of lemon-generated parsing tables *****************************/
  187071. /* The next table maps tokens (terminal symbols) into fallback tokens.
  187072. ** If a construct like the following:
  187073. **
  187074. ** %fallback ID X Y Z.
  187075. **
  187076. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  187077. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  187078. ** but it does not parse, the type of the token is changed to ID and
  187079. ** the parse is retried before an error is thrown.
  187080. **
  187081. ** This feature can be used, for example, to cause some keywords in a language
  187082. ** to revert to identifiers if they keyword does not apply in the context where
  187083. ** it appears.
  187084. */
  187085. #ifdef fts5YYFALLBACK
  187086. static const fts5YYCODETYPE fts5yyFallback[] = {
  187087. };
  187088. #endif /* fts5YYFALLBACK */
  187089. /* The following structure represents a single element of the
  187090. ** parser's stack. Information stored includes:
  187091. **
  187092. ** + The state number for the parser at this level of the stack.
  187093. **
  187094. ** + The value of the token stored at this level of the stack.
  187095. ** (In other words, the "major" token.)
  187096. **
  187097. ** + The semantic value stored at this level of the stack. This is
  187098. ** the information used by the action routines in the grammar.
  187099. ** It is sometimes called the "minor" token.
  187100. **
  187101. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  187102. ** actually contains the reduce action for the second half of the
  187103. ** SHIFTREDUCE.
  187104. */
  187105. struct fts5yyStackEntry {
  187106. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  187107. fts5YYCODETYPE major; /* The major token value. This is the code
  187108. ** number for the token at this stack level */
  187109. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  187110. ** is the value of the token */
  187111. };
  187112. typedef struct fts5yyStackEntry fts5yyStackEntry;
  187113. /* The state of the parser is completely contained in an instance of
  187114. ** the following structure */
  187115. struct fts5yyParser {
  187116. fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
  187117. #ifdef fts5YYTRACKMAXSTACKDEPTH
  187118. int fts5yyhwm; /* High-water mark of the stack */
  187119. #endif
  187120. #ifndef fts5YYNOERRORRECOVERY
  187121. int fts5yyerrcnt; /* Shifts left before out of the error */
  187122. #endif
  187123. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  187124. sqlite3Fts5ParserCTX_SDECL /* A place to hold %extra_context */
  187125. #if fts5YYSTACKDEPTH<=0
  187126. int fts5yystksz; /* Current side of the stack */
  187127. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  187128. fts5yyStackEntry fts5yystk0; /* First stack entry */
  187129. #else
  187130. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  187131. fts5yyStackEntry *fts5yystackEnd; /* Last entry in the stack */
  187132. #endif
  187133. };
  187134. typedef struct fts5yyParser fts5yyParser;
  187135. #ifndef NDEBUG
  187136. /* #include <stdio.h> */
  187137. static FILE *fts5yyTraceFILE = 0;
  187138. static char *fts5yyTracePrompt = 0;
  187139. #endif /* NDEBUG */
  187140. #ifndef NDEBUG
  187141. /*
  187142. ** Turn parser tracing on by giving a stream to which to write the trace
  187143. ** and a prompt to preface each trace message. Tracing is turned off
  187144. ** by making either argument NULL
  187145. **
  187146. ** Inputs:
  187147. ** <ul>
  187148. ** <li> A FILE* to which trace output should be written.
  187149. ** If NULL, then tracing is turned off.
  187150. ** <li> A prefix string written at the beginning of every
  187151. ** line of trace output. If NULL, then tracing is
  187152. ** turned off.
  187153. ** </ul>
  187154. **
  187155. ** Outputs:
  187156. ** None.
  187157. */
  187158. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  187159. fts5yyTraceFILE = TraceFILE;
  187160. fts5yyTracePrompt = zTracePrompt;
  187161. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  187162. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  187163. }
  187164. #endif /* NDEBUG */
  187165. #if defined(fts5YYCOVERAGE) || !defined(NDEBUG)
  187166. /* For tracing shifts, the names of all terminals and nonterminals
  187167. ** are required. The following table supplies these names */
  187168. static const char *const fts5yyTokenName[] = {
  187169. /* 0 */ "$",
  187170. /* 1 */ "OR",
  187171. /* 2 */ "AND",
  187172. /* 3 */ "NOT",
  187173. /* 4 */ "TERM",
  187174. /* 5 */ "COLON",
  187175. /* 6 */ "MINUS",
  187176. /* 7 */ "LCP",
  187177. /* 8 */ "RCP",
  187178. /* 9 */ "STRING",
  187179. /* 10 */ "LP",
  187180. /* 11 */ "RP",
  187181. /* 12 */ "CARET",
  187182. /* 13 */ "COMMA",
  187183. /* 14 */ "PLUS",
  187184. /* 15 */ "STAR",
  187185. /* 16 */ "input",
  187186. /* 17 */ "expr",
  187187. /* 18 */ "cnearset",
  187188. /* 19 */ "exprlist",
  187189. /* 20 */ "colset",
  187190. /* 21 */ "colsetlist",
  187191. /* 22 */ "nearset",
  187192. /* 23 */ "nearphrases",
  187193. /* 24 */ "phrase",
  187194. /* 25 */ "neardist_opt",
  187195. /* 26 */ "star_opt",
  187196. };
  187197. #endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */
  187198. #ifndef NDEBUG
  187199. /* For tracing reduce actions, the names of all rules are required.
  187200. */
  187201. static const char *const fts5yyRuleName[] = {
  187202. /* 0 */ "input ::= expr",
  187203. /* 1 */ "colset ::= MINUS LCP colsetlist RCP",
  187204. /* 2 */ "colset ::= LCP colsetlist RCP",
  187205. /* 3 */ "colset ::= STRING",
  187206. /* 4 */ "colset ::= MINUS STRING",
  187207. /* 5 */ "colsetlist ::= colsetlist STRING",
  187208. /* 6 */ "colsetlist ::= STRING",
  187209. /* 7 */ "expr ::= expr AND expr",
  187210. /* 8 */ "expr ::= expr OR expr",
  187211. /* 9 */ "expr ::= expr NOT expr",
  187212. /* 10 */ "expr ::= colset COLON LP expr RP",
  187213. /* 11 */ "expr ::= LP expr RP",
  187214. /* 12 */ "expr ::= exprlist",
  187215. /* 13 */ "exprlist ::= cnearset",
  187216. /* 14 */ "exprlist ::= exprlist cnearset",
  187217. /* 15 */ "cnearset ::= nearset",
  187218. /* 16 */ "cnearset ::= colset COLON nearset",
  187219. /* 17 */ "nearset ::= phrase",
  187220. /* 18 */ "nearset ::= CARET phrase",
  187221. /* 19 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  187222. /* 20 */ "nearphrases ::= phrase",
  187223. /* 21 */ "nearphrases ::= nearphrases phrase",
  187224. /* 22 */ "neardist_opt ::=",
  187225. /* 23 */ "neardist_opt ::= COMMA STRING",
  187226. /* 24 */ "phrase ::= phrase PLUS STRING star_opt",
  187227. /* 25 */ "phrase ::= STRING star_opt",
  187228. /* 26 */ "star_opt ::= STAR",
  187229. /* 27 */ "star_opt ::=",
  187230. };
  187231. #endif /* NDEBUG */
  187232. #if fts5YYSTACKDEPTH<=0
  187233. /*
  187234. ** Try to increase the size of the parser stack. Return the number
  187235. ** of errors. Return 0 on success.
  187236. */
  187237. static int fts5yyGrowStack(fts5yyParser *p){
  187238. int newSize;
  187239. int idx;
  187240. fts5yyStackEntry *pNew;
  187241. newSize = p->fts5yystksz*2 + 100;
  187242. idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
  187243. if( p->fts5yystack==&p->fts5yystk0 ){
  187244. pNew = malloc(newSize*sizeof(pNew[0]));
  187245. if( pNew ) pNew[0] = p->fts5yystk0;
  187246. }else{
  187247. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  187248. }
  187249. if( pNew ){
  187250. p->fts5yystack = pNew;
  187251. p->fts5yytos = &p->fts5yystack[idx];
  187252. #ifndef NDEBUG
  187253. if( fts5yyTraceFILE ){
  187254. fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  187255. fts5yyTracePrompt, p->fts5yystksz, newSize);
  187256. }
  187257. #endif
  187258. p->fts5yystksz = newSize;
  187259. }
  187260. return pNew==0;
  187261. }
  187262. #endif
  187263. /* Datatype of the argument to the memory allocated passed as the
  187264. ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
  187265. ** putting an appropriate #define in the %include section of the input
  187266. ** grammar.
  187267. */
  187268. #ifndef fts5YYMALLOCARGTYPE
  187269. # define fts5YYMALLOCARGTYPE size_t
  187270. #endif
  187271. /* Initialize a new parser that has already been allocated.
  187272. */
  187273. static void sqlite3Fts5ParserInit(void *fts5yypRawParser sqlite3Fts5ParserCTX_PDECL){
  187274. fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yypRawParser;
  187275. sqlite3Fts5ParserCTX_STORE
  187276. #ifdef fts5YYTRACKMAXSTACKDEPTH
  187277. fts5yypParser->fts5yyhwm = 0;
  187278. #endif
  187279. #if fts5YYSTACKDEPTH<=0
  187280. fts5yypParser->fts5yytos = NULL;
  187281. fts5yypParser->fts5yystack = NULL;
  187282. fts5yypParser->fts5yystksz = 0;
  187283. if( fts5yyGrowStack(fts5yypParser) ){
  187284. fts5yypParser->fts5yystack = &fts5yypParser->fts5yystk0;
  187285. fts5yypParser->fts5yystksz = 1;
  187286. }
  187287. #endif
  187288. #ifndef fts5YYNOERRORRECOVERY
  187289. fts5yypParser->fts5yyerrcnt = -1;
  187290. #endif
  187291. fts5yypParser->fts5yytos = fts5yypParser->fts5yystack;
  187292. fts5yypParser->fts5yystack[0].stateno = 0;
  187293. fts5yypParser->fts5yystack[0].major = 0;
  187294. #if fts5YYSTACKDEPTH>0
  187295. fts5yypParser->fts5yystackEnd = &fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1];
  187296. #endif
  187297. }
  187298. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  187299. /*
  187300. ** This function allocates a new parser.
  187301. ** The only argument is a pointer to a function which works like
  187302. ** malloc.
  187303. **
  187304. ** Inputs:
  187305. ** A pointer to the function used to allocate memory.
  187306. **
  187307. ** Outputs:
  187308. ** A pointer to a parser. This pointer is used in subsequent calls
  187309. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  187310. */
  187311. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE) sqlite3Fts5ParserCTX_PDECL){
  187312. fts5yyParser *fts5yypParser;
  187313. fts5yypParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
  187314. if( fts5yypParser ){
  187315. sqlite3Fts5ParserCTX_STORE
  187316. sqlite3Fts5ParserInit(fts5yypParser sqlite3Fts5ParserCTX_PARAM);
  187317. }
  187318. return (void*)fts5yypParser;
  187319. }
  187320. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  187321. /* The following function deletes the "minor type" or semantic value
  187322. ** associated with a symbol. The symbol can be either a terminal
  187323. ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
  187324. ** a pointer to the value to be deleted. The code used to do the
  187325. ** deletions is derived from the %destructor and/or %token_destructor
  187326. ** directives of the input grammar.
  187327. */
  187328. static void fts5yy_destructor(
  187329. fts5yyParser *fts5yypParser, /* The parser */
  187330. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  187331. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  187332. ){
  187333. sqlite3Fts5ParserARG_FETCH
  187334. sqlite3Fts5ParserCTX_FETCH
  187335. switch( fts5yymajor ){
  187336. /* Here is inserted the actions which take place when a
  187337. ** terminal or non-terminal is destroyed. This can happen
  187338. ** when the symbol is popped from the stack during a
  187339. ** reduce or during error processing or when a parser is
  187340. ** being destroyed before it is finished parsing.
  187341. **
  187342. ** Note: during a reduce, the only symbols destroyed are those
  187343. ** which appear on the RHS of the rule, but which are *not* used
  187344. ** inside the C code.
  187345. */
  187346. /********* Begin destructor definitions ***************************************/
  187347. case 16: /* input */
  187348. {
  187349. (void)pParse;
  187350. }
  187351. break;
  187352. case 17: /* expr */
  187353. case 18: /* cnearset */
  187354. case 19: /* exprlist */
  187355. {
  187356. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
  187357. }
  187358. break;
  187359. case 20: /* colset */
  187360. case 21: /* colsetlist */
  187361. {
  187362. sqlite3_free((fts5yypminor->fts5yy11));
  187363. }
  187364. break;
  187365. case 22: /* nearset */
  187366. case 23: /* nearphrases */
  187367. {
  187368. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
  187369. }
  187370. break;
  187371. case 24: /* phrase */
  187372. {
  187373. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
  187374. }
  187375. break;
  187376. /********* End destructor definitions *****************************************/
  187377. default: break; /* If no destructor action specified: do nothing */
  187378. }
  187379. }
  187380. /*
  187381. ** Pop the parser's stack once.
  187382. **
  187383. ** If there is a destructor routine associated with the token which
  187384. ** is popped from the stack, then call it.
  187385. */
  187386. static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
  187387. fts5yyStackEntry *fts5yytos;
  187388. assert( pParser->fts5yytos!=0 );
  187389. assert( pParser->fts5yytos > pParser->fts5yystack );
  187390. fts5yytos = pParser->fts5yytos--;
  187391. #ifndef NDEBUG
  187392. if( fts5yyTraceFILE ){
  187393. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  187394. fts5yyTracePrompt,
  187395. fts5yyTokenName[fts5yytos->major]);
  187396. }
  187397. #endif
  187398. fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
  187399. }
  187400. /*
  187401. ** Clear all secondary memory allocations from the parser
  187402. */
  187403. static void sqlite3Fts5ParserFinalize(void *p){
  187404. fts5yyParser *pParser = (fts5yyParser*)p;
  187405. while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
  187406. #if fts5YYSTACKDEPTH<=0
  187407. if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
  187408. #endif
  187409. }
  187410. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  187411. /*
  187412. ** Deallocate and destroy a parser. Destructors are called for
  187413. ** all stack elements before shutting the parser down.
  187414. **
  187415. ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
  187416. ** is defined in a %include section of the input grammar) then it is
  187417. ** assumed that the input pointer is never NULL.
  187418. */
  187419. static void sqlite3Fts5ParserFree(
  187420. void *p, /* The parser to be deleted */
  187421. void (*freeProc)(void*) /* Function used to reclaim memory */
  187422. ){
  187423. #ifndef fts5YYPARSEFREENEVERNULL
  187424. if( p==0 ) return;
  187425. #endif
  187426. sqlite3Fts5ParserFinalize(p);
  187427. (*freeProc)(p);
  187428. }
  187429. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  187430. /*
  187431. ** Return the peak depth of the stack for a parser.
  187432. */
  187433. #ifdef fts5YYTRACKMAXSTACKDEPTH
  187434. static int sqlite3Fts5ParserStackPeak(void *p){
  187435. fts5yyParser *pParser = (fts5yyParser*)p;
  187436. return pParser->fts5yyhwm;
  187437. }
  187438. #endif
  187439. /* This array of booleans keeps track of the parser statement
  187440. ** coverage. The element fts5yycoverage[X][Y] is set when the parser
  187441. ** is in state X and has a lookahead token Y. In a well-tested
  187442. ** systems, every element of this matrix should end up being set.
  187443. */
  187444. #if defined(fts5YYCOVERAGE)
  187445. static unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN];
  187446. #endif
  187447. /*
  187448. ** Write into out a description of every state/lookahead combination that
  187449. **
  187450. ** (1) has not been used by the parser, and
  187451. ** (2) is not a syntax error.
  187452. **
  187453. ** Return the number of missed state/lookahead combinations.
  187454. */
  187455. #if defined(fts5YYCOVERAGE)
  187456. static int sqlite3Fts5ParserCoverage(FILE *out){
  187457. int stateno, iLookAhead, i;
  187458. int nMissed = 0;
  187459. for(stateno=0; stateno<fts5YYNSTATE; stateno++){
  187460. i = fts5yy_shift_ofst[stateno];
  187461. for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){
  187462. if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  187463. if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  187464. if( out ){
  187465. fprintf(out,"State %d lookahead %s %s\n", stateno,
  187466. fts5yyTokenName[iLookAhead],
  187467. fts5yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  187468. }
  187469. }
  187470. }
  187471. return nMissed;
  187472. }
  187473. #endif
  187474. /*
  187475. ** Find the appropriate action for a parser given the terminal
  187476. ** look-ahead token iLookAhead.
  187477. */
  187478. static fts5YYACTIONTYPE fts5yy_find_shift_action(
  187479. fts5YYCODETYPE iLookAhead, /* The look-ahead token */
  187480. fts5YYACTIONTYPE stateno /* Current state number */
  187481. ){
  187482. int i;
  187483. if( stateno>fts5YY_MAX_SHIFT ) return stateno;
  187484. assert( stateno <= fts5YY_SHIFT_COUNT );
  187485. #if defined(fts5YYCOVERAGE)
  187486. fts5yycoverage[stateno][iLookAhead] = 1;
  187487. #endif
  187488. do{
  187489. i = fts5yy_shift_ofst[stateno];
  187490. assert( i>=0 );
  187491. /* assert( i+fts5YYNFTS5TOKEN<=(int)fts5YY_NLOOKAHEAD ); */
  187492. assert( iLookAhead!=fts5YYNOCODE );
  187493. assert( iLookAhead < fts5YYNFTS5TOKEN );
  187494. i += iLookAhead;
  187495. if( i>=fts5YY_NLOOKAHEAD || fts5yy_lookahead[i]!=iLookAhead ){
  187496. #ifdef fts5YYFALLBACK
  187497. fts5YYCODETYPE iFallback; /* Fallback token */
  187498. if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
  187499. && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
  187500. #ifndef NDEBUG
  187501. if( fts5yyTraceFILE ){
  187502. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  187503. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  187504. }
  187505. #endif
  187506. assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  187507. iLookAhead = iFallback;
  187508. continue;
  187509. }
  187510. #endif
  187511. #ifdef fts5YYWILDCARD
  187512. {
  187513. int j = i - iLookAhead + fts5YYWILDCARD;
  187514. if(
  187515. #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
  187516. j>=0 &&
  187517. #endif
  187518. #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
  187519. j<fts5YY_ACTTAB_COUNT &&
  187520. #endif
  187521. j<(int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])) &&
  187522. fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
  187523. ){
  187524. #ifndef NDEBUG
  187525. if( fts5yyTraceFILE ){
  187526. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  187527. fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
  187528. fts5yyTokenName[fts5YYWILDCARD]);
  187529. }
  187530. #endif /* NDEBUG */
  187531. return fts5yy_action[j];
  187532. }
  187533. }
  187534. #endif /* fts5YYWILDCARD */
  187535. return fts5yy_default[stateno];
  187536. }else{
  187537. return fts5yy_action[i];
  187538. }
  187539. }while(1);
  187540. }
  187541. /*
  187542. ** Find the appropriate action for a parser given the non-terminal
  187543. ** look-ahead token iLookAhead.
  187544. */
  187545. static fts5YYACTIONTYPE fts5yy_find_reduce_action(
  187546. fts5YYACTIONTYPE stateno, /* Current state number */
  187547. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  187548. ){
  187549. int i;
  187550. #ifdef fts5YYERRORSYMBOL
  187551. if( stateno>fts5YY_REDUCE_COUNT ){
  187552. return fts5yy_default[stateno];
  187553. }
  187554. #else
  187555. assert( stateno<=fts5YY_REDUCE_COUNT );
  187556. #endif
  187557. i = fts5yy_reduce_ofst[stateno];
  187558. assert( iLookAhead!=fts5YYNOCODE );
  187559. i += iLookAhead;
  187560. #ifdef fts5YYERRORSYMBOL
  187561. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  187562. return fts5yy_default[stateno];
  187563. }
  187564. #else
  187565. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  187566. assert( fts5yy_lookahead[i]==iLookAhead );
  187567. #endif
  187568. return fts5yy_action[i];
  187569. }
  187570. /*
  187571. ** The following routine is called if the stack overflows.
  187572. */
  187573. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
  187574. sqlite3Fts5ParserARG_FETCH
  187575. sqlite3Fts5ParserCTX_FETCH
  187576. #ifndef NDEBUG
  187577. if( fts5yyTraceFILE ){
  187578. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  187579. }
  187580. #endif
  187581. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  187582. /* Here code is inserted which will execute if the parser
  187583. ** stack every overflows */
  187584. /******** Begin %stack_overflow code ******************************************/
  187585. sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
  187586. /******** End %stack_overflow code ********************************************/
  187587. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument var */
  187588. sqlite3Fts5ParserCTX_STORE
  187589. }
  187590. /*
  187591. ** Print tracing information for a SHIFT action
  187592. */
  187593. #ifndef NDEBUG
  187594. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){
  187595. if( fts5yyTraceFILE ){
  187596. if( fts5yyNewState<fts5YYNSTATE ){
  187597. fprintf(fts5yyTraceFILE,"%s%s '%s', go to state %d\n",
  187598. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  187599. fts5yyNewState);
  187600. }else{
  187601. fprintf(fts5yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  187602. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  187603. fts5yyNewState - fts5YY_MIN_REDUCE);
  187604. }
  187605. }
  187606. }
  187607. #else
  187608. # define fts5yyTraceShift(X,Y,Z)
  187609. #endif
  187610. /*
  187611. ** Perform a shift action.
  187612. */
  187613. static void fts5yy_shift(
  187614. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  187615. fts5YYACTIONTYPE fts5yyNewState, /* The new state to shift in */
  187616. fts5YYCODETYPE fts5yyMajor, /* The major token to shift in */
  187617. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
  187618. ){
  187619. fts5yyStackEntry *fts5yytos;
  187620. fts5yypParser->fts5yytos++;
  187621. #ifdef fts5YYTRACKMAXSTACKDEPTH
  187622. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  187623. fts5yypParser->fts5yyhwm++;
  187624. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
  187625. }
  187626. #endif
  187627. #if fts5YYSTACKDEPTH>0
  187628. if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
  187629. fts5yypParser->fts5yytos--;
  187630. fts5yyStackOverflow(fts5yypParser);
  187631. return;
  187632. }
  187633. #else
  187634. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
  187635. if( fts5yyGrowStack(fts5yypParser) ){
  187636. fts5yypParser->fts5yytos--;
  187637. fts5yyStackOverflow(fts5yypParser);
  187638. return;
  187639. }
  187640. }
  187641. #endif
  187642. if( fts5yyNewState > fts5YY_MAX_SHIFT ){
  187643. fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  187644. }
  187645. fts5yytos = fts5yypParser->fts5yytos;
  187646. fts5yytos->stateno = fts5yyNewState;
  187647. fts5yytos->major = fts5yyMajor;
  187648. fts5yytos->minor.fts5yy0 = fts5yyMinor;
  187649. fts5yyTraceShift(fts5yypParser, fts5yyNewState, "Shift");
  187650. }
  187651. /* The following table contains information about every rule that
  187652. ** is used during the reduce.
  187653. */
  187654. static const struct {
  187655. fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  187656. signed char nrhs; /* Negative of the number of RHS symbols in the rule */
  187657. } fts5yyRuleInfo[] = {
  187658. { 16, -1 }, /* (0) input ::= expr */
  187659. { 20, -4 }, /* (1) colset ::= MINUS LCP colsetlist RCP */
  187660. { 20, -3 }, /* (2) colset ::= LCP colsetlist RCP */
  187661. { 20, -1 }, /* (3) colset ::= STRING */
  187662. { 20, -2 }, /* (4) colset ::= MINUS STRING */
  187663. { 21, -2 }, /* (5) colsetlist ::= colsetlist STRING */
  187664. { 21, -1 }, /* (6) colsetlist ::= STRING */
  187665. { 17, -3 }, /* (7) expr ::= expr AND expr */
  187666. { 17, -3 }, /* (8) expr ::= expr OR expr */
  187667. { 17, -3 }, /* (9) expr ::= expr NOT expr */
  187668. { 17, -5 }, /* (10) expr ::= colset COLON LP expr RP */
  187669. { 17, -3 }, /* (11) expr ::= LP expr RP */
  187670. { 17, -1 }, /* (12) expr ::= exprlist */
  187671. { 19, -1 }, /* (13) exprlist ::= cnearset */
  187672. { 19, -2 }, /* (14) exprlist ::= exprlist cnearset */
  187673. { 18, -1 }, /* (15) cnearset ::= nearset */
  187674. { 18, -3 }, /* (16) cnearset ::= colset COLON nearset */
  187675. { 22, -1 }, /* (17) nearset ::= phrase */
  187676. { 22, -2 }, /* (18) nearset ::= CARET phrase */
  187677. { 22, -5 }, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
  187678. { 23, -1 }, /* (20) nearphrases ::= phrase */
  187679. { 23, -2 }, /* (21) nearphrases ::= nearphrases phrase */
  187680. { 25, 0 }, /* (22) neardist_opt ::= */
  187681. { 25, -2 }, /* (23) neardist_opt ::= COMMA STRING */
  187682. { 24, -4 }, /* (24) phrase ::= phrase PLUS STRING star_opt */
  187683. { 24, -2 }, /* (25) phrase ::= STRING star_opt */
  187684. { 26, -1 }, /* (26) star_opt ::= STAR */
  187685. { 26, 0 }, /* (27) star_opt ::= */
  187686. };
  187687. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  187688. /*
  187689. ** Perform a reduce action and the shift that must immediately
  187690. ** follow the reduce.
  187691. **
  187692. ** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions
  187693. ** access to the lookahead token (if any). The fts5yyLookahead will be fts5YYNOCODE
  187694. ** if the lookahead token has already been consumed. As this procedure is
  187695. ** only called from one place, optimizing compilers will in-line it, which
  187696. ** means that the extra parameters have no performance impact.
  187697. */
  187698. static fts5YYACTIONTYPE fts5yy_reduce(
  187699. fts5yyParser *fts5yypParser, /* The parser */
  187700. unsigned int fts5yyruleno, /* Number of the rule by which to reduce */
  187701. int fts5yyLookahead, /* Lookahead token, or fts5YYNOCODE if none */
  187702. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken /* Value of the lookahead token */
  187703. sqlite3Fts5ParserCTX_PDECL /* %extra_context */
  187704. ){
  187705. int fts5yygoto; /* The next state */
  187706. fts5YYACTIONTYPE fts5yyact; /* The next action */
  187707. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  187708. int fts5yysize; /* Amount to pop the stack */
  187709. sqlite3Fts5ParserARG_FETCH
  187710. (void)fts5yyLookahead;
  187711. (void)fts5yyLookaheadToken;
  187712. fts5yymsp = fts5yypParser->fts5yytos;
  187713. #ifndef NDEBUG
  187714. if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  187715. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  187716. if( fts5yysize ){
  187717. fprintf(fts5yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
  187718. fts5yyTracePrompt,
  187719. fts5yyruleno, fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
  187720. }else{
  187721. fprintf(fts5yyTraceFILE, "%sReduce %d [%s].\n",
  187722. fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno]);
  187723. }
  187724. }
  187725. #endif /* NDEBUG */
  187726. /* Check that the stack is large enough to grow by a single entry
  187727. ** if the RHS of the rule is empty. This ensures that there is room
  187728. ** enough on the stack to push the LHS value */
  187729. if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
  187730. #ifdef fts5YYTRACKMAXSTACKDEPTH
  187731. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  187732. fts5yypParser->fts5yyhwm++;
  187733. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
  187734. }
  187735. #endif
  187736. #if fts5YYSTACKDEPTH>0
  187737. if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
  187738. fts5yyStackOverflow(fts5yypParser);
  187739. /* The call to fts5yyStackOverflow() above pops the stack until it is
  187740. ** empty, causing the main parser loop to exit. So the return value
  187741. ** is never used and does not matter. */
  187742. return 0;
  187743. }
  187744. #else
  187745. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
  187746. if( fts5yyGrowStack(fts5yypParser) ){
  187747. fts5yyStackOverflow(fts5yypParser);
  187748. /* The call to fts5yyStackOverflow() above pops the stack until it is
  187749. ** empty, causing the main parser loop to exit. So the return value
  187750. ** is never used and does not matter. */
  187751. return 0;
  187752. }
  187753. fts5yymsp = fts5yypParser->fts5yytos;
  187754. }
  187755. #endif
  187756. }
  187757. switch( fts5yyruleno ){
  187758. /* Beginning here are the reduction cases. A typical example
  187759. ** follows:
  187760. ** case 0:
  187761. ** #line <lineno> <grammarfile>
  187762. ** { ... } // User supplied code
  187763. ** #line <lineno> <thisfile>
  187764. ** break;
  187765. */
  187766. /********** Begin reduce actions **********************************************/
  187767. fts5YYMINORTYPE fts5yylhsminor;
  187768. case 0: /* input ::= expr */
  187769. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
  187770. break;
  187771. case 1: /* colset ::= MINUS LCP colsetlist RCP */
  187772. {
  187773. fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  187774. }
  187775. break;
  187776. case 2: /* colset ::= LCP colsetlist RCP */
  187777. { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
  187778. break;
  187779. case 3: /* colset ::= STRING */
  187780. {
  187781. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  187782. }
  187783. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  187784. break;
  187785. case 4: /* colset ::= MINUS STRING */
  187786. {
  187787. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  187788. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  187789. }
  187790. break;
  187791. case 5: /* colsetlist ::= colsetlist STRING */
  187792. {
  187793. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
  187794. fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  187795. break;
  187796. case 6: /* colsetlist ::= STRING */
  187797. {
  187798. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  187799. }
  187800. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  187801. break;
  187802. case 7: /* expr ::= expr AND expr */
  187803. {
  187804. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  187805. }
  187806. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  187807. break;
  187808. case 8: /* expr ::= expr OR expr */
  187809. {
  187810. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  187811. }
  187812. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  187813. break;
  187814. case 9: /* expr ::= expr NOT expr */
  187815. {
  187816. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  187817. }
  187818. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  187819. break;
  187820. case 10: /* expr ::= colset COLON LP expr RP */
  187821. {
  187822. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
  187823. fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
  187824. }
  187825. fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  187826. break;
  187827. case 11: /* expr ::= LP expr RP */
  187828. {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
  187829. break;
  187830. case 12: /* expr ::= exprlist */
  187831. case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
  187832. {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
  187833. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  187834. break;
  187835. case 14: /* exprlist ::= exprlist cnearset */
  187836. {
  187837. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
  187838. }
  187839. fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  187840. break;
  187841. case 15: /* cnearset ::= nearset */
  187842. {
  187843. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  187844. }
  187845. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  187846. break;
  187847. case 16: /* cnearset ::= colset COLON nearset */
  187848. {
  187849. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  187850. sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
  187851. }
  187852. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  187853. break;
  187854. case 17: /* nearset ::= phrase */
  187855. { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
  187856. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  187857. break;
  187858. case 18: /* nearset ::= CARET phrase */
  187859. {
  187860. sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy53);
  187861. fts5yymsp[-1].minor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  187862. }
  187863. break;
  187864. case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  187865. {
  187866. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  187867. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
  187868. fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
  187869. }
  187870. fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  187871. break;
  187872. case 20: /* nearphrases ::= phrase */
  187873. {
  187874. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  187875. }
  187876. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  187877. break;
  187878. case 21: /* nearphrases ::= nearphrases phrase */
  187879. {
  187880. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
  187881. }
  187882. fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  187883. break;
  187884. case 22: /* neardist_opt ::= */
  187885. { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
  187886. break;
  187887. case 23: /* neardist_opt ::= COMMA STRING */
  187888. { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  187889. break;
  187890. case 24: /* phrase ::= phrase PLUS STRING star_opt */
  187891. {
  187892. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  187893. }
  187894. fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  187895. break;
  187896. case 25: /* phrase ::= STRING star_opt */
  187897. {
  187898. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  187899. }
  187900. fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  187901. break;
  187902. case 26: /* star_opt ::= STAR */
  187903. { fts5yymsp[0].minor.fts5yy4 = 1; }
  187904. break;
  187905. case 27: /* star_opt ::= */
  187906. { fts5yymsp[1].minor.fts5yy4 = 0; }
  187907. break;
  187908. default:
  187909. break;
  187910. /********** End reduce actions ************************************************/
  187911. };
  187912. assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
  187913. fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
  187914. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  187915. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  187916. /* There are no SHIFTREDUCE actions on nonterminals because the table
  187917. ** generator has simplified them to pure REDUCE actions. */
  187918. assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
  187919. /* It is not possible for a REDUCE to be followed by an error */
  187920. assert( fts5yyact!=fts5YY_ERROR_ACTION );
  187921. fts5yymsp += fts5yysize+1;
  187922. fts5yypParser->fts5yytos = fts5yymsp;
  187923. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  187924. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  187925. fts5yyTraceShift(fts5yypParser, fts5yyact, "... then shift");
  187926. return fts5yyact;
  187927. }
  187928. /*
  187929. ** The following code executes when the parse fails
  187930. */
  187931. #ifndef fts5YYNOERRORRECOVERY
  187932. static void fts5yy_parse_failed(
  187933. fts5yyParser *fts5yypParser /* The parser */
  187934. ){
  187935. sqlite3Fts5ParserARG_FETCH
  187936. sqlite3Fts5ParserCTX_FETCH
  187937. #ifndef NDEBUG
  187938. if( fts5yyTraceFILE ){
  187939. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  187940. }
  187941. #endif
  187942. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  187943. /* Here code is inserted which will be executed whenever the
  187944. ** parser fails */
  187945. /************ Begin %parse_failure code ***************************************/
  187946. /************ End %parse_failure code *****************************************/
  187947. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  187948. sqlite3Fts5ParserCTX_STORE
  187949. }
  187950. #endif /* fts5YYNOERRORRECOVERY */
  187951. /*
  187952. ** The following code executes when a syntax error first occurs.
  187953. */
  187954. static void fts5yy_syntax_error(
  187955. fts5yyParser *fts5yypParser, /* The parser */
  187956. int fts5yymajor, /* The major type of the error token */
  187957. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
  187958. ){
  187959. sqlite3Fts5ParserARG_FETCH
  187960. sqlite3Fts5ParserCTX_FETCH
  187961. #define FTS5TOKEN fts5yyminor
  187962. /************ Begin %syntax_error code ****************************************/
  187963. UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
  187964. sqlite3Fts5ParseError(
  187965. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  187966. );
  187967. /************ End %syntax_error code ******************************************/
  187968. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  187969. sqlite3Fts5ParserCTX_STORE
  187970. }
  187971. /*
  187972. ** The following is executed when the parser accepts
  187973. */
  187974. static void fts5yy_accept(
  187975. fts5yyParser *fts5yypParser /* The parser */
  187976. ){
  187977. sqlite3Fts5ParserARG_FETCH
  187978. sqlite3Fts5ParserCTX_FETCH
  187979. #ifndef NDEBUG
  187980. if( fts5yyTraceFILE ){
  187981. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  187982. }
  187983. #endif
  187984. #ifndef fts5YYNOERRORRECOVERY
  187985. fts5yypParser->fts5yyerrcnt = -1;
  187986. #endif
  187987. assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
  187988. /* Here code is inserted which will be executed whenever the
  187989. ** parser accepts */
  187990. /*********** Begin %parse_accept code *****************************************/
  187991. /*********** End %parse_accept code *******************************************/
  187992. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  187993. sqlite3Fts5ParserCTX_STORE
  187994. }
  187995. /* The main parser program.
  187996. ** The first argument is a pointer to a structure obtained from
  187997. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  187998. ** The second argument is the major token number. The third is
  187999. ** the minor token. The fourth optional argument is whatever the
  188000. ** user wants (and specified in the grammar) and is available for
  188001. ** use by the action routines.
  188002. **
  188003. ** Inputs:
  188004. ** <ul>
  188005. ** <li> A pointer to the parser (an opaque structure.)
  188006. ** <li> The major token number.
  188007. ** <li> The minor token number.
  188008. ** <li> An option argument of a grammar-specified type.
  188009. ** </ul>
  188010. **
  188011. ** Outputs:
  188012. ** None.
  188013. */
  188014. static void sqlite3Fts5Parser(
  188015. void *fts5yyp, /* The parser */
  188016. int fts5yymajor, /* The major token code number */
  188017. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  188018. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  188019. ){
  188020. fts5YYMINORTYPE fts5yyminorunion;
  188021. fts5YYACTIONTYPE fts5yyact; /* The parser action. */
  188022. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  188023. int fts5yyendofinput; /* True if we are at the end of input */
  188024. #endif
  188025. #ifdef fts5YYERRORSYMBOL
  188026. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  188027. #endif
  188028. fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yyp; /* The parser */
  188029. sqlite3Fts5ParserCTX_FETCH
  188030. sqlite3Fts5ParserARG_STORE
  188031. assert( fts5yypParser->fts5yytos!=0 );
  188032. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  188033. fts5yyendofinput = (fts5yymajor==0);
  188034. #endif
  188035. fts5yyact = fts5yypParser->fts5yytos->stateno;
  188036. #ifndef NDEBUG
  188037. if( fts5yyTraceFILE ){
  188038. if( fts5yyact < fts5YY_MIN_REDUCE ){
  188039. fprintf(fts5yyTraceFILE,"%sInput '%s' in state %d\n",
  188040. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact);
  188041. }else{
  188042. fprintf(fts5yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  188043. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact-fts5YY_MIN_REDUCE);
  188044. }
  188045. }
  188046. #endif
  188047. do{
  188048. assert( fts5yyact==fts5yypParser->fts5yytos->stateno );
  188049. fts5yyact = fts5yy_find_shift_action((fts5YYCODETYPE)fts5yymajor,fts5yyact);
  188050. if( fts5yyact >= fts5YY_MIN_REDUCE ){
  188051. fts5yyact = fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE,fts5yymajor,
  188052. fts5yyminor sqlite3Fts5ParserCTX_PARAM);
  188053. }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  188054. fts5yy_shift(fts5yypParser,fts5yyact,(fts5YYCODETYPE)fts5yymajor,fts5yyminor);
  188055. #ifndef fts5YYNOERRORRECOVERY
  188056. fts5yypParser->fts5yyerrcnt--;
  188057. #endif
  188058. break;
  188059. }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){
  188060. fts5yypParser->fts5yytos--;
  188061. fts5yy_accept(fts5yypParser);
  188062. return;
  188063. }else{
  188064. assert( fts5yyact == fts5YY_ERROR_ACTION );
  188065. fts5yyminorunion.fts5yy0 = fts5yyminor;
  188066. #ifdef fts5YYERRORSYMBOL
  188067. int fts5yymx;
  188068. #endif
  188069. #ifndef NDEBUG
  188070. if( fts5yyTraceFILE ){
  188071. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  188072. }
  188073. #endif
  188074. #ifdef fts5YYERRORSYMBOL
  188075. /* A syntax error has occurred.
  188076. ** The response to an error depends upon whether or not the
  188077. ** grammar defines an error token "ERROR".
  188078. **
  188079. ** This is what we do if the grammar does define ERROR:
  188080. **
  188081. ** * Call the %syntax_error function.
  188082. **
  188083. ** * Begin popping the stack until we enter a state where
  188084. ** it is legal to shift the error symbol, then shift
  188085. ** the error symbol.
  188086. **
  188087. ** * Set the error count to three.
  188088. **
  188089. ** * Begin accepting and shifting new tokens. No new error
  188090. ** processing will occur until three tokens have been
  188091. ** shifted successfully.
  188092. **
  188093. */
  188094. if( fts5yypParser->fts5yyerrcnt<0 ){
  188095. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
  188096. }
  188097. fts5yymx = fts5yypParser->fts5yytos->major;
  188098. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  188099. #ifndef NDEBUG
  188100. if( fts5yyTraceFILE ){
  188101. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  188102. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  188103. }
  188104. #endif
  188105. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
  188106. fts5yymajor = fts5YYNOCODE;
  188107. }else{
  188108. while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
  188109. && (fts5yyact = fts5yy_find_reduce_action(
  188110. fts5yypParser->fts5yytos->stateno,
  188111. fts5YYERRORSYMBOL)) > fts5YY_MAX_SHIFTREDUCE
  188112. ){
  188113. fts5yy_pop_parser_stack(fts5yypParser);
  188114. }
  188115. if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
  188116. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  188117. fts5yy_parse_failed(fts5yypParser);
  188118. #ifndef fts5YYNOERRORRECOVERY
  188119. fts5yypParser->fts5yyerrcnt = -1;
  188120. #endif
  188121. fts5yymajor = fts5YYNOCODE;
  188122. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  188123. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
  188124. }
  188125. }
  188126. fts5yypParser->fts5yyerrcnt = 3;
  188127. fts5yyerrorhit = 1;
  188128. if( fts5yymajor==fts5YYNOCODE ) break;
  188129. fts5yyact = fts5yypParser->fts5yytos->stateno;
  188130. #elif defined(fts5YYNOERRORRECOVERY)
  188131. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  188132. ** do any kind of error recovery. Instead, simply invoke the syntax
  188133. ** error routine and continue going as if nothing had happened.
  188134. **
  188135. ** Applications can set this macro (for example inside %include) if
  188136. ** they intend to abandon the parse upon the first syntax error seen.
  188137. */
  188138. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  188139. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  188140. break;
  188141. #else /* fts5YYERRORSYMBOL is not defined */
  188142. /* This is what we do if the grammar does not define ERROR:
  188143. **
  188144. ** * Report an error message, and throw away the input token.
  188145. **
  188146. ** * If the input token is $, then fail the parse.
  188147. **
  188148. ** As before, subsequent error messages are suppressed until
  188149. ** three input tokens have been successfully shifted.
  188150. */
  188151. if( fts5yypParser->fts5yyerrcnt<=0 ){
  188152. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  188153. }
  188154. fts5yypParser->fts5yyerrcnt = 3;
  188155. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  188156. if( fts5yyendofinput ){
  188157. fts5yy_parse_failed(fts5yypParser);
  188158. #ifndef fts5YYNOERRORRECOVERY
  188159. fts5yypParser->fts5yyerrcnt = -1;
  188160. #endif
  188161. }
  188162. break;
  188163. #endif
  188164. }
  188165. }while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
  188166. #ifndef NDEBUG
  188167. if( fts5yyTraceFILE ){
  188168. fts5yyStackEntry *i;
  188169. char cDiv = '[';
  188170. fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
  188171. for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
  188172. fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
  188173. cDiv = ' ';
  188174. }
  188175. fprintf(fts5yyTraceFILE,"]\n");
  188176. }
  188177. #endif
  188178. return;
  188179. }
  188180. /*
  188181. ** Return the fallback token corresponding to canonical token iToken, or
  188182. ** 0 if iToken has no fallback.
  188183. */
  188184. static int sqlite3Fts5ParserFallback(int iToken){
  188185. #ifdef fts5YYFALLBACK
  188186. if( iToken<(int)(sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])) ){
  188187. return fts5yyFallback[iToken];
  188188. }
  188189. #else
  188190. (void)iToken;
  188191. #endif
  188192. return 0;
  188193. }
  188194. /*
  188195. ** 2014 May 31
  188196. **
  188197. ** The author disclaims copyright to this source code. In place of
  188198. ** a legal notice, here is a blessing:
  188199. **
  188200. ** May you do good and not evil.
  188201. ** May you find forgiveness for yourself and forgive others.
  188202. ** May you share freely, never taking more than you give.
  188203. **
  188204. ******************************************************************************
  188205. */
  188206. /* #include "fts5Int.h" */
  188207. #include <math.h> /* amalgamator: keep */
  188208. /*
  188209. ** Object used to iterate through all "coalesced phrase instances" in
  188210. ** a single column of the current row. If the phrase instances in the
  188211. ** column being considered do not overlap, this object simply iterates
  188212. ** through them. Or, if they do overlap (share one or more tokens in
  188213. ** common), each set of overlapping instances is treated as a single
  188214. ** match. See documentation for the highlight() auxiliary function for
  188215. ** details.
  188216. **
  188217. ** Usage is:
  188218. **
  188219. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  188220. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  188221. ** rc = fts5CInstIterNext(&iter)
  188222. ** ){
  188223. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  188224. ** }
  188225. **
  188226. */
  188227. typedef struct CInstIter CInstIter;
  188228. struct CInstIter {
  188229. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  188230. Fts5Context *pFts; /* First arg to pass to pApi functions */
  188231. int iCol; /* Column to search */
  188232. int iInst; /* Next phrase instance index */
  188233. int nInst; /* Total number of phrase instances */
  188234. /* Output variables */
  188235. int iStart; /* First token in coalesced phrase instance */
  188236. int iEnd; /* Last token in coalesced phrase instance */
  188237. };
  188238. /*
  188239. ** Advance the iterator to the next coalesced phrase instance. Return
  188240. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  188241. */
  188242. static int fts5CInstIterNext(CInstIter *pIter){
  188243. int rc = SQLITE_OK;
  188244. pIter->iStart = -1;
  188245. pIter->iEnd = -1;
  188246. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  188247. int ip; int ic; int io;
  188248. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  188249. if( rc==SQLITE_OK ){
  188250. if( ic==pIter->iCol ){
  188251. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  188252. if( pIter->iStart<0 ){
  188253. pIter->iStart = io;
  188254. pIter->iEnd = iEnd;
  188255. }else if( io<=pIter->iEnd ){
  188256. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  188257. }else{
  188258. break;
  188259. }
  188260. }
  188261. pIter->iInst++;
  188262. }
  188263. }
  188264. return rc;
  188265. }
  188266. /*
  188267. ** Initialize the iterator object indicated by the final parameter to
  188268. ** iterate through coalesced phrase instances in column iCol.
  188269. */
  188270. static int fts5CInstIterInit(
  188271. const Fts5ExtensionApi *pApi,
  188272. Fts5Context *pFts,
  188273. int iCol,
  188274. CInstIter *pIter
  188275. ){
  188276. int rc;
  188277. memset(pIter, 0, sizeof(CInstIter));
  188278. pIter->pApi = pApi;
  188279. pIter->pFts = pFts;
  188280. pIter->iCol = iCol;
  188281. rc = pApi->xInstCount(pFts, &pIter->nInst);
  188282. if( rc==SQLITE_OK ){
  188283. rc = fts5CInstIterNext(pIter);
  188284. }
  188285. return rc;
  188286. }
  188287. /*************************************************************************
  188288. ** Start of highlight() implementation.
  188289. */
  188290. typedef struct HighlightContext HighlightContext;
  188291. struct HighlightContext {
  188292. CInstIter iter; /* Coalesced Instance Iterator */
  188293. int iPos; /* Current token offset in zIn[] */
  188294. int iRangeStart; /* First token to include */
  188295. int iRangeEnd; /* If non-zero, last token to include */
  188296. const char *zOpen; /* Opening highlight */
  188297. const char *zClose; /* Closing highlight */
  188298. const char *zIn; /* Input text */
  188299. int nIn; /* Size of input text in bytes */
  188300. int iOff; /* Current offset within zIn[] */
  188301. char *zOut; /* Output value */
  188302. };
  188303. /*
  188304. ** Append text to the HighlightContext output string - p->zOut. Argument
  188305. ** z points to a buffer containing n bytes of text to append. If n is
  188306. ** negative, everything up until the first '\0' is appended to the output.
  188307. **
  188308. ** If *pRc is set to any value other than SQLITE_OK when this function is
  188309. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  188310. ** *pRc is set to an error code before returning.
  188311. */
  188312. static void fts5HighlightAppend(
  188313. int *pRc,
  188314. HighlightContext *p,
  188315. const char *z, int n
  188316. ){
  188317. if( *pRc==SQLITE_OK ){
  188318. if( n<0 ) n = (int)strlen(z);
  188319. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  188320. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  188321. }
  188322. }
  188323. /*
  188324. ** Tokenizer callback used by implementation of highlight() function.
  188325. */
  188326. static int fts5HighlightCb(
  188327. void *pContext, /* Pointer to HighlightContext object */
  188328. int tflags, /* Mask of FTS5_TOKEN_* flags */
  188329. const char *pToken, /* Buffer containing token */
  188330. int nToken, /* Size of token in bytes */
  188331. int iStartOff, /* Start offset of token */
  188332. int iEndOff /* End offset of token */
  188333. ){
  188334. HighlightContext *p = (HighlightContext*)pContext;
  188335. int rc = SQLITE_OK;
  188336. int iPos;
  188337. UNUSED_PARAM2(pToken, nToken);
  188338. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  188339. iPos = p->iPos++;
  188340. if( p->iRangeEnd>0 ){
  188341. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  188342. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  188343. }
  188344. if( iPos==p->iter.iStart ){
  188345. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  188346. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  188347. p->iOff = iStartOff;
  188348. }
  188349. if( iPos==p->iter.iEnd ){
  188350. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  188351. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  188352. }
  188353. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  188354. fts5HighlightAppend(&rc, p, p->zClose, -1);
  188355. p->iOff = iEndOff;
  188356. if( rc==SQLITE_OK ){
  188357. rc = fts5CInstIterNext(&p->iter);
  188358. }
  188359. }
  188360. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  188361. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  188362. p->iOff = iEndOff;
  188363. if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
  188364. fts5HighlightAppend(&rc, p, p->zClose, -1);
  188365. }
  188366. }
  188367. return rc;
  188368. }
  188369. /*
  188370. ** Implementation of highlight() function.
  188371. */
  188372. static void fts5HighlightFunction(
  188373. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  188374. Fts5Context *pFts, /* First arg to pass to pApi functions */
  188375. sqlite3_context *pCtx, /* Context for returning result/error */
  188376. int nVal, /* Number of values in apVal[] array */
  188377. sqlite3_value **apVal /* Array of trailing arguments */
  188378. ){
  188379. HighlightContext ctx;
  188380. int rc;
  188381. int iCol;
  188382. if( nVal!=3 ){
  188383. const char *zErr = "wrong number of arguments to function highlight()";
  188384. sqlite3_result_error(pCtx, zErr, -1);
  188385. return;
  188386. }
  188387. iCol = sqlite3_value_int(apVal[0]);
  188388. memset(&ctx, 0, sizeof(HighlightContext));
  188389. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  188390. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  188391. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  188392. if( ctx.zIn ){
  188393. if( rc==SQLITE_OK ){
  188394. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  188395. }
  188396. if( rc==SQLITE_OK ){
  188397. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  188398. }
  188399. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  188400. if( rc==SQLITE_OK ){
  188401. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  188402. }
  188403. sqlite3_free(ctx.zOut);
  188404. }
  188405. if( rc!=SQLITE_OK ){
  188406. sqlite3_result_error_code(pCtx, rc);
  188407. }
  188408. }
  188409. /*
  188410. ** End of highlight() implementation.
  188411. **************************************************************************/
  188412. /*
  188413. ** Context object passed to the fts5SentenceFinderCb() function.
  188414. */
  188415. typedef struct Fts5SFinder Fts5SFinder;
  188416. struct Fts5SFinder {
  188417. int iPos; /* Current token position */
  188418. int nFirstAlloc; /* Allocated size of aFirst[] */
  188419. int nFirst; /* Number of entries in aFirst[] */
  188420. int *aFirst; /* Array of first token in each sentence */
  188421. const char *zDoc; /* Document being tokenized */
  188422. };
  188423. /*
  188424. ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
  188425. ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
  188426. ** error occurs.
  188427. */
  188428. static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
  188429. if( p->nFirstAlloc==p->nFirst ){
  188430. int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
  188431. int *aNew;
  188432. aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
  188433. if( aNew==0 ) return SQLITE_NOMEM;
  188434. p->aFirst = aNew;
  188435. p->nFirstAlloc = nNew;
  188436. }
  188437. p->aFirst[p->nFirst++] = iAdd;
  188438. return SQLITE_OK;
  188439. }
  188440. /*
  188441. ** This function is an xTokenize() callback used by the auxiliary snippet()
  188442. ** function. Its job is to identify tokens that are the first in a sentence.
  188443. ** For each such token, an entry is added to the SFinder.aFirst[] array.
  188444. */
  188445. static int fts5SentenceFinderCb(
  188446. void *pContext, /* Pointer to HighlightContext object */
  188447. int tflags, /* Mask of FTS5_TOKEN_* flags */
  188448. const char *pToken, /* Buffer containing token */
  188449. int nToken, /* Size of token in bytes */
  188450. int iStartOff, /* Start offset of token */
  188451. int iEndOff /* End offset of token */
  188452. ){
  188453. int rc = SQLITE_OK;
  188454. UNUSED_PARAM2(pToken, nToken);
  188455. UNUSED_PARAM(iEndOff);
  188456. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  188457. Fts5SFinder *p = (Fts5SFinder*)pContext;
  188458. if( p->iPos>0 ){
  188459. int i;
  188460. char c = 0;
  188461. for(i=iStartOff-1; i>=0; i--){
  188462. c = p->zDoc[i];
  188463. if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
  188464. }
  188465. if( i!=iStartOff-1 && (c=='.' || c==':') ){
  188466. rc = fts5SentenceFinderAdd(p, p->iPos);
  188467. }
  188468. }else{
  188469. rc = fts5SentenceFinderAdd(p, 0);
  188470. }
  188471. p->iPos++;
  188472. }
  188473. return rc;
  188474. }
  188475. static int fts5SnippetScore(
  188476. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  188477. Fts5Context *pFts, /* First arg to pass to pApi functions */
  188478. int nDocsize, /* Size of column in tokens */
  188479. unsigned char *aSeen, /* Array with one element per query phrase */
  188480. int iCol, /* Column to score */
  188481. int iPos, /* Starting offset to score */
  188482. int nToken, /* Max tokens per snippet */
  188483. int *pnScore, /* OUT: Score */
  188484. int *piPos /* OUT: Adjusted offset */
  188485. ){
  188486. int rc;
  188487. int i;
  188488. int ip = 0;
  188489. int ic = 0;
  188490. int iOff = 0;
  188491. int iFirst = -1;
  188492. int nInst;
  188493. int nScore = 0;
  188494. int iLast = 0;
  188495. rc = pApi->xInstCount(pFts, &nInst);
  188496. for(i=0; i<nInst && rc==SQLITE_OK; i++){
  188497. rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
  188498. if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
  188499. nScore += (aSeen[ip] ? 1 : 1000);
  188500. aSeen[ip] = 1;
  188501. if( iFirst<0 ) iFirst = iOff;
  188502. iLast = iOff + pApi->xPhraseSize(pFts, ip);
  188503. }
  188504. }
  188505. *pnScore = nScore;
  188506. if( piPos ){
  188507. int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
  188508. if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
  188509. if( iAdj<0 ) iAdj = 0;
  188510. *piPos = iAdj;
  188511. }
  188512. return rc;
  188513. }
  188514. /*
  188515. ** Return the value in pVal interpreted as utf-8 text. Except, if pVal
  188516. ** contains a NULL value, return a pointer to a static string zero
  188517. ** bytes in length instead of a NULL pointer.
  188518. */
  188519. static const char *fts5ValueToText(sqlite3_value *pVal){
  188520. const char *zRet = (const char*)sqlite3_value_text(pVal);
  188521. return zRet ? zRet : "";
  188522. }
  188523. /*
  188524. ** Implementation of snippet() function.
  188525. */
  188526. static void fts5SnippetFunction(
  188527. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  188528. Fts5Context *pFts, /* First arg to pass to pApi functions */
  188529. sqlite3_context *pCtx, /* Context for returning result/error */
  188530. int nVal, /* Number of values in apVal[] array */
  188531. sqlite3_value **apVal /* Array of trailing arguments */
  188532. ){
  188533. HighlightContext ctx;
  188534. int rc = SQLITE_OK; /* Return code */
  188535. int iCol; /* 1st argument to snippet() */
  188536. const char *zEllips; /* 4th argument to snippet() */
  188537. int nToken; /* 5th argument to snippet() */
  188538. int nInst = 0; /* Number of instance matches this row */
  188539. int i; /* Used to iterate through instances */
  188540. int nPhrase; /* Number of phrases in query */
  188541. unsigned char *aSeen; /* Array of "seen instance" flags */
  188542. int iBestCol; /* Column containing best snippet */
  188543. int iBestStart = 0; /* First token of best snippet */
  188544. int nBestScore = 0; /* Score of best snippet */
  188545. int nColSize = 0; /* Total size of iBestCol in tokens */
  188546. Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
  188547. int nCol;
  188548. if( nVal!=5 ){
  188549. const char *zErr = "wrong number of arguments to function snippet()";
  188550. sqlite3_result_error(pCtx, zErr, -1);
  188551. return;
  188552. }
  188553. nCol = pApi->xColumnCount(pFts);
  188554. memset(&ctx, 0, sizeof(HighlightContext));
  188555. iCol = sqlite3_value_int(apVal[0]);
  188556. ctx.zOpen = fts5ValueToText(apVal[1]);
  188557. ctx.zClose = fts5ValueToText(apVal[2]);
  188558. zEllips = fts5ValueToText(apVal[3]);
  188559. nToken = sqlite3_value_int(apVal[4]);
  188560. iBestCol = (iCol>=0 ? iCol : 0);
  188561. nPhrase = pApi->xPhraseCount(pFts);
  188562. aSeen = sqlite3_malloc(nPhrase);
  188563. if( aSeen==0 ){
  188564. rc = SQLITE_NOMEM;
  188565. }
  188566. if( rc==SQLITE_OK ){
  188567. rc = pApi->xInstCount(pFts, &nInst);
  188568. }
  188569. memset(&sFinder, 0, sizeof(Fts5SFinder));
  188570. for(i=0; i<nCol; i++){
  188571. if( iCol<0 || iCol==i ){
  188572. int nDoc;
  188573. int nDocsize;
  188574. int ii;
  188575. sFinder.iPos = 0;
  188576. sFinder.nFirst = 0;
  188577. rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
  188578. if( rc!=SQLITE_OK ) break;
  188579. rc = pApi->xTokenize(pFts,
  188580. sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
  188581. );
  188582. if( rc!=SQLITE_OK ) break;
  188583. rc = pApi->xColumnSize(pFts, i, &nDocsize);
  188584. if( rc!=SQLITE_OK ) break;
  188585. for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
  188586. int ip, ic, io;
  188587. int iAdj;
  188588. int nScore;
  188589. int jj;
  188590. rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
  188591. if( ic!=i || rc!=SQLITE_OK ) continue;
  188592. memset(aSeen, 0, nPhrase);
  188593. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  188594. io, nToken, &nScore, &iAdj
  188595. );
  188596. if( rc==SQLITE_OK && nScore>nBestScore ){
  188597. nBestScore = nScore;
  188598. iBestCol = i;
  188599. iBestStart = iAdj;
  188600. nColSize = nDocsize;
  188601. }
  188602. if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
  188603. for(jj=0; jj<(sFinder.nFirst-1); jj++){
  188604. if( sFinder.aFirst[jj+1]>io ) break;
  188605. }
  188606. if( sFinder.aFirst[jj]<io ){
  188607. memset(aSeen, 0, nPhrase);
  188608. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  188609. sFinder.aFirst[jj], nToken, &nScore, 0
  188610. );
  188611. nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
  188612. if( rc==SQLITE_OK && nScore>nBestScore ){
  188613. nBestScore = nScore;
  188614. iBestCol = i;
  188615. iBestStart = sFinder.aFirst[jj];
  188616. nColSize = nDocsize;
  188617. }
  188618. }
  188619. }
  188620. }
  188621. }
  188622. }
  188623. if( rc==SQLITE_OK ){
  188624. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  188625. }
  188626. if( rc==SQLITE_OK && nColSize==0 ){
  188627. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  188628. }
  188629. if( ctx.zIn ){
  188630. if( rc==SQLITE_OK ){
  188631. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  188632. }
  188633. ctx.iRangeStart = iBestStart;
  188634. ctx.iRangeEnd = iBestStart + nToken - 1;
  188635. if( iBestStart>0 ){
  188636. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  188637. }
  188638. /* Advance iterator ctx.iter so that it points to the first coalesced
  188639. ** phrase instance at or following position iBestStart. */
  188640. while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
  188641. rc = fts5CInstIterNext(&ctx.iter);
  188642. }
  188643. if( rc==SQLITE_OK ){
  188644. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  188645. }
  188646. if( ctx.iRangeEnd>=(nColSize-1) ){
  188647. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  188648. }else{
  188649. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  188650. }
  188651. }
  188652. if( rc==SQLITE_OK ){
  188653. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  188654. }else{
  188655. sqlite3_result_error_code(pCtx, rc);
  188656. }
  188657. sqlite3_free(ctx.zOut);
  188658. sqlite3_free(aSeen);
  188659. sqlite3_free(sFinder.aFirst);
  188660. }
  188661. /************************************************************************/
  188662. /*
  188663. ** The first time the bm25() function is called for a query, an instance
  188664. ** of the following structure is allocated and populated.
  188665. */
  188666. typedef struct Fts5Bm25Data Fts5Bm25Data;
  188667. struct Fts5Bm25Data {
  188668. int nPhrase; /* Number of phrases in query */
  188669. double avgdl; /* Average number of tokens in each row */
  188670. double *aIDF; /* IDF for each phrase */
  188671. double *aFreq; /* Array used to calculate phrase freq. */
  188672. };
  188673. /*
  188674. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  188675. ** table matched by each individual phrase within the query.
  188676. */
  188677. static int fts5CountCb(
  188678. const Fts5ExtensionApi *pApi,
  188679. Fts5Context *pFts,
  188680. void *pUserData /* Pointer to sqlite3_int64 variable */
  188681. ){
  188682. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  188683. UNUSED_PARAM2(pApi, pFts);
  188684. (*pn)++;
  188685. return SQLITE_OK;
  188686. }
  188687. /*
  188688. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  188689. ** If the object has not already been allocated, allocate and populate it
  188690. ** now.
  188691. */
  188692. static int fts5Bm25GetData(
  188693. const Fts5ExtensionApi *pApi,
  188694. Fts5Context *pFts,
  188695. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  188696. ){
  188697. int rc = SQLITE_OK; /* Return code */
  188698. Fts5Bm25Data *p; /* Object to return */
  188699. p = pApi->xGetAuxdata(pFts, 0);
  188700. if( p==0 ){
  188701. int nPhrase; /* Number of phrases in query */
  188702. sqlite3_int64 nRow = 0; /* Number of rows in table */
  188703. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  188704. int nByte; /* Bytes of space to allocate */
  188705. int i;
  188706. /* Allocate the Fts5Bm25Data object */
  188707. nPhrase = pApi->xPhraseCount(pFts);
  188708. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  188709. p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
  188710. if( p==0 ){
  188711. rc = SQLITE_NOMEM;
  188712. }else{
  188713. memset(p, 0, nByte);
  188714. p->nPhrase = nPhrase;
  188715. p->aIDF = (double*)&p[1];
  188716. p->aFreq = &p->aIDF[nPhrase];
  188717. }
  188718. /* Calculate the average document length for this FTS5 table */
  188719. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  188720. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  188721. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  188722. /* Calculate an IDF for each phrase in the query */
  188723. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  188724. sqlite3_int64 nHit = 0;
  188725. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  188726. if( rc==SQLITE_OK ){
  188727. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  188728. ** This is done using the standard BM25 formula as found on wikipedia:
  188729. **
  188730. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  188731. **
  188732. ** where "N" is the total number of documents in the set and nHit
  188733. ** is the number that contain at least one instance of the phrase
  188734. ** under consideration.
  188735. **
  188736. ** The problem with this is that if (N < 2*nHit), the IDF is
  188737. ** negative. Which is undesirable. So the mimimum allowable IDF is
  188738. ** (1e-6) - roughly the same as a term that appears in just over
  188739. ** half of set of 5,000,000 documents. */
  188740. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  188741. if( idf<=0.0 ) idf = 1e-6;
  188742. p->aIDF[i] = idf;
  188743. }
  188744. }
  188745. if( rc!=SQLITE_OK ){
  188746. sqlite3_free(p);
  188747. }else{
  188748. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  188749. }
  188750. if( rc!=SQLITE_OK ) p = 0;
  188751. }
  188752. *ppData = p;
  188753. return rc;
  188754. }
  188755. /*
  188756. ** Implementation of bm25() function.
  188757. */
  188758. static void fts5Bm25Function(
  188759. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  188760. Fts5Context *pFts, /* First arg to pass to pApi functions */
  188761. sqlite3_context *pCtx, /* Context for returning result/error */
  188762. int nVal, /* Number of values in apVal[] array */
  188763. sqlite3_value **apVal /* Array of trailing arguments */
  188764. ){
  188765. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  188766. const double b = 0.75; /* Constant "b" from BM25 formula */
  188767. int rc = SQLITE_OK; /* Error code */
  188768. double score = 0.0; /* SQL function return value */
  188769. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  188770. int i; /* Iterator variable */
  188771. int nInst = 0; /* Value returned by xInstCount() */
  188772. double D = 0.0; /* Total number of tokens in row */
  188773. double *aFreq = 0; /* Array of phrase freq. for current row */
  188774. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  188775. ** for each phrase in the query for the current row. */
  188776. rc = fts5Bm25GetData(pApi, pFts, &pData);
  188777. if( rc==SQLITE_OK ){
  188778. aFreq = pData->aFreq;
  188779. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  188780. rc = pApi->xInstCount(pFts, &nInst);
  188781. }
  188782. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  188783. int ip; int ic; int io;
  188784. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  188785. if( rc==SQLITE_OK ){
  188786. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  188787. aFreq[ip] += w;
  188788. }
  188789. }
  188790. /* Figure out the total size of the current row in tokens. */
  188791. if( rc==SQLITE_OK ){
  188792. int nTok;
  188793. rc = pApi->xColumnSize(pFts, -1, &nTok);
  188794. D = (double)nTok;
  188795. }
  188796. /* Determine the BM25 score for the current row. */
  188797. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  188798. score += pData->aIDF[i] * (
  188799. ( aFreq[i] * (k1 + 1.0) ) /
  188800. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  188801. );
  188802. }
  188803. /* If no error has occurred, return the calculated score. Otherwise,
  188804. ** throw an SQL exception. */
  188805. if( rc==SQLITE_OK ){
  188806. sqlite3_result_double(pCtx, -1.0 * score);
  188807. }else{
  188808. sqlite3_result_error_code(pCtx, rc);
  188809. }
  188810. }
  188811. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  188812. struct Builtin {
  188813. const char *zFunc; /* Function name (nul-terminated) */
  188814. void *pUserData; /* User-data pointer */
  188815. fts5_extension_function xFunc;/* Callback function */
  188816. void (*xDestroy)(void*); /* Destructor function */
  188817. } aBuiltin [] = {
  188818. { "snippet", 0, fts5SnippetFunction, 0 },
  188819. { "highlight", 0, fts5HighlightFunction, 0 },
  188820. { "bm25", 0, fts5Bm25Function, 0 },
  188821. };
  188822. int rc = SQLITE_OK; /* Return code */
  188823. int i; /* To iterate through builtin functions */
  188824. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  188825. rc = pApi->xCreateFunction(pApi,
  188826. aBuiltin[i].zFunc,
  188827. aBuiltin[i].pUserData,
  188828. aBuiltin[i].xFunc,
  188829. aBuiltin[i].xDestroy
  188830. );
  188831. }
  188832. return rc;
  188833. }
  188834. /*
  188835. ** 2014 May 31
  188836. **
  188837. ** The author disclaims copyright to this source code. In place of
  188838. ** a legal notice, here is a blessing:
  188839. **
  188840. ** May you do good and not evil.
  188841. ** May you find forgiveness for yourself and forgive others.
  188842. ** May you share freely, never taking more than you give.
  188843. **
  188844. ******************************************************************************
  188845. */
  188846. /* #include "fts5Int.h" */
  188847. static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
  188848. if( (u32)pBuf->nSpace<nByte ){
  188849. u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
  188850. u8 *pNew;
  188851. while( nNew<nByte ){
  188852. nNew = nNew * 2;
  188853. }
  188854. pNew = sqlite3_realloc(pBuf->p, nNew);
  188855. if( pNew==0 ){
  188856. *pRc = SQLITE_NOMEM;
  188857. return 1;
  188858. }else{
  188859. pBuf->nSpace = nNew;
  188860. pBuf->p = pNew;
  188861. }
  188862. }
  188863. return 0;
  188864. }
  188865. /*
  188866. ** Encode value iVal as an SQLite varint and append it to the buffer object
  188867. ** pBuf. If an OOM error occurs, set the error code in p.
  188868. */
  188869. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  188870. if( fts5BufferGrow(pRc, pBuf, 9) ) return;
  188871. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  188872. }
  188873. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  188874. aBuf[0] = (iVal>>24) & 0x00FF;
  188875. aBuf[1] = (iVal>>16) & 0x00FF;
  188876. aBuf[2] = (iVal>> 8) & 0x00FF;
  188877. aBuf[3] = (iVal>> 0) & 0x00FF;
  188878. }
  188879. static int sqlite3Fts5Get32(const u8 *aBuf){
  188880. return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
  188881. }
  188882. /*
  188883. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  188884. ** the error code in p. If an error has already occurred when this function
  188885. ** is called, it is a no-op.
  188886. */
  188887. static void sqlite3Fts5BufferAppendBlob(
  188888. int *pRc,
  188889. Fts5Buffer *pBuf,
  188890. u32 nData,
  188891. const u8 *pData
  188892. ){
  188893. assert_nc( *pRc || nData>=0 );
  188894. if( nData ){
  188895. if( fts5BufferGrow(pRc, pBuf, nData) ) return;
  188896. memcpy(&pBuf->p[pBuf->n], pData, nData);
  188897. pBuf->n += nData;
  188898. }
  188899. }
  188900. /*
  188901. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  188902. ** ensures that the byte following the buffer data is set to 0x00, even
  188903. ** though this byte is not included in the pBuf->n count.
  188904. */
  188905. static void sqlite3Fts5BufferAppendString(
  188906. int *pRc,
  188907. Fts5Buffer *pBuf,
  188908. const char *zStr
  188909. ){
  188910. int nStr = (int)strlen(zStr);
  188911. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  188912. pBuf->n--;
  188913. }
  188914. /*
  188915. ** Argument zFmt is a printf() style format string. This function performs
  188916. ** the printf() style processing, then appends the results to buffer pBuf.
  188917. **
  188918. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  188919. ** following the buffer data is set to 0x00, even though this byte is not
  188920. ** included in the pBuf->n count.
  188921. */
  188922. static void sqlite3Fts5BufferAppendPrintf(
  188923. int *pRc,
  188924. Fts5Buffer *pBuf,
  188925. char *zFmt, ...
  188926. ){
  188927. if( *pRc==SQLITE_OK ){
  188928. char *zTmp;
  188929. va_list ap;
  188930. va_start(ap, zFmt);
  188931. zTmp = sqlite3_vmprintf(zFmt, ap);
  188932. va_end(ap);
  188933. if( zTmp==0 ){
  188934. *pRc = SQLITE_NOMEM;
  188935. }else{
  188936. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  188937. sqlite3_free(zTmp);
  188938. }
  188939. }
  188940. }
  188941. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  188942. char *zRet = 0;
  188943. if( *pRc==SQLITE_OK ){
  188944. va_list ap;
  188945. va_start(ap, zFmt);
  188946. zRet = sqlite3_vmprintf(zFmt, ap);
  188947. va_end(ap);
  188948. if( zRet==0 ){
  188949. *pRc = SQLITE_NOMEM;
  188950. }
  188951. }
  188952. return zRet;
  188953. }
  188954. /*
  188955. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  188956. */
  188957. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  188958. sqlite3_free(pBuf->p);
  188959. memset(pBuf, 0, sizeof(Fts5Buffer));
  188960. }
  188961. /*
  188962. ** Zero the contents of the buffer object. But do not free the associated
  188963. ** memory allocation.
  188964. */
  188965. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  188966. pBuf->n = 0;
  188967. }
  188968. /*
  188969. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  188970. ** the error code in p. If an error has already occurred when this function
  188971. ** is called, it is a no-op.
  188972. */
  188973. static void sqlite3Fts5BufferSet(
  188974. int *pRc,
  188975. Fts5Buffer *pBuf,
  188976. int nData,
  188977. const u8 *pData
  188978. ){
  188979. pBuf->n = 0;
  188980. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  188981. }
  188982. static int sqlite3Fts5PoslistNext64(
  188983. const u8 *a, int n, /* Buffer containing poslist */
  188984. int *pi, /* IN/OUT: Offset within a[] */
  188985. i64 *piOff /* IN/OUT: Current offset */
  188986. ){
  188987. int i = *pi;
  188988. if( i>=n ){
  188989. /* EOF */
  188990. *piOff = -1;
  188991. return 1;
  188992. }else{
  188993. i64 iOff = *piOff;
  188994. int iVal;
  188995. fts5FastGetVarint32(a, i, iVal);
  188996. if( iVal==1 ){
  188997. fts5FastGetVarint32(a, i, iVal);
  188998. iOff = ((i64)iVal) << 32;
  188999. fts5FastGetVarint32(a, i, iVal);
  189000. }
  189001. *piOff = iOff + (iVal-2);
  189002. *pi = i;
  189003. return 0;
  189004. }
  189005. }
  189006. /*
  189007. ** Advance the iterator object passed as the only argument. Return true
  189008. ** if the iterator reaches EOF, or false otherwise.
  189009. */
  189010. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  189011. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  189012. pIter->bEof = 1;
  189013. }
  189014. return pIter->bEof;
  189015. }
  189016. static int sqlite3Fts5PoslistReaderInit(
  189017. const u8 *a, int n, /* Poslist buffer to iterate through */
  189018. Fts5PoslistReader *pIter /* Iterator object to initialize */
  189019. ){
  189020. memset(pIter, 0, sizeof(*pIter));
  189021. pIter->a = a;
  189022. pIter->n = n;
  189023. sqlite3Fts5PoslistReaderNext(pIter);
  189024. return pIter->bEof;
  189025. }
  189026. /*
  189027. ** Append position iPos to the position list being accumulated in buffer
  189028. ** pBuf, which must be already be large enough to hold the new data.
  189029. ** The previous position written to this list is *piPrev. *piPrev is set
  189030. ** to iPos before returning.
  189031. */
  189032. static void sqlite3Fts5PoslistSafeAppend(
  189033. Fts5Buffer *pBuf,
  189034. i64 *piPrev,
  189035. i64 iPos
  189036. ){
  189037. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  189038. if( (iPos & colmask) != (*piPrev & colmask) ){
  189039. pBuf->p[pBuf->n++] = 1;
  189040. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  189041. *piPrev = (iPos & colmask);
  189042. }
  189043. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
  189044. *piPrev = iPos;
  189045. }
  189046. static int sqlite3Fts5PoslistWriterAppend(
  189047. Fts5Buffer *pBuf,
  189048. Fts5PoslistWriter *pWriter,
  189049. i64 iPos
  189050. ){
  189051. int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
  189052. if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
  189053. sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
  189054. return SQLITE_OK;
  189055. }
  189056. static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
  189057. void *pRet = 0;
  189058. if( *pRc==SQLITE_OK ){
  189059. pRet = sqlite3_malloc(nByte);
  189060. if( pRet==0 ){
  189061. if( nByte>0 ) *pRc = SQLITE_NOMEM;
  189062. }else{
  189063. memset(pRet, 0, nByte);
  189064. }
  189065. }
  189066. return pRet;
  189067. }
  189068. /*
  189069. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  189070. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  189071. ** the length of the string is determined using strlen().
  189072. **
  189073. ** It is the responsibility of the caller to eventually free the returned
  189074. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  189075. */
  189076. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  189077. char *zRet = 0;
  189078. if( *pRc==SQLITE_OK ){
  189079. if( nIn<0 ){
  189080. nIn = (int)strlen(pIn);
  189081. }
  189082. zRet = (char*)sqlite3_malloc(nIn+1);
  189083. if( zRet ){
  189084. memcpy(zRet, pIn, nIn);
  189085. zRet[nIn] = '\0';
  189086. }else{
  189087. *pRc = SQLITE_NOMEM;
  189088. }
  189089. }
  189090. return zRet;
  189091. }
  189092. /*
  189093. ** Return true if character 't' may be part of an FTS5 bareword, or false
  189094. ** otherwise. Characters that may be part of barewords:
  189095. **
  189096. ** * All non-ASCII characters,
  189097. ** * The 52 upper and lower case ASCII characters, and
  189098. ** * The 10 integer ASCII characters.
  189099. ** * The underscore character "_" (0x5F).
  189100. ** * The unicode "subsitute" character (0x1A).
  189101. */
  189102. static int sqlite3Fts5IsBareword(char t){
  189103. u8 aBareword[128] = {
  189104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  189105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  189106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  189107. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  189108. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  189109. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  189110. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  189111. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  189112. };
  189113. return (t & 0x80) || aBareword[(int)t];
  189114. }
  189115. /*************************************************************************
  189116. */
  189117. typedef struct Fts5TermsetEntry Fts5TermsetEntry;
  189118. struct Fts5TermsetEntry {
  189119. char *pTerm;
  189120. int nTerm;
  189121. int iIdx; /* Index (main or aPrefix[] entry) */
  189122. Fts5TermsetEntry *pNext;
  189123. };
  189124. struct Fts5Termset {
  189125. Fts5TermsetEntry *apHash[512];
  189126. };
  189127. static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
  189128. int rc = SQLITE_OK;
  189129. *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
  189130. return rc;
  189131. }
  189132. static int sqlite3Fts5TermsetAdd(
  189133. Fts5Termset *p,
  189134. int iIdx,
  189135. const char *pTerm, int nTerm,
  189136. int *pbPresent
  189137. ){
  189138. int rc = SQLITE_OK;
  189139. *pbPresent = 0;
  189140. if( p ){
  189141. int i;
  189142. u32 hash = 13;
  189143. Fts5TermsetEntry *pEntry;
  189144. /* Calculate a hash value for this term. This is the same hash checksum
  189145. ** used by the fts5_hash.c module. This is not important for correct
  189146. ** operation of the module, but is necessary to ensure that some tests
  189147. ** designed to produce hash table collisions really do work. */
  189148. for(i=nTerm-1; i>=0; i--){
  189149. hash = (hash << 3) ^ hash ^ pTerm[i];
  189150. }
  189151. hash = (hash << 3) ^ hash ^ iIdx;
  189152. hash = hash % ArraySize(p->apHash);
  189153. for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
  189154. if( pEntry->iIdx==iIdx
  189155. && pEntry->nTerm==nTerm
  189156. && memcmp(pEntry->pTerm, pTerm, nTerm)==0
  189157. ){
  189158. *pbPresent = 1;
  189159. break;
  189160. }
  189161. }
  189162. if( pEntry==0 ){
  189163. pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
  189164. if( pEntry ){
  189165. pEntry->pTerm = (char*)&pEntry[1];
  189166. pEntry->nTerm = nTerm;
  189167. pEntry->iIdx = iIdx;
  189168. memcpy(pEntry->pTerm, pTerm, nTerm);
  189169. pEntry->pNext = p->apHash[hash];
  189170. p->apHash[hash] = pEntry;
  189171. }
  189172. }
  189173. }
  189174. return rc;
  189175. }
  189176. static void sqlite3Fts5TermsetFree(Fts5Termset *p){
  189177. if( p ){
  189178. u32 i;
  189179. for(i=0; i<ArraySize(p->apHash); i++){
  189180. Fts5TermsetEntry *pEntry = p->apHash[i];
  189181. while( pEntry ){
  189182. Fts5TermsetEntry *pDel = pEntry;
  189183. pEntry = pEntry->pNext;
  189184. sqlite3_free(pDel);
  189185. }
  189186. }
  189187. sqlite3_free(p);
  189188. }
  189189. }
  189190. /*
  189191. ** 2014 Jun 09
  189192. **
  189193. ** The author disclaims copyright to this source code. In place of
  189194. ** a legal notice, here is a blessing:
  189195. **
  189196. ** May you do good and not evil.
  189197. ** May you find forgiveness for yourself and forgive others.
  189198. ** May you share freely, never taking more than you give.
  189199. **
  189200. ******************************************************************************
  189201. **
  189202. ** This is an SQLite module implementing full-text search.
  189203. */
  189204. /* #include "fts5Int.h" */
  189205. #define FTS5_DEFAULT_PAGE_SIZE 4050
  189206. #define FTS5_DEFAULT_AUTOMERGE 4
  189207. #define FTS5_DEFAULT_USERMERGE 4
  189208. #define FTS5_DEFAULT_CRISISMERGE 16
  189209. #define FTS5_DEFAULT_HASHSIZE (1024*1024)
  189210. /* Maximum allowed page size */
  189211. #define FTS5_MAX_PAGE_SIZE (128*1024)
  189212. static int fts5_iswhitespace(char x){
  189213. return (x==' ');
  189214. }
  189215. static int fts5_isopenquote(char x){
  189216. return (x=='"' || x=='\'' || x=='[' || x=='`');
  189217. }
  189218. /*
  189219. ** Argument pIn points to a character that is part of a nul-terminated
  189220. ** string. Return a pointer to the first character following *pIn in
  189221. ** the string that is not a white-space character.
  189222. */
  189223. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  189224. const char *p = pIn;
  189225. if( p ){
  189226. while( fts5_iswhitespace(*p) ){ p++; }
  189227. }
  189228. return p;
  189229. }
  189230. /*
  189231. ** Argument pIn points to a character that is part of a nul-terminated
  189232. ** string. Return a pointer to the first character following *pIn in
  189233. ** the string that is not a "bareword" character.
  189234. */
  189235. static const char *fts5ConfigSkipBareword(const char *pIn){
  189236. const char *p = pIn;
  189237. while ( sqlite3Fts5IsBareword(*p) ) p++;
  189238. if( p==pIn ) p = 0;
  189239. return p;
  189240. }
  189241. static int fts5_isdigit(char a){
  189242. return (a>='0' && a<='9');
  189243. }
  189244. static const char *fts5ConfigSkipLiteral(const char *pIn){
  189245. const char *p = pIn;
  189246. switch( *p ){
  189247. case 'n': case 'N':
  189248. if( sqlite3_strnicmp("null", p, 4)==0 ){
  189249. p = &p[4];
  189250. }else{
  189251. p = 0;
  189252. }
  189253. break;
  189254. case 'x': case 'X':
  189255. p++;
  189256. if( *p=='\'' ){
  189257. p++;
  189258. while( (*p>='a' && *p<='f')
  189259. || (*p>='A' && *p<='F')
  189260. || (*p>='0' && *p<='9')
  189261. ){
  189262. p++;
  189263. }
  189264. if( *p=='\'' && 0==((p-pIn)%2) ){
  189265. p++;
  189266. }else{
  189267. p = 0;
  189268. }
  189269. }else{
  189270. p = 0;
  189271. }
  189272. break;
  189273. case '\'':
  189274. p++;
  189275. while( p ){
  189276. if( *p=='\'' ){
  189277. p++;
  189278. if( *p!='\'' ) break;
  189279. }
  189280. p++;
  189281. if( *p==0 ) p = 0;
  189282. }
  189283. break;
  189284. default:
  189285. /* maybe a number */
  189286. if( *p=='+' || *p=='-' ) p++;
  189287. while( fts5_isdigit(*p) ) p++;
  189288. /* At this point, if the literal was an integer, the parse is
  189289. ** finished. Or, if it is a floating point value, it may continue
  189290. ** with either a decimal point or an 'E' character. */
  189291. if( *p=='.' && fts5_isdigit(p[1]) ){
  189292. p += 2;
  189293. while( fts5_isdigit(*p) ) p++;
  189294. }
  189295. if( p==pIn ) p = 0;
  189296. break;
  189297. }
  189298. return p;
  189299. }
  189300. /*
  189301. ** The first character of the string pointed to by argument z is guaranteed
  189302. ** to be an open-quote character (see function fts5_isopenquote()).
  189303. **
  189304. ** This function searches for the corresponding close-quote character within
  189305. ** the string and, if found, dequotes the string in place and adds a new
  189306. ** nul-terminator byte.
  189307. **
  189308. ** If the close-quote is found, the value returned is the byte offset of
  189309. ** the character immediately following it. Or, if the close-quote is not
  189310. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  189311. ** undefined state.
  189312. */
  189313. static int fts5Dequote(char *z){
  189314. char q;
  189315. int iIn = 1;
  189316. int iOut = 0;
  189317. q = z[0];
  189318. /* Set stack variable q to the close-quote character */
  189319. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  189320. if( q=='[' ) q = ']';
  189321. while( ALWAYS(z[iIn]) ){
  189322. if( z[iIn]==q ){
  189323. if( z[iIn+1]!=q ){
  189324. /* Character iIn was the close quote. */
  189325. iIn++;
  189326. break;
  189327. }else{
  189328. /* Character iIn and iIn+1 form an escaped quote character. Skip
  189329. ** the input cursor past both and copy a single quote character
  189330. ** to the output buffer. */
  189331. iIn += 2;
  189332. z[iOut++] = q;
  189333. }
  189334. }else{
  189335. z[iOut++] = z[iIn++];
  189336. }
  189337. }
  189338. z[iOut] = '\0';
  189339. return iIn;
  189340. }
  189341. /*
  189342. ** Convert an SQL-style quoted string into a normal string by removing
  189343. ** the quote characters. The conversion is done in-place. If the
  189344. ** input does not begin with a quote character, then this routine
  189345. ** is a no-op.
  189346. **
  189347. ** Examples:
  189348. **
  189349. ** "abc" becomes abc
  189350. ** 'xyz' becomes xyz
  189351. ** [pqr] becomes pqr
  189352. ** `mno` becomes mno
  189353. */
  189354. static void sqlite3Fts5Dequote(char *z){
  189355. char quote; /* Quote character (if any ) */
  189356. assert( 0==fts5_iswhitespace(z[0]) );
  189357. quote = z[0];
  189358. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  189359. fts5Dequote(z);
  189360. }
  189361. }
  189362. struct Fts5Enum {
  189363. const char *zName;
  189364. int eVal;
  189365. };
  189366. typedef struct Fts5Enum Fts5Enum;
  189367. static int fts5ConfigSetEnum(
  189368. const Fts5Enum *aEnum,
  189369. const char *zEnum,
  189370. int *peVal
  189371. ){
  189372. int nEnum = (int)strlen(zEnum);
  189373. int i;
  189374. int iVal = -1;
  189375. for(i=0; aEnum[i].zName; i++){
  189376. if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
  189377. if( iVal>=0 ) return SQLITE_ERROR;
  189378. iVal = aEnum[i].eVal;
  189379. }
  189380. }
  189381. *peVal = iVal;
  189382. return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
  189383. }
  189384. /*
  189385. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  189386. ** configuration object pConfig as appropriate.
  189387. **
  189388. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  189389. ** an error occurs, an SQLite error code is returned and an error message
  189390. ** may be left in *pzErr. It is the responsibility of the caller to
  189391. ** eventually free any such error message using sqlite3_free().
  189392. */
  189393. static int fts5ConfigParseSpecial(
  189394. Fts5Global *pGlobal,
  189395. Fts5Config *pConfig, /* Configuration object to update */
  189396. const char *zCmd, /* Special command to parse */
  189397. const char *zArg, /* Argument to parse */
  189398. char **pzErr /* OUT: Error message */
  189399. ){
  189400. int rc = SQLITE_OK;
  189401. int nCmd = (int)strlen(zCmd);
  189402. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  189403. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  189404. const char *p;
  189405. int bFirst = 1;
  189406. if( pConfig->aPrefix==0 ){
  189407. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  189408. if( rc ) return rc;
  189409. }
  189410. p = zArg;
  189411. while( 1 ){
  189412. int nPre = 0;
  189413. while( p[0]==' ' ) p++;
  189414. if( bFirst==0 && p[0]==',' ){
  189415. p++;
  189416. while( p[0]==' ' ) p++;
  189417. }else if( p[0]=='\0' ){
  189418. break;
  189419. }
  189420. if( p[0]<'0' || p[0]>'9' ){
  189421. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  189422. rc = SQLITE_ERROR;
  189423. break;
  189424. }
  189425. if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
  189426. *pzErr = sqlite3_mprintf(
  189427. "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
  189428. );
  189429. rc = SQLITE_ERROR;
  189430. break;
  189431. }
  189432. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  189433. nPre = nPre*10 + (p[0] - '0');
  189434. p++;
  189435. }
  189436. if( nPre<=0 || nPre>=1000 ){
  189437. *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
  189438. rc = SQLITE_ERROR;
  189439. break;
  189440. }
  189441. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  189442. pConfig->nPrefix++;
  189443. bFirst = 0;
  189444. }
  189445. assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
  189446. return rc;
  189447. }
  189448. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  189449. const char *p = (const char*)zArg;
  189450. int nArg = (int)strlen(zArg) + 1;
  189451. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  189452. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  189453. char *pSpace = pDel;
  189454. if( azArg && pSpace ){
  189455. if( pConfig->pTok ){
  189456. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  189457. rc = SQLITE_ERROR;
  189458. }else{
  189459. for(nArg=0; p && *p; nArg++){
  189460. const char *p2 = fts5ConfigSkipWhitespace(p);
  189461. if( *p2=='\'' ){
  189462. p = fts5ConfigSkipLiteral(p2);
  189463. }else{
  189464. p = fts5ConfigSkipBareword(p2);
  189465. }
  189466. if( p ){
  189467. memcpy(pSpace, p2, p-p2);
  189468. azArg[nArg] = pSpace;
  189469. sqlite3Fts5Dequote(pSpace);
  189470. pSpace += (p - p2) + 1;
  189471. p = fts5ConfigSkipWhitespace(p);
  189472. }
  189473. }
  189474. if( p==0 ){
  189475. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  189476. rc = SQLITE_ERROR;
  189477. }else{
  189478. rc = sqlite3Fts5GetTokenizer(pGlobal,
  189479. (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
  189480. pzErr
  189481. );
  189482. }
  189483. }
  189484. }
  189485. sqlite3_free(azArg);
  189486. sqlite3_free(pDel);
  189487. return rc;
  189488. }
  189489. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  189490. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  189491. *pzErr = sqlite3_mprintf("multiple content=... directives");
  189492. rc = SQLITE_ERROR;
  189493. }else{
  189494. if( zArg[0] ){
  189495. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  189496. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  189497. }else{
  189498. pConfig->eContent = FTS5_CONTENT_NONE;
  189499. }
  189500. }
  189501. return rc;
  189502. }
  189503. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  189504. if( pConfig->zContentRowid ){
  189505. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  189506. rc = SQLITE_ERROR;
  189507. }else{
  189508. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  189509. }
  189510. return rc;
  189511. }
  189512. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  189513. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  189514. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  189515. rc = SQLITE_ERROR;
  189516. }else{
  189517. pConfig->bColumnsize = (zArg[0]=='1');
  189518. }
  189519. return rc;
  189520. }
  189521. if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
  189522. const Fts5Enum aDetail[] = {
  189523. { "none", FTS5_DETAIL_NONE },
  189524. { "full", FTS5_DETAIL_FULL },
  189525. { "columns", FTS5_DETAIL_COLUMNS },
  189526. { 0, 0 }
  189527. };
  189528. if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
  189529. *pzErr = sqlite3_mprintf("malformed detail=... directive");
  189530. }
  189531. return rc;
  189532. }
  189533. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  189534. return SQLITE_ERROR;
  189535. }
  189536. /*
  189537. ** Allocate an instance of the default tokenizer ("simple") at
  189538. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  189539. ** code if an error occurs.
  189540. */
  189541. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  189542. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  189543. return sqlite3Fts5GetTokenizer(
  189544. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  189545. );
  189546. }
  189547. /*
  189548. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  189549. ** Return a pointer to the character immediately following the last in
  189550. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  189551. ** to find close-quote character).
  189552. **
  189553. ** Before returning, set pzOut to point to a new buffer containing a
  189554. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  189555. ** quoted, *pbQuoted is also set to 1 before returning.
  189556. **
  189557. ** If *pRc is other than SQLITE_OK when this function is called, it is
  189558. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  189559. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  189560. ** set if a parse error (failed to find close quote) occurs.
  189561. */
  189562. static const char *fts5ConfigGobbleWord(
  189563. int *pRc, /* IN/OUT: Error code */
  189564. const char *zIn, /* Buffer to gobble string/bareword from */
  189565. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  189566. int *pbQuoted /* OUT: Set to true if dequoting required */
  189567. ){
  189568. const char *zRet = 0;
  189569. int nIn = (int)strlen(zIn);
  189570. char *zOut = sqlite3_malloc(nIn+1);
  189571. assert( *pRc==SQLITE_OK );
  189572. *pbQuoted = 0;
  189573. *pzOut = 0;
  189574. if( zOut==0 ){
  189575. *pRc = SQLITE_NOMEM;
  189576. }else{
  189577. memcpy(zOut, zIn, nIn+1);
  189578. if( fts5_isopenquote(zOut[0]) ){
  189579. int ii = fts5Dequote(zOut);
  189580. zRet = &zIn[ii];
  189581. *pbQuoted = 1;
  189582. }else{
  189583. zRet = fts5ConfigSkipBareword(zIn);
  189584. if( zRet ){
  189585. zOut[zRet-zIn] = '\0';
  189586. }
  189587. }
  189588. }
  189589. if( zRet==0 ){
  189590. sqlite3_free(zOut);
  189591. }else{
  189592. *pzOut = zOut;
  189593. }
  189594. return zRet;
  189595. }
  189596. static int fts5ConfigParseColumn(
  189597. Fts5Config *p,
  189598. char *zCol,
  189599. char *zArg,
  189600. char **pzErr
  189601. ){
  189602. int rc = SQLITE_OK;
  189603. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  189604. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  189605. ){
  189606. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  189607. rc = SQLITE_ERROR;
  189608. }else if( zArg ){
  189609. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  189610. p->abUnindexed[p->nCol] = 1;
  189611. }else{
  189612. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  189613. rc = SQLITE_ERROR;
  189614. }
  189615. }
  189616. p->azCol[p->nCol++] = zCol;
  189617. return rc;
  189618. }
  189619. /*
  189620. ** Populate the Fts5Config.zContentExprlist string.
  189621. */
  189622. static int fts5ConfigMakeExprlist(Fts5Config *p){
  189623. int i;
  189624. int rc = SQLITE_OK;
  189625. Fts5Buffer buf = {0, 0, 0};
  189626. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  189627. if( p->eContent!=FTS5_CONTENT_NONE ){
  189628. for(i=0; i<p->nCol; i++){
  189629. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  189630. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  189631. }else{
  189632. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  189633. }
  189634. }
  189635. }
  189636. assert( p->zContentExprlist==0 );
  189637. p->zContentExprlist = (char*)buf.p;
  189638. return rc;
  189639. }
  189640. /*
  189641. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  189642. ** or xConnect method of the virtual table. This function attempts to
  189643. ** allocate an instance of Fts5Config containing the results of parsing
  189644. ** those arguments.
  189645. **
  189646. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  189647. ** new Fts5Config object. If an error occurs, an SQLite error code is
  189648. ** returned, *ppOut is set to NULL and an error message may be left in
  189649. ** *pzErr. It is the responsibility of the caller to eventually free any
  189650. ** such error message using sqlite3_free().
  189651. */
  189652. static int sqlite3Fts5ConfigParse(
  189653. Fts5Global *pGlobal,
  189654. sqlite3 *db,
  189655. int nArg, /* Number of arguments */
  189656. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  189657. Fts5Config **ppOut, /* OUT: Results of parse */
  189658. char **pzErr /* OUT: Error message */
  189659. ){
  189660. int rc = SQLITE_OK; /* Return code */
  189661. Fts5Config *pRet; /* New object to return */
  189662. int i;
  189663. int nByte;
  189664. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  189665. if( pRet==0 ) return SQLITE_NOMEM;
  189666. memset(pRet, 0, sizeof(Fts5Config));
  189667. pRet->db = db;
  189668. pRet->iCookie = -1;
  189669. nByte = nArg * (sizeof(char*) + sizeof(u8));
  189670. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  189671. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  189672. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  189673. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  189674. pRet->bColumnsize = 1;
  189675. pRet->eDetail = FTS5_DETAIL_FULL;
  189676. #ifdef SQLITE_DEBUG
  189677. pRet->bPrefixIndex = 1;
  189678. #endif
  189679. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  189680. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  189681. rc = SQLITE_ERROR;
  189682. }
  189683. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  189684. const char *zOrig = azArg[i];
  189685. const char *z;
  189686. char *zOne = 0;
  189687. char *zTwo = 0;
  189688. int bOption = 0;
  189689. int bMustBeCol = 0;
  189690. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  189691. z = fts5ConfigSkipWhitespace(z);
  189692. if( z && *z=='=' ){
  189693. bOption = 1;
  189694. z++;
  189695. if( bMustBeCol ) z = 0;
  189696. }
  189697. z = fts5ConfigSkipWhitespace(z);
  189698. if( z && z[0] ){
  189699. int bDummy;
  189700. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  189701. if( z && z[0] ) z = 0;
  189702. }
  189703. if( rc==SQLITE_OK ){
  189704. if( z==0 ){
  189705. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  189706. rc = SQLITE_ERROR;
  189707. }else{
  189708. if( bOption ){
  189709. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  189710. }else{
  189711. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  189712. zOne = 0;
  189713. }
  189714. }
  189715. }
  189716. sqlite3_free(zOne);
  189717. sqlite3_free(zTwo);
  189718. }
  189719. /* If a tokenizer= option was successfully parsed, the tokenizer has
  189720. ** already been allocated. Otherwise, allocate an instance of the default
  189721. ** tokenizer (unicode61) now. */
  189722. if( rc==SQLITE_OK && pRet->pTok==0 ){
  189723. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  189724. }
  189725. /* If no zContent option was specified, fill in the default values. */
  189726. if( rc==SQLITE_OK && pRet->zContent==0 ){
  189727. const char *zTail = 0;
  189728. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  189729. || pRet->eContent==FTS5_CONTENT_NONE
  189730. );
  189731. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  189732. zTail = "content";
  189733. }else if( pRet->bColumnsize ){
  189734. zTail = "docsize";
  189735. }
  189736. if( zTail ){
  189737. pRet->zContent = sqlite3Fts5Mprintf(
  189738. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  189739. );
  189740. }
  189741. }
  189742. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  189743. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  189744. }
  189745. /* Formulate the zContentExprlist text */
  189746. if( rc==SQLITE_OK ){
  189747. rc = fts5ConfigMakeExprlist(pRet);
  189748. }
  189749. if( rc!=SQLITE_OK ){
  189750. sqlite3Fts5ConfigFree(pRet);
  189751. *ppOut = 0;
  189752. }
  189753. return rc;
  189754. }
  189755. /*
  189756. ** Free the configuration object passed as the only argument.
  189757. */
  189758. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  189759. if( pConfig ){
  189760. int i;
  189761. if( pConfig->pTok ){
  189762. pConfig->pTokApi->xDelete(pConfig->pTok);
  189763. }
  189764. sqlite3_free(pConfig->zDb);
  189765. sqlite3_free(pConfig->zName);
  189766. for(i=0; i<pConfig->nCol; i++){
  189767. sqlite3_free(pConfig->azCol[i]);
  189768. }
  189769. sqlite3_free(pConfig->azCol);
  189770. sqlite3_free(pConfig->aPrefix);
  189771. sqlite3_free(pConfig->zRank);
  189772. sqlite3_free(pConfig->zRankArgs);
  189773. sqlite3_free(pConfig->zContent);
  189774. sqlite3_free(pConfig->zContentRowid);
  189775. sqlite3_free(pConfig->zContentExprlist);
  189776. sqlite3_free(pConfig);
  189777. }
  189778. }
  189779. /*
  189780. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  189781. ** object passed as the only argument. Return SQLITE_OK if successful, or
  189782. ** an SQLite error code if an error occurs.
  189783. */
  189784. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  189785. int i;
  189786. int rc = SQLITE_OK;
  189787. char *zSql;
  189788. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  189789. for(i=0; zSql && i<pConfig->nCol; i++){
  189790. const char *zSep = (i==0?"":", ");
  189791. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  189792. }
  189793. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  189794. zSql, pConfig->zName, FTS5_RANK_NAME
  189795. );
  189796. assert( zSql || rc==SQLITE_NOMEM );
  189797. if( zSql ){
  189798. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  189799. sqlite3_free(zSql);
  189800. }
  189801. return rc;
  189802. }
  189803. /*
  189804. ** Tokenize the text passed via the second and third arguments.
  189805. **
  189806. ** The callback is invoked once for each token in the input text. The
  189807. ** arguments passed to it are, in order:
  189808. **
  189809. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  189810. ** const char *pToken // Pointer to buffer containing token
  189811. ** int nToken // Size of token in bytes
  189812. ** int iStart // Byte offset of start of token within input text
  189813. ** int iEnd // Byte offset of end of token within input text
  189814. ** int iPos // Position of token in input (first token is 0)
  189815. **
  189816. ** If the callback returns a non-zero value the tokenization is abandoned
  189817. ** and no further callbacks are issued.
  189818. **
  189819. ** This function returns SQLITE_OK if successful or an SQLite error code
  189820. ** if an error occurs. If the tokenization was abandoned early because
  189821. ** the callback returned SQLITE_DONE, this is not an error and this function
  189822. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  189823. ** because the callback returned another non-zero value, it is assumed
  189824. ** to be an SQLite error code and returned to the caller.
  189825. */
  189826. static int sqlite3Fts5Tokenize(
  189827. Fts5Config *pConfig, /* FTS5 Configuration object */
  189828. int flags, /* FTS5_TOKENIZE_* flags */
  189829. const char *pText, int nText, /* Text to tokenize */
  189830. void *pCtx, /* Context passed to xToken() */
  189831. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  189832. ){
  189833. if( pText==0 ) return SQLITE_OK;
  189834. return pConfig->pTokApi->xTokenize(
  189835. pConfig->pTok, pCtx, flags, pText, nText, xToken
  189836. );
  189837. }
  189838. /*
  189839. ** Argument pIn points to the first character in what is expected to be
  189840. ** a comma-separated list of SQL literals followed by a ')' character.
  189841. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  189842. ** NULL to indicate a parse error.
  189843. */
  189844. static const char *fts5ConfigSkipArgs(const char *pIn){
  189845. const char *p = pIn;
  189846. while( 1 ){
  189847. p = fts5ConfigSkipWhitespace(p);
  189848. p = fts5ConfigSkipLiteral(p);
  189849. p = fts5ConfigSkipWhitespace(p);
  189850. if( p==0 || *p==')' ) break;
  189851. if( *p!=',' ){
  189852. p = 0;
  189853. break;
  189854. }
  189855. p++;
  189856. }
  189857. return p;
  189858. }
  189859. /*
  189860. ** Parameter zIn contains a rank() function specification. The format of
  189861. ** this is:
  189862. **
  189863. ** + Bareword (function name)
  189864. ** + Open parenthesis - "("
  189865. ** + Zero or more SQL literals in a comma separated list
  189866. ** + Close parenthesis - ")"
  189867. */
  189868. static int sqlite3Fts5ConfigParseRank(
  189869. const char *zIn, /* Input string */
  189870. char **pzRank, /* OUT: Rank function name */
  189871. char **pzRankArgs /* OUT: Rank function arguments */
  189872. ){
  189873. const char *p = zIn;
  189874. const char *pRank;
  189875. char *zRank = 0;
  189876. char *zRankArgs = 0;
  189877. int rc = SQLITE_OK;
  189878. *pzRank = 0;
  189879. *pzRankArgs = 0;
  189880. if( p==0 ){
  189881. rc = SQLITE_ERROR;
  189882. }else{
  189883. p = fts5ConfigSkipWhitespace(p);
  189884. pRank = p;
  189885. p = fts5ConfigSkipBareword(p);
  189886. if( p ){
  189887. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  189888. if( zRank ) memcpy(zRank, pRank, p-pRank);
  189889. }else{
  189890. rc = SQLITE_ERROR;
  189891. }
  189892. if( rc==SQLITE_OK ){
  189893. p = fts5ConfigSkipWhitespace(p);
  189894. if( *p!='(' ) rc = SQLITE_ERROR;
  189895. p++;
  189896. }
  189897. if( rc==SQLITE_OK ){
  189898. const char *pArgs;
  189899. p = fts5ConfigSkipWhitespace(p);
  189900. pArgs = p;
  189901. if( *p!=')' ){
  189902. p = fts5ConfigSkipArgs(p);
  189903. if( p==0 ){
  189904. rc = SQLITE_ERROR;
  189905. }else{
  189906. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  189907. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  189908. }
  189909. }
  189910. }
  189911. }
  189912. if( rc!=SQLITE_OK ){
  189913. sqlite3_free(zRank);
  189914. assert( zRankArgs==0 );
  189915. }else{
  189916. *pzRank = zRank;
  189917. *pzRankArgs = zRankArgs;
  189918. }
  189919. return rc;
  189920. }
  189921. static int sqlite3Fts5ConfigSetValue(
  189922. Fts5Config *pConfig,
  189923. const char *zKey,
  189924. sqlite3_value *pVal,
  189925. int *pbBadkey
  189926. ){
  189927. int rc = SQLITE_OK;
  189928. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  189929. int pgsz = 0;
  189930. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  189931. pgsz = sqlite3_value_int(pVal);
  189932. }
  189933. if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
  189934. *pbBadkey = 1;
  189935. }else{
  189936. pConfig->pgsz = pgsz;
  189937. }
  189938. }
  189939. else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
  189940. int nHashSize = -1;
  189941. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  189942. nHashSize = sqlite3_value_int(pVal);
  189943. }
  189944. if( nHashSize<=0 ){
  189945. *pbBadkey = 1;
  189946. }else{
  189947. pConfig->nHashSize = nHashSize;
  189948. }
  189949. }
  189950. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  189951. int nAutomerge = -1;
  189952. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  189953. nAutomerge = sqlite3_value_int(pVal);
  189954. }
  189955. if( nAutomerge<0 || nAutomerge>64 ){
  189956. *pbBadkey = 1;
  189957. }else{
  189958. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  189959. pConfig->nAutomerge = nAutomerge;
  189960. }
  189961. }
  189962. else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
  189963. int nUsermerge = -1;
  189964. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  189965. nUsermerge = sqlite3_value_int(pVal);
  189966. }
  189967. if( nUsermerge<2 || nUsermerge>16 ){
  189968. *pbBadkey = 1;
  189969. }else{
  189970. pConfig->nUsermerge = nUsermerge;
  189971. }
  189972. }
  189973. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  189974. int nCrisisMerge = -1;
  189975. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  189976. nCrisisMerge = sqlite3_value_int(pVal);
  189977. }
  189978. if( nCrisisMerge<0 ){
  189979. *pbBadkey = 1;
  189980. }else{
  189981. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  189982. pConfig->nCrisisMerge = nCrisisMerge;
  189983. }
  189984. }
  189985. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  189986. const char *zIn = (const char*)sqlite3_value_text(pVal);
  189987. char *zRank;
  189988. char *zRankArgs;
  189989. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  189990. if( rc==SQLITE_OK ){
  189991. sqlite3_free(pConfig->zRank);
  189992. sqlite3_free(pConfig->zRankArgs);
  189993. pConfig->zRank = zRank;
  189994. pConfig->zRankArgs = zRankArgs;
  189995. }else if( rc==SQLITE_ERROR ){
  189996. rc = SQLITE_OK;
  189997. *pbBadkey = 1;
  189998. }
  189999. }else{
  190000. *pbBadkey = 1;
  190001. }
  190002. return rc;
  190003. }
  190004. /*
  190005. ** Load the contents of the %_config table into memory.
  190006. */
  190007. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  190008. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  190009. char *zSql;
  190010. sqlite3_stmt *p = 0;
  190011. int rc = SQLITE_OK;
  190012. int iVersion = 0;
  190013. /* Set default values */
  190014. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  190015. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  190016. pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
  190017. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  190018. pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
  190019. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  190020. if( zSql ){
  190021. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  190022. sqlite3_free(zSql);
  190023. }
  190024. assert( rc==SQLITE_OK || p==0 );
  190025. if( rc==SQLITE_OK ){
  190026. while( SQLITE_ROW==sqlite3_step(p) ){
  190027. const char *zK = (const char*)sqlite3_column_text(p, 0);
  190028. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  190029. if( 0==sqlite3_stricmp(zK, "version") ){
  190030. iVersion = sqlite3_value_int(pVal);
  190031. }else{
  190032. int bDummy = 0;
  190033. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  190034. }
  190035. }
  190036. rc = sqlite3_finalize(p);
  190037. }
  190038. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  190039. rc = SQLITE_ERROR;
  190040. if( pConfig->pzErrmsg ){
  190041. assert( 0==*pConfig->pzErrmsg );
  190042. *pConfig->pzErrmsg = sqlite3_mprintf(
  190043. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  190044. iVersion, FTS5_CURRENT_VERSION
  190045. );
  190046. }
  190047. }
  190048. if( rc==SQLITE_OK ){
  190049. pConfig->iCookie = iCookie;
  190050. }
  190051. return rc;
  190052. }
  190053. /*
  190054. ** 2014 May 31
  190055. **
  190056. ** The author disclaims copyright to this source code. In place of
  190057. ** a legal notice, here is a blessing:
  190058. **
  190059. ** May you do good and not evil.
  190060. ** May you find forgiveness for yourself and forgive others.
  190061. ** May you share freely, never taking more than you give.
  190062. **
  190063. ******************************************************************************
  190064. **
  190065. */
  190066. /* #include "fts5Int.h" */
  190067. /* #include "fts5parse.h" */
  190068. /*
  190069. ** All token types in the generated fts5parse.h file are greater than 0.
  190070. */
  190071. #define FTS5_EOF 0
  190072. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  190073. typedef struct Fts5ExprTerm Fts5ExprTerm;
  190074. /*
  190075. ** Functions generated by lemon from fts5parse.y.
  190076. */
  190077. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  190078. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  190079. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  190080. #ifndef NDEBUG
  190081. /* #include <stdio.h> */
  190082. static void sqlite3Fts5ParserTrace(FILE*, char*);
  190083. #endif
  190084. static int sqlite3Fts5ParserFallback(int);
  190085. struct Fts5Expr {
  190086. Fts5Index *pIndex;
  190087. Fts5Config *pConfig;
  190088. Fts5ExprNode *pRoot;
  190089. int bDesc; /* Iterate in descending rowid order */
  190090. int nPhrase; /* Number of phrases in expression */
  190091. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  190092. };
  190093. /*
  190094. ** eType:
  190095. ** Expression node type. Always one of:
  190096. **
  190097. ** FTS5_AND (nChild, apChild valid)
  190098. ** FTS5_OR (nChild, apChild valid)
  190099. ** FTS5_NOT (nChild, apChild valid)
  190100. ** FTS5_STRING (pNear valid)
  190101. ** FTS5_TERM (pNear valid)
  190102. */
  190103. struct Fts5ExprNode {
  190104. int eType; /* Node type */
  190105. int bEof; /* True at EOF */
  190106. int bNomatch; /* True if entry is not a match */
  190107. /* Next method for this node. */
  190108. int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
  190109. i64 iRowid; /* Current rowid */
  190110. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  190111. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  190112. ** AND or OR nodes, it contains 2 or more entries. */
  190113. int nChild; /* Number of child nodes */
  190114. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  190115. };
  190116. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  190117. /*
  190118. ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
  190119. ** used as if it has the same signature as the xNext() methods themselves.
  190120. */
  190121. #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
  190122. /*
  190123. ** An instance of the following structure represents a single search term
  190124. ** or term prefix.
  190125. */
  190126. struct Fts5ExprTerm {
  190127. u8 bPrefix; /* True for a prefix term */
  190128. u8 bFirst; /* True if token must be first in column */
  190129. char *zTerm; /* nul-terminated term */
  190130. Fts5IndexIter *pIter; /* Iterator for this term */
  190131. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  190132. };
  190133. /*
  190134. ** A phrase. One or more terms that must appear in a contiguous sequence
  190135. ** within a document for it to match.
  190136. */
  190137. struct Fts5ExprPhrase {
  190138. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  190139. Fts5Buffer poslist; /* Current position list */
  190140. int nTerm; /* Number of entries in aTerm[] */
  190141. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  190142. };
  190143. /*
  190144. ** One or more phrases that must appear within a certain token distance of
  190145. ** each other within each matching document.
  190146. */
  190147. struct Fts5ExprNearset {
  190148. int nNear; /* NEAR parameter */
  190149. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  190150. int nPhrase; /* Number of entries in aPhrase[] array */
  190151. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  190152. };
  190153. /*
  190154. ** Parse context.
  190155. */
  190156. struct Fts5Parse {
  190157. Fts5Config *pConfig;
  190158. char *zErr;
  190159. int rc;
  190160. int nPhrase; /* Size of apPhrase array */
  190161. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  190162. Fts5ExprNode *pExpr; /* Result of a successful parse */
  190163. };
  190164. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  190165. va_list ap;
  190166. va_start(ap, zFmt);
  190167. if( pParse->rc==SQLITE_OK ){
  190168. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  190169. pParse->rc = SQLITE_ERROR;
  190170. }
  190171. va_end(ap);
  190172. }
  190173. static int fts5ExprIsspace(char t){
  190174. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  190175. }
  190176. /*
  190177. ** Read the first token from the nul-terminated string at *pz.
  190178. */
  190179. static int fts5ExprGetToken(
  190180. Fts5Parse *pParse,
  190181. const char **pz, /* IN/OUT: Pointer into buffer */
  190182. Fts5Token *pToken
  190183. ){
  190184. const char *z = *pz;
  190185. int tok;
  190186. /* Skip past any whitespace */
  190187. while( fts5ExprIsspace(*z) ) z++;
  190188. pToken->p = z;
  190189. pToken->n = 1;
  190190. switch( *z ){
  190191. case '(': tok = FTS5_LP; break;
  190192. case ')': tok = FTS5_RP; break;
  190193. case '{': tok = FTS5_LCP; break;
  190194. case '}': tok = FTS5_RCP; break;
  190195. case ':': tok = FTS5_COLON; break;
  190196. case ',': tok = FTS5_COMMA; break;
  190197. case '+': tok = FTS5_PLUS; break;
  190198. case '*': tok = FTS5_STAR; break;
  190199. case '-': tok = FTS5_MINUS; break;
  190200. case '^': tok = FTS5_CARET; break;
  190201. case '\0': tok = FTS5_EOF; break;
  190202. case '"': {
  190203. const char *z2;
  190204. tok = FTS5_STRING;
  190205. for(z2=&z[1]; 1; z2++){
  190206. if( z2[0]=='"' ){
  190207. z2++;
  190208. if( z2[0]!='"' ) break;
  190209. }
  190210. if( z2[0]=='\0' ){
  190211. sqlite3Fts5ParseError(pParse, "unterminated string");
  190212. return FTS5_EOF;
  190213. }
  190214. }
  190215. pToken->n = (z2 - z);
  190216. break;
  190217. }
  190218. default: {
  190219. const char *z2;
  190220. if( sqlite3Fts5IsBareword(z[0])==0 ){
  190221. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  190222. return FTS5_EOF;
  190223. }
  190224. tok = FTS5_STRING;
  190225. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  190226. pToken->n = (z2 - z);
  190227. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  190228. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  190229. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  190230. break;
  190231. }
  190232. }
  190233. *pz = &pToken->p[pToken->n];
  190234. return tok;
  190235. }
  190236. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
  190237. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  190238. static int sqlite3Fts5ExprNew(
  190239. Fts5Config *pConfig, /* FTS5 Configuration */
  190240. int iCol,
  190241. const char *zExpr, /* Expression text */
  190242. Fts5Expr **ppNew,
  190243. char **pzErr
  190244. ){
  190245. Fts5Parse sParse;
  190246. Fts5Token token;
  190247. const char *z = zExpr;
  190248. int t; /* Next token type */
  190249. void *pEngine;
  190250. Fts5Expr *pNew;
  190251. *ppNew = 0;
  190252. *pzErr = 0;
  190253. memset(&sParse, 0, sizeof(sParse));
  190254. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  190255. if( pEngine==0 ){ return SQLITE_NOMEM; }
  190256. sParse.pConfig = pConfig;
  190257. do {
  190258. t = fts5ExprGetToken(&sParse, &z, &token);
  190259. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  190260. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  190261. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  190262. /* If the LHS of the MATCH expression was a user column, apply the
  190263. ** implicit column-filter. */
  190264. if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
  190265. int n = sizeof(Fts5Colset);
  190266. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
  190267. if( pColset ){
  190268. pColset->nCol = 1;
  190269. pColset->aiCol[0] = iCol;
  190270. sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
  190271. }
  190272. }
  190273. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  190274. if( sParse.rc==SQLITE_OK ){
  190275. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  190276. if( pNew==0 ){
  190277. sParse.rc = SQLITE_NOMEM;
  190278. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  190279. }else{
  190280. if( !sParse.pExpr ){
  190281. const int nByte = sizeof(Fts5ExprNode);
  190282. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
  190283. if( pNew->pRoot ){
  190284. pNew->pRoot->bEof = 1;
  190285. }
  190286. }else{
  190287. pNew->pRoot = sParse.pExpr;
  190288. }
  190289. pNew->pIndex = 0;
  190290. pNew->pConfig = pConfig;
  190291. pNew->apExprPhrase = sParse.apPhrase;
  190292. pNew->nPhrase = sParse.nPhrase;
  190293. sParse.apPhrase = 0;
  190294. }
  190295. }else{
  190296. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  190297. }
  190298. sqlite3_free(sParse.apPhrase);
  190299. *pzErr = sParse.zErr;
  190300. return sParse.rc;
  190301. }
  190302. /*
  190303. ** Free the expression node object passed as the only argument.
  190304. */
  190305. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  190306. if( p ){
  190307. int i;
  190308. for(i=0; i<p->nChild; i++){
  190309. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  190310. }
  190311. sqlite3Fts5ParseNearsetFree(p->pNear);
  190312. sqlite3_free(p);
  190313. }
  190314. }
  190315. /*
  190316. ** Free the expression object passed as the only argument.
  190317. */
  190318. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  190319. if( p ){
  190320. sqlite3Fts5ParseNodeFree(p->pRoot);
  190321. sqlite3_free(p->apExprPhrase);
  190322. sqlite3_free(p);
  190323. }
  190324. }
  190325. /*
  190326. ** Argument pTerm must be a synonym iterator. Return the current rowid
  190327. ** that it points to.
  190328. */
  190329. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  190330. i64 iRet = 0;
  190331. int bRetValid = 0;
  190332. Fts5ExprTerm *p;
  190333. assert( pTerm->pSynonym );
  190334. assert( bDesc==0 || bDesc==1 );
  190335. for(p=pTerm; p; p=p->pSynonym){
  190336. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  190337. i64 iRowid = p->pIter->iRowid;
  190338. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  190339. iRet = iRowid;
  190340. bRetValid = 1;
  190341. }
  190342. }
  190343. }
  190344. if( pbEof && bRetValid==0 ) *pbEof = 1;
  190345. return iRet;
  190346. }
  190347. /*
  190348. ** Argument pTerm must be a synonym iterator.
  190349. */
  190350. static int fts5ExprSynonymList(
  190351. Fts5ExprTerm *pTerm,
  190352. i64 iRowid,
  190353. Fts5Buffer *pBuf, /* Use this buffer for space if required */
  190354. u8 **pa, int *pn
  190355. ){
  190356. Fts5PoslistReader aStatic[4];
  190357. Fts5PoslistReader *aIter = aStatic;
  190358. int nIter = 0;
  190359. int nAlloc = 4;
  190360. int rc = SQLITE_OK;
  190361. Fts5ExprTerm *p;
  190362. assert( pTerm->pSynonym );
  190363. for(p=pTerm; p; p=p->pSynonym){
  190364. Fts5IndexIter *pIter = p->pIter;
  190365. if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
  190366. if( pIter->nData==0 ) continue;
  190367. if( nIter==nAlloc ){
  190368. int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  190369. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  190370. if( aNew==0 ){
  190371. rc = SQLITE_NOMEM;
  190372. goto synonym_poslist_out;
  190373. }
  190374. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  190375. nAlloc = nAlloc*2;
  190376. if( aIter!=aStatic ) sqlite3_free(aIter);
  190377. aIter = aNew;
  190378. }
  190379. sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
  190380. assert( aIter[nIter].bEof==0 );
  190381. nIter++;
  190382. }
  190383. }
  190384. if( nIter==1 ){
  190385. *pa = (u8*)aIter[0].a;
  190386. *pn = aIter[0].n;
  190387. }else{
  190388. Fts5PoslistWriter writer = {0};
  190389. i64 iPrev = -1;
  190390. fts5BufferZero(pBuf);
  190391. while( 1 ){
  190392. int i;
  190393. i64 iMin = FTS5_LARGEST_INT64;
  190394. for(i=0; i<nIter; i++){
  190395. if( aIter[i].bEof==0 ){
  190396. if( aIter[i].iPos==iPrev ){
  190397. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  190398. }
  190399. if( aIter[i].iPos<iMin ){
  190400. iMin = aIter[i].iPos;
  190401. }
  190402. }
  190403. }
  190404. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  190405. rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
  190406. iPrev = iMin;
  190407. }
  190408. if( rc==SQLITE_OK ){
  190409. *pa = pBuf->p;
  190410. *pn = pBuf->n;
  190411. }
  190412. }
  190413. synonym_poslist_out:
  190414. if( aIter!=aStatic ) sqlite3_free(aIter);
  190415. return rc;
  190416. }
  190417. /*
  190418. ** All individual term iterators in pPhrase are guaranteed to be valid and
  190419. ** pointing to the same rowid when this function is called. This function
  190420. ** checks if the current rowid really is a match, and if so populates
  190421. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  190422. ** is set to true if this is really a match, or false otherwise.
  190423. **
  190424. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  190425. ** otherwise. It is not considered an error code if the current rowid is
  190426. ** not a match.
  190427. */
  190428. static int fts5ExprPhraseIsMatch(
  190429. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  190430. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  190431. int *pbMatch /* OUT: Set to true if really a match */
  190432. ){
  190433. Fts5PoslistWriter writer = {0};
  190434. Fts5PoslistReader aStatic[4];
  190435. Fts5PoslistReader *aIter = aStatic;
  190436. int i;
  190437. int rc = SQLITE_OK;
  190438. int bFirst = pPhrase->aTerm[0].bFirst;
  190439. fts5BufferZero(&pPhrase->poslist);
  190440. /* If the aStatic[] array is not large enough, allocate a large array
  190441. ** using sqlite3_malloc(). This approach could be improved upon. */
  190442. if( pPhrase->nTerm>ArraySize(aStatic) ){
  190443. int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  190444. aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  190445. if( !aIter ) return SQLITE_NOMEM;
  190446. }
  190447. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  190448. /* Initialize a term iterator for each term in the phrase */
  190449. for(i=0; i<pPhrase->nTerm; i++){
  190450. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  190451. int n = 0;
  190452. int bFlag = 0;
  190453. u8 *a = 0;
  190454. if( pTerm->pSynonym ){
  190455. Fts5Buffer buf = {0, 0, 0};
  190456. rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
  190457. if( rc ){
  190458. sqlite3_free(a);
  190459. goto ismatch_out;
  190460. }
  190461. if( a==buf.p ) bFlag = 1;
  190462. }else{
  190463. a = (u8*)pTerm->pIter->pData;
  190464. n = pTerm->pIter->nData;
  190465. }
  190466. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  190467. aIter[i].bFlag = (u8)bFlag;
  190468. if( aIter[i].bEof ) goto ismatch_out;
  190469. }
  190470. while( 1 ){
  190471. int bMatch;
  190472. i64 iPos = aIter[0].iPos;
  190473. do {
  190474. bMatch = 1;
  190475. for(i=0; i<pPhrase->nTerm; i++){
  190476. Fts5PoslistReader *pPos = &aIter[i];
  190477. i64 iAdj = iPos + i;
  190478. if( pPos->iPos!=iAdj ){
  190479. bMatch = 0;
  190480. while( pPos->iPos<iAdj ){
  190481. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  190482. }
  190483. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  190484. }
  190485. }
  190486. }while( bMatch==0 );
  190487. /* Append position iPos to the output */
  190488. if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){
  190489. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  190490. if( rc!=SQLITE_OK ) goto ismatch_out;
  190491. }
  190492. for(i=0; i<pPhrase->nTerm; i++){
  190493. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  190494. }
  190495. }
  190496. ismatch_out:
  190497. *pbMatch = (pPhrase->poslist.n>0);
  190498. for(i=0; i<pPhrase->nTerm; i++){
  190499. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  190500. }
  190501. if( aIter!=aStatic ) sqlite3_free(aIter);
  190502. return rc;
  190503. }
  190504. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  190505. struct Fts5LookaheadReader {
  190506. const u8 *a; /* Buffer containing position list */
  190507. int n; /* Size of buffer a[] in bytes */
  190508. int i; /* Current offset in position list */
  190509. i64 iPos; /* Current position */
  190510. i64 iLookahead; /* Next position */
  190511. };
  190512. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  190513. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  190514. p->iPos = p->iLookahead;
  190515. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  190516. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  190517. }
  190518. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  190519. }
  190520. static int fts5LookaheadReaderInit(
  190521. const u8 *a, int n, /* Buffer to read position list from */
  190522. Fts5LookaheadReader *p /* Iterator object to initialize */
  190523. ){
  190524. memset(p, 0, sizeof(Fts5LookaheadReader));
  190525. p->a = a;
  190526. p->n = n;
  190527. fts5LookaheadReaderNext(p);
  190528. return fts5LookaheadReaderNext(p);
  190529. }
  190530. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  190531. struct Fts5NearTrimmer {
  190532. Fts5LookaheadReader reader; /* Input iterator */
  190533. Fts5PoslistWriter writer; /* Writer context */
  190534. Fts5Buffer *pOut; /* Output poslist */
  190535. };
  190536. /*
  190537. ** The near-set object passed as the first argument contains more than
  190538. ** one phrase. All phrases currently point to the same row. The
  190539. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  190540. ** tests if the current row contains instances of each phrase sufficiently
  190541. ** close together to meet the NEAR constraint. Non-zero is returned if it
  190542. ** does, or zero otherwise.
  190543. **
  190544. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  190545. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  190546. ** occurs within this function (*pRc) is set accordingly before returning.
  190547. ** The return value is undefined in both these cases.
  190548. **
  190549. ** If no error occurs and non-zero (a match) is returned, the position-list
  190550. ** of each phrase object is edited to contain only those entries that
  190551. ** meet the constraint before returning.
  190552. */
  190553. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  190554. Fts5NearTrimmer aStatic[4];
  190555. Fts5NearTrimmer *a = aStatic;
  190556. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  190557. int i;
  190558. int rc = *pRc;
  190559. int bMatch;
  190560. assert( pNear->nPhrase>1 );
  190561. /* If the aStatic[] array is not large enough, allocate a large array
  190562. ** using sqlite3_malloc(). This approach could be improved upon. */
  190563. if( pNear->nPhrase>ArraySize(aStatic) ){
  190564. int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  190565. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  190566. }else{
  190567. memset(aStatic, 0, sizeof(aStatic));
  190568. }
  190569. if( rc!=SQLITE_OK ){
  190570. *pRc = rc;
  190571. return 0;
  190572. }
  190573. /* Initialize a lookahead iterator for each phrase. After passing the
  190574. ** buffer and buffer size to the lookaside-reader init function, zero
  190575. ** the phrase poslist buffer. The new poslist for the phrase (containing
  190576. ** the same entries as the original with some entries removed on account
  190577. ** of the NEAR constraint) is written over the original even as it is
  190578. ** being read. This is safe as the entries for the new poslist are a
  190579. ** subset of the old, so it is not possible for data yet to be read to
  190580. ** be overwritten. */
  190581. for(i=0; i<pNear->nPhrase; i++){
  190582. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  190583. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  190584. pPoslist->n = 0;
  190585. a[i].pOut = pPoslist;
  190586. }
  190587. while( 1 ){
  190588. int iAdv;
  190589. i64 iMin;
  190590. i64 iMax;
  190591. /* This block advances the phrase iterators until they point to a set of
  190592. ** entries that together comprise a match. */
  190593. iMax = a[0].reader.iPos;
  190594. do {
  190595. bMatch = 1;
  190596. for(i=0; i<pNear->nPhrase; i++){
  190597. Fts5LookaheadReader *pPos = &a[i].reader;
  190598. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  190599. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  190600. bMatch = 0;
  190601. while( pPos->iPos<iMin ){
  190602. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  190603. }
  190604. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  190605. }
  190606. }
  190607. }while( bMatch==0 );
  190608. /* Add an entry to each output position list */
  190609. for(i=0; i<pNear->nPhrase; i++){
  190610. i64 iPos = a[i].reader.iPos;
  190611. Fts5PoslistWriter *pWriter = &a[i].writer;
  190612. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  190613. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  190614. }
  190615. }
  190616. iAdv = 0;
  190617. iMin = a[0].reader.iLookahead;
  190618. for(i=0; i<pNear->nPhrase; i++){
  190619. if( a[i].reader.iLookahead < iMin ){
  190620. iMin = a[i].reader.iLookahead;
  190621. iAdv = i;
  190622. }
  190623. }
  190624. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  190625. }
  190626. ismatch_out: {
  190627. int bRet = a[0].pOut->n>0;
  190628. *pRc = rc;
  190629. if( a!=aStatic ) sqlite3_free(a);
  190630. return bRet;
  190631. }
  190632. }
  190633. /*
  190634. ** Advance iterator pIter until it points to a value equal to or laster
  190635. ** than the initial value of *piLast. If this means the iterator points
  190636. ** to a value laster than *piLast, update *piLast to the new lastest value.
  190637. **
  190638. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  190639. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  190640. ** are set, return a non-zero value. Otherwise, return zero.
  190641. */
  190642. static int fts5ExprAdvanceto(
  190643. Fts5IndexIter *pIter, /* Iterator to advance */
  190644. int bDesc, /* True if iterator is "rowid DESC" */
  190645. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  190646. int *pRc, /* OUT: Error code */
  190647. int *pbEof /* OUT: Set to true if EOF */
  190648. ){
  190649. i64 iLast = *piLast;
  190650. i64 iRowid;
  190651. iRowid = pIter->iRowid;
  190652. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  190653. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  190654. if( rc || sqlite3Fts5IterEof(pIter) ){
  190655. *pRc = rc;
  190656. *pbEof = 1;
  190657. return 1;
  190658. }
  190659. iRowid = pIter->iRowid;
  190660. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  190661. }
  190662. *piLast = iRowid;
  190663. return 0;
  190664. }
  190665. static int fts5ExprSynonymAdvanceto(
  190666. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  190667. int bDesc, /* True if iterator is "rowid DESC" */
  190668. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  190669. int *pRc /* OUT: Error code */
  190670. ){
  190671. int rc = SQLITE_OK;
  190672. i64 iLast = *piLast;
  190673. Fts5ExprTerm *p;
  190674. int bEof = 0;
  190675. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  190676. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  190677. i64 iRowid = p->pIter->iRowid;
  190678. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  190679. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  190680. }
  190681. }
  190682. }
  190683. if( rc!=SQLITE_OK ){
  190684. *pRc = rc;
  190685. bEof = 1;
  190686. }else{
  190687. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  190688. }
  190689. return bEof;
  190690. }
  190691. static int fts5ExprNearTest(
  190692. int *pRc,
  190693. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  190694. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  190695. ){
  190696. Fts5ExprNearset *pNear = pNode->pNear;
  190697. int rc = *pRc;
  190698. if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  190699. Fts5ExprTerm *pTerm;
  190700. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  190701. pPhrase->poslist.n = 0;
  190702. for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  190703. Fts5IndexIter *pIter = pTerm->pIter;
  190704. if( sqlite3Fts5IterEof(pIter)==0 ){
  190705. if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
  190706. pPhrase->poslist.n = 1;
  190707. }
  190708. }
  190709. }
  190710. return pPhrase->poslist.n;
  190711. }else{
  190712. int i;
  190713. /* Check that each phrase in the nearset matches the current row.
  190714. ** Populate the pPhrase->poslist buffers at the same time. If any
  190715. ** phrase is not a match, break out of the loop early. */
  190716. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  190717. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  190718. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym
  190719. || pNear->pColset || pPhrase->aTerm[0].bFirst
  190720. ){
  190721. int bMatch = 0;
  190722. rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
  190723. if( bMatch==0 ) break;
  190724. }else{
  190725. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  190726. fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
  190727. }
  190728. }
  190729. *pRc = rc;
  190730. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  190731. return 1;
  190732. }
  190733. return 0;
  190734. }
  190735. }
  190736. /*
  190737. ** Initialize all term iterators in the pNear object. If any term is found
  190738. ** to match no documents at all, return immediately without initializing any
  190739. ** further iterators.
  190740. **
  190741. ** If an error occurs, return an SQLite error code. Otherwise, return
  190742. ** SQLITE_OK. It is not considered an error if some term matches zero
  190743. ** documents.
  190744. */
  190745. static int fts5ExprNearInitAll(
  190746. Fts5Expr *pExpr,
  190747. Fts5ExprNode *pNode
  190748. ){
  190749. Fts5ExprNearset *pNear = pNode->pNear;
  190750. int i;
  190751. assert( pNode->bNomatch==0 );
  190752. for(i=0; i<pNear->nPhrase; i++){
  190753. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  190754. if( pPhrase->nTerm==0 ){
  190755. pNode->bEof = 1;
  190756. return SQLITE_OK;
  190757. }else{
  190758. int j;
  190759. for(j=0; j<pPhrase->nTerm; j++){
  190760. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  190761. Fts5ExprTerm *p;
  190762. int bHit = 0;
  190763. for(p=pTerm; p; p=p->pSynonym){
  190764. int rc;
  190765. if( p->pIter ){
  190766. sqlite3Fts5IterClose(p->pIter);
  190767. p->pIter = 0;
  190768. }
  190769. rc = sqlite3Fts5IndexQuery(
  190770. pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
  190771. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  190772. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  190773. pNear->pColset,
  190774. &p->pIter
  190775. );
  190776. assert( (rc==SQLITE_OK)==(p->pIter!=0) );
  190777. if( rc!=SQLITE_OK ) return rc;
  190778. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  190779. bHit = 1;
  190780. }
  190781. }
  190782. if( bHit==0 ){
  190783. pNode->bEof = 1;
  190784. return SQLITE_OK;
  190785. }
  190786. }
  190787. }
  190788. }
  190789. pNode->bEof = 0;
  190790. return SQLITE_OK;
  190791. }
  190792. /*
  190793. ** If pExpr is an ASC iterator, this function returns a value with the
  190794. ** same sign as:
  190795. **
  190796. ** (iLhs - iRhs)
  190797. **
  190798. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  190799. **
  190800. ** (iRhs - iLhs)
  190801. */
  190802. static int fts5RowidCmp(
  190803. Fts5Expr *pExpr,
  190804. i64 iLhs,
  190805. i64 iRhs
  190806. ){
  190807. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  190808. if( pExpr->bDesc==0 ){
  190809. if( iLhs<iRhs ) return -1;
  190810. return (iLhs > iRhs);
  190811. }else{
  190812. if( iLhs>iRhs ) return -1;
  190813. return (iLhs < iRhs);
  190814. }
  190815. }
  190816. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  190817. int i;
  190818. pNode->bEof = 1;
  190819. pNode->bNomatch = 0;
  190820. for(i=0; i<pNode->nChild; i++){
  190821. fts5ExprSetEof(pNode->apChild[i]);
  190822. }
  190823. }
  190824. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  190825. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  190826. Fts5ExprNearset *pNear = pNode->pNear;
  190827. int i;
  190828. for(i=0; i<pNear->nPhrase; i++){
  190829. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  190830. pPhrase->poslist.n = 0;
  190831. }
  190832. }else{
  190833. int i;
  190834. for(i=0; i<pNode->nChild; i++){
  190835. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  190836. }
  190837. }
  190838. }
  190839. /*
  190840. ** Compare the values currently indicated by the two nodes as follows:
  190841. **
  190842. ** res = (*p1) - (*p2)
  190843. **
  190844. ** Nodes that point to values that come later in the iteration order are
  190845. ** considered to be larger. Nodes at EOF are the largest of all.
  190846. **
  190847. ** This means that if the iteration order is ASC, then numerically larger
  190848. ** rowids are considered larger. Or if it is the default DESC, numerically
  190849. ** smaller rowids are larger.
  190850. */
  190851. static int fts5NodeCompare(
  190852. Fts5Expr *pExpr,
  190853. Fts5ExprNode *p1,
  190854. Fts5ExprNode *p2
  190855. ){
  190856. if( p2->bEof ) return -1;
  190857. if( p1->bEof ) return +1;
  190858. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  190859. }
  190860. /*
  190861. ** All individual term iterators in pNear are guaranteed to be valid when
  190862. ** this function is called. This function checks if all term iterators
  190863. ** point to the same rowid, and if not, advances them until they do.
  190864. ** If an EOF is reached before this happens, *pbEof is set to true before
  190865. ** returning.
  190866. **
  190867. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  190868. ** otherwise. It is not considered an error code if an iterator reaches
  190869. ** EOF.
  190870. */
  190871. static int fts5ExprNodeTest_STRING(
  190872. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  190873. Fts5ExprNode *pNode
  190874. ){
  190875. Fts5ExprNearset *pNear = pNode->pNear;
  190876. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  190877. int rc = SQLITE_OK;
  190878. i64 iLast; /* Lastest rowid any iterator points to */
  190879. int i, j; /* Phrase and token index, respectively */
  190880. int bMatch; /* True if all terms are at the same rowid */
  190881. const int bDesc = pExpr->bDesc;
  190882. /* Check that this node should not be FTS5_TERM */
  190883. assert( pNear->nPhrase>1
  190884. || pNear->apPhrase[0]->nTerm>1
  190885. || pNear->apPhrase[0]->aTerm[0].pSynonym
  190886. || pNear->apPhrase[0]->aTerm[0].bFirst
  190887. );
  190888. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  190889. ** iterator skips through rowids in the default ascending order, this means
  190890. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  190891. ** means the minimum rowid. */
  190892. if( pLeft->aTerm[0].pSynonym ){
  190893. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  190894. }else{
  190895. iLast = pLeft->aTerm[0].pIter->iRowid;
  190896. }
  190897. do {
  190898. bMatch = 1;
  190899. for(i=0; i<pNear->nPhrase; i++){
  190900. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  190901. for(j=0; j<pPhrase->nTerm; j++){
  190902. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  190903. if( pTerm->pSynonym ){
  190904. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  190905. if( iRowid==iLast ) continue;
  190906. bMatch = 0;
  190907. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  190908. pNode->bNomatch = 0;
  190909. pNode->bEof = 1;
  190910. return rc;
  190911. }
  190912. }else{
  190913. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  190914. if( pIter->iRowid==iLast || pIter->bEof ) continue;
  190915. bMatch = 0;
  190916. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  190917. return rc;
  190918. }
  190919. }
  190920. }
  190921. }
  190922. }while( bMatch==0 );
  190923. pNode->iRowid = iLast;
  190924. pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
  190925. assert( pNode->bEof==0 || pNode->bNomatch==0 );
  190926. return rc;
  190927. }
  190928. /*
  190929. ** Advance the first term iterator in the first phrase of pNear. Set output
  190930. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  190931. **
  190932. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  190933. ** occurs.
  190934. */
  190935. static int fts5ExprNodeNext_STRING(
  190936. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  190937. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  190938. int bFromValid,
  190939. i64 iFrom
  190940. ){
  190941. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  190942. int rc = SQLITE_OK;
  190943. pNode->bNomatch = 0;
  190944. if( pTerm->pSynonym ){
  190945. int bEof = 1;
  190946. Fts5ExprTerm *p;
  190947. /* Find the firstest rowid any synonym points to. */
  190948. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  190949. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  190950. ** is valid - each iterator that points to a rowid before iFrom. */
  190951. for(p=pTerm; p; p=p->pSynonym){
  190952. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  190953. i64 ii = p->pIter->iRowid;
  190954. if( ii==iRowid
  190955. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  190956. ){
  190957. if( bFromValid ){
  190958. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  190959. }else{
  190960. rc = sqlite3Fts5IterNext(p->pIter);
  190961. }
  190962. if( rc!=SQLITE_OK ) break;
  190963. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  190964. bEof = 0;
  190965. }
  190966. }else{
  190967. bEof = 0;
  190968. }
  190969. }
  190970. }
  190971. /* Set the EOF flag if either all synonym iterators are at EOF or an
  190972. ** error has occurred. */
  190973. pNode->bEof = (rc || bEof);
  190974. }else{
  190975. Fts5IndexIter *pIter = pTerm->pIter;
  190976. assert( Fts5NodeIsString(pNode) );
  190977. if( bFromValid ){
  190978. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  190979. }else{
  190980. rc = sqlite3Fts5IterNext(pIter);
  190981. }
  190982. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  190983. }
  190984. if( pNode->bEof==0 ){
  190985. assert( rc==SQLITE_OK );
  190986. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  190987. }
  190988. return rc;
  190989. }
  190990. static int fts5ExprNodeTest_TERM(
  190991. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  190992. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  190993. ){
  190994. /* As this "NEAR" object is actually a single phrase that consists
  190995. ** of a single term only, grab pointers into the poslist managed by the
  190996. ** fts5_index.c iterator object. This is much faster than synthesizing
  190997. ** a new poslist the way we have to for more complicated phrase or NEAR
  190998. ** expressions. */
  190999. Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
  191000. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  191001. assert( pNode->eType==FTS5_TERM );
  191002. assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
  191003. assert( pPhrase->aTerm[0].pSynonym==0 );
  191004. pPhrase->poslist.n = pIter->nData;
  191005. if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
  191006. pPhrase->poslist.p = (u8*)pIter->pData;
  191007. }
  191008. pNode->iRowid = pIter->iRowid;
  191009. pNode->bNomatch = (pPhrase->poslist.n==0);
  191010. return SQLITE_OK;
  191011. }
  191012. /*
  191013. ** xNext() method for a node of type FTS5_TERM.
  191014. */
  191015. static int fts5ExprNodeNext_TERM(
  191016. Fts5Expr *pExpr,
  191017. Fts5ExprNode *pNode,
  191018. int bFromValid,
  191019. i64 iFrom
  191020. ){
  191021. int rc;
  191022. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  191023. assert( pNode->bEof==0 );
  191024. if( bFromValid ){
  191025. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  191026. }else{
  191027. rc = sqlite3Fts5IterNext(pIter);
  191028. }
  191029. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  191030. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  191031. }else{
  191032. pNode->bEof = 1;
  191033. pNode->bNomatch = 0;
  191034. }
  191035. return rc;
  191036. }
  191037. static void fts5ExprNodeTest_OR(
  191038. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  191039. Fts5ExprNode *pNode /* Expression node to test */
  191040. ){
  191041. Fts5ExprNode *pNext = pNode->apChild[0];
  191042. int i;
  191043. for(i=1; i<pNode->nChild; i++){
  191044. Fts5ExprNode *pChild = pNode->apChild[i];
  191045. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  191046. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  191047. pNext = pChild;
  191048. }
  191049. }
  191050. pNode->iRowid = pNext->iRowid;
  191051. pNode->bEof = pNext->bEof;
  191052. pNode->bNomatch = pNext->bNomatch;
  191053. }
  191054. static int fts5ExprNodeNext_OR(
  191055. Fts5Expr *pExpr,
  191056. Fts5ExprNode *pNode,
  191057. int bFromValid,
  191058. i64 iFrom
  191059. ){
  191060. int i;
  191061. i64 iLast = pNode->iRowid;
  191062. for(i=0; i<pNode->nChild; i++){
  191063. Fts5ExprNode *p1 = pNode->apChild[i];
  191064. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  191065. if( p1->bEof==0 ){
  191066. if( (p1->iRowid==iLast)
  191067. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  191068. ){
  191069. int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  191070. if( rc!=SQLITE_OK ){
  191071. pNode->bNomatch = 0;
  191072. return rc;
  191073. }
  191074. }
  191075. }
  191076. }
  191077. fts5ExprNodeTest_OR(pExpr, pNode);
  191078. return SQLITE_OK;
  191079. }
  191080. /*
  191081. ** Argument pNode is an FTS5_AND node.
  191082. */
  191083. static int fts5ExprNodeTest_AND(
  191084. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  191085. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  191086. ){
  191087. int iChild;
  191088. i64 iLast = pAnd->iRowid;
  191089. int rc = SQLITE_OK;
  191090. int bMatch;
  191091. assert( pAnd->bEof==0 );
  191092. do {
  191093. pAnd->bNomatch = 0;
  191094. bMatch = 1;
  191095. for(iChild=0; iChild<pAnd->nChild; iChild++){
  191096. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  191097. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  191098. if( cmp>0 ){
  191099. /* Advance pChild until it points to iLast or laster */
  191100. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  191101. if( rc!=SQLITE_OK ){
  191102. pAnd->bNomatch = 0;
  191103. return rc;
  191104. }
  191105. }
  191106. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  191107. ** the child node is guaranteed to have advanced at least as far as
  191108. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  191109. ** new lastest rowid seen so far. */
  191110. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  191111. if( pChild->bEof ){
  191112. fts5ExprSetEof(pAnd);
  191113. bMatch = 1;
  191114. break;
  191115. }else if( iLast!=pChild->iRowid ){
  191116. bMatch = 0;
  191117. iLast = pChild->iRowid;
  191118. }
  191119. if( pChild->bNomatch ){
  191120. pAnd->bNomatch = 1;
  191121. }
  191122. }
  191123. }while( bMatch==0 );
  191124. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  191125. fts5ExprNodeZeroPoslist(pAnd);
  191126. }
  191127. pAnd->iRowid = iLast;
  191128. return SQLITE_OK;
  191129. }
  191130. static int fts5ExprNodeNext_AND(
  191131. Fts5Expr *pExpr,
  191132. Fts5ExprNode *pNode,
  191133. int bFromValid,
  191134. i64 iFrom
  191135. ){
  191136. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  191137. if( rc==SQLITE_OK ){
  191138. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  191139. }else{
  191140. pNode->bNomatch = 0;
  191141. }
  191142. return rc;
  191143. }
  191144. static int fts5ExprNodeTest_NOT(
  191145. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  191146. Fts5ExprNode *pNode /* FTS5_NOT node to advance */
  191147. ){
  191148. int rc = SQLITE_OK;
  191149. Fts5ExprNode *p1 = pNode->apChild[0];
  191150. Fts5ExprNode *p2 = pNode->apChild[1];
  191151. assert( pNode->nChild==2 );
  191152. while( rc==SQLITE_OK && p1->bEof==0 ){
  191153. int cmp = fts5NodeCompare(pExpr, p1, p2);
  191154. if( cmp>0 ){
  191155. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  191156. cmp = fts5NodeCompare(pExpr, p1, p2);
  191157. }
  191158. assert( rc!=SQLITE_OK || cmp<=0 );
  191159. if( cmp || p2->bNomatch ) break;
  191160. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  191161. }
  191162. pNode->bEof = p1->bEof;
  191163. pNode->bNomatch = p1->bNomatch;
  191164. pNode->iRowid = p1->iRowid;
  191165. if( p1->bEof ){
  191166. fts5ExprNodeZeroPoslist(p2);
  191167. }
  191168. return rc;
  191169. }
  191170. static int fts5ExprNodeNext_NOT(
  191171. Fts5Expr *pExpr,
  191172. Fts5ExprNode *pNode,
  191173. int bFromValid,
  191174. i64 iFrom
  191175. ){
  191176. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  191177. if( rc==SQLITE_OK ){
  191178. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  191179. }
  191180. if( rc!=SQLITE_OK ){
  191181. pNode->bNomatch = 0;
  191182. }
  191183. return rc;
  191184. }
  191185. /*
  191186. ** If pNode currently points to a match, this function returns SQLITE_OK
  191187. ** without modifying it. Otherwise, pNode is advanced until it does point
  191188. ** to a match or EOF is reached.
  191189. */
  191190. static int fts5ExprNodeTest(
  191191. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  191192. Fts5ExprNode *pNode /* Expression node to test */
  191193. ){
  191194. int rc = SQLITE_OK;
  191195. if( pNode->bEof==0 ){
  191196. switch( pNode->eType ){
  191197. case FTS5_STRING: {
  191198. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  191199. break;
  191200. }
  191201. case FTS5_TERM: {
  191202. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  191203. break;
  191204. }
  191205. case FTS5_AND: {
  191206. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  191207. break;
  191208. }
  191209. case FTS5_OR: {
  191210. fts5ExprNodeTest_OR(pExpr, pNode);
  191211. break;
  191212. }
  191213. default: assert( pNode->eType==FTS5_NOT ); {
  191214. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  191215. break;
  191216. }
  191217. }
  191218. }
  191219. return rc;
  191220. }
  191221. /*
  191222. ** Set node pNode, which is part of expression pExpr, to point to the first
  191223. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  191224. **
  191225. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  191226. ** It is not an error if there are no matches.
  191227. */
  191228. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  191229. int rc = SQLITE_OK;
  191230. pNode->bEof = 0;
  191231. pNode->bNomatch = 0;
  191232. if( Fts5NodeIsString(pNode) ){
  191233. /* Initialize all term iterators in the NEAR object. */
  191234. rc = fts5ExprNearInitAll(pExpr, pNode);
  191235. }else if( pNode->xNext==0 ){
  191236. pNode->bEof = 1;
  191237. }else{
  191238. int i;
  191239. int nEof = 0;
  191240. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  191241. Fts5ExprNode *pChild = pNode->apChild[i];
  191242. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  191243. assert( pChild->bEof==0 || pChild->bEof==1 );
  191244. nEof += pChild->bEof;
  191245. }
  191246. pNode->iRowid = pNode->apChild[0]->iRowid;
  191247. switch( pNode->eType ){
  191248. case FTS5_AND:
  191249. if( nEof>0 ) fts5ExprSetEof(pNode);
  191250. break;
  191251. case FTS5_OR:
  191252. if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
  191253. break;
  191254. default:
  191255. assert( pNode->eType==FTS5_NOT );
  191256. pNode->bEof = pNode->apChild[0]->bEof;
  191257. break;
  191258. }
  191259. }
  191260. if( rc==SQLITE_OK ){
  191261. rc = fts5ExprNodeTest(pExpr, pNode);
  191262. }
  191263. return rc;
  191264. }
  191265. /*
  191266. ** Begin iterating through the set of documents in index pIdx matched by
  191267. ** the MATCH expression passed as the first argument. If the "bDesc"
  191268. ** parameter is passed a non-zero value, iteration is in descending rowid
  191269. ** order. Or, if it is zero, in ascending order.
  191270. **
  191271. ** If iterating in ascending rowid order (bDesc==0), the first document
  191272. ** visited is that with the smallest rowid that is larger than or equal
  191273. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  191274. ** then the first document visited must have a rowid smaller than or
  191275. ** equal to iFirst.
  191276. **
  191277. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  191278. ** is not considered an error if the query does not match any documents.
  191279. */
  191280. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  191281. Fts5ExprNode *pRoot = p->pRoot;
  191282. int rc; /* Return code */
  191283. p->pIndex = pIdx;
  191284. p->bDesc = bDesc;
  191285. rc = fts5ExprNodeFirst(p, pRoot);
  191286. /* If not at EOF but the current rowid occurs earlier than iFirst in
  191287. ** the iteration order, move to document iFirst or later. */
  191288. if( rc==SQLITE_OK
  191289. && 0==pRoot->bEof
  191290. && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
  191291. ){
  191292. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  191293. }
  191294. /* If the iterator is not at a real match, skip forward until it is. */
  191295. while( pRoot->bNomatch ){
  191296. assert( pRoot->bEof==0 && rc==SQLITE_OK );
  191297. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  191298. }
  191299. return rc;
  191300. }
  191301. /*
  191302. ** Move to the next document
  191303. **
  191304. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  191305. ** is not considered an error if the query does not match any documents.
  191306. */
  191307. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  191308. int rc;
  191309. Fts5ExprNode *pRoot = p->pRoot;
  191310. assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
  191311. do {
  191312. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  191313. assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
  191314. }while( pRoot->bNomatch );
  191315. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  191316. pRoot->bEof = 1;
  191317. }
  191318. return rc;
  191319. }
  191320. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  191321. return p->pRoot->bEof;
  191322. }
  191323. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  191324. return p->pRoot->iRowid;
  191325. }
  191326. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  191327. int rc = SQLITE_OK;
  191328. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  191329. return rc;
  191330. }
  191331. /*
  191332. ** Free the phrase object passed as the only argument.
  191333. */
  191334. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  191335. if( pPhrase ){
  191336. int i;
  191337. for(i=0; i<pPhrase->nTerm; i++){
  191338. Fts5ExprTerm *pSyn;
  191339. Fts5ExprTerm *pNext;
  191340. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  191341. sqlite3_free(pTerm->zTerm);
  191342. sqlite3Fts5IterClose(pTerm->pIter);
  191343. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  191344. pNext = pSyn->pSynonym;
  191345. sqlite3Fts5IterClose(pSyn->pIter);
  191346. fts5BufferFree((Fts5Buffer*)&pSyn[1]);
  191347. sqlite3_free(pSyn);
  191348. }
  191349. }
  191350. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  191351. sqlite3_free(pPhrase);
  191352. }
  191353. }
  191354. /*
  191355. ** Set the "bFirst" flag on the first token of the phrase passed as the
  191356. ** only argument.
  191357. */
  191358. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){
  191359. if( pPhrase && pPhrase->nTerm ){
  191360. pPhrase->aTerm[0].bFirst = 1;
  191361. }
  191362. }
  191363. /*
  191364. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  191365. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  191366. ** appended to it and the results returned.
  191367. **
  191368. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  191369. ** NULL returned.
  191370. */
  191371. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  191372. Fts5Parse *pParse, /* Parse context */
  191373. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  191374. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  191375. ){
  191376. const int SZALLOC = 8;
  191377. Fts5ExprNearset *pRet = 0;
  191378. if( pParse->rc==SQLITE_OK ){
  191379. if( pPhrase==0 ){
  191380. return pNear;
  191381. }
  191382. if( pNear==0 ){
  191383. int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  191384. pRet = sqlite3_malloc(nByte);
  191385. if( pRet==0 ){
  191386. pParse->rc = SQLITE_NOMEM;
  191387. }else{
  191388. memset(pRet, 0, nByte);
  191389. }
  191390. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  191391. int nNew = pNear->nPhrase + SZALLOC;
  191392. int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  191393. pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
  191394. if( pRet==0 ){
  191395. pParse->rc = SQLITE_NOMEM;
  191396. }
  191397. }else{
  191398. pRet = pNear;
  191399. }
  191400. }
  191401. if( pRet==0 ){
  191402. assert( pParse->rc!=SQLITE_OK );
  191403. sqlite3Fts5ParseNearsetFree(pNear);
  191404. sqlite3Fts5ParsePhraseFree(pPhrase);
  191405. }else{
  191406. if( pRet->nPhrase>0 ){
  191407. Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
  191408. assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
  191409. if( pPhrase->nTerm==0 ){
  191410. fts5ExprPhraseFree(pPhrase);
  191411. pRet->nPhrase--;
  191412. pParse->nPhrase--;
  191413. pPhrase = pLast;
  191414. }else if( pLast->nTerm==0 ){
  191415. fts5ExprPhraseFree(pLast);
  191416. pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
  191417. pParse->nPhrase--;
  191418. pRet->nPhrase--;
  191419. }
  191420. }
  191421. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  191422. }
  191423. return pRet;
  191424. }
  191425. typedef struct TokenCtx TokenCtx;
  191426. struct TokenCtx {
  191427. Fts5ExprPhrase *pPhrase;
  191428. int rc;
  191429. };
  191430. /*
  191431. ** Callback for tokenizing terms used by ParseTerm().
  191432. */
  191433. static int fts5ParseTokenize(
  191434. void *pContext, /* Pointer to Fts5InsertCtx object */
  191435. int tflags, /* Mask of FTS5_TOKEN_* flags */
  191436. const char *pToken, /* Buffer containing token */
  191437. int nToken, /* Size of token in bytes */
  191438. int iUnused1, /* Start offset of token */
  191439. int iUnused2 /* End offset of token */
  191440. ){
  191441. int rc = SQLITE_OK;
  191442. const int SZALLOC = 8;
  191443. TokenCtx *pCtx = (TokenCtx*)pContext;
  191444. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  191445. UNUSED_PARAM2(iUnused1, iUnused2);
  191446. /* If an error has already occurred, this is a no-op */
  191447. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  191448. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  191449. if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
  191450. Fts5ExprTerm *pSyn;
  191451. int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
  191452. pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
  191453. if( pSyn==0 ){
  191454. rc = SQLITE_NOMEM;
  191455. }else{
  191456. memset(pSyn, 0, nByte);
  191457. pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
  191458. memcpy(pSyn->zTerm, pToken, nToken);
  191459. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  191460. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  191461. }
  191462. }else{
  191463. Fts5ExprTerm *pTerm;
  191464. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  191465. Fts5ExprPhrase *pNew;
  191466. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  191467. pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
  191468. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  191469. );
  191470. if( pNew==0 ){
  191471. rc = SQLITE_NOMEM;
  191472. }else{
  191473. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  191474. pCtx->pPhrase = pPhrase = pNew;
  191475. pNew->nTerm = nNew - SZALLOC;
  191476. }
  191477. }
  191478. if( rc==SQLITE_OK ){
  191479. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  191480. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  191481. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  191482. }
  191483. }
  191484. pCtx->rc = rc;
  191485. return rc;
  191486. }
  191487. /*
  191488. ** Free the phrase object passed as the only argument.
  191489. */
  191490. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  191491. fts5ExprPhraseFree(pPhrase);
  191492. }
  191493. /*
  191494. ** Free the phrase object passed as the second argument.
  191495. */
  191496. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  191497. if( pNear ){
  191498. int i;
  191499. for(i=0; i<pNear->nPhrase; i++){
  191500. fts5ExprPhraseFree(pNear->apPhrase[i]);
  191501. }
  191502. sqlite3_free(pNear->pColset);
  191503. sqlite3_free(pNear);
  191504. }
  191505. }
  191506. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  191507. assert( pParse->pExpr==0 );
  191508. pParse->pExpr = p;
  191509. }
  191510. /*
  191511. ** This function is called by the parser to process a string token. The
  191512. ** string may or may not be quoted. In any case it is tokenized and a
  191513. ** phrase object consisting of all tokens returned.
  191514. */
  191515. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  191516. Fts5Parse *pParse, /* Parse context */
  191517. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  191518. Fts5Token *pToken, /* String to tokenize */
  191519. int bPrefix /* True if there is a trailing "*" */
  191520. ){
  191521. Fts5Config *pConfig = pParse->pConfig;
  191522. TokenCtx sCtx; /* Context object passed to callback */
  191523. int rc; /* Tokenize return code */
  191524. char *z = 0;
  191525. memset(&sCtx, 0, sizeof(TokenCtx));
  191526. sCtx.pPhrase = pAppend;
  191527. rc = fts5ParseStringFromToken(pToken, &z);
  191528. if( rc==SQLITE_OK ){
  191529. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
  191530. int n;
  191531. sqlite3Fts5Dequote(z);
  191532. n = (int)strlen(z);
  191533. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  191534. }
  191535. sqlite3_free(z);
  191536. if( rc || (rc = sCtx.rc) ){
  191537. pParse->rc = rc;
  191538. fts5ExprPhraseFree(sCtx.pPhrase);
  191539. sCtx.pPhrase = 0;
  191540. }else{
  191541. if( pAppend==0 ){
  191542. if( (pParse->nPhrase % 8)==0 ){
  191543. int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  191544. Fts5ExprPhrase **apNew;
  191545. apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
  191546. if( apNew==0 ){
  191547. pParse->rc = SQLITE_NOMEM;
  191548. fts5ExprPhraseFree(sCtx.pPhrase);
  191549. return 0;
  191550. }
  191551. pParse->apPhrase = apNew;
  191552. }
  191553. pParse->nPhrase++;
  191554. }
  191555. if( sCtx.pPhrase==0 ){
  191556. /* This happens when parsing a token or quoted phrase that contains
  191557. ** no token characters at all. (e.g ... MATCH '""'). */
  191558. sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
  191559. }else if( sCtx.pPhrase->nTerm ){
  191560. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;
  191561. }
  191562. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  191563. }
  191564. return sCtx.pPhrase;
  191565. }
  191566. /*
  191567. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  191568. ** expression passed as the second argument.
  191569. */
  191570. static int sqlite3Fts5ExprClonePhrase(
  191571. Fts5Expr *pExpr,
  191572. int iPhrase,
  191573. Fts5Expr **ppNew
  191574. ){
  191575. int rc = SQLITE_OK; /* Return code */
  191576. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  191577. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  191578. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  191579. pOrig = pExpr->apExprPhrase[iPhrase];
  191580. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  191581. if( rc==SQLITE_OK ){
  191582. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  191583. sizeof(Fts5ExprPhrase*));
  191584. }
  191585. if( rc==SQLITE_OK ){
  191586. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  191587. sizeof(Fts5ExprNode));
  191588. }
  191589. if( rc==SQLITE_OK ){
  191590. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  191591. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  191592. }
  191593. if( rc==SQLITE_OK ){
  191594. Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
  191595. if( pColsetOrig ){
  191596. int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
  191597. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
  191598. if( pColset ){
  191599. memcpy(pColset, pColsetOrig, nByte);
  191600. }
  191601. pNew->pRoot->pNear->pColset = pColset;
  191602. }
  191603. }
  191604. if( pOrig->nTerm ){
  191605. int i; /* Used to iterate through phrase terms */
  191606. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  191607. int tflags = 0;
  191608. Fts5ExprTerm *p;
  191609. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  191610. const char *zTerm = p->zTerm;
  191611. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
  191612. 0, 0);
  191613. tflags = FTS5_TOKEN_COLOCATED;
  191614. }
  191615. if( rc==SQLITE_OK ){
  191616. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  191617. sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;
  191618. }
  191619. }
  191620. }else{
  191621. /* This happens when parsing a token or quoted phrase that contains
  191622. ** no token characters at all. (e.g ... MATCH '""'). */
  191623. sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
  191624. }
  191625. if( rc==SQLITE_OK ){
  191626. /* All the allocations succeeded. Put the expression object together. */
  191627. pNew->pIndex = pExpr->pIndex;
  191628. pNew->pConfig = pExpr->pConfig;
  191629. pNew->nPhrase = 1;
  191630. pNew->apExprPhrase[0] = sCtx.pPhrase;
  191631. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  191632. pNew->pRoot->pNear->nPhrase = 1;
  191633. sCtx.pPhrase->pNode = pNew->pRoot;
  191634. if( pOrig->nTerm==1
  191635. && pOrig->aTerm[0].pSynonym==0
  191636. && pOrig->aTerm[0].bFirst==0
  191637. ){
  191638. pNew->pRoot->eType = FTS5_TERM;
  191639. pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
  191640. }else{
  191641. pNew->pRoot->eType = FTS5_STRING;
  191642. pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
  191643. }
  191644. }else{
  191645. sqlite3Fts5ExprFree(pNew);
  191646. fts5ExprPhraseFree(sCtx.pPhrase);
  191647. pNew = 0;
  191648. }
  191649. *ppNew = pNew;
  191650. return rc;
  191651. }
  191652. /*
  191653. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  191654. ** is expected. If token pTok does not contain "NEAR", store an error
  191655. ** in the pParse object.
  191656. */
  191657. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  191658. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  191659. sqlite3Fts5ParseError(
  191660. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  191661. );
  191662. }
  191663. }
  191664. static void sqlite3Fts5ParseSetDistance(
  191665. Fts5Parse *pParse,
  191666. Fts5ExprNearset *pNear,
  191667. Fts5Token *p
  191668. ){
  191669. if( pNear ){
  191670. int nNear = 0;
  191671. int i;
  191672. if( p->n ){
  191673. for(i=0; i<p->n; i++){
  191674. char c = (char)p->p[i];
  191675. if( c<'0' || c>'9' ){
  191676. sqlite3Fts5ParseError(
  191677. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  191678. );
  191679. return;
  191680. }
  191681. nNear = nNear * 10 + (p->p[i] - '0');
  191682. }
  191683. }else{
  191684. nNear = FTS5_DEFAULT_NEARDIST;
  191685. }
  191686. pNear->nNear = nNear;
  191687. }
  191688. }
  191689. /*
  191690. ** The second argument passed to this function may be NULL, or it may be
  191691. ** an existing Fts5Colset object. This function returns a pointer to
  191692. ** a new colset object containing the contents of (p) with new value column
  191693. ** number iCol appended.
  191694. **
  191695. ** If an OOM error occurs, store an error code in pParse and return NULL.
  191696. ** The old colset object (if any) is not freed in this case.
  191697. */
  191698. static Fts5Colset *fts5ParseColset(
  191699. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  191700. Fts5Colset *p, /* Existing colset object */
  191701. int iCol /* New column to add to colset object */
  191702. ){
  191703. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  191704. Fts5Colset *pNew; /* New colset object to return */
  191705. assert( pParse->rc==SQLITE_OK );
  191706. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  191707. pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  191708. if( pNew==0 ){
  191709. pParse->rc = SQLITE_NOMEM;
  191710. }else{
  191711. int *aiCol = pNew->aiCol;
  191712. int i, j;
  191713. for(i=0; i<nCol; i++){
  191714. if( aiCol[i]==iCol ) return pNew;
  191715. if( aiCol[i]>iCol ) break;
  191716. }
  191717. for(j=nCol; j>i; j--){
  191718. aiCol[j] = aiCol[j-1];
  191719. }
  191720. aiCol[i] = iCol;
  191721. pNew->nCol = nCol+1;
  191722. #ifndef NDEBUG
  191723. /* Check that the array is in order and contains no duplicate entries. */
  191724. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  191725. #endif
  191726. }
  191727. return pNew;
  191728. }
  191729. /*
  191730. ** Allocate and return an Fts5Colset object specifying the inverse of
  191731. ** the colset passed as the second argument. Free the colset passed
  191732. ** as the second argument before returning.
  191733. */
  191734. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
  191735. Fts5Colset *pRet;
  191736. int nCol = pParse->pConfig->nCol;
  191737. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
  191738. sizeof(Fts5Colset) + sizeof(int)*nCol
  191739. );
  191740. if( pRet ){
  191741. int i;
  191742. int iOld = 0;
  191743. for(i=0; i<nCol; i++){
  191744. if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
  191745. pRet->aiCol[pRet->nCol++] = i;
  191746. }else{
  191747. iOld++;
  191748. }
  191749. }
  191750. }
  191751. sqlite3_free(p);
  191752. return pRet;
  191753. }
  191754. static Fts5Colset *sqlite3Fts5ParseColset(
  191755. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  191756. Fts5Colset *pColset, /* Existing colset object */
  191757. Fts5Token *p
  191758. ){
  191759. Fts5Colset *pRet = 0;
  191760. int iCol;
  191761. char *z; /* Dequoted copy of token p */
  191762. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  191763. if( pParse->rc==SQLITE_OK ){
  191764. Fts5Config *pConfig = pParse->pConfig;
  191765. sqlite3Fts5Dequote(z);
  191766. for(iCol=0; iCol<pConfig->nCol; iCol++){
  191767. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  191768. }
  191769. if( iCol==pConfig->nCol ){
  191770. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  191771. }else{
  191772. pRet = fts5ParseColset(pParse, pColset, iCol);
  191773. }
  191774. sqlite3_free(z);
  191775. }
  191776. if( pRet==0 ){
  191777. assert( pParse->rc!=SQLITE_OK );
  191778. sqlite3_free(pColset);
  191779. }
  191780. return pRet;
  191781. }
  191782. /*
  191783. ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
  191784. ** SQLITE_OK when this function is called, NULL is returned.
  191785. **
  191786. ** Otherwise, a copy of (*pOrig) is made into memory obtained from
  191787. ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
  191788. ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
  191789. */
  191790. static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
  191791. Fts5Colset *pRet;
  191792. if( pOrig ){
  191793. int nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
  191794. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
  191795. if( pRet ){
  191796. memcpy(pRet, pOrig, nByte);
  191797. }
  191798. }else{
  191799. pRet = 0;
  191800. }
  191801. return pRet;
  191802. }
  191803. /*
  191804. ** Remove from colset pColset any columns that are not also in colset pMerge.
  191805. */
  191806. static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
  191807. int iIn = 0; /* Next input in pColset */
  191808. int iMerge = 0; /* Next input in pMerge */
  191809. int iOut = 0; /* Next output slot in pColset */
  191810. while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
  191811. int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
  191812. if( iDiff==0 ){
  191813. pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
  191814. iMerge++;
  191815. iIn++;
  191816. }else if( iDiff>0 ){
  191817. iMerge++;
  191818. }else{
  191819. iIn++;
  191820. }
  191821. }
  191822. pColset->nCol = iOut;
  191823. }
  191824. /*
  191825. ** Recursively apply colset pColset to expression node pNode and all of
  191826. ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
  191827. ** of pColset. This function may use the spare copy and set (*ppFree) to
  191828. ** zero, or it may create copies of pColset using fts5CloneColset().
  191829. */
  191830. static void fts5ParseSetColset(
  191831. Fts5Parse *pParse,
  191832. Fts5ExprNode *pNode,
  191833. Fts5Colset *pColset,
  191834. Fts5Colset **ppFree
  191835. ){
  191836. if( pParse->rc==SQLITE_OK ){
  191837. assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
  191838. || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
  191839. || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
  191840. );
  191841. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  191842. Fts5ExprNearset *pNear = pNode->pNear;
  191843. if( pNear->pColset ){
  191844. fts5MergeColset(pNear->pColset, pColset);
  191845. if( pNear->pColset->nCol==0 ){
  191846. pNode->eType = FTS5_EOF;
  191847. pNode->xNext = 0;
  191848. }
  191849. }else if( *ppFree ){
  191850. pNear->pColset = pColset;
  191851. *ppFree = 0;
  191852. }else{
  191853. pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
  191854. }
  191855. }else{
  191856. int i;
  191857. assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
  191858. for(i=0; i<pNode->nChild; i++){
  191859. fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
  191860. }
  191861. }
  191862. }
  191863. }
  191864. /*
  191865. ** Apply colset pColset to expression node pExpr and all of its descendents.
  191866. */
  191867. static void sqlite3Fts5ParseSetColset(
  191868. Fts5Parse *pParse,
  191869. Fts5ExprNode *pExpr,
  191870. Fts5Colset *pColset
  191871. ){
  191872. Fts5Colset *pFree = pColset;
  191873. if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
  191874. pParse->rc = SQLITE_ERROR;
  191875. pParse->zErr = sqlite3_mprintf(
  191876. "fts5: column queries are not supported (detail=none)"
  191877. );
  191878. }else{
  191879. fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
  191880. }
  191881. sqlite3_free(pFree);
  191882. }
  191883. static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
  191884. switch( pNode->eType ){
  191885. case FTS5_STRING: {
  191886. Fts5ExprNearset *pNear = pNode->pNear;
  191887. if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
  191888. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  191889. && pNear->apPhrase[0]->aTerm[0].bFirst==0
  191890. ){
  191891. pNode->eType = FTS5_TERM;
  191892. pNode->xNext = fts5ExprNodeNext_TERM;
  191893. }else{
  191894. pNode->xNext = fts5ExprNodeNext_STRING;
  191895. }
  191896. break;
  191897. };
  191898. case FTS5_OR: {
  191899. pNode->xNext = fts5ExprNodeNext_OR;
  191900. break;
  191901. };
  191902. case FTS5_AND: {
  191903. pNode->xNext = fts5ExprNodeNext_AND;
  191904. break;
  191905. };
  191906. default: assert( pNode->eType==FTS5_NOT ); {
  191907. pNode->xNext = fts5ExprNodeNext_NOT;
  191908. break;
  191909. };
  191910. }
  191911. }
  191912. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  191913. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  191914. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  191915. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  191916. p->nChild += pSub->nChild;
  191917. sqlite3_free(pSub);
  191918. }else{
  191919. p->apChild[p->nChild++] = pSub;
  191920. }
  191921. }
  191922. /*
  191923. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  191924. ** OOM error), leave an error code in pParse and return NULL.
  191925. */
  191926. static Fts5ExprNode *sqlite3Fts5ParseNode(
  191927. Fts5Parse *pParse, /* Parse context */
  191928. int eType, /* FTS5_STRING, AND, OR or NOT */
  191929. Fts5ExprNode *pLeft, /* Left hand child expression */
  191930. Fts5ExprNode *pRight, /* Right hand child expression */
  191931. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  191932. ){
  191933. Fts5ExprNode *pRet = 0;
  191934. if( pParse->rc==SQLITE_OK ){
  191935. int nChild = 0; /* Number of children of returned node */
  191936. int nByte; /* Bytes of space to allocate for this node */
  191937. assert( (eType!=FTS5_STRING && !pNear)
  191938. || (eType==FTS5_STRING && !pLeft && !pRight)
  191939. );
  191940. if( eType==FTS5_STRING && pNear==0 ) return 0;
  191941. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  191942. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  191943. if( eType==FTS5_NOT ){
  191944. nChild = 2;
  191945. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  191946. nChild = 2;
  191947. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  191948. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  191949. }
  191950. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  191951. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  191952. if( pRet ){
  191953. pRet->eType = eType;
  191954. pRet->pNear = pNear;
  191955. fts5ExprAssignXNext(pRet);
  191956. if( eType==FTS5_STRING ){
  191957. int iPhrase;
  191958. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  191959. pNear->apPhrase[iPhrase]->pNode = pRet;
  191960. if( pNear->apPhrase[iPhrase]->nTerm==0 ){
  191961. pRet->xNext = 0;
  191962. pRet->eType = FTS5_EOF;
  191963. }
  191964. }
  191965. if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  191966. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  191967. if( pNear->nPhrase!=1
  191968. || pPhrase->nTerm>1
  191969. || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
  191970. ){
  191971. assert( pParse->rc==SQLITE_OK );
  191972. pParse->rc = SQLITE_ERROR;
  191973. assert( pParse->zErr==0 );
  191974. pParse->zErr = sqlite3_mprintf(
  191975. "fts5: %s queries are not supported (detail!=full)",
  191976. pNear->nPhrase==1 ? "phrase": "NEAR"
  191977. );
  191978. sqlite3_free(pRet);
  191979. pRet = 0;
  191980. }
  191981. }
  191982. }else{
  191983. fts5ExprAddChildren(pRet, pLeft);
  191984. fts5ExprAddChildren(pRet, pRight);
  191985. }
  191986. }
  191987. }
  191988. if( pRet==0 ){
  191989. assert( pParse->rc!=SQLITE_OK );
  191990. sqlite3Fts5ParseNodeFree(pLeft);
  191991. sqlite3Fts5ParseNodeFree(pRight);
  191992. sqlite3Fts5ParseNearsetFree(pNear);
  191993. }
  191994. return pRet;
  191995. }
  191996. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  191997. Fts5Parse *pParse, /* Parse context */
  191998. Fts5ExprNode *pLeft, /* Left hand child expression */
  191999. Fts5ExprNode *pRight /* Right hand child expression */
  192000. ){
  192001. Fts5ExprNode *pRet = 0;
  192002. Fts5ExprNode *pPrev;
  192003. if( pParse->rc ){
  192004. sqlite3Fts5ParseNodeFree(pLeft);
  192005. sqlite3Fts5ParseNodeFree(pRight);
  192006. }else{
  192007. assert( pLeft->eType==FTS5_STRING
  192008. || pLeft->eType==FTS5_TERM
  192009. || pLeft->eType==FTS5_EOF
  192010. || pLeft->eType==FTS5_AND
  192011. );
  192012. assert( pRight->eType==FTS5_STRING
  192013. || pRight->eType==FTS5_TERM
  192014. || pRight->eType==FTS5_EOF
  192015. );
  192016. if( pLeft->eType==FTS5_AND ){
  192017. pPrev = pLeft->apChild[pLeft->nChild-1];
  192018. }else{
  192019. pPrev = pLeft;
  192020. }
  192021. assert( pPrev->eType==FTS5_STRING
  192022. || pPrev->eType==FTS5_TERM
  192023. || pPrev->eType==FTS5_EOF
  192024. );
  192025. if( pRight->eType==FTS5_EOF ){
  192026. assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
  192027. sqlite3Fts5ParseNodeFree(pRight);
  192028. pRet = pLeft;
  192029. pParse->nPhrase--;
  192030. }
  192031. else if( pPrev->eType==FTS5_EOF ){
  192032. Fts5ExprPhrase **ap;
  192033. if( pPrev==pLeft ){
  192034. pRet = pRight;
  192035. }else{
  192036. pLeft->apChild[pLeft->nChild-1] = pRight;
  192037. pRet = pLeft;
  192038. }
  192039. ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
  192040. assert( ap[0]==pPrev->pNear->apPhrase[0] );
  192041. memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
  192042. pParse->nPhrase--;
  192043. sqlite3Fts5ParseNodeFree(pPrev);
  192044. }
  192045. else{
  192046. pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
  192047. }
  192048. }
  192049. return pRet;
  192050. }
  192051. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  192052. int nByte = 0;
  192053. Fts5ExprTerm *p;
  192054. char *zQuoted;
  192055. /* Determine the maximum amount of space required. */
  192056. for(p=pTerm; p; p=p->pSynonym){
  192057. nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
  192058. }
  192059. zQuoted = sqlite3_malloc(nByte);
  192060. if( zQuoted ){
  192061. int i = 0;
  192062. for(p=pTerm; p; p=p->pSynonym){
  192063. char *zIn = p->zTerm;
  192064. zQuoted[i++] = '"';
  192065. while( *zIn ){
  192066. if( *zIn=='"' ) zQuoted[i++] = '"';
  192067. zQuoted[i++] = *zIn++;
  192068. }
  192069. zQuoted[i++] = '"';
  192070. if( p->pSynonym ) zQuoted[i++] = '|';
  192071. }
  192072. if( pTerm->bPrefix ){
  192073. zQuoted[i++] = ' ';
  192074. zQuoted[i++] = '*';
  192075. }
  192076. zQuoted[i++] = '\0';
  192077. }
  192078. return zQuoted;
  192079. }
  192080. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  192081. char *zNew;
  192082. va_list ap;
  192083. va_start(ap, zFmt);
  192084. zNew = sqlite3_vmprintf(zFmt, ap);
  192085. va_end(ap);
  192086. if( zApp && zNew ){
  192087. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  192088. sqlite3_free(zNew);
  192089. zNew = zNew2;
  192090. }
  192091. sqlite3_free(zApp);
  192092. return zNew;
  192093. }
  192094. /*
  192095. ** Compose a tcl-readable representation of expression pExpr. Return a
  192096. ** pointer to a buffer containing that representation. It is the
  192097. ** responsibility of the caller to at some point free the buffer using
  192098. ** sqlite3_free().
  192099. */
  192100. static char *fts5ExprPrintTcl(
  192101. Fts5Config *pConfig,
  192102. const char *zNearsetCmd,
  192103. Fts5ExprNode *pExpr
  192104. ){
  192105. char *zRet = 0;
  192106. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  192107. Fts5ExprNearset *pNear = pExpr->pNear;
  192108. int i;
  192109. int iTerm;
  192110. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  192111. if( zRet==0 ) return 0;
  192112. if( pNear->pColset ){
  192113. int *aiCol = pNear->pColset->aiCol;
  192114. int nCol = pNear->pColset->nCol;
  192115. if( nCol==1 ){
  192116. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  192117. }else{
  192118. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  192119. for(i=1; i<pNear->pColset->nCol; i++){
  192120. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  192121. }
  192122. zRet = fts5PrintfAppend(zRet, "} ");
  192123. }
  192124. if( zRet==0 ) return 0;
  192125. }
  192126. if( pNear->nPhrase>1 ){
  192127. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  192128. if( zRet==0 ) return 0;
  192129. }
  192130. zRet = fts5PrintfAppend(zRet, "--");
  192131. if( zRet==0 ) return 0;
  192132. for(i=0; i<pNear->nPhrase; i++){
  192133. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  192134. zRet = fts5PrintfAppend(zRet, " {");
  192135. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  192136. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  192137. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  192138. if( pPhrase->aTerm[iTerm].bPrefix ){
  192139. zRet = fts5PrintfAppend(zRet, "*");
  192140. }
  192141. }
  192142. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  192143. if( zRet==0 ) return 0;
  192144. }
  192145. }else{
  192146. char const *zOp = 0;
  192147. int i;
  192148. switch( pExpr->eType ){
  192149. case FTS5_AND: zOp = "AND"; break;
  192150. case FTS5_NOT: zOp = "NOT"; break;
  192151. default:
  192152. assert( pExpr->eType==FTS5_OR );
  192153. zOp = "OR";
  192154. break;
  192155. }
  192156. zRet = sqlite3_mprintf("%s", zOp);
  192157. for(i=0; zRet && i<pExpr->nChild; i++){
  192158. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  192159. if( !z ){
  192160. sqlite3_free(zRet);
  192161. zRet = 0;
  192162. }else{
  192163. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  192164. }
  192165. }
  192166. }
  192167. return zRet;
  192168. }
  192169. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  192170. char *zRet = 0;
  192171. if( pExpr->eType==0 ){
  192172. return sqlite3_mprintf("\"\"");
  192173. }else
  192174. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  192175. Fts5ExprNearset *pNear = pExpr->pNear;
  192176. int i;
  192177. int iTerm;
  192178. if( pNear->pColset ){
  192179. int iCol = pNear->pColset->aiCol[0];
  192180. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  192181. if( zRet==0 ) return 0;
  192182. }
  192183. if( pNear->nPhrase>1 ){
  192184. zRet = fts5PrintfAppend(zRet, "NEAR(");
  192185. if( zRet==0 ) return 0;
  192186. }
  192187. for(i=0; i<pNear->nPhrase; i++){
  192188. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  192189. if( i!=0 ){
  192190. zRet = fts5PrintfAppend(zRet, " ");
  192191. if( zRet==0 ) return 0;
  192192. }
  192193. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  192194. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  192195. if( zTerm ){
  192196. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  192197. sqlite3_free(zTerm);
  192198. }
  192199. if( zTerm==0 || zRet==0 ){
  192200. sqlite3_free(zRet);
  192201. return 0;
  192202. }
  192203. }
  192204. }
  192205. if( pNear->nPhrase>1 ){
  192206. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  192207. if( zRet==0 ) return 0;
  192208. }
  192209. }else{
  192210. char const *zOp = 0;
  192211. int i;
  192212. switch( pExpr->eType ){
  192213. case FTS5_AND: zOp = " AND "; break;
  192214. case FTS5_NOT: zOp = " NOT "; break;
  192215. default:
  192216. assert( pExpr->eType==FTS5_OR );
  192217. zOp = " OR ";
  192218. break;
  192219. }
  192220. for(i=0; i<pExpr->nChild; i++){
  192221. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  192222. if( z==0 ){
  192223. sqlite3_free(zRet);
  192224. zRet = 0;
  192225. }else{
  192226. int e = pExpr->apChild[i]->eType;
  192227. int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
  192228. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  192229. (i==0 ? "" : zOp),
  192230. (b?"(":""), z, (b?")":"")
  192231. );
  192232. }
  192233. if( zRet==0 ) break;
  192234. }
  192235. }
  192236. return zRet;
  192237. }
  192238. /*
  192239. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  192240. ** and fts5_expr_tcl() (bTcl!=0).
  192241. */
  192242. static void fts5ExprFunction(
  192243. sqlite3_context *pCtx, /* Function call context */
  192244. int nArg, /* Number of args */
  192245. sqlite3_value **apVal, /* Function arguments */
  192246. int bTcl
  192247. ){
  192248. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  192249. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  192250. const char *zExpr = 0;
  192251. char *zErr = 0;
  192252. Fts5Expr *pExpr = 0;
  192253. int rc;
  192254. int i;
  192255. const char **azConfig; /* Array of arguments for Fts5Config */
  192256. const char *zNearsetCmd = "nearset";
  192257. int nConfig; /* Size of azConfig[] */
  192258. Fts5Config *pConfig = 0;
  192259. int iArg = 1;
  192260. if( nArg<1 ){
  192261. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  192262. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  192263. );
  192264. sqlite3_result_error(pCtx, zErr, -1);
  192265. sqlite3_free(zErr);
  192266. return;
  192267. }
  192268. if( bTcl && nArg>1 ){
  192269. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  192270. iArg = 2;
  192271. }
  192272. nConfig = 3 + (nArg-iArg);
  192273. azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
  192274. if( azConfig==0 ){
  192275. sqlite3_result_error_nomem(pCtx);
  192276. return;
  192277. }
  192278. azConfig[0] = 0;
  192279. azConfig[1] = "main";
  192280. azConfig[2] = "tbl";
  192281. for(i=3; iArg<nArg; iArg++){
  192282. azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
  192283. }
  192284. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  192285. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  192286. if( rc==SQLITE_OK ){
  192287. rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
  192288. }
  192289. if( rc==SQLITE_OK ){
  192290. char *zText;
  192291. if( pExpr->pRoot->xNext==0 ){
  192292. zText = sqlite3_mprintf("");
  192293. }else if( bTcl ){
  192294. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  192295. }else{
  192296. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  192297. }
  192298. if( zText==0 ){
  192299. rc = SQLITE_NOMEM;
  192300. }else{
  192301. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  192302. sqlite3_free(zText);
  192303. }
  192304. }
  192305. if( rc!=SQLITE_OK ){
  192306. if( zErr ){
  192307. sqlite3_result_error(pCtx, zErr, -1);
  192308. sqlite3_free(zErr);
  192309. }else{
  192310. sqlite3_result_error_code(pCtx, rc);
  192311. }
  192312. }
  192313. sqlite3_free((void *)azConfig);
  192314. sqlite3Fts5ConfigFree(pConfig);
  192315. sqlite3Fts5ExprFree(pExpr);
  192316. }
  192317. static void fts5ExprFunctionHr(
  192318. sqlite3_context *pCtx, /* Function call context */
  192319. int nArg, /* Number of args */
  192320. sqlite3_value **apVal /* Function arguments */
  192321. ){
  192322. fts5ExprFunction(pCtx, nArg, apVal, 0);
  192323. }
  192324. static void fts5ExprFunctionTcl(
  192325. sqlite3_context *pCtx, /* Function call context */
  192326. int nArg, /* Number of args */
  192327. sqlite3_value **apVal /* Function arguments */
  192328. ){
  192329. fts5ExprFunction(pCtx, nArg, apVal, 1);
  192330. }
  192331. /*
  192332. ** The implementation of an SQLite user-defined-function that accepts a
  192333. ** single integer as an argument. If the integer is an alpha-numeric
  192334. ** unicode code point, 1 is returned. Otherwise 0.
  192335. */
  192336. static void fts5ExprIsAlnum(
  192337. sqlite3_context *pCtx, /* Function call context */
  192338. int nArg, /* Number of args */
  192339. sqlite3_value **apVal /* Function arguments */
  192340. ){
  192341. int iCode;
  192342. u8 aArr[32];
  192343. if( nArg!=1 ){
  192344. sqlite3_result_error(pCtx,
  192345. "wrong number of arguments to function fts5_isalnum", -1
  192346. );
  192347. return;
  192348. }
  192349. memset(aArr, 0, sizeof(aArr));
  192350. sqlite3Fts5UnicodeCatParse("L*", aArr);
  192351. sqlite3Fts5UnicodeCatParse("N*", aArr);
  192352. sqlite3Fts5UnicodeCatParse("Co", aArr);
  192353. iCode = sqlite3_value_int(apVal[0]);
  192354. sqlite3_result_int(pCtx, aArr[sqlite3Fts5UnicodeCategory(iCode)]);
  192355. }
  192356. static void fts5ExprFold(
  192357. sqlite3_context *pCtx, /* Function call context */
  192358. int nArg, /* Number of args */
  192359. sqlite3_value **apVal /* Function arguments */
  192360. ){
  192361. if( nArg!=1 && nArg!=2 ){
  192362. sqlite3_result_error(pCtx,
  192363. "wrong number of arguments to function fts5_fold", -1
  192364. );
  192365. }else{
  192366. int iCode;
  192367. int bRemoveDiacritics = 0;
  192368. iCode = sqlite3_value_int(apVal[0]);
  192369. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  192370. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  192371. }
  192372. }
  192373. /*
  192374. ** This is called during initialization to register the fts5_expr() scalar
  192375. ** UDF with the SQLite handle passed as the only argument.
  192376. */
  192377. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  192378. struct Fts5ExprFunc {
  192379. const char *z;
  192380. void (*x)(sqlite3_context*,int,sqlite3_value**);
  192381. } aFunc[] = {
  192382. { "fts5_expr", fts5ExprFunctionHr },
  192383. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  192384. { "fts5_isalnum", fts5ExprIsAlnum },
  192385. { "fts5_fold", fts5ExprFold },
  192386. };
  192387. int i;
  192388. int rc = SQLITE_OK;
  192389. void *pCtx = (void*)pGlobal;
  192390. for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
  192391. struct Fts5ExprFunc *p = &aFunc[i];
  192392. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  192393. }
  192394. /* Avoid warnings indicating that sqlite3Fts5ParserTrace() and
  192395. ** sqlite3Fts5ParserFallback() are unused */
  192396. #ifndef NDEBUG
  192397. (void)sqlite3Fts5ParserTrace;
  192398. #endif
  192399. (void)sqlite3Fts5ParserFallback;
  192400. return rc;
  192401. }
  192402. /*
  192403. ** Return the number of phrases in expression pExpr.
  192404. */
  192405. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  192406. return (pExpr ? pExpr->nPhrase : 0);
  192407. }
  192408. /*
  192409. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  192410. */
  192411. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  192412. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  192413. return pExpr->apExprPhrase[iPhrase]->nTerm;
  192414. }
  192415. /*
  192416. ** This function is used to access the current position list for phrase
  192417. ** iPhrase.
  192418. */
  192419. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  192420. int nRet;
  192421. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  192422. Fts5ExprNode *pNode = pPhrase->pNode;
  192423. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  192424. *pa = pPhrase->poslist.p;
  192425. nRet = pPhrase->poslist.n;
  192426. }else{
  192427. *pa = 0;
  192428. nRet = 0;
  192429. }
  192430. return nRet;
  192431. }
  192432. struct Fts5PoslistPopulator {
  192433. Fts5PoslistWriter writer;
  192434. int bOk; /* True if ok to populate */
  192435. int bMiss;
  192436. };
  192437. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
  192438. Fts5PoslistPopulator *pRet;
  192439. pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  192440. if( pRet ){
  192441. int i;
  192442. memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  192443. for(i=0; i<pExpr->nPhrase; i++){
  192444. Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
  192445. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  192446. assert( pExpr->apExprPhrase[i]->nTerm==1 );
  192447. if( bLive &&
  192448. (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
  192449. ){
  192450. pRet[i].bMiss = 1;
  192451. }else{
  192452. pBuf->n = 0;
  192453. }
  192454. }
  192455. }
  192456. return pRet;
  192457. }
  192458. struct Fts5ExprCtx {
  192459. Fts5Expr *pExpr;
  192460. Fts5PoslistPopulator *aPopulator;
  192461. i64 iOff;
  192462. };
  192463. typedef struct Fts5ExprCtx Fts5ExprCtx;
  192464. /*
  192465. ** TODO: Make this more efficient!
  192466. */
  192467. static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
  192468. int i;
  192469. for(i=0; i<pColset->nCol; i++){
  192470. if( pColset->aiCol[i]==iCol ) return 1;
  192471. }
  192472. return 0;
  192473. }
  192474. static int fts5ExprPopulatePoslistsCb(
  192475. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  192476. int tflags, /* Mask of FTS5_TOKEN_* flags */
  192477. const char *pToken, /* Pointer to buffer containing token */
  192478. int nToken, /* Size of token in bytes */
  192479. int iUnused1, /* Byte offset of token within input text */
  192480. int iUnused2 /* Byte offset of end of token within input text */
  192481. ){
  192482. Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
  192483. Fts5Expr *pExpr = p->pExpr;
  192484. int i;
  192485. UNUSED_PARAM2(iUnused1, iUnused2);
  192486. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  192487. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
  192488. for(i=0; i<pExpr->nPhrase; i++){
  192489. Fts5ExprTerm *pTerm;
  192490. if( p->aPopulator[i].bOk==0 ) continue;
  192491. for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  192492. int nTerm = (int)strlen(pTerm->zTerm);
  192493. if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
  192494. && memcmp(pTerm->zTerm, pToken, nTerm)==0
  192495. ){
  192496. int rc = sqlite3Fts5PoslistWriterAppend(
  192497. &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
  192498. );
  192499. if( rc ) return rc;
  192500. break;
  192501. }
  192502. }
  192503. }
  192504. return SQLITE_OK;
  192505. }
  192506. static int sqlite3Fts5ExprPopulatePoslists(
  192507. Fts5Config *pConfig,
  192508. Fts5Expr *pExpr,
  192509. Fts5PoslistPopulator *aPopulator,
  192510. int iCol,
  192511. const char *z, int n
  192512. ){
  192513. int i;
  192514. Fts5ExprCtx sCtx;
  192515. sCtx.pExpr = pExpr;
  192516. sCtx.aPopulator = aPopulator;
  192517. sCtx.iOff = (((i64)iCol) << 32) - 1;
  192518. for(i=0; i<pExpr->nPhrase; i++){
  192519. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  192520. Fts5Colset *pColset = pNode->pNear->pColset;
  192521. if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
  192522. || aPopulator[i].bMiss
  192523. ){
  192524. aPopulator[i].bOk = 0;
  192525. }else{
  192526. aPopulator[i].bOk = 1;
  192527. }
  192528. }
  192529. return sqlite3Fts5Tokenize(pConfig,
  192530. FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
  192531. );
  192532. }
  192533. static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
  192534. if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
  192535. pNode->pNear->apPhrase[0]->poslist.n = 0;
  192536. }else{
  192537. int i;
  192538. for(i=0; i<pNode->nChild; i++){
  192539. fts5ExprClearPoslists(pNode->apChild[i]);
  192540. }
  192541. }
  192542. }
  192543. static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
  192544. pNode->iRowid = iRowid;
  192545. pNode->bEof = 0;
  192546. switch( pNode->eType ){
  192547. case FTS5_TERM:
  192548. case FTS5_STRING:
  192549. return (pNode->pNear->apPhrase[0]->poslist.n>0);
  192550. case FTS5_AND: {
  192551. int i;
  192552. for(i=0; i<pNode->nChild; i++){
  192553. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
  192554. fts5ExprClearPoslists(pNode);
  192555. return 0;
  192556. }
  192557. }
  192558. break;
  192559. }
  192560. case FTS5_OR: {
  192561. int i;
  192562. int bRet = 0;
  192563. for(i=0; i<pNode->nChild; i++){
  192564. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
  192565. bRet = 1;
  192566. }
  192567. }
  192568. return bRet;
  192569. }
  192570. default: {
  192571. assert( pNode->eType==FTS5_NOT );
  192572. if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
  192573. || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
  192574. ){
  192575. fts5ExprClearPoslists(pNode);
  192576. return 0;
  192577. }
  192578. break;
  192579. }
  192580. }
  192581. return 1;
  192582. }
  192583. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
  192584. fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
  192585. }
  192586. /*
  192587. ** This function is only called for detail=columns tables.
  192588. */
  192589. static int sqlite3Fts5ExprPhraseCollist(
  192590. Fts5Expr *pExpr,
  192591. int iPhrase,
  192592. const u8 **ppCollist,
  192593. int *pnCollist
  192594. ){
  192595. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  192596. Fts5ExprNode *pNode = pPhrase->pNode;
  192597. int rc = SQLITE_OK;
  192598. assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
  192599. assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  192600. if( pNode->bEof==0
  192601. && pNode->iRowid==pExpr->pRoot->iRowid
  192602. && pPhrase->poslist.n>0
  192603. ){
  192604. Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
  192605. if( pTerm->pSynonym ){
  192606. Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
  192607. rc = fts5ExprSynonymList(
  192608. pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
  192609. );
  192610. }else{
  192611. *ppCollist = pPhrase->aTerm[0].pIter->pData;
  192612. *pnCollist = pPhrase->aTerm[0].pIter->nData;
  192613. }
  192614. }else{
  192615. *ppCollist = 0;
  192616. *pnCollist = 0;
  192617. }
  192618. return rc;
  192619. }
  192620. /*
  192621. ** 2014 August 11
  192622. **
  192623. ** The author disclaims copyright to this source code. In place of
  192624. ** a legal notice, here is a blessing:
  192625. **
  192626. ** May you do good and not evil.
  192627. ** May you find forgiveness for yourself and forgive others.
  192628. ** May you share freely, never taking more than you give.
  192629. **
  192630. ******************************************************************************
  192631. **
  192632. */
  192633. /* #include "fts5Int.h" */
  192634. typedef struct Fts5HashEntry Fts5HashEntry;
  192635. /*
  192636. ** This file contains the implementation of an in-memory hash table used
  192637. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  192638. ** segment.
  192639. */
  192640. struct Fts5Hash {
  192641. int eDetail; /* Copy of Fts5Config.eDetail */
  192642. int *pnByte; /* Pointer to bytes counter */
  192643. int nEntry; /* Number of entries currently in hash */
  192644. int nSlot; /* Size of aSlot[] array */
  192645. Fts5HashEntry *pScan; /* Current ordered scan item */
  192646. Fts5HashEntry **aSlot; /* Array of hash slots */
  192647. };
  192648. /*
  192649. ** Each entry in the hash table is represented by an object of the
  192650. ** following type. Each object, its key (a nul-terminated string) and
  192651. ** its current data are stored in a single memory allocation. The
  192652. ** key immediately follows the object in memory. The position list
  192653. ** data immediately follows the key data in memory.
  192654. **
  192655. ** The data that follows the key is in a similar, but not identical format
  192656. ** to the doclist data stored in the database. It is:
  192657. **
  192658. ** * Rowid, as a varint
  192659. ** * Position list, without 0x00 terminator.
  192660. ** * Size of previous position list and rowid, as a 4 byte
  192661. ** big-endian integer.
  192662. **
  192663. ** iRowidOff:
  192664. ** Offset of last rowid written to data area. Relative to first byte of
  192665. ** structure.
  192666. **
  192667. ** nData:
  192668. ** Bytes of data written since iRowidOff.
  192669. */
  192670. struct Fts5HashEntry {
  192671. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  192672. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  192673. int nAlloc; /* Total size of allocation */
  192674. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  192675. int nData; /* Total bytes of data (incl. structure) */
  192676. int nKey; /* Length of key in bytes */
  192677. u8 bDel; /* Set delete-flag @ iSzPoslist */
  192678. u8 bContent; /* Set content-flag (detail=none mode) */
  192679. i16 iCol; /* Column of last value written */
  192680. int iPos; /* Position of last value written */
  192681. i64 iRowid; /* Rowid of last value written */
  192682. };
  192683. /*
  192684. ** Eqivalent to:
  192685. **
  192686. ** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
  192687. */
  192688. #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
  192689. /*
  192690. ** Allocate a new hash table.
  192691. */
  192692. static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
  192693. int rc = SQLITE_OK;
  192694. Fts5Hash *pNew;
  192695. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  192696. if( pNew==0 ){
  192697. rc = SQLITE_NOMEM;
  192698. }else{
  192699. int nByte;
  192700. memset(pNew, 0, sizeof(Fts5Hash));
  192701. pNew->pnByte = pnByte;
  192702. pNew->eDetail = pConfig->eDetail;
  192703. pNew->nSlot = 1024;
  192704. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  192705. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
  192706. if( pNew->aSlot==0 ){
  192707. sqlite3_free(pNew);
  192708. *ppNew = 0;
  192709. rc = SQLITE_NOMEM;
  192710. }else{
  192711. memset(pNew->aSlot, 0, nByte);
  192712. }
  192713. }
  192714. return rc;
  192715. }
  192716. /*
  192717. ** Free a hash table object.
  192718. */
  192719. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  192720. if( pHash ){
  192721. sqlite3Fts5HashClear(pHash);
  192722. sqlite3_free(pHash->aSlot);
  192723. sqlite3_free(pHash);
  192724. }
  192725. }
  192726. /*
  192727. ** Empty (but do not delete) a hash table.
  192728. */
  192729. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  192730. int i;
  192731. for(i=0; i<pHash->nSlot; i++){
  192732. Fts5HashEntry *pNext;
  192733. Fts5HashEntry *pSlot;
  192734. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  192735. pNext = pSlot->pHashNext;
  192736. sqlite3_free(pSlot);
  192737. }
  192738. }
  192739. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  192740. pHash->nEntry = 0;
  192741. }
  192742. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  192743. int i;
  192744. unsigned int h = 13;
  192745. for(i=n-1; i>=0; i--){
  192746. h = (h << 3) ^ h ^ p[i];
  192747. }
  192748. return (h % nSlot);
  192749. }
  192750. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  192751. int i;
  192752. unsigned int h = 13;
  192753. for(i=n-1; i>=0; i--){
  192754. h = (h << 3) ^ h ^ p[i];
  192755. }
  192756. h = (h << 3) ^ h ^ b;
  192757. return (h % nSlot);
  192758. }
  192759. /*
  192760. ** Resize the hash table by doubling the number of slots.
  192761. */
  192762. static int fts5HashResize(Fts5Hash *pHash){
  192763. int nNew = pHash->nSlot*2;
  192764. int i;
  192765. Fts5HashEntry **apNew;
  192766. Fts5HashEntry **apOld = pHash->aSlot;
  192767. apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
  192768. if( !apNew ) return SQLITE_NOMEM;
  192769. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  192770. for(i=0; i<pHash->nSlot; i++){
  192771. while( apOld[i] ){
  192772. unsigned int iHash;
  192773. Fts5HashEntry *p = apOld[i];
  192774. apOld[i] = p->pHashNext;
  192775. iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
  192776. (int)strlen(fts5EntryKey(p)));
  192777. p->pHashNext = apNew[iHash];
  192778. apNew[iHash] = p;
  192779. }
  192780. }
  192781. sqlite3_free(apOld);
  192782. pHash->nSlot = nNew;
  192783. pHash->aSlot = apNew;
  192784. return SQLITE_OK;
  192785. }
  192786. static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
  192787. if( p->iSzPoslist ){
  192788. u8 *pPtr = (u8*)p;
  192789. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  192790. assert( p->nData==p->iSzPoslist );
  192791. if( p->bDel ){
  192792. pPtr[p->nData++] = 0x00;
  192793. if( p->bContent ){
  192794. pPtr[p->nData++] = 0x00;
  192795. }
  192796. }
  192797. }else{
  192798. int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
  192799. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  192800. assert( p->bDel==0 || p->bDel==1 );
  192801. if( nPos<=127 ){
  192802. pPtr[p->iSzPoslist] = (u8)nPos;
  192803. }else{
  192804. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  192805. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  192806. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  192807. p->nData += (nByte-1);
  192808. }
  192809. }
  192810. p->iSzPoslist = 0;
  192811. p->bDel = 0;
  192812. p->bContent = 0;
  192813. }
  192814. }
  192815. /*
  192816. ** Add an entry to the in-memory hash table. The key is the concatenation
  192817. ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
  192818. **
  192819. ** (bByte || pToken) -> (iRowid,iCol,iPos)
  192820. **
  192821. ** Or, if iCol is negative, then the value is a delete marker.
  192822. */
  192823. static int sqlite3Fts5HashWrite(
  192824. Fts5Hash *pHash,
  192825. i64 iRowid, /* Rowid for this entry */
  192826. int iCol, /* Column token appears in (-ve -> delete) */
  192827. int iPos, /* Position of token within column */
  192828. char bByte, /* First byte of token */
  192829. const char *pToken, int nToken /* Token to add or remove to or from index */
  192830. ){
  192831. unsigned int iHash;
  192832. Fts5HashEntry *p;
  192833. u8 *pPtr;
  192834. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  192835. int bNew; /* If non-delete entry should be written */
  192836. bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
  192837. /* Attempt to locate an existing hash entry */
  192838. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  192839. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  192840. char *zKey = fts5EntryKey(p);
  192841. if( zKey[0]==bByte
  192842. && p->nKey==nToken
  192843. && memcmp(&zKey[1], pToken, nToken)==0
  192844. ){
  192845. break;
  192846. }
  192847. }
  192848. /* If an existing hash entry cannot be found, create a new one. */
  192849. if( p==0 ){
  192850. /* Figure out how much space to allocate */
  192851. char *zKey;
  192852. int nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
  192853. if( nByte<128 ) nByte = 128;
  192854. /* Grow the Fts5Hash.aSlot[] array if necessary. */
  192855. if( (pHash->nEntry*2)>=pHash->nSlot ){
  192856. int rc = fts5HashResize(pHash);
  192857. if( rc!=SQLITE_OK ) return rc;
  192858. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  192859. }
  192860. /* Allocate new Fts5HashEntry and add it to the hash table. */
  192861. p = (Fts5HashEntry*)sqlite3_malloc(nByte);
  192862. if( !p ) return SQLITE_NOMEM;
  192863. memset(p, 0, sizeof(Fts5HashEntry));
  192864. p->nAlloc = nByte;
  192865. zKey = fts5EntryKey(p);
  192866. zKey[0] = bByte;
  192867. memcpy(&zKey[1], pToken, nToken);
  192868. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
  192869. p->nKey = nToken;
  192870. zKey[nToken+1] = '\0';
  192871. p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
  192872. p->pHashNext = pHash->aSlot[iHash];
  192873. pHash->aSlot[iHash] = p;
  192874. pHash->nEntry++;
  192875. /* Add the first rowid field to the hash-entry */
  192876. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  192877. p->iRowid = iRowid;
  192878. p->iSzPoslist = p->nData;
  192879. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  192880. p->nData += 1;
  192881. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  192882. }
  192883. nIncr += p->nData;
  192884. }else{
  192885. /* Appending to an existing hash-entry. Check that there is enough
  192886. ** space to append the largest possible new entry. Worst case scenario
  192887. ** is:
  192888. **
  192889. ** + 9 bytes for a new rowid,
  192890. ** + 4 byte reserved for the "poslist size" varint.
  192891. ** + 1 byte for a "new column" byte,
  192892. ** + 3 bytes for a new column number (16-bit max) as a varint,
  192893. ** + 5 bytes for the new position offset (32-bit max).
  192894. */
  192895. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  192896. int nNew = p->nAlloc * 2;
  192897. Fts5HashEntry *pNew;
  192898. Fts5HashEntry **pp;
  192899. pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
  192900. if( pNew==0 ) return SQLITE_NOMEM;
  192901. pNew->nAlloc = nNew;
  192902. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  192903. *pp = pNew;
  192904. p = pNew;
  192905. }
  192906. nIncr -= p->nData;
  192907. }
  192908. assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
  192909. pPtr = (u8*)p;
  192910. /* If this is a new rowid, append the 4-byte size field for the previous
  192911. ** entry, and the new rowid for this entry. */
  192912. if( iRowid!=p->iRowid ){
  192913. fts5HashAddPoslistSize(pHash, p);
  192914. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  192915. p->iRowid = iRowid;
  192916. bNew = 1;
  192917. p->iSzPoslist = p->nData;
  192918. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  192919. p->nData += 1;
  192920. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  192921. p->iPos = 0;
  192922. }
  192923. }
  192924. if( iCol>=0 ){
  192925. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  192926. p->bContent = 1;
  192927. }else{
  192928. /* Append a new column value, if necessary */
  192929. assert( iCol>=p->iCol );
  192930. if( iCol!=p->iCol ){
  192931. if( pHash->eDetail==FTS5_DETAIL_FULL ){
  192932. pPtr[p->nData++] = 0x01;
  192933. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  192934. p->iCol = (i16)iCol;
  192935. p->iPos = 0;
  192936. }else{
  192937. bNew = 1;
  192938. p->iCol = (i16)(iPos = iCol);
  192939. }
  192940. }
  192941. /* Append the new position offset, if necessary */
  192942. if( bNew ){
  192943. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  192944. p->iPos = iPos;
  192945. }
  192946. }
  192947. }else{
  192948. /* This is a delete. Set the delete flag. */
  192949. p->bDel = 1;
  192950. }
  192951. nIncr += p->nData;
  192952. *pHash->pnByte += nIncr;
  192953. return SQLITE_OK;
  192954. }
  192955. /*
  192956. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  192957. ** each sorted in key order. This function merges the two lists into a
  192958. ** single list and returns a pointer to its first element.
  192959. */
  192960. static Fts5HashEntry *fts5HashEntryMerge(
  192961. Fts5HashEntry *pLeft,
  192962. Fts5HashEntry *pRight
  192963. ){
  192964. Fts5HashEntry *p1 = pLeft;
  192965. Fts5HashEntry *p2 = pRight;
  192966. Fts5HashEntry *pRet = 0;
  192967. Fts5HashEntry **ppOut = &pRet;
  192968. while( p1 || p2 ){
  192969. if( p1==0 ){
  192970. *ppOut = p2;
  192971. p2 = 0;
  192972. }else if( p2==0 ){
  192973. *ppOut = p1;
  192974. p1 = 0;
  192975. }else{
  192976. int i = 0;
  192977. char *zKey1 = fts5EntryKey(p1);
  192978. char *zKey2 = fts5EntryKey(p2);
  192979. while( zKey1[i]==zKey2[i] ) i++;
  192980. if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
  192981. /* p2 is smaller */
  192982. *ppOut = p2;
  192983. ppOut = &p2->pScanNext;
  192984. p2 = p2->pScanNext;
  192985. }else{
  192986. /* p1 is smaller */
  192987. *ppOut = p1;
  192988. ppOut = &p1->pScanNext;
  192989. p1 = p1->pScanNext;
  192990. }
  192991. *ppOut = 0;
  192992. }
  192993. }
  192994. return pRet;
  192995. }
  192996. /*
  192997. ** Extract all tokens from hash table iHash and link them into a list
  192998. ** in sorted order. The hash table is cleared before returning. It is
  192999. ** the responsibility of the caller to free the elements of the returned
  193000. ** list.
  193001. */
  193002. static int fts5HashEntrySort(
  193003. Fts5Hash *pHash,
  193004. const char *pTerm, int nTerm, /* Query prefix, if any */
  193005. Fts5HashEntry **ppSorted
  193006. ){
  193007. const int nMergeSlot = 32;
  193008. Fts5HashEntry **ap;
  193009. Fts5HashEntry *pList;
  193010. int iSlot;
  193011. int i;
  193012. *ppSorted = 0;
  193013. ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
  193014. if( !ap ) return SQLITE_NOMEM;
  193015. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  193016. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  193017. Fts5HashEntry *pIter;
  193018. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  193019. if( pTerm==0 || 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm) ){
  193020. Fts5HashEntry *pEntry = pIter;
  193021. pEntry->pScanNext = 0;
  193022. for(i=0; ap[i]; i++){
  193023. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  193024. ap[i] = 0;
  193025. }
  193026. ap[i] = pEntry;
  193027. }
  193028. }
  193029. }
  193030. pList = 0;
  193031. for(i=0; i<nMergeSlot; i++){
  193032. pList = fts5HashEntryMerge(pList, ap[i]);
  193033. }
  193034. pHash->nEntry = 0;
  193035. sqlite3_free(ap);
  193036. *ppSorted = pList;
  193037. return SQLITE_OK;
  193038. }
  193039. /*
  193040. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  193041. */
  193042. static int sqlite3Fts5HashQuery(
  193043. Fts5Hash *pHash, /* Hash table to query */
  193044. const char *pTerm, int nTerm, /* Query term */
  193045. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  193046. int *pnDoclist /* OUT: Size of doclist in bytes */
  193047. ){
  193048. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  193049. char *zKey = 0;
  193050. Fts5HashEntry *p;
  193051. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  193052. zKey = fts5EntryKey(p);
  193053. if( memcmp(zKey, pTerm, nTerm)==0 && zKey[nTerm]==0 ) break;
  193054. }
  193055. if( p ){
  193056. fts5HashAddPoslistSize(pHash, p);
  193057. *ppDoclist = (const u8*)&zKey[nTerm+1];
  193058. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  193059. }else{
  193060. *ppDoclist = 0;
  193061. *pnDoclist = 0;
  193062. }
  193063. return SQLITE_OK;
  193064. }
  193065. static int sqlite3Fts5HashScanInit(
  193066. Fts5Hash *p, /* Hash table to query */
  193067. const char *pTerm, int nTerm /* Query prefix */
  193068. ){
  193069. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  193070. }
  193071. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  193072. assert( !sqlite3Fts5HashScanEof(p) );
  193073. p->pScan = p->pScan->pScanNext;
  193074. }
  193075. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  193076. return (p->pScan==0);
  193077. }
  193078. static void sqlite3Fts5HashScanEntry(
  193079. Fts5Hash *pHash,
  193080. const char **pzTerm, /* OUT: term (nul-terminated) */
  193081. const u8 **ppDoclist, /* OUT: pointer to doclist */
  193082. int *pnDoclist /* OUT: size of doclist in bytes */
  193083. ){
  193084. Fts5HashEntry *p;
  193085. if( (p = pHash->pScan) ){
  193086. char *zKey = fts5EntryKey(p);
  193087. int nTerm = (int)strlen(zKey);
  193088. fts5HashAddPoslistSize(pHash, p);
  193089. *pzTerm = zKey;
  193090. *ppDoclist = (const u8*)&zKey[nTerm+1];
  193091. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  193092. }else{
  193093. *pzTerm = 0;
  193094. *ppDoclist = 0;
  193095. *pnDoclist = 0;
  193096. }
  193097. }
  193098. /*
  193099. ** 2014 May 31
  193100. **
  193101. ** The author disclaims copyright to this source code. In place of
  193102. ** a legal notice, here is a blessing:
  193103. **
  193104. ** May you do good and not evil.
  193105. ** May you find forgiveness for yourself and forgive others.
  193106. ** May you share freely, never taking more than you give.
  193107. **
  193108. ******************************************************************************
  193109. **
  193110. ** Low level access to the FTS index stored in the database file. The
  193111. ** routines in this file file implement all read and write access to the
  193112. ** %_data table. Other parts of the system access this functionality via
  193113. ** the interface defined in fts5Int.h.
  193114. */
  193115. /* #include "fts5Int.h" */
  193116. /*
  193117. ** Overview:
  193118. **
  193119. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  193120. ** As well as the main term index, there may be up to 31 prefix indexes.
  193121. ** The format is similar to FTS3/4, except that:
  193122. **
  193123. ** * all segment b-tree leaf data is stored in fixed size page records
  193124. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  193125. ** taken to ensure it is possible to iterate in either direction through
  193126. ** the entries in a doclist, or to seek to a specific entry within a
  193127. ** doclist, without loading it into memory.
  193128. **
  193129. ** * large doclists that span many pages have associated "doclist index"
  193130. ** records that contain a copy of the first rowid on each page spanned by
  193131. ** the doclist. This is used to speed up seek operations, and merges of
  193132. ** large doclists with very small doclists.
  193133. **
  193134. ** * extra fields in the "structure record" record the state of ongoing
  193135. ** incremental merge operations.
  193136. **
  193137. */
  193138. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  193139. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  193140. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  193141. #define FTS5_MAIN_PREFIX '0'
  193142. #if FTS5_MAX_PREFIX_INDEXES > 31
  193143. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  193144. #endif
  193145. /*
  193146. ** Details:
  193147. **
  193148. ** The %_data table managed by this module,
  193149. **
  193150. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  193151. **
  193152. ** , contains the following 5 types of records. See the comments surrounding
  193153. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  193154. ** assigned to each fo them.
  193155. **
  193156. ** 1. Structure Records:
  193157. **
  193158. ** The set of segments that make up an index - the index structure - are
  193159. ** recorded in a single record within the %_data table. The record consists
  193160. ** of a single 32-bit configuration cookie value followed by a list of
  193161. ** SQLite varints. If the FTS table features more than one index (because
  193162. ** there are one or more prefix indexes), it is guaranteed that all share
  193163. ** the same cookie value.
  193164. **
  193165. ** Immediately following the configuration cookie, the record begins with
  193166. ** three varints:
  193167. **
  193168. ** + number of levels,
  193169. ** + total number of segments on all levels,
  193170. ** + value of write counter.
  193171. **
  193172. ** Then, for each level from 0 to nMax:
  193173. **
  193174. ** + number of input segments in ongoing merge.
  193175. ** + total number of segments in level.
  193176. ** + for each segment from oldest to newest:
  193177. ** + segment id (always > 0)
  193178. ** + first leaf page number (often 1, always greater than 0)
  193179. ** + final leaf page number
  193180. **
  193181. ** 2. The Averages Record:
  193182. **
  193183. ** A single record within the %_data table. The data is a list of varints.
  193184. ** The first value is the number of rows in the index. Then, for each column
  193185. ** from left to right, the total number of tokens in the column for all
  193186. ** rows of the table.
  193187. **
  193188. ** 3. Segment leaves:
  193189. **
  193190. ** TERM/DOCLIST FORMAT:
  193191. **
  193192. ** Most of each segment leaf is taken up by term/doclist data. The
  193193. ** general format of term/doclist, starting with the first term
  193194. ** on the leaf page, is:
  193195. **
  193196. ** varint : size of first term
  193197. ** blob: first term data
  193198. ** doclist: first doclist
  193199. ** zero-or-more {
  193200. ** varint: number of bytes in common with previous term
  193201. ** varint: number of bytes of new term data (nNew)
  193202. ** blob: nNew bytes of new term data
  193203. ** doclist: next doclist
  193204. ** }
  193205. **
  193206. ** doclist format:
  193207. **
  193208. ** varint: first rowid
  193209. ** poslist: first poslist
  193210. ** zero-or-more {
  193211. ** varint: rowid delta (always > 0)
  193212. ** poslist: next poslist
  193213. ** }
  193214. **
  193215. ** poslist format:
  193216. **
  193217. ** varint: size of poslist in bytes multiplied by 2, not including
  193218. ** this field. Plus 1 if this entry carries the "delete" flag.
  193219. ** collist: collist for column 0
  193220. ** zero-or-more {
  193221. ** 0x01 byte
  193222. ** varint: column number (I)
  193223. ** collist: collist for column I
  193224. ** }
  193225. **
  193226. ** collist format:
  193227. **
  193228. ** varint: first offset + 2
  193229. ** zero-or-more {
  193230. ** varint: offset delta + 2
  193231. ** }
  193232. **
  193233. ** PAGE FORMAT
  193234. **
  193235. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  193236. ** unsigned integer fields in big-endian format. They are:
  193237. **
  193238. ** * The byte offset of the first rowid on the page, if it exists
  193239. ** and occurs before the first term (otherwise 0).
  193240. **
  193241. ** * The byte offset of the start of the page footer. If the page
  193242. ** footer is 0 bytes in size, then this field is the same as the
  193243. ** size of the leaf page in bytes.
  193244. **
  193245. ** The page footer consists of a single varint for each term located
  193246. ** on the page. Each varint is the byte offset of the current term
  193247. ** within the page, delta-compressed against the previous value. In
  193248. ** other words, the first varint in the footer is the byte offset of
  193249. ** the first term, the second is the byte offset of the second less that
  193250. ** of the first, and so on.
  193251. **
  193252. ** The term/doclist format described above is accurate if the entire
  193253. ** term/doclist data fits on a single leaf page. If this is not the case,
  193254. ** the format is changed in two ways:
  193255. **
  193256. ** + if the first rowid on a page occurs before the first term, it
  193257. ** is stored as a literal value:
  193258. **
  193259. ** varint: first rowid
  193260. **
  193261. ** + the first term on each page is stored in the same way as the
  193262. ** very first term of the segment:
  193263. **
  193264. ** varint : size of first term
  193265. ** blob: first term data
  193266. **
  193267. ** 5. Segment doclist indexes:
  193268. **
  193269. ** Doclist indexes are themselves b-trees, however they usually consist of
  193270. ** a single leaf record only. The format of each doclist index leaf page
  193271. ** is:
  193272. **
  193273. ** * Flags byte. Bits are:
  193274. ** 0x01: Clear if leaf is also the root page, otherwise set.
  193275. **
  193276. ** * Page number of fts index leaf page. As a varint.
  193277. **
  193278. ** * First rowid on page indicated by previous field. As a varint.
  193279. **
  193280. ** * A list of varints, one for each subsequent termless page. A
  193281. ** positive delta if the termless page contains at least one rowid,
  193282. ** or an 0x00 byte otherwise.
  193283. **
  193284. ** Internal doclist index nodes are:
  193285. **
  193286. ** * Flags byte. Bits are:
  193287. ** 0x01: Clear for root page, otherwise set.
  193288. **
  193289. ** * Page number of first child page. As a varint.
  193290. **
  193291. ** * Copy of first rowid on page indicated by previous field. As a varint.
  193292. **
  193293. ** * A list of delta-encoded varints - the first rowid on each subsequent
  193294. ** child page.
  193295. **
  193296. */
  193297. /*
  193298. ** Rowids for the averages and structure records in the %_data table.
  193299. */
  193300. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  193301. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  193302. /*
  193303. ** Macros determining the rowids used by segment leaves and dlidx leaves
  193304. ** and nodes. All nodes and leaves are stored in the %_data table with large
  193305. ** positive rowids.
  193306. **
  193307. ** Each segment has a unique non-zero 16-bit id.
  193308. **
  193309. ** The rowid for each segment leaf is found by passing the segment id and
  193310. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  193311. ** sequentially starting from 1.
  193312. */
  193313. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  193314. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  193315. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  193316. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  193317. #define fts5_dri(segid, dlidx, height, pgno) ( \
  193318. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  193319. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  193320. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  193321. ((i64)(pgno)) \
  193322. )
  193323. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  193324. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  193325. /*
  193326. ** Maximum segments permitted in a single index
  193327. */
  193328. #define FTS5_MAX_SEGMENT 2000
  193329. #ifdef SQLITE_DEBUG
  193330. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  193331. #endif
  193332. /*
  193333. ** Each time a blob is read from the %_data table, it is padded with this
  193334. ** many zero bytes. This makes it easier to decode the various record formats
  193335. ** without overreading if the records are corrupt.
  193336. */
  193337. #define FTS5_DATA_ZERO_PADDING 8
  193338. #define FTS5_DATA_PADDING 20
  193339. typedef struct Fts5Data Fts5Data;
  193340. typedef struct Fts5DlidxIter Fts5DlidxIter;
  193341. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  193342. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  193343. typedef struct Fts5Iter Fts5Iter;
  193344. typedef struct Fts5PageWriter Fts5PageWriter;
  193345. typedef struct Fts5SegIter Fts5SegIter;
  193346. typedef struct Fts5DoclistIter Fts5DoclistIter;
  193347. typedef struct Fts5SegWriter Fts5SegWriter;
  193348. typedef struct Fts5Structure Fts5Structure;
  193349. typedef struct Fts5StructureLevel Fts5StructureLevel;
  193350. typedef struct Fts5StructureSegment Fts5StructureSegment;
  193351. struct Fts5Data {
  193352. u8 *p; /* Pointer to buffer containing record */
  193353. int nn; /* Size of record in bytes */
  193354. int szLeaf; /* Size of leaf without page-index */
  193355. };
  193356. /*
  193357. ** One object per %_data table.
  193358. */
  193359. struct Fts5Index {
  193360. Fts5Config *pConfig; /* Virtual table configuration */
  193361. char *zDataTbl; /* Name of %_data table */
  193362. int nWorkUnit; /* Leaf pages in a "unit" of work */
  193363. /*
  193364. ** Variables related to the accumulation of tokens and doclists within the
  193365. ** in-memory hash tables before they are flushed to disk.
  193366. */
  193367. Fts5Hash *pHash; /* Hash table for in-memory data */
  193368. int nPendingData; /* Current bytes of pending data */
  193369. i64 iWriteRowid; /* Rowid for current doc being written */
  193370. int bDelete; /* Current write is a delete */
  193371. /* Error state. */
  193372. int rc; /* Current error code */
  193373. /* State used by the fts5DataXXX() functions. */
  193374. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  193375. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  193376. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  193377. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  193378. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  193379. sqlite3_stmt *pIdxSelect;
  193380. int nRead; /* Total number of blocks read */
  193381. sqlite3_stmt *pDataVersion;
  193382. i64 iStructVersion; /* data_version when pStruct read */
  193383. Fts5Structure *pStruct; /* Current db structure (or NULL) */
  193384. };
  193385. struct Fts5DoclistIter {
  193386. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  193387. /* Output variables. aPoslist==0 at EOF */
  193388. i64 iRowid;
  193389. u8 *aPoslist;
  193390. int nPoslist;
  193391. int nSize;
  193392. };
  193393. /*
  193394. ** The contents of the "structure" record for each index are represented
  193395. ** using an Fts5Structure record in memory. Which uses instances of the
  193396. ** other Fts5StructureXXX types as components.
  193397. */
  193398. struct Fts5StructureSegment {
  193399. int iSegid; /* Segment id */
  193400. int pgnoFirst; /* First leaf page number in segment */
  193401. int pgnoLast; /* Last leaf page number in segment */
  193402. };
  193403. struct Fts5StructureLevel {
  193404. int nMerge; /* Number of segments in incr-merge */
  193405. int nSeg; /* Total number of segments on level */
  193406. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  193407. };
  193408. struct Fts5Structure {
  193409. int nRef; /* Object reference count */
  193410. u64 nWriteCounter; /* Total leaves written to level 0 */
  193411. int nSegment; /* Total segments in this structure */
  193412. int nLevel; /* Number of levels in this index */
  193413. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  193414. };
  193415. /*
  193416. ** An object of type Fts5SegWriter is used to write to segments.
  193417. */
  193418. struct Fts5PageWriter {
  193419. int pgno; /* Page number for this page */
  193420. int iPrevPgidx; /* Previous value written into pgidx */
  193421. Fts5Buffer buf; /* Buffer containing leaf data */
  193422. Fts5Buffer pgidx; /* Buffer containing page-index */
  193423. Fts5Buffer term; /* Buffer containing previous term on page */
  193424. };
  193425. struct Fts5DlidxWriter {
  193426. int pgno; /* Page number for this page */
  193427. int bPrevValid; /* True if iPrev is valid */
  193428. i64 iPrev; /* Previous rowid value written to page */
  193429. Fts5Buffer buf; /* Buffer containing page data */
  193430. };
  193431. struct Fts5SegWriter {
  193432. int iSegid; /* Segid to write to */
  193433. Fts5PageWriter writer; /* PageWriter object */
  193434. i64 iPrevRowid; /* Previous rowid written to current leaf */
  193435. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  193436. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  193437. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  193438. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  193439. int nLeafWritten; /* Number of leaf pages written */
  193440. int nEmpty; /* Number of contiguous term-less nodes */
  193441. int nDlidx; /* Allocated size of aDlidx[] array */
  193442. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  193443. /* Values to insert into the %_idx table */
  193444. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  193445. int iBtPage; /* Page number corresponding to btterm */
  193446. };
  193447. typedef struct Fts5CResult Fts5CResult;
  193448. struct Fts5CResult {
  193449. u16 iFirst; /* aSeg[] index of firstest iterator */
  193450. u8 bTermEq; /* True if the terms are equal */
  193451. };
  193452. /*
  193453. ** Object for iterating through a single segment, visiting each term/rowid
  193454. ** pair in the segment.
  193455. **
  193456. ** pSeg:
  193457. ** The segment to iterate through.
  193458. **
  193459. ** iLeafPgno:
  193460. ** Current leaf page number within segment.
  193461. **
  193462. ** iLeafOffset:
  193463. ** Byte offset within the current leaf that is the first byte of the
  193464. ** position list data (one byte passed the position-list size field).
  193465. ** rowid field of the current entry. Usually this is the size field of the
  193466. ** position list data. The exception is if the rowid for the current entry
  193467. ** is the last thing on the leaf page.
  193468. **
  193469. ** pLeaf:
  193470. ** Buffer containing current leaf page data. Set to NULL at EOF.
  193471. **
  193472. ** iTermLeafPgno, iTermLeafOffset:
  193473. ** Leaf page number containing the last term read from the segment. And
  193474. ** the offset immediately following the term data.
  193475. **
  193476. ** flags:
  193477. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  193478. **
  193479. ** FTS5_SEGITER_ONETERM:
  193480. ** If set, set the iterator to point to EOF after the current doclist
  193481. ** has been exhausted. Do not proceed to the next term in the segment.
  193482. **
  193483. ** FTS5_SEGITER_REVERSE:
  193484. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  193485. ** it is set, iterate through rowid in descending order instead of the
  193486. ** default ascending order.
  193487. **
  193488. ** iRowidOffset/nRowidOffset/aRowidOffset:
  193489. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  193490. **
  193491. ** For each rowid on the page corresponding to the current term, the
  193492. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  193493. ** start of the "position-list-size" field within the page.
  193494. **
  193495. ** iTermIdx:
  193496. ** Index of current term on iTermLeafPgno.
  193497. */
  193498. struct Fts5SegIter {
  193499. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  193500. int flags; /* Mask of configuration flags */
  193501. int iLeafPgno; /* Current leaf page number */
  193502. Fts5Data *pLeaf; /* Current leaf data */
  193503. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  193504. int iLeafOffset; /* Byte offset within current leaf */
  193505. /* Next method */
  193506. void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
  193507. /* The page and offset from which the current term was read. The offset
  193508. ** is the offset of the first rowid in the current doclist. */
  193509. int iTermLeafPgno;
  193510. int iTermLeafOffset;
  193511. int iPgidxOff; /* Next offset in pgidx */
  193512. int iEndofDoclist;
  193513. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  193514. int iRowidOffset; /* Current entry in aRowidOffset[] */
  193515. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  193516. int *aRowidOffset; /* Array of offset to rowid fields */
  193517. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  193518. /* Variables populated based on current entry. */
  193519. Fts5Buffer term; /* Current term */
  193520. i64 iRowid; /* Current rowid */
  193521. int nPos; /* Number of bytes in current position list */
  193522. u8 bDel; /* True if the delete flag is set */
  193523. };
  193524. /*
  193525. ** Argument is a pointer to an Fts5Data structure that contains a
  193526. ** leaf page.
  193527. */
  193528. #define ASSERT_SZLEAF_OK(x) assert( \
  193529. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  193530. )
  193531. #define FTS5_SEGITER_ONETERM 0x01
  193532. #define FTS5_SEGITER_REVERSE 0x02
  193533. /*
  193534. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  193535. ** page. This macro evaluates to true if the leaf contains no terms, or
  193536. ** false if it contains at least one term.
  193537. */
  193538. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  193539. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  193540. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  193541. /*
  193542. ** Object for iterating through the merged results of one or more segments,
  193543. ** visiting each term/rowid pair in the merged data.
  193544. **
  193545. ** nSeg is always a power of two greater than or equal to the number of
  193546. ** segments that this object is merging data from. Both the aSeg[] and
  193547. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  193548. ** with zeroed objects - these are handled as if they were iterators opened
  193549. ** on empty segments.
  193550. **
  193551. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  193552. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  193553. ** comparison in this context is the index of the iterator that currently
  193554. ** points to the smaller term/rowid combination. Iterators at EOF are
  193555. ** considered to be greater than all other iterators.
  193556. **
  193557. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  193558. ** the smallest key overall. aFirst[0] is unused.
  193559. **
  193560. ** poslist:
  193561. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  193562. ** There is no way to tell if this is populated or not.
  193563. */
  193564. struct Fts5Iter {
  193565. Fts5IndexIter base; /* Base class containing output vars */
  193566. Fts5Index *pIndex; /* Index that owns this iterator */
  193567. Fts5Structure *pStruct; /* Database structure for this iterator */
  193568. Fts5Buffer poslist; /* Buffer containing current poslist */
  193569. Fts5Colset *pColset; /* Restrict matches to these columns */
  193570. /* Invoked to set output variables. */
  193571. void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
  193572. int nSeg; /* Size of aSeg[] array */
  193573. int bRev; /* True to iterate in reverse order */
  193574. u8 bSkipEmpty; /* True to skip deleted entries */
  193575. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  193576. Fts5CResult *aFirst; /* Current merge state (see above) */
  193577. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  193578. };
  193579. /*
  193580. ** An instance of the following type is used to iterate through the contents
  193581. ** of a doclist-index record.
  193582. **
  193583. ** pData:
  193584. ** Record containing the doclist-index data.
  193585. **
  193586. ** bEof:
  193587. ** Set to true once iterator has reached EOF.
  193588. **
  193589. ** iOff:
  193590. ** Set to the current offset within record pData.
  193591. */
  193592. struct Fts5DlidxLvl {
  193593. Fts5Data *pData; /* Data for current page of this level */
  193594. int iOff; /* Current offset into pData */
  193595. int bEof; /* At EOF already */
  193596. int iFirstOff; /* Used by reverse iterators */
  193597. /* Output variables */
  193598. int iLeafPgno; /* Page number of current leaf page */
  193599. i64 iRowid; /* First rowid on leaf iLeafPgno */
  193600. };
  193601. struct Fts5DlidxIter {
  193602. int nLvl;
  193603. int iSegid;
  193604. Fts5DlidxLvl aLvl[1];
  193605. };
  193606. static void fts5PutU16(u8 *aOut, u16 iVal){
  193607. aOut[0] = (iVal>>8);
  193608. aOut[1] = (iVal&0xFF);
  193609. }
  193610. static u16 fts5GetU16(const u8 *aIn){
  193611. return ((u16)aIn[0] << 8) + aIn[1];
  193612. }
  193613. /*
  193614. ** Allocate and return a buffer at least nByte bytes in size.
  193615. **
  193616. ** If an OOM error is encountered, return NULL and set the error code in
  193617. ** the Fts5Index handle passed as the first argument.
  193618. */
  193619. static void *fts5IdxMalloc(Fts5Index *p, int nByte){
  193620. return sqlite3Fts5MallocZero(&p->rc, nByte);
  193621. }
  193622. /*
  193623. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  193624. **
  193625. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  193626. ** +ve if pRight is smaller than pLeft. In other words:
  193627. **
  193628. ** res = *pLeft - *pRight
  193629. */
  193630. #ifdef SQLITE_DEBUG
  193631. static int fts5BufferCompareBlob(
  193632. Fts5Buffer *pLeft, /* Left hand side of comparison */
  193633. const u8 *pRight, int nRight /* Right hand side of comparison */
  193634. ){
  193635. int nCmp = MIN(pLeft->n, nRight);
  193636. int res = memcmp(pLeft->p, pRight, nCmp);
  193637. return (res==0 ? (pLeft->n - nRight) : res);
  193638. }
  193639. #endif
  193640. /*
  193641. ** Compare the contents of the two buffers using memcmp(). If one buffer
  193642. ** is a prefix of the other, it is considered the lesser.
  193643. **
  193644. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  193645. ** +ve if pRight is smaller than pLeft. In other words:
  193646. **
  193647. ** res = *pLeft - *pRight
  193648. */
  193649. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  193650. int nCmp = MIN(pLeft->n, pRight->n);
  193651. int res = memcmp(pLeft->p, pRight->p, nCmp);
  193652. return (res==0 ? (pLeft->n - pRight->n) : res);
  193653. }
  193654. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  193655. int ret;
  193656. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  193657. return ret;
  193658. }
  193659. /*
  193660. ** Close the read-only blob handle, if it is open.
  193661. */
  193662. static void fts5CloseReader(Fts5Index *p){
  193663. if( p->pReader ){
  193664. sqlite3_blob *pReader = p->pReader;
  193665. p->pReader = 0;
  193666. sqlite3_blob_close(pReader);
  193667. }
  193668. }
  193669. /*
  193670. ** Retrieve a record from the %_data table.
  193671. **
  193672. ** If an error occurs, NULL is returned and an error left in the
  193673. ** Fts5Index object.
  193674. */
  193675. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  193676. Fts5Data *pRet = 0;
  193677. if( p->rc==SQLITE_OK ){
  193678. int rc = SQLITE_OK;
  193679. if( p->pReader ){
  193680. /* This call may return SQLITE_ABORT if there has been a savepoint
  193681. ** rollback since it was last used. In this case a new blob handle
  193682. ** is required. */
  193683. sqlite3_blob *pBlob = p->pReader;
  193684. p->pReader = 0;
  193685. rc = sqlite3_blob_reopen(pBlob, iRowid);
  193686. assert( p->pReader==0 );
  193687. p->pReader = pBlob;
  193688. if( rc!=SQLITE_OK ){
  193689. fts5CloseReader(p);
  193690. }
  193691. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  193692. }
  193693. /* If the blob handle is not open at this point, open it and seek
  193694. ** to the requested entry. */
  193695. if( p->pReader==0 && rc==SQLITE_OK ){
  193696. Fts5Config *pConfig = p->pConfig;
  193697. rc = sqlite3_blob_open(pConfig->db,
  193698. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  193699. );
  193700. }
  193701. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  193702. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  193703. ** All the reasons those functions might return SQLITE_ERROR - missing
  193704. ** table, missing row, non-blob/text in block column - indicate
  193705. ** backing store corruption. */
  193706. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  193707. if( rc==SQLITE_OK ){
  193708. u8 *aOut = 0; /* Read blob data into this buffer */
  193709. int nByte = sqlite3_blob_bytes(p->pReader);
  193710. int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  193711. pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
  193712. if( pRet ){
  193713. pRet->nn = nByte;
  193714. aOut = pRet->p = (u8*)&pRet[1];
  193715. }else{
  193716. rc = SQLITE_NOMEM;
  193717. }
  193718. if( rc==SQLITE_OK ){
  193719. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  193720. }
  193721. if( rc!=SQLITE_OK ){
  193722. sqlite3_free(pRet);
  193723. pRet = 0;
  193724. }else{
  193725. /* TODO1: Fix this */
  193726. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  193727. }
  193728. }
  193729. p->rc = rc;
  193730. p->nRead++;
  193731. }
  193732. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  193733. return pRet;
  193734. }
  193735. /*
  193736. ** Release a reference to data record returned by an earlier call to
  193737. ** fts5DataRead().
  193738. */
  193739. static void fts5DataRelease(Fts5Data *pData){
  193740. sqlite3_free(pData);
  193741. }
  193742. static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
  193743. Fts5Data *pRet = fts5DataRead(p, iRowid);
  193744. if( pRet ){
  193745. if( pRet->szLeaf>pRet->nn ){
  193746. p->rc = FTS5_CORRUPT;
  193747. fts5DataRelease(pRet);
  193748. pRet = 0;
  193749. }
  193750. }
  193751. return pRet;
  193752. }
  193753. static int fts5IndexPrepareStmt(
  193754. Fts5Index *p,
  193755. sqlite3_stmt **ppStmt,
  193756. char *zSql
  193757. ){
  193758. if( p->rc==SQLITE_OK ){
  193759. if( zSql ){
  193760. p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
  193761. SQLITE_PREPARE_PERSISTENT, ppStmt, 0);
  193762. }else{
  193763. p->rc = SQLITE_NOMEM;
  193764. }
  193765. }
  193766. sqlite3_free(zSql);
  193767. return p->rc;
  193768. }
  193769. /*
  193770. ** INSERT OR REPLACE a record into the %_data table.
  193771. */
  193772. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  193773. if( p->rc!=SQLITE_OK ) return;
  193774. if( p->pWriter==0 ){
  193775. Fts5Config *pConfig = p->pConfig;
  193776. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  193777. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  193778. pConfig->zDb, pConfig->zName
  193779. ));
  193780. if( p->rc ) return;
  193781. }
  193782. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  193783. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  193784. sqlite3_step(p->pWriter);
  193785. p->rc = sqlite3_reset(p->pWriter);
  193786. sqlite3_bind_null(p->pWriter, 2);
  193787. }
  193788. /*
  193789. ** Execute the following SQL:
  193790. **
  193791. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  193792. */
  193793. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  193794. if( p->rc!=SQLITE_OK ) return;
  193795. if( p->pDeleter==0 ){
  193796. int rc;
  193797. Fts5Config *pConfig = p->pConfig;
  193798. char *zSql = sqlite3_mprintf(
  193799. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  193800. pConfig->zDb, pConfig->zName
  193801. );
  193802. if( zSql==0 ){
  193803. rc = SQLITE_NOMEM;
  193804. }else{
  193805. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  193806. SQLITE_PREPARE_PERSISTENT, &p->pDeleter, 0);
  193807. sqlite3_free(zSql);
  193808. }
  193809. if( rc!=SQLITE_OK ){
  193810. p->rc = rc;
  193811. return;
  193812. }
  193813. }
  193814. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  193815. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  193816. sqlite3_step(p->pDeleter);
  193817. p->rc = sqlite3_reset(p->pDeleter);
  193818. }
  193819. /*
  193820. ** Remove all records associated with segment iSegid.
  193821. */
  193822. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  193823. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  193824. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  193825. fts5DataDelete(p, iFirst, iLast);
  193826. if( p->pIdxDeleter==0 ){
  193827. Fts5Config *pConfig = p->pConfig;
  193828. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  193829. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  193830. pConfig->zDb, pConfig->zName
  193831. ));
  193832. }
  193833. if( p->rc==SQLITE_OK ){
  193834. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  193835. sqlite3_step(p->pIdxDeleter);
  193836. p->rc = sqlite3_reset(p->pIdxDeleter);
  193837. }
  193838. }
  193839. /*
  193840. ** Release a reference to an Fts5Structure object returned by an earlier
  193841. ** call to fts5StructureRead() or fts5StructureDecode().
  193842. */
  193843. static void fts5StructureRelease(Fts5Structure *pStruct){
  193844. if( pStruct && 0>=(--pStruct->nRef) ){
  193845. int i;
  193846. assert( pStruct->nRef==0 );
  193847. for(i=0; i<pStruct->nLevel; i++){
  193848. sqlite3_free(pStruct->aLevel[i].aSeg);
  193849. }
  193850. sqlite3_free(pStruct);
  193851. }
  193852. }
  193853. static void fts5StructureRef(Fts5Structure *pStruct){
  193854. pStruct->nRef++;
  193855. }
  193856. /*
  193857. ** Deserialize and return the structure record currently stored in serialized
  193858. ** form within buffer pData/nData.
  193859. **
  193860. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  193861. ** are over-allocated by one slot. This allows the structure contents
  193862. ** to be more easily edited.
  193863. **
  193864. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  193865. ** returned. Otherwise, *ppOut is set to point to the new object and
  193866. ** SQLITE_OK returned.
  193867. */
  193868. static int fts5StructureDecode(
  193869. const u8 *pData, /* Buffer containing serialized structure */
  193870. int nData, /* Size of buffer pData in bytes */
  193871. int *piCookie, /* Configuration cookie value */
  193872. Fts5Structure **ppOut /* OUT: Deserialized object */
  193873. ){
  193874. int rc = SQLITE_OK;
  193875. int i = 0;
  193876. int iLvl;
  193877. int nLevel = 0;
  193878. int nSegment = 0;
  193879. int nByte; /* Bytes of space to allocate at pRet */
  193880. Fts5Structure *pRet = 0; /* Structure object to return */
  193881. /* Grab the cookie value */
  193882. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  193883. i = 4;
  193884. /* Read the total number of levels and segments from the start of the
  193885. ** structure record. */
  193886. i += fts5GetVarint32(&pData[i], nLevel);
  193887. i += fts5GetVarint32(&pData[i], nSegment);
  193888. nByte = (
  193889. sizeof(Fts5Structure) + /* Main structure */
  193890. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  193891. );
  193892. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  193893. if( pRet ){
  193894. pRet->nRef = 1;
  193895. pRet->nLevel = nLevel;
  193896. pRet->nSegment = nSegment;
  193897. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  193898. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  193899. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  193900. int nTotal = 0;
  193901. int iSeg;
  193902. if( i>=nData ){
  193903. rc = FTS5_CORRUPT;
  193904. }else{
  193905. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  193906. i += fts5GetVarint32(&pData[i], nTotal);
  193907. assert( nTotal>=pLvl->nMerge );
  193908. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  193909. nTotal * sizeof(Fts5StructureSegment)
  193910. );
  193911. }
  193912. if( rc==SQLITE_OK ){
  193913. pLvl->nSeg = nTotal;
  193914. for(iSeg=0; iSeg<nTotal; iSeg++){
  193915. if( i>=nData ){
  193916. rc = FTS5_CORRUPT;
  193917. break;
  193918. }
  193919. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
  193920. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
  193921. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
  193922. }
  193923. }
  193924. }
  193925. if( rc!=SQLITE_OK ){
  193926. fts5StructureRelease(pRet);
  193927. pRet = 0;
  193928. }
  193929. }
  193930. *ppOut = pRet;
  193931. return rc;
  193932. }
  193933. /*
  193934. **
  193935. */
  193936. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  193937. if( *pRc==SQLITE_OK ){
  193938. Fts5Structure *pStruct = *ppStruct;
  193939. int nLevel = pStruct->nLevel;
  193940. int nByte = (
  193941. sizeof(Fts5Structure) + /* Main structure */
  193942. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  193943. );
  193944. pStruct = sqlite3_realloc(pStruct, nByte);
  193945. if( pStruct ){
  193946. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  193947. pStruct->nLevel++;
  193948. *ppStruct = pStruct;
  193949. }else{
  193950. *pRc = SQLITE_NOMEM;
  193951. }
  193952. }
  193953. }
  193954. /*
  193955. ** Extend level iLvl so that there is room for at least nExtra more
  193956. ** segments.
  193957. */
  193958. static void fts5StructureExtendLevel(
  193959. int *pRc,
  193960. Fts5Structure *pStruct,
  193961. int iLvl,
  193962. int nExtra,
  193963. int bInsert
  193964. ){
  193965. if( *pRc==SQLITE_OK ){
  193966. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  193967. Fts5StructureSegment *aNew;
  193968. int nByte;
  193969. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  193970. aNew = sqlite3_realloc(pLvl->aSeg, nByte);
  193971. if( aNew ){
  193972. if( bInsert==0 ){
  193973. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  193974. }else{
  193975. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  193976. memmove(&aNew[nExtra], aNew, nMove);
  193977. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  193978. }
  193979. pLvl->aSeg = aNew;
  193980. }else{
  193981. *pRc = SQLITE_NOMEM;
  193982. }
  193983. }
  193984. }
  193985. static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
  193986. Fts5Structure *pRet = 0;
  193987. Fts5Config *pConfig = p->pConfig;
  193988. int iCookie; /* Configuration cookie */
  193989. Fts5Data *pData;
  193990. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  193991. if( p->rc==SQLITE_OK ){
  193992. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  193993. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  193994. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  193995. if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
  193996. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  193997. }
  193998. fts5DataRelease(pData);
  193999. if( p->rc!=SQLITE_OK ){
  194000. fts5StructureRelease(pRet);
  194001. pRet = 0;
  194002. }
  194003. }
  194004. return pRet;
  194005. }
  194006. static i64 fts5IndexDataVersion(Fts5Index *p){
  194007. i64 iVersion = 0;
  194008. if( p->rc==SQLITE_OK ){
  194009. if( p->pDataVersion==0 ){
  194010. p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
  194011. sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
  194012. );
  194013. if( p->rc ) return 0;
  194014. }
  194015. if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
  194016. iVersion = sqlite3_column_int64(p->pDataVersion, 0);
  194017. }
  194018. p->rc = sqlite3_reset(p->pDataVersion);
  194019. }
  194020. return iVersion;
  194021. }
  194022. /*
  194023. ** Read, deserialize and return the structure record.
  194024. **
  194025. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  194026. ** are over-allocated as described for function fts5StructureDecode()
  194027. ** above.
  194028. **
  194029. ** If an error occurs, NULL is returned and an error code left in the
  194030. ** Fts5Index handle. If an error has already occurred when this function
  194031. ** is called, it is a no-op.
  194032. */
  194033. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  194034. if( p->pStruct==0 ){
  194035. p->iStructVersion = fts5IndexDataVersion(p);
  194036. if( p->rc==SQLITE_OK ){
  194037. p->pStruct = fts5StructureReadUncached(p);
  194038. }
  194039. }
  194040. #if 0
  194041. else{
  194042. Fts5Structure *pTest = fts5StructureReadUncached(p);
  194043. if( pTest ){
  194044. int i, j;
  194045. assert_nc( p->pStruct->nSegment==pTest->nSegment );
  194046. assert_nc( p->pStruct->nLevel==pTest->nLevel );
  194047. for(i=0; i<pTest->nLevel; i++){
  194048. assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
  194049. assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
  194050. for(j=0; j<pTest->aLevel[i].nSeg; j++){
  194051. Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
  194052. Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
  194053. assert_nc( p1->iSegid==p2->iSegid );
  194054. assert_nc( p1->pgnoFirst==p2->pgnoFirst );
  194055. assert_nc( p1->pgnoLast==p2->pgnoLast );
  194056. }
  194057. }
  194058. fts5StructureRelease(pTest);
  194059. }
  194060. }
  194061. #endif
  194062. if( p->rc!=SQLITE_OK ) return 0;
  194063. assert( p->iStructVersion!=0 );
  194064. assert( p->pStruct!=0 );
  194065. fts5StructureRef(p->pStruct);
  194066. return p->pStruct;
  194067. }
  194068. static void fts5StructureInvalidate(Fts5Index *p){
  194069. if( p->pStruct ){
  194070. fts5StructureRelease(p->pStruct);
  194071. p->pStruct = 0;
  194072. }
  194073. }
  194074. /*
  194075. ** Return the total number of segments in index structure pStruct. This
  194076. ** function is only ever used as part of assert() conditions.
  194077. */
  194078. #ifdef SQLITE_DEBUG
  194079. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  194080. int nSegment = 0; /* Total number of segments */
  194081. if( pStruct ){
  194082. int iLvl; /* Used to iterate through levels */
  194083. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  194084. nSegment += pStruct->aLevel[iLvl].nSeg;
  194085. }
  194086. }
  194087. return nSegment;
  194088. }
  194089. #endif
  194090. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  194091. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  194092. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  194093. (pBuf)->n += nBlob; \
  194094. }
  194095. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  194096. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  194097. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  194098. }
  194099. /*
  194100. ** Serialize and store the "structure" record.
  194101. **
  194102. ** If an error occurs, leave an error code in the Fts5Index object. If an
  194103. ** error has already occurred, this function is a no-op.
  194104. */
  194105. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  194106. if( p->rc==SQLITE_OK ){
  194107. Fts5Buffer buf; /* Buffer to serialize record into */
  194108. int iLvl; /* Used to iterate through levels */
  194109. int iCookie; /* Cookie value to store */
  194110. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  194111. memset(&buf, 0, sizeof(Fts5Buffer));
  194112. /* Append the current configuration cookie */
  194113. iCookie = p->pConfig->iCookie;
  194114. if( iCookie<0 ) iCookie = 0;
  194115. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
  194116. sqlite3Fts5Put32(buf.p, iCookie);
  194117. buf.n = 4;
  194118. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  194119. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  194120. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  194121. }
  194122. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  194123. int iSeg; /* Used to iterate through segments */
  194124. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  194125. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  194126. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  194127. assert( pLvl->nMerge<=pLvl->nSeg );
  194128. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  194129. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  194130. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  194131. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  194132. }
  194133. }
  194134. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  194135. fts5BufferFree(&buf);
  194136. }
  194137. }
  194138. #if 0
  194139. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  194140. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  194141. int rc = SQLITE_OK;
  194142. Fts5Buffer buf;
  194143. memset(&buf, 0, sizeof(buf));
  194144. fts5DebugStructure(&rc, &buf, pStruct);
  194145. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  194146. fflush(stdout);
  194147. fts5BufferFree(&buf);
  194148. }
  194149. #else
  194150. # define fts5PrintStructure(x,y)
  194151. #endif
  194152. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  194153. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  194154. }
  194155. /*
  194156. ** Return a copy of index structure pStruct. Except, promote as many
  194157. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  194158. ** returned.
  194159. */
  194160. static void fts5StructurePromoteTo(
  194161. Fts5Index *p,
  194162. int iPromote,
  194163. int szPromote,
  194164. Fts5Structure *pStruct
  194165. ){
  194166. int il, is;
  194167. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  194168. if( pOut->nMerge==0 ){
  194169. for(il=iPromote+1; il<pStruct->nLevel; il++){
  194170. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  194171. if( pLvl->nMerge ) return;
  194172. for(is=pLvl->nSeg-1; is>=0; is--){
  194173. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  194174. if( sz>szPromote ) return;
  194175. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  194176. if( p->rc ) return;
  194177. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  194178. pOut->nSeg++;
  194179. pLvl->nSeg--;
  194180. }
  194181. }
  194182. }
  194183. }
  194184. /*
  194185. ** A new segment has just been written to level iLvl of index structure
  194186. ** pStruct. This function determines if any segments should be promoted
  194187. ** as a result. Segments are promoted in two scenarios:
  194188. **
  194189. ** a) If the segment just written is smaller than one or more segments
  194190. ** within the previous populated level, it is promoted to the previous
  194191. ** populated level.
  194192. **
  194193. ** b) If the segment just written is larger than the newest segment on
  194194. ** the next populated level, then that segment, and any other adjacent
  194195. ** segments that are also smaller than the one just written, are
  194196. ** promoted.
  194197. **
  194198. ** If one or more segments are promoted, the structure object is updated
  194199. ** to reflect this.
  194200. */
  194201. static void fts5StructurePromote(
  194202. Fts5Index *p, /* FTS5 backend object */
  194203. int iLvl, /* Index level just updated */
  194204. Fts5Structure *pStruct /* Index structure */
  194205. ){
  194206. if( p->rc==SQLITE_OK ){
  194207. int iTst;
  194208. int iPromote = -1;
  194209. int szPromote = 0; /* Promote anything this size or smaller */
  194210. Fts5StructureSegment *pSeg; /* Segment just written */
  194211. int szSeg; /* Size of segment just written */
  194212. int nSeg = pStruct->aLevel[iLvl].nSeg;
  194213. if( nSeg==0 ) return;
  194214. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  194215. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  194216. /* Check for condition (a) */
  194217. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  194218. if( iTst>=0 ){
  194219. int i;
  194220. int szMax = 0;
  194221. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  194222. assert( pTst->nMerge==0 );
  194223. for(i=0; i<pTst->nSeg; i++){
  194224. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  194225. if( sz>szMax ) szMax = sz;
  194226. }
  194227. if( szMax>=szSeg ){
  194228. /* Condition (a) is true. Promote the newest segment on level
  194229. ** iLvl to level iTst. */
  194230. iPromote = iTst;
  194231. szPromote = szMax;
  194232. }
  194233. }
  194234. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  194235. ** is a no-op if it is not. */
  194236. if( iPromote<0 ){
  194237. iPromote = iLvl;
  194238. szPromote = szSeg;
  194239. }
  194240. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  194241. }
  194242. }
  194243. /*
  194244. ** Advance the iterator passed as the only argument. If the end of the
  194245. ** doclist-index page is reached, return non-zero.
  194246. */
  194247. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  194248. Fts5Data *pData = pLvl->pData;
  194249. if( pLvl->iOff==0 ){
  194250. assert( pLvl->bEof==0 );
  194251. pLvl->iOff = 1;
  194252. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  194253. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  194254. pLvl->iFirstOff = pLvl->iOff;
  194255. }else{
  194256. int iOff;
  194257. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  194258. if( pData->p[iOff] ) break;
  194259. }
  194260. if( iOff<pData->nn ){
  194261. i64 iVal;
  194262. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  194263. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  194264. pLvl->iRowid += iVal;
  194265. pLvl->iOff = iOff;
  194266. }else{
  194267. pLvl->bEof = 1;
  194268. }
  194269. }
  194270. return pLvl->bEof;
  194271. }
  194272. /*
  194273. ** Advance the iterator passed as the only argument.
  194274. */
  194275. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  194276. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  194277. assert( iLvl<pIter->nLvl );
  194278. if( fts5DlidxLvlNext(pLvl) ){
  194279. if( (iLvl+1) < pIter->nLvl ){
  194280. fts5DlidxIterNextR(p, pIter, iLvl+1);
  194281. if( pLvl[1].bEof==0 ){
  194282. fts5DataRelease(pLvl->pData);
  194283. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  194284. pLvl->pData = fts5DataRead(p,
  194285. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  194286. );
  194287. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  194288. }
  194289. }
  194290. }
  194291. return pIter->aLvl[0].bEof;
  194292. }
  194293. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  194294. return fts5DlidxIterNextR(p, pIter, 0);
  194295. }
  194296. /*
  194297. ** The iterator passed as the first argument has the following fields set
  194298. ** as follows. This function sets up the rest of the iterator so that it
  194299. ** points to the first rowid in the doclist-index.
  194300. **
  194301. ** pData:
  194302. ** pointer to doclist-index record,
  194303. **
  194304. ** When this function is called pIter->iLeafPgno is the page number the
  194305. ** doclist is associated with (the one featuring the term).
  194306. */
  194307. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  194308. int i;
  194309. for(i=0; i<pIter->nLvl; i++){
  194310. fts5DlidxLvlNext(&pIter->aLvl[i]);
  194311. }
  194312. return pIter->aLvl[0].bEof;
  194313. }
  194314. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  194315. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  194316. }
  194317. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  194318. int i;
  194319. /* Advance each level to the last entry on the last page */
  194320. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  194321. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  194322. while( fts5DlidxLvlNext(pLvl)==0 );
  194323. pLvl->bEof = 0;
  194324. if( i>0 ){
  194325. Fts5DlidxLvl *pChild = &pLvl[-1];
  194326. fts5DataRelease(pChild->pData);
  194327. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  194328. pChild->pData = fts5DataRead(p,
  194329. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  194330. );
  194331. }
  194332. }
  194333. }
  194334. /*
  194335. ** Move the iterator passed as the only argument to the previous entry.
  194336. */
  194337. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  194338. int iOff = pLvl->iOff;
  194339. assert( pLvl->bEof==0 );
  194340. if( iOff<=pLvl->iFirstOff ){
  194341. pLvl->bEof = 1;
  194342. }else{
  194343. u8 *a = pLvl->pData->p;
  194344. i64 iVal;
  194345. int iLimit;
  194346. int ii;
  194347. int nZero = 0;
  194348. /* Currently iOff points to the first byte of a varint. This block
  194349. ** decrements iOff until it points to the first byte of the previous
  194350. ** varint. Taking care not to read any memory locations that occur
  194351. ** before the buffer in memory. */
  194352. iLimit = (iOff>9 ? iOff-9 : 0);
  194353. for(iOff--; iOff>iLimit; iOff--){
  194354. if( (a[iOff-1] & 0x80)==0 ) break;
  194355. }
  194356. fts5GetVarint(&a[iOff], (u64*)&iVal);
  194357. pLvl->iRowid -= iVal;
  194358. pLvl->iLeafPgno--;
  194359. /* Skip backwards past any 0x00 varints. */
  194360. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  194361. nZero++;
  194362. }
  194363. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  194364. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  194365. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  194366. ** bytes before a[ii]. */
  194367. int bZero = 0; /* True if last 0x00 counts */
  194368. if( (ii-8)>=pLvl->iFirstOff ){
  194369. int j;
  194370. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  194371. bZero = (j>8);
  194372. }
  194373. if( bZero==0 ) nZero--;
  194374. }
  194375. pLvl->iLeafPgno -= nZero;
  194376. pLvl->iOff = iOff - nZero;
  194377. }
  194378. return pLvl->bEof;
  194379. }
  194380. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  194381. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  194382. assert( iLvl<pIter->nLvl );
  194383. if( fts5DlidxLvlPrev(pLvl) ){
  194384. if( (iLvl+1) < pIter->nLvl ){
  194385. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  194386. if( pLvl[1].bEof==0 ){
  194387. fts5DataRelease(pLvl->pData);
  194388. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  194389. pLvl->pData = fts5DataRead(p,
  194390. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  194391. );
  194392. if( pLvl->pData ){
  194393. while( fts5DlidxLvlNext(pLvl)==0 );
  194394. pLvl->bEof = 0;
  194395. }
  194396. }
  194397. }
  194398. }
  194399. return pIter->aLvl[0].bEof;
  194400. }
  194401. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  194402. return fts5DlidxIterPrevR(p, pIter, 0);
  194403. }
  194404. /*
  194405. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  194406. */
  194407. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  194408. if( pIter ){
  194409. int i;
  194410. for(i=0; i<pIter->nLvl; i++){
  194411. fts5DataRelease(pIter->aLvl[i].pData);
  194412. }
  194413. sqlite3_free(pIter);
  194414. }
  194415. }
  194416. static Fts5DlidxIter *fts5DlidxIterInit(
  194417. Fts5Index *p, /* Fts5 Backend to iterate within */
  194418. int bRev, /* True for ORDER BY ASC */
  194419. int iSegid, /* Segment id */
  194420. int iLeafPg /* Leaf page number to load dlidx for */
  194421. ){
  194422. Fts5DlidxIter *pIter = 0;
  194423. int i;
  194424. int bDone = 0;
  194425. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  194426. int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  194427. Fts5DlidxIter *pNew;
  194428. pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
  194429. if( pNew==0 ){
  194430. p->rc = SQLITE_NOMEM;
  194431. }else{
  194432. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  194433. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  194434. pIter = pNew;
  194435. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  194436. pLvl->pData = fts5DataRead(p, iRowid);
  194437. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  194438. bDone = 1;
  194439. }
  194440. pIter->nLvl = i+1;
  194441. }
  194442. }
  194443. if( p->rc==SQLITE_OK ){
  194444. pIter->iSegid = iSegid;
  194445. if( bRev==0 ){
  194446. fts5DlidxIterFirst(pIter);
  194447. }else{
  194448. fts5DlidxIterLast(p, pIter);
  194449. }
  194450. }
  194451. if( p->rc!=SQLITE_OK ){
  194452. fts5DlidxIterFree(pIter);
  194453. pIter = 0;
  194454. }
  194455. return pIter;
  194456. }
  194457. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  194458. return pIter->aLvl[0].iRowid;
  194459. }
  194460. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  194461. return pIter->aLvl[0].iLeafPgno;
  194462. }
  194463. /*
  194464. ** Load the next leaf page into the segment iterator.
  194465. */
  194466. static void fts5SegIterNextPage(
  194467. Fts5Index *p, /* FTS5 backend object */
  194468. Fts5SegIter *pIter /* Iterator to advance to next page */
  194469. ){
  194470. Fts5Data *pLeaf;
  194471. Fts5StructureSegment *pSeg = pIter->pSeg;
  194472. fts5DataRelease(pIter->pLeaf);
  194473. pIter->iLeafPgno++;
  194474. if( pIter->pNextLeaf ){
  194475. pIter->pLeaf = pIter->pNextLeaf;
  194476. pIter->pNextLeaf = 0;
  194477. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  194478. pIter->pLeaf = fts5LeafRead(p,
  194479. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  194480. );
  194481. }else{
  194482. pIter->pLeaf = 0;
  194483. }
  194484. pLeaf = pIter->pLeaf;
  194485. if( pLeaf ){
  194486. pIter->iPgidxOff = pLeaf->szLeaf;
  194487. if( fts5LeafIsTermless(pLeaf) ){
  194488. pIter->iEndofDoclist = pLeaf->nn+1;
  194489. }else{
  194490. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  194491. pIter->iEndofDoclist
  194492. );
  194493. }
  194494. }
  194495. }
  194496. /*
  194497. ** Argument p points to a buffer containing a varint to be interpreted as a
  194498. ** position list size field. Read the varint and return the number of bytes
  194499. ** read. Before returning, set *pnSz to the number of bytes in the position
  194500. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  194501. */
  194502. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  194503. int nSz;
  194504. int n = 0;
  194505. fts5FastGetVarint32(p, n, nSz);
  194506. assert_nc( nSz>=0 );
  194507. *pnSz = nSz/2;
  194508. *pbDel = nSz & 0x0001;
  194509. return n;
  194510. }
  194511. /*
  194512. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  194513. ** position-list size field. Read the value of the field and store it
  194514. ** in the following variables:
  194515. **
  194516. ** Fts5SegIter.nPos
  194517. ** Fts5SegIter.bDel
  194518. **
  194519. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  194520. ** position list content (if any).
  194521. */
  194522. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  194523. if( p->rc==SQLITE_OK ){
  194524. int iOff = pIter->iLeafOffset; /* Offset to read at */
  194525. ASSERT_SZLEAF_OK(pIter->pLeaf);
  194526. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  194527. int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
  194528. pIter->bDel = 0;
  194529. pIter->nPos = 1;
  194530. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  194531. pIter->bDel = 1;
  194532. iOff++;
  194533. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  194534. pIter->nPos = 1;
  194535. iOff++;
  194536. }else{
  194537. pIter->nPos = 0;
  194538. }
  194539. }
  194540. }else{
  194541. int nSz;
  194542. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  194543. pIter->bDel = (nSz & 0x0001);
  194544. pIter->nPos = nSz>>1;
  194545. assert_nc( pIter->nPos>=0 );
  194546. }
  194547. pIter->iLeafOffset = iOff;
  194548. }
  194549. }
  194550. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  194551. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  194552. int iOff = pIter->iLeafOffset;
  194553. ASSERT_SZLEAF_OK(pIter->pLeaf);
  194554. if( iOff>=pIter->pLeaf->szLeaf ){
  194555. fts5SegIterNextPage(p, pIter);
  194556. if( pIter->pLeaf==0 ){
  194557. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  194558. return;
  194559. }
  194560. iOff = 4;
  194561. a = pIter->pLeaf->p;
  194562. }
  194563. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  194564. pIter->iLeafOffset = iOff;
  194565. }
  194566. /*
  194567. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  194568. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  194569. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  194570. ** the first term in the segment).
  194571. **
  194572. ** This function populates:
  194573. **
  194574. ** Fts5SegIter.term
  194575. ** Fts5SegIter.rowid
  194576. **
  194577. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  194578. ** the first position list. The position list belonging to document
  194579. ** (Fts5SegIter.iRowid).
  194580. */
  194581. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  194582. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  194583. int iOff = pIter->iLeafOffset; /* Offset to read at */
  194584. int nNew; /* Bytes of new data */
  194585. iOff += fts5GetVarint32(&a[iOff], nNew);
  194586. if( iOff+nNew>pIter->pLeaf->nn ){
  194587. p->rc = FTS5_CORRUPT;
  194588. return;
  194589. }
  194590. pIter->term.n = nKeep;
  194591. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  194592. iOff += nNew;
  194593. pIter->iTermLeafOffset = iOff;
  194594. pIter->iTermLeafPgno = pIter->iLeafPgno;
  194595. pIter->iLeafOffset = iOff;
  194596. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  194597. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  194598. }else{
  194599. int nExtra;
  194600. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  194601. pIter->iEndofDoclist += nExtra;
  194602. }
  194603. fts5SegIterLoadRowid(p, pIter);
  194604. }
  194605. static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
  194606. static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
  194607. static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
  194608. static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
  194609. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  194610. pIter->xNext = fts5SegIterNext_Reverse;
  194611. }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  194612. pIter->xNext = fts5SegIterNext_None;
  194613. }else{
  194614. pIter->xNext = fts5SegIterNext;
  194615. }
  194616. }
  194617. /*
  194618. ** Initialize the iterator object pIter to iterate through the entries in
  194619. ** segment pSeg. The iterator is left pointing to the first entry when
  194620. ** this function returns.
  194621. **
  194622. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  194623. ** an error has already occurred when this function is called, it is a no-op.
  194624. */
  194625. static void fts5SegIterInit(
  194626. Fts5Index *p, /* FTS index object */
  194627. Fts5StructureSegment *pSeg, /* Description of segment */
  194628. Fts5SegIter *pIter /* Object to populate */
  194629. ){
  194630. if( pSeg->pgnoFirst==0 ){
  194631. /* This happens if the segment is being used as an input to an incremental
  194632. ** merge and all data has already been "trimmed". See function
  194633. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  194634. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  194635. ** at EOF already. */
  194636. assert( pIter->pLeaf==0 );
  194637. return;
  194638. }
  194639. if( p->rc==SQLITE_OK ){
  194640. memset(pIter, 0, sizeof(*pIter));
  194641. fts5SegIterSetNext(p, pIter);
  194642. pIter->pSeg = pSeg;
  194643. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  194644. fts5SegIterNextPage(p, pIter);
  194645. }
  194646. if( p->rc==SQLITE_OK ){
  194647. pIter->iLeafOffset = 4;
  194648. assert_nc( pIter->pLeaf->nn>4 );
  194649. assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  194650. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  194651. fts5SegIterLoadTerm(p, pIter, 0);
  194652. fts5SegIterLoadNPos(p, pIter);
  194653. }
  194654. }
  194655. /*
  194656. ** This function is only ever called on iterators created by calls to
  194657. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  194658. **
  194659. ** The iterator is in an unusual state when this function is called: the
  194660. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  194661. ** the position-list size field for the first relevant rowid on the page.
  194662. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  194663. **
  194664. ** This function advances the iterator so that it points to the last
  194665. ** relevant rowid on the page and, if necessary, initializes the
  194666. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  194667. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  194668. ** byte of the position list content associated with said rowid.
  194669. */
  194670. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  194671. int eDetail = p->pConfig->eDetail;
  194672. int n = pIter->pLeaf->szLeaf;
  194673. int i = pIter->iLeafOffset;
  194674. u8 *a = pIter->pLeaf->p;
  194675. int iRowidOffset = 0;
  194676. if( n>pIter->iEndofDoclist ){
  194677. n = pIter->iEndofDoclist;
  194678. }
  194679. ASSERT_SZLEAF_OK(pIter->pLeaf);
  194680. while( 1 ){
  194681. i64 iDelta = 0;
  194682. if( eDetail==FTS5_DETAIL_NONE ){
  194683. /* todo */
  194684. if( i<n && a[i]==0 ){
  194685. i++;
  194686. if( i<n && a[i]==0 ) i++;
  194687. }
  194688. }else{
  194689. int nPos;
  194690. int bDummy;
  194691. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  194692. i += nPos;
  194693. }
  194694. if( i>=n ) break;
  194695. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  194696. pIter->iRowid += iDelta;
  194697. /* If necessary, grow the pIter->aRowidOffset[] array. */
  194698. if( iRowidOffset>=pIter->nRowidOffset ){
  194699. int nNew = pIter->nRowidOffset + 8;
  194700. int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
  194701. if( aNew==0 ){
  194702. p->rc = SQLITE_NOMEM;
  194703. break;
  194704. }
  194705. pIter->aRowidOffset = aNew;
  194706. pIter->nRowidOffset = nNew;
  194707. }
  194708. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  194709. pIter->iLeafOffset = i;
  194710. }
  194711. pIter->iRowidOffset = iRowidOffset;
  194712. fts5SegIterLoadNPos(p, pIter);
  194713. }
  194714. /*
  194715. **
  194716. */
  194717. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  194718. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  194719. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  194720. fts5DataRelease(pIter->pLeaf);
  194721. pIter->pLeaf = 0;
  194722. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  194723. Fts5Data *pNew;
  194724. pIter->iLeafPgno--;
  194725. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  194726. pIter->pSeg->iSegid, pIter->iLeafPgno
  194727. ));
  194728. if( pNew ){
  194729. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  194730. ** thing on the page - i.e. the first rowid is on the following page.
  194731. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  194732. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  194733. assert( pIter->pLeaf==0 );
  194734. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  194735. pIter->pLeaf = pNew;
  194736. pIter->iLeafOffset = pIter->iTermLeafOffset;
  194737. }
  194738. }else{
  194739. int iRowidOff;
  194740. iRowidOff = fts5LeafFirstRowidOff(pNew);
  194741. if( iRowidOff ){
  194742. pIter->pLeaf = pNew;
  194743. pIter->iLeafOffset = iRowidOff;
  194744. }
  194745. }
  194746. if( pIter->pLeaf ){
  194747. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  194748. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  194749. break;
  194750. }else{
  194751. fts5DataRelease(pNew);
  194752. }
  194753. }
  194754. }
  194755. if( pIter->pLeaf ){
  194756. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  194757. fts5SegIterReverseInitPage(p, pIter);
  194758. }
  194759. }
  194760. /*
  194761. ** Return true if the iterator passed as the second argument currently
  194762. ** points to a delete marker. A delete marker is an entry with a 0 byte
  194763. ** position-list.
  194764. */
  194765. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
  194766. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  194767. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  194768. }
  194769. /*
  194770. ** Advance iterator pIter to the next entry.
  194771. **
  194772. ** This version of fts5SegIterNext() is only used by reverse iterators.
  194773. */
  194774. static void fts5SegIterNext_Reverse(
  194775. Fts5Index *p, /* FTS5 backend object */
  194776. Fts5SegIter *pIter, /* Iterator to advance */
  194777. int *pbUnused /* Unused */
  194778. ){
  194779. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  194780. assert( pIter->pNextLeaf==0 );
  194781. UNUSED_PARAM(pbUnused);
  194782. if( pIter->iRowidOffset>0 ){
  194783. u8 *a = pIter->pLeaf->p;
  194784. int iOff;
  194785. i64 iDelta;
  194786. pIter->iRowidOffset--;
  194787. pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
  194788. fts5SegIterLoadNPos(p, pIter);
  194789. iOff = pIter->iLeafOffset;
  194790. if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
  194791. iOff += pIter->nPos;
  194792. }
  194793. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  194794. pIter->iRowid -= iDelta;
  194795. }else{
  194796. fts5SegIterReverseNewPage(p, pIter);
  194797. }
  194798. }
  194799. /*
  194800. ** Advance iterator pIter to the next entry.
  194801. **
  194802. ** This version of fts5SegIterNext() is only used if detail=none and the
  194803. ** iterator is not a reverse direction iterator.
  194804. */
  194805. static void fts5SegIterNext_None(
  194806. Fts5Index *p, /* FTS5 backend object */
  194807. Fts5SegIter *pIter, /* Iterator to advance */
  194808. int *pbNewTerm /* OUT: Set for new term */
  194809. ){
  194810. int iOff;
  194811. assert( p->rc==SQLITE_OK );
  194812. assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  194813. assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
  194814. ASSERT_SZLEAF_OK(pIter->pLeaf);
  194815. iOff = pIter->iLeafOffset;
  194816. /* Next entry is on the next page */
  194817. if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
  194818. fts5SegIterNextPage(p, pIter);
  194819. if( p->rc || pIter->pLeaf==0 ) return;
  194820. pIter->iRowid = 0;
  194821. iOff = 4;
  194822. }
  194823. if( iOff<pIter->iEndofDoclist ){
  194824. /* Next entry is on the current page */
  194825. i64 iDelta;
  194826. iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
  194827. pIter->iLeafOffset = iOff;
  194828. pIter->iRowid += iDelta;
  194829. }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
  194830. if( pIter->pSeg ){
  194831. int nKeep = 0;
  194832. if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
  194833. iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
  194834. }
  194835. pIter->iLeafOffset = iOff;
  194836. fts5SegIterLoadTerm(p, pIter, nKeep);
  194837. }else{
  194838. const u8 *pList = 0;
  194839. const char *zTerm = 0;
  194840. int nList;
  194841. sqlite3Fts5HashScanNext(p->pHash);
  194842. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  194843. if( pList==0 ) goto next_none_eof;
  194844. pIter->pLeaf->p = (u8*)pList;
  194845. pIter->pLeaf->nn = nList;
  194846. pIter->pLeaf->szLeaf = nList;
  194847. pIter->iEndofDoclist = nList;
  194848. sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
  194849. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  194850. }
  194851. if( pbNewTerm ) *pbNewTerm = 1;
  194852. }else{
  194853. goto next_none_eof;
  194854. }
  194855. fts5SegIterLoadNPos(p, pIter);
  194856. return;
  194857. next_none_eof:
  194858. fts5DataRelease(pIter->pLeaf);
  194859. pIter->pLeaf = 0;
  194860. }
  194861. /*
  194862. ** Advance iterator pIter to the next entry.
  194863. **
  194864. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  194865. ** is not considered an error if the iterator reaches EOF. If an error has
  194866. ** already occurred when this function is called, it is a no-op.
  194867. */
  194868. static void fts5SegIterNext(
  194869. Fts5Index *p, /* FTS5 backend object */
  194870. Fts5SegIter *pIter, /* Iterator to advance */
  194871. int *pbNewTerm /* OUT: Set for new term */
  194872. ){
  194873. Fts5Data *pLeaf = pIter->pLeaf;
  194874. int iOff;
  194875. int bNewTerm = 0;
  194876. int nKeep = 0;
  194877. u8 *a;
  194878. int n;
  194879. assert( pbNewTerm==0 || *pbNewTerm==0 );
  194880. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  194881. /* Search for the end of the position list within the current page. */
  194882. a = pLeaf->p;
  194883. n = pLeaf->szLeaf;
  194884. ASSERT_SZLEAF_OK(pLeaf);
  194885. iOff = pIter->iLeafOffset + pIter->nPos;
  194886. if( iOff<n ){
  194887. /* The next entry is on the current page. */
  194888. assert_nc( iOff<=pIter->iEndofDoclist );
  194889. if( iOff>=pIter->iEndofDoclist ){
  194890. bNewTerm = 1;
  194891. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  194892. iOff += fts5GetVarint32(&a[iOff], nKeep);
  194893. }
  194894. }else{
  194895. u64 iDelta;
  194896. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  194897. pIter->iRowid += iDelta;
  194898. assert_nc( iDelta>0 );
  194899. }
  194900. pIter->iLeafOffset = iOff;
  194901. }else if( pIter->pSeg==0 ){
  194902. const u8 *pList = 0;
  194903. const char *zTerm = 0;
  194904. int nList = 0;
  194905. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  194906. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  194907. sqlite3Fts5HashScanNext(p->pHash);
  194908. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  194909. }
  194910. if( pList==0 ){
  194911. fts5DataRelease(pIter->pLeaf);
  194912. pIter->pLeaf = 0;
  194913. }else{
  194914. pIter->pLeaf->p = (u8*)pList;
  194915. pIter->pLeaf->nn = nList;
  194916. pIter->pLeaf->szLeaf = nList;
  194917. pIter->iEndofDoclist = nList+1;
  194918. sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
  194919. (u8*)zTerm);
  194920. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  194921. *pbNewTerm = 1;
  194922. }
  194923. }else{
  194924. iOff = 0;
  194925. /* Next entry is not on the current page */
  194926. while( iOff==0 ){
  194927. fts5SegIterNextPage(p, pIter);
  194928. pLeaf = pIter->pLeaf;
  194929. if( pLeaf==0 ) break;
  194930. ASSERT_SZLEAF_OK(pLeaf);
  194931. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  194932. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  194933. pIter->iLeafOffset = iOff;
  194934. if( pLeaf->nn>pLeaf->szLeaf ){
  194935. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  194936. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  194937. );
  194938. }
  194939. }
  194940. else if( pLeaf->nn>pLeaf->szLeaf ){
  194941. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  194942. &pLeaf->p[pLeaf->szLeaf], iOff
  194943. );
  194944. pIter->iLeafOffset = iOff;
  194945. pIter->iEndofDoclist = iOff;
  194946. bNewTerm = 1;
  194947. }
  194948. assert_nc( iOff<pLeaf->szLeaf );
  194949. if( iOff>pLeaf->szLeaf ){
  194950. p->rc = FTS5_CORRUPT;
  194951. return;
  194952. }
  194953. }
  194954. }
  194955. /* Check if the iterator is now at EOF. If so, return early. */
  194956. if( pIter->pLeaf ){
  194957. if( bNewTerm ){
  194958. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  194959. fts5DataRelease(pIter->pLeaf);
  194960. pIter->pLeaf = 0;
  194961. }else{
  194962. fts5SegIterLoadTerm(p, pIter, nKeep);
  194963. fts5SegIterLoadNPos(p, pIter);
  194964. if( pbNewTerm ) *pbNewTerm = 1;
  194965. }
  194966. }else{
  194967. /* The following could be done by calling fts5SegIterLoadNPos(). But
  194968. ** this block is particularly performance critical, so equivalent
  194969. ** code is inlined.
  194970. **
  194971. ** Later: Switched back to fts5SegIterLoadNPos() because it supports
  194972. ** detail=none mode. Not ideal.
  194973. */
  194974. int nSz;
  194975. assert( p->rc==SQLITE_OK );
  194976. assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
  194977. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  194978. pIter->bDel = (nSz & 0x0001);
  194979. pIter->nPos = nSz>>1;
  194980. assert_nc( pIter->nPos>=0 );
  194981. }
  194982. }
  194983. }
  194984. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  194985. #define fts5IndexSkipVarint(a, iOff) { \
  194986. int iEnd = iOff+9; \
  194987. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  194988. }
  194989. /*
  194990. ** Iterator pIter currently points to the first rowid in a doclist. This
  194991. ** function sets the iterator up so that iterates in reverse order through
  194992. ** the doclist.
  194993. */
  194994. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  194995. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  194996. Fts5Data *pLast = 0;
  194997. int pgnoLast = 0;
  194998. if( pDlidx ){
  194999. int iSegid = pIter->pSeg->iSegid;
  195000. pgnoLast = fts5DlidxIterPgno(pDlidx);
  195001. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  195002. }else{
  195003. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  195004. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  195005. ** position-list content for the current rowid. Back it up so that it
  195006. ** points to the start of the position-list size field. */
  195007. int iPoslist;
  195008. if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
  195009. iPoslist = pIter->iTermLeafOffset;
  195010. }else{
  195011. iPoslist = 4;
  195012. }
  195013. fts5IndexSkipVarint(pLeaf->p, iPoslist);
  195014. pIter->iLeafOffset = iPoslist;
  195015. /* If this condition is true then the largest rowid for the current
  195016. ** term may not be stored on the current page. So search forward to
  195017. ** see where said rowid really is. */
  195018. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  195019. int pgno;
  195020. Fts5StructureSegment *pSeg = pIter->pSeg;
  195021. /* The last rowid in the doclist may not be on the current page. Search
  195022. ** forward to find the page containing the last rowid. */
  195023. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  195024. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  195025. Fts5Data *pNew = fts5DataRead(p, iAbs);
  195026. if( pNew ){
  195027. int iRowid, bTermless;
  195028. iRowid = fts5LeafFirstRowidOff(pNew);
  195029. bTermless = fts5LeafIsTermless(pNew);
  195030. if( iRowid ){
  195031. SWAPVAL(Fts5Data*, pNew, pLast);
  195032. pgnoLast = pgno;
  195033. }
  195034. fts5DataRelease(pNew);
  195035. if( bTermless==0 ) break;
  195036. }
  195037. }
  195038. }
  195039. }
  195040. /* If pLast is NULL at this point, then the last rowid for this doclist
  195041. ** lies on the page currently indicated by the iterator. In this case
  195042. ** pIter->iLeafOffset is already set to point to the position-list size
  195043. ** field associated with the first relevant rowid on the page.
  195044. **
  195045. ** Or, if pLast is non-NULL, then it is the page that contains the last
  195046. ** rowid. In this case configure the iterator so that it points to the
  195047. ** first rowid on this page.
  195048. */
  195049. if( pLast ){
  195050. int iOff;
  195051. fts5DataRelease(pIter->pLeaf);
  195052. pIter->pLeaf = pLast;
  195053. pIter->iLeafPgno = pgnoLast;
  195054. iOff = fts5LeafFirstRowidOff(pLast);
  195055. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  195056. pIter->iLeafOffset = iOff;
  195057. if( fts5LeafIsTermless(pLast) ){
  195058. pIter->iEndofDoclist = pLast->nn+1;
  195059. }else{
  195060. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  195061. }
  195062. }
  195063. fts5SegIterReverseInitPage(p, pIter);
  195064. }
  195065. /*
  195066. ** Iterator pIter currently points to the first rowid of a doclist.
  195067. ** There is a doclist-index associated with the final term on the current
  195068. ** page. If the current term is the last term on the page, load the
  195069. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  195070. */
  195071. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  195072. int iSeg = pIter->pSeg->iSegid;
  195073. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  195074. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  195075. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  195076. assert( pIter->pDlidx==0 );
  195077. /* Check if the current doclist ends on this page. If it does, return
  195078. ** early without loading the doclist-index (as it belongs to a different
  195079. ** term. */
  195080. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  195081. && pIter->iEndofDoclist<pLeaf->szLeaf
  195082. ){
  195083. return;
  195084. }
  195085. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  195086. }
  195087. /*
  195088. ** The iterator object passed as the second argument currently contains
  195089. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  195090. ** function searches the leaf page for a term matching (pTerm/nTerm).
  195091. **
  195092. ** If the specified term is found on the page, then the iterator is left
  195093. ** pointing to it. If argument bGe is zero and the term is not found,
  195094. ** the iterator is left pointing at EOF.
  195095. **
  195096. ** If bGe is non-zero and the specified term is not found, then the
  195097. ** iterator is left pointing to the smallest term in the segment that
  195098. ** is larger than the specified term, even if this term is not on the
  195099. ** current page.
  195100. */
  195101. static void fts5LeafSeek(
  195102. Fts5Index *p, /* Leave any error code here */
  195103. int bGe, /* True for a >= search */
  195104. Fts5SegIter *pIter, /* Iterator to seek */
  195105. const u8 *pTerm, int nTerm /* Term to search for */
  195106. ){
  195107. int iOff;
  195108. const u8 *a = pIter->pLeaf->p;
  195109. int szLeaf = pIter->pLeaf->szLeaf;
  195110. int n = pIter->pLeaf->nn;
  195111. int nMatch = 0;
  195112. int nKeep = 0;
  195113. int nNew = 0;
  195114. int iTermOff;
  195115. int iPgidx; /* Current offset in pgidx */
  195116. int bEndOfPage = 0;
  195117. assert( p->rc==SQLITE_OK );
  195118. iPgidx = szLeaf;
  195119. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  195120. iOff = iTermOff;
  195121. if( iOff>n ){
  195122. p->rc = FTS5_CORRUPT;
  195123. return;
  195124. }
  195125. while( 1 ){
  195126. /* Figure out how many new bytes are in this term */
  195127. fts5FastGetVarint32(a, iOff, nNew);
  195128. if( nKeep<nMatch ){
  195129. goto search_failed;
  195130. }
  195131. assert( nKeep>=nMatch );
  195132. if( nKeep==nMatch ){
  195133. int nCmp;
  195134. int i;
  195135. nCmp = MIN(nNew, nTerm-nMatch);
  195136. for(i=0; i<nCmp; i++){
  195137. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  195138. }
  195139. nMatch += i;
  195140. if( nTerm==nMatch ){
  195141. if( i==nNew ){
  195142. goto search_success;
  195143. }else{
  195144. goto search_failed;
  195145. }
  195146. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  195147. goto search_failed;
  195148. }
  195149. }
  195150. if( iPgidx>=n ){
  195151. bEndOfPage = 1;
  195152. break;
  195153. }
  195154. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  195155. iTermOff += nKeep;
  195156. iOff = iTermOff;
  195157. if( iOff>=n ){
  195158. p->rc = FTS5_CORRUPT;
  195159. return;
  195160. }
  195161. /* Read the nKeep field of the next term. */
  195162. fts5FastGetVarint32(a, iOff, nKeep);
  195163. }
  195164. search_failed:
  195165. if( bGe==0 ){
  195166. fts5DataRelease(pIter->pLeaf);
  195167. pIter->pLeaf = 0;
  195168. return;
  195169. }else if( bEndOfPage ){
  195170. do {
  195171. fts5SegIterNextPage(p, pIter);
  195172. if( pIter->pLeaf==0 ) return;
  195173. a = pIter->pLeaf->p;
  195174. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  195175. iPgidx = pIter->pLeaf->szLeaf;
  195176. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  195177. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  195178. p->rc = FTS5_CORRUPT;
  195179. }else{
  195180. nKeep = 0;
  195181. iTermOff = iOff;
  195182. n = pIter->pLeaf->nn;
  195183. iOff += fts5GetVarint32(&a[iOff], nNew);
  195184. break;
  195185. }
  195186. }
  195187. }while( 1 );
  195188. }
  195189. search_success:
  195190. pIter->iLeafOffset = iOff + nNew;
  195191. pIter->iTermLeafOffset = pIter->iLeafOffset;
  195192. pIter->iTermLeafPgno = pIter->iLeafPgno;
  195193. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  195194. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  195195. if( iPgidx>=n ){
  195196. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  195197. }else{
  195198. int nExtra;
  195199. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  195200. pIter->iEndofDoclist = iTermOff + nExtra;
  195201. }
  195202. pIter->iPgidxOff = iPgidx;
  195203. fts5SegIterLoadRowid(p, pIter);
  195204. fts5SegIterLoadNPos(p, pIter);
  195205. }
  195206. static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
  195207. if( p->pIdxSelect==0 ){
  195208. Fts5Config *pConfig = p->pConfig;
  195209. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  195210. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  195211. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  195212. pConfig->zDb, pConfig->zName
  195213. ));
  195214. }
  195215. return p->pIdxSelect;
  195216. }
  195217. /*
  195218. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  195219. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  195220. **
  195221. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  195222. ** an error has already occurred when this function is called, it is a no-op.
  195223. */
  195224. static void fts5SegIterSeekInit(
  195225. Fts5Index *p, /* FTS5 backend */
  195226. const u8 *pTerm, int nTerm, /* Term to seek to */
  195227. int flags, /* Mask of FTS5INDEX_XXX flags */
  195228. Fts5StructureSegment *pSeg, /* Description of segment */
  195229. Fts5SegIter *pIter /* Object to populate */
  195230. ){
  195231. int iPg = 1;
  195232. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  195233. int bDlidx = 0; /* True if there is a doclist-index */
  195234. sqlite3_stmt *pIdxSelect = 0;
  195235. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  195236. assert( pTerm && nTerm );
  195237. memset(pIter, 0, sizeof(*pIter));
  195238. pIter->pSeg = pSeg;
  195239. /* This block sets stack variable iPg to the leaf page number that may
  195240. ** contain term (pTerm/nTerm), if it is present in the segment. */
  195241. pIdxSelect = fts5IdxSelectStmt(p);
  195242. if( p->rc ) return;
  195243. sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
  195244. sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  195245. if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
  195246. i64 val = sqlite3_column_int(pIdxSelect, 0);
  195247. iPg = (int)(val>>1);
  195248. bDlidx = (val & 0x0001);
  195249. }
  195250. p->rc = sqlite3_reset(pIdxSelect);
  195251. sqlite3_bind_null(pIdxSelect, 2);
  195252. if( iPg<pSeg->pgnoFirst ){
  195253. iPg = pSeg->pgnoFirst;
  195254. bDlidx = 0;
  195255. }
  195256. pIter->iLeafPgno = iPg - 1;
  195257. fts5SegIterNextPage(p, pIter);
  195258. if( pIter->pLeaf ){
  195259. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  195260. }
  195261. if( p->rc==SQLITE_OK && bGe==0 ){
  195262. pIter->flags |= FTS5_SEGITER_ONETERM;
  195263. if( pIter->pLeaf ){
  195264. if( flags & FTS5INDEX_QUERY_DESC ){
  195265. pIter->flags |= FTS5_SEGITER_REVERSE;
  195266. }
  195267. if( bDlidx ){
  195268. fts5SegIterLoadDlidx(p, pIter);
  195269. }
  195270. if( flags & FTS5INDEX_QUERY_DESC ){
  195271. fts5SegIterReverse(p, pIter);
  195272. }
  195273. }
  195274. }
  195275. fts5SegIterSetNext(p, pIter);
  195276. /* Either:
  195277. **
  195278. ** 1) an error has occurred, or
  195279. ** 2) the iterator points to EOF, or
  195280. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  195281. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  195282. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  195283. */
  195284. assert( p->rc!=SQLITE_OK /* 1 */
  195285. || pIter->pLeaf==0 /* 2 */
  195286. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  195287. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  195288. );
  195289. }
  195290. /*
  195291. ** Initialize the object pIter to point to term pTerm/nTerm within the
  195292. ** in-memory hash table. If there is no such term in the hash-table, the
  195293. ** iterator is set to EOF.
  195294. **
  195295. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  195296. ** an error has already occurred when this function is called, it is a no-op.
  195297. */
  195298. static void fts5SegIterHashInit(
  195299. Fts5Index *p, /* FTS5 backend */
  195300. const u8 *pTerm, int nTerm, /* Term to seek to */
  195301. int flags, /* Mask of FTS5INDEX_XXX flags */
  195302. Fts5SegIter *pIter /* Object to populate */
  195303. ){
  195304. const u8 *pList = 0;
  195305. int nList = 0;
  195306. const u8 *z = 0;
  195307. int n = 0;
  195308. assert( p->pHash );
  195309. assert( p->rc==SQLITE_OK );
  195310. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  195311. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  195312. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  195313. n = (z ? (int)strlen((const char*)z) : 0);
  195314. }else{
  195315. pIter->flags |= FTS5_SEGITER_ONETERM;
  195316. sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
  195317. z = pTerm;
  195318. n = nTerm;
  195319. }
  195320. if( pList ){
  195321. Fts5Data *pLeaf;
  195322. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  195323. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  195324. if( pLeaf==0 ) return;
  195325. pLeaf->p = (u8*)pList;
  195326. pLeaf->nn = pLeaf->szLeaf = nList;
  195327. pIter->pLeaf = pLeaf;
  195328. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  195329. pIter->iEndofDoclist = pLeaf->nn;
  195330. if( flags & FTS5INDEX_QUERY_DESC ){
  195331. pIter->flags |= FTS5_SEGITER_REVERSE;
  195332. fts5SegIterReverseInitPage(p, pIter);
  195333. }else{
  195334. fts5SegIterLoadNPos(p, pIter);
  195335. }
  195336. }
  195337. fts5SegIterSetNext(p, pIter);
  195338. }
  195339. /*
  195340. ** Zero the iterator passed as the only argument.
  195341. */
  195342. static void fts5SegIterClear(Fts5SegIter *pIter){
  195343. fts5BufferFree(&pIter->term);
  195344. fts5DataRelease(pIter->pLeaf);
  195345. fts5DataRelease(pIter->pNextLeaf);
  195346. fts5DlidxIterFree(pIter->pDlidx);
  195347. sqlite3_free(pIter->aRowidOffset);
  195348. memset(pIter, 0, sizeof(Fts5SegIter));
  195349. }
  195350. #ifdef SQLITE_DEBUG
  195351. /*
  195352. ** This function is used as part of the big assert() procedure implemented by
  195353. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  195354. ** in *pRes is the correct result of comparing the current positions of the
  195355. ** two iterators.
  195356. */
  195357. static void fts5AssertComparisonResult(
  195358. Fts5Iter *pIter,
  195359. Fts5SegIter *p1,
  195360. Fts5SegIter *p2,
  195361. Fts5CResult *pRes
  195362. ){
  195363. int i1 = p1 - pIter->aSeg;
  195364. int i2 = p2 - pIter->aSeg;
  195365. if( p1->pLeaf || p2->pLeaf ){
  195366. if( p1->pLeaf==0 ){
  195367. assert( pRes->iFirst==i2 );
  195368. }else if( p2->pLeaf==0 ){
  195369. assert( pRes->iFirst==i1 );
  195370. }else{
  195371. int nMin = MIN(p1->term.n, p2->term.n);
  195372. int res = memcmp(p1->term.p, p2->term.p, nMin);
  195373. if( res==0 ) res = p1->term.n - p2->term.n;
  195374. if( res==0 ){
  195375. assert( pRes->bTermEq==1 );
  195376. assert( p1->iRowid!=p2->iRowid );
  195377. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  195378. }else{
  195379. assert( pRes->bTermEq==0 );
  195380. }
  195381. if( res<0 ){
  195382. assert( pRes->iFirst==i1 );
  195383. }else{
  195384. assert( pRes->iFirst==i2 );
  195385. }
  195386. }
  195387. }
  195388. }
  195389. /*
  195390. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  195391. ** is compiled. In that case, this function is essentially an assert()
  195392. ** statement used to verify that the contents of the pIter->aFirst[] array
  195393. ** are correct.
  195394. */
  195395. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
  195396. if( p->rc==SQLITE_OK ){
  195397. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  195398. int i;
  195399. assert( (pFirst->pLeaf==0)==pIter->base.bEof );
  195400. /* Check that pIter->iSwitchRowid is set correctly. */
  195401. for(i=0; i<pIter->nSeg; i++){
  195402. Fts5SegIter *p1 = &pIter->aSeg[i];
  195403. assert( p1==pFirst
  195404. || p1->pLeaf==0
  195405. || fts5BufferCompare(&pFirst->term, &p1->term)
  195406. || p1->iRowid==pIter->iSwitchRowid
  195407. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  195408. );
  195409. }
  195410. for(i=0; i<pIter->nSeg; i+=2){
  195411. Fts5SegIter *p1 = &pIter->aSeg[i];
  195412. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  195413. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  195414. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  195415. }
  195416. for(i=1; i<(pIter->nSeg / 2); i+=2){
  195417. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  195418. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  195419. Fts5CResult *pRes = &pIter->aFirst[i];
  195420. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  195421. }
  195422. }
  195423. }
  195424. #else
  195425. # define fts5AssertMultiIterSetup(x,y)
  195426. #endif
  195427. /*
  195428. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  195429. **
  195430. ** If the returned value is non-zero, then it is the index of an entry
  195431. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  195432. ** to a key that is a duplicate of another, higher priority,
  195433. ** segment-iterator in the pSeg->aSeg[] array.
  195434. */
  195435. static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
  195436. int i1; /* Index of left-hand Fts5SegIter */
  195437. int i2; /* Index of right-hand Fts5SegIter */
  195438. int iRes;
  195439. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  195440. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  195441. Fts5CResult *pRes = &pIter->aFirst[iOut];
  195442. assert( iOut<pIter->nSeg && iOut>0 );
  195443. assert( pIter->bRev==0 || pIter->bRev==1 );
  195444. if( iOut>=(pIter->nSeg/2) ){
  195445. i1 = (iOut - pIter->nSeg/2) * 2;
  195446. i2 = i1 + 1;
  195447. }else{
  195448. i1 = pIter->aFirst[iOut*2].iFirst;
  195449. i2 = pIter->aFirst[iOut*2+1].iFirst;
  195450. }
  195451. p1 = &pIter->aSeg[i1];
  195452. p2 = &pIter->aSeg[i2];
  195453. pRes->bTermEq = 0;
  195454. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  195455. iRes = i2;
  195456. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  195457. iRes = i1;
  195458. }else{
  195459. int res = fts5BufferCompare(&p1->term, &p2->term);
  195460. if( res==0 ){
  195461. assert( i2>i1 );
  195462. assert( i2!=0 );
  195463. pRes->bTermEq = 1;
  195464. if( p1->iRowid==p2->iRowid ){
  195465. p1->bDel = p2->bDel;
  195466. return i2;
  195467. }
  195468. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  195469. }
  195470. assert( res!=0 );
  195471. if( res<0 ){
  195472. iRes = i1;
  195473. }else{
  195474. iRes = i2;
  195475. }
  195476. }
  195477. pRes->iFirst = (u16)iRes;
  195478. return 0;
  195479. }
  195480. /*
  195481. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  195482. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  195483. */
  195484. static void fts5SegIterGotoPage(
  195485. Fts5Index *p, /* FTS5 backend object */
  195486. Fts5SegIter *pIter, /* Iterator to advance */
  195487. int iLeafPgno
  195488. ){
  195489. assert( iLeafPgno>pIter->iLeafPgno );
  195490. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  195491. p->rc = FTS5_CORRUPT;
  195492. }else{
  195493. fts5DataRelease(pIter->pNextLeaf);
  195494. pIter->pNextLeaf = 0;
  195495. pIter->iLeafPgno = iLeafPgno-1;
  195496. fts5SegIterNextPage(p, pIter);
  195497. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  195498. if( p->rc==SQLITE_OK ){
  195499. int iOff;
  195500. u8 *a = pIter->pLeaf->p;
  195501. int n = pIter->pLeaf->szLeaf;
  195502. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  195503. if( iOff<4 || iOff>=n ){
  195504. p->rc = FTS5_CORRUPT;
  195505. }else{
  195506. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  195507. pIter->iLeafOffset = iOff;
  195508. fts5SegIterLoadNPos(p, pIter);
  195509. }
  195510. }
  195511. }
  195512. }
  195513. /*
  195514. ** Advance the iterator passed as the second argument until it is at or
  195515. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  195516. ** always advanced at least once.
  195517. */
  195518. static void fts5SegIterNextFrom(
  195519. Fts5Index *p, /* FTS5 backend object */
  195520. Fts5SegIter *pIter, /* Iterator to advance */
  195521. i64 iMatch /* Advance iterator at least this far */
  195522. ){
  195523. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  195524. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  195525. int iLeafPgno = pIter->iLeafPgno;
  195526. int bMove = 1;
  195527. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  195528. assert( pIter->pDlidx );
  195529. assert( pIter->pLeaf );
  195530. if( bRev==0 ){
  195531. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  195532. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  195533. fts5DlidxIterNext(p, pDlidx);
  195534. }
  195535. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  195536. if( iLeafPgno>pIter->iLeafPgno ){
  195537. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  195538. bMove = 0;
  195539. }
  195540. }else{
  195541. assert( pIter->pNextLeaf==0 );
  195542. assert( iMatch<pIter->iRowid );
  195543. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  195544. fts5DlidxIterPrev(p, pDlidx);
  195545. }
  195546. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  195547. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  195548. if( iLeafPgno<pIter->iLeafPgno ){
  195549. pIter->iLeafPgno = iLeafPgno+1;
  195550. fts5SegIterReverseNewPage(p, pIter);
  195551. bMove = 0;
  195552. }
  195553. }
  195554. do{
  195555. if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
  195556. if( pIter->pLeaf==0 ) break;
  195557. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  195558. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  195559. bMove = 1;
  195560. }while( p->rc==SQLITE_OK );
  195561. }
  195562. /*
  195563. ** Free the iterator object passed as the second argument.
  195564. */
  195565. static void fts5MultiIterFree(Fts5Iter *pIter){
  195566. if( pIter ){
  195567. int i;
  195568. for(i=0; i<pIter->nSeg; i++){
  195569. fts5SegIterClear(&pIter->aSeg[i]);
  195570. }
  195571. fts5StructureRelease(pIter->pStruct);
  195572. fts5BufferFree(&pIter->poslist);
  195573. sqlite3_free(pIter);
  195574. }
  195575. }
  195576. static void fts5MultiIterAdvanced(
  195577. Fts5Index *p, /* FTS5 backend to iterate within */
  195578. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  195579. int iChanged, /* Index of sub-iterator just advanced */
  195580. int iMinset /* Minimum entry in aFirst[] to set */
  195581. ){
  195582. int i;
  195583. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  195584. int iEq;
  195585. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  195586. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  195587. assert( p->rc==SQLITE_OK );
  195588. pSeg->xNext(p, pSeg, 0);
  195589. i = pIter->nSeg + iEq;
  195590. }
  195591. }
  195592. }
  195593. /*
  195594. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  195595. ** points to the same term though - just a different rowid. This function
  195596. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  195597. ** If it does so successfully, 0 is returned. Otherwise 1.
  195598. **
  195599. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  195600. ** on the iterator instead. That function does the same as this one, except
  195601. ** that it deals with more complicated cases as well.
  195602. */
  195603. static int fts5MultiIterAdvanceRowid(
  195604. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  195605. int iChanged, /* Index of sub-iterator just advanced */
  195606. Fts5SegIter **ppFirst
  195607. ){
  195608. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  195609. if( pNew->iRowid==pIter->iSwitchRowid
  195610. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  195611. ){
  195612. int i;
  195613. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  195614. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  195615. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  195616. Fts5CResult *pRes = &pIter->aFirst[i];
  195617. assert( pNew->pLeaf );
  195618. assert( pRes->bTermEq==0 || pOther->pLeaf );
  195619. if( pRes->bTermEq ){
  195620. if( pNew->iRowid==pOther->iRowid ){
  195621. return 1;
  195622. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  195623. pIter->iSwitchRowid = pOther->iRowid;
  195624. pNew = pOther;
  195625. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  195626. pIter->iSwitchRowid = pOther->iRowid;
  195627. }
  195628. }
  195629. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  195630. if( i==1 ) break;
  195631. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  195632. }
  195633. }
  195634. *ppFirst = pNew;
  195635. return 0;
  195636. }
  195637. /*
  195638. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  195639. */
  195640. static void fts5MultiIterSetEof(Fts5Iter *pIter){
  195641. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  195642. pIter->base.bEof = pSeg->pLeaf==0;
  195643. pIter->iSwitchRowid = pSeg->iRowid;
  195644. }
  195645. /*
  195646. ** Move the iterator to the next entry.
  195647. **
  195648. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  195649. ** considered an error if the iterator reaches EOF, or if it is already at
  195650. ** EOF when this function is called.
  195651. */
  195652. static void fts5MultiIterNext(
  195653. Fts5Index *p,
  195654. Fts5Iter *pIter,
  195655. int bFrom, /* True if argument iFrom is valid */
  195656. i64 iFrom /* Advance at least as far as this */
  195657. ){
  195658. int bUseFrom = bFrom;
  195659. assert( pIter->base.bEof==0 );
  195660. while( p->rc==SQLITE_OK ){
  195661. int iFirst = pIter->aFirst[1].iFirst;
  195662. int bNewTerm = 0;
  195663. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  195664. assert( p->rc==SQLITE_OK );
  195665. if( bUseFrom && pSeg->pDlidx ){
  195666. fts5SegIterNextFrom(p, pSeg, iFrom);
  195667. }else{
  195668. pSeg->xNext(p, pSeg, &bNewTerm);
  195669. }
  195670. if( pSeg->pLeaf==0 || bNewTerm
  195671. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  195672. ){
  195673. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  195674. fts5MultiIterSetEof(pIter);
  195675. pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  195676. if( pSeg->pLeaf==0 ) return;
  195677. }
  195678. fts5AssertMultiIterSetup(p, pIter);
  195679. assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
  195680. if( pIter->bSkipEmpty==0 || pSeg->nPos ){
  195681. pIter->xSetOutputs(pIter, pSeg);
  195682. return;
  195683. }
  195684. bUseFrom = 0;
  195685. }
  195686. }
  195687. static void fts5MultiIterNext2(
  195688. Fts5Index *p,
  195689. Fts5Iter *pIter,
  195690. int *pbNewTerm /* OUT: True if *might* be new term */
  195691. ){
  195692. assert( pIter->bSkipEmpty );
  195693. if( p->rc==SQLITE_OK ){
  195694. *pbNewTerm = 0;
  195695. do{
  195696. int iFirst = pIter->aFirst[1].iFirst;
  195697. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  195698. int bNewTerm = 0;
  195699. assert( p->rc==SQLITE_OK );
  195700. pSeg->xNext(p, pSeg, &bNewTerm);
  195701. if( pSeg->pLeaf==0 || bNewTerm
  195702. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  195703. ){
  195704. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  195705. fts5MultiIterSetEof(pIter);
  195706. *pbNewTerm = 1;
  195707. }
  195708. fts5AssertMultiIterSetup(p, pIter);
  195709. }while( fts5MultiIterIsEmpty(p, pIter) );
  195710. }
  195711. }
  195712. static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
  195713. UNUSED_PARAM2(pUnused1, pUnused2);
  195714. }
  195715. static Fts5Iter *fts5MultiIterAlloc(
  195716. Fts5Index *p, /* FTS5 backend to iterate within */
  195717. int nSeg
  195718. ){
  195719. Fts5Iter *pNew;
  195720. int nSlot; /* Power of two >= nSeg */
  195721. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  195722. pNew = fts5IdxMalloc(p,
  195723. sizeof(Fts5Iter) + /* pNew */
  195724. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  195725. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  195726. );
  195727. if( pNew ){
  195728. pNew->nSeg = nSlot;
  195729. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  195730. pNew->pIndex = p;
  195731. pNew->xSetOutputs = fts5IterSetOutputs_Noop;
  195732. }
  195733. return pNew;
  195734. }
  195735. static void fts5PoslistCallback(
  195736. Fts5Index *pUnused,
  195737. void *pContext,
  195738. const u8 *pChunk, int nChunk
  195739. ){
  195740. UNUSED_PARAM(pUnused);
  195741. assert_nc( nChunk>=0 );
  195742. if( nChunk>0 ){
  195743. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  195744. }
  195745. }
  195746. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  195747. struct PoslistCallbackCtx {
  195748. Fts5Buffer *pBuf; /* Append to this buffer */
  195749. Fts5Colset *pColset; /* Restrict matches to this column */
  195750. int eState; /* See above */
  195751. };
  195752. typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
  195753. struct PoslistOffsetsCtx {
  195754. Fts5Buffer *pBuf; /* Append to this buffer */
  195755. Fts5Colset *pColset; /* Restrict matches to this column */
  195756. int iRead;
  195757. int iWrite;
  195758. };
  195759. /*
  195760. ** TODO: Make this more efficient!
  195761. */
  195762. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  195763. int i;
  195764. for(i=0; i<pColset->nCol; i++){
  195765. if( pColset->aiCol[i]==iCol ) return 1;
  195766. }
  195767. return 0;
  195768. }
  195769. static void fts5PoslistOffsetsCallback(
  195770. Fts5Index *pUnused,
  195771. void *pContext,
  195772. const u8 *pChunk, int nChunk
  195773. ){
  195774. PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
  195775. UNUSED_PARAM(pUnused);
  195776. assert_nc( nChunk>=0 );
  195777. if( nChunk>0 ){
  195778. int i = 0;
  195779. while( i<nChunk ){
  195780. int iVal;
  195781. i += fts5GetVarint32(&pChunk[i], iVal);
  195782. iVal += pCtx->iRead - 2;
  195783. pCtx->iRead = iVal;
  195784. if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
  195785. fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
  195786. pCtx->iWrite = iVal;
  195787. }
  195788. }
  195789. }
  195790. }
  195791. static void fts5PoslistFilterCallback(
  195792. Fts5Index *pUnused,
  195793. void *pContext,
  195794. const u8 *pChunk, int nChunk
  195795. ){
  195796. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  195797. UNUSED_PARAM(pUnused);
  195798. assert_nc( nChunk>=0 );
  195799. if( nChunk>0 ){
  195800. /* Search through to find the first varint with value 1. This is the
  195801. ** start of the next columns hits. */
  195802. int i = 0;
  195803. int iStart = 0;
  195804. if( pCtx->eState==2 ){
  195805. int iCol;
  195806. fts5FastGetVarint32(pChunk, i, iCol);
  195807. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  195808. pCtx->eState = 1;
  195809. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  195810. }else{
  195811. pCtx->eState = 0;
  195812. }
  195813. }
  195814. do {
  195815. while( i<nChunk && pChunk[i]!=0x01 ){
  195816. while( pChunk[i] & 0x80 ) i++;
  195817. i++;
  195818. }
  195819. if( pCtx->eState ){
  195820. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  195821. }
  195822. if( i<nChunk ){
  195823. int iCol;
  195824. iStart = i;
  195825. i++;
  195826. if( i>=nChunk ){
  195827. pCtx->eState = 2;
  195828. }else{
  195829. fts5FastGetVarint32(pChunk, i, iCol);
  195830. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  195831. if( pCtx->eState ){
  195832. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  195833. iStart = i;
  195834. }
  195835. }
  195836. }
  195837. }while( i<nChunk );
  195838. }
  195839. }
  195840. static void fts5ChunkIterate(
  195841. Fts5Index *p, /* Index object */
  195842. Fts5SegIter *pSeg, /* Poslist of this iterator */
  195843. void *pCtx, /* Context pointer for xChunk callback */
  195844. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  195845. ){
  195846. int nRem = pSeg->nPos; /* Number of bytes still to come */
  195847. Fts5Data *pData = 0;
  195848. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  195849. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  195850. int pgno = pSeg->iLeafPgno;
  195851. int pgnoSave = 0;
  195852. /* This function does notmwork with detail=none databases. */
  195853. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  195854. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  195855. pgnoSave = pgno+1;
  195856. }
  195857. while( 1 ){
  195858. xChunk(p, pCtx, pChunk, nChunk);
  195859. nRem -= nChunk;
  195860. fts5DataRelease(pData);
  195861. if( nRem<=0 ){
  195862. break;
  195863. }else{
  195864. pgno++;
  195865. pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  195866. if( pData==0 ) break;
  195867. pChunk = &pData->p[4];
  195868. nChunk = MIN(nRem, pData->szLeaf - 4);
  195869. if( pgno==pgnoSave ){
  195870. assert( pSeg->pNextLeaf==0 );
  195871. pSeg->pNextLeaf = pData;
  195872. pData = 0;
  195873. }
  195874. }
  195875. }
  195876. }
  195877. /*
  195878. ** Iterator pIter currently points to a valid entry (not EOF). This
  195879. ** function appends the position list data for the current entry to
  195880. ** buffer pBuf. It does not make a copy of the position-list size
  195881. ** field.
  195882. */
  195883. static void fts5SegiterPoslist(
  195884. Fts5Index *p,
  195885. Fts5SegIter *pSeg,
  195886. Fts5Colset *pColset,
  195887. Fts5Buffer *pBuf
  195888. ){
  195889. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
  195890. if( pColset==0 ){
  195891. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  195892. }else{
  195893. if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
  195894. PoslistCallbackCtx sCtx;
  195895. sCtx.pBuf = pBuf;
  195896. sCtx.pColset = pColset;
  195897. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  195898. assert( sCtx.eState==0 || sCtx.eState==1 );
  195899. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  195900. }else{
  195901. PoslistOffsetsCtx sCtx;
  195902. memset(&sCtx, 0, sizeof(sCtx));
  195903. sCtx.pBuf = pBuf;
  195904. sCtx.pColset = pColset;
  195905. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
  195906. }
  195907. }
  195908. }
  195909. }
  195910. /*
  195911. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  195912. ** the position list contains entries for column iCol, then (*pa) is set
  195913. ** to point to the sub-position-list for that column and the number of
  195914. ** bytes in it returned. Or, if the argument position list does not
  195915. ** contain any entries for column iCol, return 0.
  195916. */
  195917. static int fts5IndexExtractCol(
  195918. const u8 **pa, /* IN/OUT: Pointer to poslist */
  195919. int n, /* IN: Size of poslist in bytes */
  195920. int iCol /* Column to extract from poslist */
  195921. ){
  195922. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  195923. const u8 *p = *pa;
  195924. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  195925. while( iCol>iCurrent ){
  195926. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  195927. ** not part of a varint. Note that it is not possible for a negative
  195928. ** or extremely large varint to occur within an uncorrupted position
  195929. ** list. So the last byte of each varint may be assumed to have a clear
  195930. ** 0x80 bit. */
  195931. while( *p!=0x01 ){
  195932. while( *p++ & 0x80 );
  195933. if( p>=pEnd ) return 0;
  195934. }
  195935. *pa = p++;
  195936. iCurrent = *p++;
  195937. if( iCurrent & 0x80 ){
  195938. p--;
  195939. p += fts5GetVarint32(p, iCurrent);
  195940. }
  195941. }
  195942. if( iCol!=iCurrent ) return 0;
  195943. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  195944. ** not part of a varint */
  195945. while( p<pEnd && *p!=0x01 ){
  195946. while( *p++ & 0x80 );
  195947. }
  195948. return p - (*pa);
  195949. }
  195950. static void fts5IndexExtractColset(
  195951. int *pRc,
  195952. Fts5Colset *pColset, /* Colset to filter on */
  195953. const u8 *pPos, int nPos, /* Position list */
  195954. Fts5Buffer *pBuf /* Output buffer */
  195955. ){
  195956. if( *pRc==SQLITE_OK ){
  195957. int i;
  195958. fts5BufferZero(pBuf);
  195959. for(i=0; i<pColset->nCol; i++){
  195960. const u8 *pSub = pPos;
  195961. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  195962. if( nSub ){
  195963. fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
  195964. }
  195965. }
  195966. }
  195967. }
  195968. /*
  195969. ** xSetOutputs callback used by detail=none tables.
  195970. */
  195971. static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
  195972. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
  195973. pIter->base.iRowid = pSeg->iRowid;
  195974. pIter->base.nData = pSeg->nPos;
  195975. }
  195976. /*
  195977. ** xSetOutputs callback used by detail=full and detail=col tables when no
  195978. ** column filters are specified.
  195979. */
  195980. static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  195981. pIter->base.iRowid = pSeg->iRowid;
  195982. pIter->base.nData = pSeg->nPos;
  195983. assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
  195984. assert( pIter->pColset==0 );
  195985. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  195986. /* All data is stored on the current page. Populate the output
  195987. ** variables to point into the body of the page object. */
  195988. pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  195989. }else{
  195990. /* The data is distributed over two or more pages. Copy it into the
  195991. ** Fts5Iter.poslist buffer and then set the output pointer to point
  195992. ** to this buffer. */
  195993. fts5BufferZero(&pIter->poslist);
  195994. fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  195995. pIter->base.pData = pIter->poslist.p;
  195996. }
  195997. }
  195998. /*
  195999. ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
  196000. ** against no columns at all).
  196001. */
  196002. static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  196003. UNUSED_PARAM(pSeg);
  196004. pIter->base.nData = 0;
  196005. }
  196006. /*
  196007. ** xSetOutputs callback used by detail=col when there is a column filter
  196008. ** and there are 100 or more columns. Also called as a fallback from
  196009. ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  196010. */
  196011. static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
  196012. fts5BufferZero(&pIter->poslist);
  196013. fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
  196014. pIter->base.iRowid = pSeg->iRowid;
  196015. pIter->base.pData = pIter->poslist.p;
  196016. pIter->base.nData = pIter->poslist.n;
  196017. }
  196018. /*
  196019. ** xSetOutputs callback used when:
  196020. **
  196021. ** * detail=col,
  196022. ** * there is a column filter, and
  196023. ** * the table contains 100 or fewer columns.
  196024. **
  196025. ** The last point is to ensure all column numbers are stored as
  196026. ** single-byte varints.
  196027. */
  196028. static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
  196029. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  196030. assert( pIter->pColset );
  196031. if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
  196032. fts5IterSetOutputs_Col(pIter, pSeg);
  196033. }else{
  196034. u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
  196035. u8 *pEnd = (u8*)&a[pSeg->nPos];
  196036. int iPrev = 0;
  196037. int *aiCol = pIter->pColset->aiCol;
  196038. int *aiColEnd = &aiCol[pIter->pColset->nCol];
  196039. u8 *aOut = pIter->poslist.p;
  196040. int iPrevOut = 0;
  196041. pIter->base.iRowid = pSeg->iRowid;
  196042. while( a<pEnd ){
  196043. iPrev += (int)a++[0] - 2;
  196044. while( *aiCol<iPrev ){
  196045. aiCol++;
  196046. if( aiCol==aiColEnd ) goto setoutputs_col_out;
  196047. }
  196048. if( *aiCol==iPrev ){
  196049. *aOut++ = (u8)((iPrev - iPrevOut) + 2);
  196050. iPrevOut = iPrev;
  196051. }
  196052. }
  196053. setoutputs_col_out:
  196054. pIter->base.pData = pIter->poslist.p;
  196055. pIter->base.nData = aOut - pIter->poslist.p;
  196056. }
  196057. }
  196058. /*
  196059. ** xSetOutputs callback used by detail=full when there is a column filter.
  196060. */
  196061. static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
  196062. Fts5Colset *pColset = pIter->pColset;
  196063. pIter->base.iRowid = pSeg->iRowid;
  196064. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
  196065. assert( pColset );
  196066. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  196067. /* All data is stored on the current page. Populate the output
  196068. ** variables to point into the body of the page object. */
  196069. const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  196070. if( pColset->nCol==1 ){
  196071. pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
  196072. pIter->base.pData = a;
  196073. }else{
  196074. int *pRc = &pIter->pIndex->rc;
  196075. fts5BufferZero(&pIter->poslist);
  196076. fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
  196077. pIter->base.pData = pIter->poslist.p;
  196078. pIter->base.nData = pIter->poslist.n;
  196079. }
  196080. }else{
  196081. /* The data is distributed over two or more pages. Copy it into the
  196082. ** Fts5Iter.poslist buffer and then set the output pointer to point
  196083. ** to this buffer. */
  196084. fts5BufferZero(&pIter->poslist);
  196085. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  196086. pIter->base.pData = pIter->poslist.p;
  196087. pIter->base.nData = pIter->poslist.n;
  196088. }
  196089. }
  196090. static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
  196091. if( *pRc==SQLITE_OK ){
  196092. Fts5Config *pConfig = pIter->pIndex->pConfig;
  196093. if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  196094. pIter->xSetOutputs = fts5IterSetOutputs_None;
  196095. }
  196096. else if( pIter->pColset==0 ){
  196097. pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  196098. }
  196099. else if( pIter->pColset->nCol==0 ){
  196100. pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
  196101. }
  196102. else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  196103. pIter->xSetOutputs = fts5IterSetOutputs_Full;
  196104. }
  196105. else{
  196106. assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  196107. if( pConfig->nCol<=100 ){
  196108. pIter->xSetOutputs = fts5IterSetOutputs_Col100;
  196109. sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
  196110. }else{
  196111. pIter->xSetOutputs = fts5IterSetOutputs_Col;
  196112. }
  196113. }
  196114. }
  196115. }
  196116. /*
  196117. ** Allocate a new Fts5Iter object.
  196118. **
  196119. ** The new object will be used to iterate through data in structure pStruct.
  196120. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  196121. ** is zero or greater, data from the first nSegment segments on level iLevel
  196122. ** is merged.
  196123. **
  196124. ** The iterator initially points to the first term/rowid entry in the
  196125. ** iterated data.
  196126. */
  196127. static void fts5MultiIterNew(
  196128. Fts5Index *p, /* FTS5 backend to iterate within */
  196129. Fts5Structure *pStruct, /* Structure of specific index */
  196130. int flags, /* FTS5INDEX_QUERY_XXX flags */
  196131. Fts5Colset *pColset, /* Colset to filter on (or NULL) */
  196132. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  196133. int iLevel, /* Level to iterate (-1 for all) */
  196134. int nSegment, /* Number of segments to merge (iLevel>=0) */
  196135. Fts5Iter **ppOut /* New object */
  196136. ){
  196137. int nSeg = 0; /* Number of segment-iters in use */
  196138. int iIter = 0; /* */
  196139. int iSeg; /* Used to iterate through segments */
  196140. Fts5StructureLevel *pLvl;
  196141. Fts5Iter *pNew;
  196142. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  196143. /* Allocate space for the new multi-seg-iterator. */
  196144. if( p->rc==SQLITE_OK ){
  196145. if( iLevel<0 ){
  196146. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  196147. nSeg = pStruct->nSegment;
  196148. nSeg += (p->pHash ? 1 : 0);
  196149. }else{
  196150. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  196151. }
  196152. }
  196153. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  196154. if( pNew==0 ) return;
  196155. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  196156. pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  196157. pNew->pStruct = pStruct;
  196158. pNew->pColset = pColset;
  196159. fts5StructureRef(pStruct);
  196160. if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
  196161. fts5IterSetOutputCb(&p->rc, pNew);
  196162. }
  196163. /* Initialize each of the component segment iterators. */
  196164. if( p->rc==SQLITE_OK ){
  196165. if( iLevel<0 ){
  196166. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  196167. if( p->pHash ){
  196168. /* Add a segment iterator for the current contents of the hash table. */
  196169. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  196170. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  196171. }
  196172. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  196173. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  196174. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  196175. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  196176. if( pTerm==0 ){
  196177. fts5SegIterInit(p, pSeg, pIter);
  196178. }else{
  196179. fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
  196180. }
  196181. }
  196182. }
  196183. }else{
  196184. pLvl = &pStruct->aLevel[iLevel];
  196185. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  196186. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  196187. }
  196188. }
  196189. assert( iIter==nSeg );
  196190. }
  196191. /* If the above was successful, each component iterators now points
  196192. ** to the first entry in its segment. In this case initialize the
  196193. ** aFirst[] array. Or, if an error has occurred, free the iterator
  196194. ** object and set the output variable to NULL. */
  196195. if( p->rc==SQLITE_OK ){
  196196. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  196197. int iEq;
  196198. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  196199. Fts5SegIter *pSeg = &pNew->aSeg[iEq];
  196200. if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
  196201. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  196202. }
  196203. }
  196204. fts5MultiIterSetEof(pNew);
  196205. fts5AssertMultiIterSetup(p, pNew);
  196206. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  196207. fts5MultiIterNext(p, pNew, 0, 0);
  196208. }else if( pNew->base.bEof==0 ){
  196209. Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
  196210. pNew->xSetOutputs(pNew, pSeg);
  196211. }
  196212. }else{
  196213. fts5MultiIterFree(pNew);
  196214. *ppOut = 0;
  196215. }
  196216. }
  196217. /*
  196218. ** Create an Fts5Iter that iterates through the doclist provided
  196219. ** as the second argument.
  196220. */
  196221. static void fts5MultiIterNew2(
  196222. Fts5Index *p, /* FTS5 backend to iterate within */
  196223. Fts5Data *pData, /* Doclist to iterate through */
  196224. int bDesc, /* True for descending rowid order */
  196225. Fts5Iter **ppOut /* New object */
  196226. ){
  196227. Fts5Iter *pNew;
  196228. pNew = fts5MultiIterAlloc(p, 2);
  196229. if( pNew ){
  196230. Fts5SegIter *pIter = &pNew->aSeg[1];
  196231. pIter->flags = FTS5_SEGITER_ONETERM;
  196232. if( pData->szLeaf>0 ){
  196233. pIter->pLeaf = pData;
  196234. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  196235. pIter->iEndofDoclist = pData->nn;
  196236. pNew->aFirst[1].iFirst = 1;
  196237. if( bDesc ){
  196238. pNew->bRev = 1;
  196239. pIter->flags |= FTS5_SEGITER_REVERSE;
  196240. fts5SegIterReverseInitPage(p, pIter);
  196241. }else{
  196242. fts5SegIterLoadNPos(p, pIter);
  196243. }
  196244. pData = 0;
  196245. }else{
  196246. pNew->base.bEof = 1;
  196247. }
  196248. fts5SegIterSetNext(p, pIter);
  196249. *ppOut = pNew;
  196250. }
  196251. fts5DataRelease(pData);
  196252. }
  196253. /*
  196254. ** Return true if the iterator is at EOF or if an error has occurred.
  196255. ** False otherwise.
  196256. */
  196257. static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
  196258. assert( p->rc
  196259. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
  196260. );
  196261. return (p->rc || pIter->base.bEof);
  196262. }
  196263. /*
  196264. ** Return the rowid of the entry that the iterator currently points
  196265. ** to. If the iterator points to EOF when this function is called the
  196266. ** results are undefined.
  196267. */
  196268. static i64 fts5MultiIterRowid(Fts5Iter *pIter){
  196269. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  196270. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  196271. }
  196272. /*
  196273. ** Move the iterator to the next entry at or following iMatch.
  196274. */
  196275. static void fts5MultiIterNextFrom(
  196276. Fts5Index *p,
  196277. Fts5Iter *pIter,
  196278. i64 iMatch
  196279. ){
  196280. while( 1 ){
  196281. i64 iRowid;
  196282. fts5MultiIterNext(p, pIter, 1, iMatch);
  196283. if( fts5MultiIterEof(p, pIter) ) break;
  196284. iRowid = fts5MultiIterRowid(pIter);
  196285. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  196286. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  196287. }
  196288. }
  196289. /*
  196290. ** Return a pointer to a buffer containing the term associated with the
  196291. ** entry that the iterator currently points to.
  196292. */
  196293. static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
  196294. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  196295. *pn = p->term.n;
  196296. return p->term.p;
  196297. }
  196298. /*
  196299. ** Allocate a new segment-id for the structure pStruct. The new segment
  196300. ** id must be between 1 and 65335 inclusive, and must not be used by
  196301. ** any currently existing segment. If a free segment id cannot be found,
  196302. ** SQLITE_FULL is returned.
  196303. **
  196304. ** If an error has already occurred, this function is a no-op. 0 is
  196305. ** returned in this case.
  196306. */
  196307. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  196308. int iSegid = 0;
  196309. if( p->rc==SQLITE_OK ){
  196310. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  196311. p->rc = SQLITE_FULL;
  196312. }else{
  196313. /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
  196314. ** array is 63 elements, or 252 bytes, in size. */
  196315. u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
  196316. int iLvl, iSeg;
  196317. int i;
  196318. u32 mask;
  196319. memset(aUsed, 0, sizeof(aUsed));
  196320. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  196321. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  196322. int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
  196323. if( iId<=FTS5_MAX_SEGMENT ){
  196324. aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
  196325. }
  196326. }
  196327. }
  196328. for(i=0; aUsed[i]==0xFFFFFFFF; i++);
  196329. mask = aUsed[i];
  196330. for(iSegid=0; mask & (1 << iSegid); iSegid++);
  196331. iSegid += 1 + i*32;
  196332. #ifdef SQLITE_DEBUG
  196333. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  196334. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  196335. assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
  196336. }
  196337. }
  196338. assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
  196339. {
  196340. sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
  196341. if( p->rc==SQLITE_OK ){
  196342. u8 aBlob[2] = {0xff, 0xff};
  196343. sqlite3_bind_int(pIdxSelect, 1, iSegid);
  196344. sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
  196345. assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
  196346. p->rc = sqlite3_reset(pIdxSelect);
  196347. sqlite3_bind_null(pIdxSelect, 2);
  196348. }
  196349. }
  196350. #endif
  196351. }
  196352. }
  196353. return iSegid;
  196354. }
  196355. /*
  196356. ** Discard all data currently cached in the hash-tables.
  196357. */
  196358. static void fts5IndexDiscardData(Fts5Index *p){
  196359. assert( p->pHash || p->nPendingData==0 );
  196360. if( p->pHash ){
  196361. sqlite3Fts5HashClear(p->pHash);
  196362. p->nPendingData = 0;
  196363. }
  196364. }
  196365. /*
  196366. ** Return the size of the prefix, in bytes, that buffer
  196367. ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
  196368. **
  196369. ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
  196370. ** than buffer (pOld/nOld).
  196371. */
  196372. static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
  196373. int i;
  196374. for(i=0; i<nOld; i++){
  196375. if( pOld[i]!=pNew[i] ) break;
  196376. }
  196377. return i;
  196378. }
  196379. static void fts5WriteDlidxClear(
  196380. Fts5Index *p,
  196381. Fts5SegWriter *pWriter,
  196382. int bFlush /* If true, write dlidx to disk */
  196383. ){
  196384. int i;
  196385. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  196386. for(i=0; i<pWriter->nDlidx; i++){
  196387. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  196388. if( pDlidx->buf.n==0 ) break;
  196389. if( bFlush ){
  196390. assert( pDlidx->pgno!=0 );
  196391. fts5DataWrite(p,
  196392. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  196393. pDlidx->buf.p, pDlidx->buf.n
  196394. );
  196395. }
  196396. sqlite3Fts5BufferZero(&pDlidx->buf);
  196397. pDlidx->bPrevValid = 0;
  196398. }
  196399. }
  196400. /*
  196401. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  196402. ** Any new array elements are zeroed before returning.
  196403. */
  196404. static int fts5WriteDlidxGrow(
  196405. Fts5Index *p,
  196406. Fts5SegWriter *pWriter,
  196407. int nLvl
  196408. ){
  196409. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  196410. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
  196411. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  196412. );
  196413. if( aDlidx==0 ){
  196414. p->rc = SQLITE_NOMEM;
  196415. }else{
  196416. int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  196417. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  196418. pWriter->aDlidx = aDlidx;
  196419. pWriter->nDlidx = nLvl;
  196420. }
  196421. }
  196422. return p->rc;
  196423. }
  196424. /*
  196425. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  196426. ** enough, flush it to disk and return 1. Otherwise discard it and return
  196427. ** zero.
  196428. */
  196429. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  196430. int bFlag = 0;
  196431. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  196432. ** to the database, also write the doclist-index to disk. */
  196433. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  196434. bFlag = 1;
  196435. }
  196436. fts5WriteDlidxClear(p, pWriter, bFlag);
  196437. pWriter->nEmpty = 0;
  196438. return bFlag;
  196439. }
  196440. /*
  196441. ** This function is called whenever processing of the doclist for the
  196442. ** last term on leaf page (pWriter->iBtPage) is completed.
  196443. **
  196444. ** The doclist-index for that term is currently stored in-memory within the
  196445. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  196446. ** writes it out to disk. Or, if it is too small to bother with, discards
  196447. ** it.
  196448. **
  196449. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  196450. */
  196451. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  196452. int bFlag;
  196453. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  196454. if( pWriter->iBtPage==0 ) return;
  196455. bFlag = fts5WriteFlushDlidx(p, pWriter);
  196456. if( p->rc==SQLITE_OK ){
  196457. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  196458. /* The following was already done in fts5WriteInit(): */
  196459. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  196460. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  196461. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  196462. sqlite3_step(p->pIdxWriter);
  196463. p->rc = sqlite3_reset(p->pIdxWriter);
  196464. sqlite3_bind_null(p->pIdxWriter, 2);
  196465. }
  196466. pWriter->iBtPage = 0;
  196467. }
  196468. /*
  196469. ** This is called once for each leaf page except the first that contains
  196470. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  196471. ** is larger than all terms written to earlier leaves, and equal to or
  196472. ** smaller than the first term on the new leaf.
  196473. **
  196474. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  196475. ** has already occurred when this function is called, it is a no-op.
  196476. */
  196477. static void fts5WriteBtreeTerm(
  196478. Fts5Index *p, /* FTS5 backend object */
  196479. Fts5SegWriter *pWriter, /* Writer object */
  196480. int nTerm, const u8 *pTerm /* First term on new page */
  196481. ){
  196482. fts5WriteFlushBtree(p, pWriter);
  196483. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  196484. pWriter->iBtPage = pWriter->writer.pgno;
  196485. }
  196486. /*
  196487. ** This function is called when flushing a leaf page that contains no
  196488. ** terms at all to disk.
  196489. */
  196490. static void fts5WriteBtreeNoTerm(
  196491. Fts5Index *p, /* FTS5 backend object */
  196492. Fts5SegWriter *pWriter /* Writer object */
  196493. ){
  196494. /* If there were no rowids on the leaf page either and the doclist-index
  196495. ** has already been started, append an 0x00 byte to it. */
  196496. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  196497. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  196498. assert( pDlidx->bPrevValid );
  196499. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  196500. }
  196501. /* Increment the "number of sequential leaves without a term" counter. */
  196502. pWriter->nEmpty++;
  196503. }
  196504. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  196505. i64 iRowid;
  196506. int iOff;
  196507. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  196508. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  196509. return iRowid;
  196510. }
  196511. /*
  196512. ** Rowid iRowid has just been appended to the current leaf page. It is the
  196513. ** first on the page. This function appends an appropriate entry to the current
  196514. ** doclist-index.
  196515. */
  196516. static void fts5WriteDlidxAppend(
  196517. Fts5Index *p,
  196518. Fts5SegWriter *pWriter,
  196519. i64 iRowid
  196520. ){
  196521. int i;
  196522. int bDone = 0;
  196523. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  196524. i64 iVal;
  196525. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  196526. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  196527. /* The current doclist-index page is full. Write it to disk and push
  196528. ** a copy of iRowid (which will become the first rowid on the next
  196529. ** doclist-index leaf page) up into the next level of the b-tree
  196530. ** hierarchy. If the node being flushed is currently the root node,
  196531. ** also push its first rowid upwards. */
  196532. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  196533. fts5DataWrite(p,
  196534. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  196535. pDlidx->buf.p, pDlidx->buf.n
  196536. );
  196537. fts5WriteDlidxGrow(p, pWriter, i+2);
  196538. pDlidx = &pWriter->aDlidx[i];
  196539. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  196540. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  196541. /* This was the root node. Push its first rowid up to the new root. */
  196542. pDlidx[1].pgno = pDlidx->pgno;
  196543. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  196544. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  196545. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  196546. pDlidx[1].bPrevValid = 1;
  196547. pDlidx[1].iPrev = iFirst;
  196548. }
  196549. sqlite3Fts5BufferZero(&pDlidx->buf);
  196550. pDlidx->bPrevValid = 0;
  196551. pDlidx->pgno++;
  196552. }else{
  196553. bDone = 1;
  196554. }
  196555. if( pDlidx->bPrevValid ){
  196556. iVal = iRowid - pDlidx->iPrev;
  196557. }else{
  196558. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  196559. assert( pDlidx->buf.n==0 );
  196560. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  196561. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  196562. iVal = iRowid;
  196563. }
  196564. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  196565. pDlidx->bPrevValid = 1;
  196566. pDlidx->iPrev = iRowid;
  196567. }
  196568. }
  196569. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  196570. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  196571. Fts5PageWriter *pPage = &pWriter->writer;
  196572. i64 iRowid;
  196573. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  196574. /* Set the szLeaf header field. */
  196575. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  196576. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  196577. if( pWriter->bFirstTermInPage ){
  196578. /* No term was written to this page. */
  196579. assert( pPage->pgidx.n==0 );
  196580. fts5WriteBtreeNoTerm(p, pWriter);
  196581. }else{
  196582. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  196583. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  196584. }
  196585. /* Write the page out to disk */
  196586. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  196587. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  196588. /* Initialize the next page. */
  196589. fts5BufferZero(&pPage->buf);
  196590. fts5BufferZero(&pPage->pgidx);
  196591. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  196592. pPage->iPrevPgidx = 0;
  196593. pPage->pgno++;
  196594. /* Increase the leaves written counter */
  196595. pWriter->nLeafWritten++;
  196596. /* The new leaf holds no terms or rowids */
  196597. pWriter->bFirstTermInPage = 1;
  196598. pWriter->bFirstRowidInPage = 1;
  196599. }
  196600. /*
  196601. ** Append term pTerm/nTerm to the segment being written by the writer passed
  196602. ** as the second argument.
  196603. **
  196604. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  196605. ** already occurred, this function is a no-op.
  196606. */
  196607. static void fts5WriteAppendTerm(
  196608. Fts5Index *p,
  196609. Fts5SegWriter *pWriter,
  196610. int nTerm, const u8 *pTerm
  196611. ){
  196612. int nPrefix; /* Bytes of prefix compression for term */
  196613. Fts5PageWriter *pPage = &pWriter->writer;
  196614. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  196615. assert( p->rc==SQLITE_OK );
  196616. assert( pPage->buf.n>=4 );
  196617. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  196618. /* If the current leaf page is full, flush it to disk. */
  196619. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  196620. if( pPage->buf.n>4 ){
  196621. fts5WriteFlushLeaf(p, pWriter);
  196622. }
  196623. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  196624. }
  196625. /* TODO1: Updating pgidx here. */
  196626. pPgidx->n += sqlite3Fts5PutVarint(
  196627. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  196628. );
  196629. pPage->iPrevPgidx = pPage->buf.n;
  196630. #if 0
  196631. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  196632. pPgidx->n += 2;
  196633. #endif
  196634. if( pWriter->bFirstTermInPage ){
  196635. nPrefix = 0;
  196636. if( pPage->pgno!=1 ){
  196637. /* This is the first term on a leaf that is not the leftmost leaf in
  196638. ** the segment b-tree. In this case it is necessary to add a term to
  196639. ** the b-tree hierarchy that is (a) larger than the largest term
  196640. ** already written to the segment and (b) smaller than or equal to
  196641. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  196642. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  196643. ** previous term.
  196644. **
  196645. ** Usually, the previous term is available in pPage->term. The exception
  196646. ** is if this is the first term written in an incremental-merge step.
  196647. ** In this case the previous term is not available, so just write a
  196648. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  196649. ** inefficient, but still correct. */
  196650. int n = nTerm;
  196651. if( pPage->term.n ){
  196652. n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  196653. }
  196654. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  196655. pPage = &pWriter->writer;
  196656. }
  196657. }else{
  196658. nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  196659. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  196660. }
  196661. /* Append the number of bytes of new data, then the term data itself
  196662. ** to the page. */
  196663. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  196664. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  196665. /* Update the Fts5PageWriter.term field. */
  196666. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  196667. pWriter->bFirstTermInPage = 0;
  196668. pWriter->bFirstRowidInPage = 0;
  196669. pWriter->bFirstRowidInDoclist = 1;
  196670. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  196671. pWriter->aDlidx[0].pgno = pPage->pgno;
  196672. }
  196673. /*
  196674. ** Append a rowid and position-list size field to the writers output.
  196675. */
  196676. static void fts5WriteAppendRowid(
  196677. Fts5Index *p,
  196678. Fts5SegWriter *pWriter,
  196679. i64 iRowid
  196680. ){
  196681. if( p->rc==SQLITE_OK ){
  196682. Fts5PageWriter *pPage = &pWriter->writer;
  196683. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  196684. fts5WriteFlushLeaf(p, pWriter);
  196685. }
  196686. /* If this is to be the first rowid written to the page, set the
  196687. ** rowid-pointer in the page-header. Also append a value to the dlidx
  196688. ** buffer, in case a doclist-index is required. */
  196689. if( pWriter->bFirstRowidInPage ){
  196690. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  196691. fts5WriteDlidxAppend(p, pWriter, iRowid);
  196692. }
  196693. /* Write the rowid. */
  196694. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  196695. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  196696. }else{
  196697. assert( p->rc || iRowid>pWriter->iPrevRowid );
  196698. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  196699. }
  196700. pWriter->iPrevRowid = iRowid;
  196701. pWriter->bFirstRowidInDoclist = 0;
  196702. pWriter->bFirstRowidInPage = 0;
  196703. }
  196704. }
  196705. static void fts5WriteAppendPoslistData(
  196706. Fts5Index *p,
  196707. Fts5SegWriter *pWriter,
  196708. const u8 *aData,
  196709. int nData
  196710. ){
  196711. Fts5PageWriter *pPage = &pWriter->writer;
  196712. const u8 *a = aData;
  196713. int n = nData;
  196714. assert( p->pConfig->pgsz>0 );
  196715. while( p->rc==SQLITE_OK
  196716. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  196717. ){
  196718. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  196719. int nCopy = 0;
  196720. while( nCopy<nReq ){
  196721. i64 dummy;
  196722. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  196723. }
  196724. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  196725. a += nCopy;
  196726. n -= nCopy;
  196727. fts5WriteFlushLeaf(p, pWriter);
  196728. }
  196729. if( n>0 ){
  196730. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  196731. }
  196732. }
  196733. /*
  196734. ** Flush any data cached by the writer object to the database. Free any
  196735. ** allocations associated with the writer.
  196736. */
  196737. static void fts5WriteFinish(
  196738. Fts5Index *p,
  196739. Fts5SegWriter *pWriter, /* Writer object */
  196740. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  196741. ){
  196742. int i;
  196743. Fts5PageWriter *pLeaf = &pWriter->writer;
  196744. if( p->rc==SQLITE_OK ){
  196745. assert( pLeaf->pgno>=1 );
  196746. if( pLeaf->buf.n>4 ){
  196747. fts5WriteFlushLeaf(p, pWriter);
  196748. }
  196749. *pnLeaf = pLeaf->pgno-1;
  196750. if( pLeaf->pgno>1 ){
  196751. fts5WriteFlushBtree(p, pWriter);
  196752. }
  196753. }
  196754. fts5BufferFree(&pLeaf->term);
  196755. fts5BufferFree(&pLeaf->buf);
  196756. fts5BufferFree(&pLeaf->pgidx);
  196757. fts5BufferFree(&pWriter->btterm);
  196758. for(i=0; i<pWriter->nDlidx; i++){
  196759. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  196760. }
  196761. sqlite3_free(pWriter->aDlidx);
  196762. }
  196763. static void fts5WriteInit(
  196764. Fts5Index *p,
  196765. Fts5SegWriter *pWriter,
  196766. int iSegid
  196767. ){
  196768. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  196769. memset(pWriter, 0, sizeof(Fts5SegWriter));
  196770. pWriter->iSegid = iSegid;
  196771. fts5WriteDlidxGrow(p, pWriter, 1);
  196772. pWriter->writer.pgno = 1;
  196773. pWriter->bFirstTermInPage = 1;
  196774. pWriter->iBtPage = 1;
  196775. assert( pWriter->writer.buf.n==0 );
  196776. assert( pWriter->writer.pgidx.n==0 );
  196777. /* Grow the two buffers to pgsz + padding bytes in size. */
  196778. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  196779. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  196780. if( p->pIdxWriter==0 ){
  196781. Fts5Config *pConfig = p->pConfig;
  196782. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  196783. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  196784. pConfig->zDb, pConfig->zName
  196785. ));
  196786. }
  196787. if( p->rc==SQLITE_OK ){
  196788. /* Initialize the 4-byte leaf-page header to 0x00. */
  196789. memset(pWriter->writer.buf.p, 0, 4);
  196790. pWriter->writer.buf.n = 4;
  196791. /* Bind the current output segment id to the index-writer. This is an
  196792. ** optimization over binding the same value over and over as rows are
  196793. ** inserted into %_idx by the current writer. */
  196794. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  196795. }
  196796. }
  196797. /*
  196798. ** Iterator pIter was used to iterate through the input segments of on an
  196799. ** incremental merge operation. This function is called if the incremental
  196800. ** merge step has finished but the input has not been completely exhausted.
  196801. */
  196802. static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
  196803. int i;
  196804. Fts5Buffer buf;
  196805. memset(&buf, 0, sizeof(Fts5Buffer));
  196806. for(i=0; i<pIter->nSeg; i++){
  196807. Fts5SegIter *pSeg = &pIter->aSeg[i];
  196808. if( pSeg->pSeg==0 ){
  196809. /* no-op */
  196810. }else if( pSeg->pLeaf==0 ){
  196811. /* All keys from this input segment have been transfered to the output.
  196812. ** Set both the first and last page-numbers to 0 to indicate that the
  196813. ** segment is now empty. */
  196814. pSeg->pSeg->pgnoLast = 0;
  196815. pSeg->pSeg->pgnoFirst = 0;
  196816. }else{
  196817. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  196818. i64 iLeafRowid;
  196819. Fts5Data *pData;
  196820. int iId = pSeg->pSeg->iSegid;
  196821. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  196822. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  196823. pData = fts5DataRead(p, iLeafRowid);
  196824. if( pData ){
  196825. fts5BufferZero(&buf);
  196826. fts5BufferGrow(&p->rc, &buf, pData->nn);
  196827. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  196828. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  196829. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  196830. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
  196831. if( p->rc==SQLITE_OK ){
  196832. /* Set the szLeaf field */
  196833. fts5PutU16(&buf.p[2], (u16)buf.n);
  196834. }
  196835. /* Set up the new page-index array */
  196836. fts5BufferAppendVarint(&p->rc, &buf, 4);
  196837. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  196838. && pSeg->iEndofDoclist<pData->szLeaf
  196839. ){
  196840. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  196841. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  196842. fts5BufferAppendBlob(&p->rc, &buf,
  196843. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  196844. );
  196845. }
  196846. fts5DataRelease(pData);
  196847. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  196848. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  196849. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  196850. }
  196851. }
  196852. }
  196853. fts5BufferFree(&buf);
  196854. }
  196855. static void fts5MergeChunkCallback(
  196856. Fts5Index *p,
  196857. void *pCtx,
  196858. const u8 *pChunk, int nChunk
  196859. ){
  196860. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  196861. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  196862. }
  196863. /*
  196864. **
  196865. */
  196866. static void fts5IndexMergeLevel(
  196867. Fts5Index *p, /* FTS5 backend object */
  196868. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  196869. int iLvl, /* Level to read input from */
  196870. int *pnRem /* Write up to this many output leaves */
  196871. ){
  196872. Fts5Structure *pStruct = *ppStruct;
  196873. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  196874. Fts5StructureLevel *pLvlOut;
  196875. Fts5Iter *pIter = 0; /* Iterator to read input data */
  196876. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  196877. int nInput; /* Number of input segments */
  196878. Fts5SegWriter writer; /* Writer object */
  196879. Fts5StructureSegment *pSeg; /* Output segment */
  196880. Fts5Buffer term;
  196881. int bOldest; /* True if the output segment is the oldest */
  196882. int eDetail = p->pConfig->eDetail;
  196883. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  196884. int bTermWritten = 0; /* True if current term already output */
  196885. assert( iLvl<pStruct->nLevel );
  196886. assert( pLvl->nMerge<=pLvl->nSeg );
  196887. memset(&writer, 0, sizeof(Fts5SegWriter));
  196888. memset(&term, 0, sizeof(Fts5Buffer));
  196889. if( pLvl->nMerge ){
  196890. pLvlOut = &pStruct->aLevel[iLvl+1];
  196891. assert( pLvlOut->nSeg>0 );
  196892. nInput = pLvl->nMerge;
  196893. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  196894. fts5WriteInit(p, &writer, pSeg->iSegid);
  196895. writer.writer.pgno = pSeg->pgnoLast+1;
  196896. writer.iBtPage = 0;
  196897. }else{
  196898. int iSegid = fts5AllocateSegid(p, pStruct);
  196899. /* Extend the Fts5Structure object as required to ensure the output
  196900. ** segment exists. */
  196901. if( iLvl==pStruct->nLevel-1 ){
  196902. fts5StructureAddLevel(&p->rc, ppStruct);
  196903. pStruct = *ppStruct;
  196904. }
  196905. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  196906. if( p->rc ) return;
  196907. pLvl = &pStruct->aLevel[iLvl];
  196908. pLvlOut = &pStruct->aLevel[iLvl+1];
  196909. fts5WriteInit(p, &writer, iSegid);
  196910. /* Add the new segment to the output level */
  196911. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  196912. pLvlOut->nSeg++;
  196913. pSeg->pgnoFirst = 1;
  196914. pSeg->iSegid = iSegid;
  196915. pStruct->nSegment++;
  196916. /* Read input from all segments in the input level */
  196917. nInput = pLvl->nSeg;
  196918. }
  196919. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  196920. assert( iLvl>=0 );
  196921. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
  196922. fts5MultiIterEof(p, pIter)==0;
  196923. fts5MultiIterNext(p, pIter, 0, 0)
  196924. ){
  196925. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  196926. int nPos; /* position-list size field value */
  196927. int nTerm;
  196928. const u8 *pTerm;
  196929. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  196930. if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
  196931. if( pnRem && writer.nLeafWritten>nRem ){
  196932. break;
  196933. }
  196934. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  196935. bTermWritten =0;
  196936. }
  196937. /* Check for key annihilation. */
  196938. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  196939. if( p->rc==SQLITE_OK && bTermWritten==0 ){
  196940. /* This is a new term. Append a term to the output segment. */
  196941. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  196942. bTermWritten = 1;
  196943. }
  196944. /* Append the rowid to the output */
  196945. /* WRITEPOSLISTSIZE */
  196946. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
  196947. if( eDetail==FTS5_DETAIL_NONE ){
  196948. if( pSegIter->bDel ){
  196949. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  196950. if( pSegIter->nPos>0 ){
  196951. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  196952. }
  196953. }
  196954. }else{
  196955. /* Append the position-list data to the output */
  196956. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  196957. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
  196958. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  196959. }
  196960. }
  196961. /* Flush the last leaf page to disk. Set the output segment b-tree height
  196962. ** and last leaf page number at the same time. */
  196963. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  196964. if( fts5MultiIterEof(p, pIter) ){
  196965. int i;
  196966. /* Remove the redundant segments from the %_data table */
  196967. for(i=0; i<nInput; i++){
  196968. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  196969. }
  196970. /* Remove the redundant segments from the input level */
  196971. if( pLvl->nSeg!=nInput ){
  196972. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  196973. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  196974. }
  196975. pStruct->nSegment -= nInput;
  196976. pLvl->nSeg -= nInput;
  196977. pLvl->nMerge = 0;
  196978. if( pSeg->pgnoLast==0 ){
  196979. pLvlOut->nSeg--;
  196980. pStruct->nSegment--;
  196981. }
  196982. }else{
  196983. assert( pSeg->pgnoLast>0 );
  196984. fts5TrimSegments(p, pIter);
  196985. pLvl->nMerge = nInput;
  196986. }
  196987. fts5MultiIterFree(pIter);
  196988. fts5BufferFree(&term);
  196989. if( pnRem ) *pnRem -= writer.nLeafWritten;
  196990. }
  196991. /*
  196992. ** Do up to nPg pages of automerge work on the index.
  196993. **
  196994. ** Return true if any changes were actually made, or false otherwise.
  196995. */
  196996. static int fts5IndexMerge(
  196997. Fts5Index *p, /* FTS5 backend object */
  196998. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  196999. int nPg, /* Pages of work to do */
  197000. int nMin /* Minimum number of segments to merge */
  197001. ){
  197002. int nRem = nPg;
  197003. int bRet = 0;
  197004. Fts5Structure *pStruct = *ppStruct;
  197005. while( nRem>0 && p->rc==SQLITE_OK ){
  197006. int iLvl; /* To iterate through levels */
  197007. int iBestLvl = 0; /* Level offering the most input segments */
  197008. int nBest = 0; /* Number of input segments on best level */
  197009. /* Set iBestLvl to the level to read input segments from. */
  197010. assert( pStruct->nLevel>0 );
  197011. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  197012. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  197013. if( pLvl->nMerge ){
  197014. if( pLvl->nMerge>nBest ){
  197015. iBestLvl = iLvl;
  197016. nBest = pLvl->nMerge;
  197017. }
  197018. break;
  197019. }
  197020. if( pLvl->nSeg>nBest ){
  197021. nBest = pLvl->nSeg;
  197022. iBestLvl = iLvl;
  197023. }
  197024. }
  197025. /* If nBest is still 0, then the index must be empty. */
  197026. #ifdef SQLITE_DEBUG
  197027. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  197028. assert( pStruct->aLevel[iLvl].nSeg==0 );
  197029. }
  197030. #endif
  197031. if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
  197032. break;
  197033. }
  197034. bRet = 1;
  197035. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  197036. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  197037. fts5StructurePromote(p, iBestLvl+1, pStruct);
  197038. }
  197039. }
  197040. *ppStruct = pStruct;
  197041. return bRet;
  197042. }
  197043. /*
  197044. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  197045. ** segment. This function updates the write-counter accordingly and, if
  197046. ** necessary, performs incremental merge work.
  197047. **
  197048. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  197049. ** already occurred, this function is a no-op.
  197050. */
  197051. static void fts5IndexAutomerge(
  197052. Fts5Index *p, /* FTS5 backend object */
  197053. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  197054. int nLeaf /* Number of output leaves just written */
  197055. ){
  197056. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  197057. Fts5Structure *pStruct = *ppStruct;
  197058. u64 nWrite; /* Initial value of write-counter */
  197059. int nWork; /* Number of work-quanta to perform */
  197060. int nRem; /* Number of leaf pages left to write */
  197061. /* Update the write-counter. While doing so, set nWork. */
  197062. nWrite = pStruct->nWriteCounter;
  197063. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  197064. pStruct->nWriteCounter += nLeaf;
  197065. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  197066. fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
  197067. }
  197068. }
  197069. static void fts5IndexCrisismerge(
  197070. Fts5Index *p, /* FTS5 backend object */
  197071. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  197072. ){
  197073. const int nCrisis = p->pConfig->nCrisisMerge;
  197074. Fts5Structure *pStruct = *ppStruct;
  197075. int iLvl = 0;
  197076. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  197077. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  197078. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  197079. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  197080. fts5StructurePromote(p, iLvl+1, pStruct);
  197081. iLvl++;
  197082. }
  197083. *ppStruct = pStruct;
  197084. }
  197085. static int fts5IndexReturn(Fts5Index *p){
  197086. int rc = p->rc;
  197087. p->rc = SQLITE_OK;
  197088. return rc;
  197089. }
  197090. typedef struct Fts5FlushCtx Fts5FlushCtx;
  197091. struct Fts5FlushCtx {
  197092. Fts5Index *pIdx;
  197093. Fts5SegWriter writer;
  197094. };
  197095. /*
  197096. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  197097. ** in a 32-bit integer. Return the size of the largest prefix of this
  197098. ** list nMax bytes or less in size.
  197099. */
  197100. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  197101. int ret;
  197102. u32 dummy;
  197103. ret = fts5GetVarint32(aBuf, dummy);
  197104. if( ret<nMax ){
  197105. while( 1 ){
  197106. int i = fts5GetVarint32(&aBuf[ret], dummy);
  197107. if( (ret + i) > nMax ) break;
  197108. ret += i;
  197109. }
  197110. }
  197111. return ret;
  197112. }
  197113. /*
  197114. ** Flush the contents of in-memory hash table iHash to a new level-0
  197115. ** segment on disk. Also update the corresponding structure record.
  197116. **
  197117. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  197118. ** already occurred, this function is a no-op.
  197119. */
  197120. static void fts5FlushOneHash(Fts5Index *p){
  197121. Fts5Hash *pHash = p->pHash;
  197122. Fts5Structure *pStruct;
  197123. int iSegid;
  197124. int pgnoLast = 0; /* Last leaf page number in segment */
  197125. /* Obtain a reference to the index structure and allocate a new segment-id
  197126. ** for the new level-0 segment. */
  197127. pStruct = fts5StructureRead(p);
  197128. iSegid = fts5AllocateSegid(p, pStruct);
  197129. fts5StructureInvalidate(p);
  197130. if( iSegid ){
  197131. const int pgsz = p->pConfig->pgsz;
  197132. int eDetail = p->pConfig->eDetail;
  197133. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  197134. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  197135. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  197136. Fts5SegWriter writer;
  197137. fts5WriteInit(p, &writer, iSegid);
  197138. pBuf = &writer.writer.buf;
  197139. pPgidx = &writer.writer.pgidx;
  197140. /* fts5WriteInit() should have initialized the buffers to (most likely)
  197141. ** the maximum space required. */
  197142. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  197143. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  197144. /* Begin scanning through hash table entries. This loop runs once for each
  197145. ** term/doclist currently stored within the hash table. */
  197146. if( p->rc==SQLITE_OK ){
  197147. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  197148. }
  197149. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  197150. const char *zTerm; /* Buffer containing term */
  197151. const u8 *pDoclist; /* Pointer to doclist for this term */
  197152. int nDoclist; /* Size of doclist in bytes */
  197153. /* Write the term for this entry to disk. */
  197154. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  197155. fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
  197156. assert( writer.bFirstRowidInPage==0 );
  197157. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  197158. /* The entire doclist will fit on the current leaf. */
  197159. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  197160. }else{
  197161. i64 iRowid = 0;
  197162. i64 iDelta = 0;
  197163. int iOff = 0;
  197164. /* The entire doclist will not fit on this leaf. The following
  197165. ** loop iterates through the poslists that make up the current
  197166. ** doclist. */
  197167. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  197168. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  197169. iRowid += iDelta;
  197170. if( writer.bFirstRowidInPage ){
  197171. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  197172. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  197173. writer.bFirstRowidInPage = 0;
  197174. fts5WriteDlidxAppend(p, &writer, iRowid);
  197175. }else{
  197176. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  197177. }
  197178. assert( pBuf->n<=pBuf->nSpace );
  197179. if( eDetail==FTS5_DETAIL_NONE ){
  197180. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  197181. pBuf->p[pBuf->n++] = 0;
  197182. iOff++;
  197183. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  197184. pBuf->p[pBuf->n++] = 0;
  197185. iOff++;
  197186. }
  197187. }
  197188. if( (pBuf->n + pPgidx->n)>=pgsz ){
  197189. fts5WriteFlushLeaf(p, &writer);
  197190. }
  197191. }else{
  197192. int bDummy;
  197193. int nPos;
  197194. int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  197195. nCopy += nPos;
  197196. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  197197. /* The entire poslist will fit on the current leaf. So copy
  197198. ** it in one go. */
  197199. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  197200. }else{
  197201. /* The entire poslist will not fit on this leaf. So it needs
  197202. ** to be broken into sections. The only qualification being
  197203. ** that each varint must be stored contiguously. */
  197204. const u8 *pPoslist = &pDoclist[iOff];
  197205. int iPos = 0;
  197206. while( p->rc==SQLITE_OK ){
  197207. int nSpace = pgsz - pBuf->n - pPgidx->n;
  197208. int n = 0;
  197209. if( (nCopy - iPos)<=nSpace ){
  197210. n = nCopy - iPos;
  197211. }else{
  197212. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  197213. }
  197214. assert( n>0 );
  197215. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  197216. iPos += n;
  197217. if( (pBuf->n + pPgidx->n)>=pgsz ){
  197218. fts5WriteFlushLeaf(p, &writer);
  197219. }
  197220. if( iPos>=nCopy ) break;
  197221. }
  197222. }
  197223. iOff += nCopy;
  197224. }
  197225. }
  197226. }
  197227. /* TODO2: Doclist terminator written here. */
  197228. /* pBuf->p[pBuf->n++] = '\0'; */
  197229. assert( pBuf->n<=pBuf->nSpace );
  197230. sqlite3Fts5HashScanNext(pHash);
  197231. }
  197232. sqlite3Fts5HashClear(pHash);
  197233. fts5WriteFinish(p, &writer, &pgnoLast);
  197234. /* Update the Fts5Structure. It is written back to the database by the
  197235. ** fts5StructureRelease() call below. */
  197236. if( pStruct->nLevel==0 ){
  197237. fts5StructureAddLevel(&p->rc, &pStruct);
  197238. }
  197239. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  197240. if( p->rc==SQLITE_OK ){
  197241. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  197242. pSeg->iSegid = iSegid;
  197243. pSeg->pgnoFirst = 1;
  197244. pSeg->pgnoLast = pgnoLast;
  197245. pStruct->nSegment++;
  197246. }
  197247. fts5StructurePromote(p, 0, pStruct);
  197248. }
  197249. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  197250. fts5IndexCrisismerge(p, &pStruct);
  197251. fts5StructureWrite(p, pStruct);
  197252. fts5StructureRelease(pStruct);
  197253. }
  197254. /*
  197255. ** Flush any data stored in the in-memory hash tables to the database.
  197256. */
  197257. static void fts5IndexFlush(Fts5Index *p){
  197258. /* Unless it is empty, flush the hash table to disk */
  197259. if( p->nPendingData ){
  197260. assert( p->pHash );
  197261. p->nPendingData = 0;
  197262. fts5FlushOneHash(p);
  197263. }
  197264. }
  197265. static Fts5Structure *fts5IndexOptimizeStruct(
  197266. Fts5Index *p,
  197267. Fts5Structure *pStruct
  197268. ){
  197269. Fts5Structure *pNew = 0;
  197270. int nByte = sizeof(Fts5Structure);
  197271. int nSeg = pStruct->nSegment;
  197272. int i;
  197273. /* Figure out if this structure requires optimization. A structure does
  197274. ** not require optimization if either:
  197275. **
  197276. ** + it consists of fewer than two segments, or
  197277. ** + all segments are on the same level, or
  197278. ** + all segments except one are currently inputs to a merge operation.
  197279. **
  197280. ** In the first case, return NULL. In the second, increment the ref-count
  197281. ** on *pStruct and return a copy of the pointer to it.
  197282. */
  197283. if( nSeg<2 ) return 0;
  197284. for(i=0; i<pStruct->nLevel; i++){
  197285. int nThis = pStruct->aLevel[i].nSeg;
  197286. if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
  197287. fts5StructureRef(pStruct);
  197288. return pStruct;
  197289. }
  197290. assert( pStruct->aLevel[i].nMerge<=nThis );
  197291. }
  197292. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  197293. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  197294. if( pNew ){
  197295. Fts5StructureLevel *pLvl;
  197296. nByte = nSeg * sizeof(Fts5StructureSegment);
  197297. pNew->nLevel = pStruct->nLevel+1;
  197298. pNew->nRef = 1;
  197299. pNew->nWriteCounter = pStruct->nWriteCounter;
  197300. pLvl = &pNew->aLevel[pStruct->nLevel];
  197301. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  197302. if( pLvl->aSeg ){
  197303. int iLvl, iSeg;
  197304. int iSegOut = 0;
  197305. /* Iterate through all segments, from oldest to newest. Add them to
  197306. ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
  197307. ** segment in the data structure. */
  197308. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  197309. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  197310. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  197311. iSegOut++;
  197312. }
  197313. }
  197314. pNew->nSegment = pLvl->nSeg = nSeg;
  197315. }else{
  197316. sqlite3_free(pNew);
  197317. pNew = 0;
  197318. }
  197319. }
  197320. return pNew;
  197321. }
  197322. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  197323. Fts5Structure *pStruct;
  197324. Fts5Structure *pNew = 0;
  197325. assert( p->rc==SQLITE_OK );
  197326. fts5IndexFlush(p);
  197327. pStruct = fts5StructureRead(p);
  197328. fts5StructureInvalidate(p);
  197329. if( pStruct ){
  197330. pNew = fts5IndexOptimizeStruct(p, pStruct);
  197331. }
  197332. fts5StructureRelease(pStruct);
  197333. assert( pNew==0 || pNew->nSegment>0 );
  197334. if( pNew ){
  197335. int iLvl;
  197336. for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
  197337. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  197338. int nRem = FTS5_OPT_WORK_UNIT;
  197339. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  197340. }
  197341. fts5StructureWrite(p, pNew);
  197342. fts5StructureRelease(pNew);
  197343. }
  197344. return fts5IndexReturn(p);
  197345. }
  197346. /*
  197347. ** This is called to implement the special "VALUES('merge', $nMerge)"
  197348. ** INSERT command.
  197349. */
  197350. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  197351. Fts5Structure *pStruct = fts5StructureRead(p);
  197352. if( pStruct ){
  197353. int nMin = p->pConfig->nUsermerge;
  197354. fts5StructureInvalidate(p);
  197355. if( nMerge<0 ){
  197356. Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
  197357. fts5StructureRelease(pStruct);
  197358. pStruct = pNew;
  197359. nMin = 2;
  197360. nMerge = nMerge*-1;
  197361. }
  197362. if( pStruct && pStruct->nLevel ){
  197363. if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
  197364. fts5StructureWrite(p, pStruct);
  197365. }
  197366. }
  197367. fts5StructureRelease(pStruct);
  197368. }
  197369. return fts5IndexReturn(p);
  197370. }
  197371. static void fts5AppendRowid(
  197372. Fts5Index *p,
  197373. i64 iDelta,
  197374. Fts5Iter *pUnused,
  197375. Fts5Buffer *pBuf
  197376. ){
  197377. UNUSED_PARAM(pUnused);
  197378. fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
  197379. }
  197380. static void fts5AppendPoslist(
  197381. Fts5Index *p,
  197382. i64 iDelta,
  197383. Fts5Iter *pMulti,
  197384. Fts5Buffer *pBuf
  197385. ){
  197386. int nData = pMulti->base.nData;
  197387. assert( nData>0 );
  197388. if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
  197389. fts5BufferSafeAppendVarint(pBuf, iDelta);
  197390. fts5BufferSafeAppendVarint(pBuf, nData*2);
  197391. fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
  197392. }
  197393. }
  197394. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  197395. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  197396. assert( pIter->aPoslist );
  197397. if( p>=pIter->aEof ){
  197398. pIter->aPoslist = 0;
  197399. }else{
  197400. i64 iDelta;
  197401. p += fts5GetVarint(p, (u64*)&iDelta);
  197402. pIter->iRowid += iDelta;
  197403. /* Read position list size */
  197404. if( p[0] & 0x80 ){
  197405. int nPos;
  197406. pIter->nSize = fts5GetVarint32(p, nPos);
  197407. pIter->nPoslist = (nPos>>1);
  197408. }else{
  197409. pIter->nPoslist = ((int)(p[0])) >> 1;
  197410. pIter->nSize = 1;
  197411. }
  197412. pIter->aPoslist = p;
  197413. }
  197414. }
  197415. static void fts5DoclistIterInit(
  197416. Fts5Buffer *pBuf,
  197417. Fts5DoclistIter *pIter
  197418. ){
  197419. memset(pIter, 0, sizeof(*pIter));
  197420. pIter->aPoslist = pBuf->p;
  197421. pIter->aEof = &pBuf->p[pBuf->n];
  197422. fts5DoclistIterNext(pIter);
  197423. }
  197424. #if 0
  197425. /*
  197426. ** Append a doclist to buffer pBuf.
  197427. **
  197428. ** This function assumes that space within the buffer has already been
  197429. ** allocated.
  197430. */
  197431. static void fts5MergeAppendDocid(
  197432. Fts5Buffer *pBuf, /* Buffer to write to */
  197433. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  197434. i64 iRowid /* Rowid to append */
  197435. ){
  197436. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  197437. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  197438. *piLastRowid = iRowid;
  197439. }
  197440. #endif
  197441. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  197442. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  197443. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  197444. (iLastRowid) = (iRowid); \
  197445. }
  197446. /*
  197447. ** Swap the contents of buffer *p1 with that of *p2.
  197448. */
  197449. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  197450. Fts5Buffer tmp = *p1;
  197451. *p1 = *p2;
  197452. *p2 = tmp;
  197453. }
  197454. static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
  197455. int i = *piOff;
  197456. if( i>=pBuf->n ){
  197457. *piOff = -1;
  197458. }else{
  197459. u64 iVal;
  197460. *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
  197461. *piRowid += iVal;
  197462. }
  197463. }
  197464. /*
  197465. ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
  197466. ** In this case the buffers consist of a delta-encoded list of rowids only.
  197467. */
  197468. static void fts5MergeRowidLists(
  197469. Fts5Index *p, /* FTS5 backend object */
  197470. Fts5Buffer *p1, /* First list to merge */
  197471. Fts5Buffer *p2 /* Second list to merge */
  197472. ){
  197473. int i1 = 0;
  197474. int i2 = 0;
  197475. i64 iRowid1 = 0;
  197476. i64 iRowid2 = 0;
  197477. i64 iOut = 0;
  197478. Fts5Buffer out;
  197479. memset(&out, 0, sizeof(out));
  197480. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  197481. if( p->rc ) return;
  197482. fts5NextRowid(p1, &i1, &iRowid1);
  197483. fts5NextRowid(p2, &i2, &iRowid2);
  197484. while( i1>=0 || i2>=0 ){
  197485. if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
  197486. assert( iOut==0 || iRowid1>iOut );
  197487. fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
  197488. iOut = iRowid1;
  197489. fts5NextRowid(p1, &i1, &iRowid1);
  197490. }else{
  197491. assert( iOut==0 || iRowid2>iOut );
  197492. fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
  197493. iOut = iRowid2;
  197494. if( i1>=0 && iRowid1==iRowid2 ){
  197495. fts5NextRowid(p1, &i1, &iRowid1);
  197496. }
  197497. fts5NextRowid(p2, &i2, &iRowid2);
  197498. }
  197499. }
  197500. fts5BufferSwap(&out, p1);
  197501. fts5BufferFree(&out);
  197502. }
  197503. /*
  197504. ** Buffers p1 and p2 contain doclists. This function merges the content
  197505. ** of the two doclists together and sets buffer p1 to the result before
  197506. ** returning.
  197507. **
  197508. ** If an error occurs, an error code is left in p->rc. If an error has
  197509. ** already occurred, this function is a no-op.
  197510. */
  197511. static void fts5MergePrefixLists(
  197512. Fts5Index *p, /* FTS5 backend object */
  197513. Fts5Buffer *p1, /* First list to merge */
  197514. Fts5Buffer *p2 /* Second list to merge */
  197515. ){
  197516. if( p2->n ){
  197517. i64 iLastRowid = 0;
  197518. Fts5DoclistIter i1;
  197519. Fts5DoclistIter i2;
  197520. Fts5Buffer out = {0, 0, 0};
  197521. Fts5Buffer tmp = {0, 0, 0};
  197522. /* The maximum size of the output is equal to the sum of the two
  197523. ** input sizes + 1 varint (9 bytes). The extra varint is because if the
  197524. ** first rowid in one input is a large negative number, and the first in
  197525. ** the other a non-negative number, the delta for the non-negative
  197526. ** number will be larger on disk than the literal integer value
  197527. ** was. */
  197528. if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9) ) return;
  197529. fts5DoclistIterInit(p1, &i1);
  197530. fts5DoclistIterInit(p2, &i2);
  197531. while( 1 ){
  197532. if( i1.iRowid<i2.iRowid ){
  197533. /* Copy entry from i1 */
  197534. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  197535. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  197536. fts5DoclistIterNext(&i1);
  197537. if( i1.aPoslist==0 ) break;
  197538. }
  197539. else if( i2.iRowid!=i1.iRowid ){
  197540. /* Copy entry from i2 */
  197541. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  197542. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  197543. fts5DoclistIterNext(&i2);
  197544. if( i2.aPoslist==0 ) break;
  197545. }
  197546. else{
  197547. /* Merge the two position lists. */
  197548. i64 iPos1 = 0;
  197549. i64 iPos2 = 0;
  197550. int iOff1 = 0;
  197551. int iOff2 = 0;
  197552. u8 *a1 = &i1.aPoslist[i1.nSize];
  197553. u8 *a2 = &i2.aPoslist[i2.nSize];
  197554. i64 iPrev = 0;
  197555. Fts5PoslistWriter writer;
  197556. memset(&writer, 0, sizeof(writer));
  197557. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  197558. fts5BufferZero(&tmp);
  197559. sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
  197560. if( p->rc ) break;
  197561. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  197562. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  197563. assert( iPos1>=0 && iPos2>=0 );
  197564. if( iPos1<iPos2 ){
  197565. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  197566. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  197567. }else{
  197568. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  197569. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  197570. }
  197571. if( iPos1>=0 && iPos2>=0 ){
  197572. while( 1 ){
  197573. if( iPos1<iPos2 ){
  197574. if( iPos1!=iPrev ){
  197575. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  197576. }
  197577. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  197578. if( iPos1<0 ) break;
  197579. }else{
  197580. assert( iPos2!=iPrev );
  197581. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  197582. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  197583. if( iPos2<0 ) break;
  197584. }
  197585. }
  197586. }
  197587. if( iPos1>=0 ){
  197588. if( iPos1!=iPrev ){
  197589. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  197590. }
  197591. fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
  197592. }else{
  197593. assert( iPos2>=0 && iPos2!=iPrev );
  197594. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  197595. fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
  197596. }
  197597. /* WRITEPOSLISTSIZE */
  197598. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  197599. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  197600. fts5DoclistIterNext(&i1);
  197601. fts5DoclistIterNext(&i2);
  197602. if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
  197603. }
  197604. }
  197605. if( i1.aPoslist ){
  197606. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  197607. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
  197608. }
  197609. else if( i2.aPoslist ){
  197610. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  197611. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
  197612. }
  197613. assert( out.n<=(p1->n+p2->n+9) );
  197614. fts5BufferSet(&p->rc, p1, out.n, out.p);
  197615. fts5BufferFree(&tmp);
  197616. fts5BufferFree(&out);
  197617. }
  197618. }
  197619. static void fts5SetupPrefixIter(
  197620. Fts5Index *p, /* Index to read from */
  197621. int bDesc, /* True for "ORDER BY rowid DESC" */
  197622. const u8 *pToken, /* Buffer containing prefix to match */
  197623. int nToken, /* Size of buffer pToken in bytes */
  197624. Fts5Colset *pColset, /* Restrict matches to these columns */
  197625. Fts5Iter **ppIter /* OUT: New iterator */
  197626. ){
  197627. Fts5Structure *pStruct;
  197628. Fts5Buffer *aBuf;
  197629. const int nBuf = 32;
  197630. void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
  197631. void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
  197632. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  197633. xMerge = fts5MergeRowidLists;
  197634. xAppend = fts5AppendRowid;
  197635. }else{
  197636. xMerge = fts5MergePrefixLists;
  197637. xAppend = fts5AppendPoslist;
  197638. }
  197639. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  197640. pStruct = fts5StructureRead(p);
  197641. if( aBuf && pStruct ){
  197642. const int flags = FTS5INDEX_QUERY_SCAN
  197643. | FTS5INDEX_QUERY_SKIPEMPTY
  197644. | FTS5INDEX_QUERY_NOOUTPUT;
  197645. int i;
  197646. i64 iLastRowid = 0;
  197647. Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
  197648. Fts5Data *pData;
  197649. Fts5Buffer doclist;
  197650. int bNewTerm = 1;
  197651. memset(&doclist, 0, sizeof(doclist));
  197652. fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
  197653. fts5IterSetOutputCb(&p->rc, p1);
  197654. for( /* no-op */ ;
  197655. fts5MultiIterEof(p, p1)==0;
  197656. fts5MultiIterNext2(p, p1, &bNewTerm)
  197657. ){
  197658. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  197659. int nTerm = pSeg->term.n;
  197660. const u8 *pTerm = pSeg->term.p;
  197661. p1->xSetOutputs(p1, pSeg);
  197662. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  197663. if( bNewTerm ){
  197664. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  197665. }
  197666. if( p1->base.nData==0 ) continue;
  197667. if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
  197668. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  197669. assert( i<nBuf );
  197670. if( aBuf[i].n==0 ){
  197671. fts5BufferSwap(&doclist, &aBuf[i]);
  197672. fts5BufferZero(&doclist);
  197673. }else{
  197674. xMerge(p, &doclist, &aBuf[i]);
  197675. fts5BufferZero(&aBuf[i]);
  197676. }
  197677. }
  197678. iLastRowid = 0;
  197679. }
  197680. xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
  197681. iLastRowid = p1->base.iRowid;
  197682. }
  197683. for(i=0; i<nBuf; i++){
  197684. if( p->rc==SQLITE_OK ){
  197685. xMerge(p, &doclist, &aBuf[i]);
  197686. }
  197687. fts5BufferFree(&aBuf[i]);
  197688. }
  197689. fts5MultiIterFree(p1);
  197690. pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
  197691. if( pData ){
  197692. pData->p = (u8*)&pData[1];
  197693. pData->nn = pData->szLeaf = doclist.n;
  197694. if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
  197695. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  197696. }
  197697. fts5BufferFree(&doclist);
  197698. }
  197699. fts5StructureRelease(pStruct);
  197700. sqlite3_free(aBuf);
  197701. }
  197702. /*
  197703. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  197704. ** to the document with rowid iRowid.
  197705. */
  197706. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  197707. assert( p->rc==SQLITE_OK );
  197708. /* Allocate the hash table if it has not already been allocated */
  197709. if( p->pHash==0 ){
  197710. p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
  197711. }
  197712. /* Flush the hash table to disk if required */
  197713. if( iRowid<p->iWriteRowid
  197714. || (iRowid==p->iWriteRowid && p->bDelete==0)
  197715. || (p->nPendingData > p->pConfig->nHashSize)
  197716. ){
  197717. fts5IndexFlush(p);
  197718. }
  197719. p->iWriteRowid = iRowid;
  197720. p->bDelete = bDelete;
  197721. return fts5IndexReturn(p);
  197722. }
  197723. /*
  197724. ** Commit data to disk.
  197725. */
  197726. static int sqlite3Fts5IndexSync(Fts5Index *p){
  197727. assert( p->rc==SQLITE_OK );
  197728. fts5IndexFlush(p);
  197729. fts5CloseReader(p);
  197730. return fts5IndexReturn(p);
  197731. }
  197732. /*
  197733. ** Discard any data stored in the in-memory hash tables. Do not write it
  197734. ** to the database. Additionally, assume that the contents of the %_data
  197735. ** table may have changed on disk. So any in-memory caches of %_data
  197736. ** records must be invalidated.
  197737. */
  197738. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  197739. fts5CloseReader(p);
  197740. fts5IndexDiscardData(p);
  197741. fts5StructureInvalidate(p);
  197742. /* assert( p->rc==SQLITE_OK ); */
  197743. return SQLITE_OK;
  197744. }
  197745. /*
  197746. ** The %_data table is completely empty when this function is called. This
  197747. ** function populates it with the initial structure objects for each index,
  197748. ** and the initial version of the "averages" record (a zero-byte blob).
  197749. */
  197750. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  197751. Fts5Structure s;
  197752. fts5StructureInvalidate(p);
  197753. memset(&s, 0, sizeof(Fts5Structure));
  197754. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  197755. fts5StructureWrite(p, &s);
  197756. return fts5IndexReturn(p);
  197757. }
  197758. /*
  197759. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  197760. ** and initialize the underlying %_data table.
  197761. **
  197762. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  197763. ** Otherwise, set *pp to NULL and return an SQLite error code.
  197764. */
  197765. static int sqlite3Fts5IndexOpen(
  197766. Fts5Config *pConfig,
  197767. int bCreate,
  197768. Fts5Index **pp,
  197769. char **pzErr
  197770. ){
  197771. int rc = SQLITE_OK;
  197772. Fts5Index *p; /* New object */
  197773. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  197774. if( rc==SQLITE_OK ){
  197775. p->pConfig = pConfig;
  197776. p->nWorkUnit = FTS5_WORK_UNIT;
  197777. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  197778. if( p->zDataTbl && bCreate ){
  197779. rc = sqlite3Fts5CreateTable(
  197780. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  197781. );
  197782. if( rc==SQLITE_OK ){
  197783. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  197784. "segid, term, pgno, PRIMARY KEY(segid, term)",
  197785. 1, pzErr
  197786. );
  197787. }
  197788. if( rc==SQLITE_OK ){
  197789. rc = sqlite3Fts5IndexReinit(p);
  197790. }
  197791. }
  197792. }
  197793. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  197794. if( rc ){
  197795. sqlite3Fts5IndexClose(p);
  197796. *pp = 0;
  197797. }
  197798. return rc;
  197799. }
  197800. /*
  197801. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  197802. */
  197803. static int sqlite3Fts5IndexClose(Fts5Index *p){
  197804. int rc = SQLITE_OK;
  197805. if( p ){
  197806. assert( p->pReader==0 );
  197807. fts5StructureInvalidate(p);
  197808. sqlite3_finalize(p->pWriter);
  197809. sqlite3_finalize(p->pDeleter);
  197810. sqlite3_finalize(p->pIdxWriter);
  197811. sqlite3_finalize(p->pIdxDeleter);
  197812. sqlite3_finalize(p->pIdxSelect);
  197813. sqlite3_finalize(p->pDataVersion);
  197814. sqlite3Fts5HashFree(p->pHash);
  197815. sqlite3_free(p->zDataTbl);
  197816. sqlite3_free(p);
  197817. }
  197818. return rc;
  197819. }
  197820. /*
  197821. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  197822. ** size. Return the number of bytes in the nChar character prefix of the
  197823. ** buffer, or 0 if there are less than nChar characters in total.
  197824. */
  197825. static int sqlite3Fts5IndexCharlenToBytelen(
  197826. const char *p,
  197827. int nByte,
  197828. int nChar
  197829. ){
  197830. int n = 0;
  197831. int i;
  197832. for(i=0; i<nChar; i++){
  197833. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  197834. if( (unsigned char)p[n++]>=0xc0 ){
  197835. while( (p[n] & 0xc0)==0x80 ){
  197836. n++;
  197837. if( n>=nByte ) break;
  197838. }
  197839. }
  197840. }
  197841. return n;
  197842. }
  197843. /*
  197844. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  197845. ** unicode characters in the string.
  197846. */
  197847. static int fts5IndexCharlen(const char *pIn, int nIn){
  197848. int nChar = 0;
  197849. int i = 0;
  197850. while( i<nIn ){
  197851. if( (unsigned char)pIn[i++]>=0xc0 ){
  197852. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  197853. }
  197854. nChar++;
  197855. }
  197856. return nChar;
  197857. }
  197858. /*
  197859. ** Insert or remove data to or from the index. Each time a document is
  197860. ** added to or removed from the index, this function is called one or more
  197861. ** times.
  197862. **
  197863. ** For an insert, it must be called once for each token in the new document.
  197864. ** If the operation is a delete, it must be called (at least) once for each
  197865. ** unique token in the document with an iCol value less than zero. The iPos
  197866. ** argument is ignored for a delete.
  197867. */
  197868. static int sqlite3Fts5IndexWrite(
  197869. Fts5Index *p, /* Index to write to */
  197870. int iCol, /* Column token appears in (-ve -> delete) */
  197871. int iPos, /* Position of token within column */
  197872. const char *pToken, int nToken /* Token to add or remove to or from index */
  197873. ){
  197874. int i; /* Used to iterate through indexes */
  197875. int rc = SQLITE_OK; /* Return code */
  197876. Fts5Config *pConfig = p->pConfig;
  197877. assert( p->rc==SQLITE_OK );
  197878. assert( (iCol<0)==p->bDelete );
  197879. /* Add the entry to the main terms index. */
  197880. rc = sqlite3Fts5HashWrite(
  197881. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  197882. );
  197883. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  197884. const int nChar = pConfig->aPrefix[i];
  197885. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  197886. if( nByte ){
  197887. rc = sqlite3Fts5HashWrite(p->pHash,
  197888. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  197889. nByte
  197890. );
  197891. }
  197892. }
  197893. return rc;
  197894. }
  197895. /*
  197896. ** Open a new iterator to iterate though all rowid that match the
  197897. ** specified token or token prefix.
  197898. */
  197899. static int sqlite3Fts5IndexQuery(
  197900. Fts5Index *p, /* FTS index to query */
  197901. const char *pToken, int nToken, /* Token (or prefix) to query for */
  197902. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  197903. Fts5Colset *pColset, /* Match these columns only */
  197904. Fts5IndexIter **ppIter /* OUT: New iterator object */
  197905. ){
  197906. Fts5Config *pConfig = p->pConfig;
  197907. Fts5Iter *pRet = 0;
  197908. Fts5Buffer buf = {0, 0, 0};
  197909. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  197910. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  197911. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  197912. int iIdx = 0; /* Index to search */
  197913. if( nToken ) memcpy(&buf.p[1], pToken, nToken);
  197914. /* Figure out which index to search and set iIdx accordingly. If this
  197915. ** is a prefix query for which there is no prefix index, set iIdx to
  197916. ** greater than pConfig->nPrefix to indicate that the query will be
  197917. ** satisfied by scanning multiple terms in the main index.
  197918. **
  197919. ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
  197920. ** prefix-query. Instead of using a prefix-index (if one exists),
  197921. ** evaluate the prefix query using the main FTS index. This is used
  197922. ** for internal sanity checking by the integrity-check in debug
  197923. ** mode only. */
  197924. #ifdef SQLITE_DEBUG
  197925. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  197926. assert( flags & FTS5INDEX_QUERY_PREFIX );
  197927. iIdx = 1+pConfig->nPrefix;
  197928. }else
  197929. #endif
  197930. if( flags & FTS5INDEX_QUERY_PREFIX ){
  197931. int nChar = fts5IndexCharlen(pToken, nToken);
  197932. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  197933. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  197934. }
  197935. }
  197936. if( iIdx<=pConfig->nPrefix ){
  197937. /* Straight index lookup */
  197938. Fts5Structure *pStruct = fts5StructureRead(p);
  197939. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  197940. if( pStruct ){
  197941. fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
  197942. pColset, buf.p, nToken+1, -1, 0, &pRet
  197943. );
  197944. fts5StructureRelease(pStruct);
  197945. }
  197946. }else{
  197947. /* Scan multiple terms in the main index */
  197948. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  197949. buf.p[0] = FTS5_MAIN_PREFIX;
  197950. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  197951. assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
  197952. fts5IterSetOutputCb(&p->rc, pRet);
  197953. if( p->rc==SQLITE_OK ){
  197954. Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
  197955. if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
  197956. }
  197957. }
  197958. if( p->rc ){
  197959. sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
  197960. pRet = 0;
  197961. fts5CloseReader(p);
  197962. }
  197963. *ppIter = (Fts5IndexIter*)pRet;
  197964. sqlite3Fts5BufferFree(&buf);
  197965. }
  197966. return fts5IndexReturn(p);
  197967. }
  197968. /*
  197969. ** Return true if the iterator passed as the only argument is at EOF.
  197970. */
  197971. /*
  197972. ** Move to the next matching rowid.
  197973. */
  197974. static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
  197975. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  197976. assert( pIter->pIndex->rc==SQLITE_OK );
  197977. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  197978. return fts5IndexReturn(pIter->pIndex);
  197979. }
  197980. /*
  197981. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  197982. */
  197983. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
  197984. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  197985. Fts5Index *p = pIter->pIndex;
  197986. assert( pIter->pIndex->rc==SQLITE_OK );
  197987. fts5MultiIterNext(p, pIter, 0, 0);
  197988. if( p->rc==SQLITE_OK ){
  197989. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  197990. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  197991. fts5DataRelease(pSeg->pLeaf);
  197992. pSeg->pLeaf = 0;
  197993. pIter->base.bEof = 1;
  197994. }
  197995. }
  197996. return fts5IndexReturn(pIter->pIndex);
  197997. }
  197998. /*
  197999. ** Move to the next matching rowid that occurs at or after iMatch. The
  198000. ** definition of "at or after" depends on whether this iterator iterates
  198001. ** in ascending or descending rowid order.
  198002. */
  198003. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
  198004. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  198005. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  198006. return fts5IndexReturn(pIter->pIndex);
  198007. }
  198008. /*
  198009. ** Return the current term.
  198010. */
  198011. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
  198012. int n;
  198013. const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
  198014. *pn = n-1;
  198015. return &z[1];
  198016. }
  198017. /*
  198018. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  198019. */
  198020. static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
  198021. if( pIndexIter ){
  198022. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  198023. Fts5Index *pIndex = pIter->pIndex;
  198024. fts5MultiIterFree(pIter);
  198025. fts5CloseReader(pIndex);
  198026. }
  198027. }
  198028. /*
  198029. ** Read and decode the "averages" record from the database.
  198030. **
  198031. ** Parameter anSize must point to an array of size nCol, where nCol is
  198032. ** the number of user defined columns in the FTS table.
  198033. */
  198034. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  198035. int nCol = p->pConfig->nCol;
  198036. Fts5Data *pData;
  198037. *pnRow = 0;
  198038. memset(anSize, 0, sizeof(i64) * nCol);
  198039. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  198040. if( p->rc==SQLITE_OK && pData->nn ){
  198041. int i = 0;
  198042. int iCol;
  198043. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  198044. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  198045. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  198046. }
  198047. }
  198048. fts5DataRelease(pData);
  198049. return fts5IndexReturn(p);
  198050. }
  198051. /*
  198052. ** Replace the current "averages" record with the contents of the buffer
  198053. ** supplied as the second argument.
  198054. */
  198055. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  198056. assert( p->rc==SQLITE_OK );
  198057. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  198058. return fts5IndexReturn(p);
  198059. }
  198060. /*
  198061. ** Return the total number of blocks this module has read from the %_data
  198062. ** table since it was created.
  198063. */
  198064. static int sqlite3Fts5IndexReads(Fts5Index *p){
  198065. return p->nRead;
  198066. }
  198067. /*
  198068. ** Set the 32-bit cookie value stored at the start of all structure
  198069. ** records to the value passed as the second argument.
  198070. **
  198071. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  198072. ** occurs.
  198073. */
  198074. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  198075. int rc; /* Return code */
  198076. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  198077. u8 aCookie[4]; /* Binary representation of iNew */
  198078. sqlite3_blob *pBlob = 0;
  198079. assert( p->rc==SQLITE_OK );
  198080. sqlite3Fts5Put32(aCookie, iNew);
  198081. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  198082. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  198083. );
  198084. if( rc==SQLITE_OK ){
  198085. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  198086. rc = sqlite3_blob_close(pBlob);
  198087. }
  198088. return rc;
  198089. }
  198090. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  198091. Fts5Structure *pStruct;
  198092. pStruct = fts5StructureRead(p);
  198093. fts5StructureRelease(pStruct);
  198094. return fts5IndexReturn(p);
  198095. }
  198096. /*************************************************************************
  198097. **************************************************************************
  198098. ** Below this point is the implementation of the integrity-check
  198099. ** functionality.
  198100. */
  198101. /*
  198102. ** Return a simple checksum value based on the arguments.
  198103. */
  198104. static u64 sqlite3Fts5IndexEntryCksum(
  198105. i64 iRowid,
  198106. int iCol,
  198107. int iPos,
  198108. int iIdx,
  198109. const char *pTerm,
  198110. int nTerm
  198111. ){
  198112. int i;
  198113. u64 ret = iRowid;
  198114. ret += (ret<<3) + iCol;
  198115. ret += (ret<<3) + iPos;
  198116. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  198117. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  198118. return ret;
  198119. }
  198120. #ifdef SQLITE_DEBUG
  198121. /*
  198122. ** This function is purely an internal test. It does not contribute to
  198123. ** FTS functionality, or even the integrity-check, in any way.
  198124. **
  198125. ** Instead, it tests that the same set of pgno/rowid combinations are
  198126. ** visited regardless of whether the doclist-index identified by parameters
  198127. ** iSegid/iLeaf is iterated in forwards or reverse order.
  198128. */
  198129. static void fts5TestDlidxReverse(
  198130. Fts5Index *p,
  198131. int iSegid, /* Segment id to load from */
  198132. int iLeaf /* Load doclist-index for this leaf */
  198133. ){
  198134. Fts5DlidxIter *pDlidx = 0;
  198135. u64 cksum1 = 13;
  198136. u64 cksum2 = 13;
  198137. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  198138. fts5DlidxIterEof(p, pDlidx)==0;
  198139. fts5DlidxIterNext(p, pDlidx)
  198140. ){
  198141. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  198142. int pgno = fts5DlidxIterPgno(pDlidx);
  198143. assert( pgno>iLeaf );
  198144. cksum1 += iRowid + ((i64)pgno<<32);
  198145. }
  198146. fts5DlidxIterFree(pDlidx);
  198147. pDlidx = 0;
  198148. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  198149. fts5DlidxIterEof(p, pDlidx)==0;
  198150. fts5DlidxIterPrev(p, pDlidx)
  198151. ){
  198152. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  198153. int pgno = fts5DlidxIterPgno(pDlidx);
  198154. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  198155. cksum2 += iRowid + ((i64)pgno<<32);
  198156. }
  198157. fts5DlidxIterFree(pDlidx);
  198158. pDlidx = 0;
  198159. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  198160. }
  198161. static int fts5QueryCksum(
  198162. Fts5Index *p, /* Fts5 index object */
  198163. int iIdx,
  198164. const char *z, /* Index key to query for */
  198165. int n, /* Size of index key in bytes */
  198166. int flags, /* Flags for Fts5IndexQuery */
  198167. u64 *pCksum /* IN/OUT: Checksum value */
  198168. ){
  198169. int eDetail = p->pConfig->eDetail;
  198170. u64 cksum = *pCksum;
  198171. Fts5IndexIter *pIter = 0;
  198172. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
  198173. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
  198174. i64 rowid = pIter->iRowid;
  198175. if( eDetail==FTS5_DETAIL_NONE ){
  198176. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
  198177. }else{
  198178. Fts5PoslistReader sReader;
  198179. for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
  198180. sReader.bEof==0;
  198181. sqlite3Fts5PoslistReaderNext(&sReader)
  198182. ){
  198183. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  198184. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  198185. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  198186. }
  198187. }
  198188. if( rc==SQLITE_OK ){
  198189. rc = sqlite3Fts5IterNext(pIter);
  198190. }
  198191. }
  198192. sqlite3Fts5IterClose(pIter);
  198193. *pCksum = cksum;
  198194. return rc;
  198195. }
  198196. /*
  198197. ** This function is also purely an internal test. It does not contribute to
  198198. ** FTS functionality, or even the integrity-check, in any way.
  198199. */
  198200. static void fts5TestTerm(
  198201. Fts5Index *p,
  198202. Fts5Buffer *pPrev, /* Previous term */
  198203. const char *z, int n, /* Possibly new term to test */
  198204. u64 expected,
  198205. u64 *pCksum
  198206. ){
  198207. int rc = p->rc;
  198208. if( pPrev->n==0 ){
  198209. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  198210. }else
  198211. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  198212. u64 cksum3 = *pCksum;
  198213. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  198214. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  198215. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  198216. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  198217. u64 ck1 = 0;
  198218. u64 ck2 = 0;
  198219. /* Check that the results returned for ASC and DESC queries are
  198220. ** the same. If not, call this corruption. */
  198221. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  198222. if( rc==SQLITE_OK ){
  198223. int f = flags|FTS5INDEX_QUERY_DESC;
  198224. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  198225. }
  198226. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  198227. /* If this is a prefix query, check that the results returned if the
  198228. ** the index is disabled are the same. In both ASC and DESC order.
  198229. **
  198230. ** This check may only be performed if the hash table is empty. This
  198231. ** is because the hash table only supports a single scan query at
  198232. ** a time, and the multi-iter loop from which this function is called
  198233. ** is already performing such a scan. */
  198234. if( p->nPendingData==0 ){
  198235. if( iIdx>0 && rc==SQLITE_OK ){
  198236. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  198237. ck2 = 0;
  198238. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  198239. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  198240. }
  198241. if( iIdx>0 && rc==SQLITE_OK ){
  198242. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  198243. ck2 = 0;
  198244. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  198245. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  198246. }
  198247. }
  198248. cksum3 ^= ck1;
  198249. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  198250. if( rc==SQLITE_OK && cksum3!=expected ){
  198251. rc = FTS5_CORRUPT;
  198252. }
  198253. *pCksum = cksum3;
  198254. }
  198255. p->rc = rc;
  198256. }
  198257. #else
  198258. # define fts5TestDlidxReverse(x,y,z)
  198259. # define fts5TestTerm(u,v,w,x,y,z)
  198260. #endif
  198261. /*
  198262. ** Check that:
  198263. **
  198264. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  198265. ** contain zero terms.
  198266. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  198267. ** contain zero rowids.
  198268. */
  198269. static void fts5IndexIntegrityCheckEmpty(
  198270. Fts5Index *p,
  198271. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  198272. int iFirst,
  198273. int iNoRowid,
  198274. int iLast
  198275. ){
  198276. int i;
  198277. /* Now check that the iter.nEmpty leaves following the current leaf
  198278. ** (a) exist and (b) contain no terms. */
  198279. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  198280. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  198281. if( pLeaf ){
  198282. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  198283. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  198284. }
  198285. fts5DataRelease(pLeaf);
  198286. }
  198287. }
  198288. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  198289. int iTermOff = 0;
  198290. int ii;
  198291. Fts5Buffer buf1 = {0,0,0};
  198292. Fts5Buffer buf2 = {0,0,0};
  198293. ii = pLeaf->szLeaf;
  198294. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  198295. int res;
  198296. int iOff;
  198297. int nIncr;
  198298. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  198299. iTermOff += nIncr;
  198300. iOff = iTermOff;
  198301. if( iOff>=pLeaf->szLeaf ){
  198302. p->rc = FTS5_CORRUPT;
  198303. }else if( iTermOff==nIncr ){
  198304. int nByte;
  198305. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  198306. if( (iOff+nByte)>pLeaf->szLeaf ){
  198307. p->rc = FTS5_CORRUPT;
  198308. }else{
  198309. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  198310. }
  198311. }else{
  198312. int nKeep, nByte;
  198313. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  198314. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  198315. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  198316. p->rc = FTS5_CORRUPT;
  198317. }else{
  198318. buf1.n = nKeep;
  198319. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  198320. }
  198321. if( p->rc==SQLITE_OK ){
  198322. res = fts5BufferCompare(&buf1, &buf2);
  198323. if( res<=0 ) p->rc = FTS5_CORRUPT;
  198324. }
  198325. }
  198326. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  198327. }
  198328. fts5BufferFree(&buf1);
  198329. fts5BufferFree(&buf2);
  198330. }
  198331. static void fts5IndexIntegrityCheckSegment(
  198332. Fts5Index *p, /* FTS5 backend object */
  198333. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  198334. ){
  198335. Fts5Config *pConfig = p->pConfig;
  198336. sqlite3_stmt *pStmt = 0;
  198337. int rc2;
  198338. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  198339. int iDlidxPrevLeaf = pSeg->pgnoLast;
  198340. if( pSeg->pgnoFirst==0 ) return;
  198341. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  198342. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
  198343. pConfig->zDb, pConfig->zName, pSeg->iSegid
  198344. ));
  198345. /* Iterate through the b-tree hierarchy. */
  198346. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  198347. i64 iRow; /* Rowid for this leaf */
  198348. Fts5Data *pLeaf; /* Data for this leaf */
  198349. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  198350. const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
  198351. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  198352. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  198353. /* If the leaf in question has already been trimmed from the segment,
  198354. ** ignore this b-tree entry. Otherwise, load it into memory. */
  198355. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  198356. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  198357. pLeaf = fts5LeafRead(p, iRow);
  198358. if( pLeaf==0 ) break;
  198359. /* Check that the leaf contains at least one term, and that it is equal
  198360. ** to or larger than the split-key in zIdxTerm. Also check that if there
  198361. ** is also a rowid pointer within the leaf page header, it points to a
  198362. ** location before the term. */
  198363. if( pLeaf->nn<=pLeaf->szLeaf ){
  198364. p->rc = FTS5_CORRUPT;
  198365. }else{
  198366. int iOff; /* Offset of first term on leaf */
  198367. int iRowidOff; /* Offset of first rowid on leaf */
  198368. int nTerm; /* Size of term on leaf in bytes */
  198369. int res; /* Comparison of term and split-key */
  198370. iOff = fts5LeafFirstTermOff(pLeaf);
  198371. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  198372. if( iRowidOff>=iOff ){
  198373. p->rc = FTS5_CORRUPT;
  198374. }else{
  198375. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  198376. res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  198377. if( res==0 ) res = nTerm - nIdxTerm;
  198378. if( res<0 ) p->rc = FTS5_CORRUPT;
  198379. }
  198380. fts5IntegrityCheckPgidx(p, pLeaf);
  198381. }
  198382. fts5DataRelease(pLeaf);
  198383. if( p->rc ) break;
  198384. /* Now check that the iter.nEmpty leaves following the current leaf
  198385. ** (a) exist and (b) contain no terms. */
  198386. fts5IndexIntegrityCheckEmpty(
  198387. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  198388. );
  198389. if( p->rc ) break;
  198390. /* If there is a doclist-index, check that it looks right. */
  198391. if( bIdxDlidx ){
  198392. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  198393. int iPrevLeaf = iIdxLeaf;
  198394. int iSegid = pSeg->iSegid;
  198395. int iPg = 0;
  198396. i64 iKey;
  198397. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  198398. fts5DlidxIterEof(p, pDlidx)==0;
  198399. fts5DlidxIterNext(p, pDlidx)
  198400. ){
  198401. /* Check any rowid-less pages that occur before the current leaf. */
  198402. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  198403. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  198404. pLeaf = fts5DataRead(p, iKey);
  198405. if( pLeaf ){
  198406. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  198407. fts5DataRelease(pLeaf);
  198408. }
  198409. }
  198410. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  198411. /* Check that the leaf page indicated by the iterator really does
  198412. ** contain the rowid suggested by the same. */
  198413. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  198414. pLeaf = fts5DataRead(p, iKey);
  198415. if( pLeaf ){
  198416. i64 iRowid;
  198417. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  198418. ASSERT_SZLEAF_OK(pLeaf);
  198419. if( iRowidOff>=pLeaf->szLeaf ){
  198420. p->rc = FTS5_CORRUPT;
  198421. }else{
  198422. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  198423. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  198424. }
  198425. fts5DataRelease(pLeaf);
  198426. }
  198427. }
  198428. iDlidxPrevLeaf = iPg;
  198429. fts5DlidxIterFree(pDlidx);
  198430. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  198431. }else{
  198432. iDlidxPrevLeaf = pSeg->pgnoLast;
  198433. /* TODO: Check there is no doclist index */
  198434. }
  198435. iIdxPrevLeaf = iIdxLeaf;
  198436. }
  198437. rc2 = sqlite3_finalize(pStmt);
  198438. if( p->rc==SQLITE_OK ) p->rc = rc2;
  198439. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  198440. #if 0
  198441. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  198442. p->rc = FTS5_CORRUPT;
  198443. }
  198444. #endif
  198445. }
  198446. /*
  198447. ** Run internal checks to ensure that the FTS index (a) is internally
  198448. ** consistent and (b) contains entries for which the XOR of the checksums
  198449. ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
  198450. **
  198451. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  198452. ** checksum does not match. Return SQLITE_OK if all checks pass without
  198453. ** error, or some other SQLite error code if another error (e.g. OOM)
  198454. ** occurs.
  198455. */
  198456. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  198457. int eDetail = p->pConfig->eDetail;
  198458. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  198459. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  198460. Fts5Iter *pIter; /* Used to iterate through entire index */
  198461. Fts5Structure *pStruct; /* Index structure */
  198462. #ifdef SQLITE_DEBUG
  198463. /* Used by extra internal tests only run if NDEBUG is not defined */
  198464. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  198465. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  198466. #endif
  198467. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  198468. /* Load the FTS index structure */
  198469. pStruct = fts5StructureRead(p);
  198470. /* Check that the internal nodes of each segment match the leaves */
  198471. if( pStruct ){
  198472. int iLvl, iSeg;
  198473. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  198474. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  198475. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  198476. fts5IndexIntegrityCheckSegment(p, pSeg);
  198477. }
  198478. }
  198479. }
  198480. /* The cksum argument passed to this function is a checksum calculated
  198481. ** based on all expected entries in the FTS index (including prefix index
  198482. ** entries). This block checks that a checksum calculated based on the
  198483. ** actual contents of FTS index is identical.
  198484. **
  198485. ** Two versions of the same checksum are calculated. The first (stack
  198486. ** variable cksum2) based on entries extracted from the full-text index
  198487. ** while doing a linear scan of each individual index in turn.
  198488. **
  198489. ** As each term visited by the linear scans, a separate query for the
  198490. ** same term is performed. cksum3 is calculated based on the entries
  198491. ** extracted by these queries.
  198492. */
  198493. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
  198494. fts5MultiIterEof(p, pIter)==0;
  198495. fts5MultiIterNext(p, pIter, 0, 0)
  198496. ){
  198497. int n; /* Size of term in bytes */
  198498. i64 iPos = 0; /* Position read from poslist */
  198499. int iOff = 0; /* Offset within poslist */
  198500. i64 iRowid = fts5MultiIterRowid(pIter);
  198501. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  198502. /* If this is a new term, query for it. Update cksum3 with the results. */
  198503. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  198504. if( eDetail==FTS5_DETAIL_NONE ){
  198505. if( 0==fts5MultiIterIsEmpty(p, pIter) ){
  198506. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
  198507. }
  198508. }else{
  198509. poslist.n = 0;
  198510. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
  198511. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  198512. int iCol = FTS5_POS2COLUMN(iPos);
  198513. int iTokOff = FTS5_POS2OFFSET(iPos);
  198514. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  198515. }
  198516. }
  198517. }
  198518. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  198519. fts5MultiIterFree(pIter);
  198520. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  198521. fts5StructureRelease(pStruct);
  198522. #ifdef SQLITE_DEBUG
  198523. fts5BufferFree(&term);
  198524. #endif
  198525. fts5BufferFree(&poslist);
  198526. return fts5IndexReturn(p);
  198527. }
  198528. /*************************************************************************
  198529. **************************************************************************
  198530. ** Below this point is the implementation of the fts5_decode() scalar
  198531. ** function only.
  198532. */
  198533. /*
  198534. ** Decode a segment-data rowid from the %_data table. This function is
  198535. ** the opposite of macro FTS5_SEGMENT_ROWID().
  198536. */
  198537. static void fts5DecodeRowid(
  198538. i64 iRowid, /* Rowid from %_data table */
  198539. int *piSegid, /* OUT: Segment id */
  198540. int *pbDlidx, /* OUT: Dlidx flag */
  198541. int *piHeight, /* OUT: Height */
  198542. int *piPgno /* OUT: Page number */
  198543. ){
  198544. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  198545. iRowid >>= FTS5_DATA_PAGE_B;
  198546. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  198547. iRowid >>= FTS5_DATA_HEIGHT_B;
  198548. *pbDlidx = (int)(iRowid & 0x0001);
  198549. iRowid >>= FTS5_DATA_DLI_B;
  198550. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  198551. }
  198552. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  198553. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  198554. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  198555. if( iSegid==0 ){
  198556. if( iKey==FTS5_AVERAGES_ROWID ){
  198557. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  198558. }else{
  198559. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  198560. }
  198561. }
  198562. else{
  198563. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  198564. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  198565. );
  198566. }
  198567. }
  198568. static void fts5DebugStructure(
  198569. int *pRc, /* IN/OUT: error code */
  198570. Fts5Buffer *pBuf,
  198571. Fts5Structure *p
  198572. ){
  198573. int iLvl, iSeg; /* Iterate through levels, segments */
  198574. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  198575. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  198576. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  198577. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  198578. );
  198579. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  198580. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  198581. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  198582. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  198583. );
  198584. }
  198585. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  198586. }
  198587. }
  198588. /*
  198589. ** This is part of the fts5_decode() debugging aid.
  198590. **
  198591. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  198592. ** function appends a human-readable representation of the same object
  198593. ** to the buffer passed as the second argument.
  198594. */
  198595. static void fts5DecodeStructure(
  198596. int *pRc, /* IN/OUT: error code */
  198597. Fts5Buffer *pBuf,
  198598. const u8 *pBlob, int nBlob
  198599. ){
  198600. int rc; /* Return code */
  198601. Fts5Structure *p = 0; /* Decoded structure object */
  198602. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  198603. if( rc!=SQLITE_OK ){
  198604. *pRc = rc;
  198605. return;
  198606. }
  198607. fts5DebugStructure(pRc, pBuf, p);
  198608. fts5StructureRelease(p);
  198609. }
  198610. /*
  198611. ** This is part of the fts5_decode() debugging aid.
  198612. **
  198613. ** Arguments pBlob/nBlob contain an "averages" record. This function
  198614. ** appends a human-readable representation of record to the buffer passed
  198615. ** as the second argument.
  198616. */
  198617. static void fts5DecodeAverages(
  198618. int *pRc, /* IN/OUT: error code */
  198619. Fts5Buffer *pBuf,
  198620. const u8 *pBlob, int nBlob
  198621. ){
  198622. int i = 0;
  198623. const char *zSpace = "";
  198624. while( i<nBlob ){
  198625. u64 iVal;
  198626. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  198627. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  198628. zSpace = " ";
  198629. }
  198630. }
  198631. /*
  198632. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  198633. ** each varint and append its string representation to buffer pBuf. Return
  198634. ** after either the input buffer is exhausted or a 0 value is read.
  198635. **
  198636. ** The return value is the number of bytes read from the input buffer.
  198637. */
  198638. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  198639. int iOff = 0;
  198640. while( iOff<n ){
  198641. int iVal;
  198642. iOff += fts5GetVarint32(&a[iOff], iVal);
  198643. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  198644. }
  198645. return iOff;
  198646. }
  198647. /*
  198648. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  198649. ** may or may not finish within the buffer. This function appends a text
  198650. ** representation of the part of the doclist that is present to buffer
  198651. ** pBuf.
  198652. **
  198653. ** The return value is the number of bytes read from the input buffer.
  198654. */
  198655. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  198656. i64 iDocid = 0;
  198657. int iOff = 0;
  198658. if( n>0 ){
  198659. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  198660. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  198661. }
  198662. while( iOff<n ){
  198663. int nPos;
  198664. int bDel;
  198665. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  198666. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  198667. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  198668. if( iOff<n ){
  198669. i64 iDelta;
  198670. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  198671. iDocid += iDelta;
  198672. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  198673. }
  198674. }
  198675. return iOff;
  198676. }
  198677. /*
  198678. ** This function is part of the fts5_decode() debugging function. It is
  198679. ** only ever used with detail=none tables.
  198680. **
  198681. ** Buffer (pData/nData) contains a doclist in the format used by detail=none
  198682. ** tables. This function appends a human-readable version of that list to
  198683. ** buffer pBuf.
  198684. **
  198685. ** If *pRc is other than SQLITE_OK when this function is called, it is a
  198686. ** no-op. If an OOM or other error occurs within this function, *pRc is
  198687. ** set to an SQLite error code before returning. The final state of buffer
  198688. ** pBuf is undefined in this case.
  198689. */
  198690. static void fts5DecodeRowidList(
  198691. int *pRc, /* IN/OUT: Error code */
  198692. Fts5Buffer *pBuf, /* Buffer to append text to */
  198693. const u8 *pData, int nData /* Data to decode list-of-rowids from */
  198694. ){
  198695. int i = 0;
  198696. i64 iRowid = 0;
  198697. while( i<nData ){
  198698. const char *zApp = "";
  198699. u64 iVal;
  198700. i += sqlite3Fts5GetVarint(&pData[i], &iVal);
  198701. iRowid += iVal;
  198702. if( i<nData && pData[i]==0x00 ){
  198703. i++;
  198704. if( i<nData && pData[i]==0x00 ){
  198705. i++;
  198706. zApp = "+";
  198707. }else{
  198708. zApp = "*";
  198709. }
  198710. }
  198711. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
  198712. }
  198713. }
  198714. /*
  198715. ** The implementation of user-defined scalar function fts5_decode().
  198716. */
  198717. static void fts5DecodeFunction(
  198718. sqlite3_context *pCtx, /* Function call context */
  198719. int nArg, /* Number of args (always 2) */
  198720. sqlite3_value **apVal /* Function arguments */
  198721. ){
  198722. i64 iRowid; /* Rowid for record being decoded */
  198723. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  198724. const u8 *aBlob; int n; /* Record to decode */
  198725. u8 *a = 0;
  198726. Fts5Buffer s; /* Build up text to return here */
  198727. int rc = SQLITE_OK; /* Return code */
  198728. int nSpace = 0;
  198729. int eDetailNone = (sqlite3_user_data(pCtx)!=0);
  198730. assert( nArg==2 );
  198731. UNUSED_PARAM(nArg);
  198732. memset(&s, 0, sizeof(Fts5Buffer));
  198733. iRowid = sqlite3_value_int64(apVal[0]);
  198734. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  198735. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  198736. ** buffer overreads even if the record is corrupt. */
  198737. n = sqlite3_value_bytes(apVal[1]);
  198738. aBlob = sqlite3_value_blob(apVal[1]);
  198739. nSpace = n + FTS5_DATA_ZERO_PADDING;
  198740. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  198741. if( a==0 ) goto decode_out;
  198742. memcpy(a, aBlob, n);
  198743. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  198744. fts5DebugRowid(&rc, &s, iRowid);
  198745. if( bDlidx ){
  198746. Fts5Data dlidx;
  198747. Fts5DlidxLvl lvl;
  198748. dlidx.p = a;
  198749. dlidx.nn = n;
  198750. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  198751. lvl.pData = &dlidx;
  198752. lvl.iLeafPgno = iPgno;
  198753. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  198754. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  198755. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  198756. );
  198757. }
  198758. }else if( iSegid==0 ){
  198759. if( iRowid==FTS5_AVERAGES_ROWID ){
  198760. fts5DecodeAverages(&rc, &s, a, n);
  198761. }else{
  198762. fts5DecodeStructure(&rc, &s, a, n);
  198763. }
  198764. }else if( eDetailNone ){
  198765. Fts5Buffer term; /* Current term read from page */
  198766. int szLeaf;
  198767. int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  198768. int iTermOff;
  198769. int nKeep = 0;
  198770. int iOff;
  198771. memset(&term, 0, sizeof(Fts5Buffer));
  198772. /* Decode any entries that occur before the first term. */
  198773. if( szLeaf<n ){
  198774. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
  198775. }else{
  198776. iTermOff = szLeaf;
  198777. }
  198778. fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
  198779. iOff = iTermOff;
  198780. while( iOff<szLeaf ){
  198781. int nAppend;
  198782. /* Read the term data for the next term*/
  198783. iOff += fts5GetVarint32(&a[iOff], nAppend);
  198784. term.n = nKeep;
  198785. fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
  198786. sqlite3Fts5BufferAppendPrintf(
  198787. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  198788. );
  198789. iOff += nAppend;
  198790. /* Figure out where the doclist for this term ends */
  198791. if( iPgidxOff<n ){
  198792. int nIncr;
  198793. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
  198794. iTermOff += nIncr;
  198795. }else{
  198796. iTermOff = szLeaf;
  198797. }
  198798. fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
  198799. iOff = iTermOff;
  198800. if( iOff<szLeaf ){
  198801. iOff += fts5GetVarint32(&a[iOff], nKeep);
  198802. }
  198803. }
  198804. fts5BufferFree(&term);
  198805. }else{
  198806. Fts5Buffer term; /* Current term read from page */
  198807. int szLeaf; /* Offset of pgidx in a[] */
  198808. int iPgidxOff;
  198809. int iPgidxPrev = 0; /* Previous value read from pgidx */
  198810. int iTermOff = 0;
  198811. int iRowidOff = 0;
  198812. int iOff;
  198813. int nDoclist;
  198814. memset(&term, 0, sizeof(Fts5Buffer));
  198815. if( n<4 ){
  198816. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  198817. goto decode_out;
  198818. }else{
  198819. iRowidOff = fts5GetU16(&a[0]);
  198820. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  198821. if( iPgidxOff<n ){
  198822. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  198823. }
  198824. }
  198825. /* Decode the position list tail at the start of the page */
  198826. if( iRowidOff!=0 ){
  198827. iOff = iRowidOff;
  198828. }else if( iTermOff!=0 ){
  198829. iOff = iTermOff;
  198830. }else{
  198831. iOff = szLeaf;
  198832. }
  198833. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  198834. /* Decode any more doclist data that appears on the page before the
  198835. ** first term. */
  198836. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  198837. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  198838. while( iPgidxOff<n ){
  198839. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  198840. int nByte; /* Bytes of data */
  198841. int iEnd;
  198842. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  198843. iPgidxPrev += nByte;
  198844. iOff = iPgidxPrev;
  198845. if( iPgidxOff<n ){
  198846. fts5GetVarint32(&a[iPgidxOff], nByte);
  198847. iEnd = iPgidxPrev + nByte;
  198848. }else{
  198849. iEnd = szLeaf;
  198850. }
  198851. if( bFirst==0 ){
  198852. iOff += fts5GetVarint32(&a[iOff], nByte);
  198853. term.n = nByte;
  198854. }
  198855. iOff += fts5GetVarint32(&a[iOff], nByte);
  198856. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  198857. iOff += nByte;
  198858. sqlite3Fts5BufferAppendPrintf(
  198859. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  198860. );
  198861. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  198862. }
  198863. fts5BufferFree(&term);
  198864. }
  198865. decode_out:
  198866. sqlite3_free(a);
  198867. if( rc==SQLITE_OK ){
  198868. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  198869. }else{
  198870. sqlite3_result_error_code(pCtx, rc);
  198871. }
  198872. fts5BufferFree(&s);
  198873. }
  198874. /*
  198875. ** The implementation of user-defined scalar function fts5_rowid().
  198876. */
  198877. static void fts5RowidFunction(
  198878. sqlite3_context *pCtx, /* Function call context */
  198879. int nArg, /* Number of args (always 2) */
  198880. sqlite3_value **apVal /* Function arguments */
  198881. ){
  198882. const char *zArg;
  198883. if( nArg==0 ){
  198884. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  198885. }else{
  198886. zArg = (const char*)sqlite3_value_text(apVal[0]);
  198887. if( 0==sqlite3_stricmp(zArg, "segment") ){
  198888. i64 iRowid;
  198889. int segid, pgno;
  198890. if( nArg!=3 ){
  198891. sqlite3_result_error(pCtx,
  198892. "should be: fts5_rowid('segment', segid, pgno))", -1
  198893. );
  198894. }else{
  198895. segid = sqlite3_value_int(apVal[1]);
  198896. pgno = sqlite3_value_int(apVal[2]);
  198897. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  198898. sqlite3_result_int64(pCtx, iRowid);
  198899. }
  198900. }else{
  198901. sqlite3_result_error(pCtx,
  198902. "first arg to fts5_rowid() must be 'segment'" , -1
  198903. );
  198904. }
  198905. }
  198906. }
  198907. /*
  198908. ** This is called as part of registering the FTS5 module with database
  198909. ** connection db. It registers several user-defined scalar functions useful
  198910. ** with FTS5.
  198911. **
  198912. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  198913. ** SQLite error code is returned instead.
  198914. */
  198915. static int sqlite3Fts5IndexInit(sqlite3 *db){
  198916. int rc = sqlite3_create_function(
  198917. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  198918. );
  198919. if( rc==SQLITE_OK ){
  198920. rc = sqlite3_create_function(
  198921. db, "fts5_decode_none", 2,
  198922. SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
  198923. );
  198924. }
  198925. if( rc==SQLITE_OK ){
  198926. rc = sqlite3_create_function(
  198927. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  198928. );
  198929. }
  198930. return rc;
  198931. }
  198932. static int sqlite3Fts5IndexReset(Fts5Index *p){
  198933. assert( p->pStruct==0 || p->iStructVersion!=0 );
  198934. if( fts5IndexDataVersion(p)!=p->iStructVersion ){
  198935. fts5StructureInvalidate(p);
  198936. }
  198937. return fts5IndexReturn(p);
  198938. }
  198939. /*
  198940. ** 2014 Jun 09
  198941. **
  198942. ** The author disclaims copyright to this source code. In place of
  198943. ** a legal notice, here is a blessing:
  198944. **
  198945. ** May you do good and not evil.
  198946. ** May you find forgiveness for yourself and forgive others.
  198947. ** May you share freely, never taking more than you give.
  198948. **
  198949. ******************************************************************************
  198950. **
  198951. ** This is an SQLite module implementing full-text search.
  198952. */
  198953. /* #include "fts5Int.h" */
  198954. /*
  198955. ** This variable is set to false when running tests for which the on disk
  198956. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  198957. ** assert() conditions in the fts5 code are activated - conditions that are
  198958. ** only true if it is guaranteed that the fts5 database is not corrupt.
  198959. */
  198960. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  198961. typedef struct Fts5Auxdata Fts5Auxdata;
  198962. typedef struct Fts5Auxiliary Fts5Auxiliary;
  198963. typedef struct Fts5Cursor Fts5Cursor;
  198964. typedef struct Fts5Sorter Fts5Sorter;
  198965. typedef struct Fts5Table Fts5Table;
  198966. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  198967. /*
  198968. ** NOTES ON TRANSACTIONS:
  198969. **
  198970. ** SQLite invokes the following virtual table methods as transactions are
  198971. ** opened and closed by the user:
  198972. **
  198973. ** xBegin(): Start of a new transaction.
  198974. ** xSync(): Initial part of two-phase commit.
  198975. ** xCommit(): Final part of two-phase commit.
  198976. ** xRollback(): Rollback the transaction.
  198977. **
  198978. ** Anything that is required as part of a commit that may fail is performed
  198979. ** in the xSync() callback. Current versions of SQLite ignore any errors
  198980. ** returned by xCommit().
  198981. **
  198982. ** And as sub-transactions are opened/closed:
  198983. **
  198984. ** xSavepoint(int S): Open savepoint S.
  198985. ** xRelease(int S): Commit and close savepoint S.
  198986. ** xRollbackTo(int S): Rollback to start of savepoint S.
  198987. **
  198988. ** During a write-transaction the fts5_index.c module may cache some data
  198989. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  198990. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  198991. ** is called.
  198992. **
  198993. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  198994. ** structure is used to record the current transaction state. This information
  198995. ** is not required, but it is used in the assert() statements executed by
  198996. ** function fts5CheckTransactionState() (see below).
  198997. */
  198998. struct Fts5TransactionState {
  198999. int eState; /* 0==closed, 1==open, 2==synced */
  199000. int iSavepoint; /* Number of open savepoints (0 -> none) */
  199001. };
  199002. /*
  199003. ** A single object of this type is allocated when the FTS5 module is
  199004. ** registered with a database handle. It is used to store pointers to
  199005. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  199006. */
  199007. struct Fts5Global {
  199008. fts5_api api; /* User visible part of object (see fts5.h) */
  199009. sqlite3 *db; /* Associated database connection */
  199010. i64 iNextId; /* Used to allocate unique cursor ids */
  199011. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  199012. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  199013. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  199014. Fts5Cursor *pCsr; /* First in list of all open cursors */
  199015. };
  199016. /*
  199017. ** Each auxiliary function registered with the FTS5 module is represented
  199018. ** by an object of the following type. All such objects are stored as part
  199019. ** of the Fts5Global.pAux list.
  199020. */
  199021. struct Fts5Auxiliary {
  199022. Fts5Global *pGlobal; /* Global context for this function */
  199023. char *zFunc; /* Function name (nul-terminated) */
  199024. void *pUserData; /* User-data pointer */
  199025. fts5_extension_function xFunc; /* Callback function */
  199026. void (*xDestroy)(void*); /* Destructor function */
  199027. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  199028. };
  199029. /*
  199030. ** Each tokenizer module registered with the FTS5 module is represented
  199031. ** by an object of the following type. All such objects are stored as part
  199032. ** of the Fts5Global.pTok list.
  199033. */
  199034. struct Fts5TokenizerModule {
  199035. char *zName; /* Name of tokenizer */
  199036. void *pUserData; /* User pointer passed to xCreate() */
  199037. fts5_tokenizer x; /* Tokenizer functions */
  199038. void (*xDestroy)(void*); /* Destructor function */
  199039. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  199040. };
  199041. /*
  199042. ** Virtual-table object.
  199043. */
  199044. struct Fts5Table {
  199045. sqlite3_vtab base; /* Base class used by SQLite core */
  199046. Fts5Config *pConfig; /* Virtual table configuration */
  199047. Fts5Index *pIndex; /* Full-text index */
  199048. Fts5Storage *pStorage; /* Document store */
  199049. Fts5Global *pGlobal; /* Global (connection wide) data */
  199050. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  199051. #ifdef SQLITE_DEBUG
  199052. struct Fts5TransactionState ts;
  199053. #endif
  199054. };
  199055. struct Fts5MatchPhrase {
  199056. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  199057. int nTerm; /* Size of phrase in terms */
  199058. };
  199059. /*
  199060. ** pStmt:
  199061. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  199062. **
  199063. ** aIdx[]:
  199064. ** There is one entry in the aIdx[] array for each phrase in the query,
  199065. ** the value of which is the offset within aPoslist[] following the last
  199066. ** byte of the position list for the corresponding phrase.
  199067. */
  199068. struct Fts5Sorter {
  199069. sqlite3_stmt *pStmt;
  199070. i64 iRowid; /* Current rowid */
  199071. const u8 *aPoslist; /* Position lists for current row */
  199072. int nIdx; /* Number of entries in aIdx[] */
  199073. int aIdx[1]; /* Offsets into aPoslist for current row */
  199074. };
  199075. /*
  199076. ** Virtual-table cursor object.
  199077. **
  199078. ** iSpecial:
  199079. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  199080. ** then this variable contains the result of the query.
  199081. **
  199082. ** iFirstRowid, iLastRowid:
  199083. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  199084. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  199085. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  199086. ** WHERE clause in the user's query might have been:
  199087. **
  199088. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  199089. **
  199090. ** If the cursor iterates in descending order of rowid, iFirstRowid
  199091. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  199092. ** the lower.
  199093. */
  199094. struct Fts5Cursor {
  199095. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  199096. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  199097. int *aColumnSize; /* Values for xColumnSize() */
  199098. i64 iCsrId; /* Cursor id */
  199099. /* Zero from this point onwards on cursor reset */
  199100. int ePlan; /* FTS5_PLAN_XXX value */
  199101. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  199102. i64 iFirstRowid; /* Return no rowids earlier than this */
  199103. i64 iLastRowid; /* Return no rowids later than this */
  199104. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  199105. Fts5Expr *pExpr; /* Expression for MATCH queries */
  199106. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  199107. int csrflags; /* Mask of cursor flags (see below) */
  199108. i64 iSpecial; /* Result of special query */
  199109. /* "rank" function. Populated on demand from vtab.xColumn(). */
  199110. char *zRank; /* Custom rank function */
  199111. char *zRankArgs; /* Custom rank function args */
  199112. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  199113. int nRankArg; /* Number of trailing arguments for rank() */
  199114. sqlite3_value **apRankArg; /* Array of trailing arguments */
  199115. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  199116. /* Auxiliary data storage */
  199117. Fts5Auxiliary *pAux; /* Currently executing extension function */
  199118. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  199119. /* Cache used by auxiliary functions xInst() and xInstCount() */
  199120. Fts5PoslistReader *aInstIter; /* One for each phrase */
  199121. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  199122. int nInstCount; /* Number of phrase instances */
  199123. int *aInst; /* 3 integers per phrase instance */
  199124. };
  199125. /*
  199126. ** Bits that make up the "idxNum" parameter passed indirectly by
  199127. ** xBestIndex() to xFilter().
  199128. */
  199129. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  199130. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  199131. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  199132. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  199133. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  199134. #define FTS5_BI_ORDER_RANK 0x0020
  199135. #define FTS5_BI_ORDER_ROWID 0x0040
  199136. #define FTS5_BI_ORDER_DESC 0x0080
  199137. /*
  199138. ** Values for Fts5Cursor.csrflags
  199139. */
  199140. #define FTS5CSR_EOF 0x01
  199141. #define FTS5CSR_REQUIRE_CONTENT 0x02
  199142. #define FTS5CSR_REQUIRE_DOCSIZE 0x04
  199143. #define FTS5CSR_REQUIRE_INST 0x08
  199144. #define FTS5CSR_FREE_ZRANK 0x10
  199145. #define FTS5CSR_REQUIRE_RESEEK 0x20
  199146. #define FTS5CSR_REQUIRE_POSLIST 0x40
  199147. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  199148. #define BitFlagTest(x,y) (((x) & (y))!=0)
  199149. /*
  199150. ** Macros to Set(), Clear() and Test() cursor flags.
  199151. */
  199152. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  199153. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  199154. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  199155. struct Fts5Auxdata {
  199156. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  199157. void *pPtr; /* Pointer value */
  199158. void(*xDelete)(void*); /* Destructor */
  199159. Fts5Auxdata *pNext; /* Next object in linked list */
  199160. };
  199161. #ifdef SQLITE_DEBUG
  199162. #define FTS5_BEGIN 1
  199163. #define FTS5_SYNC 2
  199164. #define FTS5_COMMIT 3
  199165. #define FTS5_ROLLBACK 4
  199166. #define FTS5_SAVEPOINT 5
  199167. #define FTS5_RELEASE 6
  199168. #define FTS5_ROLLBACKTO 7
  199169. static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
  199170. switch( op ){
  199171. case FTS5_BEGIN:
  199172. assert( p->ts.eState==0 );
  199173. p->ts.eState = 1;
  199174. p->ts.iSavepoint = -1;
  199175. break;
  199176. case FTS5_SYNC:
  199177. assert( p->ts.eState==1 );
  199178. p->ts.eState = 2;
  199179. break;
  199180. case FTS5_COMMIT:
  199181. assert( p->ts.eState==2 );
  199182. p->ts.eState = 0;
  199183. break;
  199184. case FTS5_ROLLBACK:
  199185. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  199186. p->ts.eState = 0;
  199187. break;
  199188. case FTS5_SAVEPOINT:
  199189. assert( p->ts.eState==1 );
  199190. assert( iSavepoint>=0 );
  199191. assert( iSavepoint>=p->ts.iSavepoint );
  199192. p->ts.iSavepoint = iSavepoint;
  199193. break;
  199194. case FTS5_RELEASE:
  199195. assert( p->ts.eState==1 );
  199196. assert( iSavepoint>=0 );
  199197. assert( iSavepoint<=p->ts.iSavepoint );
  199198. p->ts.iSavepoint = iSavepoint-1;
  199199. break;
  199200. case FTS5_ROLLBACKTO:
  199201. assert( p->ts.eState==1 );
  199202. assert( iSavepoint>=0 );
  199203. assert( iSavepoint<=p->ts.iSavepoint );
  199204. p->ts.iSavepoint = iSavepoint;
  199205. break;
  199206. }
  199207. }
  199208. #else
  199209. # define fts5CheckTransactionState(x,y,z)
  199210. #endif
  199211. /*
  199212. ** Return true if pTab is a contentless table.
  199213. */
  199214. static int fts5IsContentless(Fts5Table *pTab){
  199215. return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
  199216. }
  199217. /*
  199218. ** Delete a virtual table handle allocated by fts5InitVtab().
  199219. */
  199220. static void fts5FreeVtab(Fts5Table *pTab){
  199221. if( pTab ){
  199222. sqlite3Fts5IndexClose(pTab->pIndex);
  199223. sqlite3Fts5StorageClose(pTab->pStorage);
  199224. sqlite3Fts5ConfigFree(pTab->pConfig);
  199225. sqlite3_free(pTab);
  199226. }
  199227. }
  199228. /*
  199229. ** The xDisconnect() virtual table method.
  199230. */
  199231. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  199232. fts5FreeVtab((Fts5Table*)pVtab);
  199233. return SQLITE_OK;
  199234. }
  199235. /*
  199236. ** The xDestroy() virtual table method.
  199237. */
  199238. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  199239. Fts5Table *pTab = (Fts5Table*)pVtab;
  199240. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  199241. if( rc==SQLITE_OK ){
  199242. fts5FreeVtab((Fts5Table*)pVtab);
  199243. }
  199244. return rc;
  199245. }
  199246. /*
  199247. ** This function is the implementation of both the xConnect and xCreate
  199248. ** methods of the FTS3 virtual table.
  199249. **
  199250. ** The argv[] array contains the following:
  199251. **
  199252. ** argv[0] -> module name ("fts5")
  199253. ** argv[1] -> database name
  199254. ** argv[2] -> table name
  199255. ** argv[...] -> "column name" and other module argument fields.
  199256. */
  199257. static int fts5InitVtab(
  199258. int bCreate, /* True for xCreate, false for xConnect */
  199259. sqlite3 *db, /* The SQLite database connection */
  199260. void *pAux, /* Hash table containing tokenizers */
  199261. int argc, /* Number of elements in argv array */
  199262. const char * const *argv, /* xCreate/xConnect argument array */
  199263. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  199264. char **pzErr /* Write any error message here */
  199265. ){
  199266. Fts5Global *pGlobal = (Fts5Global*)pAux;
  199267. const char **azConfig = (const char**)argv;
  199268. int rc = SQLITE_OK; /* Return code */
  199269. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  199270. Fts5Table *pTab = 0; /* New virtual table object */
  199271. /* Allocate the new vtab object and parse the configuration */
  199272. pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
  199273. if( rc==SQLITE_OK ){
  199274. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  199275. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  199276. }
  199277. if( rc==SQLITE_OK ){
  199278. pTab->pConfig = pConfig;
  199279. pTab->pGlobal = pGlobal;
  199280. }
  199281. /* Open the index sub-system */
  199282. if( rc==SQLITE_OK ){
  199283. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
  199284. }
  199285. /* Open the storage sub-system */
  199286. if( rc==SQLITE_OK ){
  199287. rc = sqlite3Fts5StorageOpen(
  199288. pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
  199289. );
  199290. }
  199291. /* Call sqlite3_declare_vtab() */
  199292. if( rc==SQLITE_OK ){
  199293. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  199294. }
  199295. /* Load the initial configuration */
  199296. if( rc==SQLITE_OK ){
  199297. assert( pConfig->pzErrmsg==0 );
  199298. pConfig->pzErrmsg = pzErr;
  199299. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  199300. sqlite3Fts5IndexRollback(pTab->pIndex);
  199301. pConfig->pzErrmsg = 0;
  199302. }
  199303. if( rc!=SQLITE_OK ){
  199304. fts5FreeVtab(pTab);
  199305. pTab = 0;
  199306. }else if( bCreate ){
  199307. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  199308. }
  199309. *ppVTab = (sqlite3_vtab*)pTab;
  199310. return rc;
  199311. }
  199312. /*
  199313. ** The xConnect() and xCreate() methods for the virtual table. All the
  199314. ** work is done in function fts5InitVtab().
  199315. */
  199316. static int fts5ConnectMethod(
  199317. sqlite3 *db, /* Database connection */
  199318. void *pAux, /* Pointer to tokenizer hash table */
  199319. int argc, /* Number of elements in argv array */
  199320. const char * const *argv, /* xCreate/xConnect argument array */
  199321. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  199322. char **pzErr /* OUT: sqlite3_malloc'd error message */
  199323. ){
  199324. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  199325. }
  199326. static int fts5CreateMethod(
  199327. sqlite3 *db, /* Database connection */
  199328. void *pAux, /* Pointer to tokenizer hash table */
  199329. int argc, /* Number of elements in argv array */
  199330. const char * const *argv, /* xCreate/xConnect argument array */
  199331. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  199332. char **pzErr /* OUT: sqlite3_malloc'd error message */
  199333. ){
  199334. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  199335. }
  199336. /*
  199337. ** The different query plans.
  199338. */
  199339. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  199340. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  199341. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  199342. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  199343. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  199344. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  199345. /*
  199346. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  199347. ** extension is currently being used by a version of SQLite too old to
  199348. ** support index-info flags. In that case this function is a no-op.
  199349. */
  199350. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  199351. #if SQLITE_VERSION_NUMBER>=3008012
  199352. #ifndef SQLITE_CORE
  199353. if( sqlite3_libversion_number()>=3008012 )
  199354. #endif
  199355. {
  199356. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  199357. }
  199358. #endif
  199359. }
  199360. /*
  199361. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  199362. ** WHERE constraint, it searches for the following:
  199363. **
  199364. ** 1. A MATCH constraint against the special column.
  199365. ** 2. A MATCH constraint against the "rank" column.
  199366. ** 3. An == constraint against the rowid column.
  199367. ** 4. A < or <= constraint against the rowid column.
  199368. ** 5. A > or >= constraint against the rowid column.
  199369. **
  199370. ** Within the ORDER BY, either:
  199371. **
  199372. ** 5. ORDER BY rank [ASC|DESC]
  199373. ** 6. ORDER BY rowid [ASC|DESC]
  199374. **
  199375. ** Costs are assigned as follows:
  199376. **
  199377. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  199378. ** cost is unconditionally set to 1e50 (a really big number).
  199379. **
  199380. ** a) If a MATCH operator is present, the cost depends on the other
  199381. ** constraints also present. As follows:
  199382. **
  199383. ** * No other constraints: cost=1000.0
  199384. ** * One rowid range constraint: cost=750.0
  199385. ** * Both rowid range constraints: cost=500.0
  199386. ** * An == rowid constraint: cost=100.0
  199387. **
  199388. ** b) Otherwise, if there is no MATCH:
  199389. **
  199390. ** * No other constraints: cost=1000000.0
  199391. ** * One rowid range constraint: cost=750000.0
  199392. ** * Both rowid range constraints: cost=250000.0
  199393. ** * An == rowid constraint: cost=10.0
  199394. **
  199395. ** Costs are not modified by the ORDER BY clause.
  199396. */
  199397. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  199398. Fts5Table *pTab = (Fts5Table*)pVTab;
  199399. Fts5Config *pConfig = pTab->pConfig;
  199400. const int nCol = pConfig->nCol;
  199401. int idxFlags = 0; /* Parameter passed through to xFilter() */
  199402. int bHasMatch;
  199403. int iNext;
  199404. int i;
  199405. struct Constraint {
  199406. int op; /* Mask against sqlite3_index_constraint.op */
  199407. int fts5op; /* FTS5 mask for idxFlags */
  199408. int iCol; /* 0==rowid, 1==tbl, 2==rank */
  199409. int omit; /* True to omit this if found */
  199410. int iConsIndex; /* Index in pInfo->aConstraint[] */
  199411. } aConstraint[] = {
  199412. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  199413. FTS5_BI_MATCH, 1, 1, -1},
  199414. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  199415. FTS5_BI_RANK, 2, 1, -1},
  199416. {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
  199417. {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
  199418. FTS5_BI_ROWID_LE, 0, 0, -1},
  199419. {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
  199420. FTS5_BI_ROWID_GE, 0, 0, -1},
  199421. };
  199422. int aColMap[3];
  199423. aColMap[0] = -1;
  199424. aColMap[1] = nCol;
  199425. aColMap[2] = nCol+1;
  199426. assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH );
  199427. assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH );
  199428. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  199429. assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH );
  199430. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  199431. /* Set idxFlags flags for all WHERE clause terms that will be used. */
  199432. for(i=0; i<pInfo->nConstraint; i++){
  199433. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  199434. int iCol = p->iColumn;
  199435. if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
  199436. || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
  199437. ){
  199438. /* A MATCH operator or equivalent */
  199439. if( p->usable ){
  199440. idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
  199441. aConstraint[0].iConsIndex = i;
  199442. }else{
  199443. /* As there exists an unusable MATCH constraint this is an
  199444. ** unusable plan. Set a prohibitively high cost. */
  199445. pInfo->estimatedCost = 1e50;
  199446. return SQLITE_OK;
  199447. }
  199448. }else if( p->op<=SQLITE_INDEX_CONSTRAINT_MATCH ){
  199449. int j;
  199450. for(j=1; j<ArraySize(aConstraint); j++){
  199451. struct Constraint *pC = &aConstraint[j];
  199452. if( iCol==aColMap[pC->iCol] && (p->op & pC->op) && p->usable ){
  199453. pC->iConsIndex = i;
  199454. idxFlags |= pC->fts5op;
  199455. }
  199456. }
  199457. }
  199458. }
  199459. /* Set idxFlags flags for the ORDER BY clause */
  199460. if( pInfo->nOrderBy==1 ){
  199461. int iSort = pInfo->aOrderBy[0].iColumn;
  199462. if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
  199463. idxFlags |= FTS5_BI_ORDER_RANK;
  199464. }else if( iSort==-1 ){
  199465. idxFlags |= FTS5_BI_ORDER_ROWID;
  199466. }
  199467. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  199468. pInfo->orderByConsumed = 1;
  199469. if( pInfo->aOrderBy[0].desc ){
  199470. idxFlags |= FTS5_BI_ORDER_DESC;
  199471. }
  199472. }
  199473. }
  199474. /* Calculate the estimated cost based on the flags set in idxFlags. */
  199475. bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
  199476. if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
  199477. pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
  199478. if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
  199479. }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  199480. pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
  199481. }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  199482. pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
  199483. }else{
  199484. pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
  199485. }
  199486. /* Assign argvIndex values to each constraint in use. */
  199487. iNext = 1;
  199488. for(i=0; i<ArraySize(aConstraint); i++){
  199489. struct Constraint *pC = &aConstraint[i];
  199490. if( pC->iConsIndex>=0 ){
  199491. pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
  199492. pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
  199493. }
  199494. }
  199495. pInfo->idxNum = idxFlags;
  199496. return SQLITE_OK;
  199497. }
  199498. static int fts5NewTransaction(Fts5Table *pTab){
  199499. Fts5Cursor *pCsr;
  199500. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  199501. if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
  199502. }
  199503. return sqlite3Fts5StorageReset(pTab->pStorage);
  199504. }
  199505. /*
  199506. ** Implementation of xOpen method.
  199507. */
  199508. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  199509. Fts5Table *pTab = (Fts5Table*)pVTab;
  199510. Fts5Config *pConfig = pTab->pConfig;
  199511. Fts5Cursor *pCsr = 0; /* New cursor object */
  199512. int nByte; /* Bytes of space to allocate */
  199513. int rc; /* Return code */
  199514. rc = fts5NewTransaction(pTab);
  199515. if( rc==SQLITE_OK ){
  199516. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  199517. pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
  199518. if( pCsr ){
  199519. Fts5Global *pGlobal = pTab->pGlobal;
  199520. memset(pCsr, 0, nByte);
  199521. pCsr->aColumnSize = (int*)&pCsr[1];
  199522. pCsr->pNext = pGlobal->pCsr;
  199523. pGlobal->pCsr = pCsr;
  199524. pCsr->iCsrId = ++pGlobal->iNextId;
  199525. }else{
  199526. rc = SQLITE_NOMEM;
  199527. }
  199528. }
  199529. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  199530. return rc;
  199531. }
  199532. static int fts5StmtType(Fts5Cursor *pCsr){
  199533. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  199534. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  199535. }
  199536. return FTS5_STMT_LOOKUP;
  199537. }
  199538. /*
  199539. ** This function is called after the cursor passed as the only argument
  199540. ** is moved to point at a different row. It clears all cached data
  199541. ** specific to the previous row stored by the cursor object.
  199542. */
  199543. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  199544. CsrFlagSet(pCsr,
  199545. FTS5CSR_REQUIRE_CONTENT
  199546. | FTS5CSR_REQUIRE_DOCSIZE
  199547. | FTS5CSR_REQUIRE_INST
  199548. | FTS5CSR_REQUIRE_POSLIST
  199549. );
  199550. }
  199551. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  199552. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  199553. Fts5Auxdata *pData;
  199554. Fts5Auxdata *pNext;
  199555. sqlite3_free(pCsr->aInstIter);
  199556. sqlite3_free(pCsr->aInst);
  199557. if( pCsr->pStmt ){
  199558. int eStmt = fts5StmtType(pCsr);
  199559. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  199560. }
  199561. if( pCsr->pSorter ){
  199562. Fts5Sorter *pSorter = pCsr->pSorter;
  199563. sqlite3_finalize(pSorter->pStmt);
  199564. sqlite3_free(pSorter);
  199565. }
  199566. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  199567. sqlite3Fts5ExprFree(pCsr->pExpr);
  199568. }
  199569. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  199570. pNext = pData->pNext;
  199571. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  199572. sqlite3_free(pData);
  199573. }
  199574. sqlite3_finalize(pCsr->pRankArgStmt);
  199575. sqlite3_free(pCsr->apRankArg);
  199576. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  199577. sqlite3_free(pCsr->zRank);
  199578. sqlite3_free(pCsr->zRankArgs);
  199579. }
  199580. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  199581. }
  199582. /*
  199583. ** Close the cursor. For additional information see the documentation
  199584. ** on the xClose method of the virtual table interface.
  199585. */
  199586. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  199587. if( pCursor ){
  199588. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  199589. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  199590. Fts5Cursor **pp;
  199591. fts5FreeCursorComponents(pCsr);
  199592. /* Remove the cursor from the Fts5Global.pCsr list */
  199593. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  199594. *pp = pCsr->pNext;
  199595. sqlite3_free(pCsr);
  199596. }
  199597. return SQLITE_OK;
  199598. }
  199599. static int fts5SorterNext(Fts5Cursor *pCsr){
  199600. Fts5Sorter *pSorter = pCsr->pSorter;
  199601. int rc;
  199602. rc = sqlite3_step(pSorter->pStmt);
  199603. if( rc==SQLITE_DONE ){
  199604. rc = SQLITE_OK;
  199605. CsrFlagSet(pCsr, FTS5CSR_EOF);
  199606. }else if( rc==SQLITE_ROW ){
  199607. const u8 *a;
  199608. const u8 *aBlob;
  199609. int nBlob;
  199610. int i;
  199611. int iOff = 0;
  199612. rc = SQLITE_OK;
  199613. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  199614. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  199615. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  199616. /* nBlob==0 in detail=none mode. */
  199617. if( nBlob>0 ){
  199618. for(i=0; i<(pSorter->nIdx-1); i++){
  199619. int iVal;
  199620. a += fts5GetVarint32(a, iVal);
  199621. iOff += iVal;
  199622. pSorter->aIdx[i] = iOff;
  199623. }
  199624. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  199625. pSorter->aPoslist = a;
  199626. }
  199627. fts5CsrNewrow(pCsr);
  199628. }
  199629. return rc;
  199630. }
  199631. /*
  199632. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  199633. ** open on table pTab.
  199634. */
  199635. static void fts5TripCursors(Fts5Table *pTab){
  199636. Fts5Cursor *pCsr;
  199637. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  199638. if( pCsr->ePlan==FTS5_PLAN_MATCH
  199639. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  199640. ){
  199641. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  199642. }
  199643. }
  199644. }
  199645. /*
  199646. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  199647. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  199648. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  199649. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  199650. **
  199651. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  199652. ** to 1 before returning. Otherwise, leave it unchanged.
  199653. **
  199654. ** Return SQLITE_OK if successful or if no reseek was required, or an
  199655. ** error code if an error occurred.
  199656. */
  199657. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  199658. int rc = SQLITE_OK;
  199659. assert( *pbSkip==0 );
  199660. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  199661. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  199662. int bDesc = pCsr->bDesc;
  199663. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  199664. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
  199665. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  199666. *pbSkip = 1;
  199667. }
  199668. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  199669. fts5CsrNewrow(pCsr);
  199670. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  199671. CsrFlagSet(pCsr, FTS5CSR_EOF);
  199672. *pbSkip = 1;
  199673. }
  199674. }
  199675. return rc;
  199676. }
  199677. /*
  199678. ** Advance the cursor to the next row in the table that matches the
  199679. ** search criteria.
  199680. **
  199681. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  199682. ** even if we reach end-of-file. The fts5EofMethod() will be called
  199683. ** subsequently to determine whether or not an EOF was hit.
  199684. */
  199685. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  199686. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  199687. int rc;
  199688. assert( (pCsr->ePlan<3)==
  199689. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  199690. );
  199691. assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
  199692. if( pCsr->ePlan<3 ){
  199693. int bSkip = 0;
  199694. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  199695. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  199696. CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
  199697. fts5CsrNewrow(pCsr);
  199698. }else{
  199699. switch( pCsr->ePlan ){
  199700. case FTS5_PLAN_SPECIAL: {
  199701. CsrFlagSet(pCsr, FTS5CSR_EOF);
  199702. rc = SQLITE_OK;
  199703. break;
  199704. }
  199705. case FTS5_PLAN_SORTED_MATCH: {
  199706. rc = fts5SorterNext(pCsr);
  199707. break;
  199708. }
  199709. default:
  199710. rc = sqlite3_step(pCsr->pStmt);
  199711. if( rc!=SQLITE_ROW ){
  199712. CsrFlagSet(pCsr, FTS5CSR_EOF);
  199713. rc = sqlite3_reset(pCsr->pStmt);
  199714. }else{
  199715. rc = SQLITE_OK;
  199716. }
  199717. break;
  199718. }
  199719. }
  199720. return rc;
  199721. }
  199722. static int fts5PrepareStatement(
  199723. sqlite3_stmt **ppStmt,
  199724. Fts5Config *pConfig,
  199725. const char *zFmt,
  199726. ...
  199727. ){
  199728. sqlite3_stmt *pRet = 0;
  199729. int rc;
  199730. char *zSql;
  199731. va_list ap;
  199732. va_start(ap, zFmt);
  199733. zSql = sqlite3_vmprintf(zFmt, ap);
  199734. if( zSql==0 ){
  199735. rc = SQLITE_NOMEM;
  199736. }else{
  199737. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  199738. SQLITE_PREPARE_PERSISTENT, &pRet, 0);
  199739. if( rc!=SQLITE_OK ){
  199740. *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
  199741. }
  199742. sqlite3_free(zSql);
  199743. }
  199744. va_end(ap);
  199745. *ppStmt = pRet;
  199746. return rc;
  199747. }
  199748. static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  199749. Fts5Config *pConfig = pTab->pConfig;
  199750. Fts5Sorter *pSorter;
  199751. int nPhrase;
  199752. int nByte;
  199753. int rc;
  199754. const char *zRank = pCsr->zRank;
  199755. const char *zRankArgs = pCsr->zRankArgs;
  199756. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  199757. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  199758. pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
  199759. if( pSorter==0 ) return SQLITE_NOMEM;
  199760. memset(pSorter, 0, nByte);
  199761. pSorter->nIdx = nPhrase;
  199762. /* TODO: It would be better to have some system for reusing statement
  199763. ** handles here, rather than preparing a new one for each query. But that
  199764. ** is not possible as SQLite reference counts the virtual table objects.
  199765. ** And since the statement required here reads from this very virtual
  199766. ** table, saving it creates a circular reference.
  199767. **
  199768. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  199769. rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
  199770. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
  199771. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  199772. (zRankArgs ? ", " : ""),
  199773. (zRankArgs ? zRankArgs : ""),
  199774. bDesc ? "DESC" : "ASC"
  199775. );
  199776. pCsr->pSorter = pSorter;
  199777. if( rc==SQLITE_OK ){
  199778. assert( pTab->pSortCsr==0 );
  199779. pTab->pSortCsr = pCsr;
  199780. rc = fts5SorterNext(pCsr);
  199781. pTab->pSortCsr = 0;
  199782. }
  199783. if( rc!=SQLITE_OK ){
  199784. sqlite3_finalize(pSorter->pStmt);
  199785. sqlite3_free(pSorter);
  199786. pCsr->pSorter = 0;
  199787. }
  199788. return rc;
  199789. }
  199790. static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  199791. int rc;
  199792. Fts5Expr *pExpr = pCsr->pExpr;
  199793. rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
  199794. if( sqlite3Fts5ExprEof(pExpr) ){
  199795. CsrFlagSet(pCsr, FTS5CSR_EOF);
  199796. }
  199797. fts5CsrNewrow(pCsr);
  199798. return rc;
  199799. }
  199800. /*
  199801. ** Process a "special" query. A special query is identified as one with a
  199802. ** MATCH expression that begins with a '*' character. The remainder of
  199803. ** the text passed to the MATCH operator are used as the special query
  199804. ** parameters.
  199805. */
  199806. static int fts5SpecialMatch(
  199807. Fts5Table *pTab,
  199808. Fts5Cursor *pCsr,
  199809. const char *zQuery
  199810. ){
  199811. int rc = SQLITE_OK; /* Return code */
  199812. const char *z = zQuery; /* Special query text */
  199813. int n; /* Number of bytes in text at z */
  199814. while( z[0]==' ' ) z++;
  199815. for(n=0; z[n] && z[n]!=' '; n++);
  199816. assert( pTab->base.zErrMsg==0 );
  199817. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  199818. if( 0==sqlite3_strnicmp("reads", z, n) ){
  199819. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
  199820. }
  199821. else if( 0==sqlite3_strnicmp("id", z, n) ){
  199822. pCsr->iSpecial = pCsr->iCsrId;
  199823. }
  199824. else{
  199825. /* An unrecognized directive. Return an error message. */
  199826. pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  199827. rc = SQLITE_ERROR;
  199828. }
  199829. return rc;
  199830. }
  199831. /*
  199832. ** Search for an auxiliary function named zName that can be used with table
  199833. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  199834. ** structure. Otherwise, if no such function exists, return NULL.
  199835. */
  199836. static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
  199837. Fts5Auxiliary *pAux;
  199838. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  199839. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  199840. }
  199841. /* No function of the specified name was found. Return 0. */
  199842. return 0;
  199843. }
  199844. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  199845. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  199846. Fts5Config *pConfig = pTab->pConfig;
  199847. int rc = SQLITE_OK;
  199848. Fts5Auxiliary *pAux = 0;
  199849. const char *zRank = pCsr->zRank;
  199850. const char *zRankArgs = pCsr->zRankArgs;
  199851. if( zRankArgs ){
  199852. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  199853. if( zSql ){
  199854. sqlite3_stmt *pStmt = 0;
  199855. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  199856. SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
  199857. sqlite3_free(zSql);
  199858. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  199859. if( rc==SQLITE_OK ){
  199860. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  199861. int nByte;
  199862. pCsr->nRankArg = sqlite3_column_count(pStmt);
  199863. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  199864. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  199865. if( rc==SQLITE_OK ){
  199866. int i;
  199867. for(i=0; i<pCsr->nRankArg; i++){
  199868. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  199869. }
  199870. }
  199871. pCsr->pRankArgStmt = pStmt;
  199872. }else{
  199873. rc = sqlite3_finalize(pStmt);
  199874. assert( rc!=SQLITE_OK );
  199875. }
  199876. }
  199877. }
  199878. }
  199879. if( rc==SQLITE_OK ){
  199880. pAux = fts5FindAuxiliary(pTab, zRank);
  199881. if( pAux==0 ){
  199882. assert( pTab->base.zErrMsg==0 );
  199883. pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  199884. rc = SQLITE_ERROR;
  199885. }
  199886. }
  199887. pCsr->pRank = pAux;
  199888. return rc;
  199889. }
  199890. static int fts5CursorParseRank(
  199891. Fts5Config *pConfig,
  199892. Fts5Cursor *pCsr,
  199893. sqlite3_value *pRank
  199894. ){
  199895. int rc = SQLITE_OK;
  199896. if( pRank ){
  199897. const char *z = (const char*)sqlite3_value_text(pRank);
  199898. char *zRank = 0;
  199899. char *zRankArgs = 0;
  199900. if( z==0 ){
  199901. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  199902. }else{
  199903. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  199904. }
  199905. if( rc==SQLITE_OK ){
  199906. pCsr->zRank = zRank;
  199907. pCsr->zRankArgs = zRankArgs;
  199908. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  199909. }else if( rc==SQLITE_ERROR ){
  199910. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  199911. "parse error in rank function: %s", z
  199912. );
  199913. }
  199914. }else{
  199915. if( pConfig->zRank ){
  199916. pCsr->zRank = (char*)pConfig->zRank;
  199917. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  199918. }else{
  199919. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  199920. pCsr->zRankArgs = 0;
  199921. }
  199922. }
  199923. return rc;
  199924. }
  199925. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  199926. if( pVal ){
  199927. int eType = sqlite3_value_numeric_type(pVal);
  199928. if( eType==SQLITE_INTEGER ){
  199929. return sqlite3_value_int64(pVal);
  199930. }
  199931. }
  199932. return iDefault;
  199933. }
  199934. /*
  199935. ** This is the xFilter interface for the virtual table. See
  199936. ** the virtual table xFilter method documentation for additional
  199937. ** information.
  199938. **
  199939. ** There are three possible query strategies:
  199940. **
  199941. ** 1. Full-text search using a MATCH operator.
  199942. ** 2. A by-rowid lookup.
  199943. ** 3. A full-table scan.
  199944. */
  199945. static int fts5FilterMethod(
  199946. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  199947. int idxNum, /* Strategy index */
  199948. const char *zUnused, /* Unused */
  199949. int nVal, /* Number of elements in apVal */
  199950. sqlite3_value **apVal /* Arguments for the indexing scheme */
  199951. ){
  199952. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  199953. Fts5Config *pConfig = pTab->pConfig;
  199954. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  199955. int rc = SQLITE_OK; /* Error code */
  199956. int iVal = 0; /* Counter for apVal[] */
  199957. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  199958. int bOrderByRank; /* True if ORDER BY rank */
  199959. sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
  199960. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  199961. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  199962. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  199963. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  199964. int iCol; /* Column on LHS of MATCH operator */
  199965. char **pzErrmsg = pConfig->pzErrmsg;
  199966. UNUSED_PARAM(zUnused);
  199967. UNUSED_PARAM(nVal);
  199968. if( pCsr->ePlan ){
  199969. fts5FreeCursorComponents(pCsr);
  199970. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  199971. }
  199972. assert( pCsr->pStmt==0 );
  199973. assert( pCsr->pExpr==0 );
  199974. assert( pCsr->csrflags==0 );
  199975. assert( pCsr->pRank==0 );
  199976. assert( pCsr->zRank==0 );
  199977. assert( pCsr->zRankArgs==0 );
  199978. assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
  199979. pConfig->pzErrmsg = &pTab->base.zErrMsg;
  199980. /* Decode the arguments passed through to this function.
  199981. **
  199982. ** Note: The following set of if(...) statements must be in the same
  199983. ** order as the corresponding entries in the struct at the top of
  199984. ** fts5BestIndexMethod(). */
  199985. if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
  199986. if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
  199987. if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
  199988. if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
  199989. if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
  199990. iCol = (idxNum>>16);
  199991. assert( iCol>=0 && iCol<=pConfig->nCol );
  199992. assert( iVal==nVal );
  199993. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  199994. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  199995. /* Set the cursor upper and lower rowid limits. Only some strategies
  199996. ** actually use them. This is ok, as the xBestIndex() method leaves the
  199997. ** sqlite3_index_constraint.omit flag clear for range constraints
  199998. ** on the rowid field. */
  199999. if( pRowidEq ){
  200000. pRowidLe = pRowidGe = pRowidEq;
  200001. }
  200002. if( bDesc ){
  200003. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  200004. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  200005. }else{
  200006. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  200007. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  200008. }
  200009. if( pTab->pSortCsr ){
  200010. /* If pSortCsr is non-NULL, then this call is being made as part of
  200011. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  200012. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  200013. ** return results to the user for this query. The current cursor
  200014. ** (pCursor) is used to execute the query issued by function
  200015. ** fts5CursorFirstSorted() above. */
  200016. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  200017. assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
  200018. assert( pCsr->iLastRowid==LARGEST_INT64 );
  200019. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  200020. if( pTab->pSortCsr->bDesc ){
  200021. pCsr->iLastRowid = pTab->pSortCsr->iFirstRowid;
  200022. pCsr->iFirstRowid = pTab->pSortCsr->iLastRowid;
  200023. }else{
  200024. pCsr->iLastRowid = pTab->pSortCsr->iLastRowid;
  200025. pCsr->iFirstRowid = pTab->pSortCsr->iFirstRowid;
  200026. }
  200027. pCsr->ePlan = FTS5_PLAN_SOURCE;
  200028. pCsr->pExpr = pTab->pSortCsr->pExpr;
  200029. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  200030. }else if( pMatch ){
  200031. const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
  200032. if( zExpr==0 ) zExpr = "";
  200033. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  200034. if( rc==SQLITE_OK ){
  200035. if( zExpr[0]=='*' ){
  200036. /* The user has issued a query of the form "MATCH '*...'". This
  200037. ** indicates that the MATCH expression is not a full text query,
  200038. ** but a request for an internal parameter. */
  200039. rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
  200040. }else{
  200041. char **pzErr = &pTab->base.zErrMsg;
  200042. rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
  200043. if( rc==SQLITE_OK ){
  200044. if( bOrderByRank ){
  200045. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  200046. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  200047. }else{
  200048. pCsr->ePlan = FTS5_PLAN_MATCH;
  200049. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  200050. }
  200051. }
  200052. }
  200053. }
  200054. }else if( pConfig->zContent==0 ){
  200055. *pConfig->pzErrmsg = sqlite3_mprintf(
  200056. "%s: table does not support scanning", pConfig->zName
  200057. );
  200058. rc = SQLITE_ERROR;
  200059. }else{
  200060. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  200061. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  200062. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  200063. rc = sqlite3Fts5StorageStmt(
  200064. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
  200065. );
  200066. if( rc==SQLITE_OK ){
  200067. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  200068. sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  200069. }else{
  200070. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  200071. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  200072. }
  200073. rc = fts5NextMethod(pCursor);
  200074. }
  200075. }
  200076. pConfig->pzErrmsg = pzErrmsg;
  200077. return rc;
  200078. }
  200079. /*
  200080. ** This is the xEof method of the virtual table. SQLite calls this
  200081. ** routine to find out if it has reached the end of a result set.
  200082. */
  200083. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  200084. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  200085. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  200086. }
  200087. /*
  200088. ** Return the rowid that the cursor currently points to.
  200089. */
  200090. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  200091. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  200092. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  200093. || pCsr->ePlan==FTS5_PLAN_SOURCE
  200094. );
  200095. if( pCsr->pSorter ){
  200096. return pCsr->pSorter->iRowid;
  200097. }else{
  200098. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  200099. }
  200100. }
  200101. /*
  200102. ** This is the xRowid method. The SQLite core calls this routine to
  200103. ** retrieve the rowid for the current row of the result set. fts5
  200104. ** exposes %_content.rowid as the rowid for the virtual table. The
  200105. ** rowid should be written to *pRowid.
  200106. */
  200107. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  200108. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  200109. int ePlan = pCsr->ePlan;
  200110. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  200111. switch( ePlan ){
  200112. case FTS5_PLAN_SPECIAL:
  200113. *pRowid = 0;
  200114. break;
  200115. case FTS5_PLAN_SOURCE:
  200116. case FTS5_PLAN_MATCH:
  200117. case FTS5_PLAN_SORTED_MATCH:
  200118. *pRowid = fts5CursorRowid(pCsr);
  200119. break;
  200120. default:
  200121. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  200122. break;
  200123. }
  200124. return SQLITE_OK;
  200125. }
  200126. /*
  200127. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  200128. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  200129. **
  200130. ** If argument bErrormsg is true and an error occurs, an error message may
  200131. ** be left in sqlite3_vtab.zErrMsg.
  200132. */
  200133. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  200134. int rc = SQLITE_OK;
  200135. /* If the cursor does not yet have a statement handle, obtain one now. */
  200136. if( pCsr->pStmt==0 ){
  200137. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  200138. int eStmt = fts5StmtType(pCsr);
  200139. rc = sqlite3Fts5StorageStmt(
  200140. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
  200141. );
  200142. assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
  200143. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  200144. }
  200145. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  200146. assert( pCsr->pExpr );
  200147. sqlite3_reset(pCsr->pStmt);
  200148. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  200149. rc = sqlite3_step(pCsr->pStmt);
  200150. if( rc==SQLITE_ROW ){
  200151. rc = SQLITE_OK;
  200152. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  200153. }else{
  200154. rc = sqlite3_reset(pCsr->pStmt);
  200155. if( rc==SQLITE_OK ){
  200156. rc = FTS5_CORRUPT;
  200157. }
  200158. }
  200159. }
  200160. return rc;
  200161. }
  200162. static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
  200163. va_list ap; /* ... printf arguments */
  200164. va_start(ap, zFormat);
  200165. assert( p->base.zErrMsg==0 );
  200166. p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  200167. va_end(ap);
  200168. }
  200169. /*
  200170. ** This function is called to handle an FTS INSERT command. In other words,
  200171. ** an INSERT statement of the form:
  200172. **
  200173. ** INSERT INTO fts(fts) VALUES($pCmd)
  200174. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  200175. **
  200176. ** Argument pVal is the value assigned to column "fts" by the INSERT
  200177. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  200178. ** error code if an error occurs.
  200179. **
  200180. ** The commands implemented by this function are documented in the "Special
  200181. ** INSERT Directives" section of the documentation. It should be updated if
  200182. ** more commands are added to this function.
  200183. */
  200184. static int fts5SpecialInsert(
  200185. Fts5Table *pTab, /* Fts5 table object */
  200186. const char *zCmd, /* Text inserted into table-name column */
  200187. sqlite3_value *pVal /* Value inserted into rank column */
  200188. ){
  200189. Fts5Config *pConfig = pTab->pConfig;
  200190. int rc = SQLITE_OK;
  200191. int bError = 0;
  200192. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  200193. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  200194. fts5SetVtabError(pTab,
  200195. "'delete-all' may only be used with a "
  200196. "contentless or external content fts5 table"
  200197. );
  200198. rc = SQLITE_ERROR;
  200199. }else{
  200200. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  200201. }
  200202. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  200203. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  200204. fts5SetVtabError(pTab,
  200205. "'rebuild' may not be used with a contentless fts5 table"
  200206. );
  200207. rc = SQLITE_ERROR;
  200208. }else{
  200209. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  200210. }
  200211. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  200212. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  200213. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  200214. int nMerge = sqlite3_value_int(pVal);
  200215. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  200216. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  200217. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  200218. #ifdef SQLITE_DEBUG
  200219. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  200220. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  200221. #endif
  200222. }else{
  200223. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  200224. if( rc==SQLITE_OK ){
  200225. rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
  200226. }
  200227. if( rc==SQLITE_OK ){
  200228. if( bError ){
  200229. rc = SQLITE_ERROR;
  200230. }else{
  200231. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  200232. }
  200233. }
  200234. }
  200235. return rc;
  200236. }
  200237. static int fts5SpecialDelete(
  200238. Fts5Table *pTab,
  200239. sqlite3_value **apVal
  200240. ){
  200241. int rc = SQLITE_OK;
  200242. int eType1 = sqlite3_value_type(apVal[1]);
  200243. if( eType1==SQLITE_INTEGER ){
  200244. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  200245. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
  200246. }
  200247. return rc;
  200248. }
  200249. static void fts5StorageInsert(
  200250. int *pRc,
  200251. Fts5Table *pTab,
  200252. sqlite3_value **apVal,
  200253. i64 *piRowid
  200254. ){
  200255. int rc = *pRc;
  200256. if( rc==SQLITE_OK ){
  200257. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  200258. }
  200259. if( rc==SQLITE_OK ){
  200260. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  200261. }
  200262. *pRc = rc;
  200263. }
  200264. /*
  200265. ** This function is the implementation of the xUpdate callback used by
  200266. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  200267. ** inserted, updated or deleted.
  200268. **
  200269. ** A delete specifies a single argument - the rowid of the row to remove.
  200270. **
  200271. ** Update and insert operations pass:
  200272. **
  200273. ** 1. The "old" rowid, or NULL.
  200274. ** 2. The "new" rowid.
  200275. ** 3. Values for each of the nCol matchable columns.
  200276. ** 4. Values for the two hidden columns (<tablename> and "rank").
  200277. */
  200278. static int fts5UpdateMethod(
  200279. sqlite3_vtab *pVtab, /* Virtual table handle */
  200280. int nArg, /* Size of argument array */
  200281. sqlite3_value **apVal, /* Array of arguments */
  200282. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  200283. ){
  200284. Fts5Table *pTab = (Fts5Table*)pVtab;
  200285. Fts5Config *pConfig = pTab->pConfig;
  200286. int eType0; /* value_type() of apVal[0] */
  200287. int rc = SQLITE_OK; /* Return code */
  200288. /* A transaction must be open when this is called. */
  200289. assert( pTab->ts.eState==1 );
  200290. assert( pVtab->zErrMsg==0 );
  200291. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  200292. assert( nArg==1
  200293. || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  200294. || sqlite3_value_type(apVal[1])==SQLITE_NULL
  200295. );
  200296. assert( pTab->pConfig->pzErrmsg==0 );
  200297. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  200298. /* Put any active cursors into REQUIRE_SEEK state. */
  200299. fts5TripCursors(pTab);
  200300. eType0 = sqlite3_value_type(apVal[0]);
  200301. if( eType0==SQLITE_NULL
  200302. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  200303. ){
  200304. /* A "special" INSERT op. These are handled separately. */
  200305. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  200306. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  200307. && 0==sqlite3_stricmp("delete", z)
  200308. ){
  200309. rc = fts5SpecialDelete(pTab, apVal);
  200310. }else{
  200311. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  200312. }
  200313. }else{
  200314. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  200315. ** any conflict on the rowid value must be detected before any
  200316. ** modifications are made to the database file. There are 4 cases:
  200317. **
  200318. ** 1) DELETE
  200319. ** 2) UPDATE (rowid not modified)
  200320. ** 3) UPDATE (rowid modified)
  200321. ** 4) INSERT
  200322. **
  200323. ** Cases 3 and 4 may violate the rowid constraint.
  200324. */
  200325. int eConflict = SQLITE_ABORT;
  200326. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  200327. eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  200328. }
  200329. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  200330. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  200331. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  200332. ** This is not suported. */
  200333. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  200334. pTab->base.zErrMsg = sqlite3_mprintf(
  200335. "cannot %s contentless fts5 table: %s",
  200336. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  200337. );
  200338. rc = SQLITE_ERROR;
  200339. }
  200340. /* DELETE */
  200341. else if( nArg==1 ){
  200342. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  200343. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
  200344. }
  200345. /* INSERT */
  200346. else if( eType0!=SQLITE_INTEGER ){
  200347. /* If this is a REPLACE, first remove the current entry (if any) */
  200348. if( eConflict==SQLITE_REPLACE
  200349. && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  200350. ){
  200351. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  200352. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  200353. }
  200354. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  200355. }
  200356. /* UPDATE */
  200357. else{
  200358. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  200359. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  200360. if( iOld!=iNew ){
  200361. if( eConflict==SQLITE_REPLACE ){
  200362. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  200363. if( rc==SQLITE_OK ){
  200364. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  200365. }
  200366. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  200367. }else{
  200368. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  200369. if( rc==SQLITE_OK ){
  200370. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  200371. }
  200372. if( rc==SQLITE_OK ){
  200373. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
  200374. }
  200375. }
  200376. }else{
  200377. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  200378. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  200379. }
  200380. }
  200381. }
  200382. pTab->pConfig->pzErrmsg = 0;
  200383. return rc;
  200384. }
  200385. /*
  200386. ** Implementation of xSync() method.
  200387. */
  200388. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  200389. int rc;
  200390. Fts5Table *pTab = (Fts5Table*)pVtab;
  200391. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  200392. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  200393. fts5TripCursors(pTab);
  200394. rc = sqlite3Fts5StorageSync(pTab->pStorage);
  200395. pTab->pConfig->pzErrmsg = 0;
  200396. return rc;
  200397. }
  200398. /*
  200399. ** Implementation of xBegin() method.
  200400. */
  200401. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  200402. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
  200403. fts5NewTransaction((Fts5Table*)pVtab);
  200404. return SQLITE_OK;
  200405. }
  200406. /*
  200407. ** Implementation of xCommit() method. This is a no-op. The contents of
  200408. ** the pending-terms hash-table have already been flushed into the database
  200409. ** by fts5SyncMethod().
  200410. */
  200411. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  200412. UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
  200413. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
  200414. return SQLITE_OK;
  200415. }
  200416. /*
  200417. ** Implementation of xRollback(). Discard the contents of the pending-terms
  200418. ** hash-table. Any changes made to the database are reverted by SQLite.
  200419. */
  200420. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  200421. int rc;
  200422. Fts5Table *pTab = (Fts5Table*)pVtab;
  200423. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  200424. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  200425. return rc;
  200426. }
  200427. static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
  200428. static void *fts5ApiUserData(Fts5Context *pCtx){
  200429. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200430. return pCsr->pAux->pUserData;
  200431. }
  200432. static int fts5ApiColumnCount(Fts5Context *pCtx){
  200433. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200434. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  200435. }
  200436. static int fts5ApiColumnTotalSize(
  200437. Fts5Context *pCtx,
  200438. int iCol,
  200439. sqlite3_int64 *pnToken
  200440. ){
  200441. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200442. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  200443. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  200444. }
  200445. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  200446. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200447. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  200448. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  200449. }
  200450. static int fts5ApiTokenize(
  200451. Fts5Context *pCtx,
  200452. const char *pText, int nText,
  200453. void *pUserData,
  200454. int (*xToken)(void*, int, const char*, int, int, int)
  200455. ){
  200456. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200457. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  200458. return sqlite3Fts5Tokenize(
  200459. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  200460. );
  200461. }
  200462. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  200463. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200464. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  200465. }
  200466. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  200467. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200468. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  200469. }
  200470. static int fts5ApiColumnText(
  200471. Fts5Context *pCtx,
  200472. int iCol,
  200473. const char **pz,
  200474. int *pn
  200475. ){
  200476. int rc = SQLITE_OK;
  200477. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200478. if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
  200479. *pz = 0;
  200480. *pn = 0;
  200481. }else{
  200482. rc = fts5SeekCursor(pCsr, 0);
  200483. if( rc==SQLITE_OK ){
  200484. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  200485. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  200486. }
  200487. }
  200488. return rc;
  200489. }
  200490. static int fts5CsrPoslist(
  200491. Fts5Cursor *pCsr,
  200492. int iPhrase,
  200493. const u8 **pa,
  200494. int *pn
  200495. ){
  200496. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  200497. int rc = SQLITE_OK;
  200498. int bLive = (pCsr->pSorter==0);
  200499. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
  200500. if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
  200501. Fts5PoslistPopulator *aPopulator;
  200502. int i;
  200503. aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
  200504. if( aPopulator==0 ) rc = SQLITE_NOMEM;
  200505. for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
  200506. int n; const char *z;
  200507. rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
  200508. if( rc==SQLITE_OK ){
  200509. rc = sqlite3Fts5ExprPopulatePoslists(
  200510. pConfig, pCsr->pExpr, aPopulator, i, z, n
  200511. );
  200512. }
  200513. }
  200514. sqlite3_free(aPopulator);
  200515. if( pCsr->pSorter ){
  200516. sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
  200517. }
  200518. }
  200519. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
  200520. }
  200521. if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
  200522. Fts5Sorter *pSorter = pCsr->pSorter;
  200523. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  200524. *pn = pSorter->aIdx[iPhrase] - i1;
  200525. *pa = &pSorter->aPoslist[i1];
  200526. }else{
  200527. *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  200528. }
  200529. return rc;
  200530. }
  200531. /*
  200532. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  200533. ** correctly for the current view. Return SQLITE_OK if successful, or an
  200534. ** SQLite error code otherwise.
  200535. */
  200536. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  200537. int rc = SQLITE_OK;
  200538. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  200539. int nIter; /* Number of iterators/phrases */
  200540. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  200541. if( pCsr->aInstIter==0 ){
  200542. int nByte = sizeof(Fts5PoslistReader) * nIter;
  200543. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  200544. }
  200545. aIter = pCsr->aInstIter;
  200546. if( aIter ){
  200547. int nInst = 0; /* Number instances seen so far */
  200548. int i;
  200549. /* Initialize all iterators */
  200550. for(i=0; i<nIter && rc==SQLITE_OK; i++){
  200551. const u8 *a;
  200552. int n;
  200553. rc = fts5CsrPoslist(pCsr, i, &a, &n);
  200554. if( rc==SQLITE_OK ){
  200555. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  200556. }
  200557. }
  200558. if( rc==SQLITE_OK ){
  200559. while( 1 ){
  200560. int *aInst;
  200561. int iBest = -1;
  200562. for(i=0; i<nIter; i++){
  200563. if( (aIter[i].bEof==0)
  200564. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  200565. ){
  200566. iBest = i;
  200567. }
  200568. }
  200569. if( iBest<0 ) break;
  200570. nInst++;
  200571. if( nInst>=pCsr->nInstAlloc ){
  200572. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  200573. aInst = (int*)sqlite3_realloc(
  200574. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  200575. );
  200576. if( aInst ){
  200577. pCsr->aInst = aInst;
  200578. }else{
  200579. rc = SQLITE_NOMEM;
  200580. break;
  200581. }
  200582. }
  200583. aInst = &pCsr->aInst[3 * (nInst-1)];
  200584. aInst[0] = iBest;
  200585. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  200586. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  200587. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  200588. }
  200589. }
  200590. pCsr->nInstCount = nInst;
  200591. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  200592. }
  200593. return rc;
  200594. }
  200595. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  200596. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200597. int rc = SQLITE_OK;
  200598. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  200599. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  200600. *pnInst = pCsr->nInstCount;
  200601. }
  200602. return rc;
  200603. }
  200604. static int fts5ApiInst(
  200605. Fts5Context *pCtx,
  200606. int iIdx,
  200607. int *piPhrase,
  200608. int *piCol,
  200609. int *piOff
  200610. ){
  200611. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200612. int rc = SQLITE_OK;
  200613. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  200614. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  200615. ){
  200616. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  200617. rc = SQLITE_RANGE;
  200618. #if 0
  200619. }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
  200620. *piPhrase = pCsr->aInst[iIdx*3];
  200621. *piCol = pCsr->aInst[iIdx*3 + 2];
  200622. *piOff = -1;
  200623. #endif
  200624. }else{
  200625. *piPhrase = pCsr->aInst[iIdx*3];
  200626. *piCol = pCsr->aInst[iIdx*3 + 1];
  200627. *piOff = pCsr->aInst[iIdx*3 + 2];
  200628. }
  200629. }
  200630. return rc;
  200631. }
  200632. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  200633. return fts5CursorRowid((Fts5Cursor*)pCtx);
  200634. }
  200635. static int fts5ColumnSizeCb(
  200636. void *pContext, /* Pointer to int */
  200637. int tflags,
  200638. const char *pUnused, /* Buffer containing token */
  200639. int nUnused, /* Size of token in bytes */
  200640. int iUnused1, /* Start offset of token */
  200641. int iUnused2 /* End offset of token */
  200642. ){
  200643. int *pCnt = (int*)pContext;
  200644. UNUSED_PARAM2(pUnused, nUnused);
  200645. UNUSED_PARAM2(iUnused1, iUnused2);
  200646. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  200647. (*pCnt)++;
  200648. }
  200649. return SQLITE_OK;
  200650. }
  200651. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  200652. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200653. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  200654. Fts5Config *pConfig = pTab->pConfig;
  200655. int rc = SQLITE_OK;
  200656. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  200657. if( pConfig->bColumnsize ){
  200658. i64 iRowid = fts5CursorRowid(pCsr);
  200659. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  200660. }else if( pConfig->zContent==0 ){
  200661. int i;
  200662. for(i=0; i<pConfig->nCol; i++){
  200663. if( pConfig->abUnindexed[i]==0 ){
  200664. pCsr->aColumnSize[i] = -1;
  200665. }
  200666. }
  200667. }else{
  200668. int i;
  200669. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  200670. if( pConfig->abUnindexed[i]==0 ){
  200671. const char *z; int n;
  200672. void *p = (void*)(&pCsr->aColumnSize[i]);
  200673. pCsr->aColumnSize[i] = 0;
  200674. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  200675. if( rc==SQLITE_OK ){
  200676. rc = sqlite3Fts5Tokenize(
  200677. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  200678. );
  200679. }
  200680. }
  200681. }
  200682. }
  200683. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  200684. }
  200685. if( iCol<0 ){
  200686. int i;
  200687. *pnToken = 0;
  200688. for(i=0; i<pConfig->nCol; i++){
  200689. *pnToken += pCsr->aColumnSize[i];
  200690. }
  200691. }else if( iCol<pConfig->nCol ){
  200692. *pnToken = pCsr->aColumnSize[iCol];
  200693. }else{
  200694. *pnToken = 0;
  200695. rc = SQLITE_RANGE;
  200696. }
  200697. return rc;
  200698. }
  200699. /*
  200700. ** Implementation of the xSetAuxdata() method.
  200701. */
  200702. static int fts5ApiSetAuxdata(
  200703. Fts5Context *pCtx, /* Fts5 context */
  200704. void *pPtr, /* Pointer to save as auxdata */
  200705. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  200706. ){
  200707. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200708. Fts5Auxdata *pData;
  200709. /* Search through the cursors list of Fts5Auxdata objects for one that
  200710. ** corresponds to the currently executing auxiliary function. */
  200711. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  200712. if( pData->pAux==pCsr->pAux ) break;
  200713. }
  200714. if( pData ){
  200715. if( pData->xDelete ){
  200716. pData->xDelete(pData->pPtr);
  200717. }
  200718. }else{
  200719. int rc = SQLITE_OK;
  200720. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  200721. if( pData==0 ){
  200722. if( xDelete ) xDelete(pPtr);
  200723. return rc;
  200724. }
  200725. pData->pAux = pCsr->pAux;
  200726. pData->pNext = pCsr->pAuxdata;
  200727. pCsr->pAuxdata = pData;
  200728. }
  200729. pData->xDelete = xDelete;
  200730. pData->pPtr = pPtr;
  200731. return SQLITE_OK;
  200732. }
  200733. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  200734. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200735. Fts5Auxdata *pData;
  200736. void *pRet = 0;
  200737. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  200738. if( pData->pAux==pCsr->pAux ) break;
  200739. }
  200740. if( pData ){
  200741. pRet = pData->pPtr;
  200742. if( bClear ){
  200743. pData->pPtr = 0;
  200744. pData->xDelete = 0;
  200745. }
  200746. }
  200747. return pRet;
  200748. }
  200749. static void fts5ApiPhraseNext(
  200750. Fts5Context *pUnused,
  200751. Fts5PhraseIter *pIter,
  200752. int *piCol, int *piOff
  200753. ){
  200754. UNUSED_PARAM(pUnused);
  200755. if( pIter->a>=pIter->b ){
  200756. *piCol = -1;
  200757. *piOff = -1;
  200758. }else{
  200759. int iVal;
  200760. pIter->a += fts5GetVarint32(pIter->a, iVal);
  200761. if( iVal==1 ){
  200762. pIter->a += fts5GetVarint32(pIter->a, iVal);
  200763. *piCol = iVal;
  200764. *piOff = 0;
  200765. pIter->a += fts5GetVarint32(pIter->a, iVal);
  200766. }
  200767. *piOff += (iVal-2);
  200768. }
  200769. }
  200770. static int fts5ApiPhraseFirst(
  200771. Fts5Context *pCtx,
  200772. int iPhrase,
  200773. Fts5PhraseIter *pIter,
  200774. int *piCol, int *piOff
  200775. ){
  200776. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200777. int n;
  200778. int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  200779. if( rc==SQLITE_OK ){
  200780. pIter->b = &pIter->a[n];
  200781. *piCol = 0;
  200782. *piOff = 0;
  200783. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  200784. }
  200785. return rc;
  200786. }
  200787. static void fts5ApiPhraseNextColumn(
  200788. Fts5Context *pCtx,
  200789. Fts5PhraseIter *pIter,
  200790. int *piCol
  200791. ){
  200792. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200793. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  200794. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  200795. if( pIter->a>=pIter->b ){
  200796. *piCol = -1;
  200797. }else{
  200798. int iIncr;
  200799. pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
  200800. *piCol += (iIncr-2);
  200801. }
  200802. }else{
  200803. while( 1 ){
  200804. int dummy;
  200805. if( pIter->a>=pIter->b ){
  200806. *piCol = -1;
  200807. return;
  200808. }
  200809. if( pIter->a[0]==0x01 ) break;
  200810. pIter->a += fts5GetVarint32(pIter->a, dummy);
  200811. }
  200812. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  200813. }
  200814. }
  200815. static int fts5ApiPhraseFirstColumn(
  200816. Fts5Context *pCtx,
  200817. int iPhrase,
  200818. Fts5PhraseIter *pIter,
  200819. int *piCol
  200820. ){
  200821. int rc = SQLITE_OK;
  200822. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200823. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  200824. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  200825. Fts5Sorter *pSorter = pCsr->pSorter;
  200826. int n;
  200827. if( pSorter ){
  200828. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  200829. n = pSorter->aIdx[iPhrase] - i1;
  200830. pIter->a = &pSorter->aPoslist[i1];
  200831. }else{
  200832. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
  200833. }
  200834. if( rc==SQLITE_OK ){
  200835. pIter->b = &pIter->a[n];
  200836. *piCol = 0;
  200837. fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
  200838. }
  200839. }else{
  200840. int n;
  200841. rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  200842. if( rc==SQLITE_OK ){
  200843. pIter->b = &pIter->a[n];
  200844. if( n<=0 ){
  200845. *piCol = -1;
  200846. }else if( pIter->a[0]==0x01 ){
  200847. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  200848. }else{
  200849. *piCol = 0;
  200850. }
  200851. }
  200852. }
  200853. return rc;
  200854. }
  200855. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  200856. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  200857. );
  200858. static const Fts5ExtensionApi sFts5Api = {
  200859. 2, /* iVersion */
  200860. fts5ApiUserData,
  200861. fts5ApiColumnCount,
  200862. fts5ApiRowCount,
  200863. fts5ApiColumnTotalSize,
  200864. fts5ApiTokenize,
  200865. fts5ApiPhraseCount,
  200866. fts5ApiPhraseSize,
  200867. fts5ApiInstCount,
  200868. fts5ApiInst,
  200869. fts5ApiRowid,
  200870. fts5ApiColumnText,
  200871. fts5ApiColumnSize,
  200872. fts5ApiQueryPhrase,
  200873. fts5ApiSetAuxdata,
  200874. fts5ApiGetAuxdata,
  200875. fts5ApiPhraseFirst,
  200876. fts5ApiPhraseNext,
  200877. fts5ApiPhraseFirstColumn,
  200878. fts5ApiPhraseNextColumn,
  200879. };
  200880. /*
  200881. ** Implementation of API function xQueryPhrase().
  200882. */
  200883. static int fts5ApiQueryPhrase(
  200884. Fts5Context *pCtx,
  200885. int iPhrase,
  200886. void *pUserData,
  200887. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  200888. ){
  200889. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  200890. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  200891. int rc;
  200892. Fts5Cursor *pNew = 0;
  200893. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  200894. if( rc==SQLITE_OK ){
  200895. pNew->ePlan = FTS5_PLAN_MATCH;
  200896. pNew->iFirstRowid = SMALLEST_INT64;
  200897. pNew->iLastRowid = LARGEST_INT64;
  200898. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  200899. rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
  200900. }
  200901. if( rc==SQLITE_OK ){
  200902. for(rc = fts5CursorFirst(pTab, pNew, 0);
  200903. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  200904. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  200905. ){
  200906. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  200907. if( rc!=SQLITE_OK ){
  200908. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  200909. break;
  200910. }
  200911. }
  200912. }
  200913. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  200914. return rc;
  200915. }
  200916. static void fts5ApiInvoke(
  200917. Fts5Auxiliary *pAux,
  200918. Fts5Cursor *pCsr,
  200919. sqlite3_context *context,
  200920. int argc,
  200921. sqlite3_value **argv
  200922. ){
  200923. assert( pCsr->pAux==0 );
  200924. pCsr->pAux = pAux;
  200925. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  200926. pCsr->pAux = 0;
  200927. }
  200928. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  200929. Fts5Cursor *pCsr;
  200930. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  200931. if( pCsr->iCsrId==iCsrId ) break;
  200932. }
  200933. return pCsr;
  200934. }
  200935. static void fts5ApiCallback(
  200936. sqlite3_context *context,
  200937. int argc,
  200938. sqlite3_value **argv
  200939. ){
  200940. Fts5Auxiliary *pAux;
  200941. Fts5Cursor *pCsr;
  200942. i64 iCsrId;
  200943. assert( argc>=1 );
  200944. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  200945. iCsrId = sqlite3_value_int64(argv[0]);
  200946. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  200947. if( pCsr==0 ){
  200948. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  200949. sqlite3_result_error(context, zErr, -1);
  200950. sqlite3_free(zErr);
  200951. }else{
  200952. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  200953. }
  200954. }
  200955. /*
  200956. ** Given cursor id iId, return a pointer to the corresponding Fts5Index
  200957. ** object. Or NULL If the cursor id does not exist.
  200958. **
  200959. ** If successful, set *ppConfig to point to the associated config object
  200960. ** before returning.
  200961. */
  200962. static Fts5Index *sqlite3Fts5IndexFromCsrid(
  200963. Fts5Global *pGlobal, /* FTS5 global context for db handle */
  200964. i64 iCsrId, /* Id of cursor to find */
  200965. Fts5Config **ppConfig /* OUT: Configuration object */
  200966. ){
  200967. Fts5Cursor *pCsr;
  200968. Fts5Table *pTab;
  200969. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  200970. pTab = (Fts5Table*)pCsr->base.pVtab;
  200971. *ppConfig = pTab->pConfig;
  200972. return pTab->pIndex;
  200973. }
  200974. /*
  200975. ** Return a "position-list blob" corresponding to the current position of
  200976. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  200977. ** the current position-list for each phrase in the query associated with
  200978. ** cursor pCsr.
  200979. **
  200980. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  200981. ** the number of phrases in the query. Following the varints are the
  200982. ** concatenated position lists for each phrase, in order.
  200983. **
  200984. ** The first varint (if it exists) contains the size of the position list
  200985. ** for phrase 0. The second (same disclaimer) contains the size of position
  200986. ** list 1. And so on. There is no size field for the final position list,
  200987. ** as it can be derived from the total size of the blob.
  200988. */
  200989. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  200990. int i;
  200991. int rc = SQLITE_OK;
  200992. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  200993. Fts5Buffer val;
  200994. memset(&val, 0, sizeof(Fts5Buffer));
  200995. switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
  200996. case FTS5_DETAIL_FULL:
  200997. /* Append the varints */
  200998. for(i=0; i<(nPhrase-1); i++){
  200999. const u8 *dummy;
  201000. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  201001. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  201002. }
  201003. /* Append the position lists */
  201004. for(i=0; i<nPhrase; i++){
  201005. const u8 *pPoslist;
  201006. int nPoslist;
  201007. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  201008. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  201009. }
  201010. break;
  201011. case FTS5_DETAIL_COLUMNS:
  201012. /* Append the varints */
  201013. for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
  201014. const u8 *dummy;
  201015. int nByte;
  201016. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
  201017. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  201018. }
  201019. /* Append the position lists */
  201020. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  201021. const u8 *pPoslist;
  201022. int nPoslist;
  201023. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
  201024. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  201025. }
  201026. break;
  201027. default:
  201028. break;
  201029. }
  201030. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  201031. return rc;
  201032. }
  201033. /*
  201034. ** This is the xColumn method, called by SQLite to request a value from
  201035. ** the row that the supplied cursor currently points to.
  201036. */
  201037. static int fts5ColumnMethod(
  201038. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  201039. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  201040. int iCol /* Index of column to read value from */
  201041. ){
  201042. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  201043. Fts5Config *pConfig = pTab->pConfig;
  201044. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  201045. int rc = SQLITE_OK;
  201046. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  201047. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  201048. if( iCol==pConfig->nCol ){
  201049. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  201050. }
  201051. }else
  201052. if( iCol==pConfig->nCol ){
  201053. /* User is requesting the value of the special column with the same name
  201054. ** as the table. Return the cursor integer id number. This value is only
  201055. ** useful in that it may be passed as the first argument to an FTS5
  201056. ** auxiliary function. */
  201057. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  201058. }else if( iCol==pConfig->nCol+1 ){
  201059. /* The value of the "rank" column. */
  201060. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  201061. fts5PoslistBlob(pCtx, pCsr);
  201062. }else if(
  201063. pCsr->ePlan==FTS5_PLAN_MATCH
  201064. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  201065. ){
  201066. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  201067. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  201068. }
  201069. }
  201070. }else if( !fts5IsContentless(pTab) ){
  201071. rc = fts5SeekCursor(pCsr, 1);
  201072. if( rc==SQLITE_OK ){
  201073. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  201074. }
  201075. }
  201076. return rc;
  201077. }
  201078. /*
  201079. ** This routine implements the xFindFunction method for the FTS3
  201080. ** virtual table.
  201081. */
  201082. static int fts5FindFunctionMethod(
  201083. sqlite3_vtab *pVtab, /* Virtual table handle */
  201084. int nUnused, /* Number of SQL function arguments */
  201085. const char *zName, /* Name of SQL function */
  201086. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  201087. void **ppArg /* OUT: User data for *pxFunc */
  201088. ){
  201089. Fts5Table *pTab = (Fts5Table*)pVtab;
  201090. Fts5Auxiliary *pAux;
  201091. UNUSED_PARAM(nUnused);
  201092. pAux = fts5FindAuxiliary(pTab, zName);
  201093. if( pAux ){
  201094. *pxFunc = fts5ApiCallback;
  201095. *ppArg = (void*)pAux;
  201096. return 1;
  201097. }
  201098. /* No function of the specified name was found. Return 0. */
  201099. return 0;
  201100. }
  201101. /*
  201102. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  201103. */
  201104. static int fts5RenameMethod(
  201105. sqlite3_vtab *pVtab, /* Virtual table handle */
  201106. const char *zName /* New name of table */
  201107. ){
  201108. Fts5Table *pTab = (Fts5Table*)pVtab;
  201109. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  201110. }
  201111. /*
  201112. ** The xSavepoint() method.
  201113. **
  201114. ** Flush the contents of the pending-terms table to disk.
  201115. */
  201116. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  201117. Fts5Table *pTab = (Fts5Table*)pVtab;
  201118. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  201119. fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
  201120. fts5TripCursors(pTab);
  201121. return sqlite3Fts5StorageSync(pTab->pStorage);
  201122. }
  201123. /*
  201124. ** The xRelease() method.
  201125. **
  201126. ** This is a no-op.
  201127. */
  201128. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  201129. Fts5Table *pTab = (Fts5Table*)pVtab;
  201130. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  201131. fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
  201132. fts5TripCursors(pTab);
  201133. return sqlite3Fts5StorageSync(pTab->pStorage);
  201134. }
  201135. /*
  201136. ** The xRollbackTo() method.
  201137. **
  201138. ** Discard the contents of the pending terms table.
  201139. */
  201140. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  201141. Fts5Table *pTab = (Fts5Table*)pVtab;
  201142. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  201143. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  201144. fts5TripCursors(pTab);
  201145. return sqlite3Fts5StorageRollback(pTab->pStorage);
  201146. }
  201147. /*
  201148. ** Register a new auxiliary function with global context pGlobal.
  201149. */
  201150. static int fts5CreateAux(
  201151. fts5_api *pApi, /* Global context (one per db handle) */
  201152. const char *zName, /* Name of new function */
  201153. void *pUserData, /* User data for aux. function */
  201154. fts5_extension_function xFunc, /* Aux. function implementation */
  201155. void(*xDestroy)(void*) /* Destructor for pUserData */
  201156. ){
  201157. Fts5Global *pGlobal = (Fts5Global*)pApi;
  201158. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  201159. if( rc==SQLITE_OK ){
  201160. Fts5Auxiliary *pAux;
  201161. int nName; /* Size of zName in bytes, including \0 */
  201162. int nByte; /* Bytes of space to allocate */
  201163. nName = (int)strlen(zName) + 1;
  201164. nByte = sizeof(Fts5Auxiliary) + nName;
  201165. pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
  201166. if( pAux ){
  201167. memset(pAux, 0, nByte);
  201168. pAux->zFunc = (char*)&pAux[1];
  201169. memcpy(pAux->zFunc, zName, nName);
  201170. pAux->pGlobal = pGlobal;
  201171. pAux->pUserData = pUserData;
  201172. pAux->xFunc = xFunc;
  201173. pAux->xDestroy = xDestroy;
  201174. pAux->pNext = pGlobal->pAux;
  201175. pGlobal->pAux = pAux;
  201176. }else{
  201177. rc = SQLITE_NOMEM;
  201178. }
  201179. }
  201180. return rc;
  201181. }
  201182. /*
  201183. ** Register a new tokenizer. This is the implementation of the
  201184. ** fts5_api.xCreateTokenizer() method.
  201185. */
  201186. static int fts5CreateTokenizer(
  201187. fts5_api *pApi, /* Global context (one per db handle) */
  201188. const char *zName, /* Name of new function */
  201189. void *pUserData, /* User data for aux. function */
  201190. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  201191. void(*xDestroy)(void*) /* Destructor for pUserData */
  201192. ){
  201193. Fts5Global *pGlobal = (Fts5Global*)pApi;
  201194. Fts5TokenizerModule *pNew;
  201195. int nName; /* Size of zName and its \0 terminator */
  201196. int nByte; /* Bytes of space to allocate */
  201197. int rc = SQLITE_OK;
  201198. nName = (int)strlen(zName) + 1;
  201199. nByte = sizeof(Fts5TokenizerModule) + nName;
  201200. pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
  201201. if( pNew ){
  201202. memset(pNew, 0, nByte);
  201203. pNew->zName = (char*)&pNew[1];
  201204. memcpy(pNew->zName, zName, nName);
  201205. pNew->pUserData = pUserData;
  201206. pNew->x = *pTokenizer;
  201207. pNew->xDestroy = xDestroy;
  201208. pNew->pNext = pGlobal->pTok;
  201209. pGlobal->pTok = pNew;
  201210. if( pNew->pNext==0 ){
  201211. pGlobal->pDfltTok = pNew;
  201212. }
  201213. }else{
  201214. rc = SQLITE_NOMEM;
  201215. }
  201216. return rc;
  201217. }
  201218. static Fts5TokenizerModule *fts5LocateTokenizer(
  201219. Fts5Global *pGlobal,
  201220. const char *zName
  201221. ){
  201222. Fts5TokenizerModule *pMod = 0;
  201223. if( zName==0 ){
  201224. pMod = pGlobal->pDfltTok;
  201225. }else{
  201226. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  201227. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  201228. }
  201229. }
  201230. return pMod;
  201231. }
  201232. /*
  201233. ** Find a tokenizer. This is the implementation of the
  201234. ** fts5_api.xFindTokenizer() method.
  201235. */
  201236. static int fts5FindTokenizer(
  201237. fts5_api *pApi, /* Global context (one per db handle) */
  201238. const char *zName, /* Name of new function */
  201239. void **ppUserData,
  201240. fts5_tokenizer *pTokenizer /* Populate this object */
  201241. ){
  201242. int rc = SQLITE_OK;
  201243. Fts5TokenizerModule *pMod;
  201244. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  201245. if( pMod ){
  201246. *pTokenizer = pMod->x;
  201247. *ppUserData = pMod->pUserData;
  201248. }else{
  201249. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  201250. rc = SQLITE_ERROR;
  201251. }
  201252. return rc;
  201253. }
  201254. static int sqlite3Fts5GetTokenizer(
  201255. Fts5Global *pGlobal,
  201256. const char **azArg,
  201257. int nArg,
  201258. Fts5Tokenizer **ppTok,
  201259. fts5_tokenizer **ppTokApi,
  201260. char **pzErr
  201261. ){
  201262. Fts5TokenizerModule *pMod;
  201263. int rc = SQLITE_OK;
  201264. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  201265. if( pMod==0 ){
  201266. assert( nArg>0 );
  201267. rc = SQLITE_ERROR;
  201268. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  201269. }else{
  201270. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  201271. *ppTokApi = &pMod->x;
  201272. if( rc!=SQLITE_OK && pzErr ){
  201273. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  201274. }
  201275. }
  201276. if( rc!=SQLITE_OK ){
  201277. *ppTokApi = 0;
  201278. *ppTok = 0;
  201279. }
  201280. return rc;
  201281. }
  201282. static void fts5ModuleDestroy(void *pCtx){
  201283. Fts5TokenizerModule *pTok, *pNextTok;
  201284. Fts5Auxiliary *pAux, *pNextAux;
  201285. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  201286. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  201287. pNextAux = pAux->pNext;
  201288. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  201289. sqlite3_free(pAux);
  201290. }
  201291. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  201292. pNextTok = pTok->pNext;
  201293. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  201294. sqlite3_free(pTok);
  201295. }
  201296. sqlite3_free(pGlobal);
  201297. }
  201298. static void fts5Fts5Func(
  201299. sqlite3_context *pCtx, /* Function call context */
  201300. int nArg, /* Number of args */
  201301. sqlite3_value **apArg /* Function arguments */
  201302. ){
  201303. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  201304. fts5_api **ppApi;
  201305. UNUSED_PARAM(nArg);
  201306. assert( nArg==1 );
  201307. ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
  201308. if( ppApi ) *ppApi = &pGlobal->api;
  201309. }
  201310. /*
  201311. ** Implementation of fts5_source_id() function.
  201312. */
  201313. static void fts5SourceIdFunc(
  201314. sqlite3_context *pCtx, /* Function call context */
  201315. int nArg, /* Number of args */
  201316. sqlite3_value **apUnused /* Function arguments */
  201317. ){
  201318. assert( nArg==0 );
  201319. UNUSED_PARAM2(nArg, apUnused);
  201320. sqlite3_result_text(pCtx, "fts5: 2018-12-01 12:34:55 bf8c1b2b7a5960c282e543b9c293686dccff272512d08865f4600fb58238b4f9", -1, SQLITE_TRANSIENT);
  201321. }
  201322. /*
  201323. ** Return true if zName is the extension on one of the shadow tables used
  201324. ** by this module.
  201325. */
  201326. static int fts5ShadowName(const char *zName){
  201327. static const char *azName[] = {
  201328. "config", "content", "data", "docsize", "idx"
  201329. };
  201330. unsigned int i;
  201331. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  201332. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  201333. }
  201334. return 0;
  201335. }
  201336. static int fts5Init(sqlite3 *db){
  201337. static const sqlite3_module fts5Mod = {
  201338. /* iVersion */ 3,
  201339. /* xCreate */ fts5CreateMethod,
  201340. /* xConnect */ fts5ConnectMethod,
  201341. /* xBestIndex */ fts5BestIndexMethod,
  201342. /* xDisconnect */ fts5DisconnectMethod,
  201343. /* xDestroy */ fts5DestroyMethod,
  201344. /* xOpen */ fts5OpenMethod,
  201345. /* xClose */ fts5CloseMethod,
  201346. /* xFilter */ fts5FilterMethod,
  201347. /* xNext */ fts5NextMethod,
  201348. /* xEof */ fts5EofMethod,
  201349. /* xColumn */ fts5ColumnMethod,
  201350. /* xRowid */ fts5RowidMethod,
  201351. /* xUpdate */ fts5UpdateMethod,
  201352. /* xBegin */ fts5BeginMethod,
  201353. /* xSync */ fts5SyncMethod,
  201354. /* xCommit */ fts5CommitMethod,
  201355. /* xRollback */ fts5RollbackMethod,
  201356. /* xFindFunction */ fts5FindFunctionMethod,
  201357. /* xRename */ fts5RenameMethod,
  201358. /* xSavepoint */ fts5SavepointMethod,
  201359. /* xRelease */ fts5ReleaseMethod,
  201360. /* xRollbackTo */ fts5RollbackToMethod,
  201361. /* xShadowName */ fts5ShadowName
  201362. };
  201363. int rc;
  201364. Fts5Global *pGlobal = 0;
  201365. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  201366. if( pGlobal==0 ){
  201367. rc = SQLITE_NOMEM;
  201368. }else{
  201369. void *p = (void*)pGlobal;
  201370. memset(pGlobal, 0, sizeof(Fts5Global));
  201371. pGlobal->db = db;
  201372. pGlobal->api.iVersion = 2;
  201373. pGlobal->api.xCreateFunction = fts5CreateAux;
  201374. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  201375. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  201376. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  201377. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  201378. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  201379. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  201380. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  201381. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  201382. if( rc==SQLITE_OK ){
  201383. rc = sqlite3_create_function(
  201384. db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  201385. );
  201386. }
  201387. if( rc==SQLITE_OK ){
  201388. rc = sqlite3_create_function(
  201389. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  201390. );
  201391. }
  201392. }
  201393. /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
  201394. ** fts5_test_mi.c is compiled and linked into the executable. And call
  201395. ** its entry point to enable the matchinfo() demo. */
  201396. #ifdef SQLITE_FTS5_ENABLE_TEST_MI
  201397. if( rc==SQLITE_OK ){
  201398. extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
  201399. rc = sqlite3Fts5TestRegisterMatchinfo(db);
  201400. }
  201401. #endif
  201402. return rc;
  201403. }
  201404. /*
  201405. ** The following functions are used to register the module with SQLite. If
  201406. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  201407. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  201408. **
  201409. ** Or, if this module is being built as a loadable extension,
  201410. ** sqlite3Fts5Init() is omitted and the two standard entry points
  201411. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  201412. */
  201413. #ifndef SQLITE_CORE
  201414. #ifdef _WIN32
  201415. __declspec(dllexport)
  201416. #endif
  201417. SQLITE_API int sqlite3_fts_init(
  201418. sqlite3 *db,
  201419. char **pzErrMsg,
  201420. const sqlite3_api_routines *pApi
  201421. ){
  201422. SQLITE_EXTENSION_INIT2(pApi);
  201423. (void)pzErrMsg; /* Unused parameter */
  201424. return fts5Init(db);
  201425. }
  201426. #ifdef _WIN32
  201427. __declspec(dllexport)
  201428. #endif
  201429. SQLITE_API int sqlite3_fts5_init(
  201430. sqlite3 *db,
  201431. char **pzErrMsg,
  201432. const sqlite3_api_routines *pApi
  201433. ){
  201434. SQLITE_EXTENSION_INIT2(pApi);
  201435. (void)pzErrMsg; /* Unused parameter */
  201436. return fts5Init(db);
  201437. }
  201438. #else
  201439. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  201440. return fts5Init(db);
  201441. }
  201442. #endif
  201443. /*
  201444. ** 2014 May 31
  201445. **
  201446. ** The author disclaims copyright to this source code. In place of
  201447. ** a legal notice, here is a blessing:
  201448. **
  201449. ** May you do good and not evil.
  201450. ** May you find forgiveness for yourself and forgive others.
  201451. ** May you share freely, never taking more than you give.
  201452. **
  201453. ******************************************************************************
  201454. **
  201455. */
  201456. /* #include "fts5Int.h" */
  201457. struct Fts5Storage {
  201458. Fts5Config *pConfig;
  201459. Fts5Index *pIndex;
  201460. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  201461. i64 nTotalRow; /* Total number of rows in FTS table */
  201462. i64 *aTotalSize; /* Total sizes of each column */
  201463. sqlite3_stmt *aStmt[11];
  201464. };
  201465. #if FTS5_STMT_SCAN_ASC!=0
  201466. # error "FTS5_STMT_SCAN_ASC mismatch"
  201467. #endif
  201468. #if FTS5_STMT_SCAN_DESC!=1
  201469. # error "FTS5_STMT_SCAN_DESC mismatch"
  201470. #endif
  201471. #if FTS5_STMT_LOOKUP!=2
  201472. # error "FTS5_STMT_LOOKUP mismatch"
  201473. #endif
  201474. #define FTS5_STMT_INSERT_CONTENT 3
  201475. #define FTS5_STMT_REPLACE_CONTENT 4
  201476. #define FTS5_STMT_DELETE_CONTENT 5
  201477. #define FTS5_STMT_REPLACE_DOCSIZE 6
  201478. #define FTS5_STMT_DELETE_DOCSIZE 7
  201479. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  201480. #define FTS5_STMT_REPLACE_CONFIG 9
  201481. #define FTS5_STMT_SCAN 10
  201482. /*
  201483. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  201484. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  201485. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  201486. ** occurs.
  201487. */
  201488. static int fts5StorageGetStmt(
  201489. Fts5Storage *p, /* Storage handle */
  201490. int eStmt, /* FTS5_STMT_XXX constant */
  201491. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  201492. char **pzErrMsg /* OUT: Error message (if any) */
  201493. ){
  201494. int rc = SQLITE_OK;
  201495. /* If there is no %_docsize table, there should be no requests for
  201496. ** statements to operate on it. */
  201497. assert( p->pConfig->bColumnsize || (
  201498. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  201499. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  201500. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  201501. ));
  201502. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  201503. if( p->aStmt[eStmt]==0 ){
  201504. const char *azStmt[] = {
  201505. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  201506. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  201507. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  201508. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  201509. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  201510. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  201511. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  201512. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  201513. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  201514. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  201515. "SELECT %s FROM %s AS T", /* SCAN */
  201516. };
  201517. Fts5Config *pC = p->pConfig;
  201518. char *zSql = 0;
  201519. switch( eStmt ){
  201520. case FTS5_STMT_SCAN:
  201521. zSql = sqlite3_mprintf(azStmt[eStmt],
  201522. pC->zContentExprlist, pC->zContent
  201523. );
  201524. break;
  201525. case FTS5_STMT_SCAN_ASC:
  201526. case FTS5_STMT_SCAN_DESC:
  201527. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  201528. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  201529. pC->zContentRowid
  201530. );
  201531. break;
  201532. case FTS5_STMT_LOOKUP:
  201533. zSql = sqlite3_mprintf(azStmt[eStmt],
  201534. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  201535. );
  201536. break;
  201537. case FTS5_STMT_INSERT_CONTENT:
  201538. case FTS5_STMT_REPLACE_CONTENT: {
  201539. int nCol = pC->nCol + 1;
  201540. char *zBind;
  201541. int i;
  201542. zBind = sqlite3_malloc(1 + nCol*2);
  201543. if( zBind ){
  201544. for(i=0; i<nCol; i++){
  201545. zBind[i*2] = '?';
  201546. zBind[i*2 + 1] = ',';
  201547. }
  201548. zBind[i*2-1] = '\0';
  201549. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  201550. sqlite3_free(zBind);
  201551. }
  201552. break;
  201553. }
  201554. default:
  201555. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  201556. break;
  201557. }
  201558. if( zSql==0 ){
  201559. rc = SQLITE_NOMEM;
  201560. }else{
  201561. rc = sqlite3_prepare_v3(pC->db, zSql, -1,
  201562. SQLITE_PREPARE_PERSISTENT, &p->aStmt[eStmt], 0);
  201563. sqlite3_free(zSql);
  201564. if( rc!=SQLITE_OK && pzErrMsg ){
  201565. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  201566. }
  201567. }
  201568. }
  201569. *ppStmt = p->aStmt[eStmt];
  201570. sqlite3_reset(*ppStmt);
  201571. return rc;
  201572. }
  201573. static int fts5ExecPrintf(
  201574. sqlite3 *db,
  201575. char **pzErr,
  201576. const char *zFormat,
  201577. ...
  201578. ){
  201579. int rc;
  201580. va_list ap; /* ... printf arguments */
  201581. char *zSql;
  201582. va_start(ap, zFormat);
  201583. zSql = sqlite3_vmprintf(zFormat, ap);
  201584. if( zSql==0 ){
  201585. rc = SQLITE_NOMEM;
  201586. }else{
  201587. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  201588. sqlite3_free(zSql);
  201589. }
  201590. va_end(ap);
  201591. return rc;
  201592. }
  201593. /*
  201594. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  201595. ** code otherwise.
  201596. */
  201597. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  201598. int rc = fts5ExecPrintf(pConfig->db, 0,
  201599. "DROP TABLE IF EXISTS %Q.'%q_data';"
  201600. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  201601. "DROP TABLE IF EXISTS %Q.'%q_config';",
  201602. pConfig->zDb, pConfig->zName,
  201603. pConfig->zDb, pConfig->zName,
  201604. pConfig->zDb, pConfig->zName
  201605. );
  201606. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  201607. rc = fts5ExecPrintf(pConfig->db, 0,
  201608. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  201609. pConfig->zDb, pConfig->zName
  201610. );
  201611. }
  201612. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  201613. rc = fts5ExecPrintf(pConfig->db, 0,
  201614. "DROP TABLE IF EXISTS %Q.'%q_content';",
  201615. pConfig->zDb, pConfig->zName
  201616. );
  201617. }
  201618. return rc;
  201619. }
  201620. static void fts5StorageRenameOne(
  201621. Fts5Config *pConfig, /* Current FTS5 configuration */
  201622. int *pRc, /* IN/OUT: Error code */
  201623. const char *zTail, /* Tail of table name e.g. "data", "config" */
  201624. const char *zName /* New name of FTS5 table */
  201625. ){
  201626. if( *pRc==SQLITE_OK ){
  201627. *pRc = fts5ExecPrintf(pConfig->db, 0,
  201628. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  201629. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  201630. );
  201631. }
  201632. }
  201633. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  201634. Fts5Config *pConfig = pStorage->pConfig;
  201635. int rc = sqlite3Fts5StorageSync(pStorage);
  201636. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  201637. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  201638. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  201639. if( pConfig->bColumnsize ){
  201640. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  201641. }
  201642. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  201643. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  201644. }
  201645. return rc;
  201646. }
  201647. /*
  201648. ** Create the shadow table named zPost, with definition zDefn. Return
  201649. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  201650. */
  201651. static int sqlite3Fts5CreateTable(
  201652. Fts5Config *pConfig, /* FTS5 configuration */
  201653. const char *zPost, /* Shadow table to create (e.g. "content") */
  201654. const char *zDefn, /* Columns etc. for shadow table */
  201655. int bWithout, /* True for without rowid */
  201656. char **pzErr /* OUT: Error message */
  201657. ){
  201658. int rc;
  201659. char *zErr = 0;
  201660. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  201661. pConfig->zDb, pConfig->zName, zPost, zDefn,
  201662. #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
  201663. bWithout?" WITHOUT ROWID":
  201664. #endif
  201665. ""
  201666. );
  201667. if( zErr ){
  201668. *pzErr = sqlite3_mprintf(
  201669. "fts5: error creating shadow table %q_%s: %s",
  201670. pConfig->zName, zPost, zErr
  201671. );
  201672. sqlite3_free(zErr);
  201673. }
  201674. return rc;
  201675. }
  201676. /*
  201677. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  201678. ** and initialize the underlying tables
  201679. **
  201680. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  201681. ** Otherwise, set *pp to NULL and return an SQLite error code.
  201682. */
  201683. static int sqlite3Fts5StorageOpen(
  201684. Fts5Config *pConfig,
  201685. Fts5Index *pIndex,
  201686. int bCreate,
  201687. Fts5Storage **pp,
  201688. char **pzErr /* OUT: Error message */
  201689. ){
  201690. int rc = SQLITE_OK;
  201691. Fts5Storage *p; /* New object */
  201692. int nByte; /* Bytes of space to allocate */
  201693. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  201694. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  201695. *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
  201696. if( !p ) return SQLITE_NOMEM;
  201697. memset(p, 0, nByte);
  201698. p->aTotalSize = (i64*)&p[1];
  201699. p->pConfig = pConfig;
  201700. p->pIndex = pIndex;
  201701. if( bCreate ){
  201702. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  201703. int nDefn = 32 + pConfig->nCol*10;
  201704. char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
  201705. if( zDefn==0 ){
  201706. rc = SQLITE_NOMEM;
  201707. }else{
  201708. int i;
  201709. int iOff;
  201710. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  201711. iOff = (int)strlen(zDefn);
  201712. for(i=0; i<pConfig->nCol; i++){
  201713. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  201714. iOff += (int)strlen(&zDefn[iOff]);
  201715. }
  201716. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  201717. }
  201718. sqlite3_free(zDefn);
  201719. }
  201720. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  201721. rc = sqlite3Fts5CreateTable(
  201722. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  201723. );
  201724. }
  201725. if( rc==SQLITE_OK ){
  201726. rc = sqlite3Fts5CreateTable(
  201727. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  201728. );
  201729. }
  201730. if( rc==SQLITE_OK ){
  201731. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  201732. }
  201733. }
  201734. if( rc ){
  201735. sqlite3Fts5StorageClose(p);
  201736. *pp = 0;
  201737. }
  201738. return rc;
  201739. }
  201740. /*
  201741. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  201742. */
  201743. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  201744. int rc = SQLITE_OK;
  201745. if( p ){
  201746. int i;
  201747. /* Finalize all SQL statements */
  201748. for(i=0; i<ArraySize(p->aStmt); i++){
  201749. sqlite3_finalize(p->aStmt[i]);
  201750. }
  201751. sqlite3_free(p);
  201752. }
  201753. return rc;
  201754. }
  201755. typedef struct Fts5InsertCtx Fts5InsertCtx;
  201756. struct Fts5InsertCtx {
  201757. Fts5Storage *pStorage;
  201758. int iCol;
  201759. int szCol; /* Size of column value in tokens */
  201760. };
  201761. /*
  201762. ** Tokenization callback used when inserting tokens into the FTS index.
  201763. */
  201764. static int fts5StorageInsertCallback(
  201765. void *pContext, /* Pointer to Fts5InsertCtx object */
  201766. int tflags,
  201767. const char *pToken, /* Buffer containing token */
  201768. int nToken, /* Size of token in bytes */
  201769. int iUnused1, /* Start offset of token */
  201770. int iUnused2 /* End offset of token */
  201771. ){
  201772. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  201773. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  201774. UNUSED_PARAM2(iUnused1, iUnused2);
  201775. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  201776. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  201777. pCtx->szCol++;
  201778. }
  201779. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  201780. }
  201781. /*
  201782. ** If a row with rowid iDel is present in the %_content table, add the
  201783. ** delete-markers to the FTS index necessary to delete it. Do not actually
  201784. ** remove the %_content row at this time though.
  201785. */
  201786. static int fts5StorageDeleteFromIndex(
  201787. Fts5Storage *p,
  201788. i64 iDel,
  201789. sqlite3_value **apVal
  201790. ){
  201791. Fts5Config *pConfig = p->pConfig;
  201792. sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
  201793. int rc; /* Return code */
  201794. int rc2; /* sqlite3_reset() return code */
  201795. int iCol;
  201796. Fts5InsertCtx ctx;
  201797. if( apVal==0 ){
  201798. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  201799. if( rc!=SQLITE_OK ) return rc;
  201800. sqlite3_bind_int64(pSeek, 1, iDel);
  201801. if( sqlite3_step(pSeek)!=SQLITE_ROW ){
  201802. return sqlite3_reset(pSeek);
  201803. }
  201804. }
  201805. ctx.pStorage = p;
  201806. ctx.iCol = -1;
  201807. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  201808. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  201809. if( pConfig->abUnindexed[iCol-1]==0 ){
  201810. const char *zText;
  201811. int nText;
  201812. if( pSeek ){
  201813. zText = (const char*)sqlite3_column_text(pSeek, iCol);
  201814. nText = sqlite3_column_bytes(pSeek, iCol);
  201815. }else{
  201816. zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
  201817. nText = sqlite3_value_bytes(apVal[iCol-1]);
  201818. }
  201819. ctx.szCol = 0;
  201820. rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
  201821. zText, nText, (void*)&ctx, fts5StorageInsertCallback
  201822. );
  201823. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  201824. }
  201825. }
  201826. p->nTotalRow--;
  201827. rc2 = sqlite3_reset(pSeek);
  201828. if( rc==SQLITE_OK ) rc = rc2;
  201829. return rc;
  201830. }
  201831. /*
  201832. ** Insert a record into the %_docsize table. Specifically, do:
  201833. **
  201834. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  201835. **
  201836. ** If there is no %_docsize table (as happens if the columnsize=0 option
  201837. ** is specified when the FTS5 table is created), this function is a no-op.
  201838. */
  201839. static int fts5StorageInsertDocsize(
  201840. Fts5Storage *p, /* Storage module to write to */
  201841. i64 iRowid, /* id value */
  201842. Fts5Buffer *pBuf /* sz value */
  201843. ){
  201844. int rc = SQLITE_OK;
  201845. if( p->pConfig->bColumnsize ){
  201846. sqlite3_stmt *pReplace = 0;
  201847. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  201848. if( rc==SQLITE_OK ){
  201849. sqlite3_bind_int64(pReplace, 1, iRowid);
  201850. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  201851. sqlite3_step(pReplace);
  201852. rc = sqlite3_reset(pReplace);
  201853. sqlite3_bind_null(pReplace, 2);
  201854. }
  201855. }
  201856. return rc;
  201857. }
  201858. /*
  201859. ** Load the contents of the "averages" record from disk into the
  201860. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  201861. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  201862. ** that the contents of aTotalSize[] and nTotalRow are valid until
  201863. ** further notice.
  201864. **
  201865. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  201866. ** occurs.
  201867. */
  201868. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  201869. int rc = SQLITE_OK;
  201870. if( p->bTotalsValid==0 ){
  201871. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  201872. p->bTotalsValid = bCache;
  201873. }
  201874. return rc;
  201875. }
  201876. /*
  201877. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  201878. ** variables in the "averages" record on disk.
  201879. **
  201880. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  201881. ** occurs.
  201882. */
  201883. static int fts5StorageSaveTotals(Fts5Storage *p){
  201884. int nCol = p->pConfig->nCol;
  201885. int i;
  201886. Fts5Buffer buf;
  201887. int rc = SQLITE_OK;
  201888. memset(&buf, 0, sizeof(buf));
  201889. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  201890. for(i=0; i<nCol; i++){
  201891. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  201892. }
  201893. if( rc==SQLITE_OK ){
  201894. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  201895. }
  201896. sqlite3_free(buf.p);
  201897. return rc;
  201898. }
  201899. /*
  201900. ** Remove a row from the FTS table.
  201901. */
  201902. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
  201903. Fts5Config *pConfig = p->pConfig;
  201904. int rc;
  201905. sqlite3_stmt *pDel = 0;
  201906. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
  201907. rc = fts5StorageLoadTotals(p, 1);
  201908. /* Delete the index records */
  201909. if( rc==SQLITE_OK ){
  201910. rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
  201911. }
  201912. /* Delete the %_docsize record */
  201913. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  201914. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  201915. if( rc==SQLITE_OK ){
  201916. sqlite3_bind_int64(pDel, 1, iDel);
  201917. sqlite3_step(pDel);
  201918. rc = sqlite3_reset(pDel);
  201919. }
  201920. }
  201921. /* Delete the %_content record */
  201922. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  201923. if( rc==SQLITE_OK ){
  201924. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  201925. }
  201926. if( rc==SQLITE_OK ){
  201927. sqlite3_bind_int64(pDel, 1, iDel);
  201928. sqlite3_step(pDel);
  201929. rc = sqlite3_reset(pDel);
  201930. }
  201931. }
  201932. return rc;
  201933. }
  201934. /*
  201935. ** Delete all entries in the FTS5 index.
  201936. */
  201937. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  201938. Fts5Config *pConfig = p->pConfig;
  201939. int rc;
  201940. /* Delete the contents of the %_data and %_docsize tables. */
  201941. rc = fts5ExecPrintf(pConfig->db, 0,
  201942. "DELETE FROM %Q.'%q_data';"
  201943. "DELETE FROM %Q.'%q_idx';",
  201944. pConfig->zDb, pConfig->zName,
  201945. pConfig->zDb, pConfig->zName
  201946. );
  201947. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  201948. rc = fts5ExecPrintf(pConfig->db, 0,
  201949. "DELETE FROM %Q.'%q_docsize';",
  201950. pConfig->zDb, pConfig->zName
  201951. );
  201952. }
  201953. /* Reinitialize the %_data table. This call creates the initial structure
  201954. ** and averages records. */
  201955. if( rc==SQLITE_OK ){
  201956. rc = sqlite3Fts5IndexReinit(p->pIndex);
  201957. }
  201958. if( rc==SQLITE_OK ){
  201959. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  201960. }
  201961. return rc;
  201962. }
  201963. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  201964. Fts5Buffer buf = {0,0,0};
  201965. Fts5Config *pConfig = p->pConfig;
  201966. sqlite3_stmt *pScan = 0;
  201967. Fts5InsertCtx ctx;
  201968. int rc;
  201969. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  201970. ctx.pStorage = p;
  201971. rc = sqlite3Fts5StorageDeleteAll(p);
  201972. if( rc==SQLITE_OK ){
  201973. rc = fts5StorageLoadTotals(p, 1);
  201974. }
  201975. if( rc==SQLITE_OK ){
  201976. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  201977. }
  201978. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  201979. i64 iRowid = sqlite3_column_int64(pScan, 0);
  201980. sqlite3Fts5BufferZero(&buf);
  201981. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  201982. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  201983. ctx.szCol = 0;
  201984. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  201985. rc = sqlite3Fts5Tokenize(pConfig,
  201986. FTS5_TOKENIZE_DOCUMENT,
  201987. (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
  201988. sqlite3_column_bytes(pScan, ctx.iCol+1),
  201989. (void*)&ctx,
  201990. fts5StorageInsertCallback
  201991. );
  201992. }
  201993. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  201994. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  201995. }
  201996. p->nTotalRow++;
  201997. if( rc==SQLITE_OK ){
  201998. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  201999. }
  202000. }
  202001. sqlite3_free(buf.p);
  202002. /* Write the averages record */
  202003. if( rc==SQLITE_OK ){
  202004. rc = fts5StorageSaveTotals(p);
  202005. }
  202006. return rc;
  202007. }
  202008. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  202009. return sqlite3Fts5IndexOptimize(p->pIndex);
  202010. }
  202011. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  202012. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  202013. }
  202014. static int sqlite3Fts5StorageReset(Fts5Storage *p){
  202015. return sqlite3Fts5IndexReset(p->pIndex);
  202016. }
  202017. /*
  202018. ** Allocate a new rowid. This is used for "external content" tables when
  202019. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  202020. ** by inserting a dummy row into the %_docsize table. The dummy will be
  202021. ** overwritten later.
  202022. **
  202023. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  202024. ** this case the user is required to provide a rowid explicitly.
  202025. */
  202026. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  202027. int rc = SQLITE_MISMATCH;
  202028. if( p->pConfig->bColumnsize ){
  202029. sqlite3_stmt *pReplace = 0;
  202030. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  202031. if( rc==SQLITE_OK ){
  202032. sqlite3_bind_null(pReplace, 1);
  202033. sqlite3_bind_null(pReplace, 2);
  202034. sqlite3_step(pReplace);
  202035. rc = sqlite3_reset(pReplace);
  202036. }
  202037. if( rc==SQLITE_OK ){
  202038. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  202039. }
  202040. }
  202041. return rc;
  202042. }
  202043. /*
  202044. ** Insert a new row into the FTS content table.
  202045. */
  202046. static int sqlite3Fts5StorageContentInsert(
  202047. Fts5Storage *p,
  202048. sqlite3_value **apVal,
  202049. i64 *piRowid
  202050. ){
  202051. Fts5Config *pConfig = p->pConfig;
  202052. int rc = SQLITE_OK;
  202053. /* Insert the new row into the %_content table. */
  202054. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  202055. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  202056. *piRowid = sqlite3_value_int64(apVal[1]);
  202057. }else{
  202058. rc = fts5StorageNewRowid(p, piRowid);
  202059. }
  202060. }else{
  202061. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  202062. int i; /* Counter variable */
  202063. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  202064. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  202065. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  202066. }
  202067. if( rc==SQLITE_OK ){
  202068. sqlite3_step(pInsert);
  202069. rc = sqlite3_reset(pInsert);
  202070. }
  202071. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  202072. }
  202073. return rc;
  202074. }
  202075. /*
  202076. ** Insert new entries into the FTS index and %_docsize table.
  202077. */
  202078. static int sqlite3Fts5StorageIndexInsert(
  202079. Fts5Storage *p,
  202080. sqlite3_value **apVal,
  202081. i64 iRowid
  202082. ){
  202083. Fts5Config *pConfig = p->pConfig;
  202084. int rc = SQLITE_OK; /* Return code */
  202085. Fts5InsertCtx ctx; /* Tokenization callback context object */
  202086. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  202087. memset(&buf, 0, sizeof(Fts5Buffer));
  202088. ctx.pStorage = p;
  202089. rc = fts5StorageLoadTotals(p, 1);
  202090. if( rc==SQLITE_OK ){
  202091. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  202092. }
  202093. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  202094. ctx.szCol = 0;
  202095. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  202096. rc = sqlite3Fts5Tokenize(pConfig,
  202097. FTS5_TOKENIZE_DOCUMENT,
  202098. (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
  202099. sqlite3_value_bytes(apVal[ctx.iCol+2]),
  202100. (void*)&ctx,
  202101. fts5StorageInsertCallback
  202102. );
  202103. }
  202104. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  202105. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  202106. }
  202107. p->nTotalRow++;
  202108. /* Write the %_docsize record */
  202109. if( rc==SQLITE_OK ){
  202110. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  202111. }
  202112. sqlite3_free(buf.p);
  202113. return rc;
  202114. }
  202115. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  202116. Fts5Config *pConfig = p->pConfig;
  202117. char *zSql;
  202118. int rc;
  202119. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  202120. pConfig->zDb, pConfig->zName, zSuffix
  202121. );
  202122. if( zSql==0 ){
  202123. rc = SQLITE_NOMEM;
  202124. }else{
  202125. sqlite3_stmt *pCnt = 0;
  202126. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  202127. if( rc==SQLITE_OK ){
  202128. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  202129. *pnRow = sqlite3_column_int64(pCnt, 0);
  202130. }
  202131. rc = sqlite3_finalize(pCnt);
  202132. }
  202133. }
  202134. sqlite3_free(zSql);
  202135. return rc;
  202136. }
  202137. /*
  202138. ** Context object used by sqlite3Fts5StorageIntegrity().
  202139. */
  202140. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  202141. struct Fts5IntegrityCtx {
  202142. i64 iRowid;
  202143. int iCol;
  202144. int szCol;
  202145. u64 cksum;
  202146. Fts5Termset *pTermset;
  202147. Fts5Config *pConfig;
  202148. };
  202149. /*
  202150. ** Tokenization callback used by integrity check.
  202151. */
  202152. static int fts5StorageIntegrityCallback(
  202153. void *pContext, /* Pointer to Fts5IntegrityCtx object */
  202154. int tflags,
  202155. const char *pToken, /* Buffer containing token */
  202156. int nToken, /* Size of token in bytes */
  202157. int iUnused1, /* Start offset of token */
  202158. int iUnused2 /* End offset of token */
  202159. ){
  202160. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  202161. Fts5Termset *pTermset = pCtx->pTermset;
  202162. int bPresent;
  202163. int ii;
  202164. int rc = SQLITE_OK;
  202165. int iPos;
  202166. int iCol;
  202167. UNUSED_PARAM2(iUnused1, iUnused2);
  202168. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  202169. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  202170. pCtx->szCol++;
  202171. }
  202172. switch( pCtx->pConfig->eDetail ){
  202173. case FTS5_DETAIL_FULL:
  202174. iPos = pCtx->szCol-1;
  202175. iCol = pCtx->iCol;
  202176. break;
  202177. case FTS5_DETAIL_COLUMNS:
  202178. iPos = pCtx->iCol;
  202179. iCol = 0;
  202180. break;
  202181. default:
  202182. assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
  202183. iPos = 0;
  202184. iCol = 0;
  202185. break;
  202186. }
  202187. rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
  202188. if( rc==SQLITE_OK && bPresent==0 ){
  202189. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  202190. pCtx->iRowid, iCol, iPos, 0, pToken, nToken
  202191. );
  202192. }
  202193. for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
  202194. const int nChar = pCtx->pConfig->aPrefix[ii];
  202195. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  202196. if( nByte ){
  202197. rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
  202198. if( bPresent==0 ){
  202199. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  202200. pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
  202201. );
  202202. }
  202203. }
  202204. }
  202205. return rc;
  202206. }
  202207. /*
  202208. ** Check that the contents of the FTS index match that of the %_content
  202209. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  202210. ** some other SQLite error code if an error occurs while attempting to
  202211. ** determine this.
  202212. */
  202213. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  202214. Fts5Config *pConfig = p->pConfig;
  202215. int rc; /* Return code */
  202216. int *aColSize; /* Array of size pConfig->nCol */
  202217. i64 *aTotalSize; /* Array of size pConfig->nCol */
  202218. Fts5IntegrityCtx ctx;
  202219. sqlite3_stmt *pScan;
  202220. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  202221. ctx.pConfig = p->pConfig;
  202222. aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
  202223. if( !aTotalSize ) return SQLITE_NOMEM;
  202224. aColSize = (int*)&aTotalSize[pConfig->nCol];
  202225. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  202226. /* Generate the expected index checksum based on the contents of the
  202227. ** %_content table. This block stores the checksum in ctx.cksum. */
  202228. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  202229. if( rc==SQLITE_OK ){
  202230. int rc2;
  202231. while( SQLITE_ROW==sqlite3_step(pScan) ){
  202232. int i;
  202233. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  202234. ctx.szCol = 0;
  202235. if( pConfig->bColumnsize ){
  202236. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  202237. }
  202238. if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
  202239. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  202240. }
  202241. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  202242. if( pConfig->abUnindexed[i] ) continue;
  202243. ctx.iCol = i;
  202244. ctx.szCol = 0;
  202245. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  202246. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  202247. }
  202248. if( rc==SQLITE_OK ){
  202249. rc = sqlite3Fts5Tokenize(pConfig,
  202250. FTS5_TOKENIZE_DOCUMENT,
  202251. (const char*)sqlite3_column_text(pScan, i+1),
  202252. sqlite3_column_bytes(pScan, i+1),
  202253. (void*)&ctx,
  202254. fts5StorageIntegrityCallback
  202255. );
  202256. }
  202257. if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  202258. rc = FTS5_CORRUPT;
  202259. }
  202260. aTotalSize[i] += ctx.szCol;
  202261. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  202262. sqlite3Fts5TermsetFree(ctx.pTermset);
  202263. ctx.pTermset = 0;
  202264. }
  202265. }
  202266. sqlite3Fts5TermsetFree(ctx.pTermset);
  202267. ctx.pTermset = 0;
  202268. if( rc!=SQLITE_OK ) break;
  202269. }
  202270. rc2 = sqlite3_reset(pScan);
  202271. if( rc==SQLITE_OK ) rc = rc2;
  202272. }
  202273. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  202274. if( rc==SQLITE_OK ){
  202275. int i;
  202276. rc = fts5StorageLoadTotals(p, 0);
  202277. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  202278. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  202279. }
  202280. }
  202281. /* Check that the %_docsize and %_content tables contain the expected
  202282. ** number of rows. */
  202283. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  202284. i64 nRow = 0;
  202285. rc = fts5StorageCount(p, "content", &nRow);
  202286. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  202287. }
  202288. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  202289. i64 nRow = 0;
  202290. rc = fts5StorageCount(p, "docsize", &nRow);
  202291. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  202292. }
  202293. /* Pass the expected checksum down to the FTS index module. It will
  202294. ** verify, amongst other things, that it matches the checksum generated by
  202295. ** inspecting the index itself. */
  202296. if( rc==SQLITE_OK ){
  202297. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  202298. }
  202299. sqlite3_free(aTotalSize);
  202300. return rc;
  202301. }
  202302. /*
  202303. ** Obtain an SQLite statement handle that may be used to read data from the
  202304. ** %_content table.
  202305. */
  202306. static int sqlite3Fts5StorageStmt(
  202307. Fts5Storage *p,
  202308. int eStmt,
  202309. sqlite3_stmt **pp,
  202310. char **pzErrMsg
  202311. ){
  202312. int rc;
  202313. assert( eStmt==FTS5_STMT_SCAN_ASC
  202314. || eStmt==FTS5_STMT_SCAN_DESC
  202315. || eStmt==FTS5_STMT_LOOKUP
  202316. );
  202317. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  202318. if( rc==SQLITE_OK ){
  202319. assert( p->aStmt[eStmt]==*pp );
  202320. p->aStmt[eStmt] = 0;
  202321. }
  202322. return rc;
  202323. }
  202324. /*
  202325. ** Release an SQLite statement handle obtained via an earlier call to
  202326. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  202327. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  202328. */
  202329. static void sqlite3Fts5StorageStmtRelease(
  202330. Fts5Storage *p,
  202331. int eStmt,
  202332. sqlite3_stmt *pStmt
  202333. ){
  202334. assert( eStmt==FTS5_STMT_SCAN_ASC
  202335. || eStmt==FTS5_STMT_SCAN_DESC
  202336. || eStmt==FTS5_STMT_LOOKUP
  202337. );
  202338. if( p->aStmt[eStmt]==0 ){
  202339. sqlite3_reset(pStmt);
  202340. p->aStmt[eStmt] = pStmt;
  202341. }else{
  202342. sqlite3_finalize(pStmt);
  202343. }
  202344. }
  202345. static int fts5StorageDecodeSizeArray(
  202346. int *aCol, int nCol, /* Array to populate */
  202347. const u8 *aBlob, int nBlob /* Record to read varints from */
  202348. ){
  202349. int i;
  202350. int iOff = 0;
  202351. for(i=0; i<nCol; i++){
  202352. if( iOff>=nBlob ) return 1;
  202353. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  202354. }
  202355. return (iOff!=nBlob);
  202356. }
  202357. /*
  202358. ** Argument aCol points to an array of integers containing one entry for
  202359. ** each table column. This function reads the %_docsize record for the
  202360. ** specified rowid and populates aCol[] with the results.
  202361. **
  202362. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  202363. ** otherwise.
  202364. */
  202365. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  202366. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  202367. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  202368. int rc; /* Return Code */
  202369. assert( p->pConfig->bColumnsize );
  202370. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  202371. if( rc==SQLITE_OK ){
  202372. int bCorrupt = 1;
  202373. sqlite3_bind_int64(pLookup, 1, iRowid);
  202374. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  202375. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  202376. int nBlob = sqlite3_column_bytes(pLookup, 0);
  202377. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  202378. bCorrupt = 0;
  202379. }
  202380. }
  202381. rc = sqlite3_reset(pLookup);
  202382. if( bCorrupt && rc==SQLITE_OK ){
  202383. rc = FTS5_CORRUPT;
  202384. }
  202385. }
  202386. return rc;
  202387. }
  202388. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  202389. int rc = fts5StorageLoadTotals(p, 0);
  202390. if( rc==SQLITE_OK ){
  202391. *pnToken = 0;
  202392. if( iCol<0 ){
  202393. int i;
  202394. for(i=0; i<p->pConfig->nCol; i++){
  202395. *pnToken += p->aTotalSize[i];
  202396. }
  202397. }else if( iCol<p->pConfig->nCol ){
  202398. *pnToken = p->aTotalSize[iCol];
  202399. }else{
  202400. rc = SQLITE_RANGE;
  202401. }
  202402. }
  202403. return rc;
  202404. }
  202405. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  202406. int rc = fts5StorageLoadTotals(p, 0);
  202407. if( rc==SQLITE_OK ){
  202408. *pnRow = p->nTotalRow;
  202409. }
  202410. return rc;
  202411. }
  202412. /*
  202413. ** Flush any data currently held in-memory to disk.
  202414. */
  202415. static int sqlite3Fts5StorageSync(Fts5Storage *p){
  202416. int rc = SQLITE_OK;
  202417. i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  202418. if( p->bTotalsValid ){
  202419. rc = fts5StorageSaveTotals(p);
  202420. p->bTotalsValid = 0;
  202421. }
  202422. if( rc==SQLITE_OK ){
  202423. rc = sqlite3Fts5IndexSync(p->pIndex);
  202424. }
  202425. sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
  202426. return rc;
  202427. }
  202428. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  202429. p->bTotalsValid = 0;
  202430. return sqlite3Fts5IndexRollback(p->pIndex);
  202431. }
  202432. static int sqlite3Fts5StorageConfigValue(
  202433. Fts5Storage *p,
  202434. const char *z,
  202435. sqlite3_value *pVal,
  202436. int iVal
  202437. ){
  202438. sqlite3_stmt *pReplace = 0;
  202439. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  202440. if( rc==SQLITE_OK ){
  202441. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  202442. if( pVal ){
  202443. sqlite3_bind_value(pReplace, 2, pVal);
  202444. }else{
  202445. sqlite3_bind_int(pReplace, 2, iVal);
  202446. }
  202447. sqlite3_step(pReplace);
  202448. rc = sqlite3_reset(pReplace);
  202449. sqlite3_bind_null(pReplace, 1);
  202450. }
  202451. if( rc==SQLITE_OK && pVal ){
  202452. int iNew = p->pConfig->iCookie + 1;
  202453. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  202454. if( rc==SQLITE_OK ){
  202455. p->pConfig->iCookie = iNew;
  202456. }
  202457. }
  202458. return rc;
  202459. }
  202460. /*
  202461. ** 2014 May 31
  202462. **
  202463. ** The author disclaims copyright to this source code. In place of
  202464. ** a legal notice, here is a blessing:
  202465. **
  202466. ** May you do good and not evil.
  202467. ** May you find forgiveness for yourself and forgive others.
  202468. ** May you share freely, never taking more than you give.
  202469. **
  202470. ******************************************************************************
  202471. */
  202472. /* #include "fts5Int.h" */
  202473. /**************************************************************************
  202474. ** Start of ascii tokenizer implementation.
  202475. */
  202476. /*
  202477. ** For tokenizers with no "unicode" modifier, the set of token characters
  202478. ** is the same as the set of ASCII range alphanumeric characters.
  202479. */
  202480. static unsigned char aAsciiTokenChar[128] = {
  202481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  202482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  202483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  202484. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  202485. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  202486. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  202487. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  202488. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  202489. };
  202490. typedef struct AsciiTokenizer AsciiTokenizer;
  202491. struct AsciiTokenizer {
  202492. unsigned char aTokenChar[128];
  202493. };
  202494. static void fts5AsciiAddExceptions(
  202495. AsciiTokenizer *p,
  202496. const char *zArg,
  202497. int bTokenChars
  202498. ){
  202499. int i;
  202500. for(i=0; zArg[i]; i++){
  202501. if( (zArg[i] & 0x80)==0 ){
  202502. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  202503. }
  202504. }
  202505. }
  202506. /*
  202507. ** Delete a "ascii" tokenizer.
  202508. */
  202509. static void fts5AsciiDelete(Fts5Tokenizer *p){
  202510. sqlite3_free(p);
  202511. }
  202512. /*
  202513. ** Create an "ascii" tokenizer.
  202514. */
  202515. static int fts5AsciiCreate(
  202516. void *pUnused,
  202517. const char **azArg, int nArg,
  202518. Fts5Tokenizer **ppOut
  202519. ){
  202520. int rc = SQLITE_OK;
  202521. AsciiTokenizer *p = 0;
  202522. UNUSED_PARAM(pUnused);
  202523. if( nArg%2 ){
  202524. rc = SQLITE_ERROR;
  202525. }else{
  202526. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  202527. if( p==0 ){
  202528. rc = SQLITE_NOMEM;
  202529. }else{
  202530. int i;
  202531. memset(p, 0, sizeof(AsciiTokenizer));
  202532. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  202533. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  202534. const char *zArg = azArg[i+1];
  202535. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  202536. fts5AsciiAddExceptions(p, zArg, 1);
  202537. }else
  202538. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  202539. fts5AsciiAddExceptions(p, zArg, 0);
  202540. }else{
  202541. rc = SQLITE_ERROR;
  202542. }
  202543. }
  202544. if( rc!=SQLITE_OK ){
  202545. fts5AsciiDelete((Fts5Tokenizer*)p);
  202546. p = 0;
  202547. }
  202548. }
  202549. }
  202550. *ppOut = (Fts5Tokenizer*)p;
  202551. return rc;
  202552. }
  202553. static void asciiFold(char *aOut, const char *aIn, int nByte){
  202554. int i;
  202555. for(i=0; i<nByte; i++){
  202556. char c = aIn[i];
  202557. if( c>='A' && c<='Z' ) c += 32;
  202558. aOut[i] = c;
  202559. }
  202560. }
  202561. /*
  202562. ** Tokenize some text using the ascii tokenizer.
  202563. */
  202564. static int fts5AsciiTokenize(
  202565. Fts5Tokenizer *pTokenizer,
  202566. void *pCtx,
  202567. int iUnused,
  202568. const char *pText, int nText,
  202569. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  202570. ){
  202571. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  202572. int rc = SQLITE_OK;
  202573. int ie;
  202574. int is = 0;
  202575. char aFold[64];
  202576. int nFold = sizeof(aFold);
  202577. char *pFold = aFold;
  202578. unsigned char *a = p->aTokenChar;
  202579. UNUSED_PARAM(iUnused);
  202580. while( is<nText && rc==SQLITE_OK ){
  202581. int nByte;
  202582. /* Skip any leading divider characters. */
  202583. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  202584. is++;
  202585. }
  202586. if( is==nText ) break;
  202587. /* Count the token characters */
  202588. ie = is+1;
  202589. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  202590. ie++;
  202591. }
  202592. /* Fold to lower case */
  202593. nByte = ie-is;
  202594. if( nByte>nFold ){
  202595. if( pFold!=aFold ) sqlite3_free(pFold);
  202596. pFold = sqlite3_malloc(nByte*2);
  202597. if( pFold==0 ){
  202598. rc = SQLITE_NOMEM;
  202599. break;
  202600. }
  202601. nFold = nByte*2;
  202602. }
  202603. asciiFold(pFold, &pText[is], nByte);
  202604. /* Invoke the token callback */
  202605. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  202606. is = ie+1;
  202607. }
  202608. if( pFold!=aFold ) sqlite3_free(pFold);
  202609. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  202610. return rc;
  202611. }
  202612. /**************************************************************************
  202613. ** Start of unicode61 tokenizer implementation.
  202614. */
  202615. /*
  202616. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  202617. ** from the sqlite3 source file utf.c. If this file is compiled as part
  202618. ** of the amalgamation, they are not required.
  202619. */
  202620. #ifndef SQLITE_AMALGAMATION
  202621. static const unsigned char sqlite3Utf8Trans1[] = {
  202622. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  202623. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  202624. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  202625. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  202626. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  202627. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  202628. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  202629. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  202630. };
  202631. #define READ_UTF8(zIn, zTerm, c) \
  202632. c = *(zIn++); \
  202633. if( c>=0xc0 ){ \
  202634. c = sqlite3Utf8Trans1[c-0xc0]; \
  202635. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  202636. c = (c<<6) + (0x3f & *(zIn++)); \
  202637. } \
  202638. if( c<0x80 \
  202639. || (c&0xFFFFF800)==0xD800 \
  202640. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  202641. }
  202642. #define WRITE_UTF8(zOut, c) { \
  202643. if( c<0x00080 ){ \
  202644. *zOut++ = (unsigned char)(c&0xFF); \
  202645. } \
  202646. else if( c<0x00800 ){ \
  202647. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  202648. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  202649. } \
  202650. else if( c<0x10000 ){ \
  202651. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  202652. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  202653. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  202654. }else{ \
  202655. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  202656. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  202657. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  202658. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  202659. } \
  202660. }
  202661. #endif /* ifndef SQLITE_AMALGAMATION */
  202662. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  202663. struct Unicode61Tokenizer {
  202664. unsigned char aTokenChar[128]; /* ASCII range token characters */
  202665. char *aFold; /* Buffer to fold text into */
  202666. int nFold; /* Size of aFold[] in bytes */
  202667. int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
  202668. int nException;
  202669. int *aiException;
  202670. unsigned char aCategory[32]; /* True for token char categories */
  202671. };
  202672. static int fts5UnicodeAddExceptions(
  202673. Unicode61Tokenizer *p, /* Tokenizer object */
  202674. const char *z, /* Characters to treat as exceptions */
  202675. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  202676. ){
  202677. int rc = SQLITE_OK;
  202678. int n = (int)strlen(z);
  202679. int *aNew;
  202680. if( n>0 ){
  202681. aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
  202682. if( aNew ){
  202683. int nNew = p->nException;
  202684. const unsigned char *zCsr = (const unsigned char*)z;
  202685. const unsigned char *zTerm = (const unsigned char*)&z[n];
  202686. while( zCsr<zTerm ){
  202687. int iCode;
  202688. int bToken;
  202689. READ_UTF8(zCsr, zTerm, iCode);
  202690. if( iCode<128 ){
  202691. p->aTokenChar[iCode] = (unsigned char)bTokenChars;
  202692. }else{
  202693. bToken = p->aCategory[sqlite3Fts5UnicodeCategory(iCode)];
  202694. assert( (bToken==0 || bToken==1) );
  202695. assert( (bTokenChars==0 || bTokenChars==1) );
  202696. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  202697. int i;
  202698. for(i=0; i<nNew; i++){
  202699. if( aNew[i]>iCode ) break;
  202700. }
  202701. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  202702. aNew[i] = iCode;
  202703. nNew++;
  202704. }
  202705. }
  202706. }
  202707. p->aiException = aNew;
  202708. p->nException = nNew;
  202709. }else{
  202710. rc = SQLITE_NOMEM;
  202711. }
  202712. }
  202713. return rc;
  202714. }
  202715. /*
  202716. ** Return true if the p->aiException[] array contains the value iCode.
  202717. */
  202718. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  202719. if( p->nException>0 ){
  202720. int *a = p->aiException;
  202721. int iLo = 0;
  202722. int iHi = p->nException-1;
  202723. while( iHi>=iLo ){
  202724. int iTest = (iHi + iLo) / 2;
  202725. if( iCode==a[iTest] ){
  202726. return 1;
  202727. }else if( iCode>a[iTest] ){
  202728. iLo = iTest+1;
  202729. }else{
  202730. iHi = iTest-1;
  202731. }
  202732. }
  202733. }
  202734. return 0;
  202735. }
  202736. /*
  202737. ** Delete a "unicode61" tokenizer.
  202738. */
  202739. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  202740. if( pTok ){
  202741. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  202742. sqlite3_free(p->aiException);
  202743. sqlite3_free(p->aFold);
  202744. sqlite3_free(p);
  202745. }
  202746. return;
  202747. }
  202748. static int unicodeSetCategories(Unicode61Tokenizer *p, const char *zCat){
  202749. const char *z = zCat;
  202750. while( *z ){
  202751. while( *z==' ' || *z=='\t' ) z++;
  202752. if( *z && sqlite3Fts5UnicodeCatParse(z, p->aCategory) ){
  202753. return SQLITE_ERROR;
  202754. }
  202755. while( *z!=' ' && *z!='\t' && *z!='\0' ) z++;
  202756. }
  202757. sqlite3Fts5UnicodeAscii(p->aCategory, p->aTokenChar);
  202758. return SQLITE_OK;
  202759. }
  202760. /*
  202761. ** Create a "unicode61" tokenizer.
  202762. */
  202763. static int fts5UnicodeCreate(
  202764. void *pUnused,
  202765. const char **azArg, int nArg,
  202766. Fts5Tokenizer **ppOut
  202767. ){
  202768. int rc = SQLITE_OK; /* Return code */
  202769. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  202770. UNUSED_PARAM(pUnused);
  202771. if( nArg%2 ){
  202772. rc = SQLITE_ERROR;
  202773. }else{
  202774. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  202775. if( p ){
  202776. const char *zCat = "L* N* Co";
  202777. int i;
  202778. memset(p, 0, sizeof(Unicode61Tokenizer));
  202779. p->bRemoveDiacritic = 1;
  202780. p->nFold = 64;
  202781. p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
  202782. if( p->aFold==0 ){
  202783. rc = SQLITE_NOMEM;
  202784. }
  202785. /* Search for a "categories" argument */
  202786. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  202787. if( 0==sqlite3_stricmp(azArg[i], "categories") ){
  202788. zCat = azArg[i+1];
  202789. }
  202790. }
  202791. if( rc==SQLITE_OK ){
  202792. rc = unicodeSetCategories(p, zCat);
  202793. }
  202794. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  202795. const char *zArg = azArg[i+1];
  202796. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  202797. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
  202798. rc = SQLITE_ERROR;
  202799. }
  202800. p->bRemoveDiacritic = (zArg[0]=='1');
  202801. }else
  202802. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  202803. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  202804. }else
  202805. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  202806. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  202807. }else
  202808. if( 0==sqlite3_stricmp(azArg[i], "categories") ){
  202809. /* no-op */
  202810. }else{
  202811. rc = SQLITE_ERROR;
  202812. }
  202813. }
  202814. }else{
  202815. rc = SQLITE_NOMEM;
  202816. }
  202817. if( rc!=SQLITE_OK ){
  202818. fts5UnicodeDelete((Fts5Tokenizer*)p);
  202819. p = 0;
  202820. }
  202821. *ppOut = (Fts5Tokenizer*)p;
  202822. }
  202823. return rc;
  202824. }
  202825. /*
  202826. ** Return true if, for the purposes of tokenizing with the tokenizer
  202827. ** passed as the first argument, codepoint iCode is considered a token
  202828. ** character (not a separator).
  202829. */
  202830. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  202831. return (
  202832. p->aCategory[sqlite3Fts5UnicodeCategory(iCode)]
  202833. ^ fts5UnicodeIsException(p, iCode)
  202834. );
  202835. }
  202836. static int fts5UnicodeTokenize(
  202837. Fts5Tokenizer *pTokenizer,
  202838. void *pCtx,
  202839. int iUnused,
  202840. const char *pText, int nText,
  202841. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  202842. ){
  202843. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  202844. int rc = SQLITE_OK;
  202845. unsigned char *a = p->aTokenChar;
  202846. unsigned char *zTerm = (unsigned char*)&pText[nText];
  202847. unsigned char *zCsr = (unsigned char *)pText;
  202848. /* Output buffer */
  202849. char *aFold = p->aFold;
  202850. int nFold = p->nFold;
  202851. const char *pEnd = &aFold[nFold-6];
  202852. UNUSED_PARAM(iUnused);
  202853. /* Each iteration of this loop gobbles up a contiguous run of separators,
  202854. ** then the next token. */
  202855. while( rc==SQLITE_OK ){
  202856. int iCode; /* non-ASCII codepoint read from input */
  202857. char *zOut = aFold;
  202858. int is;
  202859. int ie;
  202860. /* Skip any separator characters. */
  202861. while( 1 ){
  202862. if( zCsr>=zTerm ) goto tokenize_done;
  202863. if( *zCsr & 0x80 ) {
  202864. /* A character outside of the ascii range. Skip past it if it is
  202865. ** a separator character. Or break out of the loop if it is not. */
  202866. is = zCsr - (unsigned char*)pText;
  202867. READ_UTF8(zCsr, zTerm, iCode);
  202868. if( fts5UnicodeIsAlnum(p, iCode) ){
  202869. goto non_ascii_tokenchar;
  202870. }
  202871. }else{
  202872. if( a[*zCsr] ){
  202873. is = zCsr - (unsigned char*)pText;
  202874. goto ascii_tokenchar;
  202875. }
  202876. zCsr++;
  202877. }
  202878. }
  202879. /* Run through the tokenchars. Fold them into the output buffer along
  202880. ** the way. */
  202881. while( zCsr<zTerm ){
  202882. /* Grow the output buffer so that there is sufficient space to fit the
  202883. ** largest possible utf-8 character. */
  202884. if( zOut>pEnd ){
  202885. aFold = sqlite3_malloc(nFold*2);
  202886. if( aFold==0 ){
  202887. rc = SQLITE_NOMEM;
  202888. goto tokenize_done;
  202889. }
  202890. zOut = &aFold[zOut - p->aFold];
  202891. memcpy(aFold, p->aFold, nFold);
  202892. sqlite3_free(p->aFold);
  202893. p->aFold = aFold;
  202894. p->nFold = nFold = nFold*2;
  202895. pEnd = &aFold[nFold-6];
  202896. }
  202897. if( *zCsr & 0x80 ){
  202898. /* An non-ascii-range character. Fold it into the output buffer if
  202899. ** it is a token character, or break out of the loop if it is not. */
  202900. READ_UTF8(zCsr, zTerm, iCode);
  202901. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  202902. non_ascii_tokenchar:
  202903. iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
  202904. if( iCode ) WRITE_UTF8(zOut, iCode);
  202905. }else{
  202906. break;
  202907. }
  202908. }else if( a[*zCsr]==0 ){
  202909. /* An ascii-range separator character. End of token. */
  202910. break;
  202911. }else{
  202912. ascii_tokenchar:
  202913. if( *zCsr>='A' && *zCsr<='Z' ){
  202914. *zOut++ = *zCsr + 32;
  202915. }else{
  202916. *zOut++ = *zCsr;
  202917. }
  202918. zCsr++;
  202919. }
  202920. ie = zCsr - (unsigned char*)pText;
  202921. }
  202922. /* Invoke the token callback */
  202923. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  202924. }
  202925. tokenize_done:
  202926. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  202927. return rc;
  202928. }
  202929. /**************************************************************************
  202930. ** Start of porter stemmer implementation.
  202931. */
  202932. /* Any tokens larger than this (in bytes) are passed through without
  202933. ** stemming. */
  202934. #define FTS5_PORTER_MAX_TOKEN 64
  202935. typedef struct PorterTokenizer PorterTokenizer;
  202936. struct PorterTokenizer {
  202937. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  202938. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  202939. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  202940. };
  202941. /*
  202942. ** Delete a "porter" tokenizer.
  202943. */
  202944. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  202945. if( pTok ){
  202946. PorterTokenizer *p = (PorterTokenizer*)pTok;
  202947. if( p->pTokenizer ){
  202948. p->tokenizer.xDelete(p->pTokenizer);
  202949. }
  202950. sqlite3_free(p);
  202951. }
  202952. }
  202953. /*
  202954. ** Create a "porter" tokenizer.
  202955. */
  202956. static int fts5PorterCreate(
  202957. void *pCtx,
  202958. const char **azArg, int nArg,
  202959. Fts5Tokenizer **ppOut
  202960. ){
  202961. fts5_api *pApi = (fts5_api*)pCtx;
  202962. int rc = SQLITE_OK;
  202963. PorterTokenizer *pRet;
  202964. void *pUserdata = 0;
  202965. const char *zBase = "unicode61";
  202966. if( nArg>0 ){
  202967. zBase = azArg[0];
  202968. }
  202969. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  202970. if( pRet ){
  202971. memset(pRet, 0, sizeof(PorterTokenizer));
  202972. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  202973. }else{
  202974. rc = SQLITE_NOMEM;
  202975. }
  202976. if( rc==SQLITE_OK ){
  202977. int nArg2 = (nArg>0 ? nArg-1 : 0);
  202978. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  202979. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  202980. }
  202981. if( rc!=SQLITE_OK ){
  202982. fts5PorterDelete((Fts5Tokenizer*)pRet);
  202983. pRet = 0;
  202984. }
  202985. *ppOut = (Fts5Tokenizer*)pRet;
  202986. return rc;
  202987. }
  202988. typedef struct PorterContext PorterContext;
  202989. struct PorterContext {
  202990. void *pCtx;
  202991. int (*xToken)(void*, int, const char*, int, int, int);
  202992. char *aBuf;
  202993. };
  202994. typedef struct PorterRule PorterRule;
  202995. struct PorterRule {
  202996. const char *zSuffix;
  202997. int nSuffix;
  202998. int (*xCond)(char *zStem, int nStem);
  202999. const char *zOutput;
  203000. int nOutput;
  203001. };
  203002. #if 0
  203003. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  203004. int ret = -1;
  203005. int nBuf = *pnBuf;
  203006. PorterRule *p;
  203007. for(p=aRule; p->zSuffix; p++){
  203008. assert( strlen(p->zSuffix)==p->nSuffix );
  203009. assert( strlen(p->zOutput)==p->nOutput );
  203010. if( nBuf<p->nSuffix ) continue;
  203011. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  203012. }
  203013. if( p->zSuffix ){
  203014. int nStem = nBuf - p->nSuffix;
  203015. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  203016. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  203017. *pnBuf = nStem + p->nOutput;
  203018. ret = p - aRule;
  203019. }
  203020. }
  203021. return ret;
  203022. }
  203023. #endif
  203024. static int fts5PorterIsVowel(char c, int bYIsVowel){
  203025. return (
  203026. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  203027. );
  203028. }
  203029. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  203030. int i;
  203031. int bCons = bPrevCons;
  203032. /* Scan for a vowel */
  203033. for(i=0; i<nStem; i++){
  203034. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  203035. }
  203036. /* Scan for a consonent */
  203037. for(i++; i<nStem; i++){
  203038. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  203039. }
  203040. return 0;
  203041. }
  203042. /* porter rule condition: (m > 0) */
  203043. static int fts5Porter_MGt0(char *zStem, int nStem){
  203044. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  203045. }
  203046. /* porter rule condition: (m > 1) */
  203047. static int fts5Porter_MGt1(char *zStem, int nStem){
  203048. int n;
  203049. n = fts5PorterGobbleVC(zStem, nStem, 0);
  203050. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  203051. return 1;
  203052. }
  203053. return 0;
  203054. }
  203055. /* porter rule condition: (m = 1) */
  203056. static int fts5Porter_MEq1(char *zStem, int nStem){
  203057. int n;
  203058. n = fts5PorterGobbleVC(zStem, nStem, 0);
  203059. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  203060. return 1;
  203061. }
  203062. return 0;
  203063. }
  203064. /* porter rule condition: (*o) */
  203065. static int fts5Porter_Ostar(char *zStem, int nStem){
  203066. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  203067. return 0;
  203068. }else{
  203069. int i;
  203070. int mask = 0;
  203071. int bCons = 0;
  203072. for(i=0; i<nStem; i++){
  203073. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  203074. assert( bCons==0 || bCons==1 );
  203075. mask = (mask << 1) + bCons;
  203076. }
  203077. return ((mask & 0x0007)==0x0005);
  203078. }
  203079. }
  203080. /* porter rule condition: (m > 1 and (*S or *T)) */
  203081. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  203082. assert( nStem>0 );
  203083. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  203084. && fts5Porter_MGt1(zStem, nStem);
  203085. }
  203086. /* porter rule condition: (*v*) */
  203087. static int fts5Porter_Vowel(char *zStem, int nStem){
  203088. int i;
  203089. for(i=0; i<nStem; i++){
  203090. if( fts5PorterIsVowel(zStem[i], i>0) ){
  203091. return 1;
  203092. }
  203093. }
  203094. return 0;
  203095. }
  203096. /**************************************************************************
  203097. ***************************************************************************
  203098. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  203099. */
  203100. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  203101. int ret = 0;
  203102. int nBuf = *pnBuf;
  203103. switch( aBuf[nBuf-2] ){
  203104. case 'a':
  203105. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  203106. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  203107. *pnBuf = nBuf - 2;
  203108. }
  203109. }
  203110. break;
  203111. case 'c':
  203112. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  203113. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  203114. *pnBuf = nBuf - 4;
  203115. }
  203116. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  203117. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  203118. *pnBuf = nBuf - 4;
  203119. }
  203120. }
  203121. break;
  203122. case 'e':
  203123. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  203124. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  203125. *pnBuf = nBuf - 2;
  203126. }
  203127. }
  203128. break;
  203129. case 'i':
  203130. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  203131. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  203132. *pnBuf = nBuf - 2;
  203133. }
  203134. }
  203135. break;
  203136. case 'l':
  203137. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  203138. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  203139. *pnBuf = nBuf - 4;
  203140. }
  203141. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  203142. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  203143. *pnBuf = nBuf - 4;
  203144. }
  203145. }
  203146. break;
  203147. case 'n':
  203148. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  203149. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  203150. *pnBuf = nBuf - 3;
  203151. }
  203152. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  203153. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  203154. *pnBuf = nBuf - 5;
  203155. }
  203156. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  203157. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  203158. *pnBuf = nBuf - 4;
  203159. }
  203160. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  203161. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  203162. *pnBuf = nBuf - 3;
  203163. }
  203164. }
  203165. break;
  203166. case 'o':
  203167. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  203168. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  203169. *pnBuf = nBuf - 3;
  203170. }
  203171. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  203172. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  203173. *pnBuf = nBuf - 2;
  203174. }
  203175. }
  203176. break;
  203177. case 's':
  203178. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  203179. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  203180. *pnBuf = nBuf - 3;
  203181. }
  203182. }
  203183. break;
  203184. case 't':
  203185. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  203186. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  203187. *pnBuf = nBuf - 3;
  203188. }
  203189. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  203190. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  203191. *pnBuf = nBuf - 3;
  203192. }
  203193. }
  203194. break;
  203195. case 'u':
  203196. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  203197. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  203198. *pnBuf = nBuf - 3;
  203199. }
  203200. }
  203201. break;
  203202. case 'v':
  203203. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  203204. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  203205. *pnBuf = nBuf - 3;
  203206. }
  203207. }
  203208. break;
  203209. case 'z':
  203210. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  203211. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  203212. *pnBuf = nBuf - 3;
  203213. }
  203214. }
  203215. break;
  203216. }
  203217. return ret;
  203218. }
  203219. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  203220. int ret = 0;
  203221. int nBuf = *pnBuf;
  203222. switch( aBuf[nBuf-2] ){
  203223. case 'a':
  203224. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  203225. memcpy(&aBuf[nBuf-2], "ate", 3);
  203226. *pnBuf = nBuf - 2 + 3;
  203227. ret = 1;
  203228. }
  203229. break;
  203230. case 'b':
  203231. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  203232. memcpy(&aBuf[nBuf-2], "ble", 3);
  203233. *pnBuf = nBuf - 2 + 3;
  203234. ret = 1;
  203235. }
  203236. break;
  203237. case 'i':
  203238. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  203239. memcpy(&aBuf[nBuf-2], "ize", 3);
  203240. *pnBuf = nBuf - 2 + 3;
  203241. ret = 1;
  203242. }
  203243. break;
  203244. }
  203245. return ret;
  203246. }
  203247. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  203248. int ret = 0;
  203249. int nBuf = *pnBuf;
  203250. switch( aBuf[nBuf-2] ){
  203251. case 'a':
  203252. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  203253. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  203254. memcpy(&aBuf[nBuf-7], "ate", 3);
  203255. *pnBuf = nBuf - 7 + 3;
  203256. }
  203257. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  203258. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  203259. memcpy(&aBuf[nBuf-6], "tion", 4);
  203260. *pnBuf = nBuf - 6 + 4;
  203261. }
  203262. }
  203263. break;
  203264. case 'c':
  203265. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  203266. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  203267. memcpy(&aBuf[nBuf-4], "ence", 4);
  203268. *pnBuf = nBuf - 4 + 4;
  203269. }
  203270. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  203271. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  203272. memcpy(&aBuf[nBuf-4], "ance", 4);
  203273. *pnBuf = nBuf - 4 + 4;
  203274. }
  203275. }
  203276. break;
  203277. case 'e':
  203278. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  203279. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  203280. memcpy(&aBuf[nBuf-4], "ize", 3);
  203281. *pnBuf = nBuf - 4 + 3;
  203282. }
  203283. }
  203284. break;
  203285. case 'g':
  203286. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  203287. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  203288. memcpy(&aBuf[nBuf-4], "log", 3);
  203289. *pnBuf = nBuf - 4 + 3;
  203290. }
  203291. }
  203292. break;
  203293. case 'l':
  203294. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  203295. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  203296. memcpy(&aBuf[nBuf-3], "ble", 3);
  203297. *pnBuf = nBuf - 3 + 3;
  203298. }
  203299. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  203300. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  203301. memcpy(&aBuf[nBuf-4], "al", 2);
  203302. *pnBuf = nBuf - 4 + 2;
  203303. }
  203304. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  203305. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  203306. memcpy(&aBuf[nBuf-5], "ent", 3);
  203307. *pnBuf = nBuf - 5 + 3;
  203308. }
  203309. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  203310. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  203311. memcpy(&aBuf[nBuf-3], "e", 1);
  203312. *pnBuf = nBuf - 3 + 1;
  203313. }
  203314. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  203315. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  203316. memcpy(&aBuf[nBuf-5], "ous", 3);
  203317. *pnBuf = nBuf - 5 + 3;
  203318. }
  203319. }
  203320. break;
  203321. case 'o':
  203322. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  203323. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  203324. memcpy(&aBuf[nBuf-7], "ize", 3);
  203325. *pnBuf = nBuf - 7 + 3;
  203326. }
  203327. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  203328. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  203329. memcpy(&aBuf[nBuf-5], "ate", 3);
  203330. *pnBuf = nBuf - 5 + 3;
  203331. }
  203332. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  203333. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  203334. memcpy(&aBuf[nBuf-4], "ate", 3);
  203335. *pnBuf = nBuf - 4 + 3;
  203336. }
  203337. }
  203338. break;
  203339. case 's':
  203340. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  203341. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  203342. memcpy(&aBuf[nBuf-5], "al", 2);
  203343. *pnBuf = nBuf - 5 + 2;
  203344. }
  203345. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  203346. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  203347. memcpy(&aBuf[nBuf-7], "ive", 3);
  203348. *pnBuf = nBuf - 7 + 3;
  203349. }
  203350. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  203351. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  203352. memcpy(&aBuf[nBuf-7], "ful", 3);
  203353. *pnBuf = nBuf - 7 + 3;
  203354. }
  203355. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  203356. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  203357. memcpy(&aBuf[nBuf-7], "ous", 3);
  203358. *pnBuf = nBuf - 7 + 3;
  203359. }
  203360. }
  203361. break;
  203362. case 't':
  203363. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  203364. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  203365. memcpy(&aBuf[nBuf-5], "al", 2);
  203366. *pnBuf = nBuf - 5 + 2;
  203367. }
  203368. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  203369. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  203370. memcpy(&aBuf[nBuf-5], "ive", 3);
  203371. *pnBuf = nBuf - 5 + 3;
  203372. }
  203373. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  203374. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  203375. memcpy(&aBuf[nBuf-6], "ble", 3);
  203376. *pnBuf = nBuf - 6 + 3;
  203377. }
  203378. }
  203379. break;
  203380. }
  203381. return ret;
  203382. }
  203383. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  203384. int ret = 0;
  203385. int nBuf = *pnBuf;
  203386. switch( aBuf[nBuf-2] ){
  203387. case 'a':
  203388. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  203389. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  203390. memcpy(&aBuf[nBuf-4], "ic", 2);
  203391. *pnBuf = nBuf - 4 + 2;
  203392. }
  203393. }
  203394. break;
  203395. case 's':
  203396. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  203397. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  203398. *pnBuf = nBuf - 4;
  203399. }
  203400. }
  203401. break;
  203402. case 't':
  203403. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  203404. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  203405. memcpy(&aBuf[nBuf-5], "ic", 2);
  203406. *pnBuf = nBuf - 5 + 2;
  203407. }
  203408. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  203409. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  203410. memcpy(&aBuf[nBuf-5], "ic", 2);
  203411. *pnBuf = nBuf - 5 + 2;
  203412. }
  203413. }
  203414. break;
  203415. case 'u':
  203416. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  203417. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  203418. *pnBuf = nBuf - 3;
  203419. }
  203420. }
  203421. break;
  203422. case 'v':
  203423. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  203424. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  203425. *pnBuf = nBuf - 5;
  203426. }
  203427. }
  203428. break;
  203429. case 'z':
  203430. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  203431. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  203432. memcpy(&aBuf[nBuf-5], "al", 2);
  203433. *pnBuf = nBuf - 5 + 2;
  203434. }
  203435. }
  203436. break;
  203437. }
  203438. return ret;
  203439. }
  203440. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  203441. int ret = 0;
  203442. int nBuf = *pnBuf;
  203443. switch( aBuf[nBuf-2] ){
  203444. case 'e':
  203445. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  203446. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  203447. memcpy(&aBuf[nBuf-3], "ee", 2);
  203448. *pnBuf = nBuf - 3 + 2;
  203449. }
  203450. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  203451. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  203452. *pnBuf = nBuf - 2;
  203453. ret = 1;
  203454. }
  203455. }
  203456. break;
  203457. case 'n':
  203458. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  203459. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  203460. *pnBuf = nBuf - 3;
  203461. ret = 1;
  203462. }
  203463. }
  203464. break;
  203465. }
  203466. return ret;
  203467. }
  203468. /*
  203469. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  203470. ***************************************************************************
  203471. **************************************************************************/
  203472. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  203473. int nBuf = *pnBuf;
  203474. if( aBuf[nBuf-1]=='s' ){
  203475. if( aBuf[nBuf-2]=='e' ){
  203476. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  203477. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  203478. ){
  203479. *pnBuf = nBuf-2;
  203480. }else{
  203481. *pnBuf = nBuf-1;
  203482. }
  203483. }
  203484. else if( aBuf[nBuf-2]!='s' ){
  203485. *pnBuf = nBuf-1;
  203486. }
  203487. }
  203488. }
  203489. static int fts5PorterCb(
  203490. void *pCtx,
  203491. int tflags,
  203492. const char *pToken,
  203493. int nToken,
  203494. int iStart,
  203495. int iEnd
  203496. ){
  203497. PorterContext *p = (PorterContext*)pCtx;
  203498. char *aBuf;
  203499. int nBuf;
  203500. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  203501. aBuf = p->aBuf;
  203502. nBuf = nToken;
  203503. memcpy(aBuf, pToken, nBuf);
  203504. /* Step 1. */
  203505. fts5PorterStep1A(aBuf, &nBuf);
  203506. if( fts5PorterStep1B(aBuf, &nBuf) ){
  203507. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  203508. char c = aBuf[nBuf-1];
  203509. if( fts5PorterIsVowel(c, 0)==0
  203510. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  203511. ){
  203512. nBuf--;
  203513. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  203514. aBuf[nBuf++] = 'e';
  203515. }
  203516. }
  203517. }
  203518. /* Step 1C. */
  203519. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  203520. aBuf[nBuf-1] = 'i';
  203521. }
  203522. /* Steps 2 through 4. */
  203523. fts5PorterStep2(aBuf, &nBuf);
  203524. fts5PorterStep3(aBuf, &nBuf);
  203525. fts5PorterStep4(aBuf, &nBuf);
  203526. /* Step 5a. */
  203527. assert( nBuf>0 );
  203528. if( aBuf[nBuf-1]=='e' ){
  203529. if( fts5Porter_MGt1(aBuf, nBuf-1)
  203530. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  203531. ){
  203532. nBuf--;
  203533. }
  203534. }
  203535. /* Step 5b. */
  203536. if( nBuf>1 && aBuf[nBuf-1]=='l'
  203537. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  203538. ){
  203539. nBuf--;
  203540. }
  203541. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  203542. pass_through:
  203543. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  203544. }
  203545. /*
  203546. ** Tokenize using the porter tokenizer.
  203547. */
  203548. static int fts5PorterTokenize(
  203549. Fts5Tokenizer *pTokenizer,
  203550. void *pCtx,
  203551. int flags,
  203552. const char *pText, int nText,
  203553. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  203554. ){
  203555. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  203556. PorterContext sCtx;
  203557. sCtx.xToken = xToken;
  203558. sCtx.pCtx = pCtx;
  203559. sCtx.aBuf = p->aBuf;
  203560. return p->tokenizer.xTokenize(
  203561. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  203562. );
  203563. }
  203564. /*
  203565. ** Register all built-in tokenizers with FTS5.
  203566. */
  203567. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  203568. struct BuiltinTokenizer {
  203569. const char *zName;
  203570. fts5_tokenizer x;
  203571. } aBuiltin[] = {
  203572. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  203573. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  203574. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  203575. };
  203576. int rc = SQLITE_OK; /* Return code */
  203577. int i; /* To iterate through builtin functions */
  203578. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  203579. rc = pApi->xCreateTokenizer(pApi,
  203580. aBuiltin[i].zName,
  203581. (void*)pApi,
  203582. &aBuiltin[i].x,
  203583. 0
  203584. );
  203585. }
  203586. return rc;
  203587. }
  203588. /*
  203589. ** 2012 May 25
  203590. **
  203591. ** The author disclaims copyright to this source code. In place of
  203592. ** a legal notice, here is a blessing:
  203593. **
  203594. ** May you do good and not evil.
  203595. ** May you find forgiveness for yourself and forgive others.
  203596. ** May you share freely, never taking more than you give.
  203597. **
  203598. ******************************************************************************
  203599. */
  203600. /*
  203601. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  203602. */
  203603. /* #include <assert.h> */
  203604. /*
  203605. ** If the argument is a codepoint corresponding to a lowercase letter
  203606. ** in the ASCII range with a diacritic added, return the codepoint
  203607. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  203608. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  203609. ** E"). The resuls of passing a codepoint that corresponds to an
  203610. ** uppercase letter are undefined.
  203611. */
  203612. static int fts5_remove_diacritic(int c){
  203613. unsigned short aDia[] = {
  203614. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  203615. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  203616. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  203617. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  203618. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  203619. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  203620. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  203621. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  203622. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  203623. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  203624. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  203625. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  203626. 62924, 63050, 63082, 63274, 63390,
  203627. };
  203628. char aChar[] = {
  203629. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  203630. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  203631. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  203632. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  203633. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  203634. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  203635. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  203636. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  203637. 'e', 'i', 'o', 'u', 'y',
  203638. };
  203639. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  203640. int iRes = 0;
  203641. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  203642. int iLo = 0;
  203643. while( iHi>=iLo ){
  203644. int iTest = (iHi + iLo) / 2;
  203645. if( key >= aDia[iTest] ){
  203646. iRes = iTest;
  203647. iLo = iTest+1;
  203648. }else{
  203649. iHi = iTest-1;
  203650. }
  203651. }
  203652. assert( key>=aDia[iRes] );
  203653. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  203654. }
  203655. /*
  203656. ** Return true if the argument interpreted as a unicode codepoint
  203657. ** is a diacritical modifier character.
  203658. */
  203659. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  203660. unsigned int mask0 = 0x08029FDF;
  203661. unsigned int mask1 = 0x000361F8;
  203662. if( c<768 || c>817 ) return 0;
  203663. return (c < 768+32) ?
  203664. (mask0 & (1 << (c-768))) :
  203665. (mask1 & (1 << (c-768-32)));
  203666. }
  203667. /*
  203668. ** Interpret the argument as a unicode codepoint. If the codepoint
  203669. ** is an upper case character that has a lower case equivalent,
  203670. ** return the codepoint corresponding to the lower case version.
  203671. ** Otherwise, return a copy of the argument.
  203672. **
  203673. ** The results are undefined if the value passed to this function
  203674. ** is less than zero.
  203675. */
  203676. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
  203677. /* Each entry in the following array defines a rule for folding a range
  203678. ** of codepoints to lower case. The rule applies to a range of nRange
  203679. ** codepoints starting at codepoint iCode.
  203680. **
  203681. ** If the least significant bit in flags is clear, then the rule applies
  203682. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  203683. ** need to be folded). Or, if it is set, then the rule only applies to
  203684. ** every second codepoint in the range, starting with codepoint C.
  203685. **
  203686. ** The 7 most significant bits in flags are an index into the aiOff[]
  203687. ** array. If a specific codepoint C does require folding, then its lower
  203688. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  203689. **
  203690. ** The contents of this array are generated by parsing the CaseFolding.txt
  203691. ** file distributed as part of the "Unicode Character Database". See
  203692. ** http://www.unicode.org for details.
  203693. */
  203694. static const struct TableEntry {
  203695. unsigned short iCode;
  203696. unsigned char flags;
  203697. unsigned char nRange;
  203698. } aEntry[] = {
  203699. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  203700. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  203701. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  203702. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  203703. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  203704. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  203705. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  203706. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  203707. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  203708. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  203709. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  203710. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  203711. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  203712. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  203713. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  203714. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  203715. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  203716. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  203717. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  203718. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  203719. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  203720. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  203721. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  203722. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  203723. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  203724. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  203725. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  203726. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  203727. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  203728. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  203729. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  203730. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  203731. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  203732. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  203733. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  203734. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  203735. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  203736. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  203737. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  203738. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  203739. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  203740. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  203741. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  203742. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  203743. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  203744. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  203745. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  203746. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  203747. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  203748. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  203749. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  203750. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  203751. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  203752. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  203753. {65313, 14, 26},
  203754. };
  203755. static const unsigned short aiOff[] = {
  203756. 1, 2, 8, 15, 16, 26, 28, 32,
  203757. 37, 38, 40, 48, 63, 64, 69, 71,
  203758. 79, 80, 116, 202, 203, 205, 206, 207,
  203759. 209, 210, 211, 213, 214, 217, 218, 219,
  203760. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  203761. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  203762. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  203763. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  203764. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  203765. 65514, 65521, 65527, 65528, 65529,
  203766. };
  203767. int ret = c;
  203768. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  203769. if( c<128 ){
  203770. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  203771. }else if( c<65536 ){
  203772. const struct TableEntry *p;
  203773. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  203774. int iLo = 0;
  203775. int iRes = -1;
  203776. assert( c>aEntry[0].iCode );
  203777. while( iHi>=iLo ){
  203778. int iTest = (iHi + iLo) / 2;
  203779. int cmp = (c - aEntry[iTest].iCode);
  203780. if( cmp>=0 ){
  203781. iRes = iTest;
  203782. iLo = iTest+1;
  203783. }else{
  203784. iHi = iTest-1;
  203785. }
  203786. }
  203787. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  203788. p = &aEntry[iRes];
  203789. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  203790. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  203791. assert( ret>0 );
  203792. }
  203793. if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
  203794. }
  203795. else if( c>=66560 && c<66600 ){
  203796. ret = c + 40;
  203797. }
  203798. return ret;
  203799. }
  203800. #if 0
  203801. static int sqlite3Fts5UnicodeNCat(void) {
  203802. return 32;
  203803. }
  203804. #endif
  203805. static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
  203806. aArray[0] = 1;
  203807. switch( zCat[0] ){
  203808. case 'C':
  203809. switch( zCat[1] ){
  203810. case 'c': aArray[1] = 1; break;
  203811. case 'f': aArray[2] = 1; break;
  203812. case 'n': aArray[3] = 1; break;
  203813. case 's': aArray[4] = 1; break;
  203814. case 'o': aArray[31] = 1; break;
  203815. case '*':
  203816. aArray[1] = 1;
  203817. aArray[2] = 1;
  203818. aArray[3] = 1;
  203819. aArray[4] = 1;
  203820. aArray[31] = 1;
  203821. break;
  203822. default: return 1; }
  203823. break;
  203824. case 'L':
  203825. switch( zCat[1] ){
  203826. case 'l': aArray[5] = 1; break;
  203827. case 'm': aArray[6] = 1; break;
  203828. case 'o': aArray[7] = 1; break;
  203829. case 't': aArray[8] = 1; break;
  203830. case 'u': aArray[9] = 1; break;
  203831. case 'C': aArray[30] = 1; break;
  203832. case '*':
  203833. aArray[5] = 1;
  203834. aArray[6] = 1;
  203835. aArray[7] = 1;
  203836. aArray[8] = 1;
  203837. aArray[9] = 1;
  203838. aArray[30] = 1;
  203839. break;
  203840. default: return 1; }
  203841. break;
  203842. case 'M':
  203843. switch( zCat[1] ){
  203844. case 'c': aArray[10] = 1; break;
  203845. case 'e': aArray[11] = 1; break;
  203846. case 'n': aArray[12] = 1; break;
  203847. case '*':
  203848. aArray[10] = 1;
  203849. aArray[11] = 1;
  203850. aArray[12] = 1;
  203851. break;
  203852. default: return 1; }
  203853. break;
  203854. case 'N':
  203855. switch( zCat[1] ){
  203856. case 'd': aArray[13] = 1; break;
  203857. case 'l': aArray[14] = 1; break;
  203858. case 'o': aArray[15] = 1; break;
  203859. case '*':
  203860. aArray[13] = 1;
  203861. aArray[14] = 1;
  203862. aArray[15] = 1;
  203863. break;
  203864. default: return 1; }
  203865. break;
  203866. case 'P':
  203867. switch( zCat[1] ){
  203868. case 'c': aArray[16] = 1; break;
  203869. case 'd': aArray[17] = 1; break;
  203870. case 'e': aArray[18] = 1; break;
  203871. case 'f': aArray[19] = 1; break;
  203872. case 'i': aArray[20] = 1; break;
  203873. case 'o': aArray[21] = 1; break;
  203874. case 's': aArray[22] = 1; break;
  203875. case '*':
  203876. aArray[16] = 1;
  203877. aArray[17] = 1;
  203878. aArray[18] = 1;
  203879. aArray[19] = 1;
  203880. aArray[20] = 1;
  203881. aArray[21] = 1;
  203882. aArray[22] = 1;
  203883. break;
  203884. default: return 1; }
  203885. break;
  203886. case 'S':
  203887. switch( zCat[1] ){
  203888. case 'c': aArray[23] = 1; break;
  203889. case 'k': aArray[24] = 1; break;
  203890. case 'm': aArray[25] = 1; break;
  203891. case 'o': aArray[26] = 1; break;
  203892. case '*':
  203893. aArray[23] = 1;
  203894. aArray[24] = 1;
  203895. aArray[25] = 1;
  203896. aArray[26] = 1;
  203897. break;
  203898. default: return 1; }
  203899. break;
  203900. case 'Z':
  203901. switch( zCat[1] ){
  203902. case 'l': aArray[27] = 1; break;
  203903. case 'p': aArray[28] = 1; break;
  203904. case 's': aArray[29] = 1; break;
  203905. case '*':
  203906. aArray[27] = 1;
  203907. aArray[28] = 1;
  203908. aArray[29] = 1;
  203909. break;
  203910. default: return 1; }
  203911. break;
  203912. }
  203913. return 0;
  203914. }
  203915. static u16 aFts5UnicodeBlock[] = {
  203916. 0, 1471, 1753, 1760, 1760, 1760, 1760, 1760, 1760, 1760,
  203917. 1760, 1760, 1760, 1760, 1760, 1763, 1765,
  203918. };
  203919. static u16 aFts5UnicodeMap[] = {
  203920. 0, 32, 33, 36, 37, 40, 41, 42, 43, 44,
  203921. 45, 46, 48, 58, 60, 63, 65, 91, 92, 93,
  203922. 94, 95, 96, 97, 123, 124, 125, 126, 127, 160,
  203923. 161, 162, 166, 167, 168, 169, 170, 171, 172, 173,
  203924. 174, 175, 176, 177, 178, 180, 181, 182, 184, 185,
  203925. 186, 187, 188, 191, 192, 215, 216, 223, 247, 248,
  203926. 256, 312, 313, 329, 330, 377, 383, 385, 387, 388,
  203927. 391, 394, 396, 398, 402, 403, 405, 406, 409, 412,
  203928. 414, 415, 417, 418, 423, 427, 428, 431, 434, 436,
  203929. 437, 440, 442, 443, 444, 446, 448, 452, 453, 454,
  203930. 455, 456, 457, 458, 459, 460, 461, 477, 478, 496,
  203931. 497, 498, 499, 500, 503, 505, 506, 564, 570, 572,
  203932. 573, 575, 577, 580, 583, 584, 592, 660, 661, 688,
  203933. 706, 710, 722, 736, 741, 748, 749, 750, 751, 768,
  203934. 880, 884, 885, 886, 890, 891, 894, 900, 902, 903,
  203935. 904, 908, 910, 912, 913, 931, 940, 975, 977, 978,
  203936. 981, 984, 1008, 1012, 1014, 1015, 1018, 1020, 1021, 1072,
  203937. 1120, 1154, 1155, 1160, 1162, 1217, 1231, 1232, 1329, 1369,
  203938. 1370, 1377, 1417, 1418, 1423, 1425, 1470, 1471, 1472, 1473,
  203939. 1475, 1476, 1478, 1479, 1488, 1520, 1523, 1536, 1542, 1545,
  203940. 1547, 1548, 1550, 1552, 1563, 1566, 1568, 1600, 1601, 1611,
  203941. 1632, 1642, 1646, 1648, 1649, 1748, 1749, 1750, 1757, 1758,
  203942. 1759, 1765, 1767, 1769, 1770, 1774, 1776, 1786, 1789, 1791,
  203943. 1792, 1807, 1808, 1809, 1810, 1840, 1869, 1958, 1969, 1984,
  203944. 1994, 2027, 2036, 2038, 2039, 2042, 2048, 2070, 2074, 2075,
  203945. 2084, 2085, 2088, 2089, 2096, 2112, 2137, 2142, 2208, 2210,
  203946. 2276, 2304, 2307, 2308, 2362, 2363, 2364, 2365, 2366, 2369,
  203947. 2377, 2381, 2382, 2384, 2385, 2392, 2402, 2404, 2406, 2416,
  203948. 2417, 2418, 2425, 2433, 2434, 2437, 2447, 2451, 2474, 2482,
  203949. 2486, 2492, 2493, 2494, 2497, 2503, 2507, 2509, 2510, 2519,
  203950. 2524, 2527, 2530, 2534, 2544, 2546, 2548, 2554, 2555, 2561,
  203951. 2563, 2565, 2575, 2579, 2602, 2610, 2613, 2616, 2620, 2622,
  203952. 2625, 2631, 2635, 2641, 2649, 2654, 2662, 2672, 2674, 2677,
  203953. 2689, 2691, 2693, 2703, 2707, 2730, 2738, 2741, 2748, 2749,
  203954. 2750, 2753, 2759, 2761, 2763, 2765, 2768, 2784, 2786, 2790,
  203955. 2800, 2801, 2817, 2818, 2821, 2831, 2835, 2858, 2866, 2869,
  203956. 2876, 2877, 2878, 2879, 2880, 2881, 2887, 2891, 2893, 2902,
  203957. 2903, 2908, 2911, 2914, 2918, 2928, 2929, 2930, 2946, 2947,
  203958. 2949, 2958, 2962, 2969, 2972, 2974, 2979, 2984, 2990, 3006,
  203959. 3008, 3009, 3014, 3018, 3021, 3024, 3031, 3046, 3056, 3059,
  203960. 3065, 3066, 3073, 3077, 3086, 3090, 3114, 3125, 3133, 3134,
  203961. 3137, 3142, 3146, 3157, 3160, 3168, 3170, 3174, 3192, 3199,
  203962. 3202, 3205, 3214, 3218, 3242, 3253, 3260, 3261, 3262, 3263,
  203963. 3264, 3270, 3271, 3274, 3276, 3285, 3294, 3296, 3298, 3302,
  203964. 3313, 3330, 3333, 3342, 3346, 3389, 3390, 3393, 3398, 3402,
  203965. 3405, 3406, 3415, 3424, 3426, 3430, 3440, 3449, 3450, 3458,
  203966. 3461, 3482, 3507, 3517, 3520, 3530, 3535, 3538, 3542, 3544,
  203967. 3570, 3572, 3585, 3633, 3634, 3636, 3647, 3648, 3654, 3655,
  203968. 3663, 3664, 3674, 3713, 3716, 3719, 3722, 3725, 3732, 3737,
  203969. 3745, 3749, 3751, 3754, 3757, 3761, 3762, 3764, 3771, 3773,
  203970. 3776, 3782, 3784, 3792, 3804, 3840, 3841, 3844, 3859, 3860,
  203971. 3861, 3864, 3866, 3872, 3882, 3892, 3893, 3894, 3895, 3896,
  203972. 3897, 3898, 3899, 3900, 3901, 3902, 3904, 3913, 3953, 3967,
  203973. 3968, 3973, 3974, 3976, 3981, 3993, 4030, 4038, 4039, 4046,
  203974. 4048, 4053, 4057, 4096, 4139, 4141, 4145, 4146, 4152, 4153,
  203975. 4155, 4157, 4159, 4160, 4170, 4176, 4182, 4184, 4186, 4190,
  203976. 4193, 4194, 4197, 4199, 4206, 4209, 4213, 4226, 4227, 4229,
  203977. 4231, 4237, 4238, 4239, 4240, 4250, 4253, 4254, 4256, 4295,
  203978. 4301, 4304, 4347, 4348, 4349, 4682, 4688, 4696, 4698, 4704,
  203979. 4746, 4752, 4786, 4792, 4800, 4802, 4808, 4824, 4882, 4888,
  203980. 4957, 4960, 4969, 4992, 5008, 5024, 5120, 5121, 5741, 5743,
  203981. 5760, 5761, 5787, 5788, 5792, 5867, 5870, 5888, 5902, 5906,
  203982. 5920, 5938, 5941, 5952, 5970, 5984, 5998, 6002, 6016, 6068,
  203983. 6070, 6071, 6078, 6086, 6087, 6089, 6100, 6103, 6104, 6107,
  203984. 6108, 6109, 6112, 6128, 6144, 6150, 6151, 6155, 6158, 6160,
  203985. 6176, 6211, 6212, 6272, 6313, 6314, 6320, 6400, 6432, 6435,
  203986. 6439, 6441, 6448, 6450, 6451, 6457, 6464, 6468, 6470, 6480,
  203987. 6512, 6528, 6576, 6593, 6600, 6608, 6618, 6622, 6656, 6679,
  203988. 6681, 6686, 6688, 6741, 6742, 6743, 6744, 6752, 6753, 6754,
  203989. 6755, 6757, 6765, 6771, 6783, 6784, 6800, 6816, 6823, 6824,
  203990. 6912, 6916, 6917, 6964, 6965, 6966, 6971, 6972, 6973, 6978,
  203991. 6979, 6981, 6992, 7002, 7009, 7019, 7028, 7040, 7042, 7043,
  203992. 7073, 7074, 7078, 7080, 7082, 7083, 7084, 7086, 7088, 7098,
  203993. 7142, 7143, 7144, 7146, 7149, 7150, 7151, 7154, 7164, 7168,
  203994. 7204, 7212, 7220, 7222, 7227, 7232, 7245, 7248, 7258, 7288,
  203995. 7294, 7360, 7376, 7379, 7380, 7393, 7394, 7401, 7405, 7406,
  203996. 7410, 7412, 7413, 7424, 7468, 7531, 7544, 7545, 7579, 7616,
  203997. 7676, 7680, 7830, 7838, 7936, 7944, 7952, 7960, 7968, 7976,
  203998. 7984, 7992, 8000, 8008, 8016, 8025, 8027, 8029, 8031, 8033,
  203999. 8040, 8048, 8064, 8072, 8080, 8088, 8096, 8104, 8112, 8118,
  204000. 8120, 8124, 8125, 8126, 8127, 8130, 8134, 8136, 8140, 8141,
  204001. 8144, 8150, 8152, 8157, 8160, 8168, 8173, 8178, 8182, 8184,
  204002. 8188, 8189, 8192, 8203, 8208, 8214, 8216, 8217, 8218, 8219,
  204003. 8221, 8222, 8223, 8224, 8232, 8233, 8234, 8239, 8240, 8249,
  204004. 8250, 8251, 8255, 8257, 8260, 8261, 8262, 8263, 8274, 8275,
  204005. 8276, 8277, 8287, 8288, 8298, 8304, 8305, 8308, 8314, 8317,
  204006. 8318, 8319, 8320, 8330, 8333, 8334, 8336, 8352, 8400, 8413,
  204007. 8417, 8418, 8421, 8448, 8450, 8451, 8455, 8456, 8458, 8459,
  204008. 8462, 8464, 8467, 8468, 8469, 8470, 8472, 8473, 8478, 8484,
  204009. 8485, 8486, 8487, 8488, 8489, 8490, 8494, 8495, 8496, 8500,
  204010. 8501, 8505, 8506, 8508, 8510, 8512, 8517, 8519, 8522, 8523,
  204011. 8524, 8526, 8527, 8528, 8544, 8579, 8581, 8585, 8592, 8597,
  204012. 8602, 8604, 8608, 8609, 8611, 8612, 8614, 8615, 8622, 8623,
  204013. 8654, 8656, 8658, 8659, 8660, 8661, 8692, 8960, 8968, 8972,
  204014. 8992, 8994, 9001, 9002, 9003, 9084, 9085, 9115, 9140, 9180,
  204015. 9186, 9216, 9280, 9312, 9372, 9450, 9472, 9655, 9656, 9665,
  204016. 9666, 9720, 9728, 9839, 9840, 9985, 10088, 10089, 10090, 10091,
  204017. 10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101,
  204018. 10102, 10132, 10176, 10181, 10182, 10183, 10214, 10215, 10216, 10217,
  204019. 10218, 10219, 10220, 10221, 10222, 10223, 10224, 10240, 10496, 10627,
  204020. 10628, 10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636, 10637,
  204021. 10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647,
  204022. 10648, 10649, 10712, 10713, 10714, 10715, 10716, 10748, 10749, 10750,
  204023. 11008, 11056, 11077, 11079, 11088, 11264, 11312, 11360, 11363, 11365,
  204024. 11367, 11374, 11377, 11378, 11380, 11381, 11383, 11388, 11390, 11393,
  204025. 11394, 11492, 11493, 11499, 11503, 11506, 11513, 11517, 11518, 11520,
  204026. 11559, 11565, 11568, 11631, 11632, 11647, 11648, 11680, 11688, 11696,
  204027. 11704, 11712, 11720, 11728, 11736, 11744, 11776, 11778, 11779, 11780,
  204028. 11781, 11782, 11785, 11786, 11787, 11788, 11789, 11790, 11799, 11800,
  204029. 11802, 11803, 11804, 11805, 11806, 11808, 11809, 11810, 11811, 11812,
  204030. 11813, 11814, 11815, 11816, 11817, 11818, 11823, 11824, 11834, 11904,
  204031. 11931, 12032, 12272, 12288, 12289, 12292, 12293, 12294, 12295, 12296,
  204032. 12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 12306,
  204033. 12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317,
  204034. 12318, 12320, 12321, 12330, 12334, 12336, 12337, 12342, 12344, 12347,
  204035. 12348, 12349, 12350, 12353, 12441, 12443, 12445, 12447, 12448, 12449,
  204036. 12539, 12540, 12543, 12549, 12593, 12688, 12690, 12694, 12704, 12736,
  204037. 12784, 12800, 12832, 12842, 12872, 12880, 12881, 12896, 12928, 12938,
  204038. 12977, 12992, 13056, 13312, 19893, 19904, 19968, 40908, 40960, 40981,
  204039. 40982, 42128, 42192, 42232, 42238, 42240, 42508, 42509, 42512, 42528,
  204040. 42538, 42560, 42606, 42607, 42608, 42611, 42612, 42622, 42623, 42624,
  204041. 42655, 42656, 42726, 42736, 42738, 42752, 42775, 42784, 42786, 42800,
  204042. 42802, 42864, 42865, 42873, 42878, 42888, 42889, 42891, 42896, 42912,
  204043. 43000, 43002, 43003, 43010, 43011, 43014, 43015, 43019, 43020, 43043,
  204044. 43045, 43047, 43048, 43056, 43062, 43064, 43065, 43072, 43124, 43136,
  204045. 43138, 43188, 43204, 43214, 43216, 43232, 43250, 43256, 43259, 43264,
  204046. 43274, 43302, 43310, 43312, 43335, 43346, 43359, 43360, 43392, 43395,
  204047. 43396, 43443, 43444, 43446, 43450, 43452, 43453, 43457, 43471, 43472,
  204048. 43486, 43520, 43561, 43567, 43569, 43571, 43573, 43584, 43587, 43588,
  204049. 43596, 43597, 43600, 43612, 43616, 43632, 43633, 43639, 43642, 43643,
  204050. 43648, 43696, 43697, 43698, 43701, 43703, 43705, 43710, 43712, 43713,
  204051. 43714, 43739, 43741, 43742, 43744, 43755, 43756, 43758, 43760, 43762,
  204052. 43763, 43765, 43766, 43777, 43785, 43793, 43808, 43816, 43968, 44003,
  204053. 44005, 44006, 44008, 44009, 44011, 44012, 44013, 44016, 44032, 55203,
  204054. 55216, 55243, 55296, 56191, 56319, 57343, 57344, 63743, 63744, 64112,
  204055. 64256, 64275, 64285, 64286, 64287, 64297, 64298, 64312, 64318, 64320,
  204056. 64323, 64326, 64434, 64467, 64830, 64831, 64848, 64914, 65008, 65020,
  204057. 65021, 65024, 65040, 65047, 65048, 65049, 65056, 65072, 65073, 65075,
  204058. 65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084, 65085, 65086,
  204059. 65087, 65088, 65089, 65090, 65091, 65092, 65093, 65095, 65096, 65097,
  204060. 65101, 65104, 65108, 65112, 65113, 65114, 65115, 65116, 65117, 65118,
  204061. 65119, 65122, 65123, 65124, 65128, 65129, 65130, 65136, 65142, 65279,
  204062. 65281, 65284, 65285, 65288, 65289, 65290, 65291, 65292, 65293, 65294,
  204063. 65296, 65306, 65308, 65311, 65313, 65339, 65340, 65341, 65342, 65343,
  204064. 65344, 65345, 65371, 65372, 65373, 65374, 65375, 65376, 65377, 65378,
  204065. 65379, 65380, 65382, 65392, 65393, 65438, 65440, 65474, 65482, 65490,
  204066. 65498, 65504, 65506, 65507, 65508, 65509, 65512, 65513, 65517, 65529,
  204067. 65532, 0, 13, 40, 60, 63, 80, 128, 256, 263,
  204068. 311, 320, 373, 377, 394, 400, 464, 509, 640, 672,
  204069. 768, 800, 816, 833, 834, 842, 896, 927, 928, 968,
  204070. 976, 977, 1024, 1064, 1104, 1184, 2048, 2056, 2058, 2103,
  204071. 2108, 2111, 2135, 2136, 2304, 2326, 2335, 2336, 2367, 2432,
  204072. 2494, 2560, 2561, 2565, 2572, 2576, 2581, 2585, 2616, 2623,
  204073. 2624, 2640, 2656, 2685, 2687, 2816, 2873, 2880, 2904, 2912,
  204074. 2936, 3072, 3680, 4096, 4097, 4098, 4099, 4152, 4167, 4178,
  204075. 4198, 4224, 4226, 4227, 4272, 4275, 4279, 4281, 4283, 4285,
  204076. 4286, 4304, 4336, 4352, 4355, 4391, 4396, 4397, 4406, 4416,
  204077. 4480, 4482, 4483, 4531, 4534, 4543, 4545, 4549, 4560, 5760,
  204078. 5803, 5804, 5805, 5806, 5808, 5814, 5815, 5824, 8192, 9216,
  204079. 9328, 12288, 26624, 28416, 28496, 28497, 28559, 28563, 45056, 53248,
  204080. 53504, 53545, 53605, 53607, 53610, 53613, 53619, 53627, 53635, 53637,
  204081. 53644, 53674, 53678, 53760, 53826, 53829, 54016, 54112, 54272, 54298,
  204082. 54324, 54350, 54358, 54376, 54402, 54428, 54430, 54434, 54437, 54441,
  204083. 54446, 54454, 54459, 54461, 54469, 54480, 54506, 54532, 54535, 54541,
  204084. 54550, 54558, 54584, 54587, 54592, 54598, 54602, 54610, 54636, 54662,
  204085. 54688, 54714, 54740, 54766, 54792, 54818, 54844, 54870, 54896, 54922,
  204086. 54952, 54977, 54978, 55003, 55004, 55010, 55035, 55036, 55061, 55062,
  204087. 55068, 55093, 55094, 55119, 55120, 55126, 55151, 55152, 55177, 55178,
  204088. 55184, 55209, 55210, 55235, 55236, 55242, 55246, 60928, 60933, 60961,
  204089. 60964, 60967, 60969, 60980, 60985, 60987, 60994, 60999, 61001, 61003,
  204090. 61005, 61009, 61012, 61015, 61017, 61019, 61021, 61023, 61025, 61028,
  204091. 61031, 61036, 61044, 61049, 61054, 61056, 61067, 61089, 61093, 61099,
  204092. 61168, 61440, 61488, 61600, 61617, 61633, 61649, 61696, 61712, 61744,
  204093. 61808, 61926, 61968, 62016, 62032, 62208, 62256, 62263, 62336, 62368,
  204094. 62406, 62432, 62464, 62528, 62530, 62713, 62720, 62784, 62800, 62971,
  204095. 63045, 63104, 63232, 0, 42710, 42752, 46900, 46912, 47133, 63488,
  204096. 1, 32, 256, 0, 65533,
  204097. };
  204098. static u16 aFts5UnicodeData[] = {
  204099. 1025, 61, 117, 55, 117, 54, 50, 53, 57, 53,
  204100. 49, 85, 333, 85, 121, 85, 841, 54, 53, 50,
  204101. 56, 48, 56, 837, 54, 57, 50, 57, 1057, 61,
  204102. 53, 151, 58, 53, 56, 58, 39, 52, 57, 34,
  204103. 58, 56, 58, 57, 79, 56, 37, 85, 56, 47,
  204104. 39, 51, 111, 53, 745, 57, 233, 773, 57, 261,
  204105. 1822, 37, 542, 37, 1534, 222, 69, 73, 37, 126,
  204106. 126, 73, 69, 137, 37, 73, 37, 105, 101, 73,
  204107. 37, 73, 37, 190, 158, 37, 126, 126, 73, 37,
  204108. 126, 94, 37, 39, 94, 69, 135, 41, 40, 37,
  204109. 41, 40, 37, 41, 40, 37, 542, 37, 606, 37,
  204110. 41, 40, 37, 126, 73, 37, 1886, 197, 73, 37,
  204111. 73, 69, 126, 105, 37, 286, 2181, 39, 869, 582,
  204112. 152, 390, 472, 166, 248, 38, 56, 38, 568, 3596,
  204113. 158, 38, 56, 94, 38, 101, 53, 88, 41, 53,
  204114. 105, 41, 73, 37, 553, 297, 1125, 94, 37, 105,
  204115. 101, 798, 133, 94, 57, 126, 94, 37, 1641, 1541,
  204116. 1118, 58, 172, 75, 1790, 478, 37, 2846, 1225, 38,
  204117. 213, 1253, 53, 49, 55, 1452, 49, 44, 53, 76,
  204118. 53, 76, 53, 44, 871, 103, 85, 162, 121, 85,
  204119. 55, 85, 90, 364, 53, 85, 1031, 38, 327, 684,
  204120. 333, 149, 71, 44, 3175, 53, 39, 236, 34, 58,
  204121. 204, 70, 76, 58, 140, 71, 333, 103, 90, 39,
  204122. 469, 34, 39, 44, 967, 876, 2855, 364, 39, 333,
  204123. 1063, 300, 70, 58, 117, 38, 711, 140, 38, 300,
  204124. 38, 108, 38, 172, 501, 807, 108, 53, 39, 359,
  204125. 876, 108, 42, 1735, 44, 42, 44, 39, 106, 268,
  204126. 138, 44, 74, 39, 236, 327, 76, 85, 333, 53,
  204127. 38, 199, 231, 44, 74, 263, 71, 711, 231, 39,
  204128. 135, 44, 39, 106, 140, 74, 74, 44, 39, 42,
  204129. 71, 103, 76, 333, 71, 87, 207, 58, 55, 76,
  204130. 42, 199, 71, 711, 231, 71, 71, 71, 44, 106,
  204131. 76, 76, 108, 44, 135, 39, 333, 76, 103, 44,
  204132. 76, 42, 295, 103, 711, 231, 71, 167, 44, 39,
  204133. 106, 172, 76, 42, 74, 44, 39, 71, 76, 333,
  204134. 53, 55, 44, 74, 263, 71, 711, 231, 71, 167,
  204135. 44, 39, 42, 44, 42, 140, 74, 74, 44, 44,
  204136. 42, 71, 103, 76, 333, 58, 39, 207, 44, 39,
  204137. 199, 103, 135, 71, 39, 71, 71, 103, 391, 74,
  204138. 44, 74, 106, 106, 44, 39, 42, 333, 111, 218,
  204139. 55, 58, 106, 263, 103, 743, 327, 167, 39, 108,
  204140. 138, 108, 140, 76, 71, 71, 76, 333, 239, 58,
  204141. 74, 263, 103, 743, 327, 167, 44, 39, 42, 44,
  204142. 170, 44, 74, 74, 76, 74, 39, 71, 76, 333,
  204143. 71, 74, 263, 103, 1319, 39, 106, 140, 106, 106,
  204144. 44, 39, 42, 71, 76, 333, 207, 58, 199, 74,
  204145. 583, 775, 295, 39, 231, 44, 106, 108, 44, 266,
  204146. 74, 53, 1543, 44, 71, 236, 55, 199, 38, 268,
  204147. 53, 333, 85, 71, 39, 71, 39, 39, 135, 231,
  204148. 103, 39, 39, 71, 135, 44, 71, 204, 76, 39,
  204149. 167, 38, 204, 333, 135, 39, 122, 501, 58, 53,
  204150. 122, 76, 218, 333, 335, 58, 44, 58, 44, 58,
  204151. 44, 54, 50, 54, 50, 74, 263, 1159, 460, 42,
  204152. 172, 53, 76, 167, 364, 1164, 282, 44, 218, 90,
  204153. 181, 154, 85, 1383, 74, 140, 42, 204, 42, 76,
  204154. 74, 76, 39, 333, 213, 199, 74, 76, 135, 108,
  204155. 39, 106, 71, 234, 103, 140, 423, 44, 74, 76,
  204156. 202, 44, 39, 42, 333, 106, 44, 90, 1225, 41,
  204157. 41, 1383, 53, 38, 10631, 135, 231, 39, 135, 1319,
  204158. 135, 1063, 135, 231, 39, 135, 487, 1831, 135, 2151,
  204159. 108, 309, 655, 519, 346, 2727, 49, 19847, 85, 551,
  204160. 61, 839, 54, 50, 2407, 117, 110, 423, 135, 108,
  204161. 583, 108, 85, 583, 76, 423, 103, 76, 1671, 76,
  204162. 42, 236, 266, 44, 74, 364, 117, 38, 117, 55,
  204163. 39, 44, 333, 335, 213, 49, 149, 108, 61, 333,
  204164. 1127, 38, 1671, 1319, 44, 39, 2247, 935, 108, 138,
  204165. 76, 106, 74, 44, 202, 108, 58, 85, 333, 967,
  204166. 167, 1415, 554, 231, 74, 333, 47, 1114, 743, 76,
  204167. 106, 85, 1703, 42, 44, 42, 236, 44, 42, 44,
  204168. 74, 268, 202, 332, 44, 333, 333, 245, 38, 213,
  204169. 140, 42, 1511, 44, 42, 172, 42, 44, 170, 44,
  204170. 74, 231, 333, 245, 346, 300, 314, 76, 42, 967,
  204171. 42, 140, 74, 76, 42, 44, 74, 71, 333, 1415,
  204172. 44, 42, 76, 106, 44, 42, 108, 74, 149, 1159,
  204173. 266, 268, 74, 76, 181, 333, 103, 333, 967, 198,
  204174. 85, 277, 108, 53, 428, 42, 236, 135, 44, 135,
  204175. 74, 44, 71, 1413, 2022, 421, 38, 1093, 1190, 1260,
  204176. 140, 4830, 261, 3166, 261, 265, 197, 201, 261, 265,
  204177. 261, 265, 197, 201, 261, 41, 41, 41, 94, 229,
  204178. 265, 453, 261, 264, 261, 264, 261, 264, 165, 69,
  204179. 137, 40, 56, 37, 120, 101, 69, 137, 40, 120,
  204180. 133, 69, 137, 120, 261, 169, 120, 101, 69, 137,
  204181. 40, 88, 381, 162, 209, 85, 52, 51, 54, 84,
  204182. 51, 54, 52, 277, 59, 60, 162, 61, 309, 52,
  204183. 51, 149, 80, 117, 57, 54, 50, 373, 57, 53,
  204184. 48, 341, 61, 162, 194, 47, 38, 207, 121, 54,
  204185. 50, 38, 335, 121, 54, 50, 422, 855, 428, 139,
  204186. 44, 107, 396, 90, 41, 154, 41, 90, 37, 105,
  204187. 69, 105, 37, 58, 41, 90, 57, 169, 218, 41,
  204188. 58, 41, 58, 41, 58, 137, 58, 37, 137, 37,
  204189. 135, 37, 90, 69, 73, 185, 94, 101, 58, 57,
  204190. 90, 37, 58, 527, 1134, 94, 142, 47, 185, 186,
  204191. 89, 154, 57, 90, 57, 90, 57, 250, 57, 1018,
  204192. 89, 90, 57, 58, 57, 1018, 8601, 282, 153, 666,
  204193. 89, 250, 54, 50, 2618, 57, 986, 825, 1306, 217,
  204194. 602, 1274, 378, 1935, 2522, 719, 5882, 57, 314, 57,
  204195. 1754, 281, 3578, 57, 4634, 3322, 54, 50, 54, 50,
  204196. 54, 50, 54, 50, 54, 50, 54, 50, 54, 50,
  204197. 975, 1434, 185, 54, 50, 1017, 54, 50, 54, 50,
  204198. 54, 50, 54, 50, 54, 50, 537, 8218, 4217, 54,
  204199. 50, 54, 50, 54, 50, 54, 50, 54, 50, 54,
  204200. 50, 54, 50, 54, 50, 54, 50, 54, 50, 54,
  204201. 50, 2041, 54, 50, 54, 50, 1049, 54, 50, 8281,
  204202. 1562, 697, 90, 217, 346, 1513, 1509, 126, 73, 69,
  204203. 254, 105, 37, 94, 37, 94, 165, 70, 105, 37,
  204204. 3166, 37, 218, 158, 108, 94, 149, 47, 85, 1221,
  204205. 37, 37, 1799, 38, 53, 44, 743, 231, 231, 231,
  204206. 231, 231, 231, 231, 231, 1036, 85, 52, 51, 52,
  204207. 51, 117, 52, 51, 53, 52, 51, 309, 49, 85,
  204208. 49, 53, 52, 51, 85, 52, 51, 54, 50, 54,
  204209. 50, 54, 50, 54, 50, 181, 38, 341, 81, 858,
  204210. 2874, 6874, 410, 61, 117, 58, 38, 39, 46, 54,
  204211. 50, 54, 50, 54, 50, 54, 50, 54, 50, 90,
  204212. 54, 50, 54, 50, 54, 50, 54, 50, 49, 54,
  204213. 82, 58, 302, 140, 74, 49, 166, 90, 110, 38,
  204214. 39, 53, 90, 2759, 76, 88, 70, 39, 49, 2887,
  204215. 53, 102, 39, 1319, 3015, 90, 143, 346, 871, 1178,
  204216. 519, 1018, 335, 986, 271, 58, 495, 1050, 335, 1274,
  204217. 495, 2042, 8218, 39, 39, 2074, 39, 39, 679, 38,
  204218. 36583, 1786, 1287, 198, 85, 8583, 38, 117, 519, 333,
  204219. 71, 1502, 39, 44, 107, 53, 332, 53, 38, 798,
  204220. 44, 2247, 334, 76, 213, 760, 294, 88, 478, 69,
  204221. 2014, 38, 261, 190, 350, 38, 88, 158, 158, 382,
  204222. 70, 37, 231, 44, 103, 44, 135, 44, 743, 74,
  204223. 76, 42, 154, 207, 90, 55, 58, 1671, 149, 74,
  204224. 1607, 522, 44, 85, 333, 588, 199, 117, 39, 333,
  204225. 903, 268, 85, 743, 364, 74, 53, 935, 108, 42,
  204226. 1511, 44, 74, 140, 74, 44, 138, 437, 38, 333,
  204227. 85, 1319, 204, 74, 76, 74, 76, 103, 44, 263,
  204228. 44, 42, 333, 149, 519, 38, 199, 122, 39, 42,
  204229. 1543, 44, 39, 108, 71, 76, 167, 76, 39, 44,
  204230. 39, 71, 38, 85, 359, 42, 76, 74, 85, 39,
  204231. 70, 42, 44, 199, 199, 199, 231, 231, 1127, 74,
  204232. 44, 74, 44, 74, 53, 42, 44, 333, 39, 39,
  204233. 743, 1575, 36, 68, 68, 36, 63, 63, 11719, 3399,
  204234. 229, 165, 39, 44, 327, 57, 423, 167, 39, 71,
  204235. 71, 3463, 536, 11623, 54, 50, 2055, 1735, 391, 55,
  204236. 58, 524, 245, 54, 50, 53, 236, 53, 81, 80,
  204237. 54, 50, 54, 50, 54, 50, 54, 50, 54, 50,
  204238. 54, 50, 54, 50, 54, 50, 85, 54, 50, 149,
  204239. 112, 117, 149, 49, 54, 50, 54, 50, 54, 50,
  204240. 117, 57, 49, 121, 53, 55, 85, 167, 4327, 34,
  204241. 117, 55, 117, 54, 50, 53, 57, 53, 49, 85,
  204242. 333, 85, 121, 85, 841, 54, 53, 50, 56, 48,
  204243. 56, 837, 54, 57, 50, 57, 54, 50, 53, 54,
  204244. 50, 85, 327, 38, 1447, 70, 999, 199, 199, 199,
  204245. 103, 87, 57, 56, 58, 87, 58, 153, 90, 98,
  204246. 90, 391, 839, 615, 71, 487, 455, 3943, 117, 1455,
  204247. 314, 1710, 143, 570, 47, 410, 1466, 44, 935, 1575,
  204248. 999, 143, 551, 46, 263, 46, 967, 53, 1159, 263,
  204249. 53, 174, 1289, 1285, 2503, 333, 199, 39, 1415, 71,
  204250. 39, 743, 53, 271, 711, 207, 53, 839, 53, 1799,
  204251. 71, 39, 108, 76, 140, 135, 103, 871, 108, 44,
  204252. 271, 309, 935, 79, 53, 1735, 245, 711, 271, 615,
  204253. 271, 2343, 1007, 42, 44, 42, 1703, 492, 245, 655,
  204254. 333, 76, 42, 1447, 106, 140, 74, 76, 85, 34,
  204255. 149, 807, 333, 108, 1159, 172, 42, 268, 333, 149,
  204256. 76, 42, 1543, 106, 300, 74, 135, 149, 333, 1383,
  204257. 44, 42, 44, 74, 204, 42, 44, 333, 28135, 3182,
  204258. 149, 34279, 18215, 2215, 39, 1482, 140, 422, 71, 7898,
  204259. 1274, 1946, 74, 108, 122, 202, 258, 268, 90, 236,
  204260. 986, 140, 1562, 2138, 108, 58, 2810, 591, 841, 837,
  204261. 841, 229, 581, 841, 837, 41, 73, 41, 73, 137,
  204262. 265, 133, 37, 229, 357, 841, 837, 73, 137, 265,
  204263. 233, 837, 73, 137, 169, 41, 233, 837, 841, 837,
  204264. 841, 837, 841, 837, 841, 837, 841, 837, 841, 901,
  204265. 809, 57, 805, 57, 197, 809, 57, 805, 57, 197,
  204266. 809, 57, 805, 57, 197, 809, 57, 805, 57, 197,
  204267. 809, 57, 805, 57, 197, 94, 1613, 135, 871, 71,
  204268. 39, 39, 327, 135, 39, 39, 39, 39, 39, 39,
  204269. 103, 71, 39, 39, 39, 39, 39, 39, 71, 39,
  204270. 135, 231, 135, 135, 39, 327, 551, 103, 167, 551,
  204271. 89, 1434, 3226, 506, 474, 506, 506, 367, 1018, 1946,
  204272. 1402, 954, 1402, 314, 90, 1082, 218, 2266, 666, 1210,
  204273. 186, 570, 2042, 58, 5850, 154, 2010, 154, 794, 2266,
  204274. 378, 2266, 3738, 39, 39, 39, 39, 39, 39, 17351,
  204275. 34, 3074, 7692, 63, 63,
  204276. };
  204277. static int sqlite3Fts5UnicodeCategory(int iCode) {
  204278. int iRes = -1;
  204279. int iHi;
  204280. int iLo;
  204281. int ret;
  204282. u16 iKey;
  204283. if( iCode>=(1<<20) ){
  204284. return 0;
  204285. }
  204286. iLo = aFts5UnicodeBlock[(iCode>>16)];
  204287. iHi = aFts5UnicodeBlock[1+(iCode>>16)];
  204288. iKey = (iCode & 0xFFFF);
  204289. while( iHi>iLo ){
  204290. int iTest = (iHi + iLo) / 2;
  204291. assert( iTest>=iLo && iTest<iHi );
  204292. if( iKey>=aFts5UnicodeMap[iTest] ){
  204293. iRes = iTest;
  204294. iLo = iTest+1;
  204295. }else{
  204296. iHi = iTest;
  204297. }
  204298. }
  204299. if( iRes<0 ) return 0;
  204300. if( iKey>=(aFts5UnicodeMap[iRes]+(aFts5UnicodeData[iRes]>>5)) ) return 0;
  204301. ret = aFts5UnicodeData[iRes] & 0x1F;
  204302. if( ret!=30 ) return ret;
  204303. return ((iKey - aFts5UnicodeMap[iRes]) & 0x01) ? 5 : 9;
  204304. }
  204305. static void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){
  204306. int i = 0;
  204307. int iTbl = 0;
  204308. while( i<128 ){
  204309. int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ];
  204310. int n = (aFts5UnicodeData[iTbl] >> 5) + i;
  204311. for(; i<128 && i<n; i++){
  204312. aAscii[i] = (u8)bToken;
  204313. }
  204314. iTbl++;
  204315. }
  204316. }
  204317. /*
  204318. ** 2015 May 30
  204319. **
  204320. ** The author disclaims copyright to this source code. In place of
  204321. ** a legal notice, here is a blessing:
  204322. **
  204323. ** May you do good and not evil.
  204324. ** May you find forgiveness for yourself and forgive others.
  204325. ** May you share freely, never taking more than you give.
  204326. **
  204327. ******************************************************************************
  204328. **
  204329. ** Routines for varint serialization and deserialization.
  204330. */
  204331. /* #include "fts5Int.h" */
  204332. /*
  204333. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  204334. ** Except, this version does handle the single byte case that the core
  204335. ** version depends on being handled before its function is called.
  204336. */
  204337. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  204338. u32 a,b;
  204339. /* The 1-byte case. Overwhelmingly the most common. */
  204340. a = *p;
  204341. /* a: p0 (unmasked) */
  204342. if (!(a&0x80))
  204343. {
  204344. /* Values between 0 and 127 */
  204345. *v = a;
  204346. return 1;
  204347. }
  204348. /* The 2-byte case */
  204349. p++;
  204350. b = *p;
  204351. /* b: p1 (unmasked) */
  204352. if (!(b&0x80))
  204353. {
  204354. /* Values between 128 and 16383 */
  204355. a &= 0x7f;
  204356. a = a<<7;
  204357. *v = a | b;
  204358. return 2;
  204359. }
  204360. /* The 3-byte case */
  204361. p++;
  204362. a = a<<14;
  204363. a |= *p;
  204364. /* a: p0<<14 | p2 (unmasked) */
  204365. if (!(a&0x80))
  204366. {
  204367. /* Values between 16384 and 2097151 */
  204368. a &= (0x7f<<14)|(0x7f);
  204369. b &= 0x7f;
  204370. b = b<<7;
  204371. *v = a | b;
  204372. return 3;
  204373. }
  204374. /* A 32-bit varint is used to store size information in btrees.
  204375. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  204376. ** A 3-byte varint is sufficient, for example, to record the size
  204377. ** of a 1048569-byte BLOB or string.
  204378. **
  204379. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  204380. ** rare larger cases can be handled by the slower 64-bit varint
  204381. ** routine.
  204382. */
  204383. {
  204384. u64 v64;
  204385. u8 n;
  204386. p -= 2;
  204387. n = sqlite3Fts5GetVarint(p, &v64);
  204388. *v = (u32)v64;
  204389. assert( n>3 && n<=9 );
  204390. return n;
  204391. }
  204392. }
  204393. /*
  204394. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  204395. ** are defined here rather than simply putting the constant expressions
  204396. ** inline in order to work around bugs in the RVT compiler.
  204397. **
  204398. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  204399. **
  204400. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  204401. */
  204402. #define SLOT_2_0 0x001fc07f
  204403. #define SLOT_4_2_0 0xf01fc07f
  204404. /*
  204405. ** Read a 64-bit variable-length integer from memory starting at p[0].
  204406. ** Return the number of bytes read. The value is stored in *v.
  204407. */
  204408. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  204409. u32 a,b,s;
  204410. a = *p;
  204411. /* a: p0 (unmasked) */
  204412. if (!(a&0x80))
  204413. {
  204414. *v = a;
  204415. return 1;
  204416. }
  204417. p++;
  204418. b = *p;
  204419. /* b: p1 (unmasked) */
  204420. if (!(b&0x80))
  204421. {
  204422. a &= 0x7f;
  204423. a = a<<7;
  204424. a |= b;
  204425. *v = a;
  204426. return 2;
  204427. }
  204428. /* Verify that constants are precomputed correctly */
  204429. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  204430. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  204431. p++;
  204432. a = a<<14;
  204433. a |= *p;
  204434. /* a: p0<<14 | p2 (unmasked) */
  204435. if (!(a&0x80))
  204436. {
  204437. a &= SLOT_2_0;
  204438. b &= 0x7f;
  204439. b = b<<7;
  204440. a |= b;
  204441. *v = a;
  204442. return 3;
  204443. }
  204444. /* CSE1 from below */
  204445. a &= SLOT_2_0;
  204446. p++;
  204447. b = b<<14;
  204448. b |= *p;
  204449. /* b: p1<<14 | p3 (unmasked) */
  204450. if (!(b&0x80))
  204451. {
  204452. b &= SLOT_2_0;
  204453. /* moved CSE1 up */
  204454. /* a &= (0x7f<<14)|(0x7f); */
  204455. a = a<<7;
  204456. a |= b;
  204457. *v = a;
  204458. return 4;
  204459. }
  204460. /* a: p0<<14 | p2 (masked) */
  204461. /* b: p1<<14 | p3 (unmasked) */
  204462. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  204463. /* moved CSE1 up */
  204464. /* a &= (0x7f<<14)|(0x7f); */
  204465. b &= SLOT_2_0;
  204466. s = a;
  204467. /* s: p0<<14 | p2 (masked) */
  204468. p++;
  204469. a = a<<14;
  204470. a |= *p;
  204471. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  204472. if (!(a&0x80))
  204473. {
  204474. /* we can skip these cause they were (effectively) done above in calc'ing s */
  204475. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  204476. /* b &= (0x7f<<14)|(0x7f); */
  204477. b = b<<7;
  204478. a |= b;
  204479. s = s>>18;
  204480. *v = ((u64)s)<<32 | a;
  204481. return 5;
  204482. }
  204483. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  204484. s = s<<7;
  204485. s |= b;
  204486. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  204487. p++;
  204488. b = b<<14;
  204489. b |= *p;
  204490. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  204491. if (!(b&0x80))
  204492. {
  204493. /* we can skip this cause it was (effectively) done above in calc'ing s */
  204494. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  204495. a &= SLOT_2_0;
  204496. a = a<<7;
  204497. a |= b;
  204498. s = s>>18;
  204499. *v = ((u64)s)<<32 | a;
  204500. return 6;
  204501. }
  204502. p++;
  204503. a = a<<14;
  204504. a |= *p;
  204505. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  204506. if (!(a&0x80))
  204507. {
  204508. a &= SLOT_4_2_0;
  204509. b &= SLOT_2_0;
  204510. b = b<<7;
  204511. a |= b;
  204512. s = s>>11;
  204513. *v = ((u64)s)<<32 | a;
  204514. return 7;
  204515. }
  204516. /* CSE2 from below */
  204517. a &= SLOT_2_0;
  204518. p++;
  204519. b = b<<14;
  204520. b |= *p;
  204521. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  204522. if (!(b&0x80))
  204523. {
  204524. b &= SLOT_4_2_0;
  204525. /* moved CSE2 up */
  204526. /* a &= (0x7f<<14)|(0x7f); */
  204527. a = a<<7;
  204528. a |= b;
  204529. s = s>>4;
  204530. *v = ((u64)s)<<32 | a;
  204531. return 8;
  204532. }
  204533. p++;
  204534. a = a<<15;
  204535. a |= *p;
  204536. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  204537. /* moved CSE2 up */
  204538. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  204539. b &= SLOT_2_0;
  204540. b = b<<8;
  204541. a |= b;
  204542. s = s<<4;
  204543. b = p[-4];
  204544. b &= 0x7f;
  204545. b = b>>3;
  204546. s |= b;
  204547. *v = ((u64)s)<<32 | a;
  204548. return 9;
  204549. }
  204550. /*
  204551. ** The variable-length integer encoding is as follows:
  204552. **
  204553. ** KEY:
  204554. ** A = 0xxxxxxx 7 bits of data and one flag bit
  204555. ** B = 1xxxxxxx 7 bits of data and one flag bit
  204556. ** C = xxxxxxxx 8 bits of data
  204557. **
  204558. ** 7 bits - A
  204559. ** 14 bits - BA
  204560. ** 21 bits - BBA
  204561. ** 28 bits - BBBA
  204562. ** 35 bits - BBBBA
  204563. ** 42 bits - BBBBBA
  204564. ** 49 bits - BBBBBBA
  204565. ** 56 bits - BBBBBBBA
  204566. ** 64 bits - BBBBBBBBC
  204567. */
  204568. #ifdef SQLITE_NOINLINE
  204569. # define FTS5_NOINLINE SQLITE_NOINLINE
  204570. #else
  204571. # define FTS5_NOINLINE
  204572. #endif
  204573. /*
  204574. ** Write a 64-bit variable-length integer to memory starting at p[0].
  204575. ** The length of data write will be between 1 and 9 bytes. The number
  204576. ** of bytes written is returned.
  204577. **
  204578. ** A variable-length integer consists of the lower 7 bits of each byte
  204579. ** for all bytes that have the 8th bit set and one byte with the 8th
  204580. ** bit clear. Except, if we get to the 9th byte, it stores the full
  204581. ** 8 bits and is the last byte.
  204582. */
  204583. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  204584. int i, j, n;
  204585. u8 buf[10];
  204586. if( v & (((u64)0xff000000)<<32) ){
  204587. p[8] = (u8)v;
  204588. v >>= 8;
  204589. for(i=7; i>=0; i--){
  204590. p[i] = (u8)((v & 0x7f) | 0x80);
  204591. v >>= 7;
  204592. }
  204593. return 9;
  204594. }
  204595. n = 0;
  204596. do{
  204597. buf[n++] = (u8)((v & 0x7f) | 0x80);
  204598. v >>= 7;
  204599. }while( v!=0 );
  204600. buf[0] &= 0x7f;
  204601. assert( n<=9 );
  204602. for(i=0, j=n-1; j>=0; j--, i++){
  204603. p[i] = buf[j];
  204604. }
  204605. return n;
  204606. }
  204607. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  204608. if( v<=0x7f ){
  204609. p[0] = v&0x7f;
  204610. return 1;
  204611. }
  204612. if( v<=0x3fff ){
  204613. p[0] = ((v>>7)&0x7f)|0x80;
  204614. p[1] = v&0x7f;
  204615. return 2;
  204616. }
  204617. return fts5PutVarint64(p,v);
  204618. }
  204619. static int sqlite3Fts5GetVarintLen(u32 iVal){
  204620. #if 0
  204621. if( iVal<(1 << 7 ) ) return 1;
  204622. #endif
  204623. assert( iVal>=(1 << 7) );
  204624. if( iVal<(1 << 14) ) return 2;
  204625. if( iVal<(1 << 21) ) return 3;
  204626. if( iVal<(1 << 28) ) return 4;
  204627. return 5;
  204628. }
  204629. /*
  204630. ** 2015 May 08
  204631. **
  204632. ** The author disclaims copyright to this source code. In place of
  204633. ** a legal notice, here is a blessing:
  204634. **
  204635. ** May you do good and not evil.
  204636. ** May you find forgiveness for yourself and forgive others.
  204637. ** May you share freely, never taking more than you give.
  204638. **
  204639. ******************************************************************************
  204640. **
  204641. ** This is an SQLite virtual table module implementing direct access to an
  204642. ** existing FTS5 index. The module may create several different types of
  204643. ** tables:
  204644. **
  204645. ** col:
  204646. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  204647. **
  204648. ** One row for each term/column combination. The value of $doc is set to
  204649. ** the number of fts5 rows that contain at least one instance of term
  204650. ** $term within column $col. Field $cnt is set to the total number of
  204651. ** instances of term $term in column $col (in any row of the fts5 table).
  204652. **
  204653. ** row:
  204654. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  204655. **
  204656. ** One row for each term in the database. The value of $doc is set to
  204657. ** the number of fts5 rows that contain at least one instance of term
  204658. ** $term. Field $cnt is set to the total number of instances of term
  204659. ** $term in the database.
  204660. **
  204661. ** instance:
  204662. ** CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
  204663. **
  204664. ** One row for each term instance in the database.
  204665. */
  204666. /* #include "fts5Int.h" */
  204667. typedef struct Fts5VocabTable Fts5VocabTable;
  204668. typedef struct Fts5VocabCursor Fts5VocabCursor;
  204669. struct Fts5VocabTable {
  204670. sqlite3_vtab base;
  204671. char *zFts5Tbl; /* Name of fts5 table */
  204672. char *zFts5Db; /* Db containing fts5 table */
  204673. sqlite3 *db; /* Database handle */
  204674. Fts5Global *pGlobal; /* FTS5 global object for this database */
  204675. int eType; /* FTS5_VOCAB_COL, ROW or INSTANCE */
  204676. };
  204677. struct Fts5VocabCursor {
  204678. sqlite3_vtab_cursor base;
  204679. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  204680. Fts5Index *pIndex; /* Associated FTS5 index */
  204681. int bEof; /* True if this cursor is at EOF */
  204682. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  204683. int nLeTerm; /* Size of zLeTerm in bytes */
  204684. char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
  204685. /* These are used by 'col' tables only */
  204686. Fts5Config *pConfig; /* Fts5 table configuration */
  204687. int iCol;
  204688. i64 *aCnt;
  204689. i64 *aDoc;
  204690. /* Output values used by all tables. */
  204691. i64 rowid; /* This table's current rowid value */
  204692. Fts5Buffer term; /* Current value of 'term' column */
  204693. /* Output values Used by 'instance' tables only */
  204694. i64 iInstPos;
  204695. int iInstOff;
  204696. };
  204697. #define FTS5_VOCAB_COL 0
  204698. #define FTS5_VOCAB_ROW 1
  204699. #define FTS5_VOCAB_INSTANCE 2
  204700. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  204701. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  204702. #define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
  204703. /*
  204704. ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
  204705. */
  204706. #define FTS5_VOCAB_TERM_EQ 0x01
  204707. #define FTS5_VOCAB_TERM_GE 0x02
  204708. #define FTS5_VOCAB_TERM_LE 0x04
  204709. /*
  204710. ** Translate a string containing an fts5vocab table type to an
  204711. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  204712. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  204713. ** and return SQLITE_ERROR.
  204714. */
  204715. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  204716. int rc = SQLITE_OK;
  204717. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  204718. if( rc==SQLITE_OK ){
  204719. sqlite3Fts5Dequote(zCopy);
  204720. if( sqlite3_stricmp(zCopy, "col")==0 ){
  204721. *peType = FTS5_VOCAB_COL;
  204722. }else
  204723. if( sqlite3_stricmp(zCopy, "row")==0 ){
  204724. *peType = FTS5_VOCAB_ROW;
  204725. }else
  204726. if( sqlite3_stricmp(zCopy, "instance")==0 ){
  204727. *peType = FTS5_VOCAB_INSTANCE;
  204728. }else
  204729. {
  204730. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  204731. rc = SQLITE_ERROR;
  204732. }
  204733. sqlite3_free(zCopy);
  204734. }
  204735. return rc;
  204736. }
  204737. /*
  204738. ** The xDisconnect() virtual table method.
  204739. */
  204740. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  204741. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  204742. sqlite3_free(pTab);
  204743. return SQLITE_OK;
  204744. }
  204745. /*
  204746. ** The xDestroy() virtual table method.
  204747. */
  204748. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  204749. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  204750. sqlite3_free(pTab);
  204751. return SQLITE_OK;
  204752. }
  204753. /*
  204754. ** This function is the implementation of both the xConnect and xCreate
  204755. ** methods of the FTS3 virtual table.
  204756. **
  204757. ** The argv[] array contains the following:
  204758. **
  204759. ** argv[0] -> module name ("fts5vocab")
  204760. ** argv[1] -> database name
  204761. ** argv[2] -> table name
  204762. **
  204763. ** then:
  204764. **
  204765. ** argv[3] -> name of fts5 table
  204766. ** argv[4] -> type of fts5vocab table
  204767. **
  204768. ** or, for tables in the TEMP schema only.
  204769. **
  204770. ** argv[3] -> name of fts5 tables database
  204771. ** argv[4] -> name of fts5 table
  204772. ** argv[5] -> type of fts5vocab table
  204773. */
  204774. static int fts5VocabInitVtab(
  204775. sqlite3 *db, /* The SQLite database connection */
  204776. void *pAux, /* Pointer to Fts5Global object */
  204777. int argc, /* Number of elements in argv array */
  204778. const char * const *argv, /* xCreate/xConnect argument array */
  204779. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  204780. char **pzErr /* Write any error message here */
  204781. ){
  204782. const char *azSchema[] = {
  204783. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  204784. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")",
  204785. "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
  204786. };
  204787. Fts5VocabTable *pRet = 0;
  204788. int rc = SQLITE_OK; /* Return code */
  204789. int bDb;
  204790. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  204791. if( argc!=5 && bDb==0 ){
  204792. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  204793. rc = SQLITE_ERROR;
  204794. }else{
  204795. int nByte; /* Bytes of space to allocate */
  204796. const char *zDb = bDb ? argv[3] : argv[1];
  204797. const char *zTab = bDb ? argv[4] : argv[3];
  204798. const char *zType = bDb ? argv[5] : argv[4];
  204799. int nDb = (int)strlen(zDb)+1;
  204800. int nTab = (int)strlen(zTab)+1;
  204801. int eType = 0;
  204802. rc = fts5VocabTableType(zType, pzErr, &eType);
  204803. if( rc==SQLITE_OK ){
  204804. assert( eType>=0 && eType<ArraySize(azSchema) );
  204805. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  204806. }
  204807. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  204808. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  204809. if( pRet ){
  204810. pRet->pGlobal = (Fts5Global*)pAux;
  204811. pRet->eType = eType;
  204812. pRet->db = db;
  204813. pRet->zFts5Tbl = (char*)&pRet[1];
  204814. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  204815. memcpy(pRet->zFts5Tbl, zTab, nTab);
  204816. memcpy(pRet->zFts5Db, zDb, nDb);
  204817. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  204818. sqlite3Fts5Dequote(pRet->zFts5Db);
  204819. }
  204820. }
  204821. *ppVTab = (sqlite3_vtab*)pRet;
  204822. return rc;
  204823. }
  204824. /*
  204825. ** The xConnect() and xCreate() methods for the virtual table. All the
  204826. ** work is done in function fts5VocabInitVtab().
  204827. */
  204828. static int fts5VocabConnectMethod(
  204829. sqlite3 *db, /* Database connection */
  204830. void *pAux, /* Pointer to tokenizer hash table */
  204831. int argc, /* Number of elements in argv array */
  204832. const char * const *argv, /* xCreate/xConnect argument array */
  204833. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  204834. char **pzErr /* OUT: sqlite3_malloc'd error message */
  204835. ){
  204836. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  204837. }
  204838. static int fts5VocabCreateMethod(
  204839. sqlite3 *db, /* Database connection */
  204840. void *pAux, /* Pointer to tokenizer hash table */
  204841. int argc, /* Number of elements in argv array */
  204842. const char * const *argv, /* xCreate/xConnect argument array */
  204843. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  204844. char **pzErr /* OUT: sqlite3_malloc'd error message */
  204845. ){
  204846. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  204847. }
  204848. /*
  204849. ** Implementation of the xBestIndex method.
  204850. **
  204851. ** Only constraints of the form:
  204852. **
  204853. ** term <= ?
  204854. ** term == ?
  204855. ** term >= ?
  204856. **
  204857. ** are interpreted. Less-than and less-than-or-equal are treated
  204858. ** identically, as are greater-than and greater-than-or-equal.
  204859. */
  204860. static int fts5VocabBestIndexMethod(
  204861. sqlite3_vtab *pUnused,
  204862. sqlite3_index_info *pInfo
  204863. ){
  204864. int i;
  204865. int iTermEq = -1;
  204866. int iTermGe = -1;
  204867. int iTermLe = -1;
  204868. int idxNum = 0;
  204869. int nArg = 0;
  204870. UNUSED_PARAM(pUnused);
  204871. for(i=0; i<pInfo->nConstraint; i++){
  204872. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  204873. if( p->usable==0 ) continue;
  204874. if( p->iColumn==0 ){ /* term column */
  204875. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
  204876. if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
  204877. if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
  204878. if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
  204879. if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
  204880. }
  204881. }
  204882. if( iTermEq>=0 ){
  204883. idxNum |= FTS5_VOCAB_TERM_EQ;
  204884. pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
  204885. pInfo->estimatedCost = 100;
  204886. }else{
  204887. pInfo->estimatedCost = 1000000;
  204888. if( iTermGe>=0 ){
  204889. idxNum |= FTS5_VOCAB_TERM_GE;
  204890. pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
  204891. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  204892. }
  204893. if( iTermLe>=0 ){
  204894. idxNum |= FTS5_VOCAB_TERM_LE;
  204895. pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
  204896. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  204897. }
  204898. }
  204899. /* This virtual table always delivers results in ascending order of
  204900. ** the "term" column (column 0). So if the user has requested this
  204901. ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
  204902. ** sqlite3_index_info.orderByConsumed flag to tell the core the results
  204903. ** are already in sorted order. */
  204904. if( pInfo->nOrderBy==1
  204905. && pInfo->aOrderBy[0].iColumn==0
  204906. && pInfo->aOrderBy[0].desc==0
  204907. ){
  204908. pInfo->orderByConsumed = 1;
  204909. }
  204910. pInfo->idxNum = idxNum;
  204911. return SQLITE_OK;
  204912. }
  204913. /*
  204914. ** Implementation of xOpen method.
  204915. */
  204916. static int fts5VocabOpenMethod(
  204917. sqlite3_vtab *pVTab,
  204918. sqlite3_vtab_cursor **ppCsr
  204919. ){
  204920. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  204921. Fts5Index *pIndex = 0;
  204922. Fts5Config *pConfig = 0;
  204923. Fts5VocabCursor *pCsr = 0;
  204924. int rc = SQLITE_OK;
  204925. sqlite3_stmt *pStmt = 0;
  204926. char *zSql = 0;
  204927. zSql = sqlite3Fts5Mprintf(&rc,
  204928. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  204929. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  204930. );
  204931. if( zSql ){
  204932. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  204933. }
  204934. sqlite3_free(zSql);
  204935. assert( rc==SQLITE_OK || pStmt==0 );
  204936. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  204937. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  204938. i64 iId = sqlite3_column_int64(pStmt, 0);
  204939. pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
  204940. }
  204941. if( rc==SQLITE_OK && pIndex==0 ){
  204942. rc = sqlite3_finalize(pStmt);
  204943. pStmt = 0;
  204944. if( rc==SQLITE_OK ){
  204945. pVTab->zErrMsg = sqlite3_mprintf(
  204946. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  204947. );
  204948. rc = SQLITE_ERROR;
  204949. }
  204950. }
  204951. if( rc==SQLITE_OK ){
  204952. int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
  204953. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  204954. }
  204955. if( pCsr ){
  204956. pCsr->pIndex = pIndex;
  204957. pCsr->pStmt = pStmt;
  204958. pCsr->pConfig = pConfig;
  204959. pCsr->aCnt = (i64*)&pCsr[1];
  204960. pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
  204961. }else{
  204962. sqlite3_finalize(pStmt);
  204963. }
  204964. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  204965. return rc;
  204966. }
  204967. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  204968. pCsr->rowid = 0;
  204969. sqlite3Fts5IterClose(pCsr->pIter);
  204970. pCsr->pIter = 0;
  204971. sqlite3_free(pCsr->zLeTerm);
  204972. pCsr->nLeTerm = -1;
  204973. pCsr->zLeTerm = 0;
  204974. }
  204975. /*
  204976. ** Close the cursor. For additional information see the documentation
  204977. ** on the xClose method of the virtual table interface.
  204978. */
  204979. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  204980. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  204981. fts5VocabResetCursor(pCsr);
  204982. sqlite3Fts5BufferFree(&pCsr->term);
  204983. sqlite3_finalize(pCsr->pStmt);
  204984. sqlite3_free(pCsr);
  204985. return SQLITE_OK;
  204986. }
  204987. static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
  204988. int rc = SQLITE_OK;
  204989. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  204990. pCsr->bEof = 1;
  204991. }else{
  204992. const char *zTerm;
  204993. int nTerm;
  204994. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  204995. if( pCsr->nLeTerm>=0 ){
  204996. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  204997. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  204998. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  204999. pCsr->bEof = 1;
  205000. }
  205001. }
  205002. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  205003. }
  205004. return rc;
  205005. }
  205006. static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
  205007. int eDetail = pCsr->pConfig->eDetail;
  205008. int rc = SQLITE_OK;
  205009. Fts5IndexIter *pIter = pCsr->pIter;
  205010. i64 *pp = &pCsr->iInstPos;
  205011. int *po = &pCsr->iInstOff;
  205012. assert( sqlite3Fts5IterEof(pIter)==0 );
  205013. assert( pCsr->bEof==0 );
  205014. while( eDetail==FTS5_DETAIL_NONE
  205015. || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
  205016. ){
  205017. pCsr->iInstPos = 0;
  205018. pCsr->iInstOff = 0;
  205019. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  205020. if( rc==SQLITE_OK ){
  205021. rc = fts5VocabInstanceNewTerm(pCsr);
  205022. if( pCsr->bEof || eDetail==FTS5_DETAIL_NONE ) break;
  205023. }
  205024. if( rc ){
  205025. pCsr->bEof = 1;
  205026. break;
  205027. }
  205028. }
  205029. return rc;
  205030. }
  205031. /*
  205032. ** Advance the cursor to the next row in the table.
  205033. */
  205034. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  205035. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  205036. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  205037. int rc = SQLITE_OK;
  205038. int nCol = pCsr->pConfig->nCol;
  205039. pCsr->rowid++;
  205040. if( pTab->eType==FTS5_VOCAB_INSTANCE ){
  205041. return fts5VocabInstanceNext(pCsr);
  205042. }
  205043. if( pTab->eType==FTS5_VOCAB_COL ){
  205044. for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
  205045. if( pCsr->aDoc[pCsr->iCol] ) break;
  205046. }
  205047. }
  205048. if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
  205049. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  205050. pCsr->bEof = 1;
  205051. }else{
  205052. const char *zTerm;
  205053. int nTerm;
  205054. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  205055. if( pCsr->nLeTerm>=0 ){
  205056. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  205057. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  205058. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  205059. pCsr->bEof = 1;
  205060. return SQLITE_OK;
  205061. }
  205062. }
  205063. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  205064. memset(pCsr->aCnt, 0, nCol * sizeof(i64));
  205065. memset(pCsr->aDoc, 0, nCol * sizeof(i64));
  205066. pCsr->iCol = 0;
  205067. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  205068. while( rc==SQLITE_OK ){
  205069. int eDetail = pCsr->pConfig->eDetail;
  205070. const u8 *pPos; int nPos; /* Position list */
  205071. i64 iPos = 0; /* 64-bit position read from poslist */
  205072. int iOff = 0; /* Current offset within position list */
  205073. pPos = pCsr->pIter->pData;
  205074. nPos = pCsr->pIter->nData;
  205075. switch( pTab->eType ){
  205076. case FTS5_VOCAB_ROW:
  205077. if( eDetail==FTS5_DETAIL_FULL ){
  205078. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  205079. pCsr->aCnt[0]++;
  205080. }
  205081. }
  205082. pCsr->aDoc[0]++;
  205083. break;
  205084. case FTS5_VOCAB_COL:
  205085. if( eDetail==FTS5_DETAIL_FULL ){
  205086. int iCol = -1;
  205087. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  205088. int ii = FTS5_POS2COLUMN(iPos);
  205089. pCsr->aCnt[ii]++;
  205090. if( iCol!=ii ){
  205091. if( ii>=nCol ){
  205092. rc = FTS5_CORRUPT;
  205093. break;
  205094. }
  205095. pCsr->aDoc[ii]++;
  205096. iCol = ii;
  205097. }
  205098. }
  205099. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  205100. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
  205101. assert_nc( iPos>=0 && iPos<nCol );
  205102. if( iPos>=nCol ){
  205103. rc = FTS5_CORRUPT;
  205104. break;
  205105. }
  205106. pCsr->aDoc[iPos]++;
  205107. }
  205108. }else{
  205109. assert( eDetail==FTS5_DETAIL_NONE );
  205110. pCsr->aDoc[0]++;
  205111. }
  205112. break;
  205113. default:
  205114. assert( pTab->eType==FTS5_VOCAB_INSTANCE );
  205115. break;
  205116. }
  205117. if( rc==SQLITE_OK ){
  205118. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  205119. }
  205120. if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
  205121. if( rc==SQLITE_OK ){
  205122. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  205123. if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
  205124. break;
  205125. }
  205126. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  205127. }
  205128. }
  205129. }
  205130. }
  205131. if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  205132. while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
  205133. assert( pCsr->iCol<pCsr->pConfig->nCol );
  205134. }
  205135. return rc;
  205136. }
  205137. /*
  205138. ** This is the xFilter implementation for the virtual table.
  205139. */
  205140. static int fts5VocabFilterMethod(
  205141. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  205142. int idxNum, /* Strategy index */
  205143. const char *zUnused, /* Unused */
  205144. int nUnused, /* Number of elements in apVal */
  205145. sqlite3_value **apVal /* Arguments for the indexing scheme */
  205146. ){
  205147. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  205148. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  205149. int eType = pTab->eType;
  205150. int rc = SQLITE_OK;
  205151. int iVal = 0;
  205152. int f = FTS5INDEX_QUERY_SCAN;
  205153. const char *zTerm = 0;
  205154. int nTerm = 0;
  205155. sqlite3_value *pEq = 0;
  205156. sqlite3_value *pGe = 0;
  205157. sqlite3_value *pLe = 0;
  205158. UNUSED_PARAM2(zUnused, nUnused);
  205159. fts5VocabResetCursor(pCsr);
  205160. if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
  205161. if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
  205162. if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
  205163. if( pEq ){
  205164. zTerm = (const char *)sqlite3_value_text(pEq);
  205165. nTerm = sqlite3_value_bytes(pEq);
  205166. f = 0;
  205167. }else{
  205168. if( pGe ){
  205169. zTerm = (const char *)sqlite3_value_text(pGe);
  205170. nTerm = sqlite3_value_bytes(pGe);
  205171. }
  205172. if( pLe ){
  205173. const char *zCopy = (const char *)sqlite3_value_text(pLe);
  205174. pCsr->nLeTerm = sqlite3_value_bytes(pLe);
  205175. pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
  205176. if( pCsr->zLeTerm==0 ){
  205177. rc = SQLITE_NOMEM;
  205178. }else{
  205179. memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
  205180. }
  205181. }
  205182. }
  205183. if( rc==SQLITE_OK ){
  205184. rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
  205185. }
  205186. if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
  205187. rc = fts5VocabInstanceNewTerm(pCsr);
  205188. }
  205189. if( rc==SQLITE_OK
  205190. && !pCsr->bEof
  205191. && (eType!=FTS5_VOCAB_INSTANCE || pCsr->pConfig->eDetail!=FTS5_DETAIL_NONE)
  205192. ){
  205193. rc = fts5VocabNextMethod(pCursor);
  205194. }
  205195. return rc;
  205196. }
  205197. /*
  205198. ** This is the xEof method of the virtual table. SQLite calls this
  205199. ** routine to find out if it has reached the end of a result set.
  205200. */
  205201. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  205202. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  205203. return pCsr->bEof;
  205204. }
  205205. static int fts5VocabColumnMethod(
  205206. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  205207. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  205208. int iCol /* Index of column to read value from */
  205209. ){
  205210. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  205211. int eDetail = pCsr->pConfig->eDetail;
  205212. int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
  205213. i64 iVal = 0;
  205214. if( iCol==0 ){
  205215. sqlite3_result_text(
  205216. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  205217. );
  205218. }else if( eType==FTS5_VOCAB_COL ){
  205219. assert( iCol==1 || iCol==2 || iCol==3 );
  205220. if( iCol==1 ){
  205221. if( eDetail!=FTS5_DETAIL_NONE ){
  205222. const char *z = pCsr->pConfig->azCol[pCsr->iCol];
  205223. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  205224. }
  205225. }else if( iCol==2 ){
  205226. iVal = pCsr->aDoc[pCsr->iCol];
  205227. }else{
  205228. iVal = pCsr->aCnt[pCsr->iCol];
  205229. }
  205230. }else if( eType==FTS5_VOCAB_ROW ){
  205231. assert( iCol==1 || iCol==2 );
  205232. if( iCol==1 ){
  205233. iVal = pCsr->aDoc[0];
  205234. }else{
  205235. iVal = pCsr->aCnt[0];
  205236. }
  205237. }else{
  205238. assert( eType==FTS5_VOCAB_INSTANCE );
  205239. switch( iCol ){
  205240. case 1:
  205241. sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
  205242. break;
  205243. case 2: {
  205244. int ii = -1;
  205245. if( eDetail==FTS5_DETAIL_FULL ){
  205246. ii = FTS5_POS2COLUMN(pCsr->iInstPos);
  205247. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  205248. ii = (int)pCsr->iInstPos;
  205249. }
  205250. if( ii>=0 && ii<pCsr->pConfig->nCol ){
  205251. const char *z = pCsr->pConfig->azCol[ii];
  205252. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  205253. }
  205254. break;
  205255. }
  205256. default: {
  205257. assert( iCol==3 );
  205258. if( eDetail==FTS5_DETAIL_FULL ){
  205259. int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
  205260. sqlite3_result_int(pCtx, ii);
  205261. }
  205262. break;
  205263. }
  205264. }
  205265. }
  205266. if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
  205267. return SQLITE_OK;
  205268. }
  205269. /*
  205270. ** This is the xRowid method. The SQLite core calls this routine to
  205271. ** retrieve the rowid for the current row of the result set. The
  205272. ** rowid should be written to *pRowid.
  205273. */
  205274. static int fts5VocabRowidMethod(
  205275. sqlite3_vtab_cursor *pCursor,
  205276. sqlite_int64 *pRowid
  205277. ){
  205278. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  205279. *pRowid = pCsr->rowid;
  205280. return SQLITE_OK;
  205281. }
  205282. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  205283. static const sqlite3_module fts5Vocab = {
  205284. /* iVersion */ 2,
  205285. /* xCreate */ fts5VocabCreateMethod,
  205286. /* xConnect */ fts5VocabConnectMethod,
  205287. /* xBestIndex */ fts5VocabBestIndexMethod,
  205288. /* xDisconnect */ fts5VocabDisconnectMethod,
  205289. /* xDestroy */ fts5VocabDestroyMethod,
  205290. /* xOpen */ fts5VocabOpenMethod,
  205291. /* xClose */ fts5VocabCloseMethod,
  205292. /* xFilter */ fts5VocabFilterMethod,
  205293. /* xNext */ fts5VocabNextMethod,
  205294. /* xEof */ fts5VocabEofMethod,
  205295. /* xColumn */ fts5VocabColumnMethod,
  205296. /* xRowid */ fts5VocabRowidMethod,
  205297. /* xUpdate */ 0,
  205298. /* xBegin */ 0,
  205299. /* xSync */ 0,
  205300. /* xCommit */ 0,
  205301. /* xRollback */ 0,
  205302. /* xFindFunction */ 0,
  205303. /* xRename */ 0,
  205304. /* xSavepoint */ 0,
  205305. /* xRelease */ 0,
  205306. /* xRollbackTo */ 0,
  205307. /* xShadowName */ 0
  205308. };
  205309. void *p = (void*)pGlobal;
  205310. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  205311. }
  205312. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  205313. /************** End of fts5.c ************************************************/
  205314. /************** Begin file stmt.c ********************************************/
  205315. /*
  205316. ** 2017-05-31
  205317. **
  205318. ** The author disclaims copyright to this source code. In place of
  205319. ** a legal notice, here is a blessing:
  205320. **
  205321. ** May you do good and not evil.
  205322. ** May you find forgiveness for yourself and forgive others.
  205323. ** May you share freely, never taking more than you give.
  205324. **
  205325. *************************************************************************
  205326. **
  205327. ** This file demonstrates an eponymous virtual table that returns information
  205328. ** about all prepared statements for the database connection.
  205329. **
  205330. ** Usage example:
  205331. **
  205332. ** .load ./stmt
  205333. ** .mode line
  205334. ** .header on
  205335. ** SELECT * FROM stmt;
  205336. */
  205337. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
  205338. #if !defined(SQLITEINT_H)
  205339. /* #include "sqlite3ext.h" */
  205340. #endif
  205341. SQLITE_EXTENSION_INIT1
  205342. /* #include <assert.h> */
  205343. /* #include <string.h> */
  205344. #ifndef SQLITE_OMIT_VIRTUALTABLE
  205345. /* stmt_vtab is a subclass of sqlite3_vtab which will
  205346. ** serve as the underlying representation of a stmt virtual table
  205347. */
  205348. typedef struct stmt_vtab stmt_vtab;
  205349. struct stmt_vtab {
  205350. sqlite3_vtab base; /* Base class - must be first */
  205351. sqlite3 *db; /* Database connection for this stmt vtab */
  205352. };
  205353. /* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
  205354. ** serve as the underlying representation of a cursor that scans
  205355. ** over rows of the result
  205356. */
  205357. typedef struct stmt_cursor stmt_cursor;
  205358. struct stmt_cursor {
  205359. sqlite3_vtab_cursor base; /* Base class - must be first */
  205360. sqlite3 *db; /* Database connection for this cursor */
  205361. sqlite3_stmt *pStmt; /* Statement cursor is currently pointing at */
  205362. sqlite3_int64 iRowid; /* The rowid */
  205363. };
  205364. /*
  205365. ** The stmtConnect() method is invoked to create a new
  205366. ** stmt_vtab that describes the stmt virtual table.
  205367. **
  205368. ** Think of this routine as the constructor for stmt_vtab objects.
  205369. **
  205370. ** All this routine needs to do is:
  205371. **
  205372. ** (1) Allocate the stmt_vtab object and initialize all fields.
  205373. **
  205374. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  205375. ** result set of queries against stmt will look like.
  205376. */
  205377. static int stmtConnect(
  205378. sqlite3 *db,
  205379. void *pAux,
  205380. int argc, const char *const*argv,
  205381. sqlite3_vtab **ppVtab,
  205382. char **pzErr
  205383. ){
  205384. stmt_vtab *pNew;
  205385. int rc;
  205386. /* Column numbers */
  205387. #define STMT_COLUMN_SQL 0 /* SQL for the statement */
  205388. #define STMT_COLUMN_NCOL 1 /* Number of result columns */
  205389. #define STMT_COLUMN_RO 2 /* True if read-only */
  205390. #define STMT_COLUMN_BUSY 3 /* True if currently busy */
  205391. #define STMT_COLUMN_NSCAN 4 /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
  205392. #define STMT_COLUMN_NSORT 5 /* SQLITE_STMTSTATUS_SORT */
  205393. #define STMT_COLUMN_NAIDX 6 /* SQLITE_STMTSTATUS_AUTOINDEX */
  205394. #define STMT_COLUMN_NSTEP 7 /* SQLITE_STMTSTATUS_VM_STEP */
  205395. #define STMT_COLUMN_REPREP 8 /* SQLITE_STMTSTATUS_REPREPARE */
  205396. #define STMT_COLUMN_RUN 9 /* SQLITE_STMTSTATUS_RUN */
  205397. #define STMT_COLUMN_MEM 10 /* SQLITE_STMTSTATUS_MEMUSED */
  205398. rc = sqlite3_declare_vtab(db,
  205399. "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
  205400. "reprep,run,mem)");
  205401. if( rc==SQLITE_OK ){
  205402. pNew = sqlite3_malloc( sizeof(*pNew) );
  205403. *ppVtab = (sqlite3_vtab*)pNew;
  205404. if( pNew==0 ) return SQLITE_NOMEM;
  205405. memset(pNew, 0, sizeof(*pNew));
  205406. pNew->db = db;
  205407. }
  205408. return rc;
  205409. }
  205410. /*
  205411. ** This method is the destructor for stmt_cursor objects.
  205412. */
  205413. static int stmtDisconnect(sqlite3_vtab *pVtab){
  205414. sqlite3_free(pVtab);
  205415. return SQLITE_OK;
  205416. }
  205417. /*
  205418. ** Constructor for a new stmt_cursor object.
  205419. */
  205420. static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  205421. stmt_cursor *pCur;
  205422. pCur = sqlite3_malloc( sizeof(*pCur) );
  205423. if( pCur==0 ) return SQLITE_NOMEM;
  205424. memset(pCur, 0, sizeof(*pCur));
  205425. pCur->db = ((stmt_vtab*)p)->db;
  205426. *ppCursor = &pCur->base;
  205427. return SQLITE_OK;
  205428. }
  205429. /*
  205430. ** Destructor for a stmt_cursor.
  205431. */
  205432. static int stmtClose(sqlite3_vtab_cursor *cur){
  205433. sqlite3_free(cur);
  205434. return SQLITE_OK;
  205435. }
  205436. /*
  205437. ** Advance a stmt_cursor to its next row of output.
  205438. */
  205439. static int stmtNext(sqlite3_vtab_cursor *cur){
  205440. stmt_cursor *pCur = (stmt_cursor*)cur;
  205441. pCur->iRowid++;
  205442. pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
  205443. return SQLITE_OK;
  205444. }
  205445. /*
  205446. ** Return values of columns for the row at which the stmt_cursor
  205447. ** is currently pointing.
  205448. */
  205449. static int stmtColumn(
  205450. sqlite3_vtab_cursor *cur, /* The cursor */
  205451. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  205452. int i /* Which column to return */
  205453. ){
  205454. stmt_cursor *pCur = (stmt_cursor*)cur;
  205455. switch( i ){
  205456. case STMT_COLUMN_SQL: {
  205457. sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
  205458. break;
  205459. }
  205460. case STMT_COLUMN_NCOL: {
  205461. sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
  205462. break;
  205463. }
  205464. case STMT_COLUMN_RO: {
  205465. sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
  205466. break;
  205467. }
  205468. case STMT_COLUMN_BUSY: {
  205469. sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
  205470. break;
  205471. }
  205472. case STMT_COLUMN_MEM: {
  205473. i = SQLITE_STMTSTATUS_MEMUSED +
  205474. STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
  205475. /* Fall thru */
  205476. }
  205477. case STMT_COLUMN_NSCAN:
  205478. case STMT_COLUMN_NSORT:
  205479. case STMT_COLUMN_NAIDX:
  205480. case STMT_COLUMN_NSTEP:
  205481. case STMT_COLUMN_REPREP:
  205482. case STMT_COLUMN_RUN: {
  205483. sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
  205484. i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
  205485. break;
  205486. }
  205487. }
  205488. return SQLITE_OK;
  205489. }
  205490. /*
  205491. ** Return the rowid for the current row. In this implementation, the
  205492. ** rowid is the same as the output value.
  205493. */
  205494. static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  205495. stmt_cursor *pCur = (stmt_cursor*)cur;
  205496. *pRowid = pCur->iRowid;
  205497. return SQLITE_OK;
  205498. }
  205499. /*
  205500. ** Return TRUE if the cursor has been moved off of the last
  205501. ** row of output.
  205502. */
  205503. static int stmtEof(sqlite3_vtab_cursor *cur){
  205504. stmt_cursor *pCur = (stmt_cursor*)cur;
  205505. return pCur->pStmt==0;
  205506. }
  205507. /*
  205508. ** This method is called to "rewind" the stmt_cursor object back
  205509. ** to the first row of output. This method is always called at least
  205510. ** once prior to any call to stmtColumn() or stmtRowid() or
  205511. ** stmtEof().
  205512. */
  205513. static int stmtFilter(
  205514. sqlite3_vtab_cursor *pVtabCursor,
  205515. int idxNum, const char *idxStr,
  205516. int argc, sqlite3_value **argv
  205517. ){
  205518. stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
  205519. pCur->pStmt = 0;
  205520. pCur->iRowid = 0;
  205521. return stmtNext(pVtabCursor);
  205522. }
  205523. /*
  205524. ** SQLite will invoke this method one or more times while planning a query
  205525. ** that uses the stmt virtual table. This routine needs to create
  205526. ** a query plan for each invocation and compute an estimated cost for that
  205527. ** plan.
  205528. */
  205529. static int stmtBestIndex(
  205530. sqlite3_vtab *tab,
  205531. sqlite3_index_info *pIdxInfo
  205532. ){
  205533. pIdxInfo->estimatedCost = (double)500;
  205534. pIdxInfo->estimatedRows = 500;
  205535. return SQLITE_OK;
  205536. }
  205537. /*
  205538. ** This following structure defines all the methods for the
  205539. ** stmt virtual table.
  205540. */
  205541. static sqlite3_module stmtModule = {
  205542. 0, /* iVersion */
  205543. 0, /* xCreate */
  205544. stmtConnect, /* xConnect */
  205545. stmtBestIndex, /* xBestIndex */
  205546. stmtDisconnect, /* xDisconnect */
  205547. 0, /* xDestroy */
  205548. stmtOpen, /* xOpen - open a cursor */
  205549. stmtClose, /* xClose - close a cursor */
  205550. stmtFilter, /* xFilter - configure scan constraints */
  205551. stmtNext, /* xNext - advance a cursor */
  205552. stmtEof, /* xEof - check for end of scan */
  205553. stmtColumn, /* xColumn - read data */
  205554. stmtRowid, /* xRowid - read data */
  205555. 0, /* xUpdate */
  205556. 0, /* xBegin */
  205557. 0, /* xSync */
  205558. 0, /* xCommit */
  205559. 0, /* xRollback */
  205560. 0, /* xFindMethod */
  205561. 0, /* xRename */
  205562. 0, /* xSavepoint */
  205563. 0, /* xRelease */
  205564. 0, /* xRollbackTo */
  205565. 0, /* xShadowName */
  205566. };
  205567. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  205568. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
  205569. int rc = SQLITE_OK;
  205570. #ifndef SQLITE_OMIT_VIRTUALTABLE
  205571. rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
  205572. #endif
  205573. return rc;
  205574. }
  205575. #ifndef SQLITE_CORE
  205576. #ifdef _WIN32
  205577. __declspec(dllexport)
  205578. #endif
  205579. SQLITE_API int sqlite3_stmt_init(
  205580. sqlite3 *db,
  205581. char **pzErrMsg,
  205582. const sqlite3_api_routines *pApi
  205583. ){
  205584. int rc = SQLITE_OK;
  205585. SQLITE_EXTENSION_INIT2(pApi);
  205586. #ifndef SQLITE_OMIT_VIRTUALTABLE
  205587. rc = sqlite3StmtVtabInit(db);
  205588. #endif
  205589. return rc;
  205590. }
  205591. #endif /* SQLITE_CORE */
  205592. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
  205593. /************** End of stmt.c ************************************************/
  205594. #if __LINE__!=220527
  205595. #undef SQLITE_SOURCE_ID
  205596. #define SQLITE_SOURCE_ID "2018-12-01 12:34:55 bf8c1b2b7a5960c282e543b9c293686dccff272512d08865f4600fb58238alt2"
  205597. #endif
  205598. /* Return the source-id for this library */
  205599. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  205600. /************************** End of sqlite3.c ******************************/